codeimprint 0.5.0a14__tar.gz → 0.5.0a16__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.0a14 → codeimprint-0.5.0a16}/CHANGELOG.md +52 -0
  2. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/PKG-INFO +13 -1
  3. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/README.pypi.md +12 -0
  4. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/pyproject.toml +5 -3
  5. codeimprint-0.5.0a16/src/codeimprint/__init__.py +6 -0
  6. codeimprint-0.5.0a16/src/codeimprint/__main__.py +6 -0
  7. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/__init__.py +1 -1
  8. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/api.py +20 -0
  9. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/chainseal.py +22 -4
  10. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/cli.py +292 -17
  11. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/imprint_file.py +1 -1
  12. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/receipt.py +105 -7
  13. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/records.py +3 -0
  14. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/.gitignore +0 -0
  15. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/LICENSE +0 -0
  16. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/NOTICE +0 -0
  17. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/__main__.py +0 -0
  18. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/config.py +0 -0
  19. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/gitrepo.py +0 -0
  20. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/linecount.py +0 -0
  21. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/ownership.py +0 -0
  22. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/project.py +0 -0
  23. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a14 → codeimprint-0.5.0a16}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,57 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a16 — Lineage records (LIN1) verify offline [CIM-BE-31-v1]
4
+
5
+ For engine 0.7.0a21. Older engines still work; they have no lineage records.
6
+
7
+ - **New record type: `LIN1`** (`codeimprint.lineage.v1`), the link between a project that
8
+ was cloned or forked and its origin. The public record never names the origin: it holds
9
+ a salted commitment. `imprint verify` now knows the type:
10
+ - the record, its typed ID and its place in the log, as for every record;
11
+ - a new `lineage` check: a declared link names the clone and its seal and has exactly one
12
+ signature, role `child`; a detected link is the server's own record, unsigned, and
13
+ names nobody;
14
+ - a new `opening` check when the opening is at hand: it must give the record's
15
+ commitment (SHA-256 of the canonical `{salt, project, seal}`; a detected link adds the
16
+ clone). A wrong project, seal or salt fails;
17
+ - with `--online`, a declared link's signing key must have been a key of the clone's
18
+ project when the record was attested (`project key`).
19
+ - **New: `imprint verify --opening FILE`** checks an opening you were given against a
20
+ lineage record. With `--online` and a sign-in, `imprint verify LIN1-…` asks the server
21
+ for the opening too; the server gives it only to an account that is part of both
22
+ projects, or that declared the link.
23
+ - **New: `imprint lineage show <LIN1-ID>`** prints a link as far as your account may see
24
+ it. `--out FILE` saves the record and its opening; `imprint verify FILE` checks both
25
+ offline. `--json` prints the server's answer.
26
+ - Not in this release: declaring a link from the client (`imprint init --new-project`
27
+ does not make one yet) and anything about detection.
28
+ - A link says that two projects share an origin and which was sealed earlier. It does not
29
+ say who wrote the code and it changes no ownership claim.
30
+ - Tests: `tests/test_lineage.py`, with real records from engine 0.7.0a21
31
+ (`tests/fixtures/lineage-engine.json`).
32
+
33
+ ## 0.5.0a15 — Another device joins the project; `python -m codeimprint` [CIM-BE-30-v1]
34
+
35
+ For engine 0.7.0a20. Older engines still work, except for the new `imprint key` commands.
36
+
37
+ - **New: `imprint key`.** The same repository on any device is the same project (ADR 0007).
38
+ - `imprint key request` on the new device makes that device's own key and asks for it to
39
+ be added. `--label` names the device; the default is the computer's name.
40
+ - `imprint key approve [fingerprint]` on a device that already seals the project shows
41
+ the request (label, and whether it comes from your own account) and adds the key.
42
+ - `imprint key list` shows the project's keys and the requests waiting.
43
+ - `imprint key retire <fingerprint>` retires a key, for example of a lost device. It
44
+ refuses to retire the project's only key.
45
+ - **Changed messages:** when this machine has no project key, or its key is not one of the
46
+ project's keys, `seal` and `init` now point to `imprint key request` (0.5.0a14 said to
47
+ copy the key file). A cloned project that is not yours names `imprint key request` as the
48
+ way to ask to join.
49
+ - **New: `python -m codeimprint`** runs the same commands as `imprint`. Use it where the
50
+ `imprint` program cannot be started, for example when Windows Application Control blocks
51
+ it. The wheel gains a small `codeimprint` package that holds only this entry point.
52
+ - Signed requests are tied to the sign-in session; with an API token they are tied to none.
53
+ - Tests: `tests/test_keys.py`.
54
+
3
55
  ## 0.5.0a14 — Sign-in works for sealing; clearer messages for clones [CIM-BE-29-v2]
4
56
 
5
57
  For engine 0.7.0a19. Older engines still work.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a14
