codeimprint 0.5.0a33__tar.gz → 0.5.0a35__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.
Files changed (27) hide show
  1. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/CHANGELOG.md +43 -0
  2. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/PKG-INFO +4 -2
  3. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/README.pypi.md +3 -1
  4. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/pyproject.toml +1 -1
  5. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/__init__.py +1 -1
  6. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/api.py +20 -3
  7. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/chainseal.py +36 -12
  8. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/cli.py +252 -9
  9. codeimprint-0.5.0a35/src/codeimprint_cli/filelist.py +289 -0
  10. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/gitrepo.py +57 -0
  11. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/project.py +52 -0
  12. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/receipt.py +80 -12
  13. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/.gitignore +0 -0
  14. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/LICENSE +0 -0
  15. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/NOTICE +0 -0
  16. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint/__init__.py +0 -0
  17. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint/__main__.py +0 -0
  18. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/__main__.py +0 -0
  19. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/config.py +0 -0
  20. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/imprint_file.py +0 -0
  21. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/linecount.py +0 -0
  22. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/ownership.py +0 -0
  23. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/records.py +0 -0
  24. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/timestamp.py +0 -0
  25. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/transparency.py +0 -0
  26. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/trust.py +0 -0
  27. {codeimprint-0.5.0a33 → codeimprint-0.5.0a35}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a35 — Your own file list: check, prove, verify a file [CIM-BE-58-v1]
4
+
5
+ For engine 0.7.0a44.
6
+
7
+ - **New: `imprint check --files`** compares a commit (`HEAD`, or `--commit REV`) or the working
8
+ tree (`--worktree`) with a seal's file list (this folder's baseline, or `--seal ID`): files
9
+ added, removed, changed, with another mode, or listed in the seal without a hash. Everything
10
+ is hashed here; only the list is fetched (`GET /api/v1/imprints/{id}/files`, the project's
11
+ owner or its CI token). Exit 1 when files differ; in an automated build a warning and 0.
12
+ `--format json` gives the lists.
13
+ - **New: `imprint prove <file>`** writes `<name>.proof.json` (`-o FILE`): the file's kind, size,
14
+ SHA-256 and salt, its audit path, the server and the seal's public receipt. It reveals no other
15
+ file. A warning when the file here is not the sealed one.
16
+ - **New: `imprint verify-file <file> --proof P`**, no account needed: the receipt is verified
17
+ (keys from the proof's server, `--url` or `--keys FILE`), then the file is hashed and its
18
+ leaf checked against the attested root and count. Exit 0 VERIFIED, 1 NOT VERIFIED, 3 newer.
19
+ - Golden vectors set 3 checks its TSA tokens against its own test root
20
+ (`golden-3-tsa-root.pem`), as sets 1 and 2 do.
21
+
22
+ ## 0.5.0a34 — Seal every tracked file, in any language [CIM-BE-58-v1]
23
+
24
+ For engine 0.7.0a43. With an older engine a seal is Python-only, as before.
25
+
26
+ - **Every file.** `imprint seal` (Git, CI tokens, `--zip` and folders without Git) lists every
27
+ tracked file after only the exclude list and `.imprint/`: links (their target text),
28
+ executables and submodules (their commit) included, no size limit. Each file is hashed here
29
+ from Git's own copy (`git cat-file --batch`, read in parts), and only the SHA-256s, sizes and
30
+ modes are sent; Python files are still uploaded when the server asks for them. **The content
31
+ of a file that is not Python never leaves your machine.**
32
+ - **Checked before you sign.** The client rebuilds the root of the salted file list under the
33
+ seal's seed (`filelist.py`, scheme `sha256-leaf-v1+rfc6962`) and the commit commitment, and
34
+ refuses to sign a statement that differs ("nothing was signed").
35
+ - **A repository with no Python seals.** The result shows "Integrity: N files · Fingerprint:
36
+ none (Python only today)"; with Python, "Fingerprint: Python (M files)". `nothing_to_seal`
37
+ only when no file is left after the excludes. The old "CodeImprint seals Python source files
38
+ (.py) at present" is said only for an older server.
39
+ - **`imprint verify`** reads receipt format 5: attestation v3, log entry v3 (rebuilt with the
40
+ file root and the commit commitment) and chain signature v2 (signed over them), and a "files"
41
+ check (for an older seal: "Python-only seal (before engine 0.7.0a43)"). An unknown file
42
+ scheme is "newer", never a failure. Receipt format 6 is the next newer format.
43
+ - Tests: `test_every_file.py`, golden vectors set 3 (the engine's every-file seals, rebuilt with
44
+ this client's code).
45
+
3
46
  ## 0.5.0a33 — Plan refusals are never silent [CIM-BE-53-v1]
4
47
 
5
48
  For engine 0.7.0a40, which can enforce the Hello plan's limits (`CODEIMPRINT_BILLING_ENFORCE`).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a33
3
+ Version: 0.5.0a35
4
4
  Summary: CodeImprint: seal your code with a CodeImprint server (tamper-evident, logged and timestamped) and verify seals offline.
5
5
  Project-URL: Homepage, https://codeimprint.ai
6
6
  Project-URL: Hub, https://app.codeimprint.ai
@@ -97,7 +97,9 @@ evidence, not proof), `imprint chain`, `imprint hook install`, `imprint identity
97
97
  `imprint seal` and `imprint check` upload the project's Python files to the CodeImprint
98
98
  server you signed in to, which deletes them as soon as it has sealed or checked them. A Git
99
99
  seal also sends the paths and Git IDs of tracked files and the commit and repository IDs;
100
- the server keeps those only as keyed hashes, with the seal.
100
+ the server keeps those only as keyed hashes, with the seal. From 0.5.0a34 a seal covers every
101
+ file in any language: the client sends each file's SHA-256, size and mode, never the content
102
+ of a file that is not Python.
101
103
  Your developer key never leaves your machine: only its public half is sent.
102
104
 
103
105
  ## Licence
@@ -63,7 +63,9 @@ evidence, not proof), `imprint chain`, `imprint hook install`, `imprint identity
63
63
  `imprint seal` and `imprint check` upload the project's Python files to the CodeImprint
64
64
  server you signed in to, which deletes them as soon as it has sealed or checked them. A Git
65
65
  seal also sends the paths and Git IDs of tracked files and the commit and repository IDs;
66
- the server keeps those only as keyed hashes, with the seal.
66
+ the server keeps those only as keyed hashes, with the seal. From 0.5.0a34 a seal covers every
67
+ file in any language: the client sends each file's SHA-256, size and mode, never the content
68
+ of a file that is not Python.
67
69
  Your developer key never leaves your machine: only its public half is sent.
68
70
 
69
71
  ## Licence
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  # Published on PyPI as `codeimprint`. The import package stays `codeimprint_cli` and the
7
7
  # command `imprint`.
8
8
  name = "codeimprint"
9
- version = "0.5.0a33"
9
+ version = "0.5.0a35"
10
10
  description = "CodeImprint: seal your code with a CodeImprint server (tamper-evident, logged and timestamped) and verify seals offline."
11
11
  readme = "README.pypi.md"
12
12
  license = "Apache-2.0"
@@ -5,4 +5,4 @@ A thin client for a CodeImprint server: it zips a project, asks the server to se
5
5
  it, and verifies Imprint files offline. All analysis happens on the server.
6
6
  """
7
7
 
8
- __version__ = "0.5.0a33"
8
+ __version__ = "0.5.0a35"
@@ -43,12 +43,18 @@ class NetworkError(Exception):
43
43
  """The server could not be reached."""
44
44
 
45
45
 
46
- def _multipart(fields: dict[str, str], file_name: str, file_bytes: bytes) -> tuple[bytes, str]:
46
+ def _multipart(fields: dict[str, str], file_name: str, file_bytes: bytes,
47
+ extra_file: tuple[str, str, bytes] | None = None) -> tuple[bytes, str]:
47
48
  boundary = f"codeimprint-{uuid.uuid4().hex}"
48
49
  parts = []
49
50
  for name, value in fields.items():
50
51
  parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'
51
52
  f"{value}\r\n".encode())
53
+ if extra_file is not None: # (field, file name, bytes), JSON
54
+ field, fname, data = extra_file
55
+ parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{field}"; '
56
+ f'filename="{fname}"\r\nContent-Type: application/json\r\n\r\n'.encode())
57
+ parts.append(data + b"\r\n")
52
58
  parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
53
59
  f'filename="{file_name}"\r\nContent-Type: application/zip\r\n\r\n'.encode())
54
60
  parts.append(file_bytes)
@@ -132,11 +138,17 @@ class Client:
132
138
  return self._request("GET", "/health")
133
139
 
134
140
  def seal(self, zip_bytes: bytes, name: str | None = None, lines: dict | None = None,
135
- project_id: str | None = None) -> dict:
141
+ project_id: str | None = None, files_manifest: bytes | None = None) -> dict:
142
+ """A zip seal. ``files_manifest`` (engine 0.7.0a43): every file, hashed here, as
143
+ JSON; the zip then holds only the files to fingerprint."""
136
144
  fields = {k: v for k, v in (("name", name), ("project_id", project_id)) if v}
137
145
  if lines is not None:
138
146
  fields["lines"] = json.dumps(lines, sort_keys=True, separators=(",", ":"))
139
- body, ctype = _multipart(fields, "project.zip", zip_bytes)
147
+ extra = None
148
+ if files_manifest is not None:
149
+ fields["files_scheme"] = "sha256-leaf-v1+rfc6962"
150
+ extra = ("files_manifest", "files.json", files_manifest)
151
+ body, ctype = _multipart(fields, "project.zip", zip_bytes, extra)
140
152
  return self._request("POST", "/api/v1/seal", body, ctype)
141
153
 
142
154
  def _json(self, method: str, path: str, payload: dict | None = None) -> dict:
@@ -402,6 +414,11 @@ class Client:
402
414
  def public_imprint(self, imprint_id: str) -> dict:
403
415
  return self._request("GET", f"/api/v1/public/imprints/{quote(imprint_id)}")
404
416
 
417
+ def seal_files(self, imprint_id: str) -> dict:
418
+ """A seal's file list, for its owner (engine 0.7.0a44): paths, kinds, sizes and
419
+ hashes, the seed, the commit and tree. Nothing is sent but the request."""
420
+ return self._request("GET", f"/api/v1/imprints/{quote(imprint_id)}/files")
421
+
405
422
  # a seal's validity and certificate (engine 0.7.0a26) -----------------------------------
406
423
  def validity(self, imprint_id: str) -> dict:
407
424
  """A seal's validity now, as the server works it out: state, valid until, timeline
@@ -18,7 +18,7 @@ import json
18
18
  import time
19
19
  from pathlib import Path
20
20
 
21
- from . import gitrepo, linecount, trust
21
+ from . import filelist, gitrepo, linecount, trust
22
22
  from .api import ApiError
23
23
  from .imprint_file import canonical
24
24
 
@@ -131,7 +131,18 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
131
131
  files = [f for f in gitrepo.ls_tree(top, commit, under)
132
132
  if not f["path"].startswith(".imprint/")] # seals and receipts: not content
133
133
  lines = linecount.count_commit(top, commit, files, under).payload()
134
- pages = [files[i:i + PAGE] for i in range(0, len(files), PAGE)] or [[]]
134
+ # Engine 0.7.0a43: every tracked file is sealed. Each is hashed here, from Git's own
135
+ # copy of the commit; only the hashes are sent (Python files are still uploaded, to be
136
+ # fingerprinted, when the server asks for them).
137
+ listed = [f for f in gitrepo.ls_tree_all(top, commit, under)
138
+ if not f["path"].startswith(".imprint/")]
139
+ digests = gitrepo.hash_blobs(top, sorted({f["blob"] for f in listed
140
+ if f["mode"] != "submodule"}))
141
+ for f in listed:
142
+ if f["mode"] != "submodule":
143
+ f["sha256"], f["size"] = digests[f["blob"]]
144
+ entries = filelist.entries_of(listed, list(exclude or []))
145
+ pages = [listed[i:i + PAGE] for i in range(0, len(listed), PAGE)] or [[]]
135
146
  plan_id, resp = None, {}
136
147
  for i, page in enumerate(pages):
137
148
  body = {"files": page, "more": i < len(pages) - 1}
@@ -139,7 +150,8 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
139
150
  body["plan_id"] = plan_id
140
151
  else:
141
152
  body.update(tree=info["tree"], commit=commit, parents=info["parents"],
142
- ref=info["ref"], kind=kind, exclude=list(exclude or []), lines=lines)
153
+ ref=info["ref"], kind=kind, exclude=list(exclude or []), lines=lines,
154
+ files_scheme=filelist.SCHEME)
143
155
  if repository: # which repository this is (engine 0.7.0a23+)
