canyonos 0.2.3.dev1__py3-none-any.whl → 0.2.3.dev2__py3-none-any.whl

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.
canyonos/auth.py CHANGED
@@ -1,565 +1,130 @@
1
1
  # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
2
  # SPDX-License-Identifier: AGPL-3.0-only
3
3
 
4
- """The keys that sign tokens and the tokens they sign, for `canyonos keys` and
5
- `canyonos token`. A private key under `~/.canyonos/auth/` signs on this machine; the
6
- public keys in its `trusted/` folder are what deploys and the dashboard verify with.
7
- """
4
+ """This machine's API key: one string the user picks with `--api-key`, kept in
5
+ `~/.canyonos/api_key`, that opens every endpoint deployed here and the dashboard API.
6
+ The containers get only its SHA-256 hash. Without a key nothing is checked."""
8
7
 
9
8
  import hashlib
10
- import json
11
- import re
12
- import time
13
- import uuid
14
- from datetime import datetime, timezone
9
+ import os
15
10
  from pathlib import Path
16
11
 
17
- import jwt
18
- from cryptography.exceptions import UnsupportedAlgorithm
19
- from cryptography.hazmat.primitives.asymmetric.ed25519 import (
20
- Ed25519PrivateKey,
21
- Ed25519PublicKey,
22
- )
23
- from cryptography.hazmat.primitives.serialization import (
24
- Encoding,
25
- NoEncryption,
26
- PrivateFormat,
27
- PublicFormat,
28
- load_pem_private_key,
29
- load_pem_public_key,
30
- )
31
-
32
12
  from canyonos import ui
33
- from canyonos.constants import project_root
34
- from canyonos.os_support import (
35
- make_private_dir,
36
- readable_by_others,
37
- shell_command,
38
- write_private_file,
39
- )
13
+ from canyonos.os_support import make_private_dir, write_private_file
40
14
 
41
- # packages/core/canyonos_core/auth.py repeats these on purpose: the CLI cannot import
42
- # canyonos_core, and both sides must agree on them.
43
- ISSUER = "canyonos"
44
- API_AUDIENCE = "canyonos-api"
45
- ALL_PROJECTS = "*"
46
- SCOPES = ("query", "read", "write")
47
- TRUSTED_KEYS_ENV = "CANYONOS_TRUSTED_KEYS"
48
- AUTH_DISABLED_ENV = "CANYONOS_AUTH_DISABLED"
15
+ # packages/core/canyonos_core/auth.py repeats this on purpose: the CLI cannot import
16
+ # canyonos_core, and both sides must agree on it.
17
+ API_KEY_HASH_ENV = "CANYONOS_API_KEY_HASH"
18
+ API_KEY_ENV = "CANYONOS_API_KEY"
49
19
 
50
- DEFAULT_KEY_NAME = "default"
51
- _KEY_NAME = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]*")
52
- _PRIVATE_KEY_MARKER = b"PRIVATE KEY-----"
53
- # The dashboard API container runs as another user and bind-mounts trusted/.
54
- _PUBLIC_DIR_MODE = 0o755
55
- _PUBLIC_FILE_MODE = 0o644
20
+ # The header every printed `curl` sends; the key itself is never printed.
21
+ BEARER_PLACEHOLDER = '-H "Authorization: Bearer <your api key>"'
56
22
 
