tup-verify 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.
@@ -0,0 +1,157 @@
1
+ Metadata-Version: 2.4
2
+ Name: tup-verify
3
+ Version: 0.1.0
4
+ Summary: Independent verifier of TUP signed messages and hash-chained audit logs: one file, Python standard library only
5
+ Author-email: Zhofri Guaman <telepathy@telepathy-tup.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://telepathy-tup.com
8
+ Project-URL: Source, https://github.com/telepathy-TUP/tup-mcp-server/tree/main/tup-verify
9
+ Project-URL: Specification, https://github.com/telepathy-TUP/tup-mcp-server/blob/main/spec/FORMAT.md
10
+ Project-URL: Changelog, https://github.com/telepathy-TUP/tup-mcp-server/blob/main/CHANGELOG.md
11
+ Project-URL: Issues, https://github.com/telepathy-TUP/tup-mcp-server/issues
12
+ Project-URL: Security, https://github.com/telepathy-TUP/tup-mcp-server/blob/main/SECURITY.md
13
+ Keywords: ed25519,audit-log,hash-chain,verification,agents
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Topic :: Security :: Cryptography
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ License-File: NOTICE
25
+ Provides-Extra: fast
26
+ Requires-Dist: cryptography>=41; extra == "fast"
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # tup-verify
32
+
33
+ An independent verifier of TUP signed messages and hash-chained audit logs. It is one file,
34
+ [tup_verify.py](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/tup-verify/tup_verify.py), and needs only the Python standard library.
35
+
36
+ It shares no code with TUP-MCP or tup-trust: it was written from [spec/FORMAT.md](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/spec/FORMAT.md). An
37
+ auditor, a partner or a customer can check a TUP-MCP audit log without installing TUP or trusting its code.
38
+ The tests check that both implementations give the same verdict on the same files.
39
+
40
+ **Status:** version 0.1.0, not on PyPI. Licensed under Apache-2.0.
41
+
42
+ ## Install
43
+
44
+ Python 3.11 or later. There are three ways:
45
+
46
+ ```bash
47
+ python tup_verify.py selftest # copy the file and run it, nothing to install
48
+ pip install ./tup-verify # adds the command tup-verify
49
+ pip install "./tup-verify[fast]" # also installs cryptography, for faster Ed25519
50
+ ```
51
+
52
+ Without `cryptography` it uses its own pure-Python Ed25519 (RFC 8032). On this machine that takes about 2.6 ms
53
+ per signature, against 0.3 ms with `cryptography`. Both apply the same strict rules (FORMAT.md 3.4).
54
+
55
+ ## Commands
56
+
57
+ ### Audit log
58
+
59
+ ```bash
60
+ tup-verify log audit.jsonl --key <writer's public key> --head <head saved elsewhere> --peers trusted_keys.json
61
+ ```
62
+
63
+ | Option | What it adds |
64
+ |---|---|
65
+ | `--key` | Every record must be signed by the log's writer: 64 hex characters, or a `public_key.pem` file. Without it, anyone who can edit the file can rebuild a consistent chain |
66
+ | `--head` | A head hash saved outside the writer's reach. Without it, deleting the last records goes unnoticed |
67
+ | `--peers` | TUP-MCP's `trusted_keys.json` (agent → list of keys). The messages in `received` records must be signed with the key pinned for their sender |
68
+ | `--chain-only` | Skip the signed messages kept in `sent` and `received` records |
69
+ | `--json` | Print the result as JSON |
70
+ | `--backend` | Force `cryptography` or `python` |
71
+
72
+ The audit log from [spec/vectors.json](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/spec/vectors.json), with every option:
73
+
74
+ ```
75
+ log: audit.jsonl
76
+ chain: OK, 3 records, every hash links to the previous one
77
+ signatures: every record is signed with the writer's key
78
+ truncation: the saved head is in the chain
79
+ head: count 3, hash 196a1d8dc707eb62c63dedb0eb46e259df635b782941bf36c70e7fb5d2d46353
80
+ messages: 1 kept in sent/received records, all with a valid signature
81
+ signed with a key you gave (--key for sent, --peers for received): 1 of 1
82
+ RESULT: VERIFIED
83
+ ```
84
+
85
+ The same log without options ends in
86
+ `RESULT: VERIFIED IN PART (no --key, no --head, messages with keys you did not give: see above)`.
87
+ A log with one changed character ends in `chain: BROKEN at line N` and `RESULT: NOT VERIFIED`.
88
+
89
+ ### One message
90
+
91
+ ```bash
92
+ tup-verify message msg.json --key <sender's public key> [--sender alice] [--recipient bob]
93
+ tup-verify message msg.json --peers trusted_keys.json
94
+ ```
95
+
96
+ You must say whose key to expect, with `--key` or `--peers`. A message that is only signed with the key it
97
+ carries proves nothing about who sent it.
98
+
99
+ ### Self-test
100
+
101
+ ```bash
102
+ tup-verify selftest
103
+ ```
104
+
105
+ It checks this machine's Ed25519 and JSON against known answers: RFC 8032 tests 1 to 3, an altered message,
106
+ a signature with S + L, and the canonical form of a record.
107
+
108
+ ## Exit codes
109
+
110
+ | Code | Meaning |
111
+ |---|---|
112
+ | 0 | Every check that ran passed. The report says which checks did not run |
113
+ | 1 | Not verified. The report gives the line and the reason |
114
+ | 2 | Input error: the file cannot be read, a key is invalid, an option is missing |
115
+
116
+ ## What it does not check
117
+
118
+ - **Replay and the time window.** The receiver checked them when it accepted the message. Offline there is
119
+ no way to know which nonces it had already seen.
120
+ - **Revocation.** It does not read revocation lists. If a key was revoked, remove it from the file you give
121
+ to `--peers`.
122
+ - **Logs in the old format** (16-character hashes) are accepted only without `--key`. That format had no
123
+ signatures.
124
+
125
+ ## Tests
126
+
127
+ ```bash
128
+ cd tup-verify
129
+ python -m pytest
130
+ ```
131
+
132
+ 32 passed. The tests cover the RFC 8032 vectors and non-canonical encodings on both backends. They check that
133
+ the two backends agree on 60 random signatures, and they run the vectors in spec/vectors.json. They also make
134
+ 18 kinds of edits to a log and check that tup-trust stops at the same line. Some of the tests need
135
+ `cryptography` and tup-trust, to create keys and compare. The verifier itself does not need them.
136
+
137
+ ## License
138
+
139
+ Apache-2.0. See [LICENSE](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/tup-verify/LICENSE) and [NOTICE](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/tup-verify/NOTICE). Copyright 2026 Zhofri Guaman.
140
+
141
+ The Ed25519 functions follow the Python illustration in RFC 8032. That code keeps the IETF Trust's
142
+ Revised BSD License, reproduced in `tup_verify.py` and at the end of [LICENSE](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/tup-verify/LICENSE).
143
+
144
+ ---
145
+
146
+ ## Resumen en español
147
+
148
+ tup-verify comprueba registros de auditoría y mensajes firmados de TUP sin instalar TUP. Es un solo archivo y
149
+ solo usa la biblioteca estándar de Python. Se escribió a partir de [spec/FORMAT.md](https://github.com/telepathy-TUP/tup-mcp-server/blob/main/spec/FORMAT.md), sin
150
+ compartir código con TUP-MCP ni con tup-trust.
151
+
152
+ - `tup-verify log audit.jsonl --key <clave del autor> --head <cabeza guardada aparte> --peers trusted_keys.json`
153
+ comprueba la cadena, las firmas de cada registro, que no falte el final y la firma de cada mensaje guardado.
154
+ - Sin `--key` o sin `--head`, el resultado es "VERIFIED IN PART" y el informe dice qué faltó.
155
+ - Código de salida: 0 verificado, 1 no verificado y 2 error de entrada.
156
+ - No comprueba replay ni revocación: eso lo hace quien recibe el mensaje.
157
+ - Licencia Apache-2.0. El código Ed25519 que sigue al RFC 8032 conserva además el aviso BSD del IETF Trust.
@@ -0,0 +1,8 @@
1
+ tup_verify.py,sha256=XCtwZkN6hjy-rD5Qc1be63wlc0MYiUkP3UICiUwyN_s,29267
2
+ tup_verify-0.1.0.dist-info/licenses/LICENSE,sha256=j8nrmyTqBFSFZ_FTvLD_soIp6Rya3QaOy9GSqmkCGMk,13195
3
+ tup_verify-0.1.0.dist-info/licenses/NOTICE,sha256=qThkgqBoLjQeFSQSHGYEIE5nzTg92xPMV6evjdnToCg,293
4
+ tup_verify-0.1.0.dist-info/METADATA,sha256=waJh_1dudIzTTDzlijaHpbluI0EHdZoN9CFNsytWTpQ,7402
5
+ tup_verify-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ tup_verify-0.1.0.dist-info/entry_points.txt,sha256=RYTPMfqt9zmdUSrr8A3On3a50ycAW8OPP5kSRobYCw8,47
7
+ tup_verify-0.1.0.dist-info/top_level.txt,sha256=orGSzbLO-ALYcMNCVE2tccWxX-31DxVMeSuAYwE8mSg,11
8
+ tup_verify-0.1.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
+ tup-verify = tup_verify:main
@@ -0,0 +1,237 @@
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.
203
+
204
+ -------------------------------------------------------------------------------
205
+
206
+ THIRD-PARTY CODE IN tup_verify.py
207
+
208
+ The Ed25519 functions in tup_verify.py follow the Python illustration in RFC 8032,
209
+ section 6. Code taken from an RFC is a Code Component, licensed as follows:
210
+
211
+ Copyright (c) 2017 IETF Trust and the persons identified as authors of the code.
212
+ All rights reserved.
213
+
214
+ Redistribution and use in source and binary forms, with or without modification,
215
+ are permitted provided that the following conditions are met:
216
+
217
+ - Redistributions of source code must retain the above copyright notice, this
218
+ list of conditions and the following disclaimer.
219
+
220
+ - Redistributions in binary form must reproduce the above copyright notice, this
221
+ list of conditions and the following disclaimer in the documentation and/or
222
+ other materials provided with the distribution.
223
+
224
+ - Neither the name of Internet Society, IETF or IETF Trust, nor the names of
225
+ specific contributors, may be used to endorse or promote products derived from
226
+ this software without specific prior written permission.
227
+
228
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
229
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
230
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
231
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
232
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
233
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
234
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
235
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
236
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
237
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,6 @@
1
+ tup-verify
2
+ Copyright 2026 Zhofri Guaman
3
+
4
+ This product includes code from RFC 8032 (Edwards-Curve Digital Signature Algorithm),
5
+ Copyright (c) 2017 IETF Trust and the persons identified as authors of the code,
6
+ under the Revised BSD License reproduced at the end of LICENSE and in tup_verify.py.
@@ -0,0 +1 @@
1
+ tup_verify
tup_verify.py ADDED
@@ -0,0 +1,646 @@
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Zhofri Guaman
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ # The Ed25519 section below also carries the Revised BSD License of RFC 8032's code.
5
+ """
6
+ tup-verify: independent verifier of TUP signed messages and audit logs.
7
+
8
+ It re-implements the checks of the specification (spec/FORMAT.md, version 1) with the
9
+ Python standard library and imports neither tup-trust nor TUP-MCP, so anyone can check a
10
+ log without installing TUP or trusting its authors. Ed25519 uses the `cryptography`
11
+ package when it is installed and otherwise a pure-Python implementation of RFC 8032
12
+ verification (slower: milliseconds per signature). Both apply the same strict rules.
13
+
14
+ tup-verify log audit.jsonl --key WRITER_KEY [--head HASH] [--peers trusted_keys.json]
15
+ tup-verify message signed.json --key SENDER_KEY [--sender ID] [--recipient ID]
16
+ tup-verify selftest
17
+
18
+ A key is 64 hex characters or the path of a public_key.pem file. Exit status: 0 verified,
19
+ 1 not verified, 2 bad usage or unreadable input. Add --json for machine-readable output.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import base64
26
+ import binascii
27
+ import functools
28
+ import hashlib
29
+ import io
30
+ import json
31
+ import os
32
+ import re
33
+ import sys
34
+ from typing import Any, Optional
35
+
36
+ __version__ = "0.1.0"
37
+
38
+ GENESIS = "GENESIS"
39
+ MSG_DOMAIN = b"TUP-MSG-v1.2\x00"
40
+ LEGACY_HASH_LEN = 16
41
+ MESSAGE_FIELDS = ("payload", "timestamp", "signature", "public_key", "version",
42
+ "sender_id", "nonce", "recipient")
43
+ SIGNED_FIELDS = ("payload", "timestamp", "version", "sender_id", "public_key", "nonce")
44
+
45
+ _HEX64 = re.compile(r"[0-9a-f]{64}")
46
+ _HEX128 = re.compile(r"[0-9a-f]{128}")
47
+ _INVALID_UTF8 = re.compile("[\udc80-\udcff]") # bytes that were not UTF-8 (surrogateescape)
48
+ _SPKI_ED25519 = bytes.fromhex("302a300506032b6570032100") # DER prefix of an Ed25519 public key
49
+
50
+
51
+ class InputError(Exception):
52
+ """Unusable input: a bad key, a missing file, an unreadable peers file (exit status 2)."""
53
+
54
+
55
+ # ------------------------------------------------------------------ Ed25519 (RFC 8032)
56
+ #
57
+ # _recover_x, _decode_point, _add, _mul, _same_point and _BASE follow the Python illustration
58
+ # in RFC 8032, section 6 (S. Josefsson and I. Liusvaara), and the self-test uses its test
59
+ # vectors from section 7.1. Code taken from an RFC is a Code Component, used under the
60
+ # Revised BSD License of the IETF Trust:
61
+ #
62
+ # Copyright (c) 2017 IETF Trust and the persons identified as authors of the code.
63
+ # All rights reserved.
64
+ #
65
+ # Redistribution and use in source and binary forms, with or without modification, are
66
+ # permitted provided that the following conditions are met:
67
+ #
68
+ # - Redistributions of source code must retain the above copyright notice, this list of
69
+ # conditions and the following disclaimer.
70
+ # - Redistributions in binary form must reproduce the above copyright notice, this list
71
+ # of conditions and the following disclaimer in the documentation and/or other
72
+ # materials provided with the distribution.
73
+ # - Neither the name of Internet Society, IETF or IETF Trust, nor the names of specific
74
+ # contributors, may be used to endorse or promote products derived from this software
75
+ # without specific prior written permission.
76
+ #
77
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
78
+ # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
79
+ # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
80
+ # THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
81
+ # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
82
+ # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
83
+ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
84
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
85
+ # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
86
+
87
+ _P = 2 ** 255 - 19
88
+ _L = 2 ** 252 + 27742317777372353535851937790883648493
89
+ _D = -121665 * pow(121666, _P - 2, _P) % _P
90
+ _SQRT_M1 = pow(2, (_P - 1) // 4, _P)
91
+
92
+
93
+ def _recover_x(y: int, sign: int) -> Optional[int]:
94
+ if y >= _P:
95
+ return None
96
+ x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P
97
+ if x2 == 0:
98
+ return None if sign else 0
99
+ x = pow(x2, (_P + 3) // 8, _P)
100
+ if (x * x - x2) % _P != 0:
101
+ x = x * _SQRT_M1 % _P
102
+ if (x * x - x2) % _P != 0:
103
+ return None
104
+ if x & 1 != sign:
105
+ x = _P - x
106
+ return x
107
+
108
+
109
+ @functools.lru_cache(maxsize=256)
110
+ def _decode_point(data: bytes):
111
+ """Extended coordinates of a canonical point encoding, or None (RFC 8032, 5.1.3)."""
112
+ if len(data) != 32:
113
+ return None
114
+ y = int.from_bytes(data, "little")
115
+ sign = y >> 255
116
+ y &= (1 << 255) - 1
117
+ x = _recover_x(y, sign)
118
+ if x is None:
119
+ return None
120
+ return (x, y, 1, x * y % _P)
121
+
122
+
123
+ def _add(p, q):
124
+ x1, y1, z1, t1 = p
125
+ x2, y2, z2, t2 = q
126
+ a = (y1 - x1) * (y2 - x2) % _P
127
+ b = (y1 + x1) * (y2 + x2) % _P
128
+ c = 2 * t1 * t2 * _D % _P
129
+ d = 2 * z1 * z2 % _P
130
+ e, f, g, h = b - a, d - c, d + c, b + a
131
+ return (e * f % _P, g * h % _P, f * g % _P, e * h % _P)
132
+
133
+
134
+ def _mul(s: int, p):
135
+ q = (0, 1, 1, 0)
136
+ while s:
137
+ if s & 1:
138
+ q = _add(q, p)
139
+ p = _add(p, p)
140
+ s >>= 1
141
+ return q
142
+
143
+
144
+ def _same_point(p, q) -> bool:
145
+ return (p[0] * q[2] - q[0] * p[2]) % _P == 0 and (p[1] * q[2] - q[1] * p[2]) % _P == 0
146
+
147
+
148
+ _BASE = _decode_point((4 * pow(5, _P - 2, _P) % _P).to_bytes(32, "little"))
149
+
150
+ try:
151
+ from cryptography.exceptions import InvalidSignature as _InvalidSignature
152
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey as _CryptoKey
153
+ except ImportError: # the pure-Python code above is used instead
154
+ _CryptoKey = None
155
+
156
+
157
+ def available_backends() -> list:
158
+ return ["cryptography", "python"] if _CryptoKey is not None else ["python"]
159
+
160
+
161
+ def ed25519_verify(public_key: bytes, message: bytes, signature: bytes,
162
+ backend: Optional[str] = None) -> bool:
163
+ """Strict Ed25519 verification (FORMAT.md 3.4). Both backends give the same answer."""
164
+ if len(public_key) != 32 or len(signature) != 64:
165
+ return False
166
+ a = _decode_point(bytes(public_key))
167
+ r = _decode_point(bytes(signature[:32]))
168
+ s = int.from_bytes(signature[32:], "little")
169
+ if a is None or r is None or s >= _L: # non-canonical encodings and S >= L
170
+ return False
171
+ backend = backend or available_backends()[0]
172
+ if backend == "cryptography":
173
+ if _CryptoKey is None:
174
+ raise InputError("the cryptography package is not installed")
175
+ try:
176
+ _CryptoKey.from_public_bytes(bytes(public_key)).verify(bytes(signature), message)
177
+ return True
178
+ except _InvalidSignature:
179
+ return False
180
+ if backend != "python":
181
+ raise InputError(f"unknown Ed25519 backend {backend!r}")
182
+ k = int.from_bytes(hashlib.sha512(signature[:32] + public_key + message).digest(), "little") % _L
183
+ return _same_point(_mul(s, _BASE), _add(r, _mul(k, a)))
184
+
185
+
186
+ # ------------------------------------------------------------------ canonical JSON (FORMAT.md 2)
187
+
188
+ def _no_duplicates(pairs):
189
+ obj = {}
190
+ for key, value in pairs:
191
+ if key in obj:
192
+ raise ValueError(f"duplicate key {key[:40]!r}")
193
+ obj[key] = value
194
+ return obj
195
+
196
+
197
+ def _no_constant(name):
198
+ raise ValueError(f"non-standard number {name}")
199
+
200
+
201
+ def parse_json(text: str) -> Any:
202
+ """Strict JSON: duplicate keys, NaN and Infinity are errors."""
203
+ return json.loads(text, object_pairs_hook=_no_duplicates, parse_constant=_no_constant)
204
+
205
+
206
+ def message_form(value: Any) -> str:
207
+ """Canonical form of signed messages (FORMAT.md 2.1)."""
208
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False)
209
+
210
+
211
+ def record_form(value: Any) -> str:
212
+ """Canonical form of audit records (FORMAT.md 2.2)."""
213
+ return json.dumps(value, sort_keys=True, ensure_ascii=True, allow_nan=False)
214
+
215
+
216
+ def record_hash(record: dict) -> str:
217
+ """SHA-256 of a record without its hash and sig members (FORMAT.md 5.2)."""
218
+ body = {k: v for k, v in record.items() if k not in ("hash", "sig")}
219
+ return hashlib.sha256(record_form(body).encode("utf-8")).hexdigest()
220
+
221
+
222
+ # ------------------------------------------------------------------ keys
223
+
224
+ def normalize_key(value: Any) -> str:
225
+ """Canonical form of a public key: 64 lowercase hex characters. Raises ValueError."""
226
+ if not isinstance(value, str) or not _HEX64.fullmatch(value.strip().lower()):
227
+ raise ValueError("an Ed25519 public key is 64 hex characters")
228
+ return value.strip().lower()
229
+
230
+
231
+ def load_key(value: str) -> str:
232
+ """A key given as 64 hex characters, or as a file: public_key.pem or a text file with the hex."""
233
+ try:
234
+ return normalize_key(value)
235
+ except ValueError:
236
+ pass
237
+ if not os.path.isfile(value):
238
+ raise InputError(f"not a 64-character hex key, nor an existing file: {value[:80]!r}")
239
+ try:
240
+ with open(value, "r", encoding="ascii", errors="replace") as f:
241
+ content = f.read().strip()
242
+ except OSError as e:
243
+ raise InputError(f"cannot read {value}: {e.strerror or e}") from e
244
+ try:
245
+ return normalize_key(content)
246
+ except ValueError:
247
+ pass
248
+ match = re.search(r"-----BEGIN PUBLIC KEY-----(.*?)-----END PUBLIC KEY-----", content, re.S)
249
+ if not match:
250
+ raise InputError(f"{value}: neither a PEM public key nor a hex key")
251
+ try:
252
+ der = base64.b64decode("".join(match.group(1).split()), validate=True)
253
+ except binascii.Error as e:
254
+ raise InputError(f"{value}: bad PEM ({e})") from e
255
+ if len(der) != 44 or not der.startswith(_SPKI_ED25519):
256
+ raise InputError(f"{value}: not an Ed25519 public key")
257
+ return der[len(_SPKI_ED25519):].hex()
258
+
259
+
260
+ def load_peers(path: str) -> dict:
261
+ """TUP-MCP's trusted_keys.json: {"agent_id": ["public key hex", ...]}."""
262
+ try:
263
+ with open(path, encoding="utf-8") as f:
264
+ data = parse_json(f.read())
265
+ except (OSError, ValueError) as e:
266
+ raise InputError(f"cannot read the peers file {path}: {e}") from e
267
+ if not isinstance(data, dict) or not all(isinstance(v, list) for v in data.values()):
268
+ raise InputError(f"{path} must map agent ids to lists of public keys")
269
+ peers = {}
270
+ for agent, keys in data.items():
271
+ try:
272
+ peers[agent] = {normalize_key(k) for k in keys}
273
+ except ValueError as e:
274
+ raise InputError(f"{path}: bad key for {agent!r}") from e
275
+ return peers
276
+
277
+
278
+ # ------------------------------------------------------------------ signed messages (FORMAT.md 3)
279
+
280
+ def check_message(msg: Any, backend: Optional[str] = None) -> Optional[str]:
281
+ """
282
+ The offline checks of FORMAT.md 3.3: None if the message is well formed and signed with
283
+ the key it names, otherwise the reason. Who holds that key is a separate question.
284
+ """
285
+ if not isinstance(msg, dict):
286
+ return "the message is not a JSON object"
287
+ missing = [name for name in MESSAGE_FIELDS if name not in msg]
288
+ if missing:
289
+ return f"missing members: {', '.join(missing)}"
290
+ for name in MESSAGE_FIELDS[1:]:
291
+ if not isinstance(msg[name], str):
292
+ return f"member {name} is not a string"
293
+ if not msg["sender_id"]:
294
+ return "empty sender_id"
295
+ try:
296
+ key = normalize_key(msg["public_key"])
297
+ except ValueError:
298
+ return "public_key is not 64 hex characters"
299
+ if not _HEX128.fullmatch(msg["signature"].lower()):
300
+ return "signature is not 128 hex characters"
301
+ content = {name: msg[name] for name in SIGNED_FIELDS}
302
+ if msg["recipient"]:
303
+ content["recipient"] = msg["recipient"]
304
+ try:
305
+ signed = MSG_DOMAIN + message_form(content).encode("utf-8")
306
+ except (ValueError, RecursionError) as e:
307
+ return f"the message cannot be serialized ({type(e).__name__})"
308
+ if not ed25519_verify(bytes.fromhex(key), signed, bytes.fromhex(msg["signature"]), backend):
309
+ return "invalid signature"
310
+ return None
311
+
312
+
313
+ def check_recorded_message(record: dict, writer_key: Optional[str], peers: Optional[dict],
314
+ backend: Optional[str] = None):
315
+ """
316
+ (problem or None, pinned) for the signed message a TUP-MCP "sent" or "received" record
317
+ keeps (FORMAT.md 6). `pinned` is True when its key is the writer's (--key) for a sent
318
+ message, or the one --peers pins for the sender of a received message.
319
+ """
320
+ msg = record.get("message")
321
+ problem = check_message(msg, backend)
322
+ if problem:
323
+ return problem, False
324
+ key = normalize_key(msg["public_key"])
325
+ agent = record.get("agent")
326
+ if record.get("event") == "received":
327
+ if msg["sender_id"] != record.get("sender"):
328
+ return f"sender_id {msg['sender_id']!r} is not the record's sender", False
329
+ if agent is not None and msg["recipient"] != agent:
330
+ return f"addressed to {msg['recipient']!r}, not to the log's agent {agent!r}", False
331
+ if peers is None:
332
+ return None, False
333
+ if key not in peers.get(msg["sender_id"], set()):
334
+ return f"signed with a key that --peers does not pin for {msg['sender_id']!r}", False
335
+ return None, True
336
+ if agent is not None and msg["sender_id"] != agent:
337
+ return f"a sent message signed as {msg['sender_id']!r}, not as the log's agent {agent!r}", False
338
+ if msg["recipient"] != record.get("recipient"):
339
+ return f"addressed to {msg['recipient']!r}, not to the record's recipient", False
340
+ if writer_key is None:
341
+ return None, False
342
+ if key != writer_key:
343
+ return "a sent message signed with a key other than the writer's (--key)", False
344
+ return None, True
345
+
346
+
347
+ # ------------------------------------------------------------------ audit logs (FORMAT.md 5)
348
+
349
+ def verify_log(path: str, key: Optional[str] = None, head: Optional[str] = None,
350
+ peers: Optional[dict] = None, backend: Optional[str] = None,
351
+ check_messages: bool = True, allow_legacy: bool = True) -> dict:
352
+ """
353
+ Verifies an audit log as FORMAT.md 5.4 says, plus the signed messages that TUP-MCP's
354
+ "sent" and "received" records keep (FORMAT.md 6) unless check_messages is False.
355
+ `key` is the writer's public key in canonical hex. Raises InputError if the file
356
+ cannot be read.
357
+ """
358
+ try:
359
+ with open(path, "rb") as f:
360
+ data = f.read()
361
+ except OSError as e:
362
+ raise InputError(f"cannot read {path}: {e.strerror or e}") from e
363
+ pub = bytes.fromhex(key) if key else None
364
+ messages = {"checked": 0, "pinned": 0, "failed": 0, "first_failure": None}
365
+ result = {"file": path, "ok": False, "chain_ok": False, "records": 0,
366
+ "head": {"count": 0, "hash": GENESIS}, "error": None, "line": None,
367
+ "signatures_checked": pub is not None, "head_checked": head is not None,
368
+ "messages": messages}
369
+ prev, count, seen_head = GENESIS, 0, head is None
370
+
371
+ def broken(lineno: Optional[int], why: str) -> dict:
372
+ result.update(records=count, head={"count": count, "hash": prev}, error=why, line=lineno)
373
+ return result
374
+
375
+ text = data.decode("utf-8", "surrogateescape")
376
+ for lineno, line in enumerate(io.StringIO(text, newline=None), start=1):
377
+ if not line.strip():
378
+ continue
379
+ if _INVALID_UTF8.search(line):
380
+ return broken(lineno, "not valid UTF-8")
381
+ try:
382
+ record = parse_json(line)
383
+ except (ValueError, RecursionError) as e:
384
+ return broken(lineno, f"invalid JSON ({e})")
385
+ if not isinstance(record, dict):
386
+ return broken(lineno, "not a JSON object")
387
+ stored = record.get("hash")
388
+ if not isinstance(stored, str) or not stored:
389
+ return broken(lineno, "no hash member")
390
+ if record.get("prev_hash") != prev:
391
+ return broken(lineno, "prev_hash does not link to the previous record")
392
+ try:
393
+ expected = record_hash(record)
394
+ except (ValueError, RecursionError) as e:
395
+ return broken(lineno, f"the record cannot be serialized ({type(e).__name__})")
396
+ if len(stored) == LEGACY_HASH_LEN and allow_legacy and pub is None:
397
+ expected = expected[:LEGACY_HASH_LEN]
398
+ if stored != expected:
399
+ return broken(lineno, "hash does not match: the record was altered")
400
+ if pub is not None:
401
+ sig = record.get("sig")
402
+ if not (isinstance(sig, str) and _HEX128.fullmatch(sig.lower())
403
+ and ed25519_verify(pub, bytes.fromhex(stored), bytes.fromhex(sig), backend)):
404
+ return broken(lineno, "signature missing or not made with the writer's key")
405
+ if stored == head:
406
+ seen_head = True
407
+ prev, count = stored, count + 1
408
+ if check_messages and record.get("event") in ("sent", "received"):
409
+ problem, pinned = check_recorded_message(record, key, peers, backend)
410
+ messages["checked"] += 1
411
+ messages["pinned"] += int(pinned)
412
+ if problem:
413
+ messages["failed"] += 1
414
+ if messages["first_failure"] is None:
415
+ messages["first_failure"] = {"line": lineno, "error": problem}
416
+
417
+ result.update(records=count, head={"count": count, "hash": prev})
418
+ if not seen_head:
419
+ result["error"] = "the saved head is not in the chain: the log was truncated or rewritten"
420
+ return result
421
+ result["chain_ok"] = True
422
+ if messages["failed"]:
423
+ result.update(error=f"a recorded message does not verify: {messages['first_failure']['error']}",
424
+ line=messages["first_failure"]["line"])
425
+ return result
426
+ result["ok"] = True
427
+ return result
428
+
429
+
430
+ def verify_message_file(path: str, key: Optional[str], peers: Optional[dict],
431
+ sender: Optional[str] = None, recipient: Optional[str] = None,
432
+ backend: Optional[str] = None) -> dict:
433
+ """Checks one signed message and that its key is the given one, or pinned for its sender."""
434
+ try:
435
+ with open(path, encoding="utf-8") as f:
436
+ msg = parse_json(f.read())
437
+ except (OSError, ValueError) as e:
438
+ raise InputError(f"cannot read the message {path}: {e}") from e
439
+ result = {"file": path, "ok": False, "error": None}
440
+ problem = check_message(msg, backend)
441
+ if problem is None:
442
+ result.update(sender_id=msg["sender_id"], recipient=msg["recipient"],
443
+ timestamp=msg["timestamp"], public_key=normalize_key(msg["public_key"]))
444
+ if key is not None and result["public_key"] != key:
445
+ problem = "signed with a key other than the one given with --key"
446
+ elif key is None and result["public_key"] not in peers.get(msg["sender_id"], set()):
447
+ problem = f"signed with a key that --peers does not pin for {msg['sender_id']!r}"
448
+ elif sender is not None and msg["sender_id"] != sender:
449
+ problem = f"sent by {msg['sender_id']!r}, not by {sender!r}"
450
+ elif recipient is not None and msg["recipient"] != recipient:
451
+ problem = f"addressed to {msg['recipient']!r}, not to {recipient!r}"
452
+ result["ok"] = problem is None
453
+ result["error"] = problem
454
+ return result
455
+
456
+
457
+ # ------------------------------------------------------------------ self-test
458
+
459
+ # RFC 8032, section 7.1, tests 1 to 3: (public key, message, signature)
460
+ _RFC8032 = [
461
+ ("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
462
+ "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
463
+ ("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72",
464
+ "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
465
+ ("fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", "af82",
466
+ "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"),
467
+ ]
468
+ # Record form of {"b": [1.0, 1e16, -0.0, 9007199254740993], "a": "ñ👋"} and its SHA-256 (FORMAT.md 2)
469
+ _CANONICAL = ('{"a": "\\u00f1\\ud83d\\udc4b", "b": [1.0, 1e+16, -0.0, 9007199254740993]}',
470
+ "c70b4a8230bddf8a352aaa037d38ef09e546d13fc1a4d3a59fcf36e12a50f4a1")
471
+
472
+
473
+ def selftest() -> dict:
474
+ """Checks this machine's Ed25519 backends and JSON encoder against known answers."""
475
+ failures = []
476
+ for backend in available_backends():
477
+ for public, message, signature in _RFC8032:
478
+ pk, msg, sig = bytes.fromhex(public), bytes.fromhex(message), bytes.fromhex(signature)
479
+ if not ed25519_verify(pk, msg, sig, backend):
480
+ failures.append(f"{backend}: RFC 8032 vector rejected")
481
+ if ed25519_verify(pk, msg + b"x", sig, backend):
482
+ failures.append(f"{backend}: altered message accepted")
483
+ s = int.from_bytes(sig[32:], "little") + _L
484
+ if s < 2 ** 256 and ed25519_verify(pk, msg, sig[:32] + s.to_bytes(32, "little"), backend):
485
+ failures.append(f"{backend}: signature with S + L accepted")
486
+ value = {"b": [1.0, 1e16, -0.0, 9007199254740993], "a": "ñ👋"}
487
+ if record_form(value) != _CANONICAL[0]:
488
+ failures.append("this Python serializes JSON differently from FORMAT.md section 2")
489
+ elif hashlib.sha256(_CANONICAL[0].encode("ascii")).hexdigest() != _CANONICAL[1]:
490
+ failures.append("SHA-256 gives an unexpected result")
491
+ return {"ok": not failures, "backends": available_backends(), "failures": failures}
492
+
493
+
494
+ # ------------------------------------------------------------------ command line
495
+
496
+ def _short(h: str) -> str:
497
+ return f"{h[:8]}…{h[-4:]}" if isinstance(h, str) and len(h) > 16 else str(h)
498
+
499
+
500
+ def _records(n: int) -> str:
501
+ return f"{n} record" if n == 1 else f"{n} records"
502
+
503
+
504
+ def _print_log(result: dict, out) -> None:
505
+ w = functools.partial(print, file=out)
506
+ n = result["records"]
507
+ w(f"log: {result['file']}")
508
+ if result["chain_ok"]:
509
+ w(f"chain: OK, {_records(n)}, every hash links to the previous one")
510
+ else:
511
+ where = f" at line {result['line']}" if result["line"] else ""
512
+ w(f"chain: BROKEN{where}: {result['error']}")
513
+ w(f" valid before that point: {_records(n)}")
514
+ if not result["signatures_checked"]:
515
+ w("signatures: NOT CHECKED. Without --key, anyone who can edit the file can rebuild a "
516
+ "consistent chain")
517
+ elif not n:
518
+ w("signatures: no valid record to check")
519
+ elif result["chain_ok"]:
520
+ w("signatures: every record is signed with the writer's key")
521
+ else:
522
+ w("signatures: every record before the break is signed with the writer's key")
523
+ if result["head_checked"]:
524
+ w("truncation: the saved head is in the chain" if result["chain_ok"] else
525
+ "truncation: not decided (the chain is broken)")
526
+ else:
527
+ w("truncation: NOT CHECKED. Pass a head saved elsewhere with --head to detect deleted last records")
528
+ label = "head" if result["chain_ok"] else "head of the valid part"
529
+ w(f"{label}: count {result['head']['count']}, hash {result['head']['hash']}")
530
+ m = result["messages"]
531
+ valid = m["checked"] - m["failed"]
532
+ if m["checked"]:
533
+ state = "all with a valid signature" if not m["failed"] else f"{m['failed']} failed"
534
+ w(f"messages: {m['checked']} kept in sent/received records, {state}")
535
+ if m["first_failure"]:
536
+ w(f" first failure at line {m['first_failure']['line']}: {m['first_failure']['error']}")
537
+ w(f" signed with a key you gave (--key for sent, --peers for received): "
538
+ f"{m['pinned']} of {valid}")
539
+ if valid > m["pinned"]:
540
+ w(f" for the other {valid - m['pinned']}, the signature matches the key in the "
541
+ "message, but nothing here says whose key that is")
542
+ if not result["ok"]:
543
+ w("RESULT: NOT VERIFIED")
544
+ return
545
+ # Exit code 0 means every check that ran passed; say plainly which ones did not run.
546
+ gaps = [gap for gap, missing in (("no --key", not result["signatures_checked"]),
547
+ ("no --head", not result["head_checked"]),
548
+ ("messages with keys you did not give", valid > m["pinned"]))
549
+ if missing]
550
+ w(f"RESULT: VERIFIED IN PART ({', '.join(gaps)}: see above)" if gaps else "RESULT: VERIFIED")
551
+
552
+
553
+ def _print_message(result: dict, out) -> None:
554
+ w = functools.partial(print, file=out)
555
+ w(f"message: {result['file']}")
556
+ if result["ok"]:
557
+ to = repr(result["recipient"]) if result["recipient"] else "nobody in particular"
558
+ w(f"signed by {result['sender_id']!r} with key {_short(result['public_key'])}, "
559
+ f"addressed to {to}, at {result['timestamp']}")
560
+ w("replay and the time window are not checked offline")
561
+ w("RESULT: VERIFIED")
562
+ else:
563
+ w(f"RESULT: NOT VERIFIED: {result['error']}")
564
+
565
+
566
+ def build_parser() -> argparse.ArgumentParser:
567
+ parser = argparse.ArgumentParser(
568
+ prog="tup-verify",
569
+ description="Independent verifier of TUP signed messages and audit logs (spec/FORMAT.md v1).")
570
+ parser.add_argument("--version", action="version", version=f"tup-verify {__version__}")
571
+ sub = parser.add_subparsers(dest="command", required=True)
572
+
573
+ def common(p):
574
+ p.add_argument("--json", action="store_true", help="print the result as JSON")
575
+ p.add_argument("--backend", choices=["cryptography", "python"],
576
+ help="force an Ed25519 implementation (default: cryptography if installed)")
577
+
578
+ log = sub.add_parser("log", help="verify a hash-chained audit log")
579
+ log.add_argument("file")
580
+ log.add_argument("--key", help="the writer's public key: 64 hex characters or a public_key.pem file")
581
+ log.add_argument("--head", help="a head hash saved elsewhere, to detect deleted last records")
582
+ log.add_argument("--peers", help="TUP-MCP trusted_keys.json, to check the senders of received messages")
583
+ log.add_argument("--chain-only", action="store_true",
584
+ help="skip the signed messages kept in sent/received records")
585
+ common(log)
586
+
587
+ msg = sub.add_parser("message", help="verify one signed message (JSON file)")
588
+ msg.add_argument("file")
589
+ msg.add_argument("--key", help="the sender's public key: 64 hex characters or a public_key.pem file")
590
+ msg.add_argument("--peers", help="TUP-MCP trusted_keys.json, instead of --key")
591
+ msg.add_argument("--sender", help="require this sender_id")
592
+ msg.add_argument("--recipient", help="require this recipient")
593
+ common(msg)
594
+
595
+ test = sub.add_parser("selftest", help="check this machine's Ed25519 and JSON against known answers")
596
+ test.add_argument("--json", action="store_true", help="print the result as JSON")
597
+ return parser
598
+
599
+
600
+ def main(argv: Optional[list] = None) -> int:
601
+ for stream in (sys.stdout, sys.stderr):
602
+ try:
603
+ stream.reconfigure(errors="backslashreplace")
604
+ except (AttributeError, ValueError):
605
+ pass
606
+ args = build_parser().parse_args(argv)
607
+ out = sys.stdout
608
+ try:
609
+ if args.command == "selftest":
610
+ result = selftest()
611
+ if args.json:
612
+ print(json.dumps(result, indent=2), file=out)
613
+ else:
614
+ for failure in result["failures"]:
615
+ print(f"FAILED: {failure}", file=out)
616
+ print(f"selftest: {'OK' if result['ok'] else 'FAILED'} "
617
+ f"(Ed25519 backends: {', '.join(result['backends'])})", file=out)
618
+ return 0 if result["ok"] else 1
619
+
620
+ if args.backend and args.backend not in available_backends():
621
+ raise InputError(f"the {args.backend} backend is not available here")
622
+ key = load_key(args.key) if args.key else None
623
+ peers = load_peers(args.peers) if args.peers else None
624
+ if args.command == "log":
625
+ result = verify_log(args.file, key=key, head=args.head.strip().lower() if args.head else None,
626
+ peers=peers, backend=args.backend, check_messages=not args.chain_only)
627
+ printer = _print_log
628
+ else:
629
+ if key is None and peers is None:
630
+ raise InputError("say whose key to expect with --key or --peers: a valid signature "
631
+ "with an unknown key proves nothing about the sender")
632
+ result = verify_message_file(args.file, key, peers, args.sender, args.recipient, args.backend)
633
+ printer = _print_message
634
+ result["backend"] = args.backend or available_backends()[0]
635
+ if args.json:
636
+ print(json.dumps(result, indent=2, ensure_ascii=False), file=out)
637
+ else:
638
+ printer(result, out)
639
+ return 0 if result["ok"] else 1
640
+ except InputError as e:
641
+ print(f"tup-verify: error: {e}", file=sys.stderr)
642
+ return 2
643
+
644
+
645
+ if __name__ == "__main__":
646
+ sys.exit(main())