codeimprint 0.5.0a18__tar.gz → 0.5.0a19__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.0a18 → codeimprint-0.5.0a19}/CHANGELOG.md +45 -0
  2. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/PKG-INFO +1 -1
  3. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/pyproject.toml +1 -1
  4. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/__init__.py +1 -1
  5. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/api.py +22 -2
  6. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/chainseal.py +35 -4
  7. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/cli.py +278 -47
  8. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/gitrepo.py +52 -0
  9. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/.gitignore +0 -0
  10. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/LICENSE +0 -0
  11. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/NOTICE +0 -0
  12. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/README.pypi.md +0 -0
  13. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint/__init__.py +0 -0
  14. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint/__main__.py +0 -0
  15. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/__main__.py +0 -0
  16. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/config.py +0 -0
  17. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/imprint_file.py +0 -0
  18. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/linecount.py +0 -0
  19. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/ownership.py +0 -0
  20. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/project.py +0 -0
  21. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/receipt.py +0 -0
  22. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a18 → codeimprint-0.5.0a19}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,50 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a19 — A different repository needs its own seal [CIM-BE-34-v1]
4
+
5
+ For engine 0.7.0a23. Older engines still work: they ignore the new field, and the checks
6
+ that need the server are skipped.
7
+
8
+ The same repository on any device is the same project. A different repository (a copy, a
9
+ fork, a template) is a different project: it is never created or sealed for you, you run
10
+ `imprint init` in it.
11
+
12
+ - **New: every Git seal and `imprint init` send which repository this is.** The provider's
13
+ repository ID in GitHub Actions and GitLab CI, else the `origin` remote as `host/path`
14
+ (scheme, credentials and port dropped), and the folder inside the repository. The server
15
+ keeps keyed hashes. `.imprint/config.json` keeps hashes too (`homes`), never the address;
16
+ the first seal of an existing project adds them ("Noted this repository…": commit it).
17
+ - **Changed: `imprint seal` in a repository that is not the project's is refused**, for
18
+ anyone, and nothing changes: "This repository is not the one this project belongs to. Run
19
+ `imprint init` to seal it as its own project." In GitHub Actions it is a warning and the
20
+ build goes on. A device that holds a project key is also told about `imprint project
21
+ move`, for a repository that was only renamed or moved.
22
+ - **Changed: `imprint init` in such a repository makes a stand-alone project** (this
23
+ device's key, a genesis seal, `.imprint/` rewritten, the other project's seal files moved
24
+ to `.imprint/origin/`). It no longer needs `--new-project`, keeps nothing about the other
25
+ project and declares **no link**.
26
+ - **New: `--link-origin`** adds the private link to the project the code came from (the
27
+ `LIN1` record that 0.5.0a17 declared by default). It also works later, on the project
28
+ that already exists.
29
+ - `--new-project` still works: it asks for the stand-alone project where the repository
30
+ cannot be told apart (no remote, or a `.imprint/` from before this version). It is
31
+ refused for your own project in the same repository, as before.
32
+ - **New: `imprint init` on another device of the same repository creates nothing.** When
33
+ your account already has a project for this repository, the config is restored for it
34
+ and you are pointed to `imprint key request`.
35
+ - **New: `imprint project move`** records that the project's repository was renamed,
36
+ transferred or moved to another host (signed by a project key). Not needed where a build
37
+ knows the repository's ID.
38
+ - **Changed: `imprint verify`** in a repository that the seal's project does not live in
39
+ still reports the seal, and adds "Not issued for this repository. Seal this repository
40
+ with `imprint init`." (a warning: `--strict` fails on it). It does not name the project or
41
+ repository the seal belongs to. `--json` gains `issued_for_this_repository`
42
+ (`true`, `false` or `null` when it cannot be told). A seal that belongs to another project
43
+ is no longer checked against this folder's developer key.
44
+ - New API calls used: `POST /api/v1/projects/{id}/home/check`, `POST /api/v1/projects/{id}/home`,
45
+ `POST /api/v1/repository/projects`; `repository` in `seal/plan` and `POST /api/v1/projects`.
46
+ - Tests: `tests/test_repository.py`.
47
+
3
48
  ## 0.5.0a18 — Seals send recent commit IDs for clone detection [CIM-BE-33-v1]
4
49
 
5
50
  For engine 0.7.0a22. Older engines still work: they ignore the two new fields.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a18
3
+ Version: 0.5.0a19
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.0a18"
9
+ version = "0.5.0a19"
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.0a18"
8
+ __version__ = "0.5.0a19"
@@ -136,10 +136,30 @@ class Client:
136
136
  return self._request(method, path, body, "application/json" if body else None)
137
137
 
138
138
  # Git-aware sealing: projects, plan -> blobs -> prepare -> finalise ------------------