57
- SKIP_AUTH_WARNING = (
58
- "--dangerous-skip-auth: the endpoint and the dashboard will answer anyone who "
59
- "reaches them, with no token. Use it only for a throwaway run."
23
+ NO_KEY_WARNING = (
24
+ "No API key is set: the endpoint and the dashboard answer anyone who reaches "
25
+ "them. Set one with --api-key <key>."
60
26
  )
61
27
 
62
- _ROTATION = (
63
- "To rotate: make a new key (canyonos keys create --name <new_name>), delete the "
64
- "old key's .pub from trusted/, then redeploy and restart the dashboard "
65
- "(canyonos serve). Every token the old key signed stops working."
66
- )
67
-
68
-
69
- def default_auth_dir() -> Path:
70
- """The folder of keys every command uses without --auth-dir: `~/.canyonos/auth`."""
71
- return Path.home() / ".canyonos" / "auth"
72
-
73
-
74
- def _folder(auth_dir: Path | None) -> Path:
75
- return (auth_dir or default_auth_dir()).absolute()
76
-
77
-
78
- def trusted_dir(auth_dir: Path | None) -> Path:
79
- """The folder of public keys deploys and the dashboard trust, inside `auth_dir`."""
80
- return _folder(auth_dir) / "trusted"
81
-
82
-
83
- def _cli(arguments: str, auth_dir: Path | None) -> str:
84
- """A `canyonos` command to copy, naming --auth-dir when the user picked one."""
85
- if auth_dir is None:
86
- return f"canyonos {arguments}"
87
- return f"canyonos {arguments} --auth-dir {shell_command([str(_folder(auth_dir))])}"
88
28
 
29
+ def api_key_path() -> Path:
30
+ """Where this machine keeps its API key: `~/.canyonos/api_key`."""
31
+ return Path.home() / ".canyonos" / "api_key"
89
32
 
90
- def key_name(value: str) -> str:
91
- """Return `value` when it can name a key file; raise RuntimeError saying which
92
- characters a name may use when it cannot."""
93
- if not _KEY_NAME.fullmatch(value):
94
- raise RuntimeError(
95
- f"{value!r} is not a key name: use only the characters [A-Za-z0-9._-], "
96
- "and do not start it with a dot"
97
- )
98
- return value
99
-
100
-
101
- def key_id(public_pem: str) -> str:
102
- """The short id `keys list` shows and every token carries in its `kid` header: the
103
- first 16 hex characters of the sha256 of the public key's SPKI DER."""
104
- der = load_pem_public_key(public_pem.encode()).public_bytes(
105
- Encoding.DER, PublicFormat.SubjectPublicKeyInfo
106
- )
107
- return hashlib.sha256(der).hexdigest()[:16]
108
-
109
-
110
- def _public_pem(key: Ed25519PublicKey) -> str:
111
- return key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo).decode()
112
33
 
113
-
114
- def _read(path: Path) -> bytes:
34
+ def _stored_api_key() -> str | None:
115
35
  try:
116
- return path.read_bytes()
36
+ key = api_key_path().read_text(encoding="utf-8").strip()
37
+ except FileNotFoundError:
38
+ return None
117
39
  except OSError as error:
118
40
  raise RuntimeError(
119
- f"Could not read {path}: {error.strerror or error}"
41
+ f"Could not read {api_key_path()}: {error.strerror or error}"
120
42
  ) from error
43
+ return key or None
121
44
 
122
45
 
123
- def load_public_key(path: Path) -> str:
124
- """Read the Ed25519 public key in the PEM file at `path` and return it as SPKI PEM;
125
- raise RuntimeError naming the file when it holds anything else, with its own
126
- message for a private key sent by mistake."""
127
- data = _read(path)
128
- try:
129
- key = load_pem_public_key(data)
130
- except (ValueError, UnsupportedAlgorithm):
131
- if _PRIVATE_KEY_MARKER in data:
132
- raise RuntimeError(
133
- f"{path} is a private key: it never leaves the machine that signs. "
134
- "Only its public half, the .pub in trusted/, is shared"
135
- ) from None
136
- raise RuntimeError(
137
- f"{path} is not a public key CanyonOS can read: it takes an Ed25519 "
138
- "public key in PEM (-----BEGIN PUBLIC KEY-----), such as the .pub "
139
- "`canyonos keys create` writes"
140
- ) from None
141
- if not isinstance(key, Ed25519PublicKey):
142
- raise RuntimeError(
143
- f"{path} is not an Ed25519 public key: CanyonOS signs and verifies tokens "
144
- "with Ed25519 keys only"
145
- )
146
- return _public_pem(key)
46
+ def machine_api_key() -> str | None:
47
+ """The API key commands here send and deploys set: `CANYONOS_API_KEY` when it is
48
+ set, else the stored key; None when there is neither."""
49
+ return os.environ.get(API_KEY_ENV, "").strip() or _stored_api_key()
147
50
 
148
51
 
