codeimprint 0.5.0a16__tar.gz → 0.5.0a18__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.0a16 → codeimprint-0.5.0a18}/CHANGELOG.md +43 -0
  2. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/PKG-INFO +1 -1
  3. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/pyproject.toml +1 -1
  4. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/__init__.py +1 -1
  5. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/api.py +8 -0
  6. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/chainseal.py +5 -0
  7. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/cli.py +116 -3
  8. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/gitrepo.py +19 -0
  9. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/receipt.py +6 -0
  10. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/.gitignore +0 -0
  11. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/LICENSE +0 -0
  12. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/NOTICE +0 -0
  13. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/README.pypi.md +0 -0
  14. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint/__init__.py +0 -0
  15. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint/__main__.py +0 -0
  16. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/__main__.py +0 -0
  17. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/config.py +0 -0
  18. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/imprint_file.py +0 -0
  19. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/linecount.py +0 -0
  20. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/ownership.py +0 -0
  21. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/project.py +0 -0
  22. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a16 → codeimprint-0.5.0a18}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a18 — Seals send recent commit IDs for clone detection [CIM-BE-33-v1]
4
+
5
+ For engine 0.7.0a22. Older engines still work: they ignore the two new fields.
6
+
7
+ - **Changed: what `imprint seal` sends in a Git repository.** Besides the commit and its
8
+ parents, each seal now sends the IDs of up to 50 first-parent ancestor commits and of
9
+ the repository's root commits. **IDs only**: no commit messages, authors, dates or
10
+ paths.
11
+ - The server (engine 0.7.0a22) keeps them as keyed hashes and uses them to find projects
12
+ that share sealed commits (clone detection). It does that later, in batches, so a seal
13
+ is exactly as fast as before and its output is unchanged.
14
+ - A shallow clone (for example `actions/checkout` with its default depth) sends no
15
+ roots, because its oldest commits are cut-off points.
16
+ - If Git cannot list the history, the seal goes ahead without the two fields.
17
+ - No new command and no new output.
18
+ - Tests: `tests/test_ancestors.py`.
19
+
20
+ ## 0.5.0a17 — `imprint init --new-project` declares a private link to the origin [CIM-BE-32-v1]
21
+
22
+ For engine 0.7.0a21. Older engines still work: the project is made and the link is skipped
23
+ with a warning.
24
+
25
+ - **Changed: `imprint init --new-project`** (in a folder that came with someone else's
26
+ project in `.imprint/`) now also **declares where the code came from**. After the new
27
+ project and its genesis seal exist, this device's key signs a lineage record (`LIN1`,
28
+ relation `clone`) that links the new project to the origin project and to the origin's
29
+ latest seal found in `.imprint/` (none, if there is no seal file).
30
+ - It prints the new project ID, `Lineage linked to its origin (private): LIN1-…` and
31
+ how to see the record (`imprint lineage show`).
32
+ - The public record holds a salted commitment, never the origin. The salt is not written
33
+ to the folder; the server keeps the opening and gives it back to you.
34
+ - `.imprint/config.json` keeps `cloned_from: {project, seal, link}`. Note that this file
35
+ is normally committed, so your repository itself says where the code came from.
36
+ - If the link cannot be declared (an older server, no network), `init` warns and
37
+ finishes; run `imprint init` again to declare it.
38
+ - **New refusal: the origin is already your own project.** When your account is part of
39
+ the project in `.imprint/`, or this device's key is one of its keys, `--new-project`
40
+ stops before changing anything: the same repository on another device is the same
41
+ project. It says to run `imprint key request` (and `imprint key approve` on a device
42
+ that already seals it).
43
+ - New API call used: `POST /api/v1/projects/{id}/lineage`.
44
+ - Tests: `tests/test_declared_link.py`.
45
+
3
46
  ## 0.5.0a16 — Lineage records (LIN1) verify offline [CIM-BE-31-v1]
4
47
 
5
48
  For engine 0.7.0a21. Older engines still work; they have no lineage records.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a16
