codeimprint 0.5.0a15__tar.gz → 0.5.0a17__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 (26) hide show
  1. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/CHANGELOG.md +56 -0
  2. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/PKG-INFO +1 -1
  3. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/pyproject.toml +1 -1
  4. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/__init__.py +1 -1
  5. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/api.py +13 -0
  6. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/cli.py +219 -7
  7. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/imprint_file.py +1 -1
  8. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/receipt.py +111 -7
  9. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/records.py +3 -0
  10. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/.gitignore +0 -0
  11. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/LICENSE +0 -0
  12. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/NOTICE +0 -0
  13. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/README.pypi.md +0 -0
  14. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint/__init__.py +0 -0
  15. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint/__main__.py +0 -0
  16. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/__main__.py +0 -0
  17. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/chainseal.py +0 -0
  18. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/config.py +0 -0
  19. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/gitrepo.py +0 -0
  20. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/linecount.py +0 -0
  21. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/ownership.py +0 -0
  22. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/project.py +0 -0
  23. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a15 → codeimprint-0.5.0a17}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,61 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a17 — `imprint init --new-project` declares a private link to the origin [CIM-BE-32-v1]
4
+
5
+ For engine 0.7.0a21. Older engines still work: the project is made and the link is skipped
6
+ with a warning.
7
+
8
+ - **Changed: `imprint init --new-project`** (in a folder that came with someone else's
9
+ project in `.imprint/`) now also **declares where the code came from**. After the new
10
+ project and its genesis seal exist, this device's key signs a lineage record (`LIN1`,
11
+ relation `clone`) that links the new project to the origin project and to the origin's
12
+ latest seal found in `.imprint/` (none, if there is no seal file).
13
+ - It prints the new project ID, `Lineage linked to its origin (private): LIN1-…` and
14
+ how to see the record (`imprint lineage show`).
15
+ - The public record holds a salted commitment, never the origin. The salt is not written
16
+ to the folder; the server keeps the opening and gives it back to you.
17
+ - `.imprint/config.json` keeps `cloned_from: {project, seal, link}`. Note that this file
18
+ is normally committed, so your repository itself says where the code came from.
19
+ - If the link cannot be declared (an older server, no network), `init` warns and
20
+ finishes; run `imprint init` again to declare it.
21
+ - **New refusal: the origin is already your own project.** When your account is part of
22
+ the project in `.imprint/`, or this device's key is one of its keys, `--new-project`
23
+ stops before changing anything: the same repository on another device is the same
24
+ project. It says to run `imprint key request` (and `imprint key approve` on a device
25
+ that already seals it).
26
+ - New API call used: `POST /api/v1/projects/{id}/lineage`.
27
+ - Tests: `tests/test_declared_link.py`.
28
+
29
+ ## 0.5.0a16 — Lineage records (LIN1) verify offline [CIM-BE-31-v1]
30
+
31
+ For engine 0.7.0a21. Older engines still work; they have no lineage records.
32
+
33
+ - **New record type: `LIN1`** (`codeimprint.lineage.v1`), the link between a project that
34
+ was cloned or forked and its origin. The public record never names the origin: it holds
35
+ a salted commitment. `imprint verify` now knows the type:
36
+ - the record, its typed ID and its place in the log, as for every record;
37
+ - a new `lineage` check: a declared link names the clone and its seal and has exactly one
38
+ signature, role `child`; a detected link is the server's own record, unsigned, and
39
+ names nobody;
40
+ - a new `opening` check when the opening is at hand: it must give the record's
41
+ commitment (SHA-256 of the canonical `{salt, project, seal}`; a detected link adds the
42
+ clone). A wrong project, seal or salt fails;
43
+ - with `--online`, a declared link's signing key must have been a key of the clone's
44
+ project when the record was attested (`project key`).
45
+ - **New: `imprint verify --opening FILE`** checks an opening you were given against a
46
+ lineage record. With `--online` and a sign-in, `imprint verify LIN1-…` asks the server
47
+ for the opening too; the server gives it only to an account that is part of both
48
+ projects, or that declared the link.
49
+ - **New: `imprint lineage show <LIN1-ID>`** prints a link as far as your account may see
50
+ it. `--out FILE` saves the record and its opening; `imprint verify FILE` checks both
51
+ offline. `--json` prints the server's answer.
52
+ - Not in this release: declaring a link from the client (`imprint init --new-project`
53
+ does not make one yet) and anything about detection.
54
+ - A link says that two projects share an origin and which was sealed earlier. It does not
55
+ say who wrote the code and it changes no ownership claim.
56
+ - Tests: `tests/test_lineage.py`, with real records from engine 0.7.0a21
57
+ (`tests/fixtures/lineage-engine.json`).
58
+
3
59
  ## 0.5.0a15 — Another device joins the project; `python -m codeimprint` [CIM-BE-30-v1]
