codeimprint 0.5.0a19__tar.gz → 0.5.0a23__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.0a19 → codeimprint-0.5.0a23}/CHANGELOG.md +75 -0
  2. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/PKG-INFO +4 -3
  3. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/README.pypi.md +3 -2
  4. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/pyproject.toml +1 -1
  5. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/__init__.py +1 -1
  6. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/api.py +41 -6
  7. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/cli.py +275 -20
  8. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/gitrepo.py +4 -1
  9. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/imprint_file.py +5 -5
  10. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/.gitignore +0 -0
  11. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/LICENSE +0 -0
  12. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/NOTICE +0 -0
  13. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint/__init__.py +0 -0
  14. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint/__main__.py +0 -0
  15. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/__main__.py +0 -0
  16. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/chainseal.py +0 -0
  17. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/config.py +0 -0
  18. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/linecount.py +0 -0
  19. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/ownership.py +0 -0
  20. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/project.py +0 -0
  21. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/receipt.py +0 -0
  22. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a19 → codeimprint-0.5.0a23}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,80 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a23 — `imprint verify` says VERIFIED [CIM-BE-36-v2]
4
+
5
+ - **Changed: the result line of `imprint verify`** reads `Result VERIFIED`, `Result
6
+ NOT VERIFIED (N check(s) failed)` or `Result NOT VERIFIED with --strict (N
7
+ warning(s))`. Before, it said VALID / NOT VALID. "Valid" is now used for a seal's validity
8
+ only (`Validity Valid until <date>`, with `--online`), so the two are never confused.
9
+ **Exit codes and `--json` are unchanged** (`"valid": true` or `false` stays as it is). A
10
+ script that reads the text `Result VALID` must read `Result VERIFIED` instead; a
11
+ script that uses the exit code or `--json` needs no change.
12
+ - Tests: `tests/test_certificate.py`.
13
+
14
+ ## 0.5.0a22 — Seal certificate, live validity, the server's own badge [CIM-BE-36-v1]
15
+
16
+ For engine 0.7.0a26. Older engines still work, except for `imprint certificate` (they answer
17
+ that the seal is not found) and the validity lines (not shown).
18
+
19
+ - **New: `imprint certificate <fingerprint ID> [-o file.pdf]`.** Downloads the seal
20
+ certificate (a one-page PDF made by the server) and saves it as `certificate-<ID>.pdf` in
21
+ the current folder, or where `-o` says. It is for the owner of the seal's project: signed in
22
+ with `imprint login`, or with that project's CI token. Without a sign-in the command says so
23
+ and asks the server nothing; when the server has no such seal, or the seal is not one of
24
+ your projects', it says that (the server answers both alike, on purpose).
25
+ - **Changed: `imprint verify --online`** adds two lines under the result, in the server's own
26
+ words: `Integrity Sealed <date>, unchanged since` and `Validity Valid until <date>` (or
27
+ `Validity lapsed on <date>`). Validity is worked out live by the server and is not part of
28
+ the signed seal, so offline nothing is shown, and the checks and the exit code are
29
+ unchanged. `--json` adds `validity` (the server's answer, or `null`).
30
+ - **Changed: the README badge that `imprint seal` prints** is the server's own badge
31
+ (`<server>/api/v1/public/imprints/<ID>/badge.svg`): it shows the project's name, when you
32
+ made it public, and the seal's state. Before, it was a static badge from a third-party
33
+ badge service that showed the ID. A badge already in a README keeps working; replace it
34
+ with the new line when you like.
35
+ - No engine or algorithm code: the client downloads and prints. Tests:
36
+ `tests/test_certificate.py`, `tests/test_branding.py`.
37
+
38
+ ## 0.5.0a21 — A CI token's check is for its own project [CIM-BE-35-v2]
39
+
40
+ For engine 0.7.0a25, where a CI token checks against, and signs, seals of its own project
41
+ only. Nothing else changes; older engines still work.
42
+
43
+ - **Changed: `imprint check` with a CI token.** When the server does not know the reference
44
+ (with a CI token that includes every seal outside the token's project), the message now
45
+ says so and what to do: use one of the project's own Imprint IDs (`imprint chain`), or a
46
+ token for the project the reference belongs to. The exit code is unchanged.
47
+ - No new command. Tests: `tests/test_tokens.py`.
48
+
49
+ ## 0.5.0a20 — CI tokens for automated builds [CIM-BE-35-v1]
50
+
51
+ For engine 0.7.0a24. Older engines still work, except for the new `imprint token` commands.
52
+
53
+ A build seals with a CI token of your own account. You never need the server's API token.
54
+
55
+ - **New: `imprint token`.**
56
+ - `imprint token create` in the project's folder (signed in) prints a token for that one
57
+ project, **once**. `--days` sets how long it lasts (default 90, at most 365; it always
58
+ expires), `--label` names it for you, `--project` picks another project.
59
+ - `imprint token list` shows your tokens: ID, project, status, dates, last use. Never the
60
+ token. `--json` for a script.
61
+ - `imprint token revoke <id>` ends one. A build that still uses it warns and goes on.
62
+ - **Changed: a CI token in `CODEIMPRINT_TOKEN` is your account, never the operator.** Before,
63
+ any token there was treated as the server's API token; `imprint init --new-project` now
64
+ refuses your own project with a CI token as it does with a sign-in. When the server does
65
+ not accept the token (expired or revoked) the message says to make a new one.
66
+ - **Changed: the build files `imprint init` writes.**
67
+ - The GitHub Actions workflow now says how to set each secret: `CODEIMPRINT_TOKEN` is a CI
68
+ token from `imprint token create`.
69
+ - **New:** a repository on GitLab gets `.gitlab-ci.yml`, one on Bitbucket gets
70
+ `bitbucket-pipelines.yml`, with the same instructions. An existing pipeline file is never
71
+ touched, not even with `--force`: `init` says to add the job from the README.
72
+ - **Changed: GitLab CI and Bitbucket Pipelines count as builds**, like GitHub Actions: a seal
73
+ that cannot be made there is a warning and exit 0. A Bitbucket build also names its
74
+ repository's ID.
75
+ - New API calls used: `POST` and `GET /api/v1/me/tokens`, `POST /api/v1/me/tokens/{id}/revoke`.
76
+ - Tests: `tests/test_tokens.py`.
77
+
3
78
  ## 0.5.0a19 — A different repository needs its own seal [CIM-BE-34-v1]
4
79
 
5
80
  For engine 0.7.0a23. Older engines still work: they ignore the new field, and the checks
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a19
3
+ Version: 0.5.0a23
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.0a19"
9
+ version = "0.5.0a23"
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.0a19"
8
+ __version__ = "0.5.0a23"
@@ -73,14 +73,24 @@ 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
 
81
82
  def _request(self, method: str, path: str, body: bytes | None = None,
82
83
  content_type: str | None = None) -> dict:
83
- headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
84
+ raw = self._open(method, path, body, content_type)
85
+ try:
86
+ return json.loads(raw.decode("utf-8"))
87
+ except ValueError as exc:
88
+ raise NetworkError(f"{self.url} did not answer with JSON") from exc
89
+
90
+ def _open(self, method: str, path: str, body: bytes | None = None,
91
+ content_type: str | None = None, accept: str = "application/json") -> bytes:
92
+ """The answer's bytes. An error answer raises ApiError with the server's own code."""
93
+ headers = {"Accept": accept, "User-Agent": USER_AGENT}
84
94
  if content_type:
85
95
  headers["Content-Type"] = content_type
86
96
  if self.token:
@@ -90,7 +100,7 @@ class Client:
90
100
  req = urllib.request.Request(self.url + path, data=body, headers=headers, method=method)
91
101
  try:
92
102
  with _OPENER.open(req, timeout=self.timeout) as res:
93
- return json.loads(res.read().decode("utf-8"))
103
+ return res.read()
94
104
  except urllib.error.HTTPError as exc:
95
105
  self._access_problem(exc)
96
106
  code, message = "http_error", exc.reason or "Request failed"
@@ -103,8 +113,6 @@ class Client:
103
113
  except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
104
114
  reason = getattr(exc, "reason", exc)
105
115
  raise NetworkError(f"could not reach {self.url}: {reason}") from exc
106
- except ValueError as exc:
107
- raise NetworkError(f"{self.url} did not answer with JSON") from exc
108
116
 
109
117
  def _access_problem(self, exc: urllib.error.HTTPError) -> None:
110
118
  """Turn Cloudflare Access's answers (a redirect to its login, or its own 401/403
@@ -195,6 +203,18 @@ class Client:
195
203
  return self._json("POST", f"/api/v1/projects/{quote(project)}/keys/requests",
196
204
  {"public_key": public_key, "signature": signature, "label": label})
197
205
 
206
+ # CI tokens of the signed-in account (engine 0.7.0a24+) ------------------------------------
207
+ def create_token(self, project: str, days: int = 90, label: str | None = None) -> dict:
208
+ return self._json("POST", "/api/v1/me/tokens",
209
+ {"project": project, "days": days,
210
+ **({"label": label} if label else {})})
211
+
212
+ def tokens(self) -> list[dict]:
213
+ return self._request("GET", "/api/v1/me/tokens").get("items") or []
214
+
215
+ def revoke_token(self, token_id: str) -> dict:
216
+ return self._json("POST", f"/api/v1/me/tokens/{quote(token_id)}/revoke", {})
217
+
198
218
  def lineage(self, record_id: str) -> dict:
199
219
  """A lineage record (LIN1): its public record and, when this account may see it,
200
220
  the opening of its commitment (engine 0.7.0a21+)."""
@@ -309,6 +329,21 @@ class Client:
309
329
  def public_imprint(self, imprint_id: str) -> dict:
310
330
  return self._request("GET", f"/api/v1/public/imprints/{quote(imprint_id)}")
311
331
 
332
+ # a seal's validity and certificate (engine 0.7.0a26) -----------------------------------
333
+ def validity(self, imprint_id: str) -> dict:
334
+ """A seal's validity now, as the server works it out: state, valid until, timeline
335
+ and the wording to show."""
336
+ return self._request("GET", f"/api/v1/public/imprints/{quote(imprint_id)}/validity")
337
+
338
+ def certificate(self, seal_id: str) -> bytes:
339
+ """A seal's certificate (PDF). The server gives it to the owner of the seal's project
340
+ and answers everyone else like a seal that does not exist."""
341
+ pdf = self._open("GET", f"/api/v1/seals/{quote(seal_id)}/certificate.pdf",
342
+ accept="application/pdf")
343
+ if not pdf.startswith(b"%PDF-"):
344
+ raise NetworkError(f"{self.url} did not answer with a PDF")
345
+ return pdf
346
+
312
347
  # ownership claims and coverage (engine 0.7.0a4) --------------------------------------
313
348
  def claim_prepare(self, project: str, document: dict) -> dict:
314
349
  return self._json("POST", f"/api/v1/projects/{quote(project)}/claims/prepare",
@@ -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
 
@@ -511,8 +626,12 @@ def cmd_init(args) -> int:
511
626
  else:
512
627
  write(cfg_path, json.dumps(cfg, indent=2) + "\n")
513
628
  if not args.no_ci:
514
- write(root / ".github" / "workflows" / "codeimprint.yml",
515
- 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)
516
635
  for rel in written:
517
636
  _say(f"created {rel}")
518
637
  for rel in skipped:
@@ -1711,7 +1830,7 @@ def _finish(args, client: Client, root: Path, result: dict, keys: list,
1711
1830
  f"Receipt {rec_path}",
1712
1831
  _verify_line(iid, hub, out))
1713
1832
  if hub:
1714
- _say("", "README badge:", imprint_file.badge(iid, hub))
1833
+ _say("", "README badge:", imprint_file.badge(iid, hub, client.url))
1715
1834
  _say("", SEAL_NOTE)
1716
1835
  _step_summary(iid, rec, stamps, signer, hub)
1717
1836
  return 0
@@ -2116,6 +2235,57 @@ def cmd_key(args) -> int:
2116
2235
 
2117
2236
 
2118
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
+
2119
2289
  def cmd_project(args) -> int:
2120
2290
  if args.action == "move":
2121
2291
  return _project_move(args)
@@ -2263,6 +2433,12 @@ def cmd_check(args) -> int:
2263
2433
  if exc.status in {401, 403, 429} or exc.status >= 500:
2264
2434
  _warn(_explain(client, exc, "check skipped"))
2265
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
2266
2442
  raise Abort(f"check failed: {exc}") from exc
2267
2443
  if args.output:
2268
2444
  Path(args.output).write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
@@ -2381,6 +2557,55 @@ def _trusted_keys(args, root: Path, client: Client | None,
2381
2557
  return []
2382
2558
 
2383
2559
 
2560
+ def _validity(client: Client, iid: str) -> dict | None:
2561
+ """A seal's validity now, from the server (`imprint verify --online`). None from a server
2562
+ that does not have it (before 0.7.0a26) or cannot be reached: validity is worked out
2563
+ live by the server, so offline there is nothing to show."""
2564
+ try:
2565
+ state = client.validity(iid)
2566
+ return state if isinstance(state.get("wording"), dict) else None
2567
+ except (ApiError, NetworkError, AttributeError):
2568
+ return None
2569
+
2570
+
2571
+ def cmd_certificate(args) -> int:
2572
+ """`imprint certificate IMP1-… [-o file.pdf]`: download a seal's certificate (PDF)."""
2573
+ if not imprint_file.is_valid_id(args.seal):
2574
+ raise Abort(f"not a fingerprint ID (IMP1-…): {args.seal}")
2575
+ iid = imprint_file.clean_id(args.seal)
2576
+ client = _client(args, _server_from_project(Path(".")))
2577
+ # The server answers everyone but the owner like a seal that does not exist, so say here
2578
+ # what it will not say: that nobody is signed in.
2579
+ if client.auth == "none":
2580
+ raise Abort(f"you are not signed in to {client.url}: run `imprint login` first. A "
2581
+ "seal's certificate is for the owner of its project.")
2582
+ if client.auth == "expired":
2583
+ raise Abort(f"your sign-in to {client.url} has expired: run `imprint login` again.")
2584
+ try:
2585
+ pdf = client.certificate(iid)
2586
+ except ApiError as exc:
2587
+ if exc.status == 404:
2588
+ scope = (" A CI token reaches the seals of its own project only."
2589
+ if client.auth == "ci" else "")
2590
+ raise Abort(f"no certificate for {iid}: {client.url} has no such seal, or it is "
2591
+ f"not a seal of one of your projects.{scope} If your sign-in has "
2592
+ "ended, run `imprint login` again.") from exc
2593
+ raise Abort(_explain(client, exc, f"cannot download the certificate for {iid}")) \
2594
+ from exc
2595
+ except NetworkError as exc:
2596
+ raise Abort(str(exc)) from exc
2597
+ out = Path(args.out or f"certificate-{iid}.pdf")
2598
+ try:
2599
+ out.parent.mkdir(parents=True, exist_ok=True)
2600
+ out.write_bytes(pdf)
2601
+ except OSError as exc:
2602
+ raise Abort(f"cannot write {out}: {exc}") from exc
2603
+ _say(f"Certificate {out}",
2604
+ " A summary of the seal record; the record itself is the evidence "
2605
+ f"(`imprint verify {iid}`).")
2606
+ return 0
2607
+
2608
+
2384
2609
  def _server_from_project(root: Path) -> str | None:
2385
2610
  path = root / project.CONFIG_DIR / trust.PROJECT_KEYS
2386
2611
  try:
@@ -2392,7 +2617,7 @@ def _server_from_project(root: Path) -> str | None:
2392
2617
  def _fetch_lineage(client: Client, record_id: str) -> tuple[dict, dict | None]:
2393
2618
  """A lineage record and, for an account that may see it, its opening. Without a
2394
2619
  sign-in (or on an older server) the public record alone."""
2395
- if client.auth in ("token", "session"):
2620
+ if client.auth in ("token", "session"): # not a CI token: it only seals
2396
2621
  try:
2397
2622
  answer = client.lineage(record_id)
2398
2623
  return answer["receipt"], answer.get("opening")
@@ -2485,6 +2710,7 @@ def cmd_verify(args) -> int:
2485
2710
  doc, rec, root = _load_target(args)
2486
2711
  found = getattr(args, "found_opening", None)
2487
2712
  checks: list[receipt.Check] = []
2713
+ state = None # the seal's validity now (--online only)
2488
2714
  client = _client(args, _server_from_project(root)) if args.online else None
2489
2715
  if rec is None and client is not None:
2490
2716
  iid = imprint_file.clean_id(args.target) if doc is None else (
@@ -2527,6 +2753,8 @@ def cmd_verify(args) -> int:
2527
2753
  except (ApiError, NetworkError, KeyError) as exc:
2528
2754
  checks.append(receipt.Check("log consistency", receipt.FAIL,
2529
2755
  f"cannot check the live log: {exc}"))
2756
+ if client is not None and "record" not in rec:
2757
+ state = _validity(client, iid)
2530
2758
  if here is not None:
2531
2759
  checks.append(here)
2532
2760
  if elsewhere: # say nothing about where the seal does belong
@@ -2544,16 +2772,21 @@ def cmd_verify(args) -> int:
2544
2772
  "issued_for_this_repository": (
2545
2773
  False if elsewhere else True if any(
2546
2774
  c.name == "repository" for c in checks) else None),
2775
+ "validity": state if valid else None,
2547
2776
  "checks": [c.as_dict() for c in checks]}, indent=2))
