codeimprint 0.5.0a18__tar.gz → 0.5.0a21__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.0a21}/CHANGELOG.md +85 -0
  2. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/PKG-INFO +4 -3
  3. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/README.pypi.md +3 -2
  4. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/pyproject.toml +1 -1
  5. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/__init__.py +1 -1
  6. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/api.py +37 -4
  7. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/chainseal.py +35 -4
  8. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/cli.py +482 -61
  9. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/gitrepo.py +55 -0
  10. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/.gitignore +0 -0
  11. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/LICENSE +0 -0
  12. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/NOTICE +0 -0
  13. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint/__init__.py +0 -0
  14. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint/__main__.py +0 -0
  15. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/__main__.py +0 -0
  16. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/config.py +0 -0
  17. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/imprint_file.py +0 -0
  18. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/linecount.py +0 -0
  19. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/ownership.py +0 -0
  20. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/project.py +0 -0
  21. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/receipt.py +0 -0
  22. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a18 → codeimprint-0.5.0a21}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,90 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a21 — A CI token's check is for its own project [CIM-BE-35-v2]
4
+
5
+ For engine 0.7.0a25, where a CI token checks against, and signs, seals of its own project
6
+ only. Nothing else changes; older engines still work.
7
+
8
+ - **Changed: `imprint check` with a CI token.** When the server does not know the reference
9
+ (with a CI token that includes every seal outside the token's project), the message now
10
+ says so and what to do: use one of the project's own Imprint IDs (`imprint chain`), or a
11
+ token for the project the reference belongs to. The exit code is unchanged.
12
+ - No new command. Tests: `tests/test_tokens.py`.
13
+
14
+ ## 0.5.0a20 — CI tokens for automated builds [CIM-BE-35-v1]
15
+
16
+ For engine 0.7.0a24. Older engines still work, except for the new `imprint token` commands.
17
+
18
+ A build seals with a CI token of your own account. You never need the server's API token.
19
+
20
+ - **New: `imprint token`.**
21
+ - `imprint token create` in the project's folder (signed in) prints a token for that one
22
+ project, **once**. `--days` sets how long it lasts (default 90, at most 365; it always
23
+ expires), `--label` names it for you, `--project` picks another project.
24
+ - `imprint token list` shows your tokens: ID, project, status, dates, last use. Never the
25
+ token. `--json` for a script.
26
+ - `imprint token revoke <id>` ends one. A build that still uses it warns and goes on.
27
+ - **Changed: a CI token in `CODEIMPRINT_TOKEN` is your account, never the operator.** Before,
28
+ any token there was treated as the server's API token; `imprint init --new-project` now
29
+ refuses your own project with a CI token as it does with a sign-in. When the server does
30
+ not accept the token (expired or revoked) the message says to make a new one.
31
+ - **Changed: the build files `imprint init` writes.**
32
+ - The GitHub Actions workflow now says how to set each secret: `CODEIMPRINT_TOKEN` is a CI
33
+ token from `imprint token create`.
34
+ - **New:** a repository on GitLab gets `.gitlab-ci.yml`, one on Bitbucket gets
35
+ `bitbucket-pipelines.yml`, with the same instructions. An existing pipeline file is never
36
+ touched, not even with `--force`: `init` says to add the job from the README.
37
+ - **Changed: GitLab CI and Bitbucket Pipelines count as builds**, like GitHub Actions: a seal
38
+ that cannot be made there is a warning and exit 0. A Bitbucket build also names its
39
+ repository's ID.
40
+ - New API calls used: `POST` and `GET /api/v1/me/tokens`, `POST /api/v1/me/tokens/{id}/revoke`.
41
+ - Tests: `tests/test_tokens.py`.
42
+
43
+ ## 0.5.0a19 — A different repository needs its own seal [CIM-BE-34-v1]
44
+
45
+ For engine 0.7.0a23. Older engines still work: they ignore the new field, and the checks
46
+ that need the server are skipped.
47
+
48
+ The same repository on any device is the same project. A different repository (a copy, a
49
+ fork, a template) is a different project: it is never created or sealed for you, you run
50
+ `imprint init` in it.
51
+
52
+ - **New: every Git seal and `imprint init` send which repository this is.** The provider's
53
+ repository ID in GitHub Actions and GitLab CI, else the `origin` remote as `host/path`
54
+ (scheme, credentials and port dropped), and the folder inside the repository. The server
55
+ keeps keyed hashes. `.imprint/config.json` keeps hashes too (`homes`), never the address;
56
+ the first seal of an existing project adds them ("Noted this repository…": commit it).
57
+ - **Changed: `imprint seal` in a repository that is not the project's is refused**, for
58
+ anyone, and nothing changes: "This repository is not the one this project belongs to. Run
59
+ `imprint init` to seal it as its own project." In GitHub Actions it is a warning and the
60
+ build goes on. A device that holds a project key is also told about `imprint project
61
+ move`, for a repository that was only renamed or moved.
62
+ - **Changed: `imprint init` in such a repository makes a stand-alone project** (this
63
+ device's key, a genesis seal, `.imprint/` rewritten, the other project's seal files moved
64
+ to `.imprint/origin/`). It no longer needs `--new-project`, keeps nothing about the other
65
+ project and declares **no link**.
66
+ - **New: `--link-origin`** adds the private link to the project the code came from (the
67
+ `LIN1` record that 0.5.0a17 declared by default). It also works later, on the project
68
+ that already exists.
69
+ - `--new-project` still works: it asks for the stand-alone project where the repository
70
+ cannot be told apart (no remote, or a `.imprint/` from before this version). It is
71
+ refused for your own project in the same repository, as before.
72
+ - **New: `imprint init` on another device of the same repository creates nothing.** When
73
+ your account already has a project for this repository, the config is restored for it
74
+ and you are pointed to `imprint key request`.
75
+ - **New: `imprint project move`** records that the project's repository was renamed,
76
+ transferred or moved to another host (signed by a project key). Not needed where a build
77
+ knows the repository's ID.
78
+ - **Changed: `imprint verify`** in a repository that the seal's project does not live in
79
+ still reports the seal, and adds "Not issued for this repository. Seal this repository
80
+ with `imprint init`." (a warning: `--strict` fails on it). It does not name the project or
81
+ repository the seal belongs to. `--json` gains `issued_for_this_repository`
82
+ (`true`, `false` or `null` when it cannot be told). A seal that belongs to another project
83
+ is no longer checked against this folder's developer key.
84
+ - New API calls used: `POST /api/v1/projects/{id}/home/check`, `POST /api/v1/projects/{id}/home`,
85
+ `POST /api/v1/repository/projects`; `repository` in `seal/plan` and `POST /api/v1/projects`.
86
+ - Tests: `tests/test_repository.py`.
87
+
3
88
  ## 0.5.0a18 — Seals send recent commit IDs for clone detection [CIM-BE-33-v1]
4
89
 
5
90
  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.0a21
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
@@ -74,8 +74,9 @@ imprint verify # check the seal offline
74
74
  ```
75
75
 
76
76
  - **`imprint login`** saves the server and your sign-in in your user config folder, readable
77
- by you only. In GitHub Actions, use an API token: `imprint login --token-stdin`, or the
78
- `CODEIMPRINT_URL` and `CODEIMPRINT_TOKEN` environment variables.
77
+ by you only. In an automated build (GitHub Actions, GitLab CI, Bitbucket Pipelines) set
78
+ `CODEIMPRINT_URL` and `CODEIMPRINT_TOKEN`, where the token is a CI token of your own
79
+ account: `imprint token create` prints one for the project, once.
79
80
  - **`imprint init`** creates your Ed25519 developer key in the user config folder (it is
80
81
  never uploaded and never written to the repository), writes `.imprint/config.json` and a
81
82
  GitHub Actions workflow, and creates the project, named `owner/repo` from the `origin`
@@ -40,8 +40,9 @@ imprint verify # check the seal offline
40
40
  ```
41
41
 
42
42
  - **`imprint login`** saves the server and your sign-in in your user config folder, readable
43
- by you only. In GitHub Actions, use an API token: `imprint login --token-stdin`, or the
44
- `CODEIMPRINT_URL` and `CODEIMPRINT_TOKEN` environment variables.
43
+ by you only. In an automated build (GitHub Actions, GitLab CI, Bitbucket Pipelines) set
44
+ `CODEIMPRINT_URL` and `CODEIMPRINT_TOKEN`, where the token is a CI token of your own
45
+ account: `imprint token create` prints one for the project, once.
45
46
  - **`imprint init`** creates your Ed25519 developer key in the user config folder (it is
46
47
  never uploaded and never written to the repository), writes `.imprint/config.json` and a
47
48
  GitHub Actions workflow, and creates the project, named `owner/repo` from the `origin`
@@ -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.0a21"
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.0a21"
@@ -73,8 +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.
76
+ # How this client is signed in: "token" (the server's API token: the operator), "ci"
77
+ # (an account's CI token), "session" (`imprint login`), "expired" (that session has
78
+ # ended) or "none". Set by the command line.
78
79
  self.auth = "token" if token else "none"
79
80
  self.access = config.cf_access_for(self.url) # this server's host only
80
81
 
@@ -136,10 +137,30 @@ class Client:
136
137
  return self._request(method, path, body, "application/json" if body else None)
137
138
 
138
139
  # Git-aware sealing: projects, plan -> blobs -> prepare -> finalise ------------------
139
- def create_project(self, public_key: str, signature: str, name: str | None = None) -> dict:
140
+ def create_project(self, public_key: str, signature: str, name: str | None = None,
141
+ repository: dict | None = None) -> dict:
140
142
  return self._json("POST", "/api/v1/projects",
141
143
  {"public_key": public_key, "signature": signature,
142
- **({"name": name} if name else {})})
144
+ **({"name": name} if name else {}),
145
+ **({"repository": repository} if repository else {})})
146
+
147
+ # repository identity (engine 0.7.0a23+): a project's homes ------------------------------
148
+ def project_home_check(self, project: str, repository: dict) -> dict:
149
+ """{home: same | unset | unknown | different, settled} for the project's own
150
+ accounts; the 404 of an unknown project for everyone else."""
151
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/home/check",
152
+ {"repository": repository})
153
+
154
+ def project_move(self, project: str, repository: dict, public_key: str,
155
+ signature: str) -> dict:
156
+ return self._json("POST", f"/api/v1/projects/{quote(project)}/home",
157
+ {"repository": repository, "public_key": public_key,
158
+ "signature": signature})
159
+
160
+ def own_projects_here(self, repository: dict) -> list[str]:
161
+ """This account's own projects that live in this repository."""
162
+ return self._json("POST", "/api/v1/repository/projects",
163
+ {"repository": repository}).get("projects") or []
143
164
 