4
60
 
5
61
  For engine 0.7.0a20. Older engines still work, except for the new `imprint key` commands.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a15
3
+ Version: 0.5.0a17
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
@@ -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.0a15"
9
+ version = "0.5.0a17"
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.0a15"
8
+ __version__ = "0.5.0a17"
@@ -175,6 +175,19 @@ class Client:
175
175
  return self._json("POST", f"/api/v1/projects/{quote(project)}/keys/requests",
176
176
  {"public_key": public_key, "signature": signature, "label": label})
177
177
 
178
+ def lineage(self, record_id: str) -> dict:
179
+ """A lineage record (LIN1): its public record and, when this account may see it,
180
+ the opening of its commitment (engine 0.7.0a21+)."""
181
+ return self._json("GET", f"/api/v1/lineage/{quote(record_id)}")
182
+
183
+ def declare_lineage(self, project: str, document: dict, signatures: list[dict],
184
+ opening: dict) -> dict:
185
+ """Declare that this project is a clone of another (a LIN1 record, engine
186
+ 0.7.0a21+). The opening names the origin; it is stored encrypted, never logged."""
187
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/lineage",
188
+ {"document": document, "signatures": signatures,
189
+ "opening": opening})
190
+
178
191
  def key_requests(self, project: str) -> dict:
179
192
  return self._json("GET", f"/api/v1/projects/{quote(project)}/keys/requests")
180
193
 
@@ -8,6 +8,7 @@ import getpass
8
8
  import hashlib
9
9
  import json
10
10
  import os
11
+ import secrets
11
12
  import sys
12
13
  import time
13
14
  import webbrowser
@@ -377,6 +378,7 @@ def cmd_init(args) -> int:
377
378
  cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
378
379
  existing = project.load_config(root)
379
380
  if getattr(args, "new_project", False) and existing.get("project_id"):
381
+ _refuse_own_origin(args, existing["project_id"]) # before anything is changed
380
382
  existing = _leave_project(root, cfg_path, existing)
