trooth 0.1.0__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.
- trooth/__init__.py +14 -0
- trooth/integrations/__init__.py +16 -0
- trooth/integrations/langchain.py +33 -0
- trooth/integrations/llama_index.py +34 -0
- trooth/integrations/openai_agents.py +44 -0
- trooth-0.1.0.dist-info/METADATA +88 -0
- trooth-0.1.0.dist-info/RECORD +20 -0
- trooth-0.1.0.dist-info/WHEEL +5 -0
- trooth-0.1.0.dist-info/entry_points.txt +2 -0
- trooth-0.1.0.dist-info/licenses/LICENSE +70 -0
- trooth-0.1.0.dist-info/top_level.txt +2 -0
- trooth_semanto_verify/__init__.py +94 -0
- trooth_semanto_verify/__main__.py +8 -0
- trooth_semanto_verify/canonical.py +88 -0
- trooth_semanto_verify/cli.py +246 -0
- trooth_semanto_verify/client.py +127 -0
- trooth_semanto_verify/httpsig.py +217 -0
- trooth_semanto_verify/jws.py +255 -0
- trooth_semanto_verify/merkle.py +110 -0
- trooth_semanto_verify/verify.py +541 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright (c) 2026 Trooth, LLC
|
|
3
|
+
#
|
|
4
|
+
# Ed25519 keys as JWKs (RFC 8037, RFC 7638 thumbprints as key ids) and JWS
|
|
5
|
+
# compact serialization (RFC 7515) over RFC 8785 canonical payloads, as the
|
|
6
|
+
# Semanto file, the witness statement, tree heads, offers and revocation lists
|
|
7
|
+
# use. Ed25519 itself comes from the `cryptography` package.
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import json
|
|
13
|
+
import hashlib
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from typing import Any, Callable, Iterable, Optional
|
|
16
|
+
|
|
17
|
+
from cryptography.exceptions import InvalidSignature
|
|
18
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
19
|
+
|
|
20
|
+
from .canonical import canonical_bytes
|
|
21
|
+
|
|
22
|
+
JWS_TYPES = {
|
|
23
|
+
"semantoVersion": "https://trooth.co/types/semanto-version",
|
|
24
|
+
"witness": "https://trooth.co/types/witness-statement",
|
|
25
|
+
"receipt": "https://trooth.co/types/coverage-receipt",
|
|
26
|
+
"treeHead": "https://trooth.co/types/signed-tree-head",
|
|
27
|
+
"offer": "https://trooth.co/types/signed-offer",
|
|
28
|
+
"productRecord": "https://trooth.co/types/product-record",
|
|
29
|
+
"sellerAttestation": "https://trooth.co/types/seller-attestation",
|
|
30
|
+
"recall": "https://trooth.co/types/recall-notice",
|
|
31
|
+
"marketplaceCatalog": "https://trooth.co/types/marketplace-catalog",
|
|
32
|
+
"firstPublication": "https://trooth.co/types/first-publication",
|
|
33
|
+
"readReceipt": "https://trooth.co/types/read-receipt",
|
|
34
|
+
"revocation": "https://trooth.co/types/revocation-list",
|
|
35
|
+
"contentSignals": "https://trooth.co/types/content-signals",
|
|
36
|
+
"sellerList": "https://trooth.co/types/seller-list",
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def b64url_decode(s: str) -> bytes:
|
|
41
|
+
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def b64url_encode(b: bytes) -> str:
|
|
45
|
+
return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def parse_time(value: str) -> datetime:
|
|
49
|
+
"""ISO 8601 UTC, with or without fractional seconds, Z or +00:00."""
|
|
50
|
+
v = value.strip()
|
|
51
|
+
if v.endswith("Z"):
|
|
52
|
+
v = v[:-1] + "+00:00"
|
|
53
|
+
dt = datetime.fromisoformat(v)
|
|
54
|
+
if dt.tzinfo is None:
|
|
55
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
56
|
+
return dt
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def thumbprint(jwk: dict) -> str:
|
|
60
|
+
"""RFC 7638: SHA-256 of the canonical required members."""
|
|
61
|
+
required = {"crv": jwk["crv"], "kty": jwk["kty"], "x": jwk["x"]}
|
|
62
|
+
return b64url_encode(hashlib.sha256(canonical_bytes(required)).digest())
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def ed25519_verify(jwk: dict, signature: bytes, data: bytes) -> bool:
|
|
66
|
+
try:
|
|
67
|
+
Ed25519PublicKey.from_public_bytes(b64url_decode(jwk["x"])).verify(signature, data)
|
|
68
|
+
return True
|
|
69
|
+
except (InvalidSignature, ValueError, KeyError):
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _instant(value: Any) -> Any:
|
|
74
|
+
"""None when absent, a datetime when it parses, the string "bad" otherwise."""
|
|
75
|
+
if value is None:
|
|
76
|
+
return None
|
|
77
|
+
if not isinstance(value, str):
|
|
78
|
+
return "bad"
|
|
79
|
+
try:
|
|
80
|
+
return parse_time(value)
|
|
81
|
+
except (ValueError, TypeError):
|
|
82
|
+
return "bad"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def key_valid_at_signing(jwk: dict, iat: datetime) -> dict:
|
|
86
|
+
"""Key validity when the statement was signed (iat), not when it is checked.
|
|
87
|
+
|
|
88
|
+
A key valid at iat verifies after rotation. A key revoked at or before iat
|
|
89
|
+
fails. A key revoked after iat verifies with the note "key revoked after
|
|
90
|
+
signing on <date>". Revocation for compromise backdates revoked_at to the
|
|
91
|
+
compromise, which invalidates every later signature.
|
|
92
|
+
"""
|
|
93
|
+
nbf, exp, rev = _instant(jwk.get("nbf")), _instant(jwk.get("exp")), _instant(jwk.get("revoked_at"))
|
|
94
|
+
if "bad" in (nbf, exp, rev):
|
|
95
|
+
return {"ok": False, "reason": "malformed"}
|
|
96
|
+
if nbf is not None and iat < nbf:
|
|
97
|
+
return {"ok": False, "reason": "key_not_yet_valid"}
|
|
98
|
+
if exp is not None and iat >= exp:
|
|
99
|
+
return {"ok": False, "reason": "key_expired"}
|
|
100
|
+
if rev is not None and iat >= rev:
|
|
101
|
+
return {"ok": False, "reason": "key_revoked"}
|
|
102
|
+
return {"ok": True, "notes": [f"key revoked after signing on {jwk['revoked_at']}"] if rev is not None else []}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def key_valid_at(jwk: dict, at: datetime) -> Optional[str]:
|
|
106
|
+
"""None when the key may be used at `at`, else a reason code."""
|
|
107
|
+
if jwk.get("nbf") and at < parse_time(jwk["nbf"]):
|
|
108
|
+
return "key_not_yet_valid"
|
|
109
|
+
if jwk.get("exp") and at >= parse_time(jwk["exp"]):
|
|
110
|
+
return "key_expired"
|
|
111
|
+
if jwk.get("revoked_at") and at >= parse_time(jwk["revoked_at"]):
|
|
112
|
+
return "key_revoked"
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _collect(keys: Any, out: list) -> None:
|
|
117
|
+
if keys is None:
|
|
118
|
+
return
|
|
119
|
+
if isinstance(keys, list):
|
|
120
|
+
for k in keys:
|
|
121
|
+
_collect(k, out)
|
|
122
|
+
return
|
|
123
|
+
if isinstance(keys, dict):
|
|
124
|
+
if isinstance(keys.get("keys"), list):
|
|
125
|
+
out.extend(j for j in keys["keys"] if isinstance(j, dict))
|
|
126
|
+
return
|
|
127
|
+
if "jwks" in keys:
|
|
128
|
+
_collect(keys["jwks"], out)
|
|
129
|
+
return
|
|
130
|
+
if keys.get("kty") == "OKP":
|
|
131
|
+
out.append(keys)
|
|
132
|
+
return
|
|
133
|
+
for v in keys.values():
|
|
134
|
+
_collect(v, out)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _resolver_of(all_keys: list) -> Callable[[str], Optional[dict]]:
|
|
138
|
+
def resolve(kid: str) -> Optional[dict]:
|
|
139
|
+
for j in all_keys:
|
|
140
|
+
if j.get("kid") == kid and j.get("kty") == "OKP" and j.get("crv") == "Ed25519":
|
|
141
|
+
return j
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
return resolve
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def key_resolver(keys: Any) -> Callable[[str], Optional[dict]]:
|
|
148
|
+
"""Every key in any shape, whatever its role. The top-level checks use role_resolver instead."""
|
|
149
|
+
all_keys: list = []
|
|
150
|
+
_collect(keys, all_keys)
|
|
151
|
+
return _resolver_of(all_keys)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
ROLE_NAMES = ("company", "trooth", "agent")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def has_roles(keys: Any) -> bool:
|
|
158
|
+
"""True when keys names its sets by role ({"company", "trooth", "agent"}, the keys.json vector shape)."""
|
|
159
|
+
return isinstance(keys, dict) and any(r in keys for r in ROLE_NAMES)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def role_keys(keys: Any, role: str) -> list:
|
|
163
|
+
"""The keys for one role. Role-shaped input gives only that role's set; a plain set is used as given for a one-role check."""
|
|
164
|
+
out: list = []
|
|
165
|
+
_collect(keys.get(role) if has_roles(keys) else keys, out)
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def role_resolver(keys: Any, role: str) -> Callable[[str], Optional[dict]]:
|
|
170
|
+
return _resolver_of(role_keys(keys, role))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def strict_role_resolver(keys: Any, role: str) -> Callable[[str], Optional[dict]]:
|
|
174
|
+
"""For checks of two roles at once: a plain set is the company's, and Trooth's is then empty."""
|
|
175
|
+
if has_roles(keys):
|
|
176
|
+
return role_resolver(keys, role)
|
|
177
|
+
if role == "company":
|
|
178
|
+
return key_resolver(keys)
|
|
179
|
+
return lambda kid: None
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def parse_dns_key_records(txt: Iterable[str]) -> list:
|
|
183
|
+
import re
|
|
184
|
+
|
|
185
|
+
out = []
|
|
186
|
+
for t in txt:
|
|
187
|
+
m = re.match(r'^v=trooth1;\s*kid=([A-Za-z0-9_-]{43})$', str(t).strip().strip('"'))
|
|
188
|
+
if m:
|
|
189
|
+
out.append(m.group(1))
|
|
190
|
+
return out
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def verify_jws(jws: str, resolve_key: Callable[[str], Optional[dict]], expect_typ: Optional[str] = None, payload: Any = None, at: Optional[datetime] = None) -> dict:
|
|
194
|
+
"""Verify a compact (h.p.s) or detached (h..s) JWS. Returns a dict with "ok" and either "reason" or "header", "payload" and "notes".
|
|
195
|
+
|
|
196
|
+
When the caller passes the payload it expects, the JWS payload segment must
|
|
197
|
+
be empty or byte-equal to base64url(canonical(payload)); anything else is
|
|
198
|
+
"payload_mismatch". Without it, the embedded payload is returned and the
|
|
199
|
+
caller compares it. The key is judged at the statement's iat; nbf and exp
|
|
200
|
+
at `at`. A header that is not a JSON object, or whose iat, nbf or exp does
|
|
201
|
+
not parse, is malformed.
|
|
202
|
+
"""
|
|
203
|
+
if not isinstance(jws, str):
|
|
204
|
+
return {"ok": False, "reason": "malformed"}
|
|
205
|
+
parts = jws.split(".")
|
|
206
|
+
if len(parts) != 3:
|
|
207
|
+
return {"ok": False, "reason": "malformed"}
|
|
208
|
+
h, p_given, s = parts
|
|
209
|
+
try:
|
|
210
|
+
header = json.loads(b64url_decode(h))
|
|
211
|
+
except Exception:
|
|
212
|
+
return {"ok": False, "reason": "malformed"}
|
|
213
|
+
if not isinstance(header, dict):
|
|
214
|
+
return {"ok": False, "reason": "malformed"}
|
|
215
|
+
if header.get("alg") != "EdDSA" or not isinstance(header.get("kid"), str):
|
|
216
|
+
return {"ok": False, "reason": "malformed"}
|
|
217
|
+
if expect_typ and header.get("typ") != expect_typ:
|
|
218
|
+
return {"ok": False, "reason": "wrong_type"}
|
|
219
|
+
iat, nbf, exp = _instant(header.get("iat")), _instant(header.get("nbf")), _instant(header.get("exp"))
|
|
220
|
+
if "bad" in (iat, nbf, exp):
|
|
221
|
+
return {"ok": False, "reason": "malformed"}
|
|
222
|
+
if payload is not None:
|
|
223
|
+
try:
|
|
224
|
+
expected = b64url_encode(canonical_bytes(payload))
|
|
225
|
+
except Exception:
|
|
226
|
+
return {"ok": False, "reason": "malformed"}
|
|
227
|
+
if p_given != "" and p_given != expected:
|
|
228
|
+
return {"ok": False, "reason": "payload_mismatch"}
|
|
229
|
+
p = expected
|
|
230
|
+
elif p_given != "":
|
|
231
|
+
p = p_given
|
|
232
|
+
else:
|
|
233
|
+
return {"ok": False, "reason": "malformed"}
|
|
234
|
+
jwk = resolve_key(header["kid"])
|
|
235
|
+
if jwk is None:
|
|
236
|
+
return {"ok": False, "reason": "unknown_key"}
|
|
237
|
+
try:
|
|
238
|
+
sig = b64url_decode(s)
|
|
239
|
+
except Exception:
|
|
240
|
+
return {"ok": False, "reason": "malformed"}
|
|
241
|
+
if not ed25519_verify(jwk, sig, f"{h}.{p}".encode("ascii")):
|
|
242
|
+
return {"ok": False, "reason": "bad_signature"}
|
|
243
|
+
at = at or datetime.now(timezone.utc)
|
|
244
|
+
kv = key_valid_at_signing(jwk, iat if iat is not None else at)
|
|
245
|
+
if not kv["ok"]:
|
|
246
|
+
return {"ok": False, "reason": kv["reason"]}
|
|
247
|
+
if nbf is not None and at < nbf:
|
|
248
|
+
return {"ok": False, "reason": "not_yet_valid"}
|
|
249
|
+
if exp is not None and at >= exp:
|
|
250
|
+
return {"ok": False, "reason": "expired"}
|
|
251
|
+
try:
|
|
252
|
+
body = json.loads(b64url_decode(p))
|
|
253
|
+
except Exception:
|
|
254
|
+
return {"ok": False, "reason": "malformed"}
|
|
255
|
+
return {"ok": True, "header": header, "payload": body, "notes": kv["notes"]}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# Copyright (c) 2026 Trooth, LLC
|
|
3
|
+
#
|
|
4
|
+
# RFC 6962 (Certificate Transparency) Merkle hashing: leaf hash SHA-256(0x00 ||
|
|
5
|
+
# data), node hash SHA-256(0x01 || left || right), with the inclusion proof
|
|
6
|
+
# check of section 2.1.3 and the consistency proof check of section 2.1.4.2.
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import re
|
|
12
|
+
from typing import Sequence
|
|
13
|
+
|
|
14
|
+
DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def sha256(data: bytes) -> bytes:
|
|
18
|
+
return hashlib.sha256(data).digest()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def digest(data: bytes) -> str:
|
|
22
|
+
"""The printed form every Semanto digest uses: sha256: plus 64 lowercase hex."""
|
|
23
|
+
return "sha256:" + hashlib.sha256(data).hexdigest()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def is_digest(value: object) -> bool:
|
|
27
|
+
return isinstance(value, str) and DIGEST_RE.match(value) is not None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def digest_bytes(d: str) -> bytes:
|
|
31
|
+
if not is_digest(d):
|
|
32
|
+
raise ValueError(f'expected "sha256:<64 hex>", got {d!r}')
|
|
33
|
+
return bytes.fromhex(d[7:])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def leaf_hash(data: bytes) -> bytes:
|
|
37
|
+
return sha256(b"\x00" + data)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def node_hash(left: bytes, right: bytes) -> bytes:
|
|
41
|
+
return sha256(b"\x01" + left + right)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _largest_power_of_two_below(n: int) -> int:
|
|
45
|
+
k = 1
|
|
46
|
+
while k * 2 < n:
|
|
47
|
+
k *= 2
|
|
48
|
+
return k
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def root_from_leaf_hashes(leaves: Sequence[bytes]) -> bytes:
|
|
52
|
+
if len(leaves) == 0:
|
|
53
|
+
return sha256(b"")
|
|
54
|
+
if len(leaves) == 1:
|
|
55
|
+
return leaves[0]
|
|
56
|
+
k = _largest_power_of_two_below(len(leaves))
|
|
57
|
+
return node_hash(root_from_leaf_hashes(leaves[:k]), root_from_leaf_hashes(leaves[k:]))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def verify_inclusion(leaf: bytes, index: int, size: int, proof: Sequence[bytes], expected_root: bytes) -> bool:
|
|
61
|
+
"""RFC 6962 2.1.3: recompute the root from a leaf hash and its audit path."""
|
|
62
|
+
if index < 0 or index >= size:
|
|
63
|
+
return False
|
|
64
|
+
fn, sn, r = index, size - 1, leaf
|
|
65
|
+
for p in proof:
|
|
66
|
+
if sn == 0:
|
|
67
|
+
return False
|
|
68
|
+
if fn % 2 == 1 or fn == sn:
|
|
69
|
+
r = node_hash(p, r)
|
|
70
|
+
while not (fn % 2 == 1 or fn == 0):
|
|
71
|
+
fn >>= 1
|
|
72
|
+
sn >>= 1
|
|
73
|
+
else:
|
|
74
|
+
r = node_hash(r, p)
|
|
75
|
+
fn >>= 1
|
|
76
|
+
sn >>= 1
|
|
77
|
+
return sn == 0 and r == expected_root
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def verify_consistency(old_size: int, new_size: int, old_root: bytes, new_root: bytes, proof: Sequence[bytes]) -> bool:
|
|
81
|
+
"""RFC 6962 2.1.4.2: the old tree is a prefix of the new tree."""
|
|
82
|
+
if old_size > new_size:
|
|
83
|
+
return False
|
|
84
|
+
if old_size == new_size:
|
|
85
|
+
return len(proof) == 0 and old_root == new_root
|
|
86
|
+
if old_size == 0:
|
|
87
|
+
return len(proof) == 0
|
|
88
|
+
is_pow2 = (old_size & (old_size - 1)) == 0
|
|
89
|
+
p = ([old_root] + list(proof)) if is_pow2 else list(proof)
|
|
90
|
+
if not p:
|
|
91
|
+
return False
|
|
92
|
+
fn, sn = old_size - 1, new_size - 1
|
|
93
|
+
while fn % 2 == 1:
|
|
94
|
+
fn >>= 1
|
|
95
|
+
sn >>= 1
|
|
96
|
+
fr = sr = p[0]
|
|
97
|
+
for c in p[1:]:
|
|
98
|
+
if sn == 0:
|
|
99
|
+
return False
|
|
100
|
+
if fn % 2 == 1 or fn == sn:
|
|
101
|
+
fr = node_hash(c, fr)
|
|
102
|
+
sr = node_hash(c, sr)
|
|
103
|
+
while not (fn % 2 == 1 or fn == 0):
|
|
104
|
+
fn >>= 1
|
|
105
|
+
sn >>= 1
|
|
106
|
+
else:
|
|
107
|
+
sr = node_hash(sr, c)
|
|
108
|
+
fn >>= 1
|
|
109
|
+
sn >>= 1
|
|
110
|
+
return sn == 0 and fr == old_root and sr == new_root
|