codeimprint 0.5.0a13__tar.gz → 0.5.0a14__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 (24) hide show
  1. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/CHANGELOG.md +29 -0
  2. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/PKG-INFO +1 -1
  3. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/pyproject.toml +1 -1
  4. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/__init__.py +1 -1
  5. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/api.py +10 -0
  6. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/chainseal.py +10 -0
  7. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/cli.py +137 -13
  8. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/config.py +6 -0
  9. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/.gitignore +0 -0
  10. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/LICENSE +0 -0
  11. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/NOTICE +0 -0
  12. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/README.pypi.md +0 -0
  13. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/__main__.py +0 -0
  14. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/gitrepo.py +0 -0
  15. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/imprint_file.py +0 -0
  16. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/linecount.py +0 -0
  17. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/ownership.py +0 -0
  18. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/project.py +0 -0
  19. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/receipt.py +0 -0
  20. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/records.py +0 -0
  21. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/timestamp.py +0 -0
  22. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/transparency.py +0 -0
  23. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/trust.py +0 -0
  24. {codeimprint-0.5.0a13 → codeimprint-0.5.0a14}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a14 — Sign-in works for sealing; clearer messages for clones [CIM-BE-29-v2]
4
+
5
+ For engine 0.7.0a19. Older engines still work.
6
+
7
+ - **Fixed: `imprint init`, `seal` and `check` use your `imprint login` session.** Before,
8
+ they sent only an API token, so on a server that requires an account they failed with
9
+ `401 login_required` right after a successful login.
10
+ - An API token (`CODEIMPRINT_TOKEN`, or saved with `imprint login --api-token`) still wins.
11
+ - An ended session says so: "your sign-in to <server> has expired: run `imprint login`
12
+ again". Not signed in at all says to run `imprint login`.
13
+ - The Git hook uses the session too.
14
+ - **Before anything is uploaded**, a project seal checks that your account may use the
15
+ project and that this machine's key is one of its keys. It proves the key to the server
16
+ for this session (`POST /api/v1/projects/{id}/access`).
17
+ - **Clearer messages:**
18
+ - The project's key is not on this machine: copy `developer-key.pem` from the machine
19
+ that has it, or set `CODEIMPRINT_DEVELOPER_KEY`. It no longer says "run `imprint init`",
20
+ which made a second key the project does not accept.
21
+ - This machine's key is not one of the project's keys: the message names the keys the
22
+ project has, and nothing is uploaded.
23
+ - `.imprint/` came with a repository you cloned and names a project your account is not
24
+ part of: `seal` and `init` stop and name `imprint init --new-project`.
25
+ - **New: `imprint init --new-project`** makes a project of your own in such a folder. It
26
+ moves the other project's seal files to `.imprint/origin/` and records `cloned_from` in
27
+ `.imprint/config.json`.
28
+ - A zip seal is "already sealed" only for your own earlier seal (engine 0.7.0a19).
29
+ - GitHub Actions: all of these stay warnings, never a failed build.
30
+ - Tests: `tests/test_phase0.py`.
31
+
3
32
  ## 0.5.0a13 — The old brand name is gone [CIM-BE-26-v1]
4
33
 
5
34
  - **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.0a14
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.0a13"
9
+ version = "0.5.0a14"
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.0a13"
8
+ __version__ = "0.5.0a14"
@@ -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,13 @@ 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
+
162
172
  def plan(self, project: str, payload: dict) -> dict:
163
173
  return self._json("POST", f"/api/v1/projects/{quote(project)}/seal/plan", payload)
164
174
 
@@ -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,15 @@ def public_key(key) -> str:
33
34
  return trust.b64e(trust.public_raw(key))
34
35
 
35
36
 
37
+ def access_proof(key, project: str, token: str | None) -> tuple[str, str]:
38
+ """(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()
42
+ return public_key(key), sign(key, {"type": "codeimprint.project-access.v1",
43
+ "project": project, "session": session})
44
+
45
+
36
46
  def create_project(client, key, name: str | None = None) -> dict:
37
47
  """Create a project for this developer key and finalise its genesis seal (an empty tree).
38
48
  ``name`` is the project's display name (shown on its public page)."""
@@ -171,13 +171,88 @@ 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, ask its owner to add "
213
+ f"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)}). 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.")
181
256
 
182
257
 
183
258
  def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool) -> bytes:
@@ -302,6 +377,8 @@ def cmd_init(args) -> int:
302
377
  raise Abort(f"no such folder: {root}")
303
378
  cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
304
379
  existing = project.load_config(root)
380
+ if getattr(args, "new_project", False) and existing.get("project_id"):
381
+ existing = _leave_project(root, cfg_path, existing)
305
382
  cfg = {"version": 1, "exclude": existing.get("exclude", project.DEFAULT_EXCLUDE),
306
383
  "fail_above": existing.get("fail_above", DEFAULT_FAIL_ABOVE),
307
384
  "reference": existing.get("reference")}
@@ -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
+ path = trust.developer_key_path()
1391
+ raise SealFailed(
1392
+ "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.")
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"):
@@ -1688,7 +1809,7 @@ def cmd_check(args) -> int:
1688
1809
  return 0
1689
1810
  except ApiError as exc:
1690
1811
  if exc.status in {401, 403, 429} or exc.status >= 500:
1691
- _warn(f"check skipped — {exc}")
1812
+ _warn(_explain(client, exc, "check skipped"))
1692
1813
  return 0
1693
1814
  raise Abort(f"check failed: {exc}") from exc
1694
1815
  if args.output:
@@ -1891,6 +2012,9 @@ def build_parser() -> argparse.ArgumentParser:
1891
2012
  help="do not create the project and its genesis seal now")
1892
2013
  n.add_argument("--name", help="the project's display name (default: owner/repo from the "
1893
2014
  "origin remote, else the folder's name); public")
2015
+ n.add_argument("--new-project", action="store_true",
2016
+ help="this folder came with another project's .imprint/ (a clone): make a "
2017
+ "project of your own for it")
1894
2018
  n.set_defaults(func=cmd_init)
1895
2019
 
1896
2020
  pj = sub.add_parser("project", help="the project's display name: rename")
@@ -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