139
- def create_project(self, public_key: str, signature: str, name: str | None = None) -> dict:
139
+ def create_project(self, public_key: str, signature: str, name: str | None = None,
140
+ repository: dict | None = None) -> dict:
140
141
  return self._json("POST", "/api/v1/projects",
141
142
  {"public_key": public_key, "signature": signature,
142
- **({"name": name} if name else {})})
143
+ **({"name": name} if name else {}),
144
+ **({"repository": repository} if repository else {})})
145
+
146
+ # repository identity (engine 0.7.0a23+): a project's homes ------------------------------
147
+ def project_home_check(self, project: str, repository: dict) -> dict:
148
+ """{home: same | unset | unknown | different, settled} for the project's own
149
+ accounts; the 404 of an unknown project for everyone else."""
150
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/home/check",
151
+ {"repository": repository})
152
+
153
+ def project_move(self, project: str, repository: dict, public_key: str,
154
+ signature: str) -> dict:
155
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/home",
156
+ {"repository": repository, "public_key": public_key,
157
+ "signature": signature})
158
+
159
+ def own_projects_here(self, repository: dict) -> list[str]:
160
+ """This account's own projects that live in this repository."""
161
+ return self._json("POST", "/api/v1/repository/projects",
162
+ {"repository": repository}).get("projects") or []
143
163
 
144
164
  def rename_project(self, project: str, name: str, public: bool, public_key: str,
145
165
  signature: str) -> dict:
@@ -61,12 +61,41 @@ def key_change(key, project: str, action: str, target_public_key: str) -> tuple[
61
61
  "action": action, "public_key": target_public_key})
62
62
 
63
63
 
64
- def create_project(client, key, name: str | None = None) -> dict:
64
+ def home_hashes(project: str, repository: dict | None) -> list[str]:
65
+ """What `.imprint/config.json` keeps about the repository a project lives in: hashes,
66
+ so that a copy of the folder in another repository can be told apart without the
67
+ server and without the file naming the repository."""
68
+ import hashlib
69
+
70
+ from .imprint_file import canonical
71
+
72
+ if not repository:
73
+ return []
74
+ folder, out = repository.get("folder") or "", []
75
+ for kind, value in (("id", f"{repository.get('provider')}:{repository.get('id')}"
76
+ if repository.get("provider") and repository.get("id") else None),
77
+ ("url", repository.get("url"))):
78
+ if value:
79
+ out.append(hashlib.sha256(canonical(
80
+ {"type": "codeimprint.home.v1", "project": project, "kind": kind,
81
+ "value": value, "folder": folder})).hexdigest())
82
+ return out
83
+
84
+
85
+ def move_proof(key, project: str, repository: dict) -> tuple[str, str]:
86
+ """(public key, signature): this project key says the project now also lives here."""
87
+ return public_key(key), sign(key, {"type": "codeimprint.project-home.v1",
88
+ "project": project, "repository": repository})
89
+
90
+
91
+ def create_project(client, key, name: str | None = None,
92
+ repository: dict | None = None) -> dict:
65
93
  """Create a project for this developer key and finalise its genesis seal (an empty tree).
66
- ``name`` is the project's display name (shown on its public page)."""
94
+ ``name`` is the project's display name (shown on its public page); ``repository`` is
95
+ the repository it is created in, which becomes its home."""
67
96
  pub = public_key(key)
68
97
  made = client.create_project(pub, sign(key, {"type": "codeimprint.project-create.v1",
69
- "public_key": pub}), name)
98
+ "public_key": pub}), name, repository)
70
99
  g = made["genesis"]
71
100
  genesis = client.finalise(made["project_id"], g["pending_id"], pub,
72
101
  sign(key, g["statement"]))
@@ -87,7 +116,7 @@ def _wait(client, job_id: str) -> dict:
87
116
 
88
117
  def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
89
118
  exclude: list[str] | None = None, confirm=None, tag: str | None = None,
90
- public_tag: bool = False) -> dict:
119
+ public_tag: bool = False, repository: dict | None = None) -> dict:
91
120
  """Seal one commit. Returns {already: ID}, {already, released: REL ID}, {release: result}
92
121
  or {result, uploaded, upload_bytes, files}.
93
122
 
@@ -110,6 +139,8 @@ def seal_commit(client, root: Path, project: str, commit: str, kind: str, key,
110
139
  else:
111
140
  body.update(tree=info["tree"], commit=commit, parents=info["parents"],
112
141
  ref=info["ref"], kind=kind, exclude=list(exclude or []), lines=lines)
142
+ if repository: # which repository this is (engine 0.7.0a23+)
143
+ body["repository"] = repository
113
144
  try: # commit IDs only (engine 0.7.0a22+ keeps them keyed)
114
145
  body.update(ancestors=gitrepo.ancestors(top, commit),
115
146
  roots=gitrepo.roots(top, commit))
@@ -214,6 +214,61 @@ def _not_your_project(client: Client, project_id: str, key) -> str:
214
214
  f"request`: its owner sees the request and can add your developer key{mine}.")
215
215
 
216
216
 