144
165
  def rename_project(self, project: str, name: str, public: bool, public_key: str,
145
166
  signature: str) -> dict:
@@ -175,6 +196,18 @@ class Client:
175
196
  return self._json("POST", f"/api/v1/projects/{quote(project)}/keys/requests",
176
197
  {"public_key": public_key, "signature": signature, "label": label})
177
198
 
199
+ # CI tokens of the signed-in account (engine 0.7.0a24+) ------------------------------------
200
+ def create_token(self, project: str, days: int = 90, label: str | None = None) -> dict:
201
+ return self._json("POST", "/api/v1/me/tokens",
202
+ {"project": project, "days": days,
203
+ **({"label": label} if label else {})})
204
+
205
+ def tokens(self) -> list[dict]:
206
+ return self._request("GET", "/api/v1/me/tokens").get("items") or []
207
+
208
+ def revoke_token(self, token_id: str) -> dict:
209
+ return self._json("POST", f"/api/v1/me/tokens/{quote(token_id)}/revoke", {})
210
+
178
211
  def lineage(self, record_id: str) -> dict:
179
212
  """A lineage record (LIN1): its public record and, when this account may see it,
180
213
  the opening of its commitment (engine 0.7.0a21+)."""
@@ -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))
@@ -36,6 +36,95 @@ SEAL_NOTE = ("A seal proves that this exact Imprint was registered at that time
36
36
  "changed since; it does not prove who wrote the code.")
37
37
 
38
38
 