381
383
  cfg = {"version": 1, "exclude": existing.get("exclude", project.DEFAULT_EXCLUDE),
382
384
  "fail_above": existing.get("fail_above", DEFAULT_FAIL_ABOVE),
@@ -432,6 +434,104 @@ def cmd_init(args) -> int:
432
434
  return 0
433
435
 
434
436
 
437
+ def _refuse_own_origin(args, origin: str) -> None:
438
+ """`imprint init --new-project` is for code that came from someone else's project. When
439
+ the project this folder names is the caller's own, this is the same repository on
440
+ another device: the same project, joined with `imprint key request`."""
441
+ settings = config.resolve(getattr(args, "url", None))
442
+ if not settings.url:
443
+ return # no server to ask; nothing is created either
444
+ client = _signed_in(settings.url, settings.token)
445
+ key = trust.load_developer_key()
446
+ fp = trust.fingerprint(trust.public_raw(key)) if key is not None else None
447
+ why = None
448
+ try:
449
+ keys = client.public_project(origin).get("keys") or []
450
+ except (ApiError, NetworkError):
451
+ keys = []
452
+ if fp and fp in [k["fingerprint"] for k in keys if not k.get("valid_until")]:
453
+ why = f"this machine's developer key {fp} is one of its keys"
454
+ elif client.auth != "token": # an API token is the operator, not an owner
455
+ try:
456
+ if _project_state(client, origin, key) == "ok":
457
+ why = "your account is part of it"
458
+ except ApiError as exc:
459
+ raise Abort(_explain(client, exc, "could not check the project this folder "
460
+ "came with") + ". Nothing was changed.") from exc
461
+ if why:
462
+ raise Abort(
463
+ f"project {origin} is already yours: {why}. The same repository on another "
464
+ "device is the same project, so no new project was made and nothing was "
465
+ "changed. To seal from this device, run `imprint key request` here and "
466
+ "`imprint key approve` on a device that already seals the project; if this "
467
+ "device already has one of its keys, just run `imprint seal`.")
468
+
469
+
470
+ def _origin_seal(root: Path, origin: str) -> str | None:
471
+ """The latest seal of the origin project among the receipts that came with the code
472
+ (.imprint/origin/ after `--new-project`), by log position; None when there is none."""
473
+ folder = root / project.CONFIG_DIR
474
+ best: tuple[int, str] | None = None
475
+ for path in [*folder.glob("origin/*.receipt.json"), *folder.glob("*.receipt.json")]:
476
+ try:
477
+ rec = json.loads(path.read_text(encoding="utf-8"))
478
+ found = (int(rec["log"]["index"]), imprint_file.clean_id(rec["imprint_id"]))
479
+ named = (rec.get("chain") or {}).get("project")
480
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
481
+ continue
482
+ if named == origin and imprint_file.is_valid_id(found[1]) and (
483
+ best is None or found > best):
484
+ best = found
485
+ return best[1] if best else None
486
+
487
+
488
+ def _declare_origin(client: Client, root: Path, cfg_path: Path, key, child: str,
489
+ child_seal: str) -> None:
490
+ """A project made with `imprint init --new-project` says where its code came from: a
491
+ lineage record (LIN1) signed by this project's key. The public record holds a salted
492
+ commitment, never the origin; the server keeps the opening encrypted. Never in the way
493
+ of init: a failure is a warning, and `imprint init` again declares the link."""
494
+ current = project.load_config(root)
495
+ came = current.get("cloned_from") or {}
496
+ origin = came.get("project")
497
+ if not origin or came.get("link") or origin == child:
498
+ return
499
+ from . import records
500
+
501
+ seal, salt = _origin_seal(root, origin), secrets.token_hex(32)
502
+ document = {"type": receipt.LINEAGE, "basis": "declared", "relation": "clone",
503
+ "child": child, "child_seal": child_seal, "signals": ["S1"],
504
+ "parent_commitment": receipt.parent_commitment(salt, origin, seal),
505
+ "declared_at": _now_iso()}
506
+ digest = hashlib.sha256(imprint_file.canonical(document)).hexdigest()
507
+ signature = {"role": "child", "public_key": chainseal.public_key(key),
508
+ "signature": chainseal.sign(key, records.sign_statement(document["type"],
509
+ digest))}
510
+ try:
511
+ made = client.declare_lineage(child, document, [signature],
512
+ {"project": origin, "seal": seal, "salt": salt})
513
+ except (ApiError, NetworkError) as exc:
514
+ _warn(_explain(client, exc, "the link to this code's origin was not declared")
515
+ + ". Run `imprint init` again to declare it (the server needs lineage "
516
+ "records, engine 0.7.0a21 or later).")
517
+ return
518
+ link = made.get("record")
519
+ if link != imprint_file.record_id("LIN1", digest):
520
+ _warn(f"the server answered with another record ({link}) than the link this key "
521
+ "signed; it was not noted in .imprint/config.json")
522
+ return
523
+ current["cloned_from"] = {"project": origin, "seal": seal, "link": link}
524
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
525
+ _say(f"Lineage linked to its origin (private): {link}",
526
+ f" Origin: project {origin}, "
527
+ + (f"its latest seal here {seal}" if seal else "no seal of it in .imprint/")
528
+ + ". Signed by this project's key.",
529
+ " The public record holds a commitment, never the origin. Both sides are shown "
530
+ "only to an",
531
+ " account that is part of both projects. A link does not say who wrote the code.",
532
+ f" See it: imprint lineage show {link}")
533
+
534
+
435
535
  def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
436
536
  """`imprint init --new-project`: stop pointing at the project this folder came with. Its
437
537
  seal files move to .imprint/origin/ (they belong to that project) and the config keeps
@@ -446,7 +546,7 @@ def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
446
546
  moved.append(path.name)
447
547
  kept = {k: v for k, v in existing.items()
448
548
  if k not in ("project_id", "developer", "cloned_from")}
449
- kept["cloned_from"] = {"project": existing["project_id"]}
549
+ kept["cloned_from"] = {"project": existing["project_id"]} # the link: _declare_origin
450
550
  cfg_path.write_text(json.dumps(kept, indent=2) + "\n", encoding="utf-8")
451
551
  _say(f"Leaving project {existing['project_id']} (kept as cloned_from in "
452
552
  ".imprint/config.json)")
@@ -482,6 +582,16 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
482
582
  if getattr(args, "name", None) and settings.url:
483
583
  _rename(_signed_in(settings.url, settings.token), current["project_id"], key,
484
584
  args.name, True)
585
+ came = current.get("cloned_from") or {}
586
+ if settings.url and came.get("project") and not came.get("link"):
587
+ try: # a link that could not be declared before
588
+ genesis = json.loads((root / project.CONFIG_DIR / "genesis.receipt.json")
589
+ .read_text(encoding="utf-8"))["imprint_id"]
590
+ except (OSError, ValueError, KeyError, TypeError):
591
+ genesis = None
592
+ if genesis:
593
+ _declare_origin(_signed_in(settings.url, settings.token), root, cfg_path, key,
594
+ current["project_id"], genesis)
485
595
  return
486
596
  if not settings.url:
487
597
  _say("", "No server configured: run `imprint login`, then `imprint init` again to "
@@ -511,6 +621,7 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
511
621
  f"Genesis {g['id']}, sealed {g['receipt']['attestation']['statement']['attested_at']} "
512
622
  f"(log entry #{g['receipt']['log']['index']}): the project's chain starts here",
513
623
  "Saved .imprint/genesis.imprint and .imprint/genesis.receipt.json (commit them)")
624
+ _declare_origin(client, root, cfg_path, key, made["project_id"], g["id"])
514
625
 
515
626
 
516
627
  def _rename(client: Client, project_id: str, key, name: str, public: bool) -> dict:
@@ -2002,6 +2113,12 @@ def _load_target(args) -> tuple[dict | None, dict | None, Path]:
2002
2113
  rec_path = Path(args.receipt) if args.receipt else receipt_path_for(target)
2003
2114
  rec = imprint_file.load(rec_path) if rec_path.is_file() else None
2004
2115
  return data, rec, _project_root(target)
2116
+ if isinstance(data, dict) and isinstance(data.get("receipt"), dict) \
2117
+ and receipt.is_lineage(data["receipt"]):
2118
+ # What `imprint lineage show --out` saved: the record and, when this account
2119
+ # may see it, the opening of its commitment.
2120
+ args.found_opening = data.get("opening")
2121
+ return None, data["receipt"], _project_root(target)
2005
2122
  if isinstance(data, dict) and "attestation" in data:
2006
2123
  doc_path = target.with_name(target.name.removesuffix(".receipt.json") + ".imprint")
2007
2124
  doc = imprint_file.load(doc_path) if doc_path.is_file() else None
@@ -2067,6 +2184,80 @@ def _server_from_project(root: Path) -> str | None:
2067
2184
  return None
2068
2185
 
2069
2186
 
2187
+ def _fetch_lineage(client: Client, record_id: str) -> tuple[dict, dict | None]:
2188
+ """A lineage record and, for an account that may see it, its opening. Without a
2189
+ sign-in (or on an older server) the public record alone."""
2190
+ if client.auth in ("token", "session"):
2191
+ try:
2192
+ answer = client.lineage(record_id)
2193
+ return answer["receipt"], answer.get("opening")
2194
+ except (ApiError, KeyError):
2195
+ pass
2196
+ return client.public_record(record_id), None
2197
+
2198
+
2199
+ def _opening_for(args, rec: dict | None, found: dict | None) -> dict | None:
2200
+ """The opening to check a lineage record's commitment against: --opening FILE, else
2201
+ the one that came with the record."""
2202
+ if not getattr(args, "opening", None):
2203
+ return found
2204
+ if rec is None or not receipt.is_lineage(rec):
2205
+ raise Abort("--opening is for lineage records (LIN1)")
2206
+ try:
2207
+ data = json.loads(Path(args.opening).read_text(encoding="utf-8"))
2208
+ except (OSError, ValueError) as exc:
2209
+ raise Abort(f"cannot read {args.opening}: {exc}") from exc
2210
+ if not isinstance(data, dict):
2211
+ raise Abort(f"{args.opening} does not hold an opening")
2212
+ return data["opening"] if "receipt" in data and "opening" in data else data
2213
+
2214
+
2215
+ def cmd_lineage(args) -> int:
2216
+ """`imprint lineage show LIN1-…`: a lineage record as this account may see it."""
2217
+ if not imprint_file.is_valid_id(args.record, ("LIN1",)):
2218
+ raise Abort(f"not a lineage record ID (LIN1-…): {args.record}")
2219
+ rid = imprint_file.clean_id(args.record)
2220
+ client = _client(args, _server_from_project(Path(".")))
2221
+ try:
2222
+ answer = client.lineage(rid)
2223
+ except (ApiError, NetworkError) as exc:
2224
+ raise Abort(_explain(client, exc, f"cannot read {rid}")) from exc
2225
+ saved = imprint_file.save(answer, args.out) if args.out else None
2226
+ if args.json:
2227
+ print(json.dumps(answer, indent=2))
2228
+ return 0
2229
+ doc = answer["receipt"]["record"]["document"]
2230
+ opening = answer.get("opening") or {}
2231
+ clone = opening.get("child") or (
2232
+ {"project": doc["child"], "seal": doc["child_seal"]} if "child" in doc else None)
2233
+ _say(f"Record {rid}",
2234
+ f"Link {answer['basis']} {answer['relation']}, signals "
2235
+ f"{', '.join(answer['signals'])}, {answer['at']}")
2236
+ if clone:
2237
+ _say(f"Clone project {clone['project']}, seal {clone['seal']}")
2238
+ else:
2239
+ _say("Clone not named in the public record")
2240
+ if opening:
2241
+ origin = opening["parent"]
2242
+ _say(f"Origin project {origin['project']}, "
2243
+ + (f"seal {origin['seal']}" if origin.get("seal") else "no seal named")
2244
+ + (" (as declared)" if answer["basis"] == "declared" else ""))
2245
+ checks = opening.get("checks")
2246
+ if checks:
2247
+ _say("Declared the origin project "
2248
+ + ("is" if checks.get("parent_known") else "is not") + " on this server; "
2249
+ "the seal named "
2250
+ + ("is" if checks.get("parent_seal_in_parent") else "is not") + " one of its seals")
2251
+ else:
2252
+ _say("Origin not shown: the public record holds a commitment only. Both sides "
2253
+ "are shown to an account that is part of both projects.")
2254
+ if saved:
2255
+ _say(f"Saved {saved} (check it offline: imprint verify {saved})")
2256
+ _say("", "A link says that two projects share an origin and which was sealed earlier; "
2257
+ "it does not say who wrote the code.")
2258
+ return 0
2259
+
2260
+
2070
2261
  def _file_only(doc: dict) -> list[receipt.Check]:
2071
2262
  status = imprint_file.verify_document(doc)
2072
2263
  sig = ("not signed" if not status["signed"] else
@@ -2087,20 +2278,25 @@ def cmd_verify(args) -> int:
2087
2278
  args.verify_parser.error("the following arguments are required: target")
2088
2279
  args.target = str(default)
2089
2280
  doc, rec, root = _load_target(args)
2281
+ found = getattr(args, "found_opening", None)
2090
2282
  checks: list[receipt.Check] = []
2091
2283
  client = _client(args, _server_from_project(root)) if args.online else None
2092
2284
  if rec is None and client is not None:
2093
2285
  iid = imprint_file.clean_id(args.target) if doc is None else (
2094
2286
  imprint_file.verify_document(doc)["id"])
2287
+ prefix = iid.split("-", 1)[0]
2095
2288
  try:
2096
- rec = (client.public_record(iid)
2097
- if iid.split("-", 1)[0] in imprint_file.RECORD_PREFIXES
2098
- else client.public_imprint(iid))
2289
+ if prefix == "LIN1":
2290
+ rec, found = _fetch_lineage(client, iid)
2291
+ else:
2292
+ rec = (client.public_record(iid) if prefix in imprint_file.RECORD_PREFIXES
2293
+ else client.public_imprint(iid))
2099
2294
  except ApiError as exc:
2100
2295
  if doc is None:
2101
2296
  raise Abort(f"no public record for {iid}: {exc}") from exc
2102
2297
  except NetworkError as exc:
2103
2298
  raise Abort(str(exc)) from exc
2299
+ opening = _opening_for(args, rec, found)
2104
2300
  if rec is None:
2105
2301
  checks = _file_only(doc)
2106
2302
  iid = imprint_file.verify_document(doc)["id"]
@@ -2115,7 +2311,7 @@ def cmd_verify(args) -> int:
2115
2311
  f"also trusting {extra} certificate(s) from "
2116
2312
  f"{args.tsa_certs}, beyond the pinned roots"))
2117
2313
  checks += receipt.verify(rec, keys, doc, developer=args.developer or developer,
2118
- anchors=anchors)
2314
+ anchors=anchors, opening=opening)
2119
2315
  if client is not None and keys:
2120
2316
  try:
2121
2317
  checks += receipt.verify_online(rec, client, keys, anchors)
@@ -2176,8 +2372,10 @@ def build_parser() -> argparse.ArgumentParser:
2176
2372
  n.add_argument("--name", help="the project's display name (default: owner/repo from the "
2177
2373
  "origin remote, else the folder's name); public")
2178
2374
  n.add_argument("--new-project", action="store_true",
2179
- help="this folder came with another project's .imprint/ (a clone): make a "
2180
- "project of your own for it")
2375
+ help="this folder came with someone else's project in .imprint/ (a clone): "
2376
+ "make a project of your own for it and declare a private link to its "
2377
+ "origin (a LIN1 record). Refused when that project is already yours: "
2378
+ "then use `imprint key request`")
2181
2379
  n.set_defaults(func=cmd_init)
2182
2380
 
2183
2381
  ky = sub.add_parser("key", help="the project's keys: add another device (request, then "
@@ -2395,9 +2593,23 @@ def build_parser() -> argparse.ArgumentParser:
2395
2593
  v.add_argument("--url", help="server URL for --online")
2396
2594
  v.add_argument("--tsa-certs", metavar="FILE",
2397
2595
  help="also trust the time-stamping authorities in this PEM bundle")
2596
+ v.add_argument("--opening", metavar="FILE",
2597
+ help="a lineage record (LIN1): check that this opening ({parent: {project, "
2598
+ "seal}, salt}) gives the record's commitment")
2398
2599
  v.add_argument("--strict", action="store_true", help="treat warnings as failures")
2399
2600
  v.add_argument("--json", action="store_true")
2400
2601
  v.set_defaults(func=cmd_verify, verify_parser=v)
2602
+
2603
+ ln = sub.add_parser("lineage", help="a lineage record (LIN1): the link between a clone "
2604
+ "and its origin, as far as you may see it")
2605
+ ln.add_argument("action", choices=["show"])
2606
+ ln.add_argument("record", help="the record's ID (LIN1-…)")
2607
+ ln.add_argument("-o", "--out", metavar="FILE",
2608
+ help="save the record (and its opening, when shown to you) to verify "
2609
+ "offline with `imprint verify FILE`")
2610
+ ln.add_argument("--json", action="store_true")
2611
+ ln.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2612
+ ln.set_defaults(func=cmd_lineage)
2401
2613
  return p
2402
2614
 
2403
2615
 
@@ -17,7 +17,7 @@ ID_PREFIX = "IMP1"
17
17
  RELEASE_PREFIX = "REL1" # release records: same shape, own namespace
18
18
  BODY_CHECKED = (ID_PREFIX, RELEASE_PREFIX) # frozen: check character over the body only
19
19
  RECORD_PREFIXES = ("IDT1", "REV1", "MBR1", "END1", "CLM1", "XFR1", "ASG1", "DCL1", "CTB1",
20
- "NTC1", "DSC1", "INT1") # ownership records: check over prefix + body
20
+ "NTC1", "DSC1", "INT1", "LIN1") # records: check over prefix + body
21
21
  ALL_PREFIXES = BODY_CHECKED + RECORD_PREFIXES
22
22
  ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ" # Crockford Base32: no I, L, O, U
23
23
 
@@ -86,6 +86,100 @@ def _record(receipt: dict) -> Check:
86
86
  return Check("record", PASS, f"{rtype.kind} record; {who}")
87
87
 
88
88
 
89
+ LINEAGE = "codeimprint.lineage.v1"
90
+ _LINEAGE_FIELDS = {
91
+ "declared": {"type", "basis", "relation", "child", "child_seal", "signals",
92
+ "parent_commitment", "declared_at"},
93
+ "detected": {"type", "basis", "relation", "signals", "link_commitment", "detected_at"},
94
+ }
95
+ _RELATIONS = ("clone", "fork", "continuation", "delivery")
96
+
97
+
98
+ def _hex64(value) -> bool:
99
+ return isinstance(value, str) and len(value) == 64 and not set(value) - set(
100
+ "0123456789abcdef")
101
+
102
+
103
+ def parent_commitment(salt: str, project: str, seal: str | None) -> str:
104
+ """What a declared lineage record publishes in place of its origin."""
105
+ return hashlib.sha256(canonical({"salt": salt, "project": project,
106
+ "seal": seal})).hexdigest()
107
+
108
+
109
+ def is_lineage(receipt: dict) -> bool:
110
+ return ((receipt or {}).get("record") or {}).get("type") == LINEAGE
111
+
112
+
113
+ def _lineage(receipt: dict) -> Check | None:
114
+ """A lineage record (LIN1) links a clone to its origin. A declared link names the clone
115
+ and its seal and is signed by one key, role child. A detected link is the server's own
116
+ record and names nobody. Neither names the origin: that is a salted commitment, which
117
+ ``_opening`` checks when the opening is at hand. The signatures themselves are verified
118
+ by ``_record``."""
119
+ if not is_lineage(receipt):
120
+ return None
121
+ doc = receipt["record"].get("document") or {}
122
+ basis = doc.get("basis")
123
+ if not isinstance(basis, str) or set(doc) != _LINEAGE_FIELDS.get(basis):
124
+ return Check("lineage", FAIL, "not a declared or detected link, or it holds other "
125
+ "fields")
126
+ signals = doc["signals"]
127
+ if doc["relation"] not in _RELATIONS or not isinstance(signals, list) or not signals \
128
+ or not all(isinstance(s, str) for s in signals):
129
+ return Check("lineage", FAIL, "unknown relation or signals")
130
+ if not _hex64(doc["parent_commitment" if basis == "declared" else "link_commitment"]):
131
+ return Check("lineage", FAIL, "the commitment is not a SHA-256")
132
+ sigs = receipt.get("signatures") or []
133
+ how = f"{doc['relation']} link, signals {', '.join(signals)}"
134
+ if basis == "declared":
135
+ if [s.get("role") for s in sigs] != ["child"]:
136
+ return Check("lineage", FAIL, "a declared link has one signature, role child")
137
+ return Check("lineage", PASS,
138
+ f"declared {how}: project {doc['child']} at seal {doc['child_seal']}, "
139
+ f"signed by key {sigs[0].get('fingerprint')}; the origin is a "
140
+ "commitment")
141
+ if sigs:
142
+ return Check("lineage", FAIL, "a detected link has no owner signature")
143
+ return Check("lineage", PASS, f"detected {how}: the server's own record; neither "
144
+ "project is named, the link is a commitment")
145
+
146
+
147
+ def _opening(receipt: dict, opening) -> Check:
148
+ """Does the opening give the record's commitment? ``parent_commitment`` is SHA-256 of
149
+ canonical JSON {salt, project, seal} (the origin); ``link_commitment`` adds the clone as
150
+ child and child_seal."""
151
+ doc = receipt["record"]["document"]
152
+ declared = doc.get("basis") == "declared"
153
+ shape = "the opening is {parent: {project, seal}, salt}" + (
154
+ "" if declared else ", with child: {project, seal}")
155
+ try:
156
+ salt, project, seal = opening["salt"], opening["parent"]["project"], opening[
157
+ "parent"]["seal"]
158
+ child = opening.get("child") if declared else opening["child"]
159
+ clone = None if child is None else (child["project"], child["seal"])
160
+ except (AttributeError, KeyError, TypeError):
161
+ return Check("opening", FAIL, shape)
162
+ if not all(isinstance(v, str) for v in (salt, project)) or not isinstance(
163
+ seal, (str, type(None))) or (clone and not all(isinstance(v, str) for v in clone)):
164
+ return Check("opening", FAIL, shape)
165
+ body = {"salt": salt, "project": project, "seal": seal}
166
+ if declared:
167
+ if clone is not None and clone != (doc.get("child"), doc.get("child_seal")):
168
+ return Check("opening", FAIL, "the opening names another clone than the record")
169
+ expected = doc.get("parent_commitment")
170
+ else:
171
+ body.update(child=clone[0], child_seal=clone[1])
172
+ expected = doc.get("link_commitment")
173
+ if hashlib.sha256(canonical(body)).hexdigest() != expected:
174
+ return Check("opening", FAIL, "the opening does not give the record's commitment: "
175
+ "another project, seal or salt")
176
+ origin = f"origin project {project}, " + (f"seal {seal}" if seal else "no seal named")
177
+ if declared:
178
+ return Check("opening", PASS, f"the commitment opens to {origin}")
179
+ return Check("opening", PASS, f"the commitment opens to clone project {clone[0]}, seal "
180
+ f"{clone[1]}, and {origin}")
181
+
182
+
89
183
  def _release(receipt: dict) -> Check:
90
184
  """A release record: its digest is SHA-256 of the release document, which names the
91
185
  labelled seal; the chain must say the same."""
@@ -552,9 +646,10 @@ def _time_order(receipt: dict, infos: list[timestamp.TokenInfo], now: datetime)
552
646
 
553
647
  def verify(receipt: dict, keys: list[dict], doc: dict | None = None,
554
648
  developer: str | None = None, now: datetime | None = None,
555
- anchors: list | None = None) -> list[Check]:
649
+ anchors: list | None = None, opening: dict | None = None) -> list[Check]:
556
650
  """Every offline check. ``developer`` is the fingerprint the project expects to sign;
557
- ``anchors`` the trusted TSA roots (default: the pinned ones)."""
651
+ ``anchors`` the trusted TSA roots (default: the pinned ones); ``opening`` what a lineage
652
+ record's commitment is said to commit to."""
558
653
  now = now or datetime.now(timezone.utc)
559
654
  anchors = timestamp.pinned_anchors() if anchors is None else anchors
560
655
  if not keys:
@@ -566,6 +661,11 @@ def verify(receipt: dict, keys: list[dict], doc: dict | None = None,
566
661
  typed = _identity(receipt, now)
567
662
  if typed:
568
663
  checks.insert(1, typed)
664
+ link = _lineage(receipt)
665
+ if link:
666
+ checks.insert(1, link)
667
+ if opening is not None and link.status == PASS:
668
+ checks.insert(2, _opening(receipt, opening))
569
669
  tokens, infos = _timestamps(receipt, keys, anchors)
570
670
  return checks + tokens + [_time_order(receipt, infos, now)]
571
671
  checks = [_digest(receipt, doc), _attestation(receipt, keys),
@@ -642,19 +742,23 @@ def verify_online(receipt: dict, client, keys: list[dict],
642
742
  f"entry #{index} was added after entry #{index - 1}"))
643
743
 
644
744
  chain = receipt.get("chain") or {}
645
- signer = chain_signer(receipt)
646
- if chain.get("project") and signer and hasattr(client, "public_project"):
745
+ signer, signed_for = chain_signer(receipt), chain.get("project")
746
+ if is_lineage(receipt): # a declared link: the clone's project key signed
747
+ doc, sigs = receipt["record"]["document"], receipt.get("signatures") or []
748
+ if doc.get("basis") == "declared" and len(sigs) == 1:
749
+ signer, signed_for = sigs[0].get("fingerprint"), doc.get("child")
750
+ if signed_for and signer and hasattr(client, "public_project"):
647
751
  attested = receipt["attestation"]["statement"]["attested_at"]
648
752
  keys_now = {k["fingerprint"]: k
649
- for k in client.public_project(chain["project"]).get("keys", [])}
753
+ for k in client.public_project(signed_for).get("keys", [])}
650
754
  k = keys_now.get(signer)
651
755
  if k and k["valid_from"] <= attested and (not k["valid_until"]
652
756
  or attested <= k["valid_until"]):
653
757
  checks.append(Check("project key", PASS, f"{signer} was a key of project "
654
- f"{chain['project']} at {attested}"))
758
+ f"{signed_for} at {attested}"))
655
759
  else:
656
760
  checks.append(Check("project key", FAIL, f"{signer} was not a key of project "
657
- f"{chain['project']} at {attested}"))
761
+ f"{signed_for} at {attested}"))
658
762
  rel = receipt.get("release")
659
763
  if rel:
660
764
  try:
@@ -43,6 +43,9 @@ TYPES: dict[str, RecordType] = {
43
43
  "codeimprint.disclosure.v1": RecordType("DSC1", "disclosure", ("record",), ("admin",)),
44
44
  "codeimprint.integration.v1": RecordType("INT1", "integration", (),
45
45
  ("integration", "owner")),
46
+ # Clone lineage: a declared link is signed by the clone's project key (role child); a
47
+ # detected link is the server's own. The origin is never a reference field.
48
+ "codeimprint.lineage.v1": RecordType("LIN1", "lineage", ("child_seal",)),
46
49
  }
47
50
 
48
51
 
File without changes
File without changes