3
+ Version: 0.5.0a16
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
@@ -52,6 +52,18 @@ seals offline. Learn more at [codeimprint.ai](https://codeimprint.ai).
52
52
  pip install --pre codeimprint
53
53
  ```
54
54
 
55
+ **Windows: if `imprint` is blocked.** Some managed Windows machines refuse to start the
56
+ `imprint` program (Application Control or AppLocker: "This app has been blocked by your
57
+ system administrator"). Run the same commands through Python instead, which those
58
+ policies usually allow:
59
+
60
+ ```bash
61
+ python -m codeimprint seal .
62
+ ```
63
+
64
+ `python -m codeimprint <command>` is the same as `imprint <command>` everywhere. On
65
+ Windows `py -m codeimprint` works too.
66
+
55
67
  ## Get started
56
68
 
57
69
  ```bash
@@ -18,6 +18,18 @@ seals offline. Learn more at [codeimprint.ai](https://codeimprint.ai).
18
18
  pip install --pre codeimprint
19
19
  ```
20
20
 
21
+ **Windows: if `imprint` is blocked.** Some managed Windows machines refuse to start the
22
+ `imprint` program (Application Control or AppLocker: "This app has been blocked by your
23
+ system administrator"). Run the same commands through Python instead, which those
24
+ policies usually allow:
25
+
26
+ ```bash
27
+ python -m codeimprint seal .
28
+ ```
29
+
30
+ `python -m codeimprint <command>` is the same as `imprint <command>` everywhere. On
31
+ Windows `py -m codeimprint` works too.
32
+
21
33
  ## Get started
22
34
 
23
35
  ```bash
@@ -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.0a14"
9
+ version = "0.5.0a16"
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"
@@ -45,12 +45,14 @@ Hub = "https://app.codeimprint.ai"
45
45
  imprint = "codeimprint_cli.cli:main"
46
46
 
47
47
  [tool.hatch.build.targets.wheel]
48
- packages = ["src/codeimprint_cli"]
48
+ # codeimprint_cli is the client; codeimprint holds only `python -m codeimprint`.
49
+ packages = ["src/codeimprint_cli", "src/codeimprint"]
49
50
 
50
51
  # The sdist holds only what builds the wheel: no tests, fixtures, workflows or repository
51
52
  # tooling (pyproject.toml is always included). scripts/check_release.py polices it.
52
53
  [tool.hatch.build.targets.sdist]
53
- only-include = ["src/codeimprint_cli", "README.pypi.md", "CHANGELOG.md", "LICENSE", "NOTICE"]
54
+ only-include = ["src/codeimprint_cli", "src/codeimprint", "README.pypi.md", "CHANGELOG.md",
55
+ "LICENSE", "NOTICE"]
54
56
 
55
57
  [tool.pytest.ini_options]
56
58
  testpaths = ["tests"]
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """`python -m codeimprint`: the `imprint` command, for machines where the `imprint` program
3
+ itself cannot be started (for example when Windows Application Control blocks it).
4
+
5
+ The client's code is the package `codeimprint_cli`; this package only holds the entry point.
6
+ """
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ import sys
3
+
4
+ from codeimprint_cli.cli import main
5
+
6
+ sys.exit(main())
@@ -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.0a14"
8
+ __version__ = "0.5.0a16"
@@ -169,6 +169,26 @@ class Client:
169
169
  return self._json("POST", f"/api/v1/projects/{quote(project)}/access",
170
170
  {"public_key": public_key, "signature": signature})
171
171
 
172
+ # a new device joins the project (engine 0.7.0a20+) ---------------------------------------
173
+ def key_request(self, project: str, public_key: str, signature: str,
174
+ label: str | None = None) -> dict:
175
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/keys/requests",
176
+ {"public_key": public_key, "signature": signature, "label": label})
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 key_requests(self, project: str) -> dict:
184
+ return self._json("GET", f"/api/v1/projects/{quote(project)}/keys/requests")
185
+
186
+ def change_project_key(self, project: str, action: str, public_key: str,
187
+ signer_public_key: str, signature: str) -> dict:
188
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/keys",
189
+ {"action": action, "public_key": public_key,
190
+ "signer_public_key": signer_public_key, "signature": signature})
191
+
172
192
  def plan(self, project: str, payload: dict) -> dict:
173
193
  return self._json("POST", f"/api/v1/projects/{quote(project)}/seal/plan", payload)
174
194
 
@@ -34,13 +34,31 @@ def public_key(key) -> str:
34
34
  return trust.b64e(trust.public_raw(key))
35
35
 
36
36
 
37
+ def session_binding(token: str | None) -> str:
38
+ """What ties a signed request to this sign-in: the SHA-256 of the session token (an API
39
+ token is not a session: the server then expects the hash of nothing)."""
40
+ session = token if token and token.startswith("cis_") else ""
41
+ return hashlib.sha256(session.encode()).hexdigest()
42
+
43
+
37
44
  def access_proof(key, project: str, token: str | None) -> tuple[str, str]:
38
45
  """(public key, signature) showing that this session holds a project key: the key signs
39
- {type, project, session}, where session is the SHA-256 of the session token, so the
40
- proof works for this sign-in only."""
41
- session = hashlib.sha256((token or "").encode()).hexdigest()
46
+ {type, project, session}, so the proof works for this sign-in only."""
42
47
  return public_key(key), sign(key, {"type": "codeimprint.project-access.v1",
43
- "project": project, "session": session})
48
+ "project": project, "session": session_binding(token)})
49
+
50
+
51
+ def key_request_proof(key, project: str, token: str | None) -> tuple[str, str]:
52
+ """(public key, signature) of a device asking for its key to be added to a project."""
53
+ pub = public_key(key)
54
+ return pub, sign(key, {"type": "codeimprint.project-key-request.v1", "project": project,
55
+ "public_key": pub, "session": session_binding(token)})
56
+
57
+
58
+ def key_change(key, project: str, action: str, target_public_key: str) -> tuple[str, str]:
59
+ """(signer public key, signature) of a project key adding or retiring another key."""
60
+ return public_key(key), sign(key, {"type": "codeimprint.project-key.v1", "project": project,
61
+ "action": action, "public_key": target_public_key})
44
62
 
45
63
 
46
64
  def create_project(client, key, name: str | None = None) -> dict:
@@ -209,8 +209,8 @@ def _not_your_project(client: Client, project_id: str, key) -> str:
209
209
  return (f"this folder's .imprint/config.json names project {project_id}, which is not on "
210
210
  f"{client.url} or which your account is not part of (for example, it came with a "
211
211
  "repository you cloned). To seal this code as a project of your own, run "
212
- "`imprint init --new-project`. To join the existing project, ask its owner to add "
213
- f"your developer key{mine}.")
212
+ "`imprint init --new-project`. To join the existing project, run `imprint key "
213
+ f"request`: its owner sees the request and can add your developer key{mine}.")
214
214
 
215
215
 
216
216
  def _project_state(client: Client, project_id: str, key) -> str:
@@ -249,10 +249,9 @@ def _project_ready(client: Client, project_id: str, key) -> None:
249
249
  if active and fp not in active:
250
250
  raise SealFailed(
251
251
  f"developer key {fp} on this machine is not a key of project {project_id} (its "
252
- f"keys: {', '.join(active)}). Use a key the project knows: copy "
253
- f"{trust.developer_key_path().name} from the machine that has it into "
254
- f"{trust.developer_key_path().parent}, or set CODEIMPRINT_DEVELOPER_KEY to its "
255
- "contents. Nothing was uploaded.")
252
+ f"keys: {', '.join(active)}). Add this device to the project: run `imprint key "
253
+ f"request` here, then `imprint key approve {fp}` on a device that already seals "
254
+ "it. Nothing was uploaded.")
256
255
 
257
256
 
258
257
  def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool) -> bytes:
@@ -423,7 +422,8 @@ def cmd_init(args) -> int:
423
422
  " To sign seals in CI, store the file's contents as the secret "
424
423
  "CODEIMPRINT_DEVELOPER_KEY.")
425
424
  if cfg.get("developer") != fp:
426
- _warn(f"this project expects developer key {cfg['developer']}, not {fp}")
425
+ _warn(f"this project expects developer key {cfg['developer']}, not {fp}: to add "
426
+ "this device to the project run `imprint key request`")
427
427
  if key is not None and not args.no_project:
428
428
  _init_project(args, root, cfg_path, key)
429
429
  if key is not None:
@@ -1387,14 +1387,14 @@ def _developer_key(required: bool = False, expected: str | None = None):
1387
1387
  except ValueError as exc:
1388
1388
  raise SealFailed(f"cannot read the developer key: {exc}") from exc
1389
1389
  if key is None and required:
1390
- path = trust.developer_key_path()
1391
1390
  raise SealFailed(
1392
1391
  "this project's seals are signed with a developer key"
1393
- + (f" ({expected})" if expected else "") + ", and this machine has none. Copy "
1394
- f"{path.name} from the machine that has it into {path.parent}, or set "
1395
- "CODEIMPRINT_DEVELOPER_KEY to its contents (in GitHub Actions: a secret). A new "
1396
- "key from `imprint init` is a different key: the project does not accept it "
1397
- "until one of its keys adds it.")
1392
+ + (f" ({expected})" if expected else "") + ", and this machine has none. Add "
1393
+ "this device to the project: run `imprint key request` here (it makes this "
1394
+ "device's own key), then `imprint key approve` on a device that already seals it. "
1395
+ "In GitHub Actions, set the secret CODEIMPRINT_DEVELOPER_KEY to the contents of an "
1396
+ "approved key file. A new key from `imprint init` alone is a different key, which "
1397
+ "the project does not accept.")
1398
1398
  return key
1399
1399
 
1400
1400
 
@@ -1693,6 +1693,169 @@ def cmd_seal(args) -> int:
1693
1693
  return rc
1694
1694
 
1695
1695
 
1696
+ # -- a project's keys: another device joins (CIM-BE-30-v1; ADR 0007, section 7.4) -------------
1697
+ def _project_keys(client: Client, project_id: str) -> list[dict]:
1698
+ try:
1699
+ return client.public_project(project_id).get("keys") or []
1700
+ except (ApiError, NetworkError):
1701
+ return []
1702
+
1703
+
1704
+ def _device_label() -> str:
1705
+ import platform
1706
+
1707
+ return (" ".join(platform.node().split()) or "device")[:60]
1708
+
1709
+
1710
+ def _key_request(args, client: Client, project_id: str) -> int:
1711
+ key, how = trust.load_developer_key(), "found"
1712
+ if key is None:
1713
+ key, how = trust.create_developer_key(), "created"
1714
+ fp = trust.fingerprint(trust.public_raw(key))
1715
+ if any(k["fingerprint"] == fp and not k.get("valid_until")
1716
+ for k in _project_keys(client, project_id)):
1717
+ _say(f"Key {fp} is already a key of project {project_id}: this device can seal")
1718
+ return 0
1719
+ label = args.label or _device_label()
1720
+ try:
1721
+ client.key_request(project_id, *chainseal.key_request_proof(key, project_id, client.token),
1722
+ label)
1723
+ except ApiError as exc:
1724
+ if exc.status == 404 and exc.code != "project_not_found":
1725
+ raise Abort(f"{client.url} does not take key requests yet (it needs engine 0.7.0a20 "
1726
+ "or later)") from exc
1727
+ raise Abort(_explain(client, exc, "the request was not sent")) from exc
1728
+ except NetworkError as exc:
1729
+ raise Abort(f"the request was not sent: {exc}") from exc
1730
+ _say(f"Requested developer key {fp} ({how}: {trust.developer_key_path()}) asks to join "
1731
+ f"project {project_id}",
1732
+ f"Label {label} (shown to whoever approves; --label to choose)",
1733
+ f"Approve on a device that already seals this project: imprint key approve {fp}",
1734
+ "Waits 7 days. Until it is approved this device can verify and check, not seal.",
1735
+ " If the project is someone else's, its owner sees the request and decides.")
1736
+ return 0
1737
+
1738
+
1739
+ def _key_list(client: Client, project_id: str) -> int:
1740
+ keys = _project_keys(client, project_id)
1741
+ if not keys:
1742
+ raise Abort(f"no such project on {client.url}: {project_id}")
1743
+ mine = trust.load_developer_key()
1744
+ here = trust.fingerprint(trust.public_raw(mine)) if mine is not None else None
1745
+ _say(f"Project {project_id}")
1746
+ for k in keys:
1747
+ state = f"retired {k['valid_until']}" if k.get("valid_until") else "active"
1748
+ _say(f" {k['fingerprint']} {k.get('kind', 'developer'):<11} {state}"
1749
+ + (" (this device)" if k["fingerprint"] == here else ""))
1750
+ try:
1751
+ waiting = client.key_requests(project_id)["requests"]
1752
+ except (ApiError, NetworkError):
1753
+ _say("Requests shown only to the project's own accounts (sign in with `imprint login`)")
1754
+ return 0
1755
+ _say(f"Requests {len(waiting)} waiting" + (":" if waiting else ""))
1756
+ for r in waiting:
1757
+ who = "your account" if r.get("same_account") else "another account"
1758
+ _say(f" {r['fingerprint']} {r.get('label') or '(no label)'} from {who}, "
1759
+ f"{r['requested_at']}, until {r['expires_at']}")
1760
+ return 0
1761
+
1762
+
1763
+ def _signing_project_key(client: Client, project_id: str):
1764
+ """This device's key, which must be active on the project: only such a key can add or
1765
+ retire another."""
1766
+ key = trust.load_developer_key()
1767
+ fp = trust.fingerprint(trust.public_raw(key)) if key is not None else None
1768
+ active = [k["fingerprint"] for k in _project_keys(client, project_id)
1769
+ if not k.get("valid_until")]
1770
+ if fp is None or (active and fp not in active):
1771
+ raise Abort("this device's key is not a key of the project: run this on a device that "
1772
+ "already seals it" + (f" (its keys: {', '.join(active)})" if active else ""))
1773
+ return key
1774
+
1775
+
1776
+ def _key_approve(args, client: Client, project_id: str) -> int:
1777
+ key = _signing_project_key(client, project_id)
1778
+ try:
1779
+ waiting = client.key_requests(project_id)["requests"]
1780
+ except ApiError as exc:
1781
+ if exc.status == 404 and exc.code == "project_not_found":
1782
+ raise Abort(_not_your_project(client, project_id, key)) from exc
1783
+ raise Abort(_explain(client, exc, "could not read the requests")) from exc
1784
+ except NetworkError as exc:
1785
+ raise Abort(f"could not read the requests: {exc}") from exc
1786
+ wanted = (args.fingerprint or "").lower()
1787
+ found = [r for r in waiting if r["fingerprint"].startswith(wanted)]
1788
+ if not waiting:
1789
+ _say("No key requests are waiting on this project.")
1790
+ return 0
1791
+ if len(found) != 1:
1792
+ for r in waiting:
1793
+ who = "your account" if r.get("same_account") else "another account"
1794
+ _say(f" {r['fingerprint']} {r.get('label') or '(no label)'} from {who}, "
1795
+ f"{r['requested_at']}")
1796
+ raise Abort("name the key to approve: imprint key approve <fingerprint>"
1797
+ if not wanted or len(found) > 1 else f"no request from a key {wanted}")
1798
+ req = found[0]
1799
+ if trust.fingerprint(imprint_file.b64d(req["public_key"])) != req["fingerprint"]:
1800
+ raise Abort("the server sent a public key that does not match its fingerprint")
1801
+ who = "your own account" if req.get("same_account") else "ANOTHER account"
1802
+ _say(f"Request key {req['fingerprint']}, label: {req.get('label') or '(none)'}",
1803
+ f"From {who}, {req['requested_at']}",
1804
+ f"Adding it lets that device seal into project {project_id}.")
1805
+ _ask(args, "Add this key to the project?")
1806
+ try:
1807
+ client.change_project_key(project_id, "add", req["public_key"],
1808
+ *chainseal.key_change(key, project_id, "add",
1809
+ req["public_key"]))
1810
+ except (ApiError, NetworkError) as exc:
1811
+ raise Abort(_explain(client, exc, "the key was not added")) from exc
1812
+ _say(f"Added key {req['fingerprint']}: that device can seal into the project now")
1813
+ return 0
1814
+
1815
+
1816
+ def _key_retire(args, client: Client, project_id: str) -> int:
1817
+ key = _signing_project_key(client, project_id)
1818
+ wanted = (args.fingerprint or "").lower()
1819
+ if not wanted:
1820
+ raise Abort("name the key to retire: imprint key retire <fingerprint>")
1821
+ active = [k for k in _project_keys(client, project_id) if not k.get("valid_until")]
1822
+ found = [k for k in active if k["fingerprint"].startswith(wanted)]
1823
+ if len(found) != 1:
1824
+ raise Abort(f"no single active key of this project starts with {wanted}")
1825
+ if len(active) == 1:
1826
+ raise Abort("that is the project's only key: retiring it would leave nobody able to "
1827
+ "seal. Add another key first")
1828
+ target = found[0]
1829
+ _say(f"Retiring key {target['fingerprint']}: it can no longer seal into project "
1830
+ f"{project_id}. Its earlier seals stay valid. This cannot be undone.")
1831
+ _ask(args, "Retire this key?")
1832
+ try:
1833
+ client.change_project_key(project_id, "retire", target["public_key"],
1834
+ *chainseal.key_change(key, project_id, "retire",
1835
+ target["public_key"]))
1836
+ except (ApiError, NetworkError) as exc:
1837
+ raise Abort(_explain(client, exc, "the key was not retired")) from exc
1838
+ _say(f"Retired key {target['fingerprint']}")
1839
+ return 0
1840
+
1841
+
1842
+ def cmd_key(args) -> int:
1843
+ root = Path(args.path)
1844
+ cfg = project.load_config(root) if root.is_dir() else {}
1845
+ project_id = args.project or cfg.get("project_id")
1846
+ if not project_id:
1847
+ raise Abort("no project here: .imprint/config.json names none (run this in the "
1848
+ "project's folder, or pass --project <ID>)")
1849
+ client = _client(args)
1850
+ if args.action == "request":
1851
+ return _key_request(args, client, project_id)
1852
+ if args.action == "approve":
1853
+ return _key_approve(args, client, project_id)
1854
+ if args.action == "retire":
1855
+ return _key_retire(args, client, project_id)
1856
+ return _key_list(client, project_id)
1857
+
1858
+
1696
1859
  # -- project names and the GitHub App (CIM-BE-19-v1) ---------------------------------------
1697
1860
  def cmd_project(args) -> int:
1698
1861
  key = _developer_key(required=True)
@@ -1839,6 +2002,12 @@ def _load_target(args) -> tuple[dict | None, dict | None, Path]:
1839
2002
  rec_path = Path(args.receipt) if args.receipt else receipt_path_for(target)
1840
2003
  rec = imprint_file.load(rec_path) if rec_path.is_file() else None
1841
2004
  return data, rec, _project_root(target)
2005
+ if isinstance(data, dict) and isinstance(data.get("receipt"), dict) \
2006
+ and receipt.is_lineage(data["receipt"]):
2007
+ # What `imprint lineage show --out` saved: the record and, when this account
2008
+ # may see it, the opening of its commitment.
2009
+ args.found_opening = data.get("opening")
2010
+ return None, data["receipt"], _project_root(target)
1842
2011
  if isinstance(data, dict) and "attestation" in data:
1843
2012
  doc_path = target.with_name(target.name.removesuffix(".receipt.json") + ".imprint")
1844
2013
  doc = imprint_file.load(doc_path) if doc_path.is_file() else None
@@ -1904,6 +2073,80 @@ def _server_from_project(root: Path) -> str | None:
1904
2073
  return None
1905
2074
 
1906
2075
 
2076
+ def _fetch_lineage(client: Client, record_id: str) -> tuple[dict, dict | None]:
2077
+ """A lineage record and, for an account that may see it, its opening. Without a
2078
+ sign-in (or on an older server) the public record alone."""
2079
+ if client.auth in ("token", "session"):
2080
+ try:
2081
+ answer = client.lineage(record_id)
2082
+ return answer["receipt"], answer.get("opening")
2083
+ except (ApiError, KeyError):
2084
+ pass
2085
+ return client.public_record(record_id), None
2086
+
2087
+
2088
+ def _opening_for(args, rec: dict | None, found: dict | None) -> dict | None:
2089
+ """The opening to check a lineage record's commitment against: --opening FILE, else
2090
+ the one that came with the record."""
2091
+ if not getattr(args, "opening", None):
2092
+ return found
2093
+ if rec is None or not receipt.is_lineage(rec):
2094
+ raise Abort("--opening is for lineage records (LIN1)")
2095
+ try:
2096
+ data = json.loads(Path(args.opening).read_text(encoding="utf-8"))
2097
+ except (OSError, ValueError) as exc:
2098
+ raise Abort(f"cannot read {args.opening}: {exc}") from exc
2099
+ if not isinstance(data, dict):
2100
+ raise Abort(f"{args.opening} does not hold an opening")
2101
+ return data["opening"] if "receipt" in data and "opening" in data else data
2102
+
2103
+
2104
+ def cmd_lineage(args) -> int:
2105
+ """`imprint lineage show LIN1-…`: a lineage record as this account may see it."""
2106
+ if not imprint_file.is_valid_id(args.record, ("LIN1",)):
2107
+ raise Abort(f"not a lineage record ID (LIN1-…): {args.record}")
2108
+ rid = imprint_file.clean_id(args.record)
2109
+ client = _client(args, _server_from_project(Path(".")))
2110
+ try:
2111
+ answer = client.lineage(rid)
2112
+ except (ApiError, NetworkError) as exc:
2113
+ raise Abort(_explain(client, exc, f"cannot read {rid}")) from exc
2114
+ saved = imprint_file.save(answer, args.out) if args.out else None
2115
+ if args.json:
2116
+ print(json.dumps(answer, indent=2))
2117
+ return 0
2118
+ doc = answer["receipt"]["record"]["document"]
2119
+ opening = answer.get("opening") or {}
2120
+ clone = opening.get("child") or (
2121
+ {"project": doc["child"], "seal": doc["child_seal"]} if "child" in doc else None)
2122
+ _say(f"Record {rid}",
2123
+ f"Link {answer['basis']} {answer['relation']}, signals "
2124
+ f"{', '.join(answer['signals'])}, {answer['at']}")
2125
+ if clone:
2126
+ _say(f"Clone project {clone['project']}, seal {clone['seal']}")
2127
+ else:
2128
+ _say("Clone not named in the public record")
2129
+ if opening:
2130
+ origin = opening["parent"]
2131
+ _say(f"Origin project {origin['project']}, "
2132
+ + (f"seal {origin['seal']}" if origin.get("seal") else "no seal named")
2133
+ + (" (as declared)" if answer["basis"] == "declared" else ""))
2134
+ checks = opening.get("checks")
2135
+ if checks:
2136
+ _say("Declared the origin project "
2137
+ + ("is" if checks.get("parent_known") else "is not") + " on this server; "
2138
+ "the seal named "
2139
+ + ("is" if checks.get("parent_seal_in_parent") else "is not") + " one of its seals")
2140
+ else:
2141
+ _say("Origin not shown: the public record holds a commitment only. Both sides "
2142
+ "are shown to an account that is part of both projects.")
2143
+ if saved:
2144
+ _say(f"Saved {saved} (check it offline: imprint verify {saved})")
2145
+ _say("", "A link says that two projects share an origin and which was sealed earlier; "
2146
+ "it does not say who wrote the code.")
2147
+ return 0
2148
+
2149
+
1907
2150
  def _file_only(doc: dict) -> list[receipt.Check]:
1908
2151
  status = imprint_file.verify_document(doc)
1909
2152
  sig = ("not signed" if not status["signed"] else
@@ -1924,20 +2167,25 @@ def cmd_verify(args) -> int:
1924
2167
  args.verify_parser.error("the following arguments are required: target")
1925
2168
  args.target = str(default)
1926
2169
  doc, rec, root = _load_target(args)
2170
+ found = getattr(args, "found_opening", None)
1927
2171
  checks: list[receipt.Check] = []
1928
2172
  client = _client(args, _server_from_project(root)) if args.online else None
1929
2173
  if rec is None and client is not None:
1930
2174
  iid = imprint_file.clean_id(args.target) if doc is None else (
1931
2175
  imprint_file.verify_document(doc)["id"])
2176
+ prefix = iid.split("-", 1)[0]
1932
2177
  try:
1933
- rec = (client.public_record(iid)
1934
- if iid.split("-", 1)[0] in imprint_file.RECORD_PREFIXES
1935
- else client.public_imprint(iid))
2178
+ if prefix == "LIN1":
2179
+ rec, found = _fetch_lineage(client, iid)
2180
+ else:
2181
+ rec = (client.public_record(iid) if prefix in imprint_file.RECORD_PREFIXES
2182
+ else client.public_imprint(iid))
1936
2183
  except ApiError as exc:
1937
2184
  if doc is None:
1938
2185
  raise Abort(f"no public record for {iid}: {exc}") from exc
1939
2186
  except NetworkError as exc:
1940
2187
  raise Abort(str(exc)) from exc
2188
+ opening = _opening_for(args, rec, found)
1941
2189
  if rec is None:
1942
2190
  checks = _file_only(doc)
1943
2191
  iid = imprint_file.verify_document(doc)["id"]
@@ -1952,7 +2200,7 @@ def cmd_verify(args) -> int:
1952
2200
  f"also trusting {extra} certificate(s) from "
1953
2201
  f"{args.tsa_certs}, beyond the pinned roots"))
1954
2202
  checks += receipt.verify(rec, keys, doc, developer=args.developer or developer,
1955
- anchors=anchors)
2203
+ anchors=anchors, opening=opening)
1956
2204
  if client is not None and keys:
1957
2205
  try:
1958
2206
  checks += receipt.verify_online(rec, client, keys, anchors)
@@ -2017,6 +2265,19 @@ def build_parser() -> argparse.ArgumentParser:
2017
2265
  "project of your own for it")
2018
2266
  n.set_defaults(func=cmd_init)
2019
2267
 
2268
+ ky = sub.add_parser("key", help="the project's keys: add another device (request, then "
2269
+ "approve), list, retire")
2270
+ ky.add_argument("action", choices=["request", "approve", "list", "retire"])
2271
+ ky.add_argument("fingerprint", nargs="?",
2272
+ help="approve, retire: the key's fingerprint (or the start of it)")
2273
+ ky.add_argument("--path", default=".", help="the project's folder (default: here)")
2274
+ ky.add_argument("--project", help="project ID (default: .imprint/config.json)")
2275
+ ky.add_argument("--label", help="request: a name for this device, shown to whoever "
2276
+ "approves (default: the computer's name)")
2277
+ ky.add_argument("--yes", action="store_true", help="approve, retire: do not ask")
2278
+ ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2279
+ ky.set_defaults(func=cmd_key)
2280
+
2020
2281
  pj = sub.add_parser("project", help="the project's display name: rename")
2021
2282
  pj.add_argument("action", choices=["rename"])
2022
2283
  pj.add_argument("name", help="the new name (1-100 characters)")
@@ -2219,9 +2480,23 @@ def build_parser() -> argparse.ArgumentParser:
2219
2480
  v.add_argument("--url", help="server URL for --online")
2220
2481
  v.add_argument("--tsa-certs", metavar="FILE",
2221
2482
  help="also trust the time-stamping authorities in this PEM bundle")
2483
+ v.add_argument("--opening", metavar="FILE",
2484
+ help="a lineage record (LIN1): check that this opening ({parent: {project, "
2485
+ "seal}, salt}) gives the record's commitment")
2222
2486
  v.add_argument("--strict", action="store_true", help="treat warnings as failures")
2223
2487
  v.add_argument("--json", action="store_true")
2224
2488
  v.set_defaults(func=cmd_verify, verify_parser=v)
2489
+
2490
+ ln = sub.add_parser("lineage", help="a lineage record (LIN1): the link between a clone "
2491
+ "and its origin, as far as you may see it")
2492
+ ln.add_argument("action", choices=["show"])
2493
+ ln.add_argument("record", help="the record's ID (LIN1-…)")
2494
+ ln.add_argument("-o", "--out", metavar="FILE",
2495
+ help="save the record (and its opening, when shown to you) to verify "
2496
+ "offline with `imprint verify FILE`")
2497
+ ln.add_argument("--json", action="store_true")
2498
+ ln.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2499
+ ln.set_defaults(func=cmd_lineage)
2225
2500
  return p
2226
2501
 
2227
2502
 
@@ -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,94 @@ 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 is_lineage(receipt: dict) -> bool:
104
+ return ((receipt or {}).get("record") or {}).get("type") == LINEAGE
105
+
106
+
107
+ def _lineage(receipt: dict) -> Check | None:
108
+ """A lineage record (LIN1) links a clone to its origin. A declared link names the clone
109
+ and its seal and is signed by one key, role child. A detected link is the server's own
110
+ record and names nobody. Neither names the origin: that is a salted commitment, which
111
+ ``_opening`` checks when the opening is at hand. The signatures themselves are verified
112
+ by ``_record``."""
113
+ if not is_lineage(receipt):
114
+ return None
115
+ doc = receipt["record"].get("document") or {}
116
+ basis = doc.get("basis")
117
+ if not isinstance(basis, str) or set(doc) != _LINEAGE_FIELDS.get(basis):
118
+ return Check("lineage", FAIL, "not a declared or detected link, or it holds other "
119
+ "fields")
120
+ signals = doc["signals"]
121
+ if doc["relation"] not in _RELATIONS or not isinstance(signals, list) or not signals \
122
+ or not all(isinstance(s, str) for s in signals):
123
+ return Check("lineage", FAIL, "unknown relation or signals")
124
+ if not _hex64(doc["parent_commitment" if basis == "declared" else "link_commitment"]):
125
+ return Check("lineage", FAIL, "the commitment is not a SHA-256")
126
+ sigs = receipt.get("signatures") or []
127
+ how = f"{doc['relation']} link, signals {', '.join(signals)}"
128
+ if basis == "declared":
129
+ if [s.get("role") for s in sigs] != ["child"]:
130
+ return Check("lineage", FAIL, "a declared link has one signature, role child")
131
+ return Check("lineage", PASS,
132
+ f"declared {how}: project {doc['child']} at seal {doc['child_seal']}, "
133
+ f"signed by key {sigs[0].get('fingerprint')}; the origin is a "
134
+ "commitment")
135
+ if sigs:
136
+ return Check("lineage", FAIL, "a detected link has no owner signature")
137
+ return Check("lineage", PASS, f"detected {how}: the server's own record; neither "
138
+ "project is named, the link is a commitment")
139
+
140
+
141
+ def _opening(receipt: dict, opening) -> Check:
142
+ """Does the opening give the record's commitment? ``parent_commitment`` is SHA-256 of
143
+ canonical JSON {salt, project, seal} (the origin); ``link_commitment`` adds the clone as
144
+ child and child_seal."""
145
+ doc = receipt["record"]["document"]
146
+ declared = doc.get("basis") == "declared"
147
+ shape = "the opening is {parent: {project, seal}, salt}" + (
148
+ "" if declared else ", with child: {project, seal}")
149
+ try:
150
+ salt, project, seal = opening["salt"], opening["parent"]["project"], opening[
151
+ "parent"]["seal"]
152
+ child = opening.get("child") if declared else opening["child"]
153
+ clone = None if child is None else (child["project"], child["seal"])
154
+ except (AttributeError, KeyError, TypeError):
155
+ return Check("opening", FAIL, shape)
156
+ if not all(isinstance(v, str) for v in (salt, project)) or not isinstance(
157
+ seal, (str, type(None))) or (clone and not all(isinstance(v, str) for v in clone)):
158
+ return Check("opening", FAIL, shape)
159
+ body = {"salt": salt, "project": project, "seal": seal}
160
+ if declared:
161
+ if clone is not None and clone != (doc.get("child"), doc.get("child_seal")):
162
+ return Check("opening", FAIL, "the opening names another clone than the record")
163
+ expected = doc.get("parent_commitment")
164
+ else:
165
+ body.update(child=clone[0], child_seal=clone[1])
166
+ expected = doc.get("link_commitment")
167
+ if hashlib.sha256(canonical(body)).hexdigest() != expected:
168
+ return Check("opening", FAIL, "the opening does not give the record's commitment: "
169
+ "another project, seal or salt")
170
+ origin = f"origin project {project}, " + (f"seal {seal}" if seal else "no seal named")
171
+ if declared:
172
+ return Check("opening", PASS, f"the commitment opens to {origin}")
173
+ return Check("opening", PASS, f"the commitment opens to clone project {clone[0]}, seal "
174
+ f"{clone[1]}, and {origin}")
175
+
176
+
89
177
  def _release(receipt: dict) -> Check:
90
178
  """A release record: its digest is SHA-256 of the release document, which names the