39
+ GITLAB_CI = """\
40
+ # Added by `imprint init` — CodeImprint
41
+ #
42
+ # Seals the code on pushes to the default branch and on tags; the seal and its receipt are
43
+ # kept as job artifacts. It installs the client from PyPI and runs `imprint`.
44
+ #
45
+ # Set up once (Settings > CI/CD > Variables; mask them, and protect them if the branch is):
46
+ # CODEIMPRINT_URL your server, for example https://api.codeimprint.ai
47
+ # CODEIMPRINT_TOKEN a CI token for this project: run `imprint token create` on your
48
+ # machine and paste what it prints. It is shown once and
49
+ # expires; make a new one with the same command
50
+ # CODEIMPRINT_DEVELOPER_KEY the contents of a developer key file that the project accepts
51
+ # (`imprint key request`, then `imprint key approve`)
52
+ # The code is uploaded, processed and deleted at once. A seal that cannot be made is a
53
+ # warning: this job never fails your pipeline.
54
+ codeimprint-seal:
55
+ image: python:3.12-slim
56
+ rules:
57
+ - if: $CODEIMPRINT_URL && ($CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_TAG)
58
+ variables:
59
+ GIT_DEPTH: "50"
60
+ allow_failure: true
61
+ script:
62
+ - apt-get update -qq && apt-get install -y -qq git > /dev/null
63
+ - python -m pip install --disable-pip-version-check --quiet --pre codeimprint
64
+ - if [ -n "$CI_COMMIT_TAG" ]; then KIND=release; else KIND=push; fi
65
+ - imprint seal . --yes --kind "$KIND"
66
+ artifacts:
67
+ when: always
68
+ paths:
69
+ - .imprint/baseline.imprint
70
+ - .imprint/baseline.receipt.json
71
+ - .imprint/server-keys.json
72
+ """
73
+
74
+ BITBUCKET_PIPELINES = """\
75
+ # Added by `imprint init` — CodeImprint
76
+ #
77
+ # Seals the code on pushes to main and on tags; the seal and its receipt are kept as
78
+ # artifacts. It installs the client from PyPI and runs `imprint`.
79
+ #
80
+ # Set up once (Repository settings > Pipelines > Repository variables; tick "Secured"):
81
+ # CODEIMPRINT_URL your server, for example https://api.codeimprint.ai
82
+ # CODEIMPRINT_TOKEN a CI token for this project: run `imprint token create` on your
83
+ # machine and paste what it prints. It is shown once and
84
+ # expires; make a new one with the same command
85
+ # CODEIMPRINT_DEVELOPER_KEY the contents of a developer key file that the project accepts
86
+ # (`imprint key request`, then `imprint key approve`)
87
+ # The code is uploaded, processed and deleted at once. A seal that cannot be made is a
88
+ # warning: these steps never fail your pipeline.
89
+ image: python:3.12
90
+
91
+ definitions:
92
+ steps:
93
+ - step: &codeimprint-seal
94
+ name: CodeImprint seal
95
+ script:
96
+ - if [ -z "$CODEIMPRINT_URL" ]; then echo "CodeImprint - no CODEIMPRINT_URL, sealing skipped"; exit 0; fi
97
+ - python -m pip install --disable-pip-version-check --quiet --pre codeimprint
98
+ - if [ -n "$BITBUCKET_TAG" ]; then KIND=release; else KIND=push; fi
99
+ - imprint seal . --yes --kind "$KIND" || echo "CodeImprint - the seal was skipped"
100
+ artifacts:
101
+ - .imprint/baseline.imprint
102
+ - .imprint/baseline.receipt.json
103
+ - .imprint/server-keys.json
104
+
105
+ pipelines:
106
+ branches:
107
+ main:
108
+ - step: *codeimprint-seal
109
+ tags:
110
+ '*':
111
+ - step: *codeimprint-seal
112
+ """
113
+
114
+
115
+ def ci_file(root: Path, fail_above) -> tuple[str, str, bool]:
116
+ """The build file `imprint init` adds, by where the repository lives: (path, text,
117
+ shared). GitHub gets a workflow of its own. GitLab and Bitbucket keep one pipeline file
118
+ for everything (``shared``), so an existing one is never touched."""
119
+ host = (gitrepo.remote_identity(gitrepo.remote_url(root)) or "").split("/", 1)[0] \
120
+ if gitrepo.is_repo(root) else ""
121
+ if "gitlab" in host:
122
+ return ".gitlab-ci.yml", GITLAB_CI, True
123
+ if "bitbucket" in host:
124
+ return "bitbucket-pipelines.yml", BITBUCKET_PIPELINES, True
125
+ return ".github/workflows/codeimprint.yml", WORKFLOW % {"fail_above": fail_above}, False
126
+
127
+
39
128
  def verify_url(imprint_id: str, hub: str | None) -> str | None:
40
129
  """The seal's page on the hub (config.hub_url), or None when no hub is known."""
41
130
  return f"{hub}/i/{imprint_id}" if hub else None