217
+ NOT_THIS_REPOSITORY = ("This repository is not the one this project belongs to. Run `imprint "
218
+ "init` to seal it as its own project.")
219
+ MOVE_HINT = (" If this is the same repository at a new address (it was renamed or moved), run "
220
+ "`imprint project move` instead.")
221
+ NOT_ISSUED = "Not issued for this repository. Seal this repository with `imprint init`."
222
+
223
+
224
+ def _identity(root: Path | None) -> dict | None:
225
+ """Which repository this folder is in; None when it is not a Git repository or has
226
+ neither a remote nor a provider ID."""
227
+ try:
228
+ return gitrepo.identity(root) if root is not None and gitrepo.is_repo(root) else None
229
+ except gitrepo.GitError:
230
+ return None
231
+
232
+
233
+ def _local_place(cfg: dict, ident: dict | None) -> str:
234
+ """From `.imprint/config.json` alone: is this the repository the project was noted in?
235
+ "same", "different", or "unknown" (nothing noted, or no identity here)."""
236
+ noted = cfg.get("homes")
237
+ if not ident or not noted or not cfg.get("project_id"):
238
+ return "unknown"
239
+ mine = chainseal.home_hashes(cfg["project_id"], ident)
240
+ return "same" if set(mine) & set(noted) else "different"
241
+
242
+
243
+ def _server_place(client: Client, project_id: str, ident: dict | None) -> tuple[str, bool]:
244
+ """Ask the server, which answers the project's own accounts only: ("same" | "different"
245
+ | "unknown", settled). Unknown for an engine before 0.7.0a23 or when there is no answer."""
246
+ if not ident:
247
+ return "unknown", False
248
+ try:
249
+ out = client.project_home_check(project_id, ident)
250
+ except (ApiError, NetworkError):
251
+ return "unknown", False
252
+ home = out.get("home")
253
+ return ("same" if home in ("same", "unset") else "different" if home == "different"
254
+ else "unknown"), bool(out.get("settled"))
255
+
256
+
257
+ def _note_home(root: Path, ident: dict | None) -> bool:
258
+ """Keep this repository's hashes in `.imprint/config.json`, so that a copy of the folder
259
+ in another repository can be told apart (chainseal.home_hashes). True when it changed."""
260
+ cfg = project.load_config(root)
261
+ if not ident or not cfg.get("project_id"):
262
+ return False
263
+ mine, noted = chainseal.home_hashes(cfg["project_id"], ident), cfg.get("homes") or []
264
+ if set(mine) <= set(noted):
265
+ return False
266
+ cfg["homes"] = noted + [h for h in mine if h not in noted]
267
+ (root / project.CONFIG_DIR / project.CONFIG_FILE).write_text(
268
+ json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
269
+ return True
270
+
271
+
217
272
  def _project_state(client: Client, project_id: str, key) -> str:
218
273
  """"ok" when this caller may use the project, "not-yours" when the server says it does
219
274
  not exist for them, else "unknown" (an engine before 0.7.0a19, or no answer)."""
@@ -232,27 +287,57 @@ def _project_state(client: Client, project_id: str, key) -> str:
232
287
  return "ok"
233
288
 
234
289
 
235
- def _project_ready(client: Client, project_id: str, key) -> None:
236
- """Before anything is uploaded: this account may use the project, and this machine's key
237
- is one of the project's keys."""
290
+ def _project_ready(client: Client, project_id: str, key, root: Path | None = None):
291
+ """Before anything is uploaded: this account may use the project, this repository is the
292
+ one the project lives in (a different repository is a different project, made with
293
+ `imprint init`), and this machine's key is one of the project's keys. Returns the
294
+ repository identity to send with the seal."""
295
+ ident = _identity(root)
296
+ cfg = project.load_config(root) if root is not None and root.is_dir() else {}
238
297
  try:
239
298
  state = _project_state(client, project_id, key)
240
299
  except ApiError as exc:
241
300
  raise SealFailed(_explain(client, exc, "sealing failed")) from exc
242
301
  if state == "not-yours":
302
+ if _local_place(cfg, ident) == "different":
303
+ raise SealFailed(NOT_THIS_REPOSITORY)
243
304
  raise SealFailed(_not_your_project(client, project_id, key))
244
305
  try:
245
306
  keys = client.public_project(project_id).get("keys") or []
246
307
  except (ApiError, NetworkError):
247
- return
248
- active = [k["fingerprint"] for k in keys if not k.get("valid_until")]
308
+ keys = None
309
+ active = [k["fingerprint"] for k in keys or [] if not k.get("valid_until")]
249
310
  fp = trust.fingerprint(trust.public_raw(key))
311
+ if state == "ok":
312
+ place, settled = _server_place(client, project_id, ident)
313
+ if place == "different":
314
+ raise SealFailed(NOT_THIS_REPOSITORY
315
+ + (MOVE_HINT if fp in active and not settled else ""))
316
+ if keys is None:
317
+ return ident
250
318
  if active and fp not in active:
251
319
  raise SealFailed(
252
320
  f"developer key {fp} on this machine is not a key of project {project_id} (its "
253
321
  f"keys: {', '.join(active)}). Add this device to the project: run `imprint key "
254
322
  f"request` here, then `imprint key approve {fp}` on a device that already seals "
255
323
  "it. Nothing was uploaded.")
324
+ return ident
325
+
326
+
327
+ def _other_repository(client: Client, cfg: dict, root: Path) -> None:
328
+ """For a machine without a developer key: refuse, with the one sentence, when this is not
329
+ the repository the folder's project lives in. Otherwise say nothing (the caller then
330
+ explains how this device gets a key)."""
331
+ ident = _identity(root)
332
+ try:
333
+ state = _project_state(client, cfg["project_id"], None)
334
+ except ApiError:
335
+ return
336
+ if state == "not-yours":
337
+ if _local_place(cfg, ident) == "different":
338
+ raise SealFailed(NOT_THIS_REPOSITORY)
339
+ elif state == "ok" and _server_place(client, cfg["project_id"], ident)[0] == "different":
340
+ raise SealFailed(NOT_THIS_REPOSITORY)
256
341
 
257
342
 
258
343
  def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool) -> bytes:
