codeimprint 0.5.0a13__tar.gz → 0.5.0a15__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.0a13 → codeimprint-0.5.0a15}/CHANGELOG.md +51 -0
  2. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/PKG-INFO +13 -1
  3. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/README.pypi.md +12 -0
  4. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/pyproject.toml +5 -3
  5. codeimprint-0.5.0a15/src/codeimprint/__init__.py +6 -0
  6. codeimprint-0.5.0a15/src/codeimprint/__main__.py +6 -0
  7. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/__init__.py +1 -1
  8. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/api.py +25 -0
  9. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/chainseal.py +28 -0
  10. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/cli.py +314 -14
  11. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/config.py +6 -0
  12. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/.gitignore +0 -0
  13. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/LICENSE +0 -0
  14. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/NOTICE +0 -0
  15. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/__main__.py +0 -0
  16. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/gitrepo.py +0 -0
  17. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/imprint_file.py +0 -0
  18. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/linecount.py +0 -0
  19. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/ownership.py +0 -0
  20. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/project.py +0 -0
  21. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/receipt.py +0 -0
  22. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a13 → codeimprint-0.5.0a15}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,56 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a15 — Another device joins the project; `python -m codeimprint` [CIM-BE-30-v1]
4
+
5
+ For engine 0.7.0a20. Older engines still work, except for the new `imprint key` commands.
6
+
7
+ - **New: `imprint key`.** The same repository on any device is the same project (ADR 0007).
8
+ - `imprint key request` on the new device makes that device's own key and asks for it to
9
+ be added. `--label` names the device; the default is the computer's name.
10
+ - `imprint key approve [fingerprint]` on a device that already seals the project shows
11
+ the request (label, and whether it comes from your own account) and adds the key.
12
+ - `imprint key list` shows the project's keys and the requests waiting.
13
+ - `imprint key retire <fingerprint>` retires a key, for example of a lost device. It
14
+ refuses to retire the project's only key.
15
+ - **Changed messages:** when this machine has no project key, or its key is not one of the
16
+ project's keys, `seal` and `init` now point to `imprint key request` (0.5.0a14 said to
17
+ copy the key file). A cloned project that is not yours names `imprint key request` as the
18
+ way to ask to join.
19
+ - **New: `python -m codeimprint`** runs the same commands as `imprint`. Use it where the
20
+ `imprint` program cannot be started, for example when Windows Application Control blocks
21
+ it. The wheel gains a small `codeimprint` package that holds only this entry point.
22
+ - Signed requests are tied to the sign-in session; with an API token they are tied to none.
23
+ - Tests: `tests/test_keys.py`.
24
+
25
+ ## 0.5.0a14 — Sign-in works for sealing; clearer messages for clones [CIM-BE-29-v2]
26
+
27
+ For engine 0.7.0a19. Older engines still work.
28
+
29
+ - **Fixed: `imprint init`, `seal` and `check` use your `imprint login` session.** Before,
30
+ they sent only an API token, so on a server that requires an account they failed with
31
+ `401 login_required` right after a successful login.
32
+ - An API token (`CODEIMPRINT_TOKEN`, or saved with `imprint login --api-token`) still wins.
33
+ - An ended session says so: "your sign-in to <server> has expired: run `imprint login`
34
+ again". Not signed in at all says to run `imprint login`.
35
+ - The Git hook uses the session too.
36
+ - **Before anything is uploaded**, a project seal checks that your account may use the
37
+ project and that this machine's key is one of its keys. It proves the key to the server
38
+ for this session (`POST /api/v1/projects/{id}/access`).
39
+ - **Clearer messages:**
40
+ - The project's key is not on this machine: copy `developer-key.pem` from the machine
41
+ that has it, or set `CODEIMPRINT_DEVELOPER_KEY`. It no longer says "run `imprint init`",
42
+ which made a second key the project does not accept.
43
+ - This machine's key is not one of the project's keys: the message names the keys the
44
+ project has, and nothing is uploaded.
45
+ - `.imprint/` came with a repository you cloned and names a project your account is not
46
+ part of: `seal` and `init` stop and name `imprint init --new-project`.
47
+ - **New: `imprint init --new-project`** makes a project of your own in such a folder. It
48
+ moves the other project's seal files to `.imprint/origin/` and records `cloned_from` in
49
+ `.imprint/config.json`.
50
+ - A zip seal is "already sealed" only for your own earlier seal (engine 0.7.0a19).
51
+ - GitHub Actions: all of these stay warnings, never a failed build.
52
+ - Tests: `tests/test_phase0.py`.
53
+
3
54
  ## 0.5.0a13 — The old brand name is gone [CIM-BE-26-v1]