@@ -72,12 +161,20 @@ WORKFLOW = """\
72
161
  # Seals the code on pushes to main and on tags (the seal and its receipt are kept as a build
73
162
  # artifact), and checks pull requests against a reference Imprint on your CodeImprint server.
74
163
  # It installs the client from PyPI (pip install --pre codeimprint) and runs `imprint`.
75
- # Secrets: CODEIMPRINT_URL (your server, for example https://api.codeimprint.ai; a repository
76
- # variable of that name works too), CODEIMPRINT_TOKEN, and CODEIMPRINT_DEVELOPER_KEY (the
77
- # contents of your developer key file) to sign seals. Variable: CODEIMPRINT_REFERENCE (an
78
- # Imprint ID) for pull request checks. The code is uploaded, processed and deleted at once.
79
- # Network and server problems are warnings, never failures; without CODEIMPRINT_URL (as in
80
- # pull requests from forks) the job is skipped with a notice.
164
+ #
165
+ # Set up once (Settings > Secrets and variables > Actions > New repository secret):
166
+ # CODEIMPRINT_URL your server, for example https://api.codeimprint.ai (a
167
+ # repository variable of that name works too)
168
+ # CODEIMPRINT_TOKEN a CI token for this project: run `imprint token create` on your
169
+ # machine and paste what it prints. It is shown once and
170
+ # expires; make a new one with the same command
171
+ # CODEIMPRINT_DEVELOPER_KEY the contents of a developer key file that the project accepts
172
+ # (`imprint key request`, then `imprint key approve`): it signs
173
+ # the seals
174
+ # Variable: CODEIMPRINT_REFERENCE (an Imprint ID) for pull request checks.
175
+ # The code is uploaded, processed and deleted at once. Network and server problems are
176
+ # warnings, never failures; without CODEIMPRINT_URL (as in pull requests from forks) the job
177
+ # is skipped with a notice.
81
178
  name: CodeImprint
82
179
 
83
180
  on:
@@ -163,20 +260,30 @@ def _say(*lines: str) -> None:
163
260
 
164
261
 
165
262
  def _ci() -> bool:
166
- return os.environ.get("GITHUB_ACTIONS") == "true"
263
+ """An automated build (GitHub Actions, GitLab CI, Bitbucket Pipelines): a seal that cannot
264
+ be made there is a warning, never a failed build."""
265
+ env = os.environ
266
+ return (env.get("GITHUB_ACTIONS") == "true" or env.get("GITLAB_CI") == "true"
267
+ or bool(env.get("BITBUCKET_BUILD_NUMBER")))
167
268
 
168
269
 
169
270
  def _warn(message: str) -> None:
170
- if _ci():
271
+ if os.environ.get("GITHUB_ACTIONS") == "true":
171
272
  print(f"::warning::CodeImprint: {message}")
172
273
  print(f"imprint: warning: {message}", file=sys.stderr)
173
274
 
174
275
 
276
+ CI_TOKEN_PREFIX = "cit_" # a per-account CI token (`imprint token create`)
277
+
278
+
175
279
  def _signed_in(url: str, api_token: str | None) -> Client:
176
280
  """A client for this server: the API token when one is set (CODEIMPRINT_TOKEN or saved by
177
281
  `imprint login --api-token`), else the session from `imprint login`."""
178
282
  if api_token:
179
- return Client(url, api_token)
283
+ client = Client(url, api_token)
284
+ if api_token.startswith(CI_TOKEN_PREFIX):
285
+ client.auth = "ci" # an account's CI token, never the operator
286
+ return client
180
287
  session = config.load_session(url)
181
288
  client = Client(url, session["token"] if session else None)
182
289
  client.auth = "session" if session else (
@@ -195,13 +302,21 @@ def _client(args, fallback_url: str | None = None) -> Client:
195
302
 
196
303
  def _explain(client: Client, exc: Exception, what: str) -> str:
197
304
  """``what: why``, with what to do when the server asks for a sign-in."""
305
+ if isinstance(exc, ApiError) and exc.code == "token_scope":
306
+ return (f"{what}: a CI token only seals and checks its own project. Sign in with "
307
+ f"`imprint login` for this. The server said: {exc}")
198
308
  if isinstance(exc, ApiError) and exc.status == 401:
309
+ if client.auth == "ci":
310
+ return (f"{what}: the CI token in CODEIMPRINT_TOKEN was not accepted by "
311
+ f"{client.url} (it expired or was revoked). Make a new one with `imprint "
312
+ f"token create` and update the secret. The server said: {exc}")
199
313
  if client.auth == "expired":
200
314
  return (f"{what}: your sign-in to {client.url} has expired: run `imprint login` "
201
315
  f"again. The server said: {exc}")
202
316
  if client.auth == "none":
203
317
  return (f"{what}: you are not signed in to {client.url}: run `imprint login` (or "
204
- f"set CODEIMPRINT_TOKEN to an API token). The server said: {exc}")
318
+ f"set CODEIMPRINT_TOKEN to a CI token from `imprint token create`). The server "
319
+ f"said: {exc}")
205
320
  return f"{what}: {exc}"
206
321
 
207
322
 
@@ -214,6 +329,61 @@ def _not_your_project(client: Client, project_id: str, key) -> str:
214
329
  f"request`: its owner sees the request and can add your developer key{mine}.")
215
330
 
216
331
 
332
+ NOT_THIS_REPOSITORY = ("This repository is not the one this project belongs to. Run `imprint "
333
+ "init` to seal it as its own project.")
334
+ MOVE_HINT = (" If this is the same repository at a new address (it was renamed or moved), run "
335
+ "`imprint project move` instead.")
336
+ NOT_ISSUED = "Not issued for this repository. Seal this repository with `imprint init`."
337
+
338
+
339
+ def _identity(root: Path | None) -> dict | None:
340
+ """Which repository this folder is in; None when it is not a Git repository or has
341
+ neither a remote nor a provider ID."""
342
+ try:
343
+ return gitrepo.identity(root) if root is not None and gitrepo.is_repo(root) else None
344
+ except gitrepo.GitError:
345
+ return None
346
+
347
+
348
+ def _local_place(cfg: dict, ident: dict | None) -> str:
349
+ """From `.imprint/config.json` alone: is this the repository the project was noted in?
350
+ "same", "different", or "unknown" (nothing noted, or no identity here)."""
351
+ noted = cfg.get("homes")
352
+ if not ident or not noted or not cfg.get("project_id"):
353
+ return "unknown"
354
+ mine = chainseal.home_hashes(cfg["project_id"], ident)
355
+ return "same" if set(mine) & set(noted) else "different"
356
+
357
+
358
+ def _server_place(client: Client, project_id: str, ident: dict | None) -> tuple[str, bool]:
359
+ """Ask the server, which answers the project's own accounts only: ("same" | "different"
360
+ | "unknown", settled). Unknown for an engine before 0.7.0a23 or when there is no answer."""
361
+ if not ident:
362
+ return "unknown", False
363
+ try:
364
+ out = client.project_home_check(project_id, ident)
365
+ except (ApiError, NetworkError):
366
+ return "unknown", False
367
+ home = out.get("home")
368
+ return ("same" if home in ("same", "unset") else "different" if home == "different"
369
+ else "unknown"), bool(out.get("settled"))
370
+
371
+
372
+ def _note_home(root: Path, ident: dict | None) -> bool:
373
+ """Keep this repository's hashes in `.imprint/config.json`, so that a copy of the folder
374
+ in another repository can be told apart (chainseal.home_hashes). True when it changed."""
375
+ cfg = project.load_config(root)
376
+ if not ident or not cfg.get("project_id"):
377
+ return False
378
+ mine, noted = chainseal.home_hashes(cfg["project_id"], ident), cfg.get("homes") or []
379
+ if set(mine) <= set(noted):
380
+ return False
381
+ cfg["homes"] = noted + [h for h in mine if h not in noted]
382
+ (root / project.CONFIG_DIR / project.CONFIG_FILE).write_text(
383
+ json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
384
+ return True
385
+
386
+
217
387
  def _project_state(client: Client, project_id: str, key) -> str:
218
388
  """"ok" when this caller may use the project, "not-yours" when the server says it does
219
389
  not exist for them, else "unknown" (an engine before 0.7.0a19, or no answer)."""
@@ -232,27 +402,57 @@ def _project_state(client: Client, project_id: str, key) -> str:
232
402
  return "ok"
233
403
 
234
404
 
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."""
405
+ def _project_ready(client: Client, project_id: str, key, root: Path | None = None):
406
+ """Before anything is uploaded: this account may use the project, this repository is the
407
+ one the project lives in (a different repository is a different project, made with
408
+ `imprint init`), and this machine's key is one of the project's keys. Returns the
409
+ repository identity to send with the seal."""
410
+ ident = _identity(root)
411
+ cfg = project.load_config(root) if root is not None and root.is_dir() else {}
238
412
  try:
239
413
  state = _project_state(client, project_id, key)
240
414
  except ApiError as exc:
241
415
  raise SealFailed(_explain(client, exc, "sealing failed")) from exc
242
416
  if state == "not-yours":
417
+ if _local_place(cfg, ident) == "different":
418
+ raise SealFailed(NOT_THIS_REPOSITORY)
243
419
  raise SealFailed(_not_your_project(client, project_id, key))
244
420
  try:
245
421
  keys = client.public_project(project_id).get("keys") or []
246
422
  except (ApiError, NetworkError):
247
- return
248
- active = [k["fingerprint"] for k in keys if not k.get("valid_until")]
423
+ keys = None
424
+ active = [k["fingerprint"] for k in keys or [] if not k.get("valid_until")]
249
425
  fp = trust.fingerprint(trust.public_raw(key))
426
+ if state == "ok":
427
+ place, settled = _server_place(client, project_id, ident)
428
+ if place == "different":
429
+ raise SealFailed(NOT_THIS_REPOSITORY
430
+ + (MOVE_HINT if fp in active and not settled else ""))
431
+ if keys is None:
432
+ return ident
250
433
  if active and fp not in active:
251
434
  raise SealFailed(
252
435
  f"developer key {fp} on this machine is not a key of project {project_id} (its "
253
436
  f"keys: {', '.join(active)}). Add this device to the project: run `imprint key "
254
437
  f"request` here, then `imprint key approve {fp}` on a device that already seals "
255
438
  "it. Nothing was uploaded.")