144
156
  body["repository"] = repository
145
157
  try: # commit IDs only (engine 0.7.0a22+ keeps them keyed)
@@ -153,7 +165,10 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
153
165
  resp = client.plan(project, body)
154
166
  except ApiError as exc:
155
167
  if exc.code == "nothing_to_seal":
156
- raise NothingToSeal(len(files), _python(files), str(exc)) from exc
168
+ # Files are left after the excludes, so the server is older than 0.7.0a43
169
+ # and seals Python files only.
170
+ raise NothingToSeal(len(files), _python(files), str(exc),
171
+ older_server=bool(entries)) from exc
157
172
  raise
158
173
  if "release" in resp:
159
174
  rel = resp["release"]
@@ -167,8 +182,8 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
167
182
  return {"already": seal, "released": resp.get("already_released"),
168
183
  "commit": commit, "info": info, "engagement": resp.get("engagement")}
169
184
  plan_id = resp.get("plan_id", plan_id)
170
- if resp.get("files") == 0: # an engine before 0.7.0a28 would seal nothing
171
- raise NothingToSeal(len(files), _python(files))
185
+ if resp.get("files") == 0 and "integrity_files" not in resp: # before 0.7.0a28
186
+ raise NothingToSeal(len(files), _python(files), older_server=True)
172
187
  need = resp["need"]
173
188
  sizes = {f["blob"]: f["size"] for f in files}
174
189
  size = sum(sizes.get(b, 0) for b in need)
@@ -191,26 +206,35 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
191
206
  if exc.code == "nothing_to_seal":
192
207
  raise NothingToSeal(said=str(exc)) from exc
193
208
  raise
209
+ statement = prep["statement"]
210
+ if statement.get("type") == "codeimprint.chain-seal.v2": # every file: check, then sign
211
+ filelist.check_statement(statement, entries, prep.get("files_seed"), commit,
212
+ info["tree"])
194
213
  result = client.finalise(project, prep["pending_id"], public_key(key),
195
- sign(key, prep["statement"]))
214
+ sign(key, statement))
196
215
  check_lines(lines, result)
197
216
  return {"result": result, "uploaded": len(need), "upload_bytes": size, "tag": tag,
198
- "files": resp.get("files", 0), "commit": commit, "info": info, "lines": lines}
217
+ "files": resp.get("files", 0), "commit": commit, "info": info, "lines": lines,
218
+ "integrity_files": resp.get("integrity_files")}
199
219
 
200
220
 
201
221
  NOTHING_TO_SEAL = ("Nothing to seal: no files matched. Check .gitignore, the exclude list in "
202
222
  ".imprint/config.json, and that you are in the project folder.")
203
- PYTHON_ONLY = " CodeImprint seals Python source files (.py) at present."
223
+ # Engine 0.7.0a43 seals every file, in any language; an older server seals Python files only.
224
+ OLDER_SERVER = (" This server is older than engine 0.7.0a43 and seals Python source files "
225
+ "(.py) only.")
204
226
 
205
227
 
206
228
  class NothingToSeal(RuntimeError):