149
- def _named_keys(folder: Path, suffix: str) -> list[Path]:
150
- """The files in `folder` ending in `suffix`, sorted, leaving out dotfiles such as
151
- the `._default.pub` macOS writes beside a copy; raise RuntimeError naming a file
152
- whose name cannot name a key."""
153
- paths = sorted(
154
- path for path in folder.glob(f"*{suffix}") if not path.name.startswith(".")
155
- )
156
- for path in paths:
157
- if not _KEY_NAME.fullmatch(path.stem):
158
- raise RuntimeError(
159
- f"{path} cannot be a key: its name may use only the characters "
160
- "[A-Za-z0-9._-]. Rename it, or move it out of the folder"
161
- )
162
- return paths
52
+ def hash_api_key(key: str | None) -> str:
53
+ """The SHA-256 of `key` in lowercase hex, as the verifiers hold it; "" for no key."""
54
+ if not key:
55
+ return ""
56
+ return hashlib.sha256(key.encode("utf-8")).hexdigest()
163
57
 
164
58
 
165
- def _trusted_files(auth_dir: Path | None) -> list[Path]:
166
- return _named_keys(trusted_dir(auth_dir), ".pub")
167
-
168
-
169
- def trusted_keys(auth_dir: Path | None) -> list[str]:
170
- """The public keys in `trusted/`, as SPKI PEM sorted by file name; raise
171
- RuntimeError naming the first file that is not an Ed25519 public key."""
172
- return [load_public_key(path) for path in _trusted_files(auth_dir)]
173
-
174
-
175
- def require_keys(auth_dir: Path | None) -> list[str]:
176
- """The trusted public keys a deploy hands its verifiers; raise RuntimeError saying
177
- how to make one when there is none."""
178
- keys = trusted_keys(auth_dir)
179
- if not keys:
180
- raise RuntimeError(
181
- f"No key is trusted in {trusted_dir(auth_dir)}, so nothing could query "
182
- f"the workflow. Make one with `{_cli('keys create', auth_dir)}`, then a "
183
- "token with `"
184
- + _cli("token create --scope query --project <project_id>", auth_dir)
185
- + "`. For a throwaway run, --dangerous-skip-auth skips this check"
186
- )
187
- return keys
188
-
189
-
190
- def refuse_keys_in_project(
191
- auth_dir: Path | None, project_folders: list[str] | None = None
192
- ) -> None:
193
- """Raise RuntimeError naming both folders when the keys folder is inside one of
194
- `project_folders`, by default the current folder's project, whose files go into
195
- the image build and the Kubernetes upload."""
196
- folder = _folder(auth_dir).resolve()
197
- for root in project_folders or [project_root()]:
198
- project = Path(root).resolve()
199
- if folder.is_relative_to(project):
200
- raise RuntimeError(
201
- f"The keys folder {folder} is inside the project folder {project}, "
202
- "so its private keys would be copied into the images and the "
203
- "Kubernetes upload. Keep the keys outside the project and pass that "
204
- "folder to --auth-dir"
205
- )
206
-
207
-
208
- def _key_names(folder: Path) -> list[str]:
209
- return [path.stem for path in _named_keys(folder, ".key")]
210
-
211
-
212
- def holds_a_key(auth_dir: Path | None) -> bool:
213
- """True when `auth_dir` holds a private key or a trusted public key, so a first
214
- run knows whether making the default pair would be its first key."""
215
- return bool(_key_names(_folder(auth_dir)) or _trusted_files(auth_dir))
216
-
217
-
218
- def private_key_path(name: str | None, auth_dir: Path | None) -> Path:
219
- """The private key to sign with: the one named `name`, else the only one in
220
- `auth_dir`; raise RuntimeError when it is missing or there are several to pick
221
- from."""
222
- folder = _folder(auth_dir)
223
- names = _key_names(folder)
224
- if name is not None:
225
- if key_name(name) not in names:
226
- raise RuntimeError(
227
- f"No private key named {name} in {folder}; "
228
- + (f"it holds {', '.join(names)}" if names else "it holds none")
229
- )
230
- return folder / f"{name}.key"
231
- if len(names) > 1:
232
- raise RuntimeError(
233
- f"{folder} holds several private keys ({', '.join(names)}): pick the one "
234
- "to sign with, with --key <name>"
235
- )
236
- if not names:
237
- raise RuntimeError(
238
- f"No private key in {folder}: make one with "
239
- f"`{_cli('keys create', auth_dir)}`"
240
- )
241
- return folder / f"{names[0]}.key"
242
-
243
-
244
- def make_key_pair() -> tuple[str, str]:
245
- """Generate an Ed25519 key pair: the private key as PKCS8 PEM and its public half
246
- as SPKI PEM."""
247
- key = Ed25519PrivateKey.generate()
248
- private = key.private_bytes(
249
- Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
250
- ).decode()
251
- return private, _public_pem(key.public_key())
252
-
253
-
254
- def load_key_pair(path: Path) -> tuple[str, str]:
255
- """Read the private key at `path` and return it with its public half, both PEM;
256
- raise RuntimeError naming the file when it is not an Ed25519 private key."""
257
- data = _read(path)
59
+ def _save(key: str) -> None:
60
+ path = api_key_path()
61
+ replaced = _stored_api_key() is not None
258
62
  try:
259
- key = load_pem_private_key(data, password=None)
260
- except (ValueError, TypeError, UnsupportedAlgorithm):
261
- key = None
262
- if not isinstance(key, Ed25519PrivateKey):
263
- raise RuntimeError(
264
- f"{path} is not a private key CanyonOS can sign with: it should be the "
265
- "unencrypted Ed25519 PEM `canyonos keys create` wrote. If it was damaged, "
266
- "make a new key and rotate"
267
- )
268
- return data.decode(), _public_pem(key.public_key())
269
-
270
-
271
- def _write_public_key(path: Path, public_pem: str) -> Path:
272
- try:
273
- path.parent.mkdir(parents=True, exist_ok=True)
274
- path.parent.chmod(_PUBLIC_DIR_MODE)
275
- path.write_text(public_pem, encoding="utf-8")
276
- path.chmod(_PUBLIC_FILE_MODE)
63
+ make_private_dir(path.parent)
64
+ write_private_file(path, key + "\n")
277
65
  except OSError as error:
278
66
  raise RuntimeError(
279
67
  f"Could not write {path}: {error.strerror or error}"
280
68
  ) from error
281
- return path
69
+ if not replaced:
70
+ ui.ok(f"Saved this machine's API key to {path}")
71
+ return
72
+ ui.ok("Replaced this machine's API key.")
73
+ ui.hint(
74
+ "The dashboard and this deployment use the new key; other running "
75
+ "deployments keep the old one until you redeploy them."
76
+ )
282
77
 
283
78
 
284
- def write_key_pair(
285
- name: str, private_pem: str, public_pem: str, auth_dir: Path | None
286
- ) -> tuple[Path, Path]:
287
- """Write the private key to `<name>.key` in `auth_dir`, readable only by you, and
288
- its public half to `trusted/<name>.pub`, readable by all; return both paths."""
289
- folder = _folder(auth_dir)
290
- private = folder / f"{name}.key"
79
+ def _remove() -> None:
291
80
  try:
292
- make_private_dir(folder)
293
- write_private_file(private, private_pem)
81
+ api_key_path().unlink()
82
+ except FileNotFoundError:
83
+ return
294
84
  except OSError as error:
295
85
  raise RuntimeError(
296
- f"Could not write {private}: {error.strerror or error}"
86
+ f"Could not remove {api_key_path()}: {error.strerror or error}"
297
87
  ) from error
298
- return private, _write_public_key(trusted_dir(auth_dir) / f"{name}.pub", public_pem)
88
+ ui.ok("Removed this machine's API key.")
299
89
 
300
90
 