@@ -377,9 +462,24 @@ def cmd_init(args) -> int:
377
462
  raise Abort(f"no such folder: {root}")
378
463
  cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
379
464
  existing = project.load_config(root)
380
- if getattr(args, "new_project", False) and existing.get("project_id"):
381
- _refuse_own_origin(args, existing["project_id"]) # before anything is changed
382
- existing = _leave_project(root, cfg_path, existing)
465
+ link = getattr(args, "link_origin", False)
466
+ if existing.get("project_id"):
467
+ # A different repository is a different project: `imprint init` there makes a
468
+ # stand-alone one. --new-project asks for that whatever the repository is.
469
+ # --link-origin alone changes no project: it adds the link (see _init_project).
470
+ place, mine = _origin_place(args, root, existing)
471
+ if getattr(args, "new_project", False) or place == "different":
472
+ if mine and place != "different": # before anything is changed
473
+ raise Abort(
474
+ f"project {existing['project_id']} is already yours: {mine}. The same "
475
+ "repository on another device is the same project, so no new project "
476
+ "was made and nothing was changed. To seal from this device, run "
477
+ "`imprint key request` here and `imprint key approve` on a device that "
478
+ "already seals the project; if this device already has one of its keys, "
479
+ "just run `imprint seal`."
480
+ + ("" if place == "same" else " (If this is a different repository, give "
481
+ "it its own `origin` remote first, then run `imprint init`.)"))
482
+ existing = _leave_project(root, cfg_path, existing, link)
383
483
  cfg = {"version": 1, "exclude": existing.get("exclude", project.DEFAULT_EXCLUDE),
384
484
  "fail_above": existing.get("fail_above", DEFAULT_FAIL_ABOVE),
385
485
  "reference": existing.get("reference")}
@@ -434,37 +534,51 @@ def cmd_init(args) -> int:
434
534
  return 0
435
535
 
436
536
 
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`."""
537
+ def _origin_place(args, root: Path, existing: dict) -> tuple[str, str | None]:
538
+ """For `imprint init` in a folder whose config already names a project: is this the
539
+ repository that project lives in ("same", "different" or "unknown"), and why the project
540
+ is the caller's own (None when it is not theirs, or that cannot be told)."""
541
+ origin, ident = existing["project_id"], _identity(root)
542
+ local = _local_place(existing, ident)
441
543
  settings = config.resolve(getattr(args, "url", None))
442
544
  if not settings.url:
443
- return # no server to ask; nothing is created either
545
+ return local, None
444
546
  client = _signed_in(settings.url, settings.token)
445
547
  key = trust.load_developer_key()
446
548
  fp = trust.fingerprint(trust.public_raw(key)) if key is not None else None
447
- why = None
549
+ mine = None
448
550
  try:
449
551
  keys = client.public_project(origin).get("keys") or []
450
552
  except (ApiError, NetworkError):
451
553
  keys = []
452
554
  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"
555
+ mine = f"this machine's developer key {fp} is one of its keys"
454
556
  elif client.auth != "token": # an API token is the operator, not an owner
455
557
  try:
456
558
  if _project_state(client, origin, key) == "ok":
457
- why = "your account is part of it"
559
+ mine = "your account is part of it"
458
560
  except ApiError as exc:
459
561
  raise Abort(_explain(client, exc, "could not check the project this folder "
460
562
  "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`.")
563
+ if not mine:
564
+ return local, None
565
+ place, _settled = _server_place(client, origin, ident)
566
+ return (local if place == "unknown" else place), mine
567
+
568
+
569
+ def _origin_project(root: Path) -> str | None:
570
+ """The project of the seal files that came with the code (.imprint/origin/), by the
571
+ latest of them; None when there are none."""
572
+ best: tuple[int, str] | None = None
573
+ for path in (root / project.CONFIG_DIR).glob("origin/*.receipt.json"):
574
+ try:
575
+ rec = json.loads(path.read_text(encoding="utf-8"))
576
+ found = (int(rec["log"]["index"]), rec["chain"]["project"])
577
+ except (OSError, ValueError, KeyError, TypeError):
578
+ continue
579
+ if isinstance(found[1], str) and (best is None or found > best):
580
+ best = found
581
+ return best[1] if best else None
468
582
 
