canyonos 0.2.2__tar.gz → 0.2.3.dev1__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 (103) hide show
  1. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/PKG-INFO +4 -4
  2. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/README.md +2 -3
  3. canyonos-0.2.3.dev1/canyonos/auth.py +565 -0
  4. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/aws_provision.py +5 -2
  5. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/clean.py +22 -22
  6. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/config.py +4 -37
  7. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/constants.py +49 -23
  8. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/convert.py +2 -2
  9. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/dashboard.compose.yml +20 -5
  10. canyonos-0.2.3.dev1/canyonos/dashboard_registration.py +164 -0
  11. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/dashboard_stack.py +101 -38
  12. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/deploy.py +148 -97
  13. canyonos-0.2.3.dev1/canyonos/deployment.py +273 -0
  14. canyonos-0.2.3.dev1/canyonos/deployment.yaml +14 -0
  15. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/doctor.py +18 -37
  16. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/env.py +3 -2
  17. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/gc.py +14 -4
  18. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/init.py +46 -39
  19. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/kubernetes_target.py +118 -46
  20. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/logs.py +2 -2
  21. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app.py +14 -1
  22. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/agents/workflow.py.tmpl +1 -1
  23. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/config/workflow_config.yaml +5 -11
  24. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/os_support/__init__.py +2 -0
  25. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/os_support/_posix.py +5 -0
  26. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/os_support/_windows.py +6 -0
  27. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/ports.py +7 -7
  28. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/quickstart.py +111 -57
  29. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/resources.py +44 -30
  30. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/selection.py +37 -37
  31. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/serve.py +43 -11
  32. canyonos-0.2.3.dev1/canyonos/starters/helloworld/README.md +154 -0
  33. canyonos-0.2.3.dev1/canyonos/starters/helloworld/deployment.yaml +15 -0
  34. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/helloworld}/helloworld/agents/workflow.py.tmpl +5 -3
  35. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/helloworld}/helloworld/config/workflow_config.yaml +3 -12
  36. canyonos-0.2.3.dev1/canyonos/starters/portfolio/deployment.yaml +23 -0
  37. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/agents/workflow.py.tmpl +6 -4
  38. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/config/workflow_config.yaml +3 -20
  39. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/stop.py +96 -99
  40. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/sync.py +89 -85
  41. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/target.py +1 -1
  42. canyonos-0.2.3.dev1/canyonos/test.py +375 -0
  43. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/ui.py +34 -4
  44. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/upgrade.py +1 -1
  45. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/validate.py +25 -3
  46. canyonos-0.2.3.dev1/canyonos/verify.py +77 -0
  47. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos.egg-info/PKG-INFO +4 -4
  48. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos.egg-info/SOURCES.txt +24 -20
  49. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos.egg-info/requires.txt +1 -0
  50. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/cli.py +220 -38
  51. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/pyproject.toml +3 -1
  52. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/tests/test_ports.py +7 -7
  53. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/utils/help_screen.py +21 -8
  54. canyonos-0.2.2/canyonos/dashboard_registration.py +0 -126
  55. canyonos-0.2.2/canyonos/project.py +0 -227
  56. canyonos-0.2.2/canyonos/starters/helloworld/README.md +0 -143
  57. canyonos-0.2.2/canyonos/test.py +0 -515
  58. canyonos-0.2.2/canyonos/verify.py +0 -127
  59. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/__init__.py +0 -0
  60. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/contact.py +0 -0
  61. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/dev_machine.py +0 -0
  62. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/docker_cmd.py +0 -0
  63. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/feedback.py +0 -0
  64. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/forwards.py +0 -0
  65. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/kubernetes_local.py +0 -0
  66. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/.env.example +0 -0
  67. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/.gitignore +0 -0
  68. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/agents/my_agent.py.tmpl +0 -0
  69. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/config/llms.yaml +0 -0
  70. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/config/policy.yaml +0 -0
  71. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/config/prompts.yaml +0 -0
  72. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/new_app_template/config/scaling.yaml +0 -0
  73. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/port_utils.py +0 -0
  74. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/provision.py +0 -0
  75. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/helloworld}/helloworld/agents/hello_agent.py.tmpl +0 -0
  76. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/helloworld}/helloworld/config/policy.yaml +0 -0
  77. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/helloworld}/helloworld/config/test_query.txt +0 -0
  78. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/.env +0 -0
  79. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/.env.example +0 -0
  80. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/agents/advisor_agent.py.tmpl +0 -0
  81. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/agents/intent_agent.py.tmpl +0 -0
  82. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/agents/metrics_agent.py.tmpl +0 -0
  83. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/agents/price_agent.py.tmpl +0 -0
  84. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/agents/risk_agent.py.tmpl +0 -0
  85. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/config/llms.yaml +0 -0
  86. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/config/policy.yaml +0 -0
  87. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/config/prompts.yaml +0 -0
  88. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/config/scaling.yaml +0 -0
  89. {canyonos-0.2.2/canyonos/starters → canyonos-0.2.3.dev1/canyonos/starters/portfolio}/portfolio/config/test_query.txt +0 -0
  90. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/status.py +0 -0
  91. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/theme.py +0 -0
  92. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/usage/__init__.py +0 -0
  93. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/usage/consent.py +0 -0
  94. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/usage/delivery.py +0 -0
  95. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/usage/outbox.py +0 -0
  96. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos/usage/settings.py +0 -0
  97. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos.egg-info/dependency_links.txt +0 -0
  98. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos.egg-info/entry_points.txt +0 -0
  99. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/canyonos.egg-info/top_level.txt +0 -0
  100. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/setup.cfg +0 -0
  101. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/tests/test_port_utils_twins.py +0 -0
  102. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/utils/__init__.py +0 -0
  103. {canyonos-0.2.2 → canyonos-0.2.3.dev1}/utils/tui.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: canyonos