439
+ return ident
440
+
441
+
442
+ def _other_repository(client: Client, cfg: dict, root: Path) -> None:
443
+ """For a machine without a developer key: refuse, with the one sentence, when this is not
444
+ the repository the folder's project lives in. Otherwise say nothing (the caller then
445
+ explains how this device gets a key)."""
446
+ ident = _identity(root)
447
+ try:
448
+ state = _project_state(client, cfg["project_id"], None)
449
+ except ApiError:
450
+ return
451
+ if state == "not-yours":
452
+ if _local_place(cfg, ident) == "different":
453
+ raise SealFailed(NOT_THIS_REPOSITORY)
454
+ elif state == "ok" and _server_place(client, cfg["project_id"], ident)[0] == "different":
455
+ raise SealFailed(NOT_THIS_REPOSITORY)
256
456
 
257
457
 
258
458
  def _prepare_upload(path: str, action: str, client: Client, assume_yes: bool) -> bytes:
@@ -377,9 +577,24 @@ def cmd_init(args) -> int:
377
577
  raise Abort(f"no such folder: {root}")
378
578
  cfg_path = root / project.CONFIG_DIR / project.CONFIG_FILE
379
579
  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)
580
+ link = getattr(args, "link_origin", False)
581
+ if existing.get("project_id"):
582
+ # A different repository is a different project: `imprint init` there makes a
583
+ # stand-alone one. --new-project asks for that whatever the repository is.
584
+ # --link-origin alone changes no project: it adds the link (see _init_project).
585
+ place, mine = _origin_place(args, root, existing)
586
+ if getattr(args, "new_project", False) or place == "different":
587
+ if mine and place != "different": # before anything is changed
588
+ raise Abort(
589
+ f"project {existing['project_id']} is already yours: {mine}. The same "
590
+ "repository on another device is the same project, so no new project "
591
+ "was made and nothing was changed. To seal from this device, run "
592
+ "`imprint key request` here and `imprint key approve` on a device that "
593
+ "already seals the project; if this device already has one of its keys, "
594
+ "just run `imprint seal`."
595
+ + ("" if place == "same" else " (If this is a different repository, give "
596
+ "it its own `origin` remote first, then run `imprint init`.)"))
597
+ existing = _leave_project(root, cfg_path, existing, link)
383
598
  cfg = {"version": 1, "exclude": existing.get("exclude", project.DEFAULT_EXCLUDE),
384
599
  "fail_above": existing.get("fail_above", DEFAULT_FAIL_ABOVE),
385
600
  "reference": existing.get("reference")}
@@ -411,8 +626,12 @@ def cmd_init(args) -> int:
411
626
  else:
412
627
  write(cfg_path, json.dumps(cfg, indent=2) + "\n")
413
628
  if not args.no_ci:
414
- write(root / ".github" / "workflows" / "codeimprint.yml",
415
- WORKFLOW % {"fail_above": cfg["fail_above"]})
629
+ rel, text, shared = ci_file(root, cfg["fail_above"])
630
+ if shared and (root / rel).exists(): # the repository's one pipeline file
631
+ _say(f"kept {rel} (it is your pipeline: add the CodeImprint job from the "
632
+ "README to it; set CODEIMPRINT_TOKEN with `imprint token create`)")
633
+ else:
634
+ write(root / rel, text)
416
635
  for rel in written:
417
636
  _say(f"created {rel}")
418
637
  for rel in skipped:
@@ -434,37 +653,51 @@ def cmd_init(args) -> int:
434
653
  return 0
435
654
 
436
655
 
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`."""
656
+ def _origin_place(args, root: Path, existing: dict) -> tuple[str, str | None]:
657
+ """For `imprint init` in a folder whose config already names a project: is this the
658
+ repository that project lives in ("same", "different" or "unknown"), and why the project
659
+ is the caller's own (None when it is not theirs, or that cannot be told)."""
660
+ origin, ident = existing["project_id"], _identity(root)
661
+ local = _local_place(existing, ident)
441
662
  settings = config.resolve(getattr(args, "url", None))
442
663
  if not settings.url:
443
- return # no server to ask; nothing is created either
664
+ return local, None
444
665
  client = _signed_in(settings.url, settings.token)
445
666
  key = trust.load_developer_key()
446
667
  fp = trust.fingerprint(trust.public_raw(key)) if key is not None else None
447
- why = None
668
+ mine = None
448
669
  try:
449
670
  keys = client.public_project(origin).get("keys") or []
450
671
  except (ApiError, NetworkError):
451
672
  keys = []
452
673
  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"
674
+ mine = f"this machine's developer key {fp} is one of its keys"
454
675
  elif client.auth != "token": # an API token is the operator, not an owner
455
676
  try:
456
677
  if _project_state(client, origin, key) == "ok":
457
- why = "your account is part of it"
678
+ mine = "your account is part of it"
458
679
  except ApiError as exc:
459
680
  raise Abort(_explain(client, exc, "could not check the project this folder "
460
681
  "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`.")
682
+ if not mine:
683
+ return local, None
684
+ place, _settled = _server_place(client, origin, ident)
685
+ return (local if place == "unknown" else place), mine
686
+
687
+
688
+ def _origin_project(root: Path) -> str | None:
689
+ """The project of the seal files that came with the code (.imprint/origin/), by the
690
+ latest of them; None when there are none."""
691
+ best: tuple[int, str] | None = None
692
+ for path in (root / project.CONFIG_DIR).glob("origin/*.receipt.json"):
693
+ try:
694
+ rec = json.loads(path.read_text(encoding="utf-8"))
695
+ found = (int(rec["log"]["index"]), rec["chain"]["project"])
696
+ except (OSError, ValueError, KeyError, TypeError):
697
+ continue
698
+ if isinstance(found[1], str) and (best is None or found > best):
699
+ best = found
700
+ return best[1] if best else None
468
701
 
469
702
 
470
703
  def _origin_seal(root: Path, origin: str) -> str | None:
@@ -532,10 +765,11 @@ def _declare_origin(client: Client, root: Path, cfg_path: Path, key, child: str,
532
765
  f" See it: imprint lineage show {link}")
533
766
 
