ledger-verify 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.
- ledger_verify-0.1.0/LICENSE +202 -0
- ledger_verify-0.1.0/MANIFEST.in +7 -0
- ledger_verify-0.1.0/PKG-INFO +97 -0
- ledger_verify-0.1.0/README.md +63 -0
- ledger_verify-0.1.0/examples/audit_demo.py +13 -0
- ledger_verify-0.1.0/pyproject.toml +49 -0
- ledger_verify-0.1.0/setup.cfg +4 -0
- ledger_verify-0.1.0/src/ledger_verify.egg-info/PKG-INFO +97 -0
- ledger_verify-0.1.0/src/ledger_verify.egg-info/SOURCES.txt +17 -0
- ledger_verify-0.1.0/src/ledger_verify.egg-info/dependency_links.txt +1 -0
- ledger_verify-0.1.0/src/ledger_verify.egg-info/entry_points.txt +2 -0
- ledger_verify-0.1.0/src/ledger_verify.egg-info/requires.txt +7 -0
- ledger_verify-0.1.0/src/ledger_verify.egg-info/top_level.txt +1 -0
- ledger_verify-0.1.0/src/ledgerverify/__init__.py +4 -0
- ledger_verify-0.1.0/src/ledgerverify/chain.py +89 -0
- ledger_verify-0.1.0/src/ledgerverify/cli.py +48 -0
- ledger_verify-0.1.0/src/ledgerverify/shred.py +40 -0
- ledger_verify-0.1.0/tests/test_chain.py +83 -0
- ledger_verify-0.1.0/tests/test_shred.py +29 -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,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ledger-verify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tamper-evident hash-chain audit trail verifier: a tiny hash-chained append-only log, a verifier that names the first broken entry, and a crypto-shredding demo.
|
|
5
|
+
Author-email: Aben Consulting <info@aben.ch>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://aben.ch/notes/tamper-evident-audit-trails/
|
|
8
|
+
Project-URL: Source, https://github.com/aben-consulting/ledger-verify
|
|
9
|
+
Project-URL: Issues, https://github.com/aben-consulting/ledger-verify/issues
|
|
10
|
+
Keywords: audit-log,hash-chain,tamper-evident,gdpr,crypto-shredding
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Security
|
|
24
|
+
Classifier: Topic :: System :: Logging
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Provides-Extra: shred
|
|
29
|
+
Requires-Dist: cryptography>=41; extra == "shred"
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Requires-Dist: cryptography>=41; extra == "test"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# ledger-verify
|
|
36
|
+
|
|
37
|
+
A tiny, dependency-free **hash-chained append-only log**, a **verifier that names the first broken entry**, and a **crypto-shredding demo** for GDPR-style erasure. Under 200 lines of library code.
|
|
38
|
+
|
|
39
|
+
It is a teaching/reference implementation of a general pattern, not a production audit system.
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
$ ledger-verify demo
|
|
43
|
+
intact: True
|
|
44
|
+
tampered: first broken entry = 2 (entry content does not match its hash)
|
|
45
|
+
tail removed, no anchor : verifies -> True (undetected without an anchored head)
|
|
46
|
+
tail removed, with anchor: verifies -> False (head differs from the anchored head (tail removed or replaced?))
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Install and run
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
git clone https://github.com/aben-consulting/ledger-verify.git && cd ledger-verify
|
|
53
|
+
pip install -e ".[shred]" # [shred] adds `cryptography` for the erasure demo
|
|
54
|
+
ledger-verify demo
|
|
55
|
+
python examples/audit_demo.py
|
|
56
|
+
pytest -q # pip install -e ".[test]" first
|
|
57
|
+
```
|
|
58
|
+
Python 3.9+. The core (`ledgerverify.chain`) has no dependencies.
|
|
59
|
+
|
|
60
|
+
## How it works
|
|
61
|
+
|
|
62
|
+
Every entry stores `hash = SHA-256(prev_hash | seq | canonical_json(payload))`. Change, reorder or delete an entry in the middle and every later hash stops matching. `verify()` reports the **first** entry that fails and why.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from ledgerverify import Ledger
|
|
66
|
+
l = Ledger()
|
|
67
|
+
l.append({"event": "finding.created", "id": "F-1"})
|
|
68
|
+
anchor = l.head # store this OUTSIDE the log (another system, signed checkpoint…)
|
|
69
|
+
l.append({"event": "finding.approved", "id": "F-1"})
|
|
70
|
+
print(l.verify(expected_head=l.head).ok) # later: l.verify(expected_head=anchor)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
CLI on a JSON Lines file (one entry per line, as written by `Ledger.dump_jsonl`):
|
|
74
|
+
```sh
|
|
75
|
+
ledger-verify verify ledger.jsonl [--head <hash stored elsewhere>]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Crypto-shredding (`ledgerverify.shred`)
|
|
79
|
+
Seal personal fields with a per-subject AES-256-GCM key and put only the ciphertext in the log. To erase a person, destroy their key: the log is unchanged, still verifies, and the data is unreadable.
|
|
80
|
+
|
|
81
|
+
## Threat model — read this
|
|
82
|
+
|
|
83
|
+
| Attack | Detected? |
|
|
84
|
+
|---|---|
|
|
85
|
+
| Edit an entry's content | Yes — names the entry |
|
|
86
|
+
| Delete or reorder an entry in the middle | Yes |
|
|
87
|
+
| Delete the **tail** of the log | **Only** if you pass an externally stored head (`expected_head`) |
|
|
88
|
+
| Rewrite the whole chain consistently | **No** — anchor the head somewhere the attacker can't write |
|
|
89
|
+
| Record a false event in the first place | No — the chain proves immutability, not truth |
|
|
90
|
+
|
|
91
|
+
Not included: persistence beyond JSONL, concurrency/locking, signatures, external timestamping, key wrapping under a KMS/HSM, key backup, rotation. `KeyStore` keeps keys in memory. Data derived from the plaintext (indexes, logs, backups) is outside the protection. Whether crypto-shredding satisfies erasure obligations for you is a question for your legal and compliance advisers.
|
|
92
|
+
|
|
93
|
+
## Contributing & security
|
|
94
|
+
Issues and pull requests are welcome. If you find a flaw in the threat model above, please open an issue — that is the most useful feedback.
|
|
95
|
+
|
|
96
|
+
## Licence
|
|
97
|
+
Apache License 2.0 — see [LICENSE](LICENSE). © Áben Consulting Kft., Budapest. https://aben.ch
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# ledger-verify
|
|
2
|
+
|
|
3
|
+
A tiny, dependency-free **hash-chained append-only log**, a **verifier that names the first broken entry**, and a **crypto-shredding demo** for GDPR-style erasure. Under 200 lines of library code.
|
|
4
|
+
|
|
5
|
+
It is a teaching/reference implementation of a general pattern, not a production audit system.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
$ ledger-verify demo
|
|
9
|
+
intact: True
|
|
10
|
+
tampered: first broken entry = 2 (entry content does not match its hash)
|
|
11
|
+
tail removed, no anchor : verifies -> True (undetected without an anchored head)
|
|
12
|
+
tail removed, with anchor: verifies -> False (head differs from the anchored head (tail removed or replaced?))
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Install and run
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
git clone https://github.com/aben-consulting/ledger-verify.git && cd ledger-verify
|
|
19
|
+
pip install -e ".[shred]" # [shred] adds `cryptography` for the erasure demo
|
|
20
|
+
ledger-verify demo
|
|
21
|
+
python examples/audit_demo.py
|
|
22
|
+
pytest -q # pip install -e ".[test]" first
|
|
23
|
+
```
|
|
24
|
+
Python 3.9+. The core (`ledgerverify.chain`) has no dependencies.
|
|
25
|
+
|
|
26
|
+
## How it works
|
|
27
|
+
|
|
28
|
+
Every entry stores `hash = SHA-256(prev_hash | seq | canonical_json(payload))`. Change, reorder or delete an entry in the middle and every later hash stops matching. `verify()` reports the **first** entry that fails and why.
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from ledgerverify import Ledger
|
|
32
|
+
l = Ledger()
|
|
33
|
+
l.append({"event": "finding.created", "id": "F-1"})
|
|
34
|
+
anchor = l.head # store this OUTSIDE the log (another system, signed checkpoint…)
|
|
35
|
+
l.append({"event": "finding.approved", "id": "F-1"})
|
|
36
|
+
print(l.verify(expected_head=l.head).ok) # later: l.verify(expected_head=anchor)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
CLI on a JSON Lines file (one entry per line, as written by `Ledger.dump_jsonl`):
|
|
40
|
+
```sh
|
|
41
|
+
ledger-verify verify ledger.jsonl [--head <hash stored elsewhere>]
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Crypto-shredding (`ledgerverify.shred`)
|
|
45
|
+
Seal personal fields with a per-subject AES-256-GCM key and put only the ciphertext in the log. To erase a person, destroy their key: the log is unchanged, still verifies, and the data is unreadable.
|
|
46
|
+
|
|
47
|
+
## Threat model — read this
|
|
48
|
+
|
|
49
|
+
| Attack | Detected? |
|
|
50
|
+
|---|---|
|
|
51
|
+
| Edit an entry's content | Yes — names the entry |
|
|
52
|
+
| Delete or reorder an entry in the middle | Yes |
|
|
53
|
+
| Delete the **tail** of the log | **Only** if you pass an externally stored head (`expected_head`) |
|
|
54
|
+
| Rewrite the whole chain consistently | **No** — anchor the head somewhere the attacker can't write |
|
|
55
|
+
| Record a false event in the first place | No — the chain proves immutability, not truth |
|
|
56
|
+
|
|
57
|
+
Not included: persistence beyond JSONL, concurrency/locking, signatures, external timestamping, key wrapping under a KMS/HSM, key backup, rotation. `KeyStore` keeps keys in memory. Data derived from the plaintext (indexes, logs, backups) is outside the protection. Whether crypto-shredding satisfies erasure obligations for you is a question for your legal and compliance advisers.
|
|
58
|
+
|
|
59
|
+
## Contributing & security
|
|
60
|
+
Issues and pull requests are welcome. If you find a flaw in the threat model above, please open an issue — that is the most useful feedback.
|
|
61
|
+
|
|
62
|
+
## Licence
|
|
63
|
+
Apache License 2.0 — see [LICENSE](LICENSE). © Áben Consulting Kft., Budapest. https://aben.ch
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Run: python examples/audit_demo.py (from the repo root, after `pip install -e .[shred]`)"""
|
|
2
|
+
from ledgerverify import Ledger
|
|
3
|
+
from ledgerverify.shred import KeyStore
|
|
4
|
+
|
|
5
|
+
keys, ledger = KeyStore(), Ledger()
|
|
6
|
+
ledger.append({"event": "auditee.registered", "contact_sealed": keys.seal("auditee-7", "Jane Doe <jane@example.com>")})
|
|
7
|
+
ledger.append({"event": "finding.created", "id": "F-1", "rating": "high"})
|
|
8
|
+
print("chain ok:", ledger.verify().ok)
|
|
9
|
+
|
|
10
|
+
print("before erasure:", keys.open("auditee-7", ledger.entries[0]["payload"]["contact_sealed"]))
|
|
11
|
+
keys.erase("auditee-7")
|
|
12
|
+
print("after erasure :", keys.open("auditee-7", ledger.entries[0]["payload"]["contact_sealed"]))
|
|
13
|
+
print("chain still ok:", ledger.verify().ok)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ledger-verify"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Tamper-evident hash-chain audit trail verifier: a tiny hash-chained append-only log, a verifier that names the first broken entry, and a crypto-shredding demo."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Aben Consulting", email = "info@aben.ch" }]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Environment :: Console",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
22
|
+
"Programming Language :: Python :: 3.9",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Topic :: Security",
|
|
28
|
+
"Topic :: System :: Logging",
|
|
29
|
+
]
|
|
30
|
+
keywords = ["audit-log", "hash-chain", "tamper-evident", "gdpr", "crypto-shredding"]
|
|
31
|
+
dependencies = []
|
|
32
|
+
|
|
33
|
+
[project.optional-dependencies]
|
|
34
|
+
shred = ["cryptography>=41"]
|
|
35
|
+
test = ["pytest", "cryptography>=41"]
|
|
36
|
+
|
|
37
|
+
[project.scripts]
|
|
38
|
+
ledger-verify = "ledgerverify.cli:main"
|
|
39
|
+
|
|
40
|
+
[project.urls]
|
|
41
|
+
Homepage = "https://aben.ch/notes/tamper-evident-audit-trails/"
|
|
42
|
+
Source = "https://github.com/aben-consulting/ledger-verify"
|
|
43
|
+
Issues = "https://github.com/aben-consulting/ledger-verify/issues"
|
|
44
|
+
|
|
45
|
+
[tool.setuptools.packages.find]
|
|
46
|
+
where = ["src"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ledger-verify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Tamper-evident hash-chain audit trail verifier: a tiny hash-chained append-only log, a verifier that names the first broken entry, and a crypto-shredding demo.
|
|
5
|
+
Author-email: Aben Consulting <info@aben.ch>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://aben.ch/notes/tamper-evident-audit-trails/
|
|
8
|
+
Project-URL: Source, https://github.com/aben-consulting/ledger-verify
|
|
9
|
+
Project-URL: Issues, https://github.com/aben-consulting/ledger-verify/issues
|
|
10
|
+
Keywords: audit-log,hash-chain,tamper-evident,gdpr,crypto-shredding
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Security
|
|
24
|
+
Classifier: Topic :: System :: Logging
|
|
25
|
+
Requires-Python: >=3.9
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Provides-Extra: shred
|
|
29
|
+
Requires-Dist: cryptography>=41; extra == "shred"
|
|
30
|
+
Provides-Extra: test
|
|
31
|
+
Requires-Dist: pytest; extra == "test"
|
|
32
|
+
Requires-Dist: cryptography>=41; extra == "test"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# ledger-verify
|
|
36
|
+
|
|
37
|
+
A tiny, dependency-free **hash-chained append-only log**, a **verifier that names the first broken entry**, and a **crypto-shredding demo** for GDPR-style erasure. Under 200 lines of library code.
|
|
38
|
+
|
|
39
|
+
It is a teaching/reference implementation of a general pattern, not a production audit system.
|
|
40
|
+
|
|
41
|
+
```text
|
|
42
|
+
$ ledger-verify demo
|
|
43
|
+
intact: True
|
|
44
|
+
tampered: first broken entry = 2 (entry content does not match its hash)
|
|
45
|
+
tail removed, no anchor : verifies -> True (undetected without an anchored head)
|
|
46
|
+
tail removed, with anchor: verifies -> False (head differs from the anchored head (tail removed or replaced?))
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Install and run
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
git clone https://github.com/aben-consulting/ledger-verify.git && cd ledger-verify
|
|
53
|
+
pip install -e ".[shred]" # [shred] adds `cryptography` for the erasure demo
|
|
54
|
+
ledger-verify demo
|
|
55
|
+
python examples/audit_demo.py
|
|
56
|
+
pytest -q # pip install -e ".[test]" first
|
|
57
|
+
```
|
|
58
|
+
Python 3.9+. The core (`ledgerverify.chain`) has no dependencies.
|
|
59
|
+
|
|
60
|
+
## How it works
|
|
61
|
+
|
|
62
|
+
Every entry stores `hash = SHA-256(prev_hash | seq | canonical_json(payload))`. Change, reorder or delete an entry in the middle and every later hash stops matching. `verify()` reports the **first** entry that fails and why.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from ledgerverify import Ledger
|
|
66
|
+
l = Ledger()
|
|
67
|
+
l.append({"event": "finding.created", "id": "F-1"})
|
|
68
|
+
anchor = l.head # store this OUTSIDE the log (another system, signed checkpoint…)
|
|
69
|
+
l.append({"event": "finding.approved", "id": "F-1"})
|
|
70
|
+
print(l.verify(expected_head=l.head).ok) # later: l.verify(expected_head=anchor)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
CLI on a JSON Lines file (one entry per line, as written by `Ledger.dump_jsonl`):
|
|
74
|
+
```sh
|
|
75
|
+
ledger-verify verify ledger.jsonl [--head <hash stored elsewhere>]
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Crypto-shredding (`ledgerverify.shred`)
|
|
79
|
+
Seal personal fields with a per-subject AES-256-GCM key and put only the ciphertext in the log. To erase a person, destroy their key: the log is unchanged, still verifies, and the data is unreadable.
|
|
80
|
+
|
|
81
|
+
## Threat model — read this
|
|
82
|
+
|
|
83
|
+
| Attack | Detected? |
|
|
84
|
+
|---|---|
|
|
85
|
+
| Edit an entry's content | Yes — names the entry |
|
|
86
|
+
| Delete or reorder an entry in the middle | Yes |
|
|
87
|
+
| Delete the **tail** of the log | **Only** if you pass an externally stored head (`expected_head`) |
|
|
88
|
+
| Rewrite the whole chain consistently | **No** — anchor the head somewhere the attacker can't write |
|
|
89
|
+
| Record a false event in the first place | No — the chain proves immutability, not truth |
|
|
90
|
+
|
|
91
|
+
Not included: persistence beyond JSONL, concurrency/locking, signatures, external timestamping, key wrapping under a KMS/HSM, key backup, rotation. `KeyStore` keeps keys in memory. Data derived from the plaintext (indexes, logs, backups) is outside the protection. Whether crypto-shredding satisfies erasure obligations for you is a question for your legal and compliance advisers.
|
|
92
|
+
|
|
93
|
+
## Contributing & security
|
|
94
|
+
Issues and pull requests are welcome. If you find a flaw in the threat model above, please open an issue — that is the most useful feedback.
|
|
95
|
+
|
|
96
|
+
## Licence
|
|
97
|
+
Apache License 2.0 — see [LICENSE](LICENSE). © Áben Consulting Kft., Budapest. https://aben.ch
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
examples/audit_demo.py
|
|
6
|
+
src/ledger_verify.egg-info/PKG-INFO
|
|
7
|
+
src/ledger_verify.egg-info/SOURCES.txt
|
|
8
|
+
src/ledger_verify.egg-info/dependency_links.txt
|
|
9
|
+
src/ledger_verify.egg-info/entry_points.txt
|
|
10
|
+
src/ledger_verify.egg-info/requires.txt
|
|
11
|
+
src/ledger_verify.egg-info/top_level.txt
|
|
12
|
+
src/ledgerverify/__init__.py
|
|
13
|
+
src/ledgerverify/chain.py
|
|
14
|
+
src/ledgerverify/cli.py
|
|
15
|
+
src/ledgerverify/shred.py
|
|
16
|
+
tests/test_chain.py
|
|
17
|
+
tests/test_shred.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ledgerverify
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Append-only, hash-chained log with a verifier that names the first broken entry.
|
|
2
|
+
|
|
3
|
+
Each entry's hash covers: previous hash, sequence number, canonical JSON payload.
|
|
4
|
+
This detects modification of any entry and reordering/removal in the middle.
|
|
5
|
+
It does NOT detect removal of the tail unless you keep the head hash elsewhere
|
|
6
|
+
(pass it to ``verify(expected_head=...)``).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Any, Iterable, Optional
|
|
14
|
+
|
|
15
|
+
GENESIS = "0" * 64
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def canonical_json(payload: Any) -> str:
|
|
19
|
+
"""Deterministic JSON: sorted keys, no whitespace, UTF-8 characters kept."""
|
|
20
|
+
return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def entry_hash(prev_hash: str, seq: int, payload: Any) -> str:
|
|
24
|
+
data = f"{prev_hash}|{seq}|{canonical_json(payload)}".encode("utf-8")
|
|
25
|
+
return hashlib.sha256(data).hexdigest()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class VerifyResult:
|
|
30
|
+
ok: bool
|
|
31
|
+
entries: int
|
|
32
|
+
first_broken_seq: Optional[int] = None
|
|
33
|
+
reason: Optional[str] = None
|
|
34
|
+
head: str = GENESIS
|
|
35
|
+
|
|
36
|
+
def __bool__(self) -> bool: # pragma: no cover - convenience
|
|
37
|
+
return self.ok
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def verify(entries: Iterable[dict], expected_head: Optional[str] = None) -> VerifyResult:
|
|
41
|
+
"""Check a sequence of entries ``{"seq", "payload", "prev", "hash"}``.
|
|
42
|
+
|
|
43
|
+
Returns a VerifyResult. If ``expected_head`` is given (a head hash you stored
|
|
44
|
+
outside the log), a shorter or different chain is reported too.
|
|
45
|
+
"""
|
|
46
|
+
prev = GENESIS
|
|
47
|
+
count = 0
|
|
48
|
+
for expected_seq, e in enumerate(entries, start=1):
|
|
49
|
+
count = expected_seq
|
|
50
|
+
if e.get("seq") != expected_seq:
|
|
51
|
+
return VerifyResult(False, count, e.get("seq", expected_seq), "sequence gap or reorder", prev)
|
|
52
|
+
if e.get("prev") != prev:
|
|
53
|
+
return VerifyResult(False, count, expected_seq, "previous-hash link broken", prev)
|
|
54
|
+
if e.get("hash") != entry_hash(prev, expected_seq, e.get("payload")):
|
|
55
|
+
return VerifyResult(False, count, expected_seq, "entry content does not match its hash", prev)
|
|
56
|
+
prev = e["hash"]
|
|
57
|
+
if expected_head is not None and prev != expected_head:
|
|
58
|
+
return VerifyResult(False, count, count + 1, "head differs from the anchored head (tail removed or replaced?)", prev)
|
|
59
|
+
return VerifyResult(True, count, None, None, prev)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Ledger:
|
|
64
|
+
entries: list = field(default_factory=list)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def head(self) -> str:
|
|
68
|
+
return self.entries[-1]["hash"] if self.entries else GENESIS
|
|
69
|
+
|
|
70
|
+
def append(self, payload: Any) -> dict:
|
|
71
|
+
seq = len(self.entries) + 1
|
|
72
|
+
e = {"seq": seq, "payload": payload, "prev": self.head,
|
|
73
|
+
"hash": entry_hash(self.head, seq, payload)}
|
|
74
|
+
self.entries.append(e)
|
|
75
|
+
return e
|
|
76
|
+
|
|
77
|
+
def verify(self, expected_head: Optional[str] = None) -> VerifyResult:
|
|
78
|
+
return verify(self.entries, expected_head)
|
|
79
|
+
|
|
80
|
+
# --- JSON Lines persistence (one entry per line) -------------------
|
|
81
|
+
def dump_jsonl(self, path: str) -> None:
|
|
82
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
83
|
+
for e in self.entries:
|
|
84
|
+
f.write(json.dumps(e, ensure_ascii=False) + "\n")
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def load_jsonl(cls, path: str) -> "Ledger":
|
|
88
|
+
with open(path, encoding="utf-8") as f:
|
|
89
|
+
return cls([json.loads(line) for line in f if line.strip()])
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Command line: verify a JSONL ledger file, or run a self-contained demo."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from .chain import Ledger
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _demo() -> int:
|
|
11
|
+
ledger = Ledger()
|
|
12
|
+
ledger.append({"event": "finding.created", "id": "F-1", "rating": "high"})
|
|
13
|
+
ledger.append({"event": "finding.approved", "id": "F-1", "by": "reviewer"})
|
|
14
|
+
ledger.append({"event": "deadline.extended", "id": "A-1", "reason": "vendor delay"})
|
|
15
|
+
anchored = ledger.head
|
|
16
|
+
print("intact:", ledger.verify(anchored).ok)
|
|
17
|
+
ledger.entries[1]["payload"]["by"] = "someone-else" # tamper with entry 2
|
|
18
|
+
r = ledger.verify(anchored)
|
|
19
|
+
print(f"tampered: first broken entry = {r.first_broken_seq} ({r.reason})")
|
|
20
|
+
ledger.entries[1]["payload"]["by"] = "reviewer" # restore
|
|
21
|
+
ledger.entries.pop() # remove the tail
|
|
22
|
+
r = ledger.verify()
|
|
23
|
+
print("tail removed, no anchor : verifies ->", r.ok, "(undetected without an anchored head)")
|
|
24
|
+
r = ledger.verify(anchored)
|
|
25
|
+
print("tail removed, with anchor: verifies ->", r.ok, f"({r.reason})")
|
|
26
|
+
return 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv=None) -> int:
|
|
30
|
+
p = argparse.ArgumentParser(prog="ledger-verify")
|
|
31
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
32
|
+
v = sub.add_parser("verify", help="verify a JSONL ledger file")
|
|
33
|
+
v.add_argument("file")
|
|
34
|
+
v.add_argument("--head", help="head hash stored outside the log (detects removed tail)")
|
|
35
|
+
sub.add_parser("demo", help="run the built-in tamper demo")
|
|
36
|
+
a = p.parse_args(argv)
|
|
37
|
+
if a.cmd == "demo":
|
|
38
|
+
return _demo()
|
|
39
|
+
r = Ledger.load_jsonl(a.file).verify(a.head)
|
|
40
|
+
if r.ok:
|
|
41
|
+
print(f"OK: {r.entries} entries, head {r.head}")
|
|
42
|
+
return 0
|
|
43
|
+
print(f"BROKEN at entry {r.first_broken_seq}: {r.reason}", file=sys.stderr)
|
|
44
|
+
return 1
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
if __name__ == "__main__":
|
|
48
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Crypto-shredding sketch: seal personal data under a per-subject key.
|
|
2
|
+
|
|
3
|
+
Put only the sealed blob in the log. To erase a person, destroy their key:
|
|
4
|
+
the ciphertext (and therefore every hash in the chain) stays unchanged but can
|
|
5
|
+
no longer be read. Requires the optional dependency ``cryptography``.
|
|
6
|
+
|
|
7
|
+
Teaching sketch: keys live in memory. A real system wraps subject keys under a
|
|
8
|
+
master key held in a KMS/HSM and persists them outside the log.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import os
|
|
14
|
+
from typing import Dict, Optional
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
18
|
+
except ImportError as exc: # pragma: no cover
|
|
19
|
+
raise ImportError("ledgerverify.shred needs: pip install 'ledger-verify[shred]'") from exc
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class KeyStore:
|
|
23
|
+
def __init__(self) -> None:
|
|
24
|
+
self._keys: Dict[str, bytes] = {}
|
|
25
|
+
|
|
26
|
+
def seal(self, subject: str, plaintext: str) -> str:
|
|
27
|
+
key = self._keys.setdefault(subject, AESGCM.generate_key(bit_length=256))
|
|
28
|
+
nonce = os.urandom(12)
|
|
29
|
+
ct = AESGCM(key).encrypt(nonce, plaintext.encode("utf-8"), subject.encode("utf-8"))
|
|
30
|
+
return base64.b64encode(nonce + ct).decode("ascii")
|
|
31
|
+
|
|
32
|
+
def open(self, subject: str, sealed: str) -> Optional[str]:
|
|
33
|
+
key = self._keys.get(subject)
|
|
34
|
+
if key is None:
|
|
35
|
+
return None # erased
|
|
36
|
+
raw = base64.b64decode(sealed)
|
|
37
|
+
return AESGCM(key).decrypt(raw[:12], raw[12:], subject.encode("utf-8")).decode("utf-8")
|
|
38
|
+
|
|
39
|
+
def erase(self, subject: str) -> bool:
|
|
40
|
+
return self._keys.pop(subject, None) is not None
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
from ledgerverify import GENESIS, Ledger, verify
|
|
4
|
+
from ledgerverify.cli import main
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def make(n=3):
|
|
8
|
+
l = Ledger()
|
|
9
|
+
for i in range(n):
|
|
10
|
+
l.append({"event": "e", "i": i})
|
|
11
|
+
return l
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_intact_chain_verifies():
|
|
15
|
+
l = make()
|
|
16
|
+
r = l.verify()
|
|
17
|
+
assert r.ok and r.entries == 3 and r.head == l.head
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_empty_chain_is_ok():
|
|
21
|
+
assert verify([]).ok and verify([]).head == GENESIS
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_payload_tamper_names_first_broken_entry():
|
|
25
|
+
l = make()
|
|
26
|
+
l.entries[1]["payload"]["i"] = 99
|
|
27
|
+
r = l.verify()
|
|
28
|
+
assert not r.ok and r.first_broken_seq == 2
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_rehashing_one_entry_breaks_the_next_link():
|
|
32
|
+
from ledgerverify import entry_hash
|
|
33
|
+
l = make()
|
|
34
|
+
l.entries[0]["payload"]["i"] = 42
|
|
35
|
+
l.entries[0]["hash"] = entry_hash(GENESIS, 1, l.entries[0]["payload"])
|
|
36
|
+
assert l.verify().first_broken_seq == 2
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_removed_middle_entry_detected():
|
|
40
|
+
l = make()
|
|
41
|
+
del l.entries[1]
|
|
42
|
+
assert not l.verify().ok
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_tail_removal_only_detected_with_anchor():
|
|
46
|
+
l = make()
|
|
47
|
+
anchor = l.head
|
|
48
|
+
l.entries.pop()
|
|
49
|
+
assert l.verify().ok # known limit
|
|
50
|
+
r = l.verify(anchor)
|
|
51
|
+
assert not r.ok and "anchored head" in r.reason
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_key_order_does_not_matter():
|
|
55
|
+
from ledgerverify import entry_hash
|
|
56
|
+
assert entry_hash(GENESIS, 1, {"a": 1, "b": 2}) == entry_hash(GENESIS, 1, {"b": 2, "a": 1})
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_unicode_payload_roundtrip(tmp_path):
|
|
60
|
+
l = Ledger()
|
|
61
|
+
l.append({"név": "Árvíztűrő tükörfúrógép"})
|
|
62
|
+
p = tmp_path / "l.jsonl"
|
|
63
|
+
l.dump_jsonl(str(p))
|
|
64
|
+
assert Ledger.load_jsonl(str(p)).verify().ok
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_cli_verify_ok_and_broken(tmp_path, capsys):
|
|
68
|
+
l = make()
|
|
69
|
+
p = tmp_path / "l.jsonl"
|
|
70
|
+
l.dump_jsonl(str(p))
|
|
71
|
+
assert main(["verify", str(p)]) == 0
|
|
72
|
+
lines = p.read_text().splitlines()
|
|
73
|
+
e = json.loads(lines[1]); e["payload"]["i"] = 7
|
|
74
|
+
lines[1] = json.dumps(e)
|
|
75
|
+
p.write_text("\n".join(lines) + "\n")
|
|
76
|
+
assert main(["verify", str(p)]) == 1
|
|
77
|
+
assert "entry 2" in capsys.readouterr().err
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def test_cli_demo_runs(capsys):
|
|
81
|
+
assert main(["demo"]) == 0
|
|
82
|
+
out = capsys.readouterr().out
|
|
83
|
+
assert "intact: True" in out and "first broken entry = 2" in out
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
pytest.importorskip("cryptography")
|
|
4
|
+
|
|
5
|
+
from ledgerverify import Ledger
|
|
6
|
+
from ledgerverify.shred import KeyStore
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_seal_open_erase_keeps_chain_valid():
|
|
10
|
+
ks, l = KeyStore(), Ledger()
|
|
11
|
+
sealed = ks.seal("client-42", "Jane Doe")
|
|
12
|
+
l.append({"event": "client.created", "name_sealed": sealed})
|
|
13
|
+
assert ks.open("client-42", sealed) == "Jane Doe"
|
|
14
|
+
assert ks.erase("client-42") is True
|
|
15
|
+
assert ks.open("client-42", sealed) is None
|
|
16
|
+
assert l.verify().ok # chain untouched by erasure
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_wrong_subject_cannot_open():
|
|
20
|
+
ks = KeyStore()
|
|
21
|
+
sealed = ks.seal("a", "secret")
|
|
22
|
+
ks.seal("b", "other")
|
|
23
|
+
from cryptography.exceptions import InvalidTag
|
|
24
|
+
with pytest.raises(InvalidTag):
|
|
25
|
+
ks.open("b", sealed)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_erase_unknown_subject_returns_false():
|
|
29
|
+
assert KeyStore().erase("nobody") is False
|