sumseal 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.
sumseal/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """sumseal: record a SHA-256 manifest of a folder of files and verify it later.
2
+
3
+ sumseal records file integrity only. It does not prove who created a file or
4
+ that its content is genuine.
5
+ """
6
+
7
+ __version__ = "0.1.0"
sumseal/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m sumseal``."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
sumseal/cli.py ADDED
@@ -0,0 +1,254 @@
1
+ """Command-line interface.
2
+
3
+ Exit codes: 0 OK, 1 problems found (or output cut short by a closed pipe),
4
+ 2 usage or input error, 3 internal error.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ import re
12
+ import sys
13
+ from collections.abc import Sequence
14
+
15
+ from . import __version__
16
+ from .manifest import SumsealError, add_source, create, load_manifest, manifest_digest
17
+ from .report import render_csv, render_markdown
18
+ from .verify import PROBLEMS, RESULTS, verify
19
+
20
+ EXIT_OK = 0
21
+ EXIT_PROBLEMS = 1
22
+ EXIT_USAGE = 2
23
+ EXIT_INTERNAL = 3
24
+
25
+ HEX_DIGEST = re.compile(r"[0-9a-f]{64}")
26
+
27
+
28
+ def _hex_digest(text: str) -> str:
29
+ if not HEX_DIGEST.fullmatch(text):
30
+ raise argparse.ArgumentTypeError("must be exactly 64 lowercase hex characters (0-9, a-f)")
31
+ return text
32
+
33
+
34
+ def build_parser() -> argparse.ArgumentParser:
35
+ parser = argparse.ArgumentParser(
36
+ prog="sumseal",
37
+ description="Record a SHA-256 manifest of a folder of files and verify it later.",
38
+ epilog=(
39
+ "Exit codes: 0 everything OK, 1 problems found or output cut short by a "
40
+ "closed pipe, 2 usage or input error, "
41
+ "3 internal error (a bug in sumseal; please report it). "
42
+ "sumseal records file integrity only; it does not prove who made a file "
43
+ "or that its content is genuine."
44
+ ),
45
+ )
46
+ parser.add_argument("--version", action="version", version=f"sumseal {__version__}")
47
+ commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
48
+
49
+ create_cmd = commands.add_parser(
50
+ "create",
51
+ help="record a manifest of a folder",
52
+ description=(
53
+ "Record every file in FOLDER. The manifest is written next to the "
54
+ "folder as <folder-name>.sumseal.json unless --out is given."
55
+ ),
56
+ )
57
+ create_cmd.add_argument("folder", help="folder to record")
58
+ create_cmd.add_argument("--collector", required=True, metavar="NAME",
59
+ help="who collected the files")
60
+ create_cmd.add_argument("--case", dest="case_id", metavar="ID", help="optional case ID")
61
+ create_cmd.add_argument("--exclude", action="append", default=[], metavar="GLOB",
62
+ help="leave out matching files or folders (repeatable, recorded)")
63
+ create_cmd.add_argument("--skip-special", action="store_true",
64
+ help="record symlinks and special files in 'skipped' instead of stopping")
65
+ create_cmd.add_argument("--out", metavar="FILE", help="where to write the manifest")
66
+
67
+ verify_cmd = commands.add_parser(
68
+ "verify",
69
+ help="check a folder against its manifest",
70
+ description=(
71
+ "Check FOLDER against its manifest (<folder-name>.sumseal.json next to "
72
+ "the folder unless --manifest is given). Exit 0 if everything matches, "
73
+ "1 if anything is CHANGED, MISSING, NEW or UNREADABLE, or if "
74
+ "--expect-digest does not match the manifest digest."
75
+ ),
76
+ )
77
+ verify_cmd.add_argument("folder", help="folder to check")
78
+ verify_cmd.add_argument("--manifest", metavar="FILE", help="manifest to check against")
79
+ verify_cmd.add_argument("--expect-digest", type=_hex_digest, metavar="HEX",
80
+ help="the digest you anchored (64 lowercase hex characters); "
81
+ "a different manifest digest is a problem")
82
+
83
+ source_cmd = commands.add_parser(
84
+ "add-source",
85
+ help="record where one file came from",
86
+ description=(
87
+ "Record the source URL of one file already in the manifest. The manifest "
88
+ "is rewritten and its digest changes: anchor the digest only after your "
89
+ "last edit. An existing source is never overwritten."
90
+ ),
91
+ )
92
+ source_cmd.add_argument("manifest", help="manifest file to update")
93
+ source_cmd.add_argument("path", help="file path exactly as in the manifest (use /)")
94
+ source_cmd.add_argument("url", help="where the file came from")
95
+ source_cmd.add_argument("--accessed", required=True, metavar="TIME",
96
+ help="when it was accessed, UTC, like 2026-01-02T03:04:05Z")
97
+ source_cmd.add_argument("--note", metavar="TEXT", help="optional note")
98
+
99
+ digest_cmd = commands.add_parser("digest", help="print the manifest digest")
100
+ digest_cmd.add_argument("manifest", help="manifest file")
101
+
102
+ report_cmd = commands.add_parser(
103
+ "report", help="print a readable report (UTF-8) of a manifest"
104
+ )
105
+ report_cmd.add_argument("manifest", help="manifest file")
106
+ report_cmd.add_argument("--format", choices=("md", "csv"), default="md",
107
+ help="md (default) or csv")
108
+ return parser
109
+
110
+
111
+ def show(name: str) -> str:
112
+ """Name as printed: escaped if it has control, invisible or format characters."""
113
+ return name if name.isprintable() else ascii(name)
114
+
115
+
116
+ def _cmd_create(args: argparse.Namespace) -> int:
117
+ notes: list[str] = []
118
+ out_path, digest, manifest = create(
119
+ args.folder,
120
+ collector=args.collector,
121
+ case_id=args.case_id,
122
+ excludes=args.exclude,
123
+ skip_special=args.skip_special,
124
+ out=args.out,
125
+ notes=notes,
126
+ )
127
+ for note in notes:
128
+ print(f"note: {note}")
129
+ print(f"Recorded {len(manifest['files'])} files from {show(manifest['root_name'])}")
130
+ if manifest["skipped"]:
131
+ print(f"Skipped {len(manifest['skipped'])} special items (listed in the manifest)")
132
+ if manifest["excludes"]:
133
+ print("Excluded: " + ", ".join(manifest["excludes"]))
134
+ print(f"Manifest: {show(str(out_path))}")
135
+ print(f"Manifest digest (sha256): {digest}")
136
+ print("Anchor this digest somewhere outside the folder.")
137
+ return EXIT_OK
138
+
139
+
140
+ def _cmd_verify(args: argparse.Namespace) -> int:
141
+ report = verify(args.folder, args.manifest)
142
+ print(f"Manifest: {show(str(report.manifest_path))}")
143
+ print(f"Manifest digest (sha256): {report.digest}")
144
+ digest_mismatch = False
145
+ if args.expect_digest is None:
146
+ print("Compare this digest with the one you anchored when the manifest was made.")
147
+ elif args.expect_digest == report.digest:
148
+ print("Expected digest: matches the manifest digest.")
149
+ else:
150
+ digest_mismatch = True
151
+ print(f"MISMATCH manifest digest differs from --expect-digest {args.expect_digest}")
152
+ problems = [f for f in report.findings if f.result in PROBLEMS]
153
+ if problems:
154
+ print()
155
+ width = max(len(result) for result in RESULTS)
156
+ for finding in problems:
157
+ detail = f" ({finding.detail})" if finding.detail else ""
158
+ print(f"{finding.result:<{width}} {show(finding.path)}{detail}")
159
+ if report.notes:
160
+ print()
161
+ for note in report.notes:
162
+ print(f"note: {note}")
163
+ print()
164
+ print(" ".join(f"{result} {count}" for result, count in report.counts().items()))
165
+ if digest_mismatch:
166
+ files = "files match the manifest" if report.ok else "problems found in the files too"
167
+ print(f"Result: the manifest digest does not match the expected digest ({files}).")
168
+ return EXIT_PROBLEMS
169
+ if report.ok:
170
+ print("Result: everything matches the manifest.")
171
+ return EXIT_OK
172
+ print("Result: problems found.")
173
+ return EXIT_PROBLEMS
174
+
175
+
176
+ def _cmd_add_source(args: argparse.Namespace) -> int:
177
+ old, new = add_source(
178
+ args.manifest, args.path, args.url, accessed=args.accessed, note=args.note
179
+ )
180
+ print(f"Source recorded for {show(args.path)}")
181
+ print(f"Previous digest (sha256): {old}")
182
+ print(f"New manifest digest (sha256): {new}")
183
+ print("Anchor the digest only after your last edit.")
184
+ return EXIT_OK
185
+
186
+
187
+ def _cmd_digest(args: argparse.Namespace) -> int:
188
+ print(manifest_digest(load_manifest(args.manifest)))
189
+ return EXIT_OK
190
+
191
+
192
+ def _cmd_report(args: argparse.Namespace) -> int:
193
+ manifest = load_manifest(args.manifest)
194
+ text = render_csv(manifest) if args.format == "csv" else render_markdown(manifest)
195
+ # Always UTF-8 bytes: the console or pipe encoding must never alter file names.
196
+ sys.stdout.flush()
197
+ sys.stdout.buffer.write(text.encode("utf-8"))
198
+ sys.stdout.buffer.flush()
199
+ return EXIT_OK
200
+
201
+
202
+ COMMANDS = {
203
+ "create": _cmd_create,
204
+ "verify": _cmd_verify,
205
+ "add-source": _cmd_add_source,
206
+ "digest": _cmd_digest,
207
+ "report": _cmd_report,
208
+ }
209
+
210
+
211
+ def _safe_streams() -> None:
212
+ # A console or pipe that cannot show a file name must not crash the run.
213
+ for stream in (sys.stdout, sys.stderr):
214
+ try:
215
+ stream.reconfigure(errors="backslashreplace") # type: ignore[union-attr]
216
+ except (AttributeError, ValueError):
217
+ pass
218
+
219
+
220
+ def _stdout_to_devnull() -> None:
221
+ # Point the stdout file descriptor at the null device, so the flush Python does
222
+ # at exit writes there instead of raising BrokenPipeError again.
223
+ try:
224
+ fd = sys.stdout.fileno()
225
+ except (AttributeError, OSError, ValueError):
226
+ return # not a real file (for example captured in tests): nothing to redirect
227
+ devnull = os.open(os.devnull, os.O_WRONLY)
228
+ try:
229
+ os.dup2(devnull, fd)
230
+ finally:
231
+ os.close(devnull)
232
+
233
+
234
+ def main(argv: Sequence[str] | None = None) -> int:
235
+ _safe_streams()
236
+ args = build_parser().parse_args(argv) # argparse exits with 2 on bad arguments
237
+ try:
238
+ code = COMMANDS[args.command](args)
239
+ if sys.stdout is not None: # no stdout at all (for example pythonw): nothing to flush
240
+ sys.stdout.flush() # a closed pipe should surface here, not at interpreter exit
241
+ return code
242
+ except SumsealError as exc:
243
+ print(f"sumseal: error: {exc}", file=sys.stderr)
244
+ for detail in exc.details:
245
+ print(f" {detail}", file=sys.stderr)
246
+ return EXIT_USAGE
247
+ except BrokenPipeError:
248
+ # The reader went away (for example `| head`). The output was cut short, so
249
+ # never claim OK: exit 1, print nothing.
250
+ _stdout_to_devnull()
251
+ return EXIT_PROBLEMS
252
+ except Exception as exc: # a bug: report it plainly instead of a traceback
253
+ print(f"sumseal: internal error: {type(exc).__name__}: {exc}", file=sys.stderr)
254
+ return EXIT_INTERNAL
sumseal/hashing.py ADDED
@@ -0,0 +1,29 @@
1
+ """SHA-256 hashing of files, read in fixed-size chunks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+
8
+ HASH_ALGORITHM = "sha256"
9
+ CHUNK_SIZE = 1024 * 1024 # 1 MiB, per SPEC.md
10
+
11
+
12
+ def hash_file(path: str | os.PathLike[str]) -> tuple[str, int]:
13
+ """Return (lowercase hex SHA-256, size in bytes) of the file at ``path``.
14
+
15
+ The size is the number of bytes actually read and hashed, so the two values
16
+ always describe the same content even if the file changes on disk later.
17
+ Any OSError (missing, unreadable, a directory) propagates to the caller;
18
+ nothing is skipped or guessed here.
19
+ """
20
+ digest = hashlib.sha256()
21
+ size = 0
22
+ with open(path, "rb") as handle:
23
+ while True:
24
+ chunk = handle.read(CHUNK_SIZE)
25
+ if not chunk:
26
+ break
27
+ digest.update(chunk)
28
+ size += len(chunk)
29
+ return digest.hexdigest(), size