codeimprint 0.5.0a19__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.0a19 → codeimprint-0.5.0a21}/CHANGELOG.md +40 -0
  2. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/PKG-INFO +4 -3
  3. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/README.pypi.md +3 -2
  4. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/pyproject.toml +1 -1
  5. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/__init__.py +1 -1
  6. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/api.py +15 -2
  7. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/cli.py +204 -14
  8. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/gitrepo.py +4 -1
  9. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/.gitignore +0 -0
  10. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/LICENSE +0 -0
  11. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/NOTICE +0 -0
  12. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint/__init__.py +0 -0
  13. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint/__main__.py +0 -0
  14. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/__main__.py +0 -0
  15. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/chainseal.py +0 -0
  16. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/config.py +0 -0
  17. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/imprint_file.py +0 -0
  18. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/linecount.py +0 -0
  19. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/ownership.py +0 -0
  20. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/project.py +0 -0
  21. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/receipt.py +0 -0
  22. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/records.py +0 -0
  23. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/timestamp.py +0 -0
  24. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/transparency.py +0 -0
  25. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/trust.py +0 -0
  26. {codeimprint-0.5.0a19 → codeimprint-0.5.0a21}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,45 @@
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
+
3
43
  ## 0.5.0a19 — A different repository needs its own seal [CIM-BE-34-v1]
4
44
 
5
45
  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.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.0a19"
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.0a19"
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
 
@@ -195,6 +196,18 @@ class Client:
195
196
  return self._json("POST", f"/api/v1/projects/{quote(project)}/keys/requests",
196
197
  {"public_key": public_key, "signature": signature, "label": label})
197
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
+
198
211
  def lineage(self, record_id: str) -> dict:
199
212
  """A lineage record (LIN1): its public record and, when this account may see it,
200
213
  the opening of its commitment (engine 0.7.0a21+)."""
@@ -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:
@@ -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")
@@ -2392,7 +2568,7 @@ def _server_from_project(root: Path) -> str | None:
2392
2568
  def _fetch_lineage(client: Client, record_id: str) -> tuple[dict, dict | None]:
2393
2569
  """A lineage record and, for an account that may see it, its opening. Without a
2394
2570
  sign-in (or on an older server) the public record alone."""
2395
- if client.auth in ("token", "session"):
2571
+ if client.auth in ("token", "session"): # not a CI token: it only seals
2396
2572
  try:
2397
2573
  answer = client.lineage(record_id)
2398
2574
  return answer["receipt"], answer.get("opening")
@@ -2584,7 +2760,8 @@ def build_parser() -> argparse.ArgumentParser:
2584
2760
  n = sub.add_parser("init", help="create your developer key, .imprint/config.json and a "
2585
2761
  "GitHub workflow")
2586
2762
  n.add_argument("path", nargs="?", default=".")
2587
- 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)")
2588
2765
  n.add_argument("--no-key", action="store_true", help="do not create a developer key")
2589
2766
  n.add_argument("--force", action="store_true", help="overwrite files that already exist")
2590
2767
  n.add_argument("--url", help="server URL for creating the project (else login or "
@@ -2618,6 +2795,19 @@ def build_parser() -> argparse.ArgumentParser:
2618
2795
  ky.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
2619
2796
  ky.set_defaults(func=cmd_key)
2620
2797
 
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
+
2621
2811
  pj = sub.add_parser("project", help="the project: rename it, or record that its "
2622
2812
  "repository moved")
2623
2813
  pj.add_argument("action", choices=["rename", "move"],
@@ -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
File without changes
File without changes