4
55
 
5
56
  - **Development origin:** `receipt.ORIGIN`, the development log origin the tests' simulated
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a13
3
+ Version: 0.5.0a15
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.0a13"
9
+ version = "0.5.0a15"
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.0a13"
8
+ __version__ = "0.5.0a15"
@@ -73,6 +73,9 @@ def _multipart_parts(parts: list[tuple[str, bytes]]) -> tuple[bytes, str]:
73
73
  class Client:
74
74
  def __init__(self, url: str, token: str | None = None, timeout: float = 300) -> None:
75
75
  self.url, self.token, self.timeout = url.rstrip("/"), token, timeout
76
+ # How this client is signed in: "token" (an API token), "session" (`imprint login`),
77
+ # "expired" (that session has ended) or "none". Set by the command line.
78
+ self.auth = "token" if token else "none"
76
79
  self.access = config.cf_access_for(self.url) # this server's host only
77
80
 
78
81
  def _request(self, method: str, path: str, body: bytes | None = None,
@@ -159,6 +162,28 @@ class Client:
159
162
  "signature": signature,
160
163
  **({"key_signature": key_signature} if key_signature else {})})
161
164
 
165
+ def project_access(self, project: str, public_key: str | None = None,
166
+ signature: str | None = None) -> dict:
167
+ """200 when this caller may use the project (engine 0.7.0a19+); a project key's
168
+ signature links an account that is not linked yet."""
169
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/access",
170
+ {"public_key": public_key, "signature": signature})
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 key_requests(self, project: str) -> dict:
179
+ return self._json("GET", f"/api/v1/projects/{quote(project)}/keys/requests")
180
+
181
+ def change_project_key(self, project: str, action: str, public_key: str,
182
+ signer_public_key: str, signature: str) -> dict:
183
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/keys",
184
+ {"action": action, "public_key": public_key,
185
+ "signer_public_key": signer_public_key, "signature": signature})
186
+
162
187
  def plan(self, project: str, payload: dict) -> dict:
163
188
  return self._json("POST", f"/api/v1/projects/{quote(project)}/seal/plan", payload)
164
189
 
@@ -13,6 +13,7 @@ Local state lives in the Git directory, never in the working tree:
13
13
 
14
14
  from __future__ import annotations
15
15
 
16
+ import hashlib
16
17
  import json
17
18
  import time
18
19
  from pathlib import Path
@@ -33,6 +34,33 @@ def public_key(key) -> str:
33
34
  return trust.b64e(trust.public_raw(key))
34
35
 
35
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
+
44
+ def access_proof(key, project: str, token: str | None) -> tuple[str, str]:
45
+ """(public key, signature) showing that this session holds a project key: the key signs
46
+ {type, project, session}, so the proof works for this sign-in only."""
47
+ return public_key(key), sign(key, {"type": "codeimprint.project-access.v1",
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})
62
+
63
+
36
64
  def create_project(client, key, name: str | None = None) -> dict:
37
65
  """Create a project for this developer key and finalise its genesis seal (an empty tree).
38
66
  ``name`` is the project's display name (shown on its public page)."""
@@ -171,13 +171,87 @@ def _warn(message: str) -> None:
171
171
  print(f"imprint: warning: {message}", file=sys.stderr)