2548
2777
  else:
2549
2778
  _say(f"{'Record ' if rec and 'record' in rec else 'Imprint'} {iid}", "")
2550
2779
  for c in checks:
2551
2780
  _say(f"{c.status:<5} {c.name:<20} {c.detail}")
2552
- verdict = ("VALID" if valid else
2553
- f"NOT VALID ({len(failed)} check(s) failed)" if failed else
2554
- f"NOT VALID with --strict ({len(warned)} warning(s))")
2555
- _say("", f"Result {verdict}", *([f" {NOT_ISSUED}"] if elsewhere else []),
2556
- "", SEAL_NOTE)
2781
+ # "Verified" is about the checks. "Valid" is kept for a seal's validity alone.
2782
+ verdict = ("VERIFIED" if valid else
2783
+ f"NOT VERIFIED ({len(failed)} check(s) failed)" if failed else
2784
+ f"NOT VERIFIED with --strict ({len(warned)} warning(s))")
2785
+ _say("", f"Result {verdict}", *([f" {NOT_ISSUED}"] if elsewhere else []))
2786
+ if valid and state: # the server's own wording, as the seal page shows
2787
+ _say(f"Integrity {state['wording']['integrity']}",
2788
+ f"Validity {state['wording']['validity']}")
2789
+ _say("", SEAL_NOTE)
2557
2790
  return 0 if valid else 1