3
+ Version: 0.5.0a18
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.0a16"
9
+ version = "0.5.0a18"
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.0a16"
8
+ __version__ = "0.5.0a18"
@@ -180,6 +180,14 @@ class Client:
180
180
  the opening of its commitment (engine 0.7.0a21+)."""
181
181
  return self._json("GET", f"/api/v1/lineage/{quote(record_id)}")
182
182
 
183
+ def declare_lineage(self, project: str, document: dict, signatures: list[dict],
184
+ opening: dict) -> dict:
185
+ """Declare that this project is a clone of another (a LIN1 record, engine
186
+ 0.7.0a21+). The opening names the origin; it is stored encrypted, never logged."""
187
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/lineage",
188
+ {"document": document, "signatures": signatures,
189
+ "opening": opening})
190
+
183
191
  def key_requests(self, project: str) -> dict:
184
192
  return self._json("GET", f"/api/v1/projects/{quote(project)}/keys/requests")
185
193
 
@@ -110,6 +110,11 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
110
110
  else:
111
111
  body.update(tree=info["tree"], commit=commit, parents=info["parents"],
112
112
  ref=info["ref"], kind=kind, exclude=list(exclude or []), lines=lines)
113
+ try: # commit IDs only (engine 0.7.0a22+ keeps them keyed)
114
+ body.update(ancestors=gitrepo.ancestors(top, commit),
115
+ roots=gitrepo.roots(top, commit))
116
+ except gitrepo.GitError:
117
+ pass # the seal does not depend on them
113
118
  if kind == "release" and tag:
114
119
  body.update(tag=tag, public_tag=public_tag)
115
120
  resp = client.plan(project, body)
@@ -8,6 +8,7 @@ import getpass
8
8
  import hashlib
9
9
  import json
10
10
  import os
11
+ import secrets
11
12
  import sys
12
13
  import time
13
14
  import webbrowser
@@ -377,6 +378,7 @@ def cmd_init(args) -> int:
377
378
  cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
378
379
  existing = project.load_config(root)
379
380
  if getattr(args, "new_project", False) and existing.get("project_id"):
381
+ _refuse_own_origin(args, existing["project_id"]) # before anything is changed
380
382
  existing = _leave_project(root, cfg_path, existing)
381
383
  cfg = {"version": 1, "exclude": existing.get("exclude", project.DEFAULT_EXCLUDE),
382
384
  "fail_above": existing.get("fail_above", DEFAULT_FAIL_ABOVE),
@@ -432,6 +434,104 @@ def cmd_init(args) -> int:
432
434
  return 0
433
435
 
434
436
 
437
+ def _refuse_own_origin(args, origin: str) -> None:
438
+ """`imprint init --new-project` is for code that came from someone else's project. When
439
+ the project this folder names is the caller's own, this is the same repository on
440
+ another device: the same project, joined with `imprint key request`."""
441
+ settings = config.resolve(getattr(args, "url", None))
442
+ if not settings.url:
443
+ return # no server to ask; nothing is created either
444
+ client = _signed_in(settings.url, settings.token)
445
+ key = trust.load_developer_key()
446
+ fp = trust.fingerprint(trust.public_raw(key)) if key is not None else None
447
+ why = None
448
+ try:
449
+ keys = client.public_project(origin).get("keys") or []
450
+ except (ApiError, NetworkError):
451
+ keys = []
452
+ if fp and fp in [k["fingerprint"] for k in keys if not k.get("valid_until")]:
453
+ why = f"this machine's developer key {fp} is one of its keys"
454
+ elif client.auth != "token": # an API token is the operator, not an owner
455
+ try:
456
+ if _project_state(client, origin, key) == "ok":
457
+ why = "your account is part of it"
458
+ except ApiError as exc:
459
+ raise Abort(_explain(client, exc, "could not check the project this folder "
460
+ "came with") + ". Nothing was changed.") from exc
461
+ if why:
462
+ raise Abort(
463
+ f"project {origin} is already yours: {why}. The same repository on another "
464
+ "device is the same project, so no new project was made and nothing was "
465
+ "changed. To seal from this device, run `imprint key request` here and "
466
+ "`imprint key approve` on a device that already seals the project; if this "
467
+ "device already has one of its keys, just run `imprint seal`.")
468
+
469
+
470
+ def _origin_seal(root: Path, origin: str) -> str | None:
471
+ """The latest seal of the origin project among the receipts that came with the code
472
+ (.imprint/origin/ after `--new-project`), by log position; None when there is none."""
473
+ folder = root / project.CONFIG_DIR
474
+ best: tuple[int, str] | None = None
475
+ for path in [*folder.glob("origin/*.receipt.json"), *folder.glob("*.receipt.json")]:
476
+ try:
477
+ rec = json.loads(path.read_text(encoding="utf-8"))
478
+ found = (int(rec["log"]["index"]), imprint_file.clean_id(rec["imprint_id"]))
479
+ named = (rec.get("chain") or {}).get("project")
480
+ except (OSError, ValueError, KeyError, TypeError, AttributeError):
481
+ continue
482
+ if named == origin and imprint_file.is_valid_id(found[1]) and (
483
+ best is None or found > best):
484
+ best = found
485
+ return best[1] if best else None
486
+
487
+
488
+ def _declare_origin(client: Client, root: Path, cfg_path: Path, key, child: str,
489
+ child_seal: str) -> None:
490
+ """A project made with `imprint init --new-project` says where its code came from: a
491
+ lineage record (LIN1) signed by this project's key. The public record holds a salted
492
+ commitment, never the origin; the server keeps the opening encrypted. Never in the way
493
+ of init: a failure is a warning, and `imprint init` again declares the link."""
494
+ current = project.load_config(root)
495
+ came = current.get("cloned_from") or {}
496
+ origin = came.get("project")
497
+ if not origin or came.get("link") or origin == child:
498
+ return
499
+ from . import records
500
+
501
+ seal, salt = _origin_seal(root, origin), secrets.token_hex(32)
502
+ document = {"type": receipt.LINEAGE, "basis": "declared", "relation": "clone",
503
+ "child": child, "child_seal": child_seal, "signals": ["S1"],
504
+ "parent_commitment": receipt.parent_commitment(salt, origin, seal),
505
+ "declared_at": _now_iso()}
506
+ digest = hashlib.sha256(imprint_file.canonical(document)).hexdigest()
507
+ signature = {"role": "child", "public_key": chainseal.public_key(key),
508
+ "signature": chainseal.sign(key, records.sign_statement(document["type"],
509
+ digest))}
510
+ try:
511
+ made = client.declare_lineage(child, document, [signature],
512
+ {"project": origin, "seal": seal, "salt": salt})
513
+ except (ApiError, NetworkError) as exc:
514
+ _warn(_explain(client, exc, "the link to this code's origin was not declared")
515
+ + ". Run `imprint init` again to declare it (the server needs lineage "
516
+ "records, engine 0.7.0a21 or later).")
517
+ return
518
+ link = made.get("record")
519
+ if link != imprint_file.record_id("LIN1", digest):
520
+ _warn(f"the server answered with another record ({link}) than the link this key "
521
+ "signed; it was not noted in .imprint/config.json")
522
+ return
523
+ current["cloned_from"] = {"project": origin, "seal": seal, "link": link}
524
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
525
+ _say(f"Lineage linked to its origin (private): {link}",
526
+ f" Origin: project {origin}, "
527
+ + (f"its latest seal here {seal}" if seal else "no seal of it in .imprint/")
528
+ + ". Signed by this project's key.",
529
+ " The public record holds a commitment, never the origin. Both sides are shown "
530
+ "only to an",
531
+ " account that is part of both projects. A link does not say who wrote the code.",
532
+ f" See it: imprint lineage show {link}")
533
+
534
+
435
535
  def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
436
536
  """`imprint init --new-project`: stop pointing at the project this folder came with. Its
