tenthlook-core 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.
- tenthlook_core/__init__.py +2 -0
- tenthlook_core/cli.py +73 -0
- tenthlook_core/crypto.py +200 -0
- tenthlook_core/receipt.py +124 -0
- tenthlook_core/store.py +176 -0
- tenthlook_core-0.1.0.dist-info/METADATA +67 -0
- tenthlook_core-0.1.0.dist-info/RECORD +11 -0
- tenthlook_core-0.1.0.dist-info/WHEEL +5 -0
- tenthlook_core-0.1.0.dist-info/entry_points.txt +2 -0
- tenthlook_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- tenthlook_core-0.1.0.dist-info/top_level.txt +1 -0
tenthlook_core/cli.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""`tenthlook` command line. Nothing here touches the network."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import crypto, receipt, store
|
|
10
|
+
|
|
11
|
+
DEFAULT_KEY = Path("~/.config/tenthlook/signing.key")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _pub(a) -> str | None:
|
|
15
|
+
if getattr(a, "pubkey_file", None):
|
|
16
|
+
return Path(a.pubkey_file).read_text().strip()
|
|
17
|
+
return getattr(a, "pubkey", None)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def main(argv: list[str] | None = None) -> int:
|
|
21
|
+
ap = argparse.ArgumentParser(prog="tenthlook", description="Signed, hash-chained receipts. Offline.")
|
|
22
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
23
|
+
k = sub.add_parser("keygen", help="create a signing key file (0600, outside any repo, never overwritten)")
|
|
24
|
+
k.add_argument("--out", default=str(DEFAULT_KEY))
|
|
25
|
+
v = sub.add_parser("verify-receipt", help="verify one receipt file")
|
|
26
|
+
v.add_argument("file")
|
|
27
|
+
c = sub.add_parser("verify-chain", help="verify a receipt database")
|
|
28
|
+
c.add_argument("db")
|
|
29
|
+
c.add_argument("--expect-head", help="head hash you recorded elsewhere (detects removal of the newest receipts)")
|
|
30
|
+
c.add_argument("--expect-count", type=int)
|
|
31
|
+
for p in (v, c):
|
|
32
|
+
p.add_argument("--pubkey", help="pin the signer's public key (base64)")
|
|
33
|
+
p.add_argument("--pubkey-file")
|
|
34
|
+
a = ap.parse_args(argv)
|
|
35
|
+
try:
|
|
36
|
+
if a.cmd == "keygen":
|
|
37
|
+
out = Path(a.out).expanduser()
|
|
38
|
+
pub = crypto.write_new_key_file(out)
|
|
39
|
+
print(f"private key written to {out} (mode 600; back it up, never commit it)\npublic key (give this to verifiers): {pub}")
|
|
40
|
+
return 0
|
|
41
|
+
if a.cmd == "verify-receipt":
|
|
42
|
+
try:
|
|
43
|
+
r = json.loads(Path(a.file).read_text(encoding="utf-8"))
|
|
44
|
+
except (OSError, ValueError) as e:
|
|
45
|
+
print(f"FAIL: cannot read receipt: {e}")
|
|
46
|
+
return 1
|
|
47
|
+
res = receipt.verify(r, _pub(a))
|
|
48
|
+
for m in res.errors:
|
|
49
|
+
print("FAIL:", m)
|
|
50
|
+
if res.ok:
|
|
51
|
+
print(f"OK: {r['verdict']} for {r['subject_type']} {r['artifact_sha256'][:12]}.. under policy {r['policy_sha256'][:12]}.. "
|
|
52
|
+
f"by {r['checker']['name']} {r['checker']['version']} at {r['timestamp_utc']}")
|
|
53
|
+
for m in res.notes:
|
|
54
|
+
print("note:", m)
|
|
55
|
+
print("reminder: a receipt shows what was checked and that it was not altered, not that the action or code is safe")
|
|
56
|
+
return 0 if res.ok else 1
|
|
57
|
+
if a.cmd == "verify-chain":
|
|
58
|
+
res = store.verify_chain(a.db, _pub(a), a.expect_head, a.expect_count)
|
|
59
|
+
for m in res.errors:
|
|
60
|
+
print("FAIL:", m)
|
|
61
|
+
if res.ok:
|
|
62
|
+
print(f"OK: {res.count} receipts, chain intact, head {res.head}")
|
|
63
|
+
for m in res.notes:
|
|
64
|
+
print("note:", m)
|
|
65
|
+
return 0 if res.ok else 1
|
|
66
|
+
except (crypto.KeyRefused, crypto.KeyMissing, FileExistsError) as e:
|
|
67
|
+
print(f"error: {e}", file=sys.stderr)
|
|
68
|
+
return 2
|
|
69
|
+
return 2
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
sys.exit(main())
|
tenthlook_core/crypto.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""Canonical JSON, SHA-256, Ed25519 keys.
|
|
2
|
+
|
|
3
|
+
Canonical JSON
|
|
4
|
+
--------------
|
|
5
|
+
`canonical_json` approximates RFC 8785 (JCS) for the subset of JSON this library signs: objects, arrays, strings,
|
|
6
|
+
booleans, null and *integers*. Where it matches JCS: keys sorted by UTF-16 code unit, no whitespace, minimal string
|
|
7
|
+
escaping, UTF-8 output. Where it differs, on purpose:
|
|
8
|
+
|
|
9
|
+
* Floats are REJECTED (JCS defines ES6 number formatting; reimplementing it identically in every language is the
|
|
10
|
+
classic way signatures stop verifying). Put decimals in strings, money in minor units.
|
|
11
|
+
* Integers outside +/-(2**53-1) are rejected (they do not survive JavaScript).
|
|
12
|
+
* NaN/Infinity are rejected (not JSON).
|
|
13
|
+
* Strings with lone surrogates are rejected (JCS says to reject them too, but Python and JS disagree about
|
|
14
|
+
what they emit).
|
|
15
|
+
* Keys must be strings; duplicate keys cannot occur in a dict.
|
|
16
|
+
|
|
17
|
+
So: anything this accepts is canonical under JCS, but this does NOT accept everything JCS does. A TypeScript port only
|
|
18
|
+
needs sorted keys, `JSON.stringify` for strings/ints, and `undefined` dropped (see the conformance fixtures).
|
|
19
|
+
|
|
20
|
+
Keys
|
|
21
|
+
----
|
|
22
|
+
There are no default keys and no key in any repo. A signing key is a 32-byte Ed25519 seed, base64, read from a file
|
|
23
|
+
(`TENTHLOOK_KEY_FILE` or an explicit path) or, for CI secrets, from `TENTHLOOK_SIGNING_KEY`. If neither is given,
|
|
24
|
+
signing raises `KeyMissing`. Key files must be outside any git work tree and not group/world readable.
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import base64
|
|
29
|
+
import hashlib
|
|
30
|
+
import json
|
|
31
|
+
import os
|
|
32
|
+
import stat
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
KEY_FILE_ENV = "TENTHLOOK_KEY_FILE"
|
|
36
|
+
KEY_ENV = "TENTHLOOK_SIGNING_KEY"
|
|
37
|
+
MAX_SAFE_INT = 2**53 - 1
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class KeyMissing(RuntimeError):
|
|
41
|
+
"""No signing key was provided. There is deliberately no fallback."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class KeyRefused(RuntimeError):
|
|
45
|
+
"""A key file is somewhere it must not be (inside a repo) or is too readable."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------- canonical JSON
|
|
49
|
+
|
|
50
|
+
def _utf16_key(s: str) -> bytes:
|
|
51
|
+
return s.encode("utf-16-be", "surrogatepass")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _enc(v, out: list[str]) -> None:
|
|
55
|
+
if v is None:
|
|
56
|
+
out.append("null")
|
|
57
|
+
elif v is True:
|
|
58
|
+
out.append("true")
|
|
59
|
+
elif v is False:
|
|
60
|
+
out.append("false")
|
|
61
|
+
elif isinstance(v, int):
|
|
62
|
+
if abs(v) > MAX_SAFE_INT:
|
|
63
|
+
raise ValueError(f"integer {v} is outside the safe range")
|
|
64
|
+
out.append(str(v))
|
|
65
|
+
elif isinstance(v, float):
|
|
66
|
+
raise TypeError("floats are not allowed in canonical JSON; use an integer or a string")
|
|
67
|
+
elif isinstance(v, str):
|
|
68
|
+
try:
|
|
69
|
+
v.encode("utf-8")
|
|
70
|
+
except UnicodeEncodeError as e:
|
|
71
|
+
raise ValueError("string contains a lone surrogate") from e
|
|
72
|
+
out.append(json.dumps(v, ensure_ascii=False))
|
|
73
|
+
elif isinstance(v, (list, tuple)):
|
|
74
|
+
out.append("[")
|
|
75
|
+
for i, x in enumerate(v):
|
|
76
|
+
if i:
|
|
77
|
+
out.append(",")
|
|
78
|
+
_enc(x, out)
|
|
79
|
+
out.append("]")
|
|
80
|
+
elif isinstance(v, dict):
|
|
81
|
+
for k in v:
|
|
82
|
+
if not isinstance(k, str):
|
|
83
|
+
raise TypeError("object keys must be strings")
|
|
84
|
+
out.append("{")
|
|
85
|
+
for i, k in enumerate(sorted(v, key=_utf16_key)):
|
|
86
|
+
if i:
|
|
87
|
+
out.append(",")
|
|
88
|
+
_enc(k, out)
|
|
89
|
+
out.append(":")
|
|
90
|
+
_enc(v[k], out)
|
|
91
|
+
out.append("}")
|
|
92
|
+
else:
|
|
93
|
+
raise TypeError(f"cannot canonicalize {type(v).__name__}")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def canonical_json(obj) -> bytes:
|
|
97
|
+
out: list[str] = []
|
|
98
|
+
_enc(obj, out)
|
|
99
|
+
return "".join(out).encode("utf-8")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def sha256_hex(data: bytes | str) -> str:
|
|
103
|
+
return hashlib.sha256(data.encode("utf-8") if isinstance(data, str) else data).hexdigest()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def hash_json(obj) -> str:
|
|
107
|
+
return sha256_hex(canonical_json(obj))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ---------------------------------------------------------------- keys
|
|
111
|
+
|
|
112
|
+
def _lib():
|
|
113
|
+
from cryptography.exceptions import InvalidSignature
|
|
114
|
+
from cryptography.hazmat.primitives import serialization
|
|
115
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
|
116
|
+
return InvalidSignature, serialization, Ed25519PrivateKey, Ed25519PublicKey
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _b64(b: bytes) -> str:
|
|
120
|
+
return base64.b64encode(b).decode("ascii")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def generate_keypair() -> tuple[str, str]:
|
|
124
|
+
"""(private seed b64, public key b64). Nothing is written anywhere."""
|
|
125
|
+
_, ser, Priv, _ = _lib()
|
|
126
|
+
k = Priv.generate()
|
|
127
|
+
return (_b64(k.private_bytes(ser.Encoding.Raw, ser.PrivateFormat.Raw, ser.NoEncryption())),
|
|
128
|
+
_b64(k.public_key().public_bytes(ser.Encoding.Raw, ser.PublicFormat.Raw)))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def public_from_private(seed_b64: str) -> str:
|
|
132
|
+
_, ser, Priv, _ = _lib()
|
|
133
|
+
k = Priv.from_private_bytes(base64.b64decode(seed_b64, validate=True))
|
|
134
|
+
return _b64(k.public_key().public_bytes(ser.Encoding.Raw, ser.PublicFormat.Raw))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def inside_git_worktree(path: Path) -> bool:
|
|
138
|
+
p = path.resolve()
|
|
139
|
+
for d in [p, *p.parents]:
|
|
140
|
+
if (d / ".git").exists():
|
|
141
|
+
return True
|
|
142
|
+
return False
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def check_key_path(path: Path) -> None:
|
|
146
|
+
if inside_git_worktree(path.parent if not path.is_dir() else path):
|
|
147
|
+
raise KeyRefused(f"{path} is inside a git work tree; keys must be stored outside repositories")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def write_new_key_file(path: Path, force: bool = False, pub_file: bool = False) -> str:
|
|
151
|
+
"""Create a key file (0600; refuses to overwrite unless force=True). Returns the public key; with pub_file also
|
|
152
|
+
writes it to `<path>.pub` (public, safe to share)."""
|
|
153
|
+
path = Path(path).expanduser()
|
|
154
|
+
check_key_path(path)
|
|
155
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
156
|
+
if force and path.exists():
|
|
157
|
+
path.unlink()
|
|
158
|
+
priv, pub = generate_keypair()
|
|
159
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) # O_EXCL: refuse to overwrite
|
|
160
|
+
with os.fdopen(fd, "w") as f:
|
|
161
|
+
f.write(priv + "\n")
|
|
162
|
+
if pub_file:
|
|
163
|
+
Path(str(path) + ".pub").write_text(pub + "\n")
|
|
164
|
+
return pub
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def load_signing_key(key_file: str | os.PathLike | None = None) -> str:
|
|
168
|
+
"""Return the private seed (b64). Order: explicit path, TENTHLOOK_KEY_FILE, TENTHLOOK_SIGNING_KEY. Else KeyMissing."""
|
|
169
|
+
path = key_file or os.environ.get(KEY_FILE_ENV)
|
|
170
|
+
if path:
|
|
171
|
+
p = Path(path).expanduser()
|
|
172
|
+
if not p.is_file():
|
|
173
|
+
raise KeyMissing(f"key file {p} does not exist")
|
|
174
|
+
check_key_path(p)
|
|
175
|
+
if p.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
|
|
176
|
+
raise KeyRefused(f"{p} is readable by group/others; run: chmod 600 {p}")
|
|
177
|
+
seed = p.read_text().strip()
|
|
178
|
+
else:
|
|
179
|
+
seed = (os.environ.get(KEY_ENV) or "").strip()
|
|
180
|
+
if not seed:
|
|
181
|
+
raise KeyMissing(f"no signing key: pass a key file or set {KEY_FILE_ENV} (or {KEY_ENV} in CI). There is no default key.")
|
|
182
|
+
try:
|
|
183
|
+
public_from_private(seed)
|
|
184
|
+
except Exception as e:
|
|
185
|
+
raise KeyMissing("signing key is not a base64 32-byte Ed25519 seed") from e
|
|
186
|
+
return seed
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def sign_bytes(seed_b64: str, data: bytes) -> str:
|
|
190
|
+
_, _, Priv, _ = _lib()
|
|
191
|
+
return _b64(Priv.from_private_bytes(base64.b64decode(seed_b64, validate=True)).sign(data))
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def verify_bytes(pub_b64: str, sig_b64: str, data: bytes) -> bool:
|
|
195
|
+
InvalidSignature, _, _, Pub = _lib()
|
|
196
|
+
try:
|
|
197
|
+
Pub.from_public_bytes(base64.b64decode(pub_b64, validate=True)).verify(base64.b64decode(sig_b64, validate=True), data)
|
|
198
|
+
return True
|
|
199
|
+
except (InvalidSignature, ValueError):
|
|
200
|
+
return False
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""The receipt: one signed statement that a named checker, with a hashed policy, reached a verdict on a hashed artifact.
|
|
2
|
+
|
|
3
|
+
It proves who signed what and that it was not altered afterwards. It does not prove the artifact is safe or correct.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import datetime as _dt
|
|
8
|
+
import re
|
|
9
|
+
import uuid
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from . import crypto
|
|
13
|
+
|
|
14
|
+
VERSION = 1
|
|
15
|
+
GENESIS = "0" * 64
|
|
16
|
+
SUBJECT_TYPES = ("mcp_tool_call", "git_diff", "sql_query")
|
|
17
|
+
VERDICTS = ("ALLOWED", "BLOCKED", "NEEDS_CONSENT", "Z3_VERIFIED", "Z3_COUNTEREXAMPLE", "NOT_CHECKABLE")
|
|
18
|
+
FIELDS = ("version", "receipt_id", "timestamp_utc", "subject_type", "artifact_sha256", "policy_sha256", "checker",
|
|
19
|
+
"verdict", "reasons", "trace_sha256", "prev_receipt_sha256", "pubkey", "signature")
|
|
20
|
+
_HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
|
21
|
+
_TS = re.compile(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z$")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ReceiptError(ValueError):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def now_utc() -> str:
|
|
29
|
+
return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def validate_shape(r: dict) -> list[str]:
|
|
33
|
+
"""Schema problems (empty list = well-formed). Does not check the signature."""
|
|
34
|
+
e: list[str] = []
|
|
35
|
+
if not isinstance(r, dict):
|
|
36
|
+
return ["receipt is not an object"]
|
|
37
|
+
for k in sorted(set(r) - set(FIELDS)):
|
|
38
|
+
e.append(f"unknown field {k!r}")
|
|
39
|
+
for k in FIELDS:
|
|
40
|
+
if k not in r:
|
|
41
|
+
e.append(f"missing field {k!r}")
|
|
42
|
+
if e:
|
|
43
|
+
return e
|
|
44
|
+
if r["version"] != VERSION:
|
|
45
|
+
e.append(f"unsupported version {r['version']!r}")
|
|
46
|
+
if not isinstance(r["receipt_id"], str) or not r["receipt_id"]:
|
|
47
|
+
e.append("receipt_id must be a non-empty string")
|
|
48
|
+
if not isinstance(r["timestamp_utc"], str) or not _TS.match(r["timestamp_utc"]):
|
|
49
|
+
e.append("timestamp_utc must be ISO-8601 UTC ending in Z")
|
|
50
|
+
if r["subject_type"] not in SUBJECT_TYPES:
|
|
51
|
+
e.append(f"subject_type must be one of {SUBJECT_TYPES}")
|
|
52
|
+
for k in ("artifact_sha256", "policy_sha256", "prev_receipt_sha256"):
|
|
53
|
+
if not (isinstance(r[k], str) and _HEX64.match(r[k])):
|
|
54
|
+
e.append(f"{k} must be 64 lowercase hex characters")
|
|
55
|
+
if r["trace_sha256"] is not None and not (isinstance(r["trace_sha256"], str) and _HEX64.match(r["trace_sha256"])):
|
|
56
|
+
e.append("trace_sha256 must be null or 64 lowercase hex characters")
|
|
57
|
+
c = r["checker"]
|
|
58
|
+
if not (isinstance(c, dict) and set(c) == {"name", "version"} and all(isinstance(v, str) and v for v in c.values())):
|
|
59
|
+
e.append("checker must be {name, version} (non-empty strings)")
|
|
60
|
+
if r["verdict"] not in VERDICTS:
|
|
61
|
+
e.append(f"verdict must be one of {VERDICTS}")
|
|
62
|
+
if not (isinstance(r["reasons"], list) and all(isinstance(x, str) for x in r["reasons"])):
|
|
63
|
+
e.append("reasons must be a list of strings")
|
|
64
|
+
for k in ("pubkey", "signature"):
|
|
65
|
+
if not isinstance(r[k], str):
|
|
66
|
+
e.append(f"{k} must be a string")
|
|
67
|
+
return e
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def signing_bytes(r: dict) -> bytes:
|
|
71
|
+
"""What is signed: every field except the signature itself."""
|
|
72
|
+
return crypto.canonical_json({k: v for k, v in r.items() if k != "signature"})
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def receipt_hash(r: dict) -> str:
|
|
76
|
+
"""Identity used by the chain: SHA-256 of the whole receipt, signature included."""
|
|
77
|
+
return crypto.hash_json(r)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def create(*, subject_type: str, artifact_sha256: str, policy_sha256: str, checker_name: str, checker_version: str,
|
|
81
|
+
verdict: str, reasons: list[str] | None = None, trace_sha256: str | None = None,
|
|
82
|
+
prev_receipt_sha256: str = GENESIS, signing_key: str, timestamp_utc: str | None = None,
|
|
83
|
+
receipt_id: str | None = None) -> dict:
|
|
84
|
+
"""Build and sign a receipt. `signing_key` is the private seed (see crypto.load_signing_key); it is required."""
|
|
85
|
+
if not signing_key:
|
|
86
|
+
raise crypto.KeyMissing("refusing to create a receipt without a signing key")
|
|
87
|
+
r = {"version": VERSION, "receipt_id": receipt_id or str(uuid.uuid4()), "timestamp_utc": timestamp_utc or now_utc(),
|
|
88
|
+
"subject_type": subject_type, "artifact_sha256": artifact_sha256, "policy_sha256": policy_sha256,
|
|
89
|
+
"checker": {"name": checker_name, "version": checker_version}, "verdict": verdict,
|
|
90
|
+
"reasons": list(reasons or []), "trace_sha256": trace_sha256, "prev_receipt_sha256": prev_receipt_sha256,
|
|
91
|
+
"pubkey": crypto.public_from_private(signing_key), "signature": ""}
|
|
92
|
+
problems = validate_shape(r)
|
|
93
|
+
if problems:
|
|
94
|
+
raise ReceiptError("; ".join(problems))
|
|
95
|
+
r["signature"] = crypto.sign_bytes(signing_key, signing_bytes(r))
|
|
96
|
+
return r
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class Verification:
|
|
101
|
+
ok: bool
|
|
102
|
+
errors: list[str] = field(default_factory=list)
|
|
103
|
+
notes: list[str] = field(default_factory=list)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def verify(r: dict, pinned_pubkey: str | None = None) -> Verification:
|
|
107
|
+
"""Offline check: well-formed, signed by `pubkey`, and (if given) `pubkey` is the pinned one.
|
|
108
|
+
|
|
109
|
+
Without a pinned key this only shows the receipt is unmodified since SOME key signed it; anyone can make their own key."""
|
|
110
|
+
errs = validate_shape(r)
|
|
111
|
+
if errs:
|
|
112
|
+
return Verification(False, errs)
|
|
113
|
+
out = Verification(True)
|
|
114
|
+
if pinned_pubkey is not None and pinned_pubkey != r["pubkey"]:
|
|
115
|
+
out.ok = False
|
|
116
|
+
out.errors.append("signed by a different key than the pinned one")
|
|
117
|
+
return out
|
|
118
|
+
if not crypto.verify_bytes(r["pubkey"], r["signature"], signing_bytes(r)):
|
|
119
|
+
out.ok = False
|
|
120
|
+
out.errors.append("signature does not match the receipt (altered, or wrong key)")
|
|
121
|
+
return out
|
|
122
|
+
if pinned_pubkey is None:
|
|
123
|
+
out.notes.append("no pinned public key: this shows the receipt is unaltered, not who signed it")
|
|
124
|
+
return out
|
tenthlook_core/store.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Append-only SQLite receipt store with a hash chain.
|
|
2
|
+
|
|
3
|
+
Each receipt carries the SHA-256 of the previous receipt (`prev_receipt_sha256`), and is signed, so editing,
|
|
4
|
+
deleting or reordering any receipt that is followed by another one breaks `verify_chain`.
|
|
5
|
+
|
|
6
|
+
Limits (see README): deleting the LAST receipts is not detectable from the database alone (nothing follows them). Keep the
|
|
7
|
+
head hash and count somewhere else (`head()`; `verify_chain(expect_head=..., expect_count=...)`). SQLite triggers refuse
|
|
8
|
+
UPDATE and DELETE through SQL, but anyone with file access can bypass them; the signed chain is what detects that.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import sqlite3
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import crypto, receipt as rcpt
|
|
18
|
+
|
|
19
|
+
_SCHEMA = """
|
|
20
|
+
CREATE TABLE IF NOT EXISTS receipts (
|
|
21
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
22
|
+
receipt_sha256 TEXT NOT NULL UNIQUE,
|
|
23
|
+
body TEXT NOT NULL
|
|
24
|
+
);
|
|
25
|
+
CREATE TRIGGER IF NOT EXISTS receipts_no_update BEFORE UPDATE ON receipts BEGIN SELECT RAISE(ABORT, 'receipts are append-only'); END;
|
|
26
|
+
CREATE TRIGGER IF NOT EXISTS receipts_no_delete BEFORE DELETE ON receipts BEGIN SELECT RAISE(ABORT, 'receipts are append-only'); END;
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ChainError(RuntimeError):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class ChainResult:
|
|
36
|
+
ok: bool
|
|
37
|
+
count: int = 0
|
|
38
|
+
head: str = rcpt.GENESIS
|
|
39
|
+
errors: list[str] = field(default_factory=list)
|
|
40
|
+
notes: list[str] = field(default_factory=list)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Store:
|
|
44
|
+
def __init__(self, path: str | Path):
|
|
45
|
+
self.path = str(path)
|
|
46
|
+
self.db = sqlite3.connect(self.path, isolation_level=None) # explicit transactions
|
|
47
|
+
self.db.executescript(_SCHEMA)
|
|
48
|
+
|
|
49
|
+
def close(self) -> None:
|
|
50
|
+
self.db.close()
|
|
51
|
+
|
|
52
|
+
def __enter__(self):
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def __exit__(self, *a):
|
|
56
|
+
self.close()
|
|
57
|
+
|
|
58
|
+
def head(self) -> str:
|
|
59
|
+
row = self.db.execute("SELECT receipt_sha256 FROM receipts ORDER BY seq DESC LIMIT 1").fetchone()
|
|
60
|
+
return row[0] if row else rcpt.GENESIS
|
|
61
|
+
|
|
62
|
+
def count(self) -> int:
|
|
63
|
+
return self.db.execute("SELECT COUNT(*) FROM receipts").fetchone()[0]
|
|
64
|
+
|
|
65
|
+
def append(self, r: dict) -> str:
|
|
66
|
+
"""Add an already-signed receipt. It must verify and its prev hash must equal the current head."""
|
|
67
|
+
v = rcpt.verify(r)
|
|
68
|
+
if not v.ok:
|
|
69
|
+
raise ChainError("; ".join(v.errors))
|
|
70
|
+
self.db.execute("BEGIN IMMEDIATE")
|
|
71
|
+
try:
|
|
72
|
+
head = self.head()
|
|
73
|
+
if r["prev_receipt_sha256"] != head:
|
|
74
|
+
raise ChainError(f"prev_receipt_sha256 {r['prev_receipt_sha256'][:12]}.. is not the current head {head[:12]}..")
|
|
75
|
+
h = rcpt.receipt_hash(r)
|
|
76
|
+
self.db.execute("INSERT INTO receipts (receipt_sha256, body) VALUES (?, ?)", (h, crypto.canonical_json(r).decode()))
|
|
77
|
+
self.db.execute("COMMIT")
|
|
78
|
+
return h
|
|
79
|
+
except BaseException:
|
|
80
|
+
self.db.execute("ROLLBACK")
|
|
81
|
+
raise
|
|
82
|
+
|
|
83
|
+
def create_and_append(self, *, signing_key: str, **kw) -> dict:
|
|
84
|
+
"""Build a receipt chained to the current head, sign it and store it, atomically with respect to other writers."""
|
|
85
|
+
self.db.execute("BEGIN IMMEDIATE")
|
|
86
|
+
try:
|
|
87
|
+
r = rcpt.create(prev_receipt_sha256=self.head(), signing_key=signing_key, **kw)
|
|
88
|
+
self.db.execute("INSERT INTO receipts (receipt_sha256, body) VALUES (?, ?)",
|
|
89
|
+
(rcpt.receipt_hash(r), crypto.canonical_json(r).decode()))
|
|
90
|
+
self.db.execute("COMMIT")
|
|
91
|
+
return r
|
|
92
|
+
except BaseException:
|
|
93
|
+
self.db.execute("ROLLBACK")
|
|
94
|
+
raise
|
|
95
|
+
|
|
96
|
+
def all(self) -> list[dict]:
|
|
97
|
+
return [json.loads(b) for (b,) in self.db.execute("SELECT body FROM receipts ORDER BY seq")]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def verify_receipts(receipts: list, pinned_pubkey: str | None = None, expect_head: str | None = None,
|
|
101
|
+
expect_count: int | None = None, seqs: list[int] | None = None, stored_hashes: list[str] | None = None) -> ChainResult:
|
|
102
|
+
"""Offline chain check over receipts in order (from a core store, a JSON export, or any append-only ledger).
|
|
103
|
+
|
|
104
|
+
Checks each receipt's schema and signature, that it names the previous receipt's hash, and (when `seqs` /
|
|
105
|
+
`stored_hashes` are given) that sequence numbers are contiguous and stored hashes match."""
|
|
106
|
+
res = ChainResult(True)
|
|
107
|
+
prev, last_seq = rcpt.GENESIS, 0
|
|
108
|
+
for i, r in enumerate(receipts):
|
|
109
|
+
seq = seqs[i] if seqs else i + 1
|
|
110
|
+
tag = f"receipt #{seq}"
|
|
111
|
+
if seq != last_seq + 1:
|
|
112
|
+
res.errors.append(f"{tag}: sequence gap (expected #{last_seq + 1}): a receipt was deleted or inserted")
|
|
113
|
+
last_seq = seq
|
|
114
|
+
if not isinstance(r, dict):
|
|
115
|
+
res.errors.append(f"{tag}: not an object")
|
|
116
|
+
prev = ""
|
|
117
|
+
continue
|
|
118
|
+
v = rcpt.verify(r, pinned_pubkey)
|
|
119
|
+
res.errors += [f"{tag}: {m}" for m in v.errors]
|
|
120
|
+
h = rcpt.receipt_hash(r) if not rcpt.validate_shape(r) else ""
|
|
121
|
+
if not v.errors:
|
|
122
|
+
if stored_hashes and stored_hashes[i] != h:
|
|
123
|
+
res.errors.append(f"{tag}: stored hash does not match the receipt")
|
|
124
|
+
if r["prev_receipt_sha256"] != prev:
|
|
125
|
+
res.errors.append(f"{tag}: previous-receipt hash does not match the receipt before it: edited, deleted or reordered")
|
|
126
|
+
prev = h or (stored_hashes[i] if stored_hashes else "")
|
|
127
|
+
res.count, res.head = len(receipts), prev if receipts else rcpt.GENESIS
|
|
128
|
+
if expect_head is not None and expect_head != res.head:
|
|
129
|
+
res.errors.append(f"head is {res.head[:12]}.., expected {expect_head[:12]}..: receipts were removed or added since it was recorded")
|
|
130
|
+
if expect_count is not None and expect_count != len(receipts):
|
|
131
|
+
res.errors.append(f"{len(receipts)} receipts, expected {expect_count}")
|
|
132
|
+
if expect_head is None and expect_count is None:
|
|
133
|
+
res.notes.append("no expected head/count given: removal of the newest receipts cannot be detected")
|
|
134
|
+
if pinned_pubkey is None:
|
|
135
|
+
res.notes.append("no pinned public key: this shows internal consistency, not who signed")
|
|
136
|
+
res.ok = not res.errors
|
|
137
|
+
return res
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def verify_chain(db_path: str | Path, pinned_pubkey: str | None = None, expect_head: str | None = None,
|
|
141
|
+
expect_count: int | None = None) -> ChainResult:
|
|
142
|
+
"""Offline. `db_path` is a core receipt database, or a JSON file holding a list of receipts in order (for example
|
|
143
|
+
`panel export-receipts`)."""
|
|
144
|
+
p = Path(db_path)
|
|
145
|
+
if not p.is_file():
|
|
146
|
+
return ChainResult(False, errors=[f"{p} does not exist"])
|
|
147
|
+
head = p.read_bytes()[:16]
|
|
148
|
+
if not head.startswith(b"SQLite format 3"):
|
|
149
|
+
try:
|
|
150
|
+
data = json.loads(p.read_text(encoding="utf-8"))
|
|
151
|
+
except ValueError:
|
|
152
|
+
return ChainResult(False, errors=[f"{p} is neither a receipt database nor a JSON list of receipts"])
|
|
153
|
+
if not isinstance(data, list):
|
|
154
|
+
return ChainResult(False, errors=["JSON chain must be a list of receipts, oldest first"])
|
|
155
|
+
return verify_receipts(data, pinned_pubkey, expect_head, expect_count)
|
|
156
|
+
con = sqlite3.connect(f"file:{p}?mode=ro", uri=True)
|
|
157
|
+
try:
|
|
158
|
+
rows = con.execute("SELECT seq, receipt_sha256, body FROM receipts ORDER BY seq").fetchall()
|
|
159
|
+
except sqlite3.Error as e:
|
|
160
|
+
return ChainResult(False, errors=[f"not a receipt database: {e}"])
|
|
161
|
+
finally:
|
|
162
|
+
con.close()
|
|
163
|
+
bodies, bad = [], []
|
|
164
|
+
for seq, _, body in rows:
|
|
165
|
+
try:
|
|
166
|
+
r = json.loads(body)
|
|
167
|
+
if crypto.canonical_json(r).decode() != body:
|
|
168
|
+
bad.append(f"receipt #{seq}: body is not in canonical form")
|
|
169
|
+
bodies.append(r)
|
|
170
|
+
except (ValueError, TypeError):
|
|
171
|
+
bodies.append(None)
|
|
172
|
+
bad.append(f"receipt #{seq}: body is not JSON")
|
|
173
|
+
res = verify_receipts(bodies, pinned_pubkey, expect_head, expect_count, [r[0] for r in rows], [r[1] for r in rows])
|
|
174
|
+
res.errors += bad
|
|
175
|
+
res.ok = not res.errors
|
|
176
|
+
return res
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tenthlook-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Signed, hash-chained receipts (Ed25519 + SHA-256 + SQLite) shared by Panel and Tenthcheck. Offline verification.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: cryptography>=42
|
|
10
|
+
Provides-Extra: test
|
|
11
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# tenthlook-core
|
|
15
|
+
|
|
16
|
+
Signed, hash-chained receipts for automated checks, shared by Panel (policy checks on agent actions) and Tenthcheck (CI checks on diffs). Python, `cryptography` is the only dependency. Verification is offline: no network, no service.
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
pip install tenthlook-core # (not published yet: pip install -e .)
|
|
20
|
+
tenthlook keygen # key file in ~/.config/tenthlook/, mode 600, never inside a git repo, never overwritten
|
|
21
|
+
tenthlook verify-receipt receipt.json --pubkey <base64 public key>
|
|
22
|
+
tenthlook verify-chain receipts.db --pubkey <base64> [--expect-head <hash> --expect-count <n>]
|
|
23
|
+
# verify-chain also takes a JSON file holding a list of receipts, oldest first (e.g. `panel export-receipts`)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## A receipt
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{ "version": 1, "receipt_id": "...", "timestamp_utc": "2026-11-22T10:00:00.123456Z",
|
|
30
|
+
"subject_type": "mcp_tool_call | git_diff | sql_query",
|
|
31
|
+
"artifact_sha256": "...", "policy_sha256": "...", "checker": {"name": "...", "version": "..."},
|
|
32
|
+
"verdict": "ALLOWED | BLOCKED | NEEDS_CONSENT | Z3_VERIFIED | Z3_COUNTEREXAMPLE | NOT_CHECKABLE",
|
|
33
|
+
"reasons": ["..."], "trace_sha256": null, "prev_receipt_sha256": "<hash of the previous receipt, or 64 zeros>",
|
|
34
|
+
"pubkey": "<base64 Ed25519>", "signature": "<base64>" }
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The signature covers every other field (canonical JSON). A receipt's identity in the chain is the SHA-256 of the whole receipt including its signature. `store.Store` is an append-only SQLite table; each new receipt must name the current head as its `prev_receipt_sha256`.
|
|
38
|
+
|
|
39
|
+
## What a receipt proves
|
|
40
|
+
|
|
41
|
+
- **Who checked:** the holder of the private key for `pubkey` signed it (and *you* know who that is only if you pinned the public key, `--pubkey`; without that, anyone can sign with their own key).
|
|
42
|
+
- **What was checked:** the artifact with hash `artifact_sha256`, against the policy with hash `policy_sha256`, by the named checker and version. Given the original artifact and policy you can re-hash them and see they match.
|
|
43
|
+
- **What came out:** the verdict and the reasons, as the checker reported them.
|
|
44
|
+
- **That the record wasn't altered:** editing any field breaks the signature; in a chain, deleting, editing or reordering a receipt that is followed by another breaks the links.
|
|
45
|
+
|
|
46
|
+
## What it does NOT prove
|
|
47
|
+
|
|
48
|
+
- **Not that the action or code is safe or correct.** `ALLOWED` means the checker found nothing in its policy that forbids it. The checker can be wrong, the policy can be incomplete, and `Z3_VERIFIED` is only as good as the model handed to Z3.
|
|
49
|
+
- **Not that the check was run honestly.** A compromised signer, or a signer that skipped the check, still produces a valid signature. Nothing here attests the checker's execution environment.
|
|
50
|
+
- **Not that the artifact was what was acted on.** The receipt binds to a hash; nothing forces the agent or pipeline to use that exact artifact afterwards (check-then-swap).
|
|
51
|
+
- **Not that nothing is missing.** The chain detects removal of any receipt *followed by another*. Removing the newest receipts leaves a shorter, valid chain. Record `head` and count somewhere else (`--expect-head`, `--expect-count`) to detect that. A signer can also keep several chains, or never record a check at all.
|
|
52
|
+
- **Not time.** `timestamp_utc` is the signer's own clock; no trusted timestamping.
|
|
53
|
+
- **Not tamper-proof storage.** The SQLite triggers refuse UPDATE/DELETE through SQL, but anyone with file access can bypass them. The signatures and links are what reveal it afterwards.
|
|
54
|
+
- **Not a compliance certification** (SOC 2, ISO 27001, EU AI Act or anything else), and not an audit. It is evidence about a record, not an attestation about a system.
|
|
55
|
+
- **Not revocation or key rotation.** There is no revocation list; verify against the public key you pinned and rotate by publishing a new one.
|
|
56
|
+
|
|
57
|
+
## Keys
|
|
58
|
+
|
|
59
|
+
No default keys; signing without one raises. A key is a base64 32-byte Ed25519 seed in a file (`TENTHLOOK_KEY_FILE` or `--out`) that must be outside any git work tree and not group/world readable, or in `TENTHLOOK_SIGNING_KEY` for CI secrets. `tests/fixtures/conformance.json` contains a public test-only seed for cross-language checks; never sign anything real with it.
|
|
60
|
+
|
|
61
|
+
## Canonical JSON
|
|
62
|
+
|
|
63
|
+
`crypto.canonical_json` approximates RFC 8785 (JCS): sorted keys (by UTF-16 code unit, as JCS), no whitespace, UTF-8, minimal escaping. It differs by being **stricter**: floats, NaN/Infinity, integers beyond 2^53-1 and lone surrogates are rejected rather than formatted, because number formatting is where independent implementations stop agreeing. Anything it accepts is canonical under JCS; it does not accept everything JCS does. Put decimals in strings and money in minor units. A TypeScript port (Panel's `signedReceipt.ts`) is tested against `tests/fixtures/conformance.json`.
|
|
64
|
+
|
|
65
|
+
## Tests
|
|
66
|
+
|
|
67
|
+
`pip install -e '.[test]' && pytest`
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
tenthlook_core/__init__.py,sha256=kv86CTKcFW_L30e49fTlZulDIdRvikYQaOuwcNAoS_s,75
|
|
2
|
+
tenthlook_core/cli.py,sha256=wBTTfgMWnLJfWkoxQlbriPBndgYD4qEkO-Qs2DEjn9c,3077
|
|
3
|
+
tenthlook_core/crypto.py,sha256=CsIJ_KXUE0qR3nGVvetiBQQ95esIMEpJZIxr0TwBIMM,7406
|
|
4
|
+
tenthlook_core/receipt.py,sha256=9Z4ONMbxpcpF1yDRp0H61Qkya7MtjI1OjNE2mp3r8_Y,5664
|
|
5
|
+
tenthlook_core/store.py,sha256=K3BzxTwX215KPMjp3oPFgpX-cIcN-MwAVN0dFJcsy-o,7948
|
|
6
|
+
tenthlook_core-0.1.0.dist-info/licenses/LICENSE,sha256=bnnChWYVaTp5zAqMkzg3U9cYIyRZhsp4rDA-IvQy1wo,1072
|
|
7
|
+
tenthlook_core-0.1.0.dist-info/METADATA,sha256=FnVgRkdmYWdiFWK29cManiV0u9Cv6GmYqufaSXtGS7w,5244
|
|
8
|
+
tenthlook_core-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
tenthlook_core-0.1.0.dist-info/entry_points.txt,sha256=kr0WNO4tmlPMNZf-34bGdnMaSWfgJMO81KuepnoruIo,54
|
|
10
|
+
tenthlook_core-0.1.0.dist-info/top_level.txt,sha256=QzmAg4FDMd-Nkebc3LoJ3LBBf2OUzWIIIiAjtFTI9VI,15
|
|
11
|
+
tenthlook_core-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Naren Saravanan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tenthlook_core
|