301
- def _audience(scope: str, projects: list[str], all_projects: bool) -> list[str]:
302
- if scope != "query":
303
- for flag, given in (("--project", projects), ("--all-projects", all_projects)):
304
- if given:
305
- raise RuntimeError(
306
- f"{flag} is for --scope query only: a {scope} token is for the "
307
- "dashboard API, which covers every project"
308
- )
309
- return [API_AUDIENCE]
310
- if projects and all_projects:
311
- raise RuntimeError("Pass --project or --all-projects, not both")
312
- if all_projects:
313
- return [ALL_PROJECTS]
314
- if not projects:
91
+ def resolve_api_key(api_key: str | None, no_api_key: bool) -> str | None:
92
+ """Apply `--api-key` (save it, replacing any stored key) or `--no-api-key` (remove
93
+ the stored key) and return the key this deploy or serve sets, warning when there is
94
+ none; raise RuntimeError for an empty `--api-key`."""
95
+ if api_key is not None and not api_key.strip():
315
96
  raise RuntimeError(
316
- "A query token needs the projects it may query: --project <project_id> "
317
- "(repeat it for more) or --all-projects"
318
- )
319
- return list(dict.fromkeys(_project_id(value) for value in projects))
320
-
321
-
322
- def is_project_id(value) -> bool:
323
- """True when `value` is a UUID in the form `canyonos deploy` writes `deployment_id`:
324
- lowercase and hyphenated, since the endpoint compares `aud` with it as written."""
325
- try:
326
- return isinstance(value, str) and value == str(uuid.UUID(value))
327
- except ValueError:
328
- return False
329
-
330
-
331
- def _project_id(value: str) -> str:
332
- """`value` when it is a project ID (see `is_project_id`); raise RuntimeError
333
- saying what one looks like otherwise."""
334
- if not is_project_id(value):
335
- raise RuntimeError(
336
- f"--project {value!r} is not a project ID: a project ID is a lowercase, "
337
- "hyphenated UUID (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx), the `deployment_id` "
338
- "in its deployment.yaml"
339
- )
340
- return value
341
-
342
-
343
- def token_claims(
344
- scope: str, projects: list[str], all_projects: bool, ttl: int | None
345
- ) -> dict:
346
- """The claims of a new token: who it is for (`aud`), what it may do (`scope`) and,
347
- with `ttl` seconds, when it expires; raise RuntimeError when the options do not
348
- make a token."""
349
- if scope not in SCOPES:
350
- raise RuntimeError(f"--scope is one of {', '.join(SCOPES)}, not {scope!r}")
351
- if ttl is not None and ttl <= 0:
352
- raise RuntimeError(f"--ttl must be more than 0 seconds, not {ttl}")
353
- issued = int(time.time())
354
- claims = {
355
- "iss": ISSUER,
356
- "iat": issued,
357
- "jti": uuid.uuid4().hex,
358
- "aud": _audience(scope, projects, all_projects),
359
- "scope": scope,
360
- }
361
- if ttl is not None:
362
- claims["exp"] = issued + ttl
363
- return claims
364
-
365
-
366
- def sign_token(private_pem: str, claims: dict, kid: str) -> str:
367
- """Sign `claims` with the private key into a JWT (EdDSA) carrying `kid`."""
368
- return jwt.encode(claims, private_pem, algorithm="EdDSA", headers={"kid": kid})
369
-
370
-
371
- def query_token(
372
- project_id: str,
373
- key: str | None = None,
374
- auth_dir: Path | None = None,
375
- ttl: int | None = None,
376
- ) -> str:
377
- """Sign a token that may query the project `project_id`, with the private key
378
- named `key` in `auth_dir` (or its only one), for a command that queries the
379
- workflow itself; with `ttl`, it expires that many seconds from now."""
380
- private, public = load_key_pair(private_key_path(key, auth_dir))
381
- return sign_token(
382
- private, token_claims("query", [project_id], False, ttl), key_id(public)
383
- )
384
-
385
-
386
- def api_token(
387
- scope: str,
388
- ttl: int,
389
- key: str | None = None,
390
- auth_dir: Path | None = None,
391
- ) -> str:
392
- """Sign a `read` or `write` token for the dashboard API, expiring `ttl` seconds
393
- from now, with the private key named `key` in `auth_dir` (or its only one), for
394
- a command that calls the dashboard API itself."""
395
- private, public = load_key_pair(private_key_path(key, auth_dir))
396
- return sign_token(private, token_claims(scope, [], False, ttl), key_id(public))
397
-
398
-
399
- def gc_env(keys: list[str], disabled: bool) -> list[str]:
400
- """The `docker run` options that hand the Global Controller the trusted public
401
- keys, and the switch that turns verification off when `disabled`."""
402
- options = ["-e", f"{TRUSTED_KEYS_ENV}={json.dumps(keys)}"]
403
- if disabled:
404
- options += ["-e", f"{AUTH_DISABLED_ENV}=true"]
405
- return options
406
-
407
-
408
- def show_new_key(private: Path, public: Path, auth_dir: Path | None) -> None:
409
- """Show in the terminal where a new key pair is, what each half is for, the
410
- commands that make a token with it, and how to rotate it."""
411
- ui.ok(f"Made the key pair {private.stem}")
412
- ui.say(f"Private key: {private}")
413
- ui.hint(
414
- "It signs your tokens and never leaves this machine: keep it like a password, "
415
- "and never commit or send it."
416
- )
417
- ui.say(f"Public key: {public}")
418
- ui.hint(
419
- "Deploys and the dashboard trust every token a key in this folder signed. "
420
- "Share the .pub, never the .key."
421
- )
422
- ui.blank()
423
- ui.say("Make a token to query a workflow, or to read the dashboard API:")
424
- ui.command(_cli("token create --scope query --project <project_id>", auth_dir))
425
- ui.command(_cli("token create --scope read", auth_dir))
426
- ui.blank()
427
- ui.hint(_ROTATION)
428
-
429
-
430
- def _grants(claims: dict) -> str:
431
- audience = claims["aud"]
432
- return {
433
- "query": (
434
- "query the workflow of every project"
435
- if audience == [ALL_PROJECTS]
436
- else f"query the workflow of project {', '.join(audience)}"
437
- ),
438
- "read": "read the dashboard API (every GET), for every project it shows",
439
- "write": (
440
- "change things through the dashboard API (POST, PUT, DELETE), and "
441
- "read what it can change: project detail, scaling, governance and prompts; "
442
- "every other GET (project list, stats, requests, logs, metrics, "
443
- "monitoring, resources) needs a read token"
444
- ),
445
- }[claims["scope"]]
446
-
447
-
448
- def _expiry(claims: dict) -> str:
449
- if "exp" not in claims:
450
- return "never (no expiry): it works until its key is rotated"
451
- when = datetime.fromtimestamp(claims["exp"], timezone.utc)
452
- return f"{when:%Y-%m-%d %H:%M:%S} UTC, {claims['exp'] - claims['iat']}s from now"
453
-
454
-
455
- def show_token(token: str, claims: dict) -> None:
456
- """Write the token alone to stdout, and on stderr what it grants, how to send it
457
- and how to rotate it, so `$(canyonos token create ...)` captures only the token."""
458
- with ui.to_stderr():
459
- ui.ok(
460
- f"Signed a {claims['scope']} token. It is shown once and stored nowhere: "
461
- "keep it now."
97
+ "--api-key needs a key. To run without one, pass --no-api-key instead"
462
98
  )