172
172
 
173
173
 
174
+ def _signed_in(url: str, api_token: str | None) -> Client:
175
+ """A client for this server: the API token when one is set (CODEIMPRINT_TOKEN or saved by
176
+ `imprint login --api-token`), else the session from `imprint login`."""
177
+ if api_token:
178
+ return Client(url, api_token)
179
+ session = config.load_session(url)
180
+ client = Client(url, session["token"] if session else None)
181
+ client.auth = "session" if session else (
182
+ "expired" if config.session_expired(url) else "none")
183
+ return client
184
+
185
+
174
186
  def _client(args, fallback_url: str | None = None) -> Client:
175
187
  settings = config.resolve(getattr(args, "url", None))
176
188
  url = settings.url or fallback_url
177
189
  if not url:
178
190
  raise Abort("no server configured: run `imprint login --url <server>` or set "
179
191
  "CODEIMPRINT_URL")
180
- return Client(url, settings.token if settings.url else None)
192
+ return _signed_in(url, settings.token if settings.url else None)
193
+
194
+
195
+ def _explain(client: Client, exc: Exception, what: str) -> str:
196
+ """``what: why``, with what to do when the server asks for a sign-in."""
197
+ if isinstance(exc, ApiError) and exc.status == 401:
198
+ if client.auth == "expired":
199
+ return (f"{what}: your sign-in to {client.url} has expired: run `imprint login` "
200
+ f"again. The server said: {exc}")
201
+ if client.auth == "none":
202
+ return (f"{what}: you are not signed in to {client.url}: run `imprint login` (or "
203
+ f"set CODEIMPRINT_TOKEN to an API token). The server said: {exc}")
204
+ return f"{what}: {exc}"
205
+
206
+
207
+ def _not_your_project(client: Client, project_id: str, key) -> str:
208
+ mine = f" {trust.fingerprint(trust.public_raw(key))}" if key is not None else ""
209
+ return (f"this folder's .imprint/config.json names project {project_id}, which is not on "
210
+ f"{client.url} or which your account is not part of (for example, it came with a "
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, run `imprint key "
213
+ f"request`: its owner sees the request and can add your developer key{mine}.")
214
+
215
+
216
+ def _project_state(client: Client, project_id: str, key) -> str:
217
+ """"ok" when this caller may use the project, "not-yours" when the server says it does
218
+ not exist for them, else "unknown" (an engine before 0.7.0a19, or no answer)."""
219
+ try:
220
+ proof = chainseal.access_proof(key, project_id, client.token) if key is not None \
221
+ else (None, None)
222
+ client.project_access(project_id, *proof)
223
+ except ApiError as exc:
224
+ if exc.status == 404 and exc.code == "project_not_found":
225
+ return "not-yours"
226
+ if exc.status == 401:
227
+ raise
228
+ return "unknown"
229
+ except NetworkError:
230
+ return "unknown"
231
+ return "ok"
232
+
233
+
234
+ def _project_ready(client: Client, project_id: str, key) -> None:
235
+ """Before anything is uploaded: this account may use the project, and this machine's key
236
+ is one of the project's keys."""
237
+ try:
238
+ state = _project_state(client, project_id, key)
239
+ except ApiError as exc:
240
+ raise SealFailed(_explain(client, exc, "sealing failed")) from exc
241
+ if state == "not-yours":
242
+ raise SealFailed(_not_your_project(client, project_id, key))
243
+ try:
244
+ keys = client.public_project(project_id).get("keys") or []
245
+ except (ApiError, NetworkError):
246
+ return
247
+ active = [k["fingerprint"] for k in keys if not k.get("valid_until")]
248
+ fp = trust.fingerprint(trust.public_raw(key))
249
+ if active and fp not in active:
250
+ raise SealFailed(
251
+ f"developer key {fp} on this machine is not a key of project {project_id} (its "
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.")
181
255
 
182
256
 
183
257
  def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool) -> bytes:
@@ -302,6 +376,8 @@ def cmd_init(args) -> int:
302
376
  raise Abort(f"no such folder: {root}")
303
377
  cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
304
378
  existing = project.load_config(root)
379
+ if getattr(args, "new_project", False) and existing.get("project_id"):
380
+ existing = _leave_project(root, cfg_path, existing)
305
381
  cfg = {"version": 1, "exclude": existing.get("exclude", project.DEFAULT_EXCLUDE),
306
382
  "fail_above": existing.get("fail_above", DEFAULT_FAIL_ABOVE),
307
383
  "reference": existing.get("reference")}
@@ -346,7 +422,8 @@ def cmd_init(args) -> int:
346
422
  " To sign seals in CI, store the file's contents as the secret "
347
423
  "CODEIMPRINT_DEVELOPER_KEY.")