469
583
 
470
584
  def _origin_seal(root: Path, origin: str) -> str | None:
@@ -532,10 +646,11 @@ def _declare_origin(client: Client, root: Path, cfg_path: Path, key, child: str,
532
646
  f" See it: imprint lineage show {link}")
533
647
 
534
648
 
535
- def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
536
- """`imprint init --new-project`: stop pointing at the project this folder came with. Its
537
- seal files move to .imprint/origin/ (they belong to that project) and the config keeps
538
- only where the code came from."""
649
+ def _leave_project(root: Path, cfg_path: Path, existing: dict, link: bool = False) -> dict:
650
+ """`imprint init` in another repository than the project's: stop pointing at the project
651
+ this folder came with. Its seal files move to .imprint/origin/ (they belong to that
652
+ project). Nothing about that project is kept in the config, unless a link to it was asked
653
+ for (--link-origin)."""
539
654
  folder = root / project.CONFIG_DIR
540
655
  origin = folder / "origin"
541
656
  moved = []
@@ -545,11 +660,12 @@ def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
545
660
  path.replace(origin / path.name)
546
661
  moved.append(path.name)
547
662
  kept = {k: v for k, v in existing.items()
548
- if k not in ("project_id", "developer", "cloned_from")}
549
- kept["cloned_from"] = {"project": existing["project_id"]} # the link: _declare_origin
663
+ if k not in ("project_id", "developer", "cloned_from", "homes")}
664
+ if link:
665
+ kept["cloned_from"] = {"project": existing["project_id"]} # the link: _declare_origin
550
666
  cfg_path.write_text(json.dumps(kept, indent=2) + "\n", encoding="utf-8")
551
- _say(f"Leaving project {existing['project_id']} (kept as cloned_from in "
552
- ".imprint/config.json)")
667
+ _say("Leaving the project this folder came with: this repository gets a project of "
668
+ "its own")
553
669
  if moved:
554
670
  _say(f"Moved {len(moved)} seal file(s) of that project to .imprint/origin/")
555
671
  return kept
@@ -583,8 +699,16 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
583
699
  _rename(_signed_in(settings.url, settings.token), current["project_id"], key,
584
700
  args.name, True)
585
701
  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
702
+ if getattr(args, "link_origin", False) and settings.url and not came.get("link"):
703
+ origin = came.get("project") or _origin_project(root)
704
+ if not origin:
705
+ _warn("--link-origin: nothing in .imprint/origin/ names the project this "
706
+ "code came from, so there is nothing to link to")
707
+ return
708
+ if not came.get("project"):
709
+ current["cloned_from"] = {"project": origin}
710
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
711
+ try: # the link, asked for now or not declared before
588
712
  genesis = json.loads((root / project.CONFIG_DIR / "genesis.receipt.json")
589
713
  .read_text(encoding="utf-8"))["imprint_id"]
590
714
  except (OSError, ValueError, KeyError, TypeError):
@@ -599,8 +723,25 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
599
723
  return
600
724
  client = _signed_in(settings.url, settings.token)
601
725
  name = getattr(args, "name", None) or default_project_name(root)
726
+ ident = _identity(root)
727
+ try: # the same repository on another device is the same project
728
+ own = client.own_projects_here(ident) if ident and client.auth == "session" else []
729
+ except (ApiError, NetworkError):
730
+ own = []
731
+ if own:
732
+ current["project_id"] = own[0]
733
+ cfg_path.parent.mkdir(parents=True, exist_ok=True)
734
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
735
+ _note_home(root, ident)
736
+ _say("", f"Project {own[0]} (yours: this repository already has it, so nothing was "
737
+ "created; .imprint/config.json now names it)",
738
+ " The same repository on another device is the same project. To seal from this "
739
+ "device, run",
740
+ " `imprint key request` here and `imprint key approve` on a device that already "
741
+ "seals it.")
742
+ return
602
743
  try:
603
- made = chainseal.create_project(client, key, name)
744
+ made = chainseal.create_project(client, key, name, ident)
604
745
  except (ApiError, NetworkError) as exc:
605
746
  _warn(_explain(client, exc, "the project was not created")
606
747
  + "; run `imprint init` again afterwards")
@@ -621,7 +762,9 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
621
762
  f"Genesis {g['id']}, sealed {g['receipt']['attestation']['statement']['attested_at']} "
622
763
  f"(log entry #{g['receipt']['log']['index']}): the project's chain starts here",
623
764
  "Saved .imprint/genesis.imprint and .imprint/genesis.receipt.json (commit them)")