437
537
  seal files move to .imprint/origin/ (they belong to that project) and the config keeps
@@ -446,7 +546,7 @@ def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
446
546
  moved.append(path.name)
447
547
  kept = {k: v for k, v in existing.items()
448
548
  if k not in ("project_id", "developer", "cloned_from")}
449
- kept["cloned_from"] = {"project": existing["project_id"]}
549
+ kept["cloned_from"] = {"project": existing["project_id"]} # the link: _declare_origin
450
550
  cfg_path.write_text(json.dumps(kept, indent=2) + "\n", encoding="utf-8")
451
551
  _say(f"Leaving project {existing['project_id']} (kept as cloned_from in "
452
552
  ".imprint/config.json)")
@@ -482,6 +582,16 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
482
582
  if getattr(args, "name", None) and settings.url:
483
583
  _rename(_signed_in(settings.url, settings.token), current["project_id"], key,
484
584
  args.name, True)
585
+ came = current.get("cloned_from") or {}
586
+ if settings.url and came.get("project") and not came.get("link"):
587
+ try: # a link that could not be declared before
588
+ genesis = json.loads((root / project.CONFIG_DIR / "genesis.receipt.json")
589
+ .read_text(encoding="utf-8"))["imprint_id"]
590
+ except (OSError, ValueError, KeyError, TypeError):
591
+ genesis = None
592
+ if genesis:
593
+ _declare_origin(_signed_in(settings.url, settings.token), root, cfg_path, key,
594
+ current["project_id"], genesis)
485
595
  return