348
424
  if cfg.get("developer") != fp:
349
- _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`")
350
427
  if key is not None and not args.no_project:
351
428
  _init_project(args, root, cfg_path, key)
352
429
  if key is not None:
@@ -355,6 +432,29 @@ def cmd_init(args) -> int:
355
432
  return 0
356
433
 
357
434
 
435
+ def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
436
+ """`imprint init --new-project`: stop pointing at the project this folder came with. Its
437
+ seal files move to .imprint/origin/ (they belong to that project) and the config keeps
438
+ only where the code came from."""
439
+ folder = root / project.CONFIG_DIR
440
+ origin = folder / "origin"
441
+ moved = []
442
+ for path in sorted(folder.iterdir()):
443
+ if path.is_file() and (path.suffix == ".imprint" or path.name.endswith(".receipt.json")):
444
+ origin.mkdir(exist_ok=True)
445
+ path.replace(origin / path.name)
446
+ moved.append(path.name)
447
+ kept = {k: v for k, v in existing.items()
448
+ if k not in ("project_id", "developer", "cloned_from")}
449
+ kept["cloned_from"] = {"project": existing["project_id"]}
450
+ cfg_path.write_text(json.dumps(kept, indent=2) + "\n", encoding="utf-8")
451
+ _say(f"Leaving project {existing['project_id']} (kept as cloned_from in "
452
+ ".imprint/config.json)")
453
+ if moved:
454
+ _say(f"Moved {len(moved)} seal file(s) of that project to .imprint/origin/")
455
+ return kept
456
+
457
+
358
458
  def default_project_name(root: Path) -> str:
359
459
  """The repository's ``owner/repo`` from its origin remote, else the folder's name."""
360
460
  if gitrepo.is_repo(root):
@@ -369,21 +469,31 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
369
469
  current = project.load_config(root)
370
470
  settings = config.resolve(getattr(args, "url", None))
371
471
  if current.get("project_id"):
472
+ if settings.url:
473
+ client = _signed_in(settings.url, settings.token)
474
+ try:
475
+ state = _project_state(client, current["project_id"], key)
476
+ except ApiError as exc:
477
+ _warn(_explain(client, exc, "could not check the project"))
478
+ state = "unknown"
479
+ if state == "not-yours":
480
+ raise Abort(_not_your_project(client, current["project_id"], key))
372
481
  _say(f"Project {current['project_id']} (already created)")
373
482
  if getattr(args, "name", None) and settings.url:
374
- _rename(Client(settings.url, settings.token), current["project_id"], key,
483
+ _rename(_signed_in(settings.url, settings.token), current["project_id"], key,
375
484
  args.name, True)
376
485
  return
377
486
  if not settings.url:
378
487
  _say("", "No server configured: run `imprint login`, then `imprint init` again to "
379
488
  "create the project and its genesis seal.")
380
489
  return
381
- client = Client(settings.url, settings.token)
490
+ client = _signed_in(settings.url, settings.token)
382
491
  name = getattr(args, "name", None) or default_project_name(root)
383
492
  try:
384
493
  made = chainseal.create_project(client, key, name)
385
494
  except (ApiError, NetworkError) as exc:
386
- _warn(f"the project was not created ({exc}); run `imprint init` again later")
495
+ _warn(_explain(client, exc, "the project was not created")
496
+ + "; run `imprint init` again afterwards")
387
497
  return
388
498
  g = made["genesis"]
389
499
  current["project_id"] = made["project_id"]
@@ -493,7 +603,8 @@ def _hook_run(args, root: Path) -> int:
493
603
  return warn("this repository has no CodeImprint project; run `imprint init`")
494
604
  key = trust.load_developer_key()
495
605
  if key is None:
496
- return warn("no developer key; run `imprint init`")
606
+ return warn("no developer key on this machine; run `imprint seal` to see how to "
607
+ "proceed")
497
608
  settings = config.resolve(None)
498
609
  head = gitrepo.resolve(root, "HEAD")
499
610
  except (gitrepo.GitError, ValueError, OSError) as exc:
@@ -504,7 +615,8 @@ def _hook_run(args, root: Path) -> int:
504
615
  if not settings.url:
505
616
  chainseal.save_queue(root, queue)
506
617
  return warn(f"no server configured; {len(queue)} seal(s) queued")
507
- client = Client(settings.url, settings.token, timeout=60)
618
+ client = _signed_in(settings.url, settings.token)
619
+ client.timeout = 60
508
620
  for i, item in enumerate(queue):
509
621
  try:
510
622
  out = chainseal.seal_commit(client, root, cfg["project_id"], item["commit"],
@@ -1269,14 +1381,20 @@ def _failed(checks: list[receipt.Check]) -> list[receipt.Check]:
1269
1381
  return [c for c in checks if c.status == receipt.FAIL]
1270
1382
 
1271
1383
 
1272
- def _developer_key(required: bool = False):
1384
+ def _developer_key(required: bool = False, expected: str | None = None):
1273
1385
  try:
1274
1386
  key = trust.load_developer_key()
1275
1387
  except ValueError as exc:
1276
1388
  raise SealFailed(f"cannot read the developer key: {exc}") from exc
1277
1389
  if key is None and required:
1278
- raise SealFailed("this project's seals are signed by your developer key, and none was "
1279
- "found: run `imprint init` (or set CODEIMPRINT_DEVELOPER_KEY in CI)")
1390
+ raise SealFailed(
1391
+ "this project's seals are signed with a developer key"
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.")
1280
1398
  return key
1281
1399
 
1282
1400
 
@@ -1356,6 +1474,8 @@ def _seal_zip(args, client: Client, data: bytes, project_id: str | None,
1356
1474
  """A zip seal (kind manual): code without Git, or `--zip`. Joins the project's chain
1357
1475
  when the project is known."""
1358
1476
  key = _developer_key(required=bool(project_id))
1477
+ if project_id:
1478
+ _project_ready(client, project_id, key)
1359
1479
  try:
1360
1480
  result = client.seal(data, name=args.name, lines=lines, project_id=project_id)
1361
1481
  if "pending_id" in result: # chained: sign, then finalise
@@ -1365,7 +1485,7 @@ def _seal_zip(args, client: Client, data: bytes, project_id: str | None,
1365
1485
  if lines is not None:
1366
1486
  chainseal.check_lines(lines, result)
1367
1487
  except (ApiError, NetworkError) as exc:
1368
- raise SealFailed(f"sealing failed: {exc}") from exc
1488
+ raise SealFailed(_explain(client, exc, "sealing failed")) from exc
1369
1489
  except RuntimeError as exc:
1370
1490
  raise SealFailed(str(exc)) from exc
1371
1491
  if result.get("already_sealed"):
@@ -1414,7 +1534,8 @@ def _confirm_upload(args, client: Client):
1414
1534
 
1415
1535
  def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1416
1536
  """Incremental seals of one commit or a range (ADR 0001): only new blobs are sent."""
1417
- key = _developer_key(required=True)
1537
+ key = _developer_key(required=True, expected=cfg.get("developer"))
1538
+ _project_ready(client, cfg["project_id"], key)
1418
1539
  try:
1419
1540
  commits = (gitrepo.commits(root, args.all_commits) if args.all_commits
1420
1541
  else [gitrepo.resolve(root, args.rev)])
@@ -1430,7 +1551,7 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1430
1551
  cfg.get("exclude"), _confirm_upload(args, client),
1431
1552
  tag=tag, public_tag=args.public_tag)
1432
1553
  except (ApiError, NetworkError) as exc:
1433
- raise SealFailed(f"sealing failed: {exc}") from exc
1554
+ raise SealFailed(_explain(client, exc, "sealing failed")) from exc
1434
1555
  except (gitrepo.GitError, RuntimeError) as exc:
1435
1556
  raise SealFailed(str(exc)) from exc
1436
1557
  if out.get("cancelled"):
@@ -1572,6 +1693,169 @@ def cmd_seal(args) -> int:
1572
1693
  return rc
1573
1694
 
1574
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
+
1575
1859
  # -- project names and the GitHub App (CIM-BE-19-v1) ---------------------------------------
1576
1860
  def cmd_project(args) -> int:
1577
1861
  key = _developer_key(required=True)
@@ -1688,7 +1972,7 @@ def cmd_check(args) -> int:
1688
1972
  return 0
1689
1973
  except ApiError as exc:
1690
1974
  if exc.status in {401, 403, 429} or exc.status >= 500:
1691
- _warn(f"check skipped — {exc}")
1975
+ _warn(_explain(client, exc, "check skipped"))
1692
1976
  return 0
1693
1977
  raise Abort(f"check failed: {exc}") from exc
1694
1978
  if args.output:
@@ -1891,8 +2175,24 @@ def build_parser() -> argparse.ArgumentParser:
1891
2175
  help="do not create the project and its genesis seal now")
1892
2176
  n.add_argument("--name", help="the project's display name (default: owner/repo from the "
1893
2177
  "origin remote, else the folder's name); public")
2178
+ 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")
1894
2181
  n.set_defaults(func=cmd_init)
1895
2182
 
2183
+ ky = sub.add_parser("key", help="the project's keys: add another device (request, then "
2184
+ "approve), list, retire")
2185
+ ky.add_argument("action", choices=["request", "approve", "list", "retire"])
2186
+ ky.add_argument("fingerprint", nargs="?",
2187
+ help="approve, retire: the key's fingerprint (or the start of it)")
2188
+ ky.add_argument("--path", default=".", help="the project's folder (default: here)")
2189
+ ky.add_argument("--project", help="project ID (default: .imprint/config.json)")
2190
+ ky.add_argument("--label", help="request: a name for this device, shown to whoever "
2191
+ "approves (default: the computer's name)")
2192
+ ky.add_argument("--yes", action="store_true", help="approve, retire: do not ask")
2193
+ ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2194
+ ky.set_defaults(func=cmd_key)
2195
+
1896
2196
  pj = sub.add_parser("project", help="the project's display name: rename")
1897
2197
  pj.add_argument("action", choices=["rename"])
1898
2198
  pj.add_argument("name", help="the new name (1-100 characters)")
@@ -92,6 +92,12 @@ def load_session(url: str) -> dict | None:
92
92
  return s if s.get("expires_at", "") > now else None
93
93
 
94
94
 
95
+ def session_expired(url: str) -> bool:
96
+ """True when `imprint login` once signed in to this server and that session has ended."""
97
+ s = load_user_config().get("session") or {}
98
+ return bool(s.get("token")) and s.get("url") == url.rstrip("/") and load_session(url) is None
99
+
100
+
95
101
  LOOPBACK = {"localhost", "127.0.0.1", "::1"}
96
102
 
97
103
 
File without changes
File without changes