624
- _declare_origin(client, root, cfg_path, key, made["project_id"], g["id"])
765
+ _note_home(root, ident)
766
+ if getattr(args, "link_origin", False):
767
+ _declare_origin(client, root, cfg_path, key, made["project_id"], g["id"])
625
768
 
626
769
 
627
770
  def _rename(client: Client, project_id: str, key, name: str, public: bool) -> dict:
@@ -1645,8 +1788,10 @@ def _confirm_upload(args, client: Client):
1645
1788
 
1646
1789
  def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1647
1790
  """Incremental seals of one commit or a range (ADR 0001): only new blobs are sent."""
1791
+ if _developer_key() is None: # no key here yet: say first if this is another
1792
+ _other_repository(client, cfg, root) # repository, where no key would help
1648
1793
  key = _developer_key(required=True, expected=cfg.get("developer"))
1649
- _project_ready(client, cfg["project_id"], key)
1794
+ ident = _project_ready(client, cfg["project_id"], key, root)
1650
1795
  try:
1651
1796
  commits = (gitrepo.commits(root, args.all_commits) if args.all_commits
1652
1797
  else [gitrepo.resolve(root, args.rev)])
@@ -1660,7 +1805,7 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1660
1805
  tag = next(iter(gitrepo.tags_at(root, commit)), None)
1661
1806
  out = chainseal.seal_commit(client, root, cfg["project_id"], commit, args.kind, key,
1662
1807
  cfg.get("exclude"), _confirm_upload(args, client),
1663
- tag=tag, public_tag=args.public_tag)
1808
+ tag=tag, public_tag=args.public_tag, repository=ident)
1664
1809
  except (ApiError, NetworkError) as exc:
1665
1810
  raise SealFailed(_explain(client, exc, "sealing failed")) from exc
1666
1811
  except (gitrepo.GitError, RuntimeError) as exc:
@@ -1683,6 +1828,9 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1683
1828
  _say(f"sealed {commit[:12]} as {out['result']['id']} "
1684
1829
  f"({out['uploaded']} file(s) uploaded)")
1685
1830
  last = out
1831
+ if _note_home(root, ident):
1832
+ _say("Noted this repository as the project's home in .imprint/config.json "
1833
+ "(commit it)")
1686
1834
  if last is None:
1687
1835
  return 0
1688
1836
  result = last["result"]
@@ -1969,12 +2117,42 @@ def cmd_key(args) -> int:
1969
2117
 
1970
2118
  # -- project names and the GitHub App (CIM-BE-19-v1) ---------------------------------------
1971
2119
  def cmd_project(args) -> int:
2120
+ if args.action == "move":
2121
+ return _project_move(args)
2122
+ if not args.name:
2123
+ raise Abort("give the new name: imprint project rename <name>")
1972
2124
  key = _developer_key(required=True)
1973
2125
  project_id = _project_id(args)
1974
2126
  _rename(_client(args), project_id, key, args.name, not args.private)
1975
2127
  return 0
1976
2128
 
1977
2129
 