207
229
  """A seal that would cover no file is never made (engine 0.7.0a28 answers 422
208
230
  nothing_to_seal; for an older engine the client stops here, before anything is sent).
209
- ``tracked`` is the number of files Git tracks at the commit, of any kind."""
231
+ ``tracked`` is the number of files Git tracks at the commit, of any kind;
232
+ ``older_server``: files were left, so the server seals Python files only."""
210
233
 
211
- def __init__(self, tracked: int = 0, python: int = 0, said: str | None = None) -> None:
234
+ def __init__(self, tracked: int = 0, python: int = 0, said: str | None = None,
235
+ older_server: bool = False) -> None:
212
236
  super().__init__((said or NOTHING_TO_SEAL)
213
- + (PYTHON_ONLY if tracked and not python else ""))
237
+ + (OLDER_SERVER if older_server and tracked and not python else ""))
214
238
 
215
239
 
216
240
  def check_lines(sent: dict, result: dict) -> None:
@@ -19,6 +19,7 @@ from . import (
19
19
  __version__,
20
20
  chainseal,
21
21
  config,
22
+ filelist,
22
23
  gitrepo,
23
24
  imprint_file,
24
25
  linecount,
@@ -502,17 +503,23 @@ def _other_repository(client: Client, cfg: dict, root: Path) -> None:
502
503
  raise SealFailed(NOT_THIS_REPOSITORY)
503
504
 
504
505
 
505
- def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool) -> bytes:
506
+ def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool,
507
+ every: dict | None = None) -> bytes:
508
+ """The zip to send. For a seal, ``every`` is every file of the folder, hashed here
509
+ (engine 0.7.0a43): only their hashes are sent, and the zip holds the Python files."""
506
510
  sel = project.select_files(path)
507
- if sel.count == 0:
511
+ if sel.count == 0 and not every:
508
512
  if action == "seal": # a seal of nothing is never made
509
- raise SealFailed(chainseal.NOTHING_TO_SEAL + chainseal.PYTHON_ONLY)
513
+ raise SealFailed(chainseal.NOTHING_TO_SEAL)
510
514
  raise Abort(f"no Python files to send under {sel.root} (check .gitignore and "
511
515
  ".imprint/config.json excludes)")
512
516
  data = project.build_zip(sel)
517
+ hashed = ([f" the SHA-256 of {len(every)} file(s) of any kind, hashed here "
518
+ + "(their content is not sent)"] if every else [])
513
519
  _say(f"About to send to {client.url}:",
514
520
  f" {sel.count} Python file(s), {project.human_size(sel.total_bytes)} "
515
521
  f"({project.human_size(len(data))} zipped) from {sel.root}",
522
+ *hashed,
516
523
  f" {sel.ignored} path(s) left out by .gitignore, .imprint/config.json or defaults",
517
524
  f" {HANDLING[action]}")
518
525
  if not assume_yes:
@@ -1930,6 +1937,8 @@ def _finish(args, client: Client, root: Path, result: dict, keys: list,
1930
1937
  *([f"Kind {st['kind']} (parent: {parents})"] if "kind" in st else []),
1931
1938
  *extra,
1932
1939
  f"Units {result['units']}",
1940
+ *([f"Integrity {filelist.summary(st)}"] if st.get("type", "").startswith(
1941
+ "codeimprint.attestation.") else []),
1933
1942
  *([f"Lines {linecount.summary(doc['lines'])}"] if doc.get("lines") else []),
1934
1943
  f"Sealed {st['attested_at']}, attested by {rec['attestation']['key_id']}",
1935
1944
  f"Log entry #{rec['log']['index']}, checkpoint of "
@@ -1963,18 +1972,23 @@ def _folder_lines(path: str) -> dict:
1963
1972
 
1964
1973
 
1965
1974
  def _seal_zip(args, client: Client, data: bytes, project_id: str | None,
1966
- lines: dict | None = None) -> int:
1975
+ lines: dict | None = None, every: dict | None = None) -> int:
1967
1976
  """A zip seal (kind manual): code without Git, or `--zip`. Joins the project's chain
1968
- when the project is known."""
1977
+ when the project is known. ``every``: every file, hashed here (engine 0.7.0a43)."""
1969
1978
  key = _developer_key(required=bool(project_id))
1970
1979
  if project_id:
1971
1980
  _project_ready(client, project_id, key)
1972
1981
  try:
1973
- result = client.seal(data, name=args.name, lines=lines, project_id=project_id)
1982
+ result = client.seal(data, name=args.name, lines=lines, project_id=project_id,
1983
+ files_manifest=filelist.manifest_json(every) if every else None)
1974
1984
  if "pending_id" in result: # chained: sign, then finalise
1985
+ if every and result["statement"].get("type") == "codeimprint.chain-seal.v2":
1986
+ filelist.check_statement(result["statement"], every, result.get("files_seed"))
1975
1987
  pub = chainseal.public_key(key)
1976
1988
  result = client.finalise(project_id, result["pending_id"], pub,
1977
1989
  chainseal.sign(key, result["statement"]))
1990
+ elif every:
1991
+ _check_counts(result, every)
1978
1992
  if lines is not None:
1979
1993
  chainseal.check_lines(lines, result)
1980
1994
  except (ApiError, NetworkError) as exc:
