verdock-verify 0.4.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.
@@ -0,0 +1,7 @@
1
+ """Verify Verdock action receipts offline. Receipt format and verification only."""
2
+
3
+ from .disclosure import verify_disclosure
4
+ from .receipts import canonical_bytes, line_hash, verify_bytes, verify_log
5
+
6
+ __version__ = "0.4.0"
7
+ __all__ = ["__version__", "canonical_bytes", "line_hash", "verify_bytes", "verify_log", "verify_disclosure"]
@@ -0,0 +1,42 @@
1
+ """Command line: verdock-verify FILE --public-key HEX."""
2
+ import argparse
3
+ import sys
4
+
5
+ from . import __version__
6
+ from .receipts import verify_log
7
+
8
+
9
+ def run(path, public_key, manifest_root=None):
10
+ try:
11
+ report = verify_log(path, public_key, manifest_root)
12
+ except OSError as exc:
13
+ print("error: cannot read %s: %s" % (path, exc.strerror or exc), file=sys.stderr)
14
+ return 2
15
+ except ValueError as exc:
16
+ print("error: %s" % exc, file=sys.stderr)
17
+ return 2
18
+ by_line = {}
19
+ for failure in report["failures"]:
20
+ by_line.setdefault(failure["line"], []).append(failure["reason"])
21
+ for number in range(1, report["count"] + 1):
22
+ reasons = by_line.get(number)
23
+ print("line %d: %s" % (number, "FAIL " + "; ".join(reasons) if reasons else "ok"))
24
+ if report["ok"]:
25
+ print("verified: %d lines, chain intact, signed by the trusted key" % report["count"])
26
+ return 0
27
+ print("failed: %d problems in %d lines" % (len(report["failures"]), report["count"]))
28
+ return 1
29
+
30
+
31
+ def main(argv=None):
32
+ parser = argparse.ArgumentParser(prog="verdock-verify", description="Verify a receipt log offline.")
33
+ parser.add_argument("--version", action="version", version="verdock-verify " + __version__)
34
+ parser.add_argument("file", help="NDJSON receipt log")
35
+ parser.add_argument("--public-key", required=True, help="trusted Ed25519 public key, 64 hex characters")
36
+ parser.add_argument("--manifest-root", help="64 hex root key that must have signed the first delegation record")
37
+ args = parser.parse_args(argv)
38
+ return run(args.file, args.public_key, args.manifest_root)
39
+
40
+
41
+ if __name__ == "__main__":
42
+ sys.exit(main())
@@ -0,0 +1,74 @@
1
+ """Verification of the approval evidence carried inside a receipt.
2
+
3
+ This checks what a receipt can prove on its own: the attached policy matches the signed policy hash, every vote is
4
+ signed by a listed approver key, the requester did not approve, no person or key counts twice, each vote falls inside
5
+ the validity period, and the number of approvals reaches the number recorded in the signed request. It does not
6
+ recompute whether the policy should have asked for that number.
7
+ """
8
+ import hashlib
9
+ import json
10
+
11
+ from . import ed25519
12
+
13
+
14
+ def encoded(value):
15
+ return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False).encode()
16
+
17
+
18
+ def key_id(public_key):
19
+ return hashlib.sha256(bytes.fromhex(public_key)).hexdigest()
20
+
21
+
22
+ def signing_bytes(request, decision):
23
+ return b'verdock-approval-v1\0' + encoded({'request': request, 'decision': {
24
+ k: decision[k] for k in ('approver', 'key_id', 'decision', 'ts_ms')}})
25
+
26
+
27
+ def _well_formed(request, votes):
28
+ """The members a receipt is compared against must be present and have the right type."""
29
+ return (isinstance(request, dict) and isinstance(votes, list)
30
+ and all(isinstance(request[k], str) and request[k] for k in ('id', 'operation', 'requested_by'))
31
+ and all(type(request[k]) is int for k in ('amount_minor', 'requested_at_ms', 'expires_at_ms'))
32
+ and request['amount_minor'] >= 0
33
+ and (request['currency'] is None or isinstance(request['currency'], str))
34
+ and isinstance(request['trusted_approvers'], dict))
35
+
36
+
37
+ def check_evidence(evidence, now_ms=None):
38
+ """Reject missing quorum, unknown keys, requester votes and changed signatures."""
39
+ try:
40
+ request, votes = evidence['request'], evidence['decisions']
41
+ if not _well_formed(request, votes):
42
+ return 'invalid approval evidence'
43
+ if request['policy_hash'] != hashlib.sha256(encoded(request['policy'])).hexdigest():
44
+ return 'approval policy hash mismatch'
45
+ needed = request['approvers_required']
46
+ if type(needed) is not int or needed < 1:
47
+ return 'invalid approval evidence'
48
+ identities, keys = set(), set()
49
+ # Compare key bytes, so one key written in another letter case is still the same key.
50
+ requester_pub = request['trusted_approvers'].get(request['requested_by'])
51
+ requester_key = None if requester_pub is None else bytes.fromhex(requester_pub)
52
+ for vote in votes:
53
+ person = vote['approver']
54
+ pub = request['trusted_approvers'][person]
55
+ key = bytes.fromhex(pub)
56
+ if person == request['requested_by'] or person in identities or key in keys or key == requester_key:
57
+ return 'duplicate or requester approval'
58
+ if vote['key_id'] != key_id(pub):
59
+ return 'approver key id mismatch'
60
+ if vote['decision'] != 'approved':
61
+ return 'approval rejected'
62
+ if type(vote['ts_ms']) is not int or not request['requested_at_ms'] <= vote['ts_ms'] < request['expires_at_ms']:
63
+ return 'approval outside validity period'
64
+ if not ed25519.verify(key, signing_bytes(request, vote), bytes.fromhex(vote['signature'])):
65
+ return 'approver signature invalid'
66
+ identities.add(person)
67
+ keys.add(key)
68
+ if len(identities) < needed:
69
+ return 'approval count below requirement'
70
+ if now_ms is not None and now_ms >= request['expires_at_ms']:
71
+ return 'approval expired'
72
+ except (KeyError, ValueError, TypeError, OverflowError, AttributeError, RecursionError):
73
+ return 'invalid approval evidence'
74
+ return None
@@ -0,0 +1,157 @@
1
+ """Verification of the delegation record carried inside a receipt."""
2
+ import hashlib
3
+ import re
4
+
5
+ from . import ed25519
6
+ from .receipts import _canon
7
+
8
+
9
+ _HEX64 = re.compile(r"[0-9a-f]{64}")
10
+
11
+
12
+ _CURRENCY = re.compile(r"[A-Z]{3}")
13
+
14
+
15
+ _KIND_KEYS = {"max_amount_minor", "currency", "destinations"}
16
+
17
+
18
+ class ManifestError(ValueError):
19
+ """A manifest is malformed or a delegation would widen its parent."""
20
+
21
+
22
+ def key_id(public_key_hex):
23
+ return hashlib.sha256(bytes.fromhex(public_key_hex)).hexdigest()
24
+
25
+
26
+ def _is_int(value):
27
+ return isinstance(value, int) and not isinstance(value, bool)
28
+
29
+
30
+ def normalize_actions(actions):
31
+ """Validate an actions mapping and return a normalized copy."""
32
+ if not isinstance(actions, dict):
33
+ raise ManifestError("actions must be a mapping")
34
+ result = {}
35
+ for kind, spec in actions.items():
36
+ if not isinstance(kind, str) or not kind:
37
+ raise ManifestError("action kind must be a non empty string")
38
+ if not isinstance(spec, dict) or not set(spec) <= _KIND_KEYS:
39
+ raise ManifestError("action %s has unknown members" % kind)
40
+ entry = {}
41
+ if "max_amount_minor" in spec:
42
+ if not _is_int(spec["max_amount_minor"]) or spec["max_amount_minor"] < 0:
43
+ raise ManifestError("max_amount_minor must be an integer >= 0")
44
+ entry["max_amount_minor"] = spec["max_amount_minor"]
45
+ if "currency" in spec:
46
+ if not isinstance(spec["currency"], str) or not _CURRENCY.fullmatch(spec["currency"]):
47
+ raise ManifestError("currency must be three upper case letters")
48
+ entry["currency"] = spec["currency"]
49
+ destinations = spec.get("destinations", [])
50
+ if not isinstance(destinations, list) or not all(isinstance(d, str) and d for d in destinations):
51
+ raise ManifestError("destinations must be a list of non empty strings")
52
+ entry["destinations"] = sorted(set(destinations))
53
+ result[kind] = entry
54
+ return result
55
+
56
+
57
+ def widening(child, parent):
58
+ """Return a failure reason if child actions are not a subset of parent actions."""
59
+ for kind, spec in child.items():
60
+ base = parent.get(kind)
61
+ if base is None:
62
+ return "delegation widens parent: action kind"
63
+ if "max_amount_minor" in base and (
64
+ "max_amount_minor" not in spec or spec["max_amount_minor"] > base["max_amount_minor"]):
65
+ return "delegation widens parent: limit"
66
+ if "currency" in base and spec.get("currency") != base["currency"]:
67
+ return "delegation widens parent: currency"
68
+ if not set(spec["destinations"]) <= set(base["destinations"]):
69
+ return "delegation widens parent: destinations"
70
+ return None
71
+
72
+
73
+ def _signing_bytes(manifest):
74
+ return b"verdock-manifest-v1\0" + _canon(manifest).encode("utf-8")
75
+
76
+
77
+ def manifest_hash(signed):
78
+ return hashlib.sha256(_canon(signed).encode("utf-8")).hexdigest()
79
+
80
+
81
+ def verify_chain(chain, root_public_key=None):
82
+ """Return None when the chain is sound, else a failure reason.
83
+
84
+ chain runs from the root manifest to the acting agent's manifest. When
85
+ root_public_key is given the root manifest must be signed by it.
86
+ """
87
+ try:
88
+ if not isinstance(chain, list) or not chain:
89
+ return "delegation chain invalid"
90
+ previous = None
91
+ for signed in chain:
92
+ m = signed["manifest"]
93
+ if type(m["version"]) is not int or m["version"] != 1 or set(m) != {"version", "issuer_public_key", "issuer_key_id", "subject_public_key",
94
+ "subject_key_id", "parent_hash", "actions"}:
95
+ return "delegation chain invalid"
96
+ for name in ("issuer_public_key", "subject_public_key"):
97
+ if not isinstance(m[name], str) or not _HEX64.fullmatch(m[name]):
98
+ return "delegation chain invalid"
99
+ if m["issuer_key_id"] != key_id(m["issuer_public_key"]) or m["subject_key_id"] != key_id(m["subject_public_key"]):
100
+ return "delegation chain invalid"
101
+ if normalize_actions(m["actions"]) != m["actions"]:
102
+ return "delegation chain invalid"
103
+ if not ed25519.verify(bytes.fromhex(m["issuer_public_key"]), _signing_bytes(m), bytes.fromhex(signed["signature"])):
104
+ return "delegation signature invalid"
105
+ if previous is None:
106
+ if m["parent_hash"] is not None:
107
+ return "delegation chain invalid"
108
+ if root_public_key is not None and m["issuer_public_key"] != root_public_key:
109
+ return "delegation root untrusted"
110
+ else:
111
+ if m["parent_hash"] != manifest_hash(previous) or m["issuer_public_key"] != previous["manifest"]["subject_public_key"]:
112
+ return "delegation chain invalid"
113
+ reason = widening(m["actions"], previous["manifest"]["actions"])
114
+ if reason:
115
+ return reason
116
+ previous = signed
117
+ except (KeyError, TypeError, ValueError, ManifestError, AttributeError, RecursionError):
118
+ return "delegation chain invalid"
119
+ return None
120
+
121
+
122
+ def check_action(actions, kind, amount_minor=None, currency=None, destination=None):
123
+ """Return None when the action fits the actions mapping, else a reason."""
124
+ spec = actions.get(kind) if isinstance(kind, str) else None
125
+ if spec is None:
126
+ return "manifest denies action kind"
127
+ if "max_amount_minor" in spec:
128
+ if not _is_int(amount_minor) or amount_minor < 0 or amount_minor > spec["max_amount_minor"]:
129
+ return "amount above manifest limit"
130
+ if "currency" in spec and currency != spec["currency"]:
131
+ return "currency not allowed by manifest"
132
+ if spec["destinations"]:
133
+ if destination not in spec["destinations"]:
134
+ return "destination not allowed by manifest"
135
+ elif destination is not None:
136
+ return "destination not allowed by manifest"
137
+ return None
138
+
139
+
140
+ def check_delegation(delegation, root_public_key=None):
141
+ """Check a receipt's delegation record: {"chain": [...], "action": {...}}.
142
+
143
+ Verifies the chain and that the action fits every manifest on it.
144
+ """
145
+ reason = verify_chain(delegation.get("chain") if isinstance(delegation, dict) else None, root_public_key)
146
+ if reason:
147
+ return reason
148
+ try:
149
+ action = delegation["action"]
150
+ for signed in delegation["chain"]:
151
+ reason = check_action(signed["manifest"]["actions"], action["kind"], action.get("amount_minor"),
152
+ action.get("currency"), action.get("destination"))
153
+ if reason:
154
+ return "action outside delegated manifest: " + reason
155
+ except (KeyError, TypeError, AttributeError):
156
+ return "delegation chain invalid"
157
+ return None
@@ -0,0 +1,51 @@
1
+ """Check that one opened field matches the commitment inside an already verified receipt."""
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+
6
+
7
+ def _no_floats(value):
8
+ if isinstance(value, float):
9
+ raise ValueError('committed values must not contain non integer numbers')
10
+ if isinstance(value, (list, tuple)):
11
+ for item in value:
12
+ _no_floats(item)
13
+ elif isinstance(value, dict):
14
+ for item in value.values():
15
+ _no_floats(item)
16
+
17
+
18
+ def _json(value):
19
+ _no_floats(value)
20
+ return json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':'), allow_nan=False)
21
+
22
+
23
+ def commitment(value, salt):
24
+ return hashlib.sha256(b'verdock-field-v1\0' + salt + _json(value).encode()).hexdigest()
25
+
26
+
27
+ def _field(receipt, path):
28
+ value = receipt
29
+ for part in path.lstrip('/').split('/'):
30
+ part = part.replace('~1', '/').replace('~0', '~')
31
+ value = value[int(part)] if isinstance(value, list) else value[part]
32
+ return value
33
+
34
+
35
+ # Only signed fields can be opened. Exchange receipts are not checked here.
36
+ PREFIX = '/params/'
37
+
38
+
39
+ def verify_disclosure(receipt, proof):
40
+ """Use an independently signature-verified receipt as the trust anchor."""
41
+ try:
42
+ if not proof['path'].startswith(PREFIX):
43
+ return False
44
+ if proof['step_id'] != receipt['step_id']:
45
+ return False
46
+ salt = bytes.fromhex(proof['field_salt'])
47
+ target = _field(receipt, proof['path'])
48
+ return len(salt) == 32 and set(target) == {'sha256'} and hmac.compare_digest(
49
+ target['sha256'], commitment(proof['value'], salt))
50
+ except (KeyError, ValueError, TypeError, IndexError, AttributeError, RecursionError):
51
+ return False
@@ -0,0 +1,106 @@
1
+ """Ed25519 signature verification (RFC 8032, section 5.1) in pure Python. Verification only."""
2
+
3
+ import hashlib
4
+
5
+ _P = 2 ** 255 - 19
6
+
7
+
8
+ _L = 2 ** 252 + 27742317777372353535851937790883648493
9
+
10
+
11
+ def _inv(x):
12
+ return pow(x, _P - 2, _P)
13
+
14
+
15
+ _D = -121665 * _inv(121666) % _P
16
+
17
+
18
+ _SQRT_M1 = pow(2, (_P - 1) // 4, _P)
19
+
20
+
21
+ def _add(p1, p2):
22
+ # Extended homogeneous coordinates (X, Y, Z, T), RFC 8032 section 5.1.4.
23
+ x1, y1, z1, t1 = p1
24
+ x2, y2, z2, t2 = p2
25
+ a = (y1 - x1) * (y2 - x2) % _P
26
+ b = (y1 + x1) * (y2 + x2) % _P
27
+ c = 2 * t1 * t2 * _D % _P
28
+ d = 2 * z1 * z2 % _P
29
+ e, f, g, h = b - a, d - c, d + c, b + a
30
+ return (e * f % _P, g * h % _P, f * g % _P, e * h % _P)
31
+
32
+
33
+ _IDENTITY = (0, 1, 1, 0)
34
+
35
+
36
+ def _mul(scalar, point):
37
+ result = _IDENTITY
38
+ while scalar > 0:
39
+ if scalar & 1:
40
+ result = _add(result, point)
41
+ point = _add(point, point)
42
+ scalar >>= 1
43
+ return result
44
+
45
+
46
+ def _equal(p1, p2):
47
+ return ((p1[0] * p2[2] - p2[0] * p1[2]) % _P == 0
48
+ and (p1[1] * p2[2] - p2[1] * p1[2]) % _P == 0)
49
+
50
+
51
+ def _recover_x(y, sign):
52
+ if y >= _P:
53
+ return None
54
+ x2 = (y * y - 1) * _inv(_D * y * y + 1) % _P
55
+ if x2 == 0:
56
+ return None if sign else 0
57
+ x = pow(x2, (_P + 3) // 8, _P)
58
+ if (x * x - x2) % _P != 0:
59
+ x = x * _SQRT_M1 % _P
60
+ if (x * x - x2) % _P != 0:
61
+ return None
62
+ if (x & 1) != sign:
63
+ x = _P - x
64
+ return x
65
+
66
+
67
+ _GY = 4 * _inv(5) % _P
68
+
69
+
70
+ _GX = _recover_x(_GY, 0)
71
+
72
+
73
+ _G = (_GX, _GY, 1, _GX * _GY % _P)
74
+
75
+
76
+ def _decode(data):
77
+ if len(data) != 32:
78
+ return None
79
+ y = int.from_bytes(data, "little")
80
+ sign = y >> 255
81
+ y &= (1 << 255) - 1
82
+ x = _recover_x(y, sign)
83
+ if x is None:
84
+ return None
85
+ return (x, y, 1, x * y % _P)
86
+
87
+
88
+ def _hash_int(data):
89
+ return int.from_bytes(hashlib.sha512(data).digest(), "little")
90
+
91
+
92
+ def verify(pub, message, signature):
93
+ """Return True if signature is valid for message under public key pub."""
94
+ if len(pub) != 32 or len(signature) != 64:
95
+ return False
96
+ a_point = _decode(bytes(pub))
97
+ if a_point is None:
98
+ return False
99
+ r_point = _decode(bytes(signature[:32]))
100
+ if r_point is None:
101
+ return False
102
+ s = int.from_bytes(signature[32:], "little")
103
+ if s >= _L:
104
+ return False
105
+ k = _hash_int(bytes(signature[:32]) + bytes(pub) + bytes(message)) % _L
106
+ return _equal(_mul(s, _G), _add(r_point, _mul(k, a_point)))
@@ -0,0 +1,332 @@
1
+ """Signed, hash chained action receipts (draft-sahu-agent-action-receipts-00).
2
+
3
+ Each receipt is one line of newline delimited JSON with these members:
4
+
5
+ step_id string, required
6
+ action_id string, required
7
+ params any JSON value, required
8
+ success boolean, required
9
+ ts_ms integer milliseconds since the Unix epoch, required
10
+ actor object with string members agent and/or user, optional
11
+ prev_hash 64 lowercase hex, absent on the first line, required after
12
+ public_key 64 lowercase hex (Ed25519, 32 bytes), required
13
+ signature 128 lowercase hex (Ed25519, 64 bytes), required
14
+
15
+ Other members may be present. They are not signed, but they are covered by
16
+ the next line's prev_hash because that digest is over the exact line bytes.
17
+ On the last line nothing covers them. A line that repeats a member name in any
18
+ object is rejected.
19
+
20
+ Signed bytes (draft section 4): compact JSON of the signed members in the
21
+ fixed order step_id, action_id, params, success, ts_ms, actor (agent then
22
+ user), prev_hash, omitting absent ones. Object keys inside params are
23
+ sorted by Unicode code point at every depth; arrays keep their order.
24
+ Strings use the shortest RFC 8259 form with lowercase \\u escapes. Numbers
25
+ must be integers within +/- (2**53 - 1); this package rejects any non
26
+ integer number token anywhere in a line, so the Python and browser
27
+ verifiers always agree.
28
+
29
+ Chain (draft section 6): prev_hash of line n is the SHA-256 hex digest of
30
+ the exact octets of line n - 1, without its newline.
31
+
32
+ Limits: a log whose newest lines were removed still verifies (draft section 9); detecting
33
+ that needs a head digest stored somewhere else.
34
+ """
35
+
36
+ import hashlib
37
+ import json
38
+ import os
39
+ import re
40
+
41
+ from . import ed25519
42
+
43
+ SIGNED_MEMBERS = ("step_id", "action_id", "params", "success", "ts_ms", "actor", "prev_hash")
44
+
45
+
46
+ MAX_SAFE_INTEGER = 2 ** 53 - 1
47
+
48
+
49
+ _HEX64 = re.compile(r"[0-9a-f]{64}")
50
+
51
+
52
+ _HEX128 = re.compile(r"[0-9a-f]{128}")
53
+
54
+
55
+ _SURROGATE = re.compile("[\ud800-\udfff]")
56
+
57
+
58
+ class ReceiptError(ValueError):
59
+ """A receipt value cannot be canonicalized."""
60
+
61
+
62
+ def _canon_string(value):
63
+ if _SURROGATE.search(value):
64
+ raise ReceiptError("invalid string")
65
+ return json.dumps(value, ensure_ascii=False)
66
+
67
+
68
+ def _canon(value):
69
+ if value is None:
70
+ return "null"
71
+ if value is True:
72
+ return "true"
73
+ if value is False:
74
+ return "false"
75
+ if isinstance(value, int):
76
+ if abs(value) > MAX_SAFE_INTEGER:
77
+ raise ReceiptError("integer out of range")
78
+ return str(value)
79
+ if isinstance(value, float):
80
+ raise ReceiptError("non-integer number")
81
+ if isinstance(value, str):
82
+ return _canon_string(value)
83
+ if isinstance(value, (list, tuple)):
84
+ return "[" + ",".join(_canon(item) for item in value) + "]"
85
+ if isinstance(value, dict):
86
+ for key in value:
87
+ if not isinstance(key, str):
88
+ raise ReceiptError("object keys must be strings")
89
+ # Python orders str by code point, which is what the draft requires.
90
+ return "{" + ",".join(
91
+ _canon_string(key) + ":" + _canon(value[key]) for key in sorted(value)
92
+ ) + "}"
93
+ raise ReceiptError("unsupported value type %s" % type(value).__name__)
94
+
95
+
96
+ def _check_members(receipt):
97
+ """Return a failure reason for missing or mistyped members, or None."""
98
+ for name in ("step_id", "action_id", "params", "success", "ts_ms", "public_key", "signature"):
99
+ if name not in receipt:
100
+ return "missing member: %s" % name
101
+ for name in ("step_id", "action_id", "public_key", "signature"):
102
+ if not isinstance(receipt[name], str):
103
+ return "wrong type: %s" % name
104
+ if not isinstance(receipt["success"], bool):
105
+ return "wrong type: success"
106
+ ts_ms = receipt["ts_ms"]
107
+ if not isinstance(ts_ms, int) or isinstance(ts_ms, bool):
108
+ return "wrong type: ts_ms"
109
+ if "actor" in receipt:
110
+ actor = receipt["actor"]
111
+ if not isinstance(actor, dict) or not set(actor) <= {"agent", "user"}:
112
+ return "wrong type: actor"
113
+ if not all(isinstance(v, str) for v in actor.values()):
114
+ return "wrong type: actor"
115
+ if "prev_hash" in receipt and not isinstance(receipt["prev_hash"], str):
116
+ return "wrong type: prev_hash"
117
+ return None
118
+
119
+
120
+ def canonical_bytes(receipt):
121
+ """Return the signed byte sequence for a receipt mapping."""
122
+ parts = []
123
+ for name in SIGNED_MEMBERS:
124
+ if name not in receipt:
125
+ continue
126
+ value = receipt[name]
127
+ if name == "actor":
128
+ encoded = "{" + ",".join(
129
+ _canon_string(key) + ":" + _canon_string(value[key])
130
+ for key in ("agent", "user") if key in value
131
+ ) + "}"
132
+ else:
133
+ encoded = _canon(value)
134
+ parts.append(_canon_string(name) + ":" + encoded)
135
+ return ("{" + ",".join(parts) + "}").encode("utf-8")
136
+
137
+
138
+ def line_hash(line):
139
+ """SHA-256 hex of a line's octets (str is encoded as UTF-8)."""
140
+ if isinstance(line, str):
141
+ line = line.encode("utf-8")
142
+ return hashlib.sha256(line).hexdigest()
143
+
144
+
145
+ class _NonInteger(Exception):
146
+ pass
147
+
148
+
149
+ def _reject_float(text):
150
+ raise _NonInteger()
151
+
152
+
153
+ def _reject_constant(text):
154
+ raise ValueError("invalid constant")
155
+
156
+
157
+ class _Duplicate(Exception):
158
+ pass
159
+
160
+
161
+ def _unique_members(pairs):
162
+ result = dict(pairs)
163
+ if len(result) != len(pairs):
164
+ raise _Duplicate()
165
+ return result
166
+
167
+
168
+ def _numbers_ok(value):
169
+ if isinstance(value, bool) or value is None or isinstance(value, str):
170
+ return True
171
+ if isinstance(value, int):
172
+ return abs(value) <= MAX_SAFE_INTEGER
173
+ if isinstance(value, list):
174
+ return all(_numbers_ok(item) for item in value)
175
+ if isinstance(value, dict):
176
+ return all(_numbers_ok(item) for item in value.values())
177
+ return False
178
+
179
+
180
+ def _has_surrogate(value):
181
+ if isinstance(value, str):
182
+ return bool(_SURROGATE.search(value))
183
+ if isinstance(value, list):
184
+ return any(_has_surrogate(item) for item in value)
185
+ if isinstance(value, dict):
186
+ return any(_has_surrogate(k) or _has_surrogate(v) for k, v in value.items())
187
+ return False
188
+
189
+
190
+ def _split(data):
191
+ if data.endswith(b"\n"):
192
+ data = data[:-1]
193
+ if not data:
194
+ return []
195
+ return data.split(b"\n")
196
+
197
+
198
+ def _check_line(raw, index, prev_raw, anchor, manifest_root=None):
199
+ """Return the list of failure reasons for one line."""
200
+ try:
201
+ return _line_failures(raw, index, prev_raw, anchor, manifest_root)
202
+ except RecursionError:
203
+ return ["nested too deeply"]
204
+
205
+
206
+ def _line_failures(raw, index, prev_raw, anchor, manifest_root):
207
+ if raw == b"":
208
+ return ["empty line"]
209
+ try:
210
+ text = raw.decode("utf-8")
211
+ except UnicodeDecodeError:
212
+ return ["invalid UTF-8"]
213
+ try:
214
+ receipt = json.loads(text, parse_float=_reject_float, parse_constant=_reject_constant,
215
+ object_pairs_hook=_unique_members)
216
+ except _Duplicate:
217
+ return ["duplicate member name"]
218
+ except _NonInteger:
219
+ # Report invalid JSON first if the rest of the line is also broken.
220
+ try:
221
+ json.loads(text, parse_constant=_reject_constant)
222
+ except (ValueError, RecursionError):
223
+ return ["invalid JSON"]
224
+ return ["non-integer number"]
225
+ except (ValueError, RecursionError):
226
+ return ["invalid JSON"]
227
+ if not _numbers_ok(receipt):
228
+ return ["integer out of range"]
229
+ if _has_surrogate(receipt):
230
+ return ["invalid string"]
231
+ if not isinstance(receipt, dict):
232
+ return ["not an object"]
233
+ reason = _check_members(receipt)
234
+ if reason:
235
+ return [reason]
236
+ failures = []
237
+ pub_ok = bool(_HEX64.fullmatch(receipt["public_key"]))
238
+ sig_ok = bool(_HEX128.fullmatch(receipt["signature"]))
239
+ if not pub_ok:
240
+ failures.append("invalid hex: public_key")
241
+ if not sig_ok:
242
+ failures.append("invalid hex: signature")
243
+ if "prev_hash" in receipt and not _HEX64.fullmatch(receipt["prev_hash"]):
244
+ failures.append("invalid hex: prev_hash")
245
+ if pub_ok and sig_ok:
246
+ message = canonical_bytes(receipt)
247
+ if not ed25519.verify(bytes.fromhex(receipt["public_key"]), message,
248
+ bytes.fromhex(receipt["signature"])):
249
+ failures.append("signature invalid")
250
+ if index == 0:
251
+ if "prev_hash" in receipt:
252
+ failures.append("unexpected prev_hash on first line")
253
+ elif "prev_hash" not in receipt:
254
+ failures.append("missing prev_hash")
255
+ elif receipt["prev_hash"] != hashlib.sha256(prev_raw).hexdigest():
256
+ failures.append("chain break")
257
+ if pub_ok and receipt["public_key"] != anchor:
258
+ failures.append("untrusted public key")
259
+ if isinstance(receipt.get('params'), dict) and 'approval_evidence' in receipt['params']:
260
+ from .approvals import check_evidence
261
+ evidence = receipt['params']['approval_evidence']
262
+ reason = check_evidence(evidence)
263
+ if reason:
264
+ failures.append(reason)
265
+ elif receipt['action_id'] != evidence['request']['operation']:
266
+ failures.append('receipt action differs from approved operation')
267
+ elif receipt['step_id'] != evidence['request']['id']:
268
+ failures.append('receipt differs from approved action')
269
+ elif receipt['ts_ms'] < max(v['ts_ms'] for v in evidence['decisions']) or receipt['ts_ms'] >= evidence['request']['expires_at_ms']:
270
+ failures.append('receipt outside approval validity period')
271
+ elif any(k in receipt['params'] and (type(receipt['params'][k]) is not type(evidence['request'][k])
272
+ or receipt['params'][k] != evidence['request'][k]) for k in ('amount_minor', 'currency')):
273
+ failures.append('receipt differs from approved action')
274
+ if isinstance(receipt.get('params'), dict) and 'delegation' in receipt['params']:
275
+ from .delegation import check_delegation
276
+ reason = check_delegation(receipt['params']['delegation'], manifest_root)
277
+ if reason:
278
+ failures.append(reason)
279
+ return failures
280
+
281
+
282
+ def _normalize_anchor(trust_anchor_hex):
283
+ if not isinstance(trust_anchor_hex, str):
284
+ raise ValueError("trust anchor must be a hex string")
285
+ anchor = trust_anchor_hex.strip().lower()
286
+ if not _HEX64.fullmatch(anchor):
287
+ raise ValueError("trust anchor must be 64 hex characters")
288
+ return anchor
289
+
290
+
291
+ def verify_bytes(data, trust_anchor_hex, manifest_root=None):
292
+ """Verify a whole log given as bytes. See verify_log for the result."""
293
+ anchor = _normalize_anchor(trust_anchor_hex)
294
+ if manifest_root is not None:
295
+ manifest_root = manifest_root.strip().lower() if isinstance(manifest_root, str) else ""
296
+ if not _HEX64.fullmatch(manifest_root):
297
+ raise ValueError("manifest root must be 64 hex characters")
298
+ lines = _split(bytes(data))
299
+ failures = []
300
+ prev_raw = None
301
+ for index, raw in enumerate(lines):
302
+ for reason in _check_line(raw, index, prev_raw, anchor, manifest_root):
303
+ failures.append({"line": index + 1, "reason": reason})
304
+ prev_raw = raw
305
+ return {"ok": not failures, "count": len(lines), "failures": failures}
306
+
307
+
308
+ def verify_log(lines_or_path, trust_anchor_hex, manifest_root=None):
309
+ """Verify a receipt log against a trust anchor (draft section 7).
310
+
311
+ lines_or_path is a path (str or os.PathLike) or an iterable of lines
312
+ (str or bytes, a trailing newline on each is allowed). Returns
313
+ {"ok": bool, "count": number of lines, "failures": [{"line", "reason"}]}
314
+ with 1 based line numbers. manifest_root, when given, is the 64 hex root
315
+ key that must have signed the first manifest of any delegation chain.
316
+ Every line is checked; a bad line is reported,
317
+ never skipped, and ok is True only when there are no failures.
318
+ """
319
+ if isinstance(lines_or_path, (str, os.PathLike)):
320
+ with open(lines_or_path, "rb") as handle:
321
+ return verify_bytes(handle.read(), trust_anchor_hex, manifest_root)
322
+ encoded = []
323
+ for line in lines_or_path:
324
+ if isinstance(line, str):
325
+ try:
326
+ line = line.encode("utf-8")
327
+ except UnicodeEncodeError:
328
+ line = b"\xff" # reported as invalid UTF-8
329
+ if line.endswith(b"\n"):
330
+ line = line[:-1]
331
+ encoded.append(line)
332
+ return verify_bytes(b"\n".join(encoded) + (b"\n" if encoded else b""), trust_anchor_hex, manifest_root)
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: verdock-verify
3
+ Version: 0.4.0
4
+ Summary: Offline verifier for Verdock action receipts
5
+ Author: Sriharsan B S
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://getverdock.com
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # verdock-verify
14
+
15
+ Check Verdock action receipts on your own machine, with no network and no account. Python standard library only.
16
+
17
+ ```sh
18
+ pip install . # run in a copy of this repository
19
+ verdock-verify receipts.ndjson --public-key <64 hex characters>
20
+ ```
21
+
22
+ Exit status 0 means every line verified, 1 means at least one line failed, 2 means a usage or file error. An empty file has no line to fail, so it exits 0 and reports 0 lines. Check the line count.
23
+
24
+ ## What a pass tells you
25
+
26
+ * Every line's signed fields (`step_id`, `action_id`, `params`, `success`, `ts_ms`, `actor`, `prev_hash`) are signed by the key you trust.
27
+ * No line before the last one was changed, and no line was reordered or removed from the start or middle of the file.
28
+ * Approval records in `params.approval_evidence` are signed by approver keys listed in that record. The requester's name and listed key did not approve, no name or key counted twice, the approvals reach the number in the signed request, and the receipt matches its action id, step id, validity period and (when `params` repeats them) amount and currency.
29
+ * Delegation records in `params.delegation` are signed, each child stays inside its parent, and the action written in the record fits the whole chain.
30
+
31
+ ## What it does not tell you
32
+
33
+ * Lines removed from the end of a log cannot be detected unless you stored the last line hash elsewhere.
34
+ * Unsigned members and spacing on the last line can be changed without detection.
35
+ * Whether the approver keys in an approval record belong to real or authorised people. The verifier has no approver list of its own.
36
+ * Whether the action in a delegation record is the action the receipt describes, or who used the delegation. The root key is checked only with `--manifest-root`, a receipt with no delegation record still passes, and revocation is not checked.
37
+ * It does not recompute whether a policy should have asked for more approvals, or allowed the action at all.
38
+ * It does not check exchange receipts.
39
+
40
+ The receipt format is described at the top of `verdock_verify/receipts.py`.
41
+
42
+ ## Licence
43
+
44
+ MIT. This licence covers the verifier only. The Verdock platform is licensed separately.
@@ -0,0 +1,13 @@
1
+ verdock_verify/__init__.py,sha256=ToOhe-16K-Jfi4ScretiMpF89wQQE3cxtt64pUO8qFI,341
2
+ verdock_verify/__main__.py,sha256=sRInUOn2WyFvE9KAZVai0wL2bjgw29QTqxQtLLFPAsY,1738
3
+ verdock_verify/approvals.py,sha256=33Fv8KN1lzuSrmw2cCQSa9G8cTUtM6X77Io_IV2HbFg,3778
4
+ verdock_verify/delegation.py,sha256=0Zh2Kqa4x9x3hgFZKD4RC6tSfUJe9f9yVsWF22iKUo4,7041
5
+ verdock_verify/disclosure.py,sha256=7qO-q6R1SQrjqCphX9QFBdojdiMIqhZQnvyaWqZlo2s,1771
6
+ verdock_verify/ed25519.py,sha256=lPXVSUyjIuCb_LVbb6T_GxWB83tbTHgmBVecrwtMkSE,2532
7
+ verdock_verify/receipts.py,sha256=WglH7tLr_Kf9uJJfJtAdld4SmKL4A98ispLoi6zHA1E,12872
8
+ verdock_verify-0.4.0.dist-info/licenses/LICENSE,sha256=o8tei2L18iJ-OzGINjtH2xcMB8HRKJkbFUpCnsIzZQE,1091
9
+ verdock_verify-0.4.0.dist-info/METADATA,sha256=4BMBNIup_fe28EWrWXFErvWuCOGR7NqRjdvt0CEckJw,2525
10
+ verdock_verify-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ verdock_verify-0.4.0.dist-info/entry_points.txt,sha256=K-JB0gUCzVfr0l_zLyh3q0e2yTE8ALwAoCD0aPi5EqU,64
12
+ verdock_verify-0.4.0.dist-info/top_level.txt,sha256=uAF6kMW5Ct0V6gxl7XVTKamYOOogm3IW55sKPFn9V7M,15
13
+ verdock_verify-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ verdock-verify = verdock_verify.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sriharsan B S
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
+ verdock_verify