caisson-tools 0.1.0__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.
- caisson_tools/__init__.py +1 -0
- caisson_tools/_revision.txt +1 -0
- caisson_tools/agentctl-commands.json +1 -0
- caisson_tools/allowlist_syntax.py +44 -0
- caisson_tools/browser.py +36 -0
- caisson_tools/common.py +174 -0
- caisson_tools/context.py +36 -0
- caisson_tools/environment.py +92 -0
- caisson_tools/management.py +113 -0
- caisson_tools/manifest.py +41 -0
- caisson_tools/ops.py +839 -0
- caisson_tools/podman.py +325 -0
- caisson_tools/remote.py +158 -0
- caisson_tools/secrets.py +100 -0
- caisson_tools/serve.py +160 -0
- caisson_tools/terminal.py +194 -0
- caisson_tools/transport.py +370 -0
- caisson_tools/user.py +789 -0
- caisson_tools/version.py +37 -0
- caisson_tools-0.1.0.dist-info/METADATA +69 -0
- caisson_tools-0.1.0.dist-info/RECORD +25 -0
- caisson_tools-0.1.0.dist-info/WHEEL +4 -0
- caisson_tools-0.1.0.dist-info/entry_points.txt +3 -0
- caisson_tools-0.1.0.dist-info/licenses/LICENSE +202 -0
- caisson_tools-0.1.0.dist-info/licenses/NOTICE +6 -0
caisson_tools/podman.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Host-side workspace driver. The SSH account is a trusted Podman operator."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import fcntl
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import re
|
|
9
|
+
import signal
|
|
10
|
+
import socket
|
|
11
|
+
import stat
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
from .serve import Serve, assignments, state_dir
|
|
15
|
+
from .transport import guest_sftp_command, sftp_socket_path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
LABEL = "com.caisson.workspace=true"
|
|
19
|
+
NAME = re.compile(r"[a-z](?:[a-z0-9-]{0,38}[a-z0-9])?")
|
|
20
|
+
PREFIX = "caisson-ws-"
|
|
21
|
+
LIFECYCLE = {"new", "start", "stop", "rebuild", "destroy"}
|
|
22
|
+
STOPPED = {None, "created", "configured", "exited", "stopped"}
|
|
23
|
+
RELAY = "14096/tcp"
|
|
24
|
+
CONFIG = Path("/etc/caisson/podman.json")
|
|
25
|
+
INPUTS = Path("/etc/caisson/workspaces")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def podman(*args, capture=False):
|
|
29
|
+
return subprocess.run(
|
|
30
|
+
podman_args(*args), check=True, text=True, stdin=subprocess.DEVNULL,
|
|
31
|
+
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
|
32
|
+
).stdout
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def has_controlling_terminal():
|
|
36
|
+
# With scp -D, stdin and stdout are protocol pipes even when launched
|
|
37
|
+
# from a terminal. sudo can prompt on /dev/tty without touching either.
|
|
38
|
+
try:
|
|
39
|
+
with open("/dev/tty", "rb", buffering=0):
|
|
40
|
+
return True
|
|
41
|
+
except OSError:
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def podman_args(*args):
|
|
46
|
+
if os.geteuid() == 0:
|
|
47
|
+
return ["podman", *args]
|
|
48
|
+
sudo = ["sudo"] if has_controlling_terminal() else ["sudo", "-n"]
|
|
49
|
+
return [*sudo, "podman", *args]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def managed_names(kind):
|
|
53
|
+
return set(podman(
|
|
54
|
+
kind, "ls", "--filter", f"label={LABEL}", "--format", "{{.Name}}", capture=True,
|
|
55
|
+
).splitlines())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def workspace_states():
|
|
59
|
+
"""A named volume is the inventory record; no container yet is None."""
|
|
60
|
+
states = dict(line.rsplit(" ", 1) for line in podman(
|
|
61
|
+
"ps", "-a", "--filter", f"label={LABEL}", "--format", "{{.Names}} {{.State}}",
|
|
62
|
+
capture=True,
|
|
63
|
+
).splitlines())
|
|
64
|
+
return {
|
|
65
|
+
resource.removeprefix(PREFIX): states.get(resource)
|
|
66
|
+
for resource in sorted(managed_names("volume"))
|
|
67
|
+
if resource.startswith(PREFIX) and NAME.fullmatch(resource.removeprefix(PREFIX))
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def workspace_status(name, state):
|
|
72
|
+
return {
|
|
73
|
+
"name": name,
|
|
74
|
+
"state": "STOPPED" if state in STOPPED else state.upper(),
|
|
75
|
+
"needs_repair": False,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def settings():
|
|
80
|
+
try:
|
|
81
|
+
config = json.loads(CONFIG.read_text())
|
|
82
|
+
except FileNotFoundError:
|
|
83
|
+
config = {}
|
|
84
|
+
fields = {"image", "workspace_config", "credentials", "tailscale_serve"}
|
|
85
|
+
if not isinstance(config, dict) or config.keys() - fields or any(
|
|
86
|
+
not isinstance(value, str) or not value for key, value in config.items() if key != "tailscale_serve"
|
|
87
|
+
):
|
|
88
|
+
raise ValueError(f"Invalid settings in {CONFIG}")
|
|
89
|
+
if type(config.get("tailscale_serve", False)) is not bool:
|
|
90
|
+
raise ValueError("tailscale_serve must be true or false")
|
|
91
|
+
return config
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def create_resource(kind, resource, *options):
|
|
95
|
+
podman(kind, "create", "--label", LABEL, *options, resource)
|
|
96
|
+
if resource not in managed_names(kind):
|
|
97
|
+
raise ValueError(f"{resource} exists but is not a Caisson {kind}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def input_mounts(name, config):
|
|
101
|
+
options = []
|
|
102
|
+
for setting, filename, key in (
|
|
103
|
+
("workspace_config", "workspace-config.json", "CAISSON_WORKSPACE_CONFIG_FILE"),
|
|
104
|
+
("credentials", "credentials.json", "CAISSON_CREDENTIALS_FILE"),
|
|
105
|
+
):
|
|
106
|
+
source = INPUTS / name / filename
|
|
107
|
+
try:
|
|
108
|
+
source.lstat()
|
|
109
|
+
except FileNotFoundError:
|
|
110
|
+
if setting not in config:
|
|
111
|
+
continue
|
|
112
|
+
source = Path(config[setting])
|
|
113
|
+
if not source.is_absolute():
|
|
114
|
+
raise ValueError(f"{setting} must be an absolute path on the target")
|
|
115
|
+
path = source.resolve(strict=True)
|
|
116
|
+
info = path.stat()
|
|
117
|
+
if not stat.S_ISREG(info.st_mode) or ":" in str(path):
|
|
118
|
+
raise ValueError(f"{setting} must name a regular file with no colon in its path")
|
|
119
|
+
if setting == "credentials" and not (
|
|
120
|
+
info.st_uid == 0 and info.st_mode & stat.S_IRUSR and not info.st_mode & 0o077
|
|
121
|
+
):
|
|
122
|
+
raise ValueError(f"Credentials must be root-owned and root-only (e.g. 0400): {path}")
|
|
123
|
+
target = f"/etc/caisson/inputs/{filename}"
|
|
124
|
+
options.extend(["--volume", f"{path}:{target}:ro", "--env", f"{key}={target}"])
|
|
125
|
+
return options
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def create_container(name, config, options):
|
|
129
|
+
resource = PREFIX + name
|
|
130
|
+
if resource not in managed_names("network"):
|
|
131
|
+
create_resource("network", resource, "--opt", "isolate=true")
|
|
132
|
+
podman(
|
|
133
|
+
"create", "--name", resource, "--label", LABEL, "--pull=never",
|
|
134
|
+
"--privileged", "--stop-timeout", "75", "--network", resource,
|
|
135
|
+
"--volume", f"{resource}:/home", "--env", "CAISSON_RUNTIME=podman", *options,
|
|
136
|
+
"--", config.get("image", "localhost/caisson-workstation-nix:scratch"),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def lifecycle(command, name, config, *, start_new=False):
|
|
141
|
+
resource = PREFIX + name
|
|
142
|
+
states = workspace_states()
|
|
143
|
+
if command == "new":
|
|
144
|
+
if name not in states:
|
|
145
|
+
create_resource("volume", resource)
|
|
146
|
+
states[name] = None
|
|
147
|
+
if not start_new:
|
|
148
|
+
return
|
|
149
|
+
command = "start"
|
|
150
|
+
state = require_workspace(states, name)
|
|
151
|
+
create = command == "rebuild" or (command == "start" and state is None)
|
|
152
|
+
options = input_mounts(name, config) if create else []
|
|
153
|
+
enabled = config.get("tailscale_serve", False)
|
|
154
|
+
ports = assignments()
|
|
155
|
+
# Retire an existing listener before releasing its relay, even when the
|
|
156
|
+
# operator has just disabled Serve in the config.
|
|
157
|
+
ingress = Serve(ports) if enabled or name in ports else None
|
|
158
|
+
if ingress:
|
|
159
|
+
if not enabled and command == "start":
|
|
160
|
+
raise ValueError(f"Serve was disabled; rebuild {name} to remove its web relay")
|
|
161
|
+
ingress.is_served(443) # Check picker ownership before changing any workspace.
|
|
162
|
+
for other, port in ingress.ports.items():
|
|
163
|
+
if states.get(other) != "running" or (other == name and command != "start"):
|
|
164
|
+
ingress.configure(port, False)
|
|
165
|
+
if enabled and command in {"start", "rebuild"}:
|
|
166
|
+
url = ingress.allocate(name)
|
|
167
|
+
port = ingress.ports[name]
|
|
168
|
+
relay = ingress.relay(port)
|
|
169
|
+
if create:
|
|
170
|
+
options.extend(["--publish", f"{relay}:{RELAY}", "--env", f"CAISSON_PODMAN_WEB_URL={url}"])
|
|
171
|
+
if state is not None and command in {"stop", "rebuild", "destroy"}:
|
|
172
|
+
if state not in STOPPED:
|
|
173
|
+
podman("stop", resource)
|
|
174
|
+
if command != "stop":
|
|
175
|
+
podman("rm", resource)
|
|
176
|
+
if command in {"start", "rebuild"}:
|
|
177
|
+
if create:
|
|
178
|
+
create_container(name, config, options)
|
|
179
|
+
if command == "rebuild" or state != "running":
|
|
180
|
+
podman("start", resource)
|
|
181
|
+
if enabled:
|
|
182
|
+
if podman("port", resource, RELAY, capture=True).strip() != relay:
|
|
183
|
+
raise ValueError(f"Workspace relay does not match Serve assignment; rebuild {name}")
|
|
184
|
+
ingress.configure(port, True)
|
|
185
|
+
elif command == "destroy":
|
|
186
|
+
if resource in managed_names("network"):
|
|
187
|
+
podman("network", "rm", resource)
|
|
188
|
+
podman("volume", "rm", resource)
|
|
189
|
+
if ingress:
|
|
190
|
+
if command == "destroy" or (command == "rebuild" and not enabled):
|
|
191
|
+
ingress.ports.pop(name, None)
|
|
192
|
+
ingress.save()
|
|
193
|
+
ingress.picker(workspace_states())
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def require_workspace(states, name):
|
|
197
|
+
if name not in states:
|
|
198
|
+
raise ValueError(f"No workspace named {name}")
|
|
199
|
+
return states[name]
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def web_url(name):
|
|
203
|
+
if not settings().get("tailscale_serve"):
|
|
204
|
+
raise ValueError("Web ingress is not configured on this Podman target")
|
|
205
|
+
ingress = Serve(assignments())
|
|
206
|
+
url = ingress.url(name)
|
|
207
|
+
if not ingress.is_served(ingress.ports[name]):
|
|
208
|
+
raise ValueError(f"Serve listener missing; retry start {name}")
|
|
209
|
+
return url
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def sftp_via_socket(token, invoke):
|
|
213
|
+
path = sftp_socket_path(token)
|
|
214
|
+
path.parent.mkdir(mode=0o700)
|
|
215
|
+
try:
|
|
216
|
+
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:
|
|
217
|
+
listener.bind(str(path))
|
|
218
|
+
listener.listen(1)
|
|
219
|
+
listener.settimeout(30)
|
|
220
|
+
sys.stdout.write(f"\x1e{token}:")
|
|
221
|
+
sys.stdout.flush()
|
|
222
|
+
peer, _ = listener.accept()
|
|
223
|
+
finally:
|
|
224
|
+
path.unlink(missing_ok=True)
|
|
225
|
+
path.parent.rmdir()
|
|
226
|
+
with peer:
|
|
227
|
+
# sudo still uses the SSH session's controlling terminal for prompts.
|
|
228
|
+
os.dup2(peer.fileno(), 0)
|
|
229
|
+
os.dup2(peer.fileno(), 1)
|
|
230
|
+
os.execvp(invoke[0], invoke)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def execute(args):
|
|
234
|
+
command = args[0] if args else ""
|
|
235
|
+
if args == ["ls", "--json", "--details"]:
|
|
236
|
+
items = [workspace_status(name, state) for name, state in workspace_states().items()]
|
|
237
|
+
print(json.dumps({"workspaces": items}))
|
|
238
|
+
return
|
|
239
|
+
if len(args) < 2 or not NAME.fullmatch(args[1]):
|
|
240
|
+
raise ValueError("Expected a workspace name: 1–40 lowercase letters, digits or hyphens")
|
|
241
|
+
name = args[1]
|
|
242
|
+
if command in LIFECYCLE:
|
|
243
|
+
flags = args[2:]
|
|
244
|
+
start_new = command == "new" and flags == ["--start"]
|
|
245
|
+
if not start_new and flags != (["--yes"] if command == "destroy" else []):
|
|
246
|
+
raise ValueError("Unsupported Podman workspace operation")
|
|
247
|
+
state = state_dir()
|
|
248
|
+
state.mkdir(parents=True, exist_ok=True)
|
|
249
|
+
with (state / "podman.lock").open("a") as lock:
|
|
250
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
251
|
+
lifecycle(command, name, settings(), start_new=start_new)
|
|
252
|
+
return
|
|
253
|
+
state = require_workspace(workspace_states(), name)
|
|
254
|
+
if command == "status" and args[2:] in ([], ["--json"]):
|
|
255
|
+
status = workspace_status(name, state)
|
|
256
|
+
print(json.dumps(status) if args[2:] else f"{name}: {status['state']}")
|
|
257
|
+
return
|
|
258
|
+
token = None
|
|
259
|
+
if command == "sftp" and len(args) == 4 and args[2] == "--socket":
|
|
260
|
+
if not re.fullmatch(r"[0-9a-f]{32}", args[3]) or not has_controlling_terminal():
|
|
261
|
+
raise ValueError("SFTP socket mode requires a valid token and a terminal")
|
|
262
|
+
token = args[3]
|
|
263
|
+
elif command not in {"exec", "web", "sftp"} or (command != "exec" and len(args) != 2):
|
|
264
|
+
raise ValueError("Unsupported Podman workspace operation")
|
|
265
|
+
if state != "running":
|
|
266
|
+
status = workspace_status(name, state)["state"].lower()
|
|
267
|
+
raise ValueError(f"Workspace is {status}; run start {name}")
|
|
268
|
+
if command == "web":
|
|
269
|
+
print(web_url(name))
|
|
270
|
+
return
|
|
271
|
+
if command == "sftp":
|
|
272
|
+
# Binary protocol: keep stdin/stdout intact through Podman and SSH.
|
|
273
|
+
tty = False
|
|
274
|
+
argv = guest_sftp_command()
|
|
275
|
+
else:
|
|
276
|
+
tty = args[2:3] == ["--tty"]
|
|
277
|
+
argv = args[3:] if tty else args[2:]
|
|
278
|
+
if not argv or argv[0] != "--":
|
|
279
|
+
raise ValueError("Missing command separator")
|
|
280
|
+
argv = argv[1:] or ["/bin/bash", "-l"]
|
|
281
|
+
if argv == ["agentctl", "pair"]:
|
|
282
|
+
web_url(name)
|
|
283
|
+
invoke = podman_args(
|
|
284
|
+
"exec", "--interactive", *(["--tty"] if tty else []),
|
|
285
|
+
"--user", "1000:1000", "--env", "HOME=/home/user", PREFIX + name,
|
|
286
|
+
*argv,
|
|
287
|
+
)
|
|
288
|
+
if token:
|
|
289
|
+
# Unwind the socket's cleanup when the SSH terminal goes away.
|
|
290
|
+
def hangup(_signum, _frame):
|
|
291
|
+
raise SystemExit(129)
|
|
292
|
+
|
|
293
|
+
signal.signal(signal.SIGHUP, hangup)
|
|
294
|
+
sftp_via_socket(token, invoke)
|
|
295
|
+
return
|
|
296
|
+
os.execvp(invoke[0], invoke)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def main():
|
|
300
|
+
try:
|
|
301
|
+
if sys.platform != "linux":
|
|
302
|
+
raise ValueError("Podman targets run on Linux; use --target ssh://HOST for a Linux worker")
|
|
303
|
+
args = sys.argv[1:]
|
|
304
|
+
# With SSH's PTY, stderr and stdout ordinarily share one stream.
|
|
305
|
+
# Leave sudo on the terminal; frame only the command's stdout.
|
|
306
|
+
if args[:1] == ["--capture"]:
|
|
307
|
+
if len(args) < 3 or not re.fullmatch(r"[0-9a-f]{32}", args[1]):
|
|
308
|
+
raise ValueError("Invalid terminal capture token")
|
|
309
|
+
child = subprocess.run(
|
|
310
|
+
[sys.executable, "-m", "caisson_tools.podman", *args[2:]], stdout=subprocess.PIPE,
|
|
311
|
+
)
|
|
312
|
+
sys.stdout.buffer.write(
|
|
313
|
+
b"\x1e" + args[1].encode() + b":" + base64.b64encode(child.stdout) + b"\n"
|
|
314
|
+
)
|
|
315
|
+
raise SystemExit(child.returncode)
|
|
316
|
+
execute(args)
|
|
317
|
+
except subprocess.CalledProcessError as exc:
|
|
318
|
+
raise SystemExit(exc.returncode) from None
|
|
319
|
+
except (OSError, ValueError) as exc:
|
|
320
|
+
print(f"caisson-podman: {exc}", file=sys.stderr)
|
|
321
|
+
raise SystemExit(1) from None
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
if __name__ == "__main__":
|
|
325
|
+
main()
|
caisson_tools/remote.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Build discoverable Click commands from agentctl's generated parser schema."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
from click.core import ParameterSource
|
|
7
|
+
from click.shell_completion import CompletionItem
|
|
8
|
+
|
|
9
|
+
from .common import UXGroup
|
|
10
|
+
from .manifest import load_manifest, schema_help
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
CATALOG = load_manifest()["catalogs"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def catalog_completion(kind):
|
|
17
|
+
def complete(ctx, param, incomplete):
|
|
18
|
+
return [
|
|
19
|
+
CompletionItem(name) for name in CATALOG.get(kind, []) if name.startswith(incomplete)
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
return complete
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RemoteCommand(click.Command):
|
|
26
|
+
def __init__(self, *args, forwarded_aliases=None, **kwargs):
|
|
27
|
+
super().__init__(*args, **kwargs)
|
|
28
|
+
self.forwarded_aliases = forwarded_aliases or {}
|
|
29
|
+
|
|
30
|
+
def parse_args(self, ctx, args):
|
|
31
|
+
# Keep remote argv byte-for-byte (including -- and ordering). Click
|
|
32
|
+
# provides local help/completion/basic validation, not reserialization.
|
|
33
|
+
original = list(args) # Click may consume/mutate the list while parsing.
|
|
34
|
+
result = super().parse_args(ctx, args)
|
|
35
|
+
options = {
|
|
36
|
+
name: param
|
|
37
|
+
for param in self.params
|
|
38
|
+
if isinstance(param, click.Option)
|
|
39
|
+
for name in param.opts
|
|
40
|
+
}
|
|
41
|
+
forwarded, after_separator, values_remaining = [], False, 0
|
|
42
|
+
for word in original:
|
|
43
|
+
if values_remaining:
|
|
44
|
+
forwarded.append(word)
|
|
45
|
+
values_remaining -= 1
|
|
46
|
+
continue
|
|
47
|
+
if word == "--":
|
|
48
|
+
after_separator = True
|
|
49
|
+
if not after_separator and word in {"--tty", "--no-tty"}:
|
|
50
|
+
continue
|
|
51
|
+
if not after_separator:
|
|
52
|
+
word = self.forwarded_aliases.get(word, word)
|
|
53
|
+
forwarded.append(word)
|
|
54
|
+
name, separator, _ = word.partition("=")
|
|
55
|
+
option = options.get(name)
|
|
56
|
+
if not after_separator and option and not option.is_flag and not separator:
|
|
57
|
+
values_remaining = option.nargs
|
|
58
|
+
ctx.remote_argv = forwarded
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parameter(item, *, option=False, catalog=None):
|
|
63
|
+
kwargs = {}
|
|
64
|
+
if item.get("choices"):
|
|
65
|
+
kwargs["type"] = click.Choice(item["choices"])
|
|
66
|
+
if catalog:
|
|
67
|
+
kwargs["shell_complete"] = catalog_completion(catalog)
|
|
68
|
+
if option:
|
|
69
|
+
kwargs.update(
|
|
70
|
+
help=item["help"],
|
|
71
|
+
required=item.get("required", False),
|
|
72
|
+
is_flag=item.get("flag", False),
|
|
73
|
+
multiple=item.get("multiple", False),
|
|
74
|
+
)
|
|
75
|
+
if item.get("default") is not None:
|
|
76
|
+
kwargs["default"] = item["default"]
|
|
77
|
+
kwargs["show_default"] = True
|
|
78
|
+
return click.Option(item["flags"], **kwargs)
|
|
79
|
+
nargs = item.get("nargs")
|
|
80
|
+
kwargs.update(required=nargs not in {"?", "*"}, nargs=-1 if nargs in {"+", "*", "..."} else 1)
|
|
81
|
+
return click.Argument([item["name"]], **kwargs)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def remote_tree(path, description, execute, schema=None):
|
|
85
|
+
schema = schema or {}
|
|
86
|
+
if schema.get("commands"):
|
|
87
|
+
group = UXGroup(path[-1], help=description)
|
|
88
|
+
for name, child in schema["commands"].items():
|
|
89
|
+
group.add_command(
|
|
90
|
+
remote_tree(
|
|
91
|
+
[*path, name],
|
|
92
|
+
child.get("help") or f"{name.capitalize()} {path[-1]}.",
|
|
93
|
+
execute,
|
|
94
|
+
child,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
group.epilog = schema.get("epilog") or None
|
|
98
|
+
return group
|
|
99
|
+
params = []
|
|
100
|
+
for item in schema.get("arguments", []):
|
|
101
|
+
catalog = None
|
|
102
|
+
if path[0] == "creds" and item["name"] == "preset":
|
|
103
|
+
catalog = "preset"
|
|
104
|
+
elif path[0] == "allowlist" and item["name"] in {"list", "lists"}:
|
|
105
|
+
catalog = "lists"
|
|
106
|
+
elif path[0] == "tool" and item["name"] == "name":
|
|
107
|
+
catalog = "tools"
|
|
108
|
+
params.append(parameter(item, catalog=catalog))
|
|
109
|
+
forwarded_aliases = {}
|
|
110
|
+
for item in schema.get("options", []):
|
|
111
|
+
if path in (["logs"], ["proxy-logs"]) and "--follow" in item["flags"]:
|
|
112
|
+
if "-f" not in item["flags"]:
|
|
113
|
+
item = {**item, "flags": [*item["flags"], "-f"]}
|
|
114
|
+
forwarded_aliases["-f"] = "--follow"
|
|
115
|
+
params.append(parameter(item, option=True))
|
|
116
|
+
params.append(
|
|
117
|
+
click.Option(
|
|
118
|
+
["--tty/--no-tty"],
|
|
119
|
+
default=None,
|
|
120
|
+
help="Force a terminal, or keep stdout/stderr separate (default: auto).",
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
@click.pass_context
|
|
125
|
+
def invoke(ctx, **values):
|
|
126
|
+
for exclusive in schema.get("exclusive", []):
|
|
127
|
+
used = [
|
|
128
|
+
name
|
|
129
|
+
for name in exclusive["names"]
|
|
130
|
+
if ctx.get_parameter_source(name) == ParameterSource.COMMANDLINE
|
|
131
|
+
]
|
|
132
|
+
labels = " / ".join("--" + name.replace("_", "-") for name in exclusive["names"])
|
|
133
|
+
if len(used) > 1 or (exclusive["required"] and not used):
|
|
134
|
+
raise click.UsageError(
|
|
135
|
+
f"Choose exactly one of {labels}"
|
|
136
|
+
if exclusive["required"]
|
|
137
|
+
else f"Use at most one of {labels}"
|
|
138
|
+
)
|
|
139
|
+
state = ctx.obj
|
|
140
|
+
tty = values.get("tty")
|
|
141
|
+
if tty is None:
|
|
142
|
+
# Runtime status stays JSON even at an interactive prompt.
|
|
143
|
+
tty = path != ["status"] and sys.stdin.isatty() and sys.stdout.isatty()
|
|
144
|
+
args = list(ctx.remote_argv)
|
|
145
|
+
if path in (["logs"], ["proxy-logs"]) and not values.get("follow") and not values.get("no_follow"):
|
|
146
|
+
# Older images follow proxy logs by default. Pin snapshot mode on the wire.
|
|
147
|
+
args.append("--no-follow")
|
|
148
|
+
execute(state, None, ["agentctl", *path, *args], tty=tty)
|
|
149
|
+
|
|
150
|
+
return RemoteCommand(
|
|
151
|
+
path[-1],
|
|
152
|
+
params=params,
|
|
153
|
+
callback=invoke,
|
|
154
|
+
help=schema_help({**schema, "help": description}),
|
|
155
|
+
epilog=schema.get("epilog") or None,
|
|
156
|
+
context_settings={"ignore_unknown_options": schema.get("passthrough", False)},
|
|
157
|
+
forwarded_aliases=forwarded_aliases,
|
|
158
|
+
)
|
caisson_tools/secrets.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Secret Manager JSON documents, pinned reads, and explicit project selection."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import re
|
|
6
|
+
import shlex
|
|
7
|
+
import tempfile
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SecretDocument:
|
|
11
|
+
def __init__(self, env, resource, cloud, *, error=ValueError):
|
|
12
|
+
self.error = error
|
|
13
|
+
match = re.fullmatch(r"projects/([^/]+)/secrets/([A-Za-z0-9_-]+)", resource)
|
|
14
|
+
if match:
|
|
15
|
+
self.env = {**env, "PROJECT_ID": match[1]}
|
|
16
|
+
self.secret = match[2]
|
|
17
|
+
elif re.fullmatch(r"[A-Za-z0-9_-]+", resource):
|
|
18
|
+
self.env = dict(env)
|
|
19
|
+
self.secret = resource
|
|
20
|
+
else:
|
|
21
|
+
raise error("expected secret ID or projects/PROJECT/secrets/SECRET")
|
|
22
|
+
self.resource = (
|
|
23
|
+
f"projects/{self.env['PROJECT_ID']}/secrets/{self.secret}"
|
|
24
|
+
if self.env.get("PROJECT_ID") else self.secret
|
|
25
|
+
)
|
|
26
|
+
self.cloud = cloud
|
|
27
|
+
|
|
28
|
+
def latest(self):
|
|
29
|
+
# Listing also handles a newly provisioned secret with no versions.
|
|
30
|
+
# Include disabled/destroyed versions: never silently fall back to older
|
|
31
|
+
# configuration when the latest version was deliberately disabled.
|
|
32
|
+
value = self.cloud(
|
|
33
|
+
self.env, "secrets", "versions", "list", self.secret,
|
|
34
|
+
"--sort-by=~createTime", "--limit=1", "--format=value(name.basename())", capture=True,
|
|
35
|
+
).strip()
|
|
36
|
+
# gcloud's list formatter shortens `name` to the version number.
|
|
37
|
+
# Request that explicitly, then normalize instead of expecting an API
|
|
38
|
+
# resource name from display-oriented `value(name)` output.
|
|
39
|
+
if value and not re.fullmatch(r"[1-9][0-9]*", value):
|
|
40
|
+
raise self.error("Could not read latest secret version")
|
|
41
|
+
if not value:
|
|
42
|
+
return None
|
|
43
|
+
return f"{self.resource}/versions/{value}" if "/" in self.resource else value
|
|
44
|
+
|
|
45
|
+
def read(self, version):
|
|
46
|
+
if version is None:
|
|
47
|
+
return {}
|
|
48
|
+
try:
|
|
49
|
+
return json.loads(self.cloud(
|
|
50
|
+
self.env, "secrets", "versions", "access", version.rsplit("/", 1)[-1],
|
|
51
|
+
f"--secret={self.secret}", capture=True,
|
|
52
|
+
))
|
|
53
|
+
except ValueError:
|
|
54
|
+
raise self.error("Invalid JSON in Secret Manager document") from None
|
|
55
|
+
|
|
56
|
+
def check_version(self, original):
|
|
57
|
+
if self.latest() != original:
|
|
58
|
+
raise self.error(
|
|
59
|
+
"Latest secret version changed; refusing to overwrite concurrent changes. "
|
|
60
|
+
"Fetch the latest version and retry.")
|
|
61
|
+
|
|
62
|
+
def publish(self, value):
|
|
63
|
+
# Values go over stdin, never argv, plans, tfvars or release records.
|
|
64
|
+
self.cloud(
|
|
65
|
+
self.env, "secrets", "versions", "add", self.secret, "--data-file=-",
|
|
66
|
+
input=json.dumps(value, separators=(",", ":")),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def publish_secret(secret, document, original, *, confirm, emit):
|
|
71
|
+
# addVersion has no version-match precondition. These optimistic checks
|
|
72
|
+
# narrow the race, but operators must still serialize concurrent publishers.
|
|
73
|
+
secret.check_version(original)
|
|
74
|
+
if not confirm():
|
|
75
|
+
emit("Cancelled.")
|
|
76
|
+
return False
|
|
77
|
+
secret.check_version(original)
|
|
78
|
+
secret.publish(document)
|
|
79
|
+
return True
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def edit_secret(secret, validate, *, run, confirm, emit, warning, cwd=None, empty=None):
|
|
83
|
+
"""Shared private edit/validate/confirm flow; never display document values."""
|
|
84
|
+
original = secret.latest()
|
|
85
|
+
document = validate(secret.read(original) if original else (empty if empty is not None else {}))
|
|
86
|
+
emit(warning)
|
|
87
|
+
with tempfile.TemporaryDirectory(prefix="caisson-secret-") as directory:
|
|
88
|
+
config = Path(directory) / "document.json"
|
|
89
|
+
config.write_text(json.dumps(document, indent=2) + "\n")
|
|
90
|
+
config.chmod(0o600)
|
|
91
|
+
run([*shlex.split(os.environ.get("EDITOR", "vi")), str(config)], cwd=cwd)
|
|
92
|
+
try:
|
|
93
|
+
updated = json.loads(config.read_text())
|
|
94
|
+
except (ValueError, OSError):
|
|
95
|
+
raise secret.error("Could not read edited secret JSON") from None
|
|
96
|
+
updated = validate(updated)
|
|
97
|
+
if updated == document:
|
|
98
|
+
emit("No changes.")
|
|
99
|
+
return False
|
|
100
|
+
return publish_secret(secret, updated, original, confirm=confirm, emit=emit)
|