3
- Version: 0.2.2
3
+ Version: 0.2.3.dev1
4
4
  Summary: Open-source platform for multi-agent apps: per-agent scaling, tracing and cost, in plain Python
5
5
  License-Expression: AGPL-3.0-only
6
6
  Project-URL: Homepage, https://canyonos.ai
@@ -16,6 +16,7 @@ Requires-Python: >=3.10
16
16
  Description-Content-Type: text/markdown
17
17
  Requires-Dist: boto3[crt]>=1.43.109
18
18
  Requires-Dist: pyfiglet
19
+ Requires-Dist: pyjwt[crypto]>=2.10.1
19
20
  Requires-Dist: python-dotenv
20
21
  Requires-Dist: pyyaml
21
22
  Requires-Dist: rich
@@ -38,9 +39,8 @@ Converting an existing workflow? Run `canyonos convert` in its folder first; you
38
39
  agent writes a CanyonOS version of it into a `.canyon/` folder.
39
40
 
40
41
  ```bash
41
- cd your-project
42
- canyonos deploy # build and launch the workflow, then open the dashboard
43
- canyonos stop # stop the deploy and remove its containers and files
42
+ canyonos deploy your-project --folder your-deployment # build and launch the workflow, then open the dashboard
43
+ canyonos stop # stop the deploy and remove its containers and files
44
44
  ```
45
45
 
46
46
  Run `canyonos -h` for every command.
@@ -15,9 +15,8 @@ Converting an existing workflow? Run `canyonos convert` in its folder first; you
15
15
  agent writes a CanyonOS version of it into a `.canyon/` folder.
16
16
 
17
17
  ```bash
18
- cd your-project
19
- canyonos deploy # build and launch the workflow, then open the dashboard
20
- canyonos stop # stop the deploy and remove its containers and files
18
+ canyonos deploy your-project --folder your-deployment # build and launch the workflow, then open the dashboard
19
+ canyonos stop # stop the deploy and remove its containers and files
21
20
  ```
22
21
 
23
22
  Run `canyonos -h` for every command.
@@ -0,0 +1,565 @@
1
+ # SPDX-FileCopyrightText: 2026 Canyon Code, Inc.
2
+ # SPDX-License-Identifier: AGPL-3.0-only
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
+ """
8
+
9
+ import hashlib
10
+ import json
11
+ import re
12
+ import time
13
+ import uuid
14
+ from datetime import datetime, timezone
15
+ from pathlib import Path
16
+
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
+ 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
+ )
40
+
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"
49
+
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
56
+
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."
60
+ )
61
+
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
+
89
+
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
+
113
+
114
+ def _read(path: Path) -> bytes:
115
+ try:
116
+ return path.read_bytes()
117
+ except OSError as error:
118
+ raise RuntimeError(
119
+ f"Could not read {path}: {error.strerror or error}"
120
+ ) from error
121
+
122
+
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)
147
+
148
+
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
163
+
164
+
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)
258
+ 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)
277
+ except OSError as error:
278
+ raise RuntimeError(
279
+ f"Could not write {path}: {error.strerror or error}"
280
+ ) from error
281
+ return path
282
+
283
+
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"
291
+ try:
292
+ make_private_dir(folder)
293
+ write_private_file(private, private_pem)
294
+ except OSError as error:
295
+ raise RuntimeError(
296
+ f"Could not write {private}: {error.strerror or error}"
297
+ ) from error
298
+ return private, _write_public_key(trusted_dir(auth_dir) / f"{name}.pub", public_pem)
299
+
300
+
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:
315
+ 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."
462
+ )
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
@@ -1322,11 +1322,14 @@ class _AwsProvision:
1322
1322
  ui.command(f"scp -i {key} -r <project folder> {SSH_USER}@{address}:~/")
1323
1323
  ui.say("Then sign in, wait for the install, and deploy:")
1324
1324
  ui.command(f"ssh -i {key} {SSH_USER}@{address}")
1325
- ui.command("cloud-init status --wait && cd <project folder> && canyonos deploy")
1325
+ ui.command(
1326
+ "cloud-init status --wait && "
1327
+ "canyonos deploy <project folder> --folder deployment"
1328
+ )
1326
1329
  ui.blank()
1327
1330
  ui.hint(
1328
1331
  "To run agents on EC2, set `provider: ec2-assign` and give each agent a "
1329
- "machine type under `ec2-assign: machine_type:` in workflow_config.yaml, "
1332
+ "machine type under `ec2-assign: machine_type:` in deployment.yaml, "
1330
1333
  "or `provider: ec2-pool` with a pool under `ec2-pool: machine_type:`. They launch "
1331
1334
  "into this machine's subnet and security group."
1332
1335
  )