91
179
  labelled seal; the chain must say the same."""
@@ -552,9 +640,10 @@ def _time_order(receipt: dict, infos: list[timestamp.TokenInfo], now: datetime)
552
640
 
553
641
  def verify(receipt: dict, keys: list[dict], doc: dict | None = None,
554
642
  developer: str | None = None, now: datetime | None = None,
555
- anchors: list | None = None) -> list[Check]:
643
+ anchors: list | None = None, opening: dict | None = None) -> list[Check]:
556
644
  """Every offline check. ``developer`` is the fingerprint the project expects to sign;
557
- ``anchors`` the trusted TSA roots (default: the pinned ones)."""
645
+ ``anchors`` the trusted TSA roots (default: the pinned ones); ``opening`` what a lineage
646
+ record's commitment is said to commit to."""
558
647
  now = now or datetime.now(timezone.utc)
559
648
  anchors = timestamp.pinned_anchors() if anchors is None else anchors
560
649
  if not keys:
@@ -566,6 +655,11 @@ def verify(receipt: dict, keys: list[dict], doc: dict | None = None,
566
655
  typed = _identity(receipt, now)
567
656
  if typed:
568
657
  checks.insert(1, typed)
658
+ link = _lineage(receipt)
659
+ if link:
660
+ checks.insert(1, link)
661
+ if opening is not None and link.status == PASS:
662
+ checks.insert(2, _opening(receipt, opening))
569
663
  tokens, infos = _timestamps(receipt, keys, anchors)
570
664
  return checks + tokens + [_time_order(receipt, infos, now)]
571
665
  checks = [_digest(receipt, doc), _attestation(receipt, keys),
@@ -642,19 +736,23 @@ def verify_online(receipt: dict, client, keys: list[dict],
642
736
  f"entry #{index} was added after entry #{index - 1}"))
643
737
 
644
738
  chain = receipt.get("chain") or {}
645
- signer = chain_signer(receipt)
646
- if chain.get("project") and signer and hasattr(client, "public_project"):
739
+ signer, signed_for = chain_signer(receipt), chain.get("project")
740
+ if is_lineage(receipt): # a declared link: the clone's project key signed
741
+ doc, sigs = receipt["record"]["document"], receipt.get("signatures") or []
742
+ if doc.get("basis") == "declared" and len(sigs) == 1:
743
+ signer, signed_for = sigs[0].get("fingerprint"), doc.get("child")
744
+ if signed_for and signer and hasattr(client, "public_project"):
647
745
  attested = receipt["attestation"]["statement"]["attested_at"]
648
746
  keys_now = {k["fingerprint"]: k
649
- for k in client.public_project(chain["project"]).get("keys", [])}
747
+ for k in client.public_project(signed_for).get("keys", [])}
650
748
  k = keys_now.get(signer)
651
749
  if k and k["valid_from"] <= attested and (not k["valid_until"]
652
750
  or attested <= k["valid_until"]):
653
751
  checks.append(Check("project key", PASS, f"{signer} was a key of project "
654
- f"{chain['project']} at {attested}"))
752
+ f"{signed_for} at {attested}"))
655
753
  else:
656
754
  checks.append(Check("project key", FAIL, f"{signer} was not a key of project "
657
- f"{chain['project']} at {attested}"))
755
+ f"{signed_for} at {attested}"))
658
756
  rel = receipt.get("release")
659
757
  if rel:
660
758
  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