534
767
 
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."""
768
+ def _leave_project(root: Path, cfg_path: Path, existing: dict, link: bool = False) -> dict:
769
+ """`imprint init` in another repository than the project's: stop pointing at the project
770
+ this folder came with. Its seal files move to .imprint/origin/ (they belong to that
771
+ project). Nothing about that project is kept in the config, unless a link to it was asked
772
+ for (--link-origin)."""
539
773
  folder = root / project.CONFIG_DIR
540
774
  origin = folder / "origin"
541
775
  moved = []
@@ -545,11 +779,12 @@ def _leave_project(root: Path, cfg_path: Path, existing: dict) -> dict:
545
779
  path.replace(origin / path.name)
546
780
  moved.append(path.name)
547
781
  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
782
+ if k not in ("project_id", "developer", "cloned_from", "homes")}
783
+ if link:
784
+ kept["cloned_from"] = {"project": existing["project_id"]} # the link: _declare_origin
550
785
  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)")
786
+ _say("Leaving the project this folder came with: this repository gets a project of "
787
+ "its own")
553
788
  if moved:
554
789
  _say(f"Moved {len(moved)} seal file(s) of that project to .imprint/origin/")
555
790
  return kept
@@ -583,8 +818,16 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
583
818
  _rename(_signed_in(settings.url, settings.token), current["project_id"], key,
584
819
  args.name, True)
585
820
  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
821
+ if getattr(args, "link_origin", False) and settings.url and not came.get("link"):
822
+ origin = came.get("project") or _origin_project(root)
823
+ if not origin:
824
+ _warn("--link-origin: nothing in .imprint/origin/ names the project this "
825
+ "code came from, so there is nothing to link to")
826
+ return
827
+ if not came.get("project"):
828
+ current["cloned_from"] = {"project": origin}
829
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
830
+ try: # the link, asked for now or not declared before
588
831
  genesis = json.loads((root / project.CONFIG_DIR / "genesis.receipt.json")
589
832
  .read_text(encoding="utf-8"))["imprint_id"]
590
833
  except (OSError, ValueError, KeyError, TypeError):
@@ -599,8 +842,25 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
599
842
  return
600
843
  client = _signed_in(settings.url, settings.token)
601
844
  name = getattr(args, "name", None) or default_project_name(root)
845
+ ident = _identity(root)
846
+ try: # the same repository on another device is the same project
847
+ own = client.own_projects_here(ident) if ident and client.auth == "session" else []
848
+ except (ApiError, NetworkError):
849
+ own = []
850
+ if own:
851
+ current["project_id"] = own[0]
852
+ cfg_path.parent.mkdir(parents=True, exist_ok=True)
853
+ cfg_path.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8")
854
+ _note_home(root, ident)
855
+ _say("", f"Project {own[0]} (yours: this repository already has it, so nothing was "
856
+ "created; .imprint/config.json now names it)",
857
+ " The same repository on another device is the same project. To seal from this "
858
+ "device, run",
859
+ " `imprint key request` here and `imprint key approve` on a device that already "
860
+ "seals it.")
861
+ return
602
862
  try:
603
- made = chainseal.create_project(client, key, name)
863
+ made = chainseal.create_project(client, key, name, ident)
604
864
  except (ApiError, NetworkError) as exc:
605
865
  _warn(_explain(client, exc, "the project was not created")
606
866
  + "; run `imprint init` again afterwards")
@@ -621,7 +881,9 @@ def _init_project(args, root: Path, cfg_path: Path, key) -> None:
621
881
  f"Genesis {g['id']}, sealed {g['receipt']['attestation']['statement']['attested_at']} "
622
882
  f"(log entry #{g['receipt']['log']['index']}): the project's chain starts here",
623
883
  "Saved .imprint/genesis.imprint and .imprint/genesis.receipt.json (commit them)")
624
- _declare_origin(client, root, cfg_path, key, made["project_id"], g["id"])
884
+ _note_home(root, ident)
885
+ if getattr(args, "link_origin", False):
886
+ _declare_origin(client, root, cfg_path, key, made["project_id"], g["id"])
625
887
 
626
888
 
627
889
  def _rename(client: Client, project_id: str, key, name: str, public: bool) -> dict:
@@ -1645,8 +1907,10 @@ def _confirm_upload(args, client: Client):
1645
1907
 
1646
1908
  def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1647
1909
  """Incremental seals of one commit or a range (ADR 0001): only new blobs are sent."""
1910
+ if _developer_key() is None: # no key here yet: say first if this is another
1911
+ _other_repository(client, cfg, root) # repository, where no key would help
1648
1912
  key = _developer_key(required=True, expected=cfg.get("developer"))
1649
- _project_ready(client, cfg["project_id"], key)
1913
+ ident = _project_ready(client, cfg["project_id"], key, root)
1650
1914
  try:
1651
1915
  commits = (gitrepo.commits(root, args.all_commits) if args.all_commits
1652
1916
  else [gitrepo.resolve(root, args.rev)])
@@ -1660,7 +1924,7 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1660
1924
  tag = next(iter(gitrepo.tags_at(root, commit)), None)
1661
1925
  out = chainseal.seal_commit(client, root, cfg["project_id"], commit, args.kind, key,
1662
1926
  cfg.get("exclude"), _confirm_upload(args, client),
1663
- tag=tag, public_tag=args.public_tag)
1927
+ tag=tag, public_tag=args.public_tag, repository=ident)
1664
1928
  except (ApiError, NetworkError) as exc:
1665
1929
  raise SealFailed(_explain(client, exc, "sealing failed")) from exc
1666
1930
  except (gitrepo.GitError, RuntimeError) as exc:
@@ -1683,6 +1947,9 @@ def _seal_git(args, client: Client, root: Path, cfg: dict) -> int:
1683
1947
  _say(f"sealed {commit[:12]} as {out['result']['id']} "
1684
1948
  f"({out['uploaded']} file(s) uploaded)")
1685
1949
  last = out
1950
+ if _note_home(root, ident):
1951
+ _say("Noted this repository as the project's home in .imprint/config.json "
1952
+ "(commit it)")
1686
1953
  if last is None:
1687
1954
  return 0
1688
1955
  result = last["result"]
@@ -1968,13 +2235,94 @@ def cmd_key(args) -> int:
1968
2235
 
1969
2236
 
1970
2237
  # -- project names and the GitHub App (CIM-BE-19-v1) ---------------------------------------
2238
+ def cmd_token(args) -> int:
2239
+ """`imprint token create | list | revoke`: CI tokens of the signed-in account. A token
2240
+ acts as the account for one project, on the sealing routes, until it expires."""
2241
+ client = _session_client(args)
2242
+ try:
2243
+ if args.action == "create":
2244
+ root = Path(args.path)
2245
+ cfg = project.load_config(root) if root.is_dir() else {}
2246
+ project_id = args.project or cfg.get("project_id")
2247
+ if not project_id:
2248
+ raise Abort("no project: run this in the project's folder, or pass --project")
2249
+ if not 1 <= args.days <= 365:
2250
+ raise Abort("--days is 1 to 365: a CI token always expires")
2251
+ made = client.create_token(project_id, args.days, args.label)
2252
+ _say(f"Token {made['token']}",
2253
+ " Shown once: copy it now. It is not saved on this machine or shown again.",
2254
+ f"ID {made['id']}" + (f" ({made['label']})" if made.get("label")
2255
+ else ""),
2256
+ f"Project {made['project']} (this token seals this project only)",
2257
+ f"Expires {made['expires_at']} ({args.days} days): then make a new one "
2258
+ "the same way",
2259
+ "", "Add it to your build as the secret CODEIMPRINT_TOKEN (GitHub: Settings > "
2260
+ "Secrets and variables >",
2261
+ "Actions; GitLab: Settings > CI/CD > Variables; Bitbucket: Repository settings "
2262
+ "> Repository variables).",
2263
+ f"Revoke it with: imprint token revoke {made['id']}")
2264
+ return 0
2265
+ if args.action == "revoke":
2266
+ if not args.token:
2267
+ raise Abort("name the token: imprint token revoke <id> (see `imprint token "
2268
+ "list`)")
2269
+ client.revoke_token(args.token)
2270
+ _say(f"Revoked {args.token}: builds that use it stop sealing (they warn and go "
2271
+ "on)")
2272
+ return 0
2273
+ items = client.tokens()
2274
+ except (ApiError, NetworkError) as exc:
2275
+ raise Abort(_explain(client, exc, "the token request failed")) from exc
2276
+ if args.json:
2277
+ print(json.dumps(items, indent=2))
2278
+ return 0
2279
+ if not items:
2280
+ _say("No CI tokens. Make one with `imprint token create` in a project's folder.")
2281
+ return 0
2282
+ for t in items:
2283
+ used = f"last used {t['last_used_at']}" if t.get("last_used_at") else "never used"
2284
+ _say(f"{t['id']} {t['status']:<8} project {t['project']} expires {t['expires_at']} "
2285
+ f"{used}" + (f" ({t['label']})" if t.get("label") else ""))
2286
+ return 0
2287
+
2288
+
1971
2289
  def cmd_project(args) -> int:
2290
+ if args.action == "move":
2291
+ return _project_move(args)
2292
+ if not args.name:
2293
+ raise Abort("give the new name: imprint project rename <name>")
1972
2294
  key = _developer_key(required=True)
1973
2295
  project_id = _project_id(args)
1974
2296
  _rename(_client(args), project_id, key, args.name, not args.private)
1975
2297
  return 0
1976
2298
 
1977
2299
 
2300
+ def _project_move(args) -> int:
2301
+ """`imprint project move [folder]`: this repository was renamed, transferred or moved to
2302
+ another host, and is still the same project. A project key signs that the project now
2303
+ also lives here; nothing else changes."""
2304
+ root = Path(args.name or ".")
2305
+ cfg = project.load_config(root) if root.is_dir() else {}
2306
+ project_id = getattr(args, "project", None) or cfg.get("project_id")
2307
+ if not project_id:
2308
+ raise Abort("no project: run `imprint init` (or pass --project)")
2309
+ ident = _identity(root)
2310
+ if not ident:
2311
+ raise Abort("this folder has no repository to move the project to: it needs a Git "
2312
+ "repository with an `origin` remote")
2313
+ key = _developer_key(required=True)
2314
+ client = _client(args)
2315
+ try:
2316
+ client.project_move(project_id, ident, *chainseal.move_proof(key, project_id, ident))
2317
+ except (ApiError, NetworkError) as exc:
2318
+ raise Abort(_explain(client, exc, "the move was not recorded")) from exc
2319
+ _note_home(root, ident)
2320
+ _say(f"Moved project {project_id} now also lives in this repository",
2321
+ " Its chain and its earlier seals are unchanged; `imprint seal` works here again.",
2322
+ " .imprint/config.json was updated: commit it.")
2323
+ return 0
2324
+
2325
+
1978
2326
  GITHUB_MODES = {
1979
2327
  "upgrade": "The App made this project with a key CodeImprint holds. Your developer key "
1980
2328
  "becomes its key too, and authorises the App's key to keep sealing pushes: "
@@ -2085,6 +2433,12 @@ def cmd_check(args) -> int:
2085
2433
  if exc.status in {401, 403, 429} or exc.status >= 500:
2086
2434
  _warn(_explain(client, exc, "check skipped"))
2087
2435
  return 0
2436
+ if exc.status == 404 and client.auth == "ci":
2437
+ raise Abort("check failed: with a CI token the reference must be a seal of the "
2438
+ "token's own project, and the server knows no such seal there. Use "
2439
+ "one of this project's Imprint IDs (`imprint chain`), or make the "
2440
+ f"token for the project the reference belongs to. The server said: "
2441
+ f"{exc}") from exc
2088
2442
  raise Abort(f"check failed: {exc}") from exc
2089
2443
  if args.output:
2090
2444
  Path(args.output).write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
@@ -2097,8 +2451,35 @@ def cmd_check(args) -> int:
2097
2451
 
2098
2452
  # -- verify --------------------------------------------------------------------------------
2099
2453
  def _project_root(path: Path) -> Path:
2454
+ """The project folder a seal file belongs to: the parent of the `.imprint/` it is in
2455
+ (also for files under .imprint/origin/), else its own folder."""
2100
2456
  folder = path.resolve().parent
2101
- return folder.parent if folder.name == project.CONFIG_DIR else folder
2457
+ for parent in (folder, *folder.parents):
2458
+ if parent.name == project.CONFIG_DIR:
2459
+ return parent.parent
2460
+ return folder
2461
+
2462
+
2463
+ def _repository_check(root: Path, rec: dict | None) -> receipt.Check | None:
2464
+ """Was this seal issued for the repository it is being verified in? A seal belongs to
2465
+ its project, and a project to its repository: a seal file copied into another repository
2466
+ still verifies, but says nothing about that repository. Decided from `.imprint/` alone;
2467
+ None when it cannot be told (no project here, no remote, an ownership record). The
2468
+ repository and project the seal does belong to are never named."""
2469
+ chain = (rec or {}).get("chain") or {}
2470
+ if not chain.get("project") or "record" in (rec or {}) or not root.is_dir():
2471
+ return None
2472
+ cfg = project.load_config(root)
2473
+ if not cfg.get("project_id"):
2474
+ return None
2475
+ if cfg["project_id"] != chain["project"]:
2476
+ return receipt.Check("repository", receipt.WARN, NOT_ISSUED)
2477
+ place = _local_place(cfg, _identity(root))
2478
+ if place == "different":
2479
+ return receipt.Check("repository", receipt.WARN, NOT_ISSUED)
2480
+ if place == "same":
2481
+ return receipt.Check("repository", receipt.PASS, "issued for this repository's project")
2482
+ return None
2102
2483
 
2103
2484
 
2104
2485
  def _load_target(args) -> tuple[dict | None, dict | None, Path]:
@@ -2187,7 +2568,7 @@ def _server_from_project(root: Path) -> str | None:
2187
2568
  def _fetch_lineage(client: Client, record_id: str) -> tuple[dict, dict | None]:
2188
2569
  """A lineage record and, for an account that may see it, its opening. Without a