486
596
  if not settings.url:
487
597
  _say("", "No server configured: run `imprint login`, then `imprint init` again to "
@@ -511,6 +621,7 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
511
621
  f"Genesis {g['id']}, sealed {g['receipt']['attestation']['statement']['attested_at']} "
512
622
  f"(log entry #{g['receipt']['log']['index']}): the project's chain starts here",
513
623
  "Saved .imprint/genesis.imprint and .imprint/genesis.receipt.json (commit them)")
624
+ _declare_origin(client, root, cfg_path, key, made["project_id"], g["id"])
514
625
 
515
626
 
516
627
  def _rename(client: Client, project_id: str, key, name: str, public: bool) -> dict:
@@ -2261,8 +2372,10 @@ def build_parser() -> argparse.ArgumentParser:
2261
2372
  n.add_argument("--name", help="the project's display name (default: owner/repo from the "
2262
2373
  "origin remote, else the folder's name); public")
2263
2374
  n.add_argument("--new-project", action="store_true",
2264
- help="this folder came with another project's .imprint/ (a clone): make a "
2265
- "project of your own for it")
2375
+ help="this folder came with someone else's project in .imprint/ (a clone): "
2376
+ "make a project of your own for it and declare a private link to its "
2377
+ "origin (a LIN1 record). Refused when that project is already yours: "
2378
+ "then use `imprint key request`")
2266
2379
  n.set_defaults(func=cmd_init)
2267
2380
 
2268
2381
  ky = sub.add_parser("key", help="the project's keys: add another device (request, then "
@@ -102,6 +102,25 @@ def commit_info(root: Path, commit: str) -> dict:
102
102
  return {"commit": commit, "tree": tree, "parents": line[1:], "ref": ref or None}
103
103
 
104
104
 
105
+ ANCESTORS = 50 # first-parent ancestors sent with a seal
106
+ ROOTS = 20
107
+
108
+
109
+ def ancestors(root: Path, commit: str, limit: int = ANCESTORS) -> list[str]:
110
+ """Up to ``limit`` first-parent ancestors of a commit, nearest first."""
111
+ listed = _git(root, "rev-list", "--first-parent", f"--max-count={limit + 1}",
112
+ commit).decode().split()
113
+ return listed[1:]
114
+
115
+
116
+ def roots(root: Path, commit: str, limit: int = ROOTS) -> list[str]:
117
+ """The root commits of a commit's history. None for a shallow clone: there the oldest
118
+ commits present are cut-off points, not roots."""
119
+ if _git(root, "rev-parse", "--is-shallow-repository").strip() == b"true":
120
+ return []
121
+ return _git(root, "rev-list", "--max-parents=0", commit).decode().split()[:limit]
122
+
123
+
105
124
  def tags_at(root: Path, commit: str) -> list[str]:
106
125
  """Tags pointing at a commit, sorted (``git tag --points-at``)."""
107
126
  return sorted(_git(root, "tag", "--points-at", commit).decode().split())
@@ -100,6 +100,12 @@ def _hex64(value) -> bool:
100
100
  "0123456789abcdef")
101
101
 
102
102
 
103
+ def parent_commitment(salt: str, project: str, seal: str | None) -> str:
104
+ """What a declared lineage record publishes in place of its origin."""
105
+ return hashlib.sha256(canonical({"salt": salt, "project": project,
106
+ "seal": seal})).hexdigest()
107
+
108
+
103
109
  def is_lineage(receipt: dict) -> bool:
104
110
  return ((receipt or {}).get("record") or {}).get("type") == LINEAGE
105
111
 
File without changes
File without changes