463
- ui.result(token)
464
- with ui.to_stderr():
465
- ui.say(f"Grants: {_grants(claims)}")
466
- ui.say(f"Expires: {_expiry(claims)}")
467
- if claims["scope"] == "query":
468
- ui.say("Send it as the header Authorization: Bearer <token>, as in:")
469
- ui.command(
470
- 'curl -X POST <endpoint-url>/<method> -H "Authorization: Bearer '
471
- '<token>" -H "Content-Type: application/json" -d \'<request body>\''
472
- )
473
- else:
474
- ui.say(
475
- "Send it to the dashboard API as the header "
476
- "Authorization: Bearer <token>."
477
- )
478
- ui.hint(_ROTATION)
479
-
480
-
481
- def run_keys_create(name: str, auth_dir: Path | None) -> bool:
482
- """Make a key pair for `canyonos keys create` and show where it is; refuse, without
483
- touching anything, a name whose key or public key already exists."""
484
- name = key_name(name)
485
- for existing in (
486
- _folder(auth_dir) / f"{name}.key",
487
- trusted_dir(auth_dir) / f"{name}.pub",
488
- ):
489
- if existing.exists():
490
- ui.fail(
491
- f"{existing} already exists, and the tokens key {name} signed depend "
492
- "on it. Pick another name with --name, or delete it first to rotate."
493
- )
494
- return False
495
- private, public = write_key_pair(name, *make_key_pair(), auth_dir)
496
- show_new_key(private, public, auth_dir)
497
- return True
498
-
499
-
500
- def run_keys_list(auth_dir: Path | None) -> bool:
501
- """Show the trusted public keys for `canyonos keys list`, one line each with its
502
- name, kid and file, or how to make one when there is none."""
503
- files = _trusted_files(auth_dir)
504
- if not files:
505
- ui.say(f"No key is registered in {trusted_dir(auth_dir)}. Make one with:")
506
- ui.command(_cli("keys create", auth_dir))
507
- return True
508
- kids = [key_id(load_public_key(path)) for path in files]
509
- width = max(len(path.stem) for path in files)
510
- for path, kid in zip(files, kids):
511
- ui.say(f"{path.stem:<{width}} {kid} {path}")
512
- return True
513
-
514
-
515
- def run_keys_trust(file: str, auth_dir: Path | None) -> bool:
516
- """Register someone's public key for `canyonos keys trust`, as `trusted/<name>.pub`
517
- whatever its suffix; refuse one that is not an Ed25519 public key, or whose name
518
- is taken."""
519
- source = Path(file)
520
- public = load_public_key(source)
521
- destination = trusted_dir(auth_dir) / f"{key_name(source.stem)}.pub"
522
- if destination.exists():
523
- ui.fail(
524
- f"{destination} already exists: delete it first to replace that key, or "
525
- f"rename {source.name} to trust it under another name."
526
- )
527
- return False
528
- _write_public_key(destination, public)
529
- ui.ok(f"Trusted {source} as {destination}")
530
- ui.say(f"Key ID: {key_id(public)}")
531
- ui.hint(
532
- "Deploys and the dashboard read trusted/ when they start: redeploy and restart "
533
- "the dashboard (canyonos serve) for the key to count."
534
- )
535
- return True
536
-
537
-
538
- def run_token_create(
539
- scope: str,
540
- projects: list[str],
541
- all_projects: bool,
542
- ttl: int | None,
543
- key: str | None,
544
- auth_dir: Path | None,
545
- ) -> bool:
546
- """Sign a token for `canyonos token create` and show it once, warning when the key
547
- is readable by others or no deploy trusts it."""
548
- claims = token_claims(scope, projects, all_projects, ttl)
549
- path = private_key_path(key, auth_dir)
550
- private, public = load_key_pair(path)
551
- token = sign_token(private, claims, key_id(public))
552
- if readable_by_others(path):
553
- ui.warn(
554
- f"{path} is readable by other users of this machine, and whoever reads it "
555
- f"can sign tokens. Run: {shell_command(['chmod', '600', str(path)])}"
556
- )
557
- trusted = trusted_dir(auth_dir) / f"{path.stem}.pub"
558
- if not trusted.is_file():
559
- ui.warn(
560
- f"Signed, but no deploy trusts this key: {trusted} is missing, so "
561
- "workflows and the dashboard refuse this token. Put the public key back "
562
- "with `canyonos keys trust <file>` and redeploy."
563
- )
564
- show_token(token, claims)
565
- return True
99
+ if no_api_key:
100
+ _remove()
101
+ key = None
102
+ elif api_key is not None:
103
+ key = api_key.strip()
104
+ _save(key)
105
+ else:
106
+ key = machine_api_key()
107
+ if key is None:
108
+ ui.warn(NO_KEY_WARNING)
109
+ return key
110
+
111
+
112
+ def auth_header(key: str | None = None) -> dict[str, str]:
113
+ """The header that sends `key`, by default this machine's API key; none when there
114
+ is no key."""
115
+ key = key or machine_api_key()
116
+ if not key:
117
+ return {}
118
+ return {"Authorization": f"Bearer {key}"}
119
+
120
+
121
+ def curl_auth(keyed: bool) -> str:
122
+ """The placeholder header a printed `curl` shows when the deploy is `keyed`, else
123
+ ""."""
124
+ return f" {BEARER_PLACEHOLDER}" if keyed else ""
125
+
126
+
127
+ def gc_env(key: str | None) -> list[str]:
128
+ """The `docker run` options that hand the Global Controller the hash of `key`; an
129
+ empty hash when there is no key, so nothing is checked."""
130
+ return ["-e", f"{API_KEY_HASH_ENV}={hash_api_key(key)}"]