2189
2570
  sign-in (or on an older server) the public record alone."""
2190
- if client.auth in ("token", "session"):
2571
+ if client.auth in ("token", "session"): # not a CI token: it only seals
2191
2572
  try:
2192
2573
  answer = client.lineage(record_id)
2193
2574
  return answer["receipt"], answer.get("opening")
@@ -2303,7 +2684,11 @@ def cmd_verify(args) -> int:
2303
2684
  else:
2304
2685
  iid = rec.get("imprint_id")
2305
2686
  keys = _trusted_keys(args, root, client, checks)
2306
- developer = project.load_config(root).get("developer") if root.is_dir() else None
2687
+ here = _repository_check(root, rec)
2688
+ elsewhere = here is not None and here.status == receipt.WARN
2689
+ # The folder's developer key is expected on this project's seals only.
2690
+ developer = (project.load_config(root).get("developer")
2691
+ if root.is_dir() and not elsewhere else None)
2307
2692
  anchors = _anchors(args)
2308
2693
  if args.tsa_certs:
2309
2694
  extra = len(anchors) - len(PINNED_ROOTS)
@@ -2318,11 +2703,23 @@ def cmd_verify(args) -> int:
2318
2703
  except (ApiError, NetworkError, KeyError) as exc:
2319
2704
  checks.append(receipt.Check("log consistency", receipt.FAIL,
2320
2705
  f"cannot check the live log: {exc}"))
2706
+ if here is not None:
2707
+ checks.append(here)
2708
+ if elsewhere: # say nothing about where the seal does belong
2709
+ named = ((rec.get("chain") or {}).get("project"))
2710
+ for c in checks:
2711
+ if named and named in c.detail:
2712
+ c.detail = c.detail.replace(f"project {named}", "its project").replace(
2713
+ named, "its project")
2321
2714
  failed = [c for c in checks if c.status == receipt.FAIL]
2322
2715
  warned = [c for c in checks if c.status == receipt.WARN]
2323
2716
  valid = not failed and not (args.strict and warned)
2717
+ elsewhere = any(c.name == "repository" and c.status == receipt.WARN for c in checks)
2324
2718
  if args.json:
2325
2719
  print(json.dumps({"imprint_id": iid, "valid": valid,
2720
+ "issued_for_this_repository": (
2721
+ False if elsewhere else True if any(
2722
+ c.name == "repository" for c in checks) else None),
2326
2723
  "checks": [c.as_dict() for c in checks]}, indent=2))
2327
2724
  else:
2328
2725
  _say(f"{'Record ' if rec and 'record' in rec else 'Imprint'} {iid}", "")
@@ -2331,7 +2728,8 @@ def cmd_verify(args) -> int:
2331
2728
  verdict = ("VALID" if valid else
2332
2729
  f"NOT VALID ({len(failed)} check(s) failed)" if failed else
2333
2730
  f"NOT VALID with --strict ({len(warned)} warning(s))")
2334
- _say("", f"Result {verdict}", "", SEAL_NOTE)
2731
+ _say("", f"Result {verdict}", *([f" {NOT_ISSUED}"] if elsewhere else []),
2732
+ "", SEAL_NOTE)
2335
2733
  return 0 if valid else 1
2336
2734
 
2337
2735
 
@@ -2362,7 +2760,8 @@ def build_parser() -> argparse.ArgumentParser:
2362
2760
  n = sub.add_parser("init", help="create your developer key, .imprint/config.json and a "
2363
2761
  "GitHub workflow")
2364
2762
  n.add_argument("path", nargs="?", default=".")
2365
- n.add_argument("--no-ci", action="store_true", help="do not add a GitHub workflow")
2763
+ n.add_argument("--no-ci", action="store_true", help="do not add a build workflow (GitHub Actions, GitLab "
2764
+ "CI or Bitbucket Pipelines, by the remote)")
2366
2765
  n.add_argument("--no-key", action="store_true", help="do not create a developer key")
2367
2766
  n.add_argument("--force", action="store_true", help="overwrite files that already exist")
2368
2767
  n.add_argument("--url", help="server URL for creating the project (else login or "
@@ -2372,10 +2771,15 @@ def build_parser() -> argparse.ArgumentParser:
2372
2771
  n.add_argument("--name", help="the project's display name (default: owner/repo from the "
2373
2772
  "origin remote, else the folder's name); public")
2374
2773
  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`")
2774
+ help="this folder came with another project in .imprint/: make a project "
2775
+ "of its own for this repository, with no link to that one. This is "
2776
+ "what `imprint init` does by itself in a different repository; the "
2777
+ "flag asks for it where the repository cannot be told apart. Refused "
2778
+ "when it is your own project in the same repository: then use "
2779
+ "`imprint key request`")
2780
+ n.add_argument("--link-origin", action="store_true",
2781
+ help="also declare a private link (a LIN1 record) from the new project to "
2782
+ "the project this code came from")
2379
2783
  n.set_defaults(func=cmd_init)
2380
2784
 
2381
2785
  ky = sub.add_parser("key", help="the project's keys: add another device (request, then "
@@ -2391,9 +2795,26 @@ def build_parser() -> argparse.ArgumentParser:
2391
2795
  ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2392
2796
  ky.set_defaults(func=cmd_key)
2393
2797
 
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)")
2798
+ tk = sub.add_parser("token", help="CI tokens for automated builds (CODEIMPRINT_TOKEN): "
2799
+ "create, list, revoke")
2800
+ tk.add_argument("action", choices=["create", "list", "revoke"])
2801
+ tk.add_argument("token", nargs="?", help="revoke: the token's ID (tok_…)")
2802
+ tk.add_argument("--path", default=".", help="create: the project's folder (default: here)")
2803
+ tk.add_argument("--project", help="create: project ID (default: .imprint/config.json)")
2804
+ tk.add_argument("--days", type=int, default=90,
2805
+ help="create: how long the token lasts, 1 to 365 (default 90)")
2806
+ tk.add_argument("--label", help="create: a name for you, for example where it is kept")
2807
+ tk.add_argument("--json", action="store_true", help="list: as JSON")
2808
+ tk.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2809
+ tk.set_defaults(func=cmd_token)
2810
+
2811
+ pj = sub.add_parser("project", help="the project: rename it, or record that its "
2812
+ "repository moved")
2813
+ pj.add_argument("action", choices=["rename", "move"],
2814
+ help="rename: a new display name. move: this repository was renamed, "
2815
+ "transferred or moved to another host and is still the same project")
2816
+ pj.add_argument("name", nargs="?", help="rename: the new name (1-100 characters); "
2817
+ "move: the project's folder (default: here)")
2397
2818
  pj.add_argument("path", nargs="?", default=".")
2398
2819
  pj.add_argument("--private", action="store_true",
2399
2820
  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,60 @@ 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, Bitbucket Pipelines), 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
+ elif env.get("BITBUCKET_BUILD_NUMBER") and env.get("BITBUCKET_REPO_UUID"):
128
+ provider, rid = "bitbucket.org", env["BITBUCKET_REPO_UUID"].strip("{}").lower()
129
+ named = env.get("BITBUCKET_REPO_FULL_NAME")
130
+ if rid:
131
+ here = f"{provider}/{named}".lower() if named else None
132
+ if url and here and url != here: # the job checked out another repository
133
+ provider = rid = None
134
+ elif not url:
135
+ url = here
136
+ if not url and not rid:
137
+ return None
138
+ return {"provider": provider, "id": rid, "url": url, "folder": prefix(root).strip("/")}
139
+
140
+
86
141
  def has_commits(root: Path) -> bool:
87
142
  try:
88
143
  resolve(root, "HEAD")
File without changes
File without changes