@@ -2015,6 +2029,17 @@ def _seal_zip(args, client: Client, data: bytes, project_id: str | None,
2015
2029
  return _finish(args, client, root, result, keys, checks, signer)
2016
2030
 
2017
2031
 
2032
+ def _check_counts(result: dict, every: dict) -> None:
2033
+ """A zip seal outside a project: the attested count and size are what was hashed here."""
2034
+ files = (((result.get("receipt") or {}).get("attestation") or {}).get("statement")
2035
+ or {}).get("files")
2036
+ if files is None or result.get("already_sealed"):
2037
+ return # an older server: Python files only
2038
+ size = sum(s for k, s, _ in every.values() if k in filelist.HASHED)
2039
+ if (files.get("count"), files.get("bytes")) != (len(every), size):
2040
+ raise RuntimeError("the server attested another file list than this client hashed")
2041
+
2042
+
2018
2043
  def _confirm_upload(args, client: Client):
2019
2044
  def ask(count: int, size: int) -> bool:
2020
2045
  _say(f"About to send to {client.url}:",
@@ -2084,7 +2109,11 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
2084
2109
  signer = trust.fingerprint(trust.public_raw(key))
2085
2110
  extra = [f"Commit {last['commit'][:12]}" + (f" ({last['info']['ref']})"
2086
2111
  if last["info"]["ref"] else ""),
2087
- (f"Files {last['files']} Python file(s); uploaded {last['uploaded']} "
2112
+ (f"Files {last['integrity_files']} file(s) hashed here; "
2113
+ f"{last['files']} Python file(s) fingerprinted, uploaded {last['uploaded']} "
2114
+ f"({project.human_size(last['upload_bytes'])}), the rest were already known"
2115
+ if last.get("integrity_files") is not None else
2116
+ f"Files {last['files']} Python file(s); uploaded {last['uploaded']} "
2088
2117
  f"({project.human_size(last['upload_bytes'])}), the rest were already "
2089
2118
  "fingerprinted")]
2090
2119
  rel = result["imprint"].get("release")
@@ -2183,8 +2212,12 @@ def cmd_seal(args) -> int:
2183
2212
  raise Abort("this repository has no commits yet: commit first, then seal")
2184
2213
  rc = _seal_git(args, client, root, cfg)
2185
2214
  else:
2186
- data = _prepare_upload(args.path, "seal", client, args.yes)
2187
- rc = _seal_zip(args, client, data, cfg.get("project_id"), _folder_lines(args.path))
2215
+ every = project.every_file(args.path)
2216
+ if not every:
2217
+ raise SealFailed(chainseal.NOTHING_TO_SEAL)
2218
+ data = _prepare_upload(args.path, "seal", client, args.yes, every)
2219
+ rc = _seal_zip(args, client, data, cfg.get("project_id"), _folder_lines(args.path),
2220
+ every)
2188
2221
  except SealFailed as exc:
2189
2222
  refusal = _plan_refusal(exc)
2190
2223
  if refusal is not None: # the plan said no: never silent (CIM-BE-53-v1)
@@ -2874,6 +2907,8 @@ def _print_result(r: dict, fail_above: float) -> None:
2874
2907
 
2875
2908
 
2876
2909
  def cmd_check(args) -> int:
2910
+ if getattr(args, "files", False): # every file against a seal's list (0.5.0a35)
2911
+ return cmd_check_files(args)
2877
2912
  root = Path(args.path)
2878
2913
  cfg = project.load_config(root) if root.is_dir() else {}
2879
2914
  reference = args.reference or os.environ.get("CODEIMPRINT_REFERENCE") or cfg.get("reference")
@@ -3279,6 +3314,185 @@ def cmd_verify(args) -> int:
3279
3314
  return 0 if valid else 1
3280
3315
 
3281
3316
 
3317
+ # -- every file (engine 0.7.0a44): the owner's comparison and proofs ------------------------
3318
+ def _default_seal(root: Path, given: str | None) -> str:
3319
+ """--seal, else the seal of this folder's baseline receipt."""
3320
+ if given:
3321
+ if not imprint_file.is_valid_id(given):
3322
+ raise Abort(f"not a valid Imprint ID: {given}")
3323
+ return imprint_file.clean_id(given)
3324
+ rec = root / project.CONFIG_DIR / "baseline.receipt.json"
3325
+ try:
3326
+ return json.loads(rec.read_text(encoding="utf-8"))["imprint_id"]
3327
+ except (OSError, ValueError, KeyError) as exc:
3328
+ raise Abort("no seal given: pass --seal <Imprint ID> (or seal this folder first)") \
3329
+ from exc
3330
+
3331
+
3332
+ def _seal_list(client: Client, seal: str) -> dict:
3333
+ try:
3334
+ return client.seal_files(seal)
3335
+ except ApiError as exc:
3336
+ if exc.status == 404:
3337
+ raise Abort(f"{seal} has no file list for you: it was sealed before engine "
3338
+ "0.7.0a43, its list was erased, or it is not your project's seal") \
3339
+ from exc
3340
+ raise Abort(_explain(client, exc, "cannot read the seal's file list")) from exc
3341
+ except NetworkError as exc:
3342
+ raise Abort(str(exc)) from exc
3343
+
3344
+
3345
+ def _local_entries(root: Path, worktree: bool, rev: str | None) -> tuple[dict, str]:
3346
+ """(entries, what was compared): a commit of this repository (default HEAD), or the
3347
+ working tree. Everything is hashed here; nothing is sent."""
3348
+ exclude = list(project.load_config(root).get("exclude", [])) if root.is_dir() else []
3349
+ git = gitrepo.is_repo(root)
3350
+ if worktree or not git:
3351
+ entries = {p: e for p, e in project.every_file(root).items()
3352
+ if not filelist.excluded(p, exclude)}
3353
+ if git: # a submodule is its recorded commit, as in the seal
3354
+ for f in gitrepo.ls_tree_all(gitrepo.toplevel(root), "HEAD",
3355
+ gitrepo.prefix(root)):
3356
+ if f["mode"] == "submodule" and not filelist.excluded(f["path"], exclude):
3357
+ entries[f["path"]] = ["submodule", 0, f["blob"]]
3358
+ return entries, "the working tree"
3359
+ top, commit = gitrepo.toplevel(root), gitrepo.resolve(root, rev or "HEAD")
3360
+ listed = [f for f in gitrepo.ls_tree_all(top, commit, gitrepo.prefix(root))
3361
+ if not f["path"].startswith(".imprint/")]
3362
+ digests = gitrepo.hash_blobs(top, sorted({f["blob"] for f in listed
3363
+ if f["mode"] != "submodule"}))
3364
+ for f in listed:
3365
+ if f["mode"] != "submodule":
3366
+ f["sha256"], f["size"] = digests[f["blob"]]
3367
+ return filelist.entries_of(listed, exclude), f"commit {commit[:12]}"
3368
+
3369
+
3370
+ DIFF_LABELS = (("added", "Added", "not in the seal"),
3371
+ ("removed", "Removed", "in the seal only"),
3372
+ ("changed", "Changed", "other content"),
3373
+ ("mode", "Mode", "same content, other mode"),
3374
+ ("unhashed", "Not hashed", "listed in the seal without a hash"))
3375
+
3376
+
3377
+ def cmd_check_files(args) -> int:
3378
+ """`imprint check --files`: this folder's files against a seal's list, hashed here."""
3379
+ root = Path(args.path)
3380
+ seal = _default_seal(root, args.seal)
3381
+ client = _client(args, _server_from_project(root))
3382
+ body = _seal_list(client, seal)
3383
+ if body.get("scheme") != filelist.SCHEME:
3384
+ raise Abort(f"the seal lists its files with {body.get('scheme')!r}, which this "
3385
+ "client does not know: upgrade it")
3386
+ try:
3387
+ local, what = _local_entries(root, args.worktree, args.commit)
3388
+ except gitrepo.GitError as exc:
3389
+ raise Abort(f"cannot read the repository: {exc}") from exc
3390
+ diff = filelist.compare(filelist.sealed_entries(body), local)
3391
+ count = sum(len(diff[k]) for k in ("added", "removed", "changed", "mode"))
3392
+ if args.format == "json":
3393
+ print(json.dumps({"seal": seal, "compared": what, "files": body["count"],
3394
+ "same": count == 0, **diff}, indent=2))
3395
+ else:
3396
+ commit = f", commit {body['commit'][:12]}" if body.get("commit") else ""
3397
+ _say(f"Seal {seal} ({body['count']} files{commit})",
3398
+ f"Compared {what}, hashed here (nothing was sent)")
3399
+ for key, label, note in DIFF_LABELS:
3400
+ for path in diff[key]:
3401
+ _say(f"{label:<10} {path} ({note})")
3402
+ _say(f"Result {'every file matches the seal' if not count else f'{count} file(s) differ'}")
3403
+ if count and _ci(): # never break a build by surprise
3404
+ _warn(f"{count} file(s) differ from seal {seal}")
3405
+ return 0
3406
+ return 1 if count else 0
3407
+
3408
+
3409
+ def cmd_prove(args) -> int:
3410
+ """`imprint prove <path>`: a proof that one file is in a seal, for anyone to check."""
3411
+ root = Path(args.root)
3412
+ seal = _default_seal(root, args.seal)
3413
+ target = Path(args.path)
3414
+ rel = (target.resolve().relative_to(root.resolve()).as_posix()
3415
+ if target.exists() or target.is_symlink() else args.path.replace("\\", "/"))
3416
+ client = _client(args, _server_from_project(root))
3417
+ body = _seal_list(client, seal)
3418
+ try:
3419
+ proof = filelist.make_proof(body, rel, client.public_imprint(seal), client.url)
3420
+ except KeyError as exc:
3421
+ raise Abort(f"{rel} is not in seal {seal}") from exc
3422
+ except (ApiError, NetworkError) as exc:
3423
+ raise Abort(f"cannot read the seal's public record: {exc}") from exc
3424
+ out = Path(args.output or f"{Path(rel).name}.proof.json")
3425
+ out.write_text(json.dumps(proof, indent=1, sort_keys=True) + "\n", encoding="utf-8")
3426
+ _say(f"Seal {seal}", f"File {rel} ({proof['kind']}, {proof['size']:,} bytes)",
3427
+ f"Proof {out}",
3428
+ "Shares this file's hash, size, mode and salt only; no other file of the seal",
3429
+ f"Check imprint verify-file {rel} --proof {out}")
3430
+ if target.exists() or target.is_symlink():
3431
+ here = filelist.local_file(target, proof["kind"])
3432
+ if here[1:] != [proof["size"], proof["ref"]]:
3433
+ _warn("the file here is not the sealed one: the proof is for the sealed content")
3434
+ return 0
3435
+
3436
+
3437
+ def cmd_verify_file(args) -> int:
3438
+ """`imprint verify-file <file> --proof P`: no account. The seal's receipt is verified,
3439
+ then the file's hash, through the proof, is shown to be in the sealed list."""
3440
+ try:
3441
+ proof = json.loads(Path(args.proof).read_text(encoding="utf-8"))
3442
+ except (OSError, ValueError) as exc:
3443
+ raise Abort(f"cannot read {args.proof}: {exc}") from exc
3444
+ url = args.url or proof.get("server")
3445
+ rec = proof.get("receipt")
3446
+ client = Client(url) if url else None
3447
+ if rec is None:
3448
+ if client is None:
3449
+ raise Abort("the proof holds no receipt: pass --url to fetch it")
3450
+ try:
3451
+ rec = client.public_imprint(proof["seal"])
3452
+ except (ApiError, NetworkError, KeyError) as exc:
3453
+ raise Abort(f"cannot fetch the seal's public record: {exc}") from exc
3454
+ why = receipt.newer_format(rec)
3455
+ if why:
3456
+ return _newer_result(args, rec.get("imprint_id"), why, receipt.newer_message())
3457
+ checks: list[receipt.Check] = []
3458
+ if args.keys:
3459
+ keys = _trusted_keys(args, Path("."), None, checks)
3460
+ elif client is not None:
3461
+ keys = _trusted_keys(args, Path("."), client, checks)
3462
+ else:
3463
+ keys = _trusted_keys(args, Path("."), None, checks)
3464
+ checks += [c for c in receipt.verify(rec, keys, None, anchors=_anchors(args))]
3465
+ st = (rec.get("attestation") or {}).get("statement") or {}
3466
+ files = st.get("files") or {}
3467
+ if rec.get("imprint_id") != proof.get("seal"):
3468
+ checks.append(receipt.Check("file", receipt.FAIL, "the receipt is for another seal"))
3469
+ elif not files:
3470
+ checks.append(receipt.Check("file", receipt.FAIL, "this seal lists no files (sealed "
3471
+ "before engine 0.7.0a43)"))
3472
+ else:
3473
+ try:
3474
+ here = filelist.local_file(args.file, proof.get("kind"))
3475
+ except OSError as exc:
3476
+ raise Abort(f"cannot read {args.file}: {exc}") from exc
3477
+ problems = filelist.check_proof(proof, files, here)
3478
+ name = filelist.proof_path(proof)
3479
+ checks.append(receipt.Check("file", receipt.FAIL if problems else receipt.PASS,
3480
+ "; ".join(problems) if problems else
3481
+ f"{name} ({here[0]}, {here[1]:,} bytes) is file "
3482
+ f"{proof['index'] + 1} of {files['count']} in the sealed, "
3483
+ "signed and logged list"))
3484
+ failed = [c for c in checks if c.status == receipt.FAIL]
3485
+ if args.json:
3486
+ print(json.dumps({"seal": proof.get("seal"), "valid": not failed,
3487
+ "checks": [c.as_dict() for c in checks]}, indent=2))
3488
+ else:
3489
+ _say(f"Seal {proof.get('seal')}", "")
3490
+ for c in checks:
3491
+ _say(f"{c.status:<5} {c.name:<20} {c.detail}")
3492
+ _say("", f"Result {'VERIFIED' if not failed else 'NOT VERIFIED'}", "", SEAL_NOTE)
3493
+ return 1 if failed else 0
3494
+
3495
+
3282
3496
  # -- parser --------------------------------------------------------------------------------
3283
3497
  def build_parser() -> argparse.ArgumentParser:
3284
3498
  p = argparse.ArgumentParser(prog="imprint", description="CodeImprint — seal and check "
@@ -3594,8 +3808,37 @@ def build_parser() -> argparse.ArgumentParser:
3594
3808
  c.add_argument("-o", "--output", help="also write the JSON result to this file")
3595
3809
  c.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3596
3810
  c.add_argument("--yes", action="store_true", help="do not ask before uploading (CI)")
3811
+ c.add_argument("--files", action="store_true",
3812
+ help="compare every file with a seal's file list, hashed here; nothing is "
3813
+ "uploaded (engine 0.7.0a44, the seal's owner)")
3814
+ c.add_argument("--seal", help="with --files: the seal (default: this folder's baseline)")
3815
+ c.add_argument("--commit", help="with --files: the commit to compare (default HEAD)")
3816
+ c.add_argument("--worktree", action="store_true",
3817
+ help="with --files: compare the working tree instead of a commit")
3597
3818
  c.set_defaults(func=cmd_check)
3598
3819
 
3820
+ pv = sub.add_parser("prove", help="make a proof that one file is in a seal (its owner)")
3821
+ pv.add_argument("path", help="the file, as in the sealed folder")
3822
+ pv.add_argument("--seal", help="the seal (default: this folder's baseline)")
3823
+ pv.add_argument("--root", default=".", help="the sealed folder (default: here)")
3824
+ pv.add_argument("-o", "--output", help="where to write it (default <name>.proof.json)")
3825
+ pv.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3826
+ pv.set_defaults(func=cmd_prove)
3827
+
3828
+ vf = sub.add_parser("verify-file", help="check that a file is in a seal, from a proof "
3829
+ "(no account)",
3830
+ epilog="Exit codes: 0 VERIFIED; 1 NOT VERIFIED; 2 a usage or other "
3831
+ "error; 3 a newer format than this client understands.")
3832
+ vf.add_argument("file", help="the file to check")
3833
+ vf.add_argument("--proof", required=True, help="the proof (from `imprint prove`)")
3834
+ vf.add_argument("--keys", metavar="FILE",
3835
+ help="trust only these server keys (a codeimprint-keys.json)")
3836
+ vf.add_argument("--url", help="the server (default: the one the proof names)")
3837
+ vf.add_argument("--tsa-certs", metavar="FILE",
3838
+ help="also trust the time-stamping authorities in this PEM bundle")
3839
+ vf.add_argument("--json", action="store_true")
3840
+ vf.set_defaults(func=cmd_verify_file)
3841
+
3599
3842
  v = sub.add_parser("verify", help="verify a seal offline: .imprint file, receipt or ID",
3600
3843
  epilog="Exit codes: 0 VERIFIED; 1 NOT VERIFIED (a check failed, or a "
3601
3844
  "warning with --strict); 2 a usage or other error; 3 a newer "
@@ -0,0 +1,289 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Every file of a seal, hashed on this machine (engine 0.7.0a43+, scheme
3
+ ``sha256-leaf-v1+rfc6962``).
4
+
5
+ A seal lists every tracked file: the SHA-256 of its raw bytes, its size and its mode. The
6
+ server publishes only the Merkle root of the salted list, the number of files and their size;
7
+ this module rebuilds that root from what this client hashed, under the seal's seed, before the
8
+ developer signs it. The leaf format is public (the hub's frontend contract, section 3.19):
9
+
10
+ "CIF1" || salt (32) || u32 len(path) || path || kind (1) || u64 size || u8 len(ref) || ref
11
+
12
+ with integers big-endian, ``path`` the raw bytes Git stores, and the salt
13
+ SHA-256(SHA-256("CIF1 file-leaf" || 0x00 || seed || u32 len(path) || path)). This is integrity
14
+ only: plain SHA-256 over raw bytes. The fingerprint stays on the server.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import base64
20
+ import fnmatch
21
+ import hashlib
22
+ import json
23
+
24
+ from .imprint_file import canonical
25
+ from .transparency import leaf_hash, node_hash
26
+
27
+ SCHEME = "sha256-leaf-v1+rfc6962"
28
+ KINDS = {"regular": 1, "executable": 2, "symlink": 3, "submodule": 4, "unhashed": 5}
29
+ HASHED = ("regular", "executable", "symlink")
30
+ GIT_MODES = {"100644": "regular", "100664": "regular", "100755": "executable",
31
+ "120000": "symlink", "160000": "submodule"}
32
+ CHUNK = 1024 * 1024
33
+
34
+
35
+ class FileListMismatch(RuntimeError):
36
+ """The server's statement does not describe the files this client hashed."""
37
+
38
+
39
+ def path_bytes(path: str) -> bytes:
40
+ return path.encode("utf-8", "surrogateescape")
41
+
42
+
43
+ def _derive(label: bytes, seed: bytes, data: bytes = b"") -> bytes:
44
+ if len(seed) != 32:
45
+ raise ValueError("a seal's seed is 32 bytes")
46
+ return hashlib.sha256(hashlib.sha256(b"CIF1 " + label + b"\x00" + seed + data).digest()
47
+ ).digest()
48
+
49
+
50
+ def leaf_salt(seed: bytes, path: str) -> bytes:
51
+ pb = path_bytes(path)
52
+ return _derive(b"file-leaf", seed, len(pb).to_bytes(4, "big") + pb)
53
+
54
+
55
+ def leaf_bytes(salt: bytes, path: str, kind: str, size: int, ref: str) -> bytes:
56
+ pb, rb = path_bytes(path), bytes.fromhex(ref)
57
+ return (b"CIF1" + salt + len(pb).to_bytes(4, "big") + pb + bytes([KINDS[kind]])
58
+ + size.to_bytes(8, "big") + bytes([len(rb)]) + rb)
59
+
60
+
61
+ def _root(hashes: list[bytes]) -> bytes:
62
+ if not hashes:
63
+ return hashlib.sha256(b"").digest()
64
+ if len(hashes) == 1:
65
+ return hashes[0]
66
+ k = 1
67
+ while k << 1 < len(hashes):
68
+ k <<= 1
69
+ return node_hash(_root(hashes[:k]), _root(hashes[k:]))
70
+
71
+
72
+ def root(entries: dict[str, list], seed: bytes) -> str:
73
+ """The RFC 6962 root of {path: [kind, size, ref]} under ``seed`` (hex)."""
74
+ order = sorted(entries, key=path_bytes)
75
+ return _root([leaf_hash(leaf_bytes(leaf_salt(seed, p), p, *entries[p]))
76
+ for p in order]).hex()
77
+
78
+
79
+ def b64e(data: bytes) -> str:
80
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
81
+
82
+
83
+ def commitment(seed: bytes, commit: str | None, tree: str | None) -> str | None:
84
+ """The public commitment to a seal's commit and tree IDs."""
85
+ if not commit and not tree:
86
+ return None
87
+ salt = b64e(_derive(b"commit-commitment", seed))
88
+ return hashlib.sha256(canonical({"salt": salt, "commit": commit, "tree": tree})).hexdigest()
89
+
90
+
91
+ def hash_stream(read) -> tuple[str, int]:
92
+ h, size = hashlib.sha256(), 0
93
+ while True:
94
+ part = read(CHUNK)
95
+ if not part:
96
+ return h.hexdigest(), size
97
+ h.update(part)
98
+ size += len(part)
99
+
100
+
101
+ def excluded(path: str, patterns: list[str]) -> bool:
102
+ """The engine's exclude rule: a glob on the relative path; ``*`` crosses folders."""
103
+ return any(fnmatch.fnmatchcase(path, p) for p in patterns)
104
+
105
+
106
+ def entries_of(listed: list[dict], exclude: list[str] | None = None) -> dict[str, list]:
107
+ """{path: [kind, size, ref]} of a plan's files, as the server seals them."""
108
+ out = {}
109
+ for f in listed:
110
+ if f["path"].startswith(".imprint/") or (exclude and excluded(f["path"], exclude)):
111
+ continue
112
+ out[f["path"]] = (["submodule", 0, f["blob"]] if f["mode"] == "submodule"
113
+ else [f["mode"], f["size"], f["sha256"]])
114
+ return out
115
+
116
+
117
+ def check_statement(statement: dict, entries: dict[str, list], seed_hex: str | None,
118
+ commit: str | None = None, tree: str | None = None) -> dict:
119
+ """Refuse to sign a statement whose files block is not what this client hashed: the
120
+ scheme, the count, the size, the root under the seal's seed and the commit commitment.
121
+ Returns the files block."""
122
+ files = statement.get("files") or {}
123
+ if files.get("scheme") != SCHEME:
124
+ raise FileListMismatch(f"the server seals files with {files.get('scheme')!r}, which "
125
+ "this client does not know: upgrade it")
126
+ try:
127
+ seed = bytes.fromhex(seed_hex or "")
128
+ mine = root(entries, seed)
129
+ except ValueError as exc:
130
+ raise FileListMismatch("the server sent no usable seed for the file list") from exc
131
+ size = sum(s for k, s, _ in entries.values() if k in HASHED)
132
+ if (files.get("count"), files.get("bytes"), files.get("unhashed"),
133
+ files.get("attested_by"), files.get("root")) != (len(entries), size, 0,
134
+ "developer", mine):
135
+ raise FileListMismatch("the server's file list is not the one this client hashed; "
136
+ "nothing was signed")
137
+ if commit is not None and statement.get("commit_commitment") != commitment(seed, commit,
138
+ tree):
139
+ raise FileListMismatch("the server's commit commitment is not for this commit; "
140
+ "nothing was signed")
141
+ return files
142
+
143
+
144
+ def manifest_json(entries: dict[str, list]) -> bytes:
145
+ """A zip seal's list for the server: [{path, mode, size, sha256}]."""
146
+ return json.dumps([{"path": p, "mode": k, "size": s, "sha256": r}
147
+ for p, (k, s, r) in sorted(entries.items())]).encode()
148
+
149
+
150
+ def summary(statement: dict) -> str:
151
+ """'Integrity: N files · Fingerprint: …' for a seal's attestation (or chain) statement."""
152
+ files = statement.get("files")
153
+ if not files:
154
+ return "Python-only seal (before engine 0.7.0a43)"
155
+ by = "hashed on this machine" if files.get("attested_by") == "developer" else \
156
+ "hashed by CodeImprint"
157
+ python = next((f for f in statement.get("fingerprints") or []
158
+ if f.get("handler") == "python"), None)
159
+ print_ = (f"Python ({python['files']} file{'s' if python['files'] != 1 else ''})"
160
+ if python else "none (Python only today)")
161
+ extra = f", {files['unhashed']} listed without a hash" if files.get("unhashed") else ""
162
+ return f"{files['count']} files ({by}{extra}) · Fingerprint: {print_}"
163
+
164
+
165
+ # -- the owner's list (engine 0.7.0a44): compare, prove one file, check a proof -----------
166
+ PROOF = "codeimprint.file-proof.v1"
167
+
168
+
169
+ def sealed_entries(body: dict) -> dict[str, list]:
170
+ """{path: [kind, size, ref]} from the server's answer (raw path bytes kept)."""
171
+ out = {}
172
+ for f in body.get("files") or []:
173
+ path = (bytes.fromhex(f["path_hex"]).decode("utf-8", "surrogateescape")
174
+ if f.get("path_hex") else f["path"])
175
+ out[path] = [f["kind"], f["size"], f["ref"]]
176
+ return out
177
+
178
+
179
+ def compare(sealed: dict[str, list], local: dict[str, list]) -> dict[str, list[str]]:
180
+ """What differs: {added, removed, changed, mode, unhashed}, each a sorted list of paths.
181
+ ``mode``: the same content with another mode. ``unhashed``: files the seal lists without
182
+ a hash, which cannot be compared."""
183
+ out: dict[str, list[str]] = {"added": [], "removed": [], "changed": [], "mode": [],
184
+ "unhashed": []}
185
+ for path in sorted(set(sealed) | set(local), key=path_bytes):
186
+ if path not in local:
187
+ out["removed"].append(path)
188
+ elif path not in sealed:
189
+ out["added"].append(path)
190
+ elif sealed[path][0] == "unhashed":
191
+ out["unhashed"].append(path)
192
+ elif sealed[path] != local[path]:
193
+ same = sealed[path][1:] == local[path][1:]
194
+ out["mode" if same else "changed"].append(path)
195
+ return out
196
+
197
+
198
+ def _path(hashes: list[bytes], m: int) -> list[bytes]:
199
+ """RFC 6962 audit path of leaf ``m`` in ``hashes``."""
200
+ n = len(hashes)
201
+ if n <= 1:
202
+ return []
203
+ k = 1
204
+ while k << 1 < n:
205
+ k <<= 1
206
+ if m < k:
207
+ return _path(hashes[:k], m) + [_root(hashes[k:])]
208
+ return _path(hashes[k:], m - k) + [_root(hashes[:k])]
209
+
210
+
211
+ def make_proof(body: dict, path: str, receipt: dict | None = None,
212
+ server: str | None = None) -> dict:
213
+ """A proof that ``path`` is in the seal, revealing that one file only: its kind, size,
214
+ hash, salt and audit path. With the seal's public receipt, anyone can check it."""
215
+ entries = sealed_entries(body)
216
+ if path not in entries:
217
+ raise KeyError(path)
218
+ seed = bytes.fromhex(body["seed"])
219
+ order = sorted(entries, key=path_bytes)
220
+ hashes = [leaf_hash(leaf_bytes(leaf_salt(seed, p), p, *entries[p])) for p in order]
221
+ index = order.index(path)
222
+ kind, size, ref = entries[path]
223
+ raw = path_bytes(path)
224
+ out = {"type": PROOF, "scheme": SCHEME, "seal": body["imprint_id"],
225
+ "path": raw.decode("utf-8", "replace"), "kind": kind, "size": size, "ref": ref,
226
+ "salt": leaf_salt(seed, path).hex(), "index": index, "count": len(order),
227
+ "inclusion_proof": [h.hex() for h in _path(hashes, index)]}
228
+ if out["path"].encode("utf-8") != raw:
229
+ out["path_hex"] = raw.hex()
230
+ if server:
231
+ out["server"] = server
232
+ if receipt is not None:
233
+ out["receipt"] = receipt
234
+ return out
235
+
236
+
237
+ def proof_path(proof: dict) -> str:
238
+ return (bytes.fromhex(proof["path_hex"]).decode("utf-8", "surrogateescape")
239
+ if proof.get("path_hex") else proof["path"])
240
+
241
+
242
+ def check_proof(proof: dict, files: dict, local: list | None) -> list[str]:
243
+ """Problems with a file proof against the seal's attested ``files`` block (empty: it
244
+ holds). ``local``: [kind, size, sha256] of the file on this machine, or None."""
245
+ from .transparency import verify_inclusion
246
+
247
+ problems = []
248
+ if proof.get("type") != PROOF or proof.get("scheme") != SCHEME:
249
+ return [f"not a {PROOF} proof for {SCHEME}"]
250
+ if files.get("scheme") != SCHEME:
251
+ return ["the seal does not list its files in this scheme"]
252
+ if proof.get("count") != files.get("count"):
253
+ problems.append("the proof is for another number of files than the seal lists")
254
+ try:
255
+ leaf = leaf_bytes(bytes.fromhex(proof["salt"]), proof_path(proof), proof["kind"],
256
+ proof["size"], proof["ref"])
257
+ audit = [bytes.fromhex(h) for h in proof["inclusion_proof"]]
258
+ root_ = bytes.fromhex(files["root"])
259
+ except (KeyError, ValueError, TypeError):
260
+ return problems + ["the proof is malformed"]
261
+ if not verify_inclusion(proof["index"], proof["count"], leaf_hash(leaf), audit, root_):
262
+ problems.append("the file is not in the sealed list (the audit path does not reach "
263
+ "the attested root)")
264
+ if local is not None:
265
+ if proof["kind"] == "unhashed":
266
+ problems.append("the seal lists this file without a hash")
267
+ elif local[2] != proof["ref"] or local[1] != proof["size"]:
268
+ problems.append("this file's content is not the sealed one")
269
+ elif local[0] != proof["kind"]:
270
+ problems.append(f"the file is {local[0]} here but {proof['kind']} in the seal")
271
+ return problems
272
+
273
+
274
+ def local_file(path, kind_hint: str | None = None) -> list:
275
+ """[kind, size, sha256] of a file on this machine (a link: its target text)."""
276
+ import os
277
+ from pathlib import Path
278
+
279
+ p = Path(path)
280
+ if p.is_symlink():
281
+ target = os.readlink(p).encode("utf-8", "surrogateescape")
282
+ return ["symlink", len(target), hashlib.sha256(target).hexdigest()]
283
+ with open(p, "rb") as f:
284
+ sha, size = hash_stream(f.read)
285
+ if os.name == "nt": # no executable bit here: take the seal's, the content decides
286
+ kind = kind_hint if kind_hint in ("regular", "executable") else "regular"
287
+ else:
288
+ kind = "executable" if p.stat().st_mode & 0o111 else "regular"
289
+ return [kind, size, sha]
@@ -12,6 +12,8 @@ import os
12
12
  import subprocess
13
13
  from pathlib import Path
14
14
 
15
+ from . import filelist
16
+
15
17
 
16
18
  class GitError(Exception):
17
19
  """Not a Git repository, or a git command failed."""
@@ -202,6 +204,61 @@ def ls_tree(root: Path, commit: str, under: str = "") -> list[dict]:
202
204
  return files
203
205
 
204
206
 
207
+ def ls_tree_all(root: Path, commit: str, under: str = "") -> list[dict]:
208
+ """Every entry of a commit (engine 0.7.0a43: every file is sealed): [{path, blob, size,
209
+ mode}] with ``mode`` regular, executable, symlink or submodule (a submodule's ``blob`` is
210
+ its gitlink commit, size 0). Paths keep Git's raw bytes (``surrogateescape``)."""
211
+ out = _git(root, "ls-tree", "-r", "-z", "--long", "--full-tree", commit)
212
+ files = []
213
+ for record in out.split(b"\0"):
214
+ if not record:
215
+ continue
216
+ meta, _, path = record.partition(b"\t")
217
+ mode, kind, blob, size = meta.decode().split()
218
+ name = path.decode("utf-8", errors="surrogateescape")
219
+ if kind not in ("blob", "commit") or not name.startswith(under):
220
+ continue
221
+ files.append({"path": name[len(under):], "blob": blob,
222
+ "size": int(size) if size.isdigit() else 0,
223
+ "mode": filelist.GIT_MODES.get(mode, "regular")})
224
+ return files
225
+
226
+
227
+ def hash_blobs(root: Path, blob_ids: list[str]) -> dict[str, tuple[str, int]]:
228
+ """{blob ID: (SHA-256, size)} of each blob's raw bytes, read in parts through one
229
+ `git cat-file --batch` process: a large file is never held whole."""
230
+ out: dict[str, tuple[str, int]] = {}
231
+ if not blob_ids:
232
+ return out
233
+ proc = subprocess.Popen(["git", "-C", str(root), "cat-file", "--batch"],
234
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE)
235
+ try:
236
+ for blob in blob_ids:
237
+ proc.stdin.write(blob.encode() + b"\n")
238
+ proc.stdin.flush()
239
+ header = proc.stdout.readline().split()
240
+ if len(header) != 3:
241
+ raise GitError(f"blob {blob} is missing from the repository")
242
+ left = int(header[2])
243
+
244
+ def read(n: int) -> bytes:
245
+ nonlocal left
246
+ if left <= 0:
247
+ return b""
248
+ part = proc.stdout.read(min(n, left))
249
+ if not part:
250
+ raise GitError("a blob ended early")
251
+ left -= len(part)
252
+ return part
253
+
254
+ out[blob] = filelist.hash_stream(read)
255
+ proc.stdout.read(1) # the newline after each object
256
+ finally:
257
+ proc.stdin.close()
258
+ proc.wait()
259
+ return out
260
+
261
+
205
262
  def read_blobs(root: Path, blob_ids: list[str]):
206
263
  """Yield (blob ID, content) for each ID, via one `git cat-file --batch` process."""
207
264
  if not blob_ids:
@@ -9,6 +9,7 @@ symlinks, version-control folders and virtual environments.
9
9
  from __future__ import annotations
10
10
 
11
11
  import fnmatch
12
+ import hashlib
12
13
  import io
13
14
  import json
14
15
  import os
@@ -18,6 +19,8 @@ from pathlib import Path
18
19
 
19
20
  import pathspec
20
21
 
22
+ from . import filelist
23
+
21
24
  CONFIG_DIR = ".imprint"
22
25
  CONFIG_FILE = "config.json"
23
26
  SOURCE_SUFFIXES = (".py",)
@@ -110,6 +113,55 @@ def select_files(root: str | Path, suffixes: tuple[str, ...] | None = SOURCE_SUF
110
113
  return sel
111
114
 
112
115
 
116
+ VCS_DIRS = {".git", ".hg", ".svn", CONFIG_DIR}
117
+
118
+
119
+ def every_file(root: str | Path) -> dict[str, list]:
120
+ """Every file of a folder sealed as a zip (engine 0.7.0a43), hashed here: {path: [mode,
121
+ size, SHA-256]}. Only .gitignore, .imprint/config.json excludes and version-control folders
122
+ leave files out (no Python filter, no size limit); a link is its target text."""
123
+ root = Path(root).resolve()
124
+ excludes = list(load_config(root).get("exclude", []))
125
+ ignores: list[tuple[str, pathspec.GitIgnoreSpec]] = []
126
+ out: dict[str, list] = {}
127
+
128
+ def ignored(rel: str, is_dir: bool) -> bool:
129
+ for prefix, spec in ignores:
130
+ if prefix and not rel.startswith(prefix):
131
+ continue
132
+ if spec.match_file(rel[len(prefix):] + ("/" if is_dir else "")):
133
+ return True
134
+ return False
135
+
136
+ for dirpath, dirnames, filenames in os.walk(root):
137
+ here = Path(dirpath)
138
+ rel_dir = here.relative_to(root).as_posix()
139
+ prefix = "" if rel_dir == "." else rel_dir + "/"
140
+ if (here / ".gitignore").is_file():
141
+ lines = (here / ".gitignore").read_text(encoding="utf-8",
142
+ errors="replace").splitlines()
143
+ ignores.append((prefix, pathspec.GitIgnoreSpec.from_lines(lines)))
144
+ dirnames[:] = [d for d in sorted(dirnames)
145
+ if d not in VCS_DIRS and not (here / d).is_symlink()
146
+ and not (here / d / ".git").exists() # a submodule
147
+ and not ignored(prefix + d, True)
148
+ and not _excluded(prefix + d + "/", excludes)]
149
+ for name in sorted(filenames):
150
+ rel, path = prefix + name, here / name
151
+ if ignored(rel, False) or _excluded(rel, excludes):
152
+ continue
153
+ if path.is_symlink():
154
+ target = os.readlink(path).encode("utf-8", "surrogateescape")
155
+ out[rel] = ["symlink", len(target), hashlib.sha256(target).hexdigest()]
156
+ continue
157
+ with open(path, "rb") as f:
158
+ sha, size = filelist.hash_stream(f.read)
159
+ mode = "executable" if os.name != "nt" and path.stat().st_mode & 0o111 else \
160
+ "regular"
161
+ out[rel] = [mode, size, sha]
162
+ return out
163
+
164
+
113
165
  def build_zip(sel: Selection) -> bytes:
114
166
  buf = io.BytesIO()
115
167
  with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
@@ -13,7 +13,7 @@ import re
13
13
  from dataclasses import asdict, dataclass
14
14
  from datetime import datetime, timedelta, timezone
15
15
 
16
- from . import imprint_file, records, timestamp, transparency, trust
16
+ from . import filelist, imprint_file, records, timestamp, transparency, trust
17
17
  from .imprint_file import b64d, canonical
18
18
 
19
19
  # The development log's origin. Servers can run under another origin (CODEIMPRINT_LOG_ORIGIN),
@@ -28,7 +28,7 @@ PASS, FAIL, WARN = "PASS", "FAIL", "WARN"
28
28
  # as a failure (42b-01). Its own result, exit code and --json status.
29
29
  NEWER = "NEWER"
30
30
  UPGRADE = "Upgrade: pip install --pre -U codeimprint"
31
- RECEIPT_VERSION = 4 # the newest receipt format this client reads
31
+ RECEIPT_VERSION = 5 # the newest receipt format this client reads
32
32
 
33
33
 
34
34
  @dataclass
@@ -60,9 +60,11 @@ def newer_message(what: str = "seal") -> str:
60
60
  # Every statement, entry and document type this client knows. A well-formed type that is not
61
61
  # one of them (codeimprint.<name>.v<N>) is a newer format; anything else is malformed.
62
62
  KNOWN_TYPES = frozenset({
63
- "codeimprint.attestation.v1", "codeimprint.attestation.v2", "codeimprint.log-entry.v1",
64
- "codeimprint.log-entry.v2", "codeimprint.checkpoint.v1", "codeimprint.timestamps.v1",
65
- RELEASE, "codeimprint.chain-seal.v1", records.RECORD_SIGN, *records.TYPES})
63
+ "codeimprint.attestation.v1", "codeimprint.attestation.v2", "codeimprint.attestation.v3",
64
+ "codeimprint.log-entry.v1", "codeimprint.log-entry.v2", "codeimprint.log-entry.v3",
65
+ "codeimprint.checkpoint.v1", "codeimprint.timestamps.v1", RELEASE,
66
+ "codeimprint.chain-seal.v1", "codeimprint.chain-seal.v2", records.RECORD_SIGN,
67
+ *records.TYPES})
66
68
  _TYPE = re.compile(r"codeimprint\.[a-z][a-z0-9-]*\.v[1-9][0-9]*")
67
69
 
68
70
 
@@ -98,6 +100,9 @@ def newer_format(receipt: dict) -> str | None:
98
100
  "record", "document", "type") else None)):
99
101
  if _unknown_type(value):
100
102
  return f"{label} {value}"
103
+ scheme = at("attestation", "statement", "files", "scheme")
104
+ if isinstance(scheme, str) and scheme != filelist.SCHEME:
105
+ return f"file scheme {scheme}"
101
106
  iid = receipt.get("imprint_id")
102
107
  if isinstance(iid, str) and imprint_file.is_newer_id(iid):
103
108
  return f"ID prefix {imprint_file.clean_id(iid).split('-', 1)[0]}"
@@ -439,10 +444,13 @@ def _attestation(receipt: dict, keys: list[dict]) -> Check:
439
444
  if not ok:
440
445
  return Check("attestation", FAIL, why)
441
446
  st = att["statement"]
442
- if st.get("type") not in ("codeimprint.attestation.v1", "codeimprint.attestation.v2"):
447
+ if st.get("type") not in ("codeimprint.attestation.v1", "codeimprint.attestation.v2",
448
+ ATTESTATION_V3):
443
449
  return Check("attestation", FAIL, "not an attestation statement")
450
+ if st["type"] == ATTESTATION_V3 and not _files_block_ok(st):
451
+ return Check("attestation", FAIL, "the attestation's file list is malformed")
444
452
  chain = receipt.get("chain")
445
- if (st["type"].endswith(".v2") or chain) and "record" not in receipt:
453
+ if (st["type"] != "codeimprint.attestation.v1" or chain) and "record" not in receipt:
446
454
  fields = ("project", "kind", "parents")
447
455
  if not chain or any(st.get(k) != chain.get(k) for k in fields):
448
456
  return Check("attestation", FAIL, "the attestation and the receipt's chain disagree")
@@ -457,6 +465,47 @@ def _attestation(receipt: dict, keys: list[dict]) -> Check:
457
465
 
458
466
 
459
467
  CHAIN_STATEMENT = "codeimprint.chain-seal.v1"
468
+ CHAIN_STATEMENT_V2 = "codeimprint.chain-seal.v2"
469
+ ATTESTATION_V3 = "codeimprint.attestation.v3"
470
+
471
+
472
+ def _count(value) -> bool:
473
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
474
+
475
+
476
+ def _files_block_ok(st: dict) -> bool:
477
+ """An attestation v3: every file's root and counts, the fingerprint handlers, and (Git
478
+ seals) the commit commitment, all of the right shape."""
479
+ files = st.get("files")
480
+ if not isinstance(files, dict) or files.get("scheme") != filelist.SCHEME:
481
+ return False
482
+ if not _hex64(files.get("root")) or files.get("attested_by") not in ("developer", "server"):
483
+ return False
484
+ if not all(_count(files.get(k)) for k in ("count", "bytes", "unhashed")):
485
+ return False
486
+ if files["unhashed"] > files["count"]:
487
+ return False
488
+ prints = st.get("fingerprints")
489
+ if not isinstance(prints, list) or not all(
490
+ isinstance(f, dict) and isinstance(f.get("handler"), str) and _count(f.get("files"))
491
+ for f in prints):
492
+ return False
493
+ return "commit_commitment" not in st or _hex64(st["commit_commitment"])
494
+
495
+
496
+ def chain_statement_of(receipt: dict) -> dict:
497
+ """What the developer signed: chain-seal v1, or v2 with the attested file list."""
498
+ chain = receipt.get("chain") or {}
499
+ st = ((receipt.get("attestation") or {}).get("statement")) or {}
500
+ statement = {"type": CHAIN_STATEMENT, "project": chain.get("project"),
501
+ "kind": chain.get("kind"), "parents": chain.get("parents") or [],
502
+ "digest": receipt.get("digest")}
503
+ if st.get("type") == ATTESTATION_V3:
504
+ statement.update(type=CHAIN_STATEMENT_V2, files=st.get("files"),
505
+ fingerprints=st.get("fingerprints") or [])
506
+ if "commit_commitment" in st:
507
+ statement["commit_commitment"] = st["commit_commitment"]
508
+ return statement
460
509
 
461
510
 
462
511
  def chain_signer(receipt: dict) -> str | None:
@@ -468,9 +517,7 @@ def chain_signer(receipt: dict) -> str | None:
468
517
  sig = chain.get("signature")
469
518
  if not sig:
470
519
  return None
471
- statement = {"type": CHAIN_STATEMENT, "project": chain.get("project"),
472
- "kind": chain.get("kind"), "parents": chain.get("parents") or [],
473
- "digest": receipt.get("digest")}
520
+ statement = chain_statement_of(receipt)
474
521
  try:
475
522
  raw = b64d(sig["public_key"])
476
523
  Ed25519PublicKey.from_public_bytes(raw).verify(b64d(sig["signature"]),
@@ -510,6 +557,23 @@ def _manifest(receipt: dict, doc: dict | None) -> Check | None:
510
557
  "units matches the attestation")
511
558
 
512
559
 
560
+ def _files(receipt: dict) -> Check | None:
561
+ """Every file's root and count (engine 0.7.0a43): signed in the attestation, in the log
562
+ entry and, for a project seal, in the developer's chain signature (those checks run
563
+ apart). An older seal covers Python files only."""
564
+ st = ((receipt.get("attestation") or {}).get("statement")) or {}
565
+ if "release" in receipt or st.get("kind") == "genesis": # records and genesis: no files
566
+ return None
567
+ if st.get("type") != ATTESTATION_V3:
568
+ return Check("files", PASS, "Python-only seal (before engine 0.7.0a43)")
569
+ files = st["files"]
570
+ if not _hex64(files.get("root")):
571
+ return Check("files", FAIL, "the file list's root is malformed")
572
+ commit = " and the commit (a salted commitment)" if "commit_commitment" in st else ""
573
+ return Check("files", PASS, f"{filelist.summary(st)}; root {files['root'][:16]}…{commit} "
574
+ "signed and logged")
575
+
576
+
513
577
  def _release_tag(receipt: dict, doc: dict | None) -> Check | None:
514
578
  """A release seal names its tag as a release record does (a salted commitment, or the tag
515
579
  when published): the Imprint's public header and the signed attestation must agree."""
@@ -572,9 +636,13 @@ def _log(receipt: dict, keys: list[dict]) -> Check:
572
636
  "attestation_key_id": att.get("key_id"),
573
637
  "attestation_signature": att.get("signature")}
574
638
  ast = att.get("statement") or {}
575
- if ast.get("type") == "codeimprint.attestation.v2":
639
+ if ast.get("type") in ("codeimprint.attestation.v2", ATTESTATION_V3):
576
640
  expected.update(type="codeimprint.log-entry.v2", project=ast.get("project"),
577
641
  kind=ast.get("kind"), parents=ast.get("parents"))
642
+ if ast.get("type") == ATTESTATION_V3: # every file's root and count, logged
643
+ expected.update(type="codeimprint.log-entry.v3", files=ast.get("files"))
644
+ if "commit_commitment" in ast:
645
+ expected["commit_commitment"] = ast["commit_commitment"]
578
646
  if leaf != expected:
579
647
  return Check("log inclusion", FAIL, "the log entry does not match this seal")
580
648
  size = st.get("tree_size")
@@ -771,7 +839,7 @@ def verify(receipt: dict, keys: list[dict], doc: dict | None = None,
771
839
  return checks + tokens + [_time_order(receipt, infos, now)]
772
840
  checks = [_digest(receipt, doc), _attestation(receipt, keys),
773
841
  *[c for c in (_chain(receipt), _manifest(receipt, doc),
774
- _release_tag(receipt, doc)) if c],
842
+ _release_tag(receipt, doc), _files(receipt)) if c],
775
843
  _developer(receipt, developer), _log(receipt, keys)]
776
844
  tokens, infos = _timestamps(receipt, keys, anchors)
777
845
  checks += tokens
File without changes
File without changes