2558
2791
 
2559
2792
 
@@ -2584,7 +2817,8 @@ def build_parser() -> argparse.ArgumentParser:
2584
2817
  n = sub.add_parser("init", help="create your developer key, .imprint/config.json and a "
2585
2818
  "GitHub workflow")
2586
2819
  n.add_argument("path", nargs="?", default=".")
2587
- n.add_argument("--no-ci", action="store_true", help="do not add a GitHub workflow")
2820
+ n.add_argument("--no-ci", action="store_true", help="do not add a build workflow (GitHub Actions, GitLab "
2821
+ "CI or Bitbucket Pipelines, by the remote)")
2588
2822
  n.add_argument("--no-key", action="store_true", help="do not create a developer key")
2589
2823
  n.add_argument("--force", action="store_true", help="overwrite files that already exist")
2590
2824
  n.add_argument("--url", help="server URL for creating the project (else login or "
@@ -2618,6 +2852,19 @@ def build_parser() -> argparse.ArgumentParser:
2618
2852
  ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2619
2853
  ky.set_defaults(func=cmd_key)
2620
2854
 
2855
+ tk = sub.add_parser("token", help="CI tokens for automated builds (CODEIMPRINT_TOKEN): "
2856
+ "create, list, revoke")
2857
+ tk.add_argument("action", choices=["create", "list", "revoke"])
2858
+ tk.add_argument("token", nargs="?", help="revoke: the token's ID (tok_…)")
2859
+ tk.add_argument("--path", default=".", help="create: the project's folder (default: here)")
2860
+ tk.add_argument("--project", help="create: project ID (default: .imprint/config.json)")
2861
+ tk.add_argument("--days", type=int, default=90,
2862
+ help="create: how long the token lasts, 1 to 365 (default 90)")
2863
+ tk.add_argument("--label", help="create: a name for you, for example where it is kept")
2864
+ tk.add_argument("--json", action="store_true", help="list: as JSON")
2865
+ tk.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2866
+ tk.set_defaults(func=cmd_token)
2867
+
2621
2868
  pj = sub.add_parser("project", help="the project: rename it, or record that its "
2622
2869
  "repository moved")
2623
2870
  pj.add_argument("action", choices=["rename", "move"],
@@ -2841,6 +3088,14 @@ def build_parser() -> argparse.ArgumentParser:
2841
3088
  ln.add_argument("--json", action="store_true")
2842
3089
  ln.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2843
3090
  ln.set_defaults(func=cmd_lineage)
3091
+
3092
+ ce = sub.add_parser("certificate", help="download a seal's certificate (PDF): for the "
3093
+ "owner of the seal's project")
3094
+ ce.add_argument("seal", metavar="FINGERPRINT_ID", help="the seal's ID (IMP1-…)")
3095
+ ce.add_argument("-o", "--out", metavar="FILE",
3096
+ help="where to save it (default: certificate-<ID>.pdf in this folder)")
3097
+ ce.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3098
+ ce.set_defaults(func=cmd_certificate)
2844
3099
  return p
2845
3100
 
2846
3101
 
@@ -111,7 +111,7 @@ def remote_identity(url: str | None) -> str | None:
111
111
  def identity(root: Path) -> dict | None:
112
112
  """Which repository this folder is in, as ``{provider, id, url, folder}``: the
113
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.
114
+ CI, Bitbucket Pipelines), the origin remote in its canonical form, and the folder inside the repository.
115
115
  None when there is neither an ID nor a remote (a local repository). The server keeps
116
116
  it only as keyed hashes."""
117
117
  env = os.environ
@@ -124,6 +124,9 @@ def identity(root: Path) -> dict | None:
124
124
  elif env.get("GITLAB_CI") == "true" and env.get("CI_PROJECT_ID"):
125
125
  provider, rid = (env.get("CI_SERVER_HOST") or "gitlab.com").lower(), env["CI_PROJECT_ID"]
126
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")
127
130
  if rid:
128
131
  here = f"{provider}/{named}".lower() if named else None
129
132
  if url and here and url != here: # the job checked out another repository
@@ -122,8 +122,8 @@ def save(doc: dict, path: str | Path) -> Path:
122
122
  return out
123
123
 
124
124
 
125
- def badge(imprint_id_text: str, public_url: str) -> str:
126
- """README badge Markdown (rust, B23C0C), linking to the seal's page on the hub."""
127
- shield = imprint_id_text.replace("-", "--")
128
- return (f"[![Sealed by CodeImprint](https://img.shields.io/badge/CodeImprint-{shield}-B23C0C)]"
129
- f"({public_url.rstrip('/')}/i/{imprint_id_text})")
125
+ def badge(imprint_id_text: str, public_url: str, server_url: str) -> str:
126
+ """README badge Markdown: the server's own badge for the seal (the project's public name
127
+ and the seal's state, drawn by the server), linking to the seal's page on the hub."""
128
+ return (f"[![Sealed by CodeImprint]({server_url.rstrip('/')}/api/v1/public/imprints/"
129
+ f"{imprint_id_text}/badge.svg)]({public_url.rstrip('/')}/i/{imprint_id_text})")
File without changes
File without changes