2130
+ def _project_move(args) -> int:
2131
+ """`imprint project move [folder]`: this repository was renamed, transferred or moved to
2132
+ another host, and is still the same project. A project key signs that the project now
2133
+ also lives here; nothing else changes."""
2134
+ root = Path(args.name or ".")
2135
+ cfg = project.load_config(root) if root.is_dir() else {}
2136
+ project_id = getattr(args, "project", None) or cfg.get("project_id")
2137
+ if not project_id:
2138
+ raise Abort("no project: run `imprint init` (or pass --project)")
2139
+ ident = _identity(root)
2140
+ if not ident:
2141
+ raise Abort("this folder has no repository to move the project to: it needs a Git "
2142
+ "repository with an `origin` remote")
2143
+ key = _developer_key(required=True)
2144
+ client = _client(args)
2145
+ try:
2146
+ client.project_move(project_id, ident, *chainseal.move_proof(key, project_id, ident))
2147
+ except (ApiError, NetworkError) as exc:
2148
+ raise Abort(_explain(client, exc, "the move was not recorded")) from exc
2149
+ _note_home(root, ident)
2150
+ _say(f"Moved project {project_id} now also lives in this repository",
2151
+ " Its chain and its earlier seals are unchanged; `imprint seal` works here again.",
2152
+ " .imprint/config.json was updated: commit it.")
2153
+ return 0
2154
+
2155
+
1978
2156
  GITHUB_MODES = {
1979
2157
  "upgrade": "The App made this project with a key CodeImprint holds. Your developer key "
1980
2158
  "becomes its key too, and authorises the App's key to keep sealing pushes: "
@@ -2097,8 +2275,35 @@ def cmd_check(args) -> int:
2097
2275
 
2098
2276
  # -- verify --------------------------------------------------------------------------------
2099
2277
  def _project_root(path: Path) -> Path:
2278
+ """The project folder a seal file belongs to: the parent of the `.imprint/` it is in
2279
+ (also for files under .imprint/origin/), else its own folder."""
2100
2280
  folder = path.resolve().parent
2101
- return folder.parent if folder.name == project.CONFIG_DIR else folder
2281
+ for parent in (folder, *folder.parents):
2282
+ if parent.name == project.CONFIG_DIR:
2283
+ return parent.parent
2284
+ return folder
2285
+
2286
+
2287
+ def _repository_check(root: Path, rec: dict | None) -> receipt.Check | None:
2288
+ """Was this seal issued for the repository it is being verified in? A seal belongs to
2289
+ its project, and a project to its repository: a seal file copied into another repository
2290
+ still verifies, but says nothing about that repository. Decided from `.imprint/` alone;
2291
+ None when it cannot be told (no project here, no remote, an ownership record). The
2292
+ repository and project the seal does belong to are never named."""
2293
+ chain = (rec or {}).get("chain") or {}
2294
+ if not chain.get("project") or "record" in (rec or {}) or not root.is_dir():
2295
+ return None
2296
+ cfg = project.load_config(root)
2297
+ if not cfg.get("project_id"):
2298
+ return None
2299
+ if cfg["project_id"] != chain["project"]:
2300
+ return receipt.Check("repository", receipt.WARN, NOT_ISSUED)
2301
+ place = _local_place(cfg, _identity(root))
2302
+ if place == "different":
2303
+ return receipt.Check("repository", receipt.WARN, NOT_ISSUED)
2304
+ if place == "same":
2305
+ return receipt.Check("repository", receipt.PASS, "issued for this repository's project")
2306
+ return None
2102
2307
 
2103
2308
 
2104
2309
  def _load_target(args) -> tuple[dict | None, dict | None, Path]:
@@ -2303,7 +2508,11 @@ def cmd_verify(args) -> int:
2303
2508
  else:
2304
2509
  iid = rec.get("imprint_id")
2305
2510
  keys = _trusted_keys(args, root, client, checks)
2306
- developer = project.load_config(root).get("developer") if root.is_dir() else None
2511
+ here = _repository_check(root, rec)
2512
+ elsewhere = here is not None and here.status == receipt.WARN
2513
+ # The folder's developer key is expected on this project's seals only.
2514
+ developer = (project.load_config(root).get("developer")
2515
+ if root.is_dir() and not elsewhere else None)
2307
2516
  anchors = _anchors(args)
2308
2517
  if args.tsa_certs:
2309
2518
  extra = len(anchors) - len(PINNED_ROOTS)
@@ -2318,11 +2527,23 @@ def cmd_verify(args) -> int:
2318
2527
  except (ApiError, NetworkError, KeyError) as exc:
2319
2528
  checks.append(receipt.Check("log consistency", receipt.FAIL,
2320
2529
  f"cannot check the live log: {exc}"))
2530
+ if here is not None:
2531
+ checks.append(here)
2532
+ if elsewhere: # say nothing about where the seal does belong
2533
+ named = ((rec.get("chain") or {}).get("project"))
2534
+ for c in checks:
2535
+ if named and named in c.detail:
2536
+ c.detail = c.detail.replace(f"project {named}", "its project").replace(
2537
+ named, "its project")
2321
2538
  failed = [c for c in checks if c.status == receipt.FAIL]
2322
2539
  warned = [c for c in checks if c.status == receipt.WARN]
2323
2540
  valid = not failed and not (args.strict and warned)
2541
+ elsewhere = any(c.name == "repository" and c.status == receipt.WARN for c in checks)
2324
2542
  if args.json:
2325
2543
  print(json.dumps({"imprint_id": iid, "valid": valid,
2544
+ "issued_for_this_repository": (
2545
+ False if elsewhere else True if any(
2546
+ c.name == "repository" for c in checks) else None),
2326
2547
  "checks": [c.as_dict() for c in checks]}, indent=2))
2327
2548
  else:
2328
2549
  _say(f"{'Record ' if rec and 'record' in rec else 'Imprint'} {iid}", "")
@@ -2331,7 +2552,8 @@ def cmd_verify(args) -> int:
2331
2552
  verdict = ("VALID" if valid else
2332
2553
  f"NOT VALID ({len(failed)} check(s) failed)" if failed else
2333
2554
  f"NOT VALID with --strict ({len(warned)} warning(s))")
2334
- _say("", f"Result {verdict}", "", SEAL_NOTE)
2555
+ _say("", f"Result {verdict}", *([f" {NOT_ISSUED}"] if elsewhere else []),
2556
+ "", SEAL_NOTE)
2335
2557
  return 0 if valid else 1
2336
2558
 
2337
2559
 
@@ -2372,10 +2594,15 @@ def build_parser() -> argparse.ArgumentParser:
2372
2594
  n.add_argument("--name", help="the project's display name (default: owner/repo from the "
2373
2595
  "origin remote, else the folder's name); public")
2374
2596
  n.add_argument("--new-project", action="store_true",
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`")
2597
+ help="this folder came with another project in .imprint/: make a project "
2598
+ "of its own for this repository, with no link to that one. This is "
2599
+ "what `imprint init` does by itself in a different repository; the "
2600
+ "flag asks for it where the repository cannot be told apart. Refused "
2601
+ "when it is your own project in the same repository: then use "
2602
+ "`imprint key request`")
2603
+ n.add_argument("--link-origin", action="store_true",
2604
+ help="also declare a private link (a LIN1 record) from the new project to "
2605
+ "the project this code came from")
2379
2606
  n.set_defaults(func=cmd_init)
2380
2607
 
2381
2608
  ky = sub.add_parser("key", help="the project's keys: add another device (request, then "
@@ -2391,9 +2618,13 @@ def build_parser() -> argparse.ArgumentParser:
2391
2618
  ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2392
2619
  ky.set_defaults(func=cmd_key)
2393
2620
 
2394
- pj = sub.add_parser("project", help="the project's display name: rename")
2395
- pj.add_argument("action", choices=["rename"])
2396
- pj.add_argument("name", help="the new name (1-100 characters)")
2621
+ pj = sub.add_parser("project", help="the project: rename it, or record that its "
2622
+ "repository moved")
2623
+ pj.add_argument("action", choices=["rename", "move"],
2624
+ help="rename: a new display name. move: this repository was renamed, "
2625
+ "transferred or moved to another host and is still the same project")
2626
+ pj.add_argument("name", nargs="?", help="rename: the new name (1-100 characters); "
2627
+ "move: the project's folder (default: here)")
2397
2628
  pj.add_argument("path", nargs="?", default=".")
2398
2629
  pj.add_argument("--private", action="store_true",
2399
2630
  help="show the name to you only, not on the public project page")
@@ -8,6 +8,7 @@ claims; it never publishes them.
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
+ import os
11
12
  import subprocess
12
13
  from pathlib import Path
13
14
 
@@ -83,6 +84,57 @@ def repository_name(url: str | None) -> tuple[str | None, str | None]:
83
84
  return host.lower() or None, "/".join(bits[-2:])
84
85
 
85
86
 
87
+ def remote_identity(url: str | None) -> str | None:
88
+ """A remote in one canonical ``host/path`` form, so that the https and ssh addresses of
89
+ a repository are equal: scheme, credentials, port, a trailing ``.git`` and letter case
90
+ are dropped. None for a local path, or for anything that cannot be read."""
91
+ if not url:
92
+ return None
93
+ from urllib.parse import urlsplit
94
+
95
+ if "://" in url:
96
+ parts = urlsplit(url)
97
+ if parts.scheme == "file":
98
+ return None
99
+ host, path = (parts.hostname or ""), parts.path
100
+ else: # scp form: [user@]host:owner/repo
101
+ head, sep, path = url.partition(":")
102
+ host = head.rsplit("@", 1)[-1]
103
+ if not sep or "/" in head or "\\" in head or len(host) < 2:
104
+ return None # a local path (also C:\\folder)
105
+ path = path.strip("/").removesuffix(".git").strip("/")
106
+ if not host or not path:
107
+ return None
108
+ return f"{host}/{path}".lower()
109
+
110
+
111
+ def identity(root: Path) -> dict | None:
112
+ """Which repository this folder is in, as ``{provider, id, url, folder}``: the
113
+ provider's repository ID where the build environment gives it (GitHub Actions, GitLab
114
+ CI), the origin remote in its canonical form, and the folder inside the repository.
115
+ None when there is neither an ID nor a remote (a local repository). The server keeps
116
+ it only as keyed hashes."""
117
+ env = os.environ
118
+ url = remote_identity(remote_url(root))
119
+ provider = rid = named = None
120
+ if env.get("GITHUB_ACTIONS") == "true" and env.get("GITHUB_REPOSITORY_ID"):
121
+ provider = remote_identity(env.get("GITHUB_SERVER_URL", "") + "/x") or "github.com/x"
122
+ provider, rid = provider.rsplit("/", 1)[0], env["GITHUB_REPOSITORY_ID"]
123
+ named = env.get("GITHUB_REPOSITORY")
124
+ elif env.get("GITLAB_CI") == "true" and env.get("CI_PROJECT_ID"):
125
+ provider, rid = (env.get("CI_SERVER_HOST") or "gitlab.com").lower(), env["CI_PROJECT_ID"]
126
+ named = env.get("CI_PROJECT_PATH")
127
+ if rid:
128
+ here = f"{provider}/{named}".lower() if named else None
129
+ if url and here and url != here: # the job checked out another repository
130
+ provider = rid = None
131
+ elif not url:
132
+ url = here
133
+ if not url and not rid:
134
+ return None
135
+ return {"provider": provider, "id": rid, "url": url, "folder": prefix(root).strip("/")}
136
+
137
+
86
138
  def has_commits(root: Path) -> bool:
87
139
  try:
88
140
  resolve(root, "HEAD")
File without changes
File without changes