telos-receipt 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- telos_receipt-0.1.0/.gitignore +7 -0
- telos_receipt-0.1.0/LICENSE +202 -0
- telos_receipt-0.1.0/PKG-INFO +121 -0
- telos_receipt-0.1.0/README.md +96 -0
- telos_receipt-0.1.0/pyproject.toml +56 -0
- telos_receipt-0.1.0/telos_receipt/__init__.py +331 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: telos-receipt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The canonical unsigned integrity-hash receipt contract for TELOS AI Labs: one envelope both the trust surface and the MCP governance server speak. Pure stdlib, zero dependencies.
|
|
5
|
+
Project-URL: Homepage, https://telos-labs.ai
|
|
6
|
+
Project-URL: Repository, https://github.com/TELOS-Labs-AI/telos-receipt
|
|
7
|
+
Author-email: TELOS AI Labs <team@telos-labs.ai>
|
|
8
|
+
License: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agent-governance,ai-governance,integrity-hash,receipts,telos
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
23
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# telos-receipt
|
|
27
|
+
|
|
28
|
+
The canonical **unsigned integrity-hash receipt contract** for TELOS AI Labs.
|
|
29
|
+
|
|
30
|
+
One receipt envelope, spoken by both ends of the trust loop:
|
|
31
|
+
|
|
32
|
+
- **telos-mcp** mints a receipt when its governance scorer scores an action.
|
|
33
|
+
- **telos-trust-surface** serves and verifies receipts other agents fetch.
|
|
34
|
+
|
|
35
|
+
Because both import this package, a receipt minted by the scorer verifies on the
|
|
36
|
+
trust surface unchanged, no translation, no second shape to keep in sync.
|
|
37
|
+
|
|
38
|
+
Pure stdlib, zero dependencies, offline, key-free.
|
|
39
|
+
|
|
40
|
+
## The envelope
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"receipt_version": "telos/0.1-unsigned",
|
|
45
|
+
"kind": "action_governed",
|
|
46
|
+
"agent_id": "...",
|
|
47
|
+
"payload": { "...": "..." },
|
|
48
|
+
"issued_at": "<iso8601>",
|
|
49
|
+
"integrity_hash": "sha256:<hex over canonical payload>",
|
|
50
|
+
"covered_fields": "payload (canonical JSON, sort_keys, compact separators)",
|
|
51
|
+
"signing_status": "unsigned_integrity_hash",
|
|
52
|
+
"signature": null,
|
|
53
|
+
"engine": "telos v0.1 (unsigned integrity-hash; no governance engine wired)"
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Canonical form, stated exactly** (independent verifiers MUST match all six or payloads will falsely mismatch): keys sorted, compact separators (`,` `:`), NaN/Infinity refused, and **ASCII-escaped output** (Python `json.dumps` default `ensure_ascii=True`: non-ASCII characters serialize as `\uXXXX` escapes, including UTF-16 surrogate pairs for astral characters). A verifier emitting raw UTF-8 will compute a different hash on any non-ASCII payload. Two further rules govern numbers, because the action receipt carries floats:
|
|
58
|
+
|
|
59
|
+
5. **Number formatting.** Floats serialize as Python's shortest round-trip `repr` (equivalently the ECMAScript Number-to-String algorithm): `0.1` emits `0.1`, not `0.10000000000000001`. A non-Python verifier MUST reproduce that exact formatting or any float-bearing payload will mismatch.
|
|
60
|
+
6. **Number type is significant.** JSON has a single number type, but this contract preserves the payload's Python type: `1` (int) and `1.0` (float) are distinct inputs producing distinct hashes. A reimplementation that collapses `1.0` to `1` cannot reproduce a float-typed hash. `build_action_receipt` puts floats (`composite_score`, `scores`) into the payload, so this rule is load-bearing for action receipts.
|
|
61
|
+
|
|
62
|
+
### Known-answer vectors
|
|
63
|
+
|
|
64
|
+
Recomputed from this package on CPython 3.11 / 3.12 / 3.14 (byte-identical on all three). Each entry is the exact ASCII-escaped canonical JSON that `compute_integrity_hash` produces (the string that is UTF-8 encoded and SHA-256'd), followed by the hash it returns. Copy the escaped string verbatim. The second vector is a non-ASCII payload (`e` + combining accent U+0301, Cyrillic, and an astral emoji), shown as its escaped canonical form because that is what actually gets hashed:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
{"action":"wrote_file","path":"demo.txt"}
|
|
68
|
+
sha256:acd144a9dc2a2d19c13d1ef5119759ae963c406d7e980b017e00cb163517f692
|
|
69
|
+
|
|
70
|
+
{"msg":"cafe\u0301 \u043c\u0438\u0440 \ud83d\ude80"}
|
|
71
|
+
sha256:f9c77a03300b6507b66feccb530a6e3ed9eb0fe80f27c3a269559de15d0a0911
|
|
72
|
+
|
|
73
|
+
{"composite_score":0.1,"scores":{"purpose":0.9,"scope":0.8}}
|
|
74
|
+
sha256:3d3fbf211d5c93140e5a55713c571544718b1d59c581e19e134a74664b025f54
|
|
75
|
+
|
|
76
|
+
{"v":1}
|
|
77
|
+
sha256:afbf9d0f3560b0fd7795e81c42a0a79ee6b6fc67e064f77826aee642cad28d91
|
|
78
|
+
|
|
79
|
+
{"v":1.0}
|
|
80
|
+
sha256:f3c8be97307d38261061fa08e74365e54a239cddb1d189f3bea18022adbe2f35
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The float payload exercises rule 5; the last two vectors differ by number type alone (rule 6).
|
|
84
|
+
|
|
85
|
+
## What the integrity hash does and does not tell you
|
|
86
|
+
|
|
87
|
+
- **Does:** confirm the `payload` matches the `integrity_hash` recorded in the
|
|
88
|
+
receipt (it detects alteration of the payload relative to that hash).
|
|
89
|
+
- **Does NOT:** prove who issued it, when, or that the payload+hash pair was not
|
|
90
|
+
minted fresh. Anyone can compute the same hash over any payload. Authorship
|
|
91
|
+
and time need a signature, which this contract does not provide yet.
|
|
92
|
+
|
|
93
|
+
`verify_receipt` checks the payload-to-hash binding ONLY. It does not read, trust,
|
|
94
|
+
or validate a receipt's `signature` or `signing_status` fields; its result always
|
|
95
|
+
reports `signature_verified: false` and the library's own unsigned
|
|
96
|
+
`signing_status` constant, never the receipt's self-declared value.
|
|
97
|
+
|
|
98
|
+
## Going live (no schema break)
|
|
99
|
+
|
|
100
|
+
Two internals flip; the shape does not move:
|
|
101
|
+
|
|
102
|
+
1. The governance engine flips stub → real (real verdicts/scores in the payload).
|
|
103
|
+
2. The signer flips null → real: `signature` is filled and `signing_status`
|
|
104
|
+
changes. Every field already exists.
|
|
105
|
+
|
|
106
|
+
## API
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from telos_receipt import build_receipt, build_action_receipt, verify_receipt
|
|
110
|
+
|
|
111
|
+
r = build_action_receipt(
|
|
112
|
+
action_name="write_file",
|
|
113
|
+
action_params={"path": "/tmp/x"},
|
|
114
|
+
agent_id="agent-alpha",
|
|
115
|
+
verdict="EXECUTE",
|
|
116
|
+
composite_score=0.81,
|
|
117
|
+
scores={"purpose": 0.9, "scope": 0.8},
|
|
118
|
+
pa_id="pa::agent-alpha::v1",
|
|
119
|
+
)
|
|
120
|
+
assert verify_receipt(r)["match"] is True
|
|
121
|
+
```
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# telos-receipt
|
|
2
|
+
|
|
3
|
+
The canonical **unsigned integrity-hash receipt contract** for TELOS AI Labs.
|
|
4
|
+
|
|
5
|
+
One receipt envelope, spoken by both ends of the trust loop:
|
|
6
|
+
|
|
7
|
+
- **telos-mcp** mints a receipt when its governance scorer scores an action.
|
|
8
|
+
- **telos-trust-surface** serves and verifies receipts other agents fetch.
|
|
9
|
+
|
|
10
|
+
Because both import this package, a receipt minted by the scorer verifies on the
|
|
11
|
+
trust surface unchanged, no translation, no second shape to keep in sync.
|
|
12
|
+
|
|
13
|
+
Pure stdlib, zero dependencies, offline, key-free.
|
|
14
|
+
|
|
15
|
+
## The envelope
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"receipt_version": "telos/0.1-unsigned",
|
|
20
|
+
"kind": "action_governed",
|
|
21
|
+
"agent_id": "...",
|
|
22
|
+
"payload": { "...": "..." },
|
|
23
|
+
"issued_at": "<iso8601>",
|
|
24
|
+
"integrity_hash": "sha256:<hex over canonical payload>",
|
|
25
|
+
"covered_fields": "payload (canonical JSON, sort_keys, compact separators)",
|
|
26
|
+
"signing_status": "unsigned_integrity_hash",
|
|
27
|
+
"signature": null,
|
|
28
|
+
"engine": "telos v0.1 (unsigned integrity-hash; no governance engine wired)"
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Canonical form, stated exactly** (independent verifiers MUST match all six or payloads will falsely mismatch): keys sorted, compact separators (`,` `:`), NaN/Infinity refused, and **ASCII-escaped output** (Python `json.dumps` default `ensure_ascii=True`: non-ASCII characters serialize as `\uXXXX` escapes, including UTF-16 surrogate pairs for astral characters). A verifier emitting raw UTF-8 will compute a different hash on any non-ASCII payload. Two further rules govern numbers, because the action receipt carries floats:
|
|
33
|
+
|
|
34
|
+
5. **Number formatting.** Floats serialize as Python's shortest round-trip `repr` (equivalently the ECMAScript Number-to-String algorithm): `0.1` emits `0.1`, not `0.10000000000000001`. A non-Python verifier MUST reproduce that exact formatting or any float-bearing payload will mismatch.
|
|
35
|
+
6. **Number type is significant.** JSON has a single number type, but this contract preserves the payload's Python type: `1` (int) and `1.0` (float) are distinct inputs producing distinct hashes. A reimplementation that collapses `1.0` to `1` cannot reproduce a float-typed hash. `build_action_receipt` puts floats (`composite_score`, `scores`) into the payload, so this rule is load-bearing for action receipts.
|
|
36
|
+
|
|
37
|
+
### Known-answer vectors
|
|
38
|
+
|
|
39
|
+
Recomputed from this package on CPython 3.11 / 3.12 / 3.14 (byte-identical on all three). Each entry is the exact ASCII-escaped canonical JSON that `compute_integrity_hash` produces (the string that is UTF-8 encoded and SHA-256'd), followed by the hash it returns. Copy the escaped string verbatim. The second vector is a non-ASCII payload (`e` + combining accent U+0301, Cyrillic, and an astral emoji), shown as its escaped canonical form because that is what actually gets hashed:
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
{"action":"wrote_file","path":"demo.txt"}
|
|
43
|
+
sha256:acd144a9dc2a2d19c13d1ef5119759ae963c406d7e980b017e00cb163517f692
|
|
44
|
+
|
|
45
|
+
{"msg":"cafe\u0301 \u043c\u0438\u0440 \ud83d\ude80"}
|
|
46
|
+
sha256:f9c77a03300b6507b66feccb530a6e3ed9eb0fe80f27c3a269559de15d0a0911
|
|
47
|
+
|
|
48
|
+
{"composite_score":0.1,"scores":{"purpose":0.9,"scope":0.8}}
|
|
49
|
+
sha256:3d3fbf211d5c93140e5a55713c571544718b1d59c581e19e134a74664b025f54
|
|
50
|
+
|
|
51
|
+
{"v":1}
|
|
52
|
+
sha256:afbf9d0f3560b0fd7795e81c42a0a79ee6b6fc67e064f77826aee642cad28d91
|
|
53
|
+
|
|
54
|
+
{"v":1.0}
|
|
55
|
+
sha256:f3c8be97307d38261061fa08e74365e54a239cddb1d189f3bea18022adbe2f35
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The float payload exercises rule 5; the last two vectors differ by number type alone (rule 6).
|
|
59
|
+
|
|
60
|
+
## What the integrity hash does and does not tell you
|
|
61
|
+
|
|
62
|
+
- **Does:** confirm the `payload` matches the `integrity_hash` recorded in the
|
|
63
|
+
receipt (it detects alteration of the payload relative to that hash).
|
|
64
|
+
- **Does NOT:** prove who issued it, when, or that the payload+hash pair was not
|
|
65
|
+
minted fresh. Anyone can compute the same hash over any payload. Authorship
|
|
66
|
+
and time need a signature, which this contract does not provide yet.
|
|
67
|
+
|
|
68
|
+
`verify_receipt` checks the payload-to-hash binding ONLY. It does not read, trust,
|
|
69
|
+
or validate a receipt's `signature` or `signing_status` fields; its result always
|
|
70
|
+
reports `signature_verified: false` and the library's own unsigned
|
|
71
|
+
`signing_status` constant, never the receipt's self-declared value.
|
|
72
|
+
|
|
73
|
+
## Going live (no schema break)
|
|
74
|
+
|
|
75
|
+
Two internals flip; the shape does not move:
|
|
76
|
+
|
|
77
|
+
1. The governance engine flips stub → real (real verdicts/scores in the payload).
|
|
78
|
+
2. The signer flips null → real: `signature` is filled and `signing_status`
|
|
79
|
+
changes. Every field already exists.
|
|
80
|
+
|
|
81
|
+
## API
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from telos_receipt import build_receipt, build_action_receipt, verify_receipt
|
|
85
|
+
|
|
86
|
+
r = build_action_receipt(
|
|
87
|
+
action_name="write_file",
|
|
88
|
+
action_params={"path": "/tmp/x"},
|
|
89
|
+
agent_id="agent-alpha",
|
|
90
|
+
verdict="EXECUTE",
|
|
91
|
+
composite_score=0.81,
|
|
92
|
+
scores={"purpose": 0.9, "scope": 0.8},
|
|
93
|
+
pa_id="pa::agent-alpha::v1",
|
|
94
|
+
)
|
|
95
|
+
assert verify_receipt(r)["match"] is True
|
|
96
|
+
```
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "telos-receipt"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "The canonical unsigned integrity-hash receipt contract for TELOS AI Labs: one envelope both the trust surface and the MCP governance server speak. Pure stdlib, zero dependencies."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "Apache-2.0" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "TELOS AI Labs", email = "team@telos-labs.ai" }
|
|
14
|
+
]
|
|
15
|
+
keywords = [
|
|
16
|
+
"telos",
|
|
17
|
+
"ai-governance",
|
|
18
|
+
"agent-governance",
|
|
19
|
+
"receipts",
|
|
20
|
+
"integrity-hash",
|
|
21
|
+
]
|
|
22
|
+
classifiers = [
|
|
23
|
+
"Development Status :: 3 - Alpha",
|
|
24
|
+
"Intended Audience :: Developers",
|
|
25
|
+
"License :: OSI Approved :: Apache Software License",
|
|
26
|
+
"Operating System :: OS Independent",
|
|
27
|
+
"Programming Language :: Python :: 3",
|
|
28
|
+
"Programming Language :: Python :: 3.10",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
32
|
+
]
|
|
33
|
+
dependencies = []
|
|
34
|
+
|
|
35
|
+
[project.optional-dependencies]
|
|
36
|
+
dev = [
|
|
37
|
+
"pytest>=8.0",
|
|
38
|
+
"ruff>=0.5",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://telos-labs.ai"
|
|
43
|
+
Repository = "https://github.com/TELOS-Labs-AI/telos-receipt"
|
|
44
|
+
|
|
45
|
+
[tool.hatch.build.targets.wheel]
|
|
46
|
+
packages = ["telos_receipt"]
|
|
47
|
+
|
|
48
|
+
# Explicit sdist allowlist: ship ONLY the package + metadata. Without this,
|
|
49
|
+
# hatchling falls back to gitignore-based selection and an untracked workspace
|
|
50
|
+
# (venvs, caches, scratch files) gets swept into the published sdist.
|
|
51
|
+
[tool.hatch.build.targets.sdist]
|
|
52
|
+
only-include = ["telos_receipt", "README.md", "LICENSE", "pyproject.toml"]
|
|
53
|
+
|
|
54
|
+
[tool.ruff]
|
|
55
|
+
line-length = 120
|
|
56
|
+
target-version = "py310"
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
"""telos-receipt: the canonical unsigned integrity-hash receipt contract.
|
|
2
|
+
|
|
3
|
+
This is the single source of truth for the TELOS receipt envelope. Both the
|
|
4
|
+
agent-facing trust surface (which serves + verifies receipts) and the telos-mcp
|
|
5
|
+
governance server (which mints receipts when it scores an action) speak THIS
|
|
6
|
+
shape, so a receipt minted by one verifies on the other with no translation.
|
|
7
|
+
|
|
8
|
+
Pure stdlib, zero dependencies, offline, key-free.
|
|
9
|
+
|
|
10
|
+
The integrity hash is a SHA-256 over the canonical-JSON serialization of the
|
|
11
|
+
receipt `payload`. Recomputing it confirms the payload matches the hash recorded
|
|
12
|
+
in the receipt: it detects alteration of the payload relative to that recorded
|
|
13
|
+
hash. It is key-free, so it is NOT a digital signature: anyone can recompute it
|
|
14
|
+
(or mint a fresh payload + matching hash), and it says nothing about who issued
|
|
15
|
+
the receipt or when. That honesty is the point. When the signing ceremony lands,
|
|
16
|
+
a real signature populates the `signature` field and `signing_status` flips to
|
|
17
|
+
the signed value, without changing this hash or the envelope shape.
|
|
18
|
+
|
|
19
|
+
Go-live swap (no schema break, no re-architecture):
|
|
20
|
+
- The governance engine flips from stub to real (it computes real verdicts /
|
|
21
|
+
scores; the payload it commits to becomes real, not synthetic).
|
|
22
|
+
- The signer flips from null to a real signature: `signature` is filled and
|
|
23
|
+
`signing_status` changes. Every field already exists; nothing moves.
|
|
24
|
+
|
|
25
|
+
Canonical form: json.dumps(payload, sort_keys=True, separators=(",", ":"),
|
|
26
|
+
allow_nan=False), over JSON-native, finite payloads only. A value with no
|
|
27
|
+
canonical JSON form (set/bytes/datetime/object) or a non-finite float is REFUSED
|
|
28
|
+
(the build raises; verify reports a controlled mismatch), because such inputs have
|
|
29
|
+
no deterministic hash. Determinism: same payload in -> same hash out, on every
|
|
30
|
+
run, on every machine.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import hashlib
|
|
36
|
+
import json
|
|
37
|
+
import math
|
|
38
|
+
import re
|
|
39
|
+
from datetime import datetime, timezone
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
__version__ = "0.1.0"
|
|
43
|
+
|
|
44
|
+
RECEIPT_VERSION = "telos/0.1-unsigned"
|
|
45
|
+
SIGNING_STATUS = "unsigned_integrity_hash"
|
|
46
|
+
ENGINE_LABEL = "telos v0.1 (unsigned integrity-hash; no governance engine wired)"
|
|
47
|
+
HASH_PREFIX = "sha256:"
|
|
48
|
+
|
|
49
|
+
# A payload nested deeper than this is refused identically on every supported
|
|
50
|
+
# runtime. Real receipt payloads are a handful of levels deep; the cap exists so
|
|
51
|
+
# the accept/refuse boundary is a documented contract constant instead of
|
|
52
|
+
# whatever recursion limit a given Python build happens to have.
|
|
53
|
+
MAX_DEPTH = 200
|
|
54
|
+
|
|
55
|
+
_HASH_RE = re.compile(r"sha256:[0-9a-f]{64}\Z")
|
|
56
|
+
|
|
57
|
+
# Fields the integrity hash covers. Anything outside `payload` (issued_at,
|
|
58
|
+
# signature, engine label) is metadata and is intentionally NOT hashed, so the
|
|
59
|
+
# same logical payload yields the same hash regardless of when it was served.
|
|
60
|
+
COVERED = "payload (canonical JSON, sort_keys, compact separators)"
|
|
61
|
+
|
|
62
|
+
# Public surface: exactly these 11 names. `__version__` is included on purpose
|
|
63
|
+
# (callers pin against it; a public version attribute is part of the contract),
|
|
64
|
+
# and MAX_DEPTH is public because the depth cap is part of the accept/refuse
|
|
65
|
+
# contract. tests/test_tier2_fixes.py asserts `import *` matches this list.
|
|
66
|
+
__all__ = [
|
|
67
|
+
"RECEIPT_VERSION",
|
|
68
|
+
"SIGNING_STATUS",
|
|
69
|
+
"ENGINE_LABEL",
|
|
70
|
+
"HASH_PREFIX",
|
|
71
|
+
"COVERED",
|
|
72
|
+
"MAX_DEPTH",
|
|
73
|
+
"compute_integrity_hash",
|
|
74
|
+
"build_receipt",
|
|
75
|
+
"build_action_receipt",
|
|
76
|
+
"verify_receipt",
|
|
77
|
+
"__version__",
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _prevalidate(value: Any, depth: int = 0) -> None:
|
|
82
|
+
# STRICT JSON-native gate, checked BEFORE serialization. json.dumps alone is
|
|
83
|
+
# not strict enough: it coerces int/bool/None dict keys to strings and tuples
|
|
84
|
+
# to arrays, so distinct Python payloads would mint the SAME hash (a collision
|
|
85
|
+
# by coercion), and a hostile container subclass could run arbitrary code
|
|
86
|
+
# during encoding. Exact types only:
|
|
87
|
+
# containers exactly dict / list (subclasses and tuples refused)
|
|
88
|
+
# dict keys exactly str
|
|
89
|
+
# scalars exactly str / int / float (finite) / bool / None
|
|
90
|
+
# Refusals use the same controlled paths as before: TypeError for a value
|
|
91
|
+
# with no canonical form, ValueError for non-finite floats and for nesting
|
|
92
|
+
# beyond MAX_DEPTH (the runtime-independent depth contract).
|
|
93
|
+
if value is None:
|
|
94
|
+
return
|
|
95
|
+
t = type(value)
|
|
96
|
+
if t is str or t is bool or t is int:
|
|
97
|
+
return
|
|
98
|
+
if t is float:
|
|
99
|
+
if not math.isfinite(value):
|
|
100
|
+
raise ValueError("payload contains a non-finite float (NaN/Infinity); no canonical JSON form")
|
|
101
|
+
return
|
|
102
|
+
if t is dict:
|
|
103
|
+
if depth >= MAX_DEPTH:
|
|
104
|
+
raise ValueError(f"payload exceeds the maximum nesting depth ({MAX_DEPTH})")
|
|
105
|
+
for k, v in value.items():
|
|
106
|
+
if type(k) is not str:
|
|
107
|
+
# Type-only message: never invoke repr()/str() (or any dunder)
|
|
108
|
+
# on a rejected value -- a hostile __repr__ would turn this
|
|
109
|
+
# controlled TypeError into an arbitrary escape.
|
|
110
|
+
raise TypeError(
|
|
111
|
+
f"payload dict key of type {type(k).__name__} is not str; "
|
|
112
|
+
"key coercion would let distinct payloads mint the same hash"
|
|
113
|
+
)
|
|
114
|
+
_prevalidate(v, depth + 1)
|
|
115
|
+
return
|
|
116
|
+
if t is list:
|
|
117
|
+
if depth >= MAX_DEPTH:
|
|
118
|
+
raise ValueError(f"payload exceeds the maximum nesting depth ({MAX_DEPTH})")
|
|
119
|
+
for item in value:
|
|
120
|
+
_prevalidate(item, depth + 1)
|
|
121
|
+
return
|
|
122
|
+
raise TypeError(
|
|
123
|
+
f"payload value of type {type(value).__name__} is not JSON-native "
|
|
124
|
+
"(exactly dict/list/str/int/float/bool/None); no canonical JSON form"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _canonical(payload: Any) -> bytes:
|
|
129
|
+
# STRICT canonical JSON: exact-type prevalidation first (see _prevalidate),
|
|
130
|
+
# then no `default=` coercion and allow_nan=False. A value with no canonical
|
|
131
|
+
# JSON form (set/frozenset/bytes/datetime/custom object/subclass), a
|
|
132
|
+
# non-finite float (NaN/Infinity), or nesting beyond MAX_DEPTH has NO
|
|
133
|
+
# deterministic, RFC-8259 hash -- so we REFUSE it (raise) rather than
|
|
134
|
+
# silently hashing an order-dependent str()/repr or a coerced form. Callers
|
|
135
|
+
# pass JSON-native, finite payloads; verify catches the raise and returns
|
|
136
|
+
# match:false so hostile input never crashes it. For payloads that pass the
|
|
137
|
+
# gate, the serialized bytes are identical to what this function has always
|
|
138
|
+
# produced -- the gate only adds refusals at the edges.
|
|
139
|
+
_prevalidate(payload)
|
|
140
|
+
return json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def compute_integrity_hash(payload: Any) -> str:
|
|
144
|
+
"""Return 'sha256:<hex>' over the canonical-JSON form of `payload`.
|
|
145
|
+
|
|
146
|
+
`payload` must be strictly JSON-native and finite: containers exactly
|
|
147
|
+
dict/list, dict keys exactly str, scalars exactly str/int/float/bool/None,
|
|
148
|
+
nested at most MAX_DEPTH (200) levels. A non-conforming value raises
|
|
149
|
+
TypeError; a NaN/Infinity float, a circular reference, or nesting beyond
|
|
150
|
+
MAX_DEPTH raises ValueError. There is no canonical hash for such inputs, so
|
|
151
|
+
refusing them keeps the hash deterministic on every run/process/machine and
|
|
152
|
+
on every supported Python version.
|
|
153
|
+
"""
|
|
154
|
+
return HASH_PREFIX + hashlib.sha256(_canonical(payload)).hexdigest()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _now_iso() -> str:
|
|
158
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def build_receipt(
|
|
162
|
+
kind: str,
|
|
163
|
+
payload: dict[str, Any],
|
|
164
|
+
agent_id: str,
|
|
165
|
+
issued_at: str | None = None,
|
|
166
|
+
engine: str = ENGINE_LABEL,
|
|
167
|
+
) -> dict[str, Any]:
|
|
168
|
+
"""Build an unsigned integrity-hash receipt.
|
|
169
|
+
|
|
170
|
+
`signature` is explicitly null and `signing_status` declares the unsigned
|
|
171
|
+
state, so no reader can mistake this for a digital signature. The envelope
|
|
172
|
+
shape is stable: a later signed build only fills `signature` and changes
|
|
173
|
+
`signing_status`.
|
|
174
|
+
|
|
175
|
+
`engine` labels which engine produced the payload (e.g. the trust surface,
|
|
176
|
+
or the MCP governance scorer in stub mode). It is metadata, not hashed.
|
|
177
|
+
"""
|
|
178
|
+
issued = issued_at if issued_at is not None else _now_iso()
|
|
179
|
+
return {
|
|
180
|
+
"receipt_version": RECEIPT_VERSION,
|
|
181
|
+
"kind": kind,
|
|
182
|
+
"agent_id": agent_id,
|
|
183
|
+
"payload": payload,
|
|
184
|
+
"issued_at": issued,
|
|
185
|
+
"integrity_hash": compute_integrity_hash(payload),
|
|
186
|
+
"covered_fields": COVERED,
|
|
187
|
+
"signing_status": SIGNING_STATUS,
|
|
188
|
+
"signature": None,
|
|
189
|
+
"engine": engine,
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def build_action_receipt(
|
|
194
|
+
action_name: str,
|
|
195
|
+
action_params: dict[str, Any],
|
|
196
|
+
agent_id: str,
|
|
197
|
+
verdict: str,
|
|
198
|
+
composite_score: float,
|
|
199
|
+
scores: dict[str, float],
|
|
200
|
+
pa_id: str,
|
|
201
|
+
issued_at: str | None = None,
|
|
202
|
+
engine: str = ENGINE_LABEL,
|
|
203
|
+
) -> dict[str, Any]:
|
|
204
|
+
"""Build a governed-action receipt: the result of scoring one action.
|
|
205
|
+
|
|
206
|
+
This is the receipt a governance scorer emits per action. The payload
|
|
207
|
+
commits to the governance result (verdict + per-dimension scores + the PA
|
|
208
|
+
it was measured against) and to *which* action was scored via a hash of the
|
|
209
|
+
action params -- the raw params are deliberately not echoed, so the receipt
|
|
210
|
+
is publishable without leaking the action's arguments.
|
|
211
|
+
|
|
212
|
+
The envelope is the same `build_receipt` shape the trust surface verifies,
|
|
213
|
+
so a receipt minted here verifies there unchanged.
|
|
214
|
+
|
|
215
|
+
`action_params` must be JSON-native and finite (the values that cross an MCP/
|
|
216
|
+
HTTP boundary always are). A non-serializable or non-finite value raises,
|
|
217
|
+
rather than committing to a process-dependent hash.
|
|
218
|
+
"""
|
|
219
|
+
payload = {
|
|
220
|
+
"action_name": action_name,
|
|
221
|
+
"action_params_hash": compute_integrity_hash(action_params),
|
|
222
|
+
"verdict": verdict,
|
|
223
|
+
"composite_score": composite_score,
|
|
224
|
+
"scores": scores,
|
|
225
|
+
"pa_id": pa_id,
|
|
226
|
+
}
|
|
227
|
+
return build_receipt(
|
|
228
|
+
kind="action_governed",
|
|
229
|
+
payload=payload,
|
|
230
|
+
agent_id=agent_id,
|
|
231
|
+
issued_at=issued_at,
|
|
232
|
+
engine=engine,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def verify_receipt(receipt: Any) -> dict[str, Any]:
|
|
237
|
+
"""Recompute the integrity hash over `receipt['payload']` and compare.
|
|
238
|
+
|
|
239
|
+
Pure, offline, key-free. Returns a dict with `match` (bool) and a `reason`.
|
|
240
|
+
Rejects malformed input (not exactly a dict, missing payload/integrity_hash,
|
|
241
|
+
integrity_hash not exactly str, wrong hash format) with `match: false` and a
|
|
242
|
+
clear reason, never raising -- for ANY input, hostile subclasses included.
|
|
243
|
+
The receipt must be exactly `dict` and its `integrity_hash` exactly `str`
|
|
244
|
+
(same exact-type discipline as the payload gate): subclasses are refused
|
|
245
|
+
before any of their methods can run.
|
|
246
|
+
|
|
247
|
+
This validates the payload<->integrity_hash binding ONLY. It does not read,
|
|
248
|
+
trust, or validate the receipt's `signature` or `signing_status` fields; the
|
|
249
|
+
result's `signature_verified` is always False and its `signing_status` is the
|
|
250
|
+
library's own unsigned constant, never the receipt's self-declared value.
|
|
251
|
+
"""
|
|
252
|
+
try:
|
|
253
|
+
return _verify(receipt)
|
|
254
|
+
except BaseException: # noqa: BLE001 -- the never-raises contract is absolute:
|
|
255
|
+
# a hostile object (e.g. a container subclass that raises mid-iteration,
|
|
256
|
+
# an overridden __getitem__/__eq__, a __repr__ raising KeyboardInterrupt)
|
|
257
|
+
# must normalize to a controlled mismatch, never escape to the caller.
|
|
258
|
+
# BaseException, not Exception: the contract claims ANY input, and a
|
|
259
|
+
# hostile dunder can raise KeyboardInterrupt/SystemExit on purpose. The
|
|
260
|
+
# exact-type gates in _verify/_prevalidate stop hostile code from ever
|
|
261
|
+
# running, so the only interrupt this can swallow on the valid path is a
|
|
262
|
+
# genuine Ctrl-C landing inside a sub-millisecond pure computation --
|
|
263
|
+
# the process stays interruptible at its next point.
|
|
264
|
+
return _result(False, None, "unexpected error while verifying (hostile or malformed input)")
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _verify(receipt: Any) -> dict[str, Any]:
|
|
268
|
+
# Exact type, not isinstance: a dict SUBCLASS could override __contains__/
|
|
269
|
+
# get/__getitem__ to raise (KeyboardInterrupt included) or lie. Refusing it
|
|
270
|
+
# here, before any of its methods run, keeps the refusal side-effect-free.
|
|
271
|
+
if type(receipt) is not dict:
|
|
272
|
+
return _result(False, None, "receipt is not a JSON object")
|
|
273
|
+
if "payload" not in receipt:
|
|
274
|
+
return _result(False, receipt.get("integrity_hash"), "missing required field: payload")
|
|
275
|
+
stated = receipt.get("integrity_hash")
|
|
276
|
+
# Exact str for the same reason: a str subclass controls startswith/__eq__,
|
|
277
|
+
# so it could raise here or return a non-boolean from the == below.
|
|
278
|
+
if type(stated) is not str or not stated.startswith(HASH_PREFIX):
|
|
279
|
+
return _result(False, stated, "missing or malformed integrity_hash (expected 'sha256:<hex>')")
|
|
280
|
+
if _HASH_RE.fullmatch(stated) is None:
|
|
281
|
+
# Diagnose the hash itself before recomputing anything: a stated hash
|
|
282
|
+
# that is not 'sha256:' + exactly 64 lowercase hex chars is MALFORMED --
|
|
283
|
+
# reporting it as "payload altered" would misdirect the operator.
|
|
284
|
+
return _result(
|
|
285
|
+
False,
|
|
286
|
+
stated,
|
|
287
|
+
"malformed integrity_hash: expected 'sha256:' followed by exactly 64 lowercase hex characters",
|
|
288
|
+
)
|
|
289
|
+
try:
|
|
290
|
+
recomputed = compute_integrity_hash(receipt["payload"])
|
|
291
|
+
except (TypeError, ValueError, RecursionError):
|
|
292
|
+
# Hostile payload with no canonical JSON form: a non-serializable type, a
|
|
293
|
+
# non-finite float, a circular reference, or nesting too deep to encode.
|
|
294
|
+
# Honor the never-raises contract -- report a controlled mismatch.
|
|
295
|
+
return _result(
|
|
296
|
+
False,
|
|
297
|
+
stated,
|
|
298
|
+
"payload has no canonical JSON form (non-serializable, non-finite, circular, or too deeply nested)",
|
|
299
|
+
)
|
|
300
|
+
# `recomputed` is our own hexdigest-derived exact str; `stated` is exact str
|
|
301
|
+
# by the gate above, so == is real str equality. bool() pins the contract
|
|
302
|
+
# (`match` is exactly bool) even if either side ever changes.
|
|
303
|
+
match = bool(recomputed == stated)
|
|
304
|
+
reason = (
|
|
305
|
+
"payload matches the recorded integrity_hash (not altered relative to the hash)"
|
|
306
|
+
if match
|
|
307
|
+
else "MISMATCH: recomputed hash differs from stated integrity_hash (payload was altered)"
|
|
308
|
+
)
|
|
309
|
+
return {
|
|
310
|
+
"match": match,
|
|
311
|
+
"stated_integrity_hash": stated,
|
|
312
|
+
"recomputed_integrity_hash": recomputed,
|
|
313
|
+
"covered_fields": COVERED,
|
|
314
|
+
"signature_verified": False,
|
|
315
|
+
"signing_status": SIGNING_STATUS,
|
|
316
|
+
"note": "integrity hash is key-free; it confirms the payload matches the recorded hash, not who issued it or when",
|
|
317
|
+
"reason": reason,
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _result(match: bool, stated: Any, reason: str) -> dict[str, Any]:
|
|
322
|
+
return {
|
|
323
|
+
"match": match,
|
|
324
|
+
"stated_integrity_hash": stated,
|
|
325
|
+
"recomputed_integrity_hash": None,
|
|
326
|
+
"covered_fields": COVERED,
|
|
327
|
+
"signature_verified": False,
|
|
328
|
+
"signing_status": SIGNING_STATUS,
|
|
329
|
+
"note": "integrity hash is key-free; it confirms the payload matches the recorded hash, not who issued it or when",
|
|
330
|
+
"reason": reason,
|
|
331
|
+
}
|