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.
@@ -0,0 +1,370 @@
1
+ """OpenSSH connection reuse, including PTYs and host-local forwarding."""
2
+
3
+ import base64
4
+ import binascii
5
+ from pathlib import Path
6
+ import hashlib
7
+ import os
8
+ import re
9
+ import secrets
10
+ import shlex
11
+ import socket
12
+ import stat
13
+ import subprocess
14
+ import sys
15
+ import tempfile
16
+ import threading
17
+
18
+ import click
19
+
20
+ from .common import run
21
+
22
+
23
+ def valid_host(value):
24
+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", value):
25
+ raise click.BadParameter("expected an SSH hostname or IPv4 address")
26
+ return value
27
+
28
+
29
+ def is_ssh_destination(value):
30
+ return re.fullmatch(r"(?:[a-z_][a-z0-9_-]*@)?[A-Za-z0-9][A-Za-z0-9._-]*", value) is not None
31
+
32
+
33
+ def guest_ssh_options():
34
+ """The guest identity exists only on the workstation, never the laptop."""
35
+ return [
36
+ "-F",
37
+ "/dev/null",
38
+ "-i",
39
+ "/run/caisson/agent/client_key",
40
+ "-o",
41
+ "UserKnownHostsFile=/run/caisson/agent/known_hosts",
42
+ "-o",
43
+ "StrictHostKeyChecking=yes",
44
+ "-o",
45
+ "IdentitiesOnly=yes",
46
+ "-o",
47
+ "IdentityAgent=none",
48
+ "-o",
49
+ "ForwardAgent=no",
50
+ "-o",
51
+ "BatchMode=yes",
52
+ "-o",
53
+ "ConnectTimeout=3",
54
+ "-o",
55
+ "ServerAliveInterval=15",
56
+ "-o",
57
+ "ServerAliveCountMax=3",
58
+ ]
59
+
60
+
61
+ def guest_sftp_command():
62
+ return [
63
+ "ssh", *guest_ssh_options(), "-o", "ClearAllForwardings=yes",
64
+ "-T", "-s", "agent@192.0.2.2", "sftp",
65
+ ]
66
+
67
+
68
+ def control_directory():
69
+ """Stable, owner-only sockets; no keys or credentials are written here."""
70
+ base = Path(tempfile.gettempdir()).resolve()
71
+ root = base / f"caisson-ssh-{os.getuid()}"
72
+ # macOS TMPDIR can be too long for sockaddr_un. %C adds 40 characters.
73
+ if len(os.fsencode(root)) + 55 >= 100:
74
+ base = Path("/tmp").resolve()
75
+ root = base / f"caisson-ssh-{os.getuid()}"
76
+ for parent in (base, *base.parents):
77
+ info = parent.stat()
78
+ if info.st_uid not in {0, os.getuid()} or (
79
+ info.st_mode & 0o022 and not info.st_mode & stat.S_ISVTX
80
+ ):
81
+ raise click.ClickException(f"Unsafe SSH control directory parent: {parent}")
82
+ try:
83
+ root.mkdir(mode=0o700)
84
+ except FileExistsError:
85
+ pass
86
+ info = root.lstat()
87
+ if (
88
+ not stat.S_ISDIR(info.st_mode)
89
+ or info.st_uid != os.getuid()
90
+ or stat.S_IMODE(info.st_mode) & 0o077
91
+ ):
92
+ raise click.ClickException(
93
+ f"Unsafe SSH control directory: {root}; expected an owner-only directory"
94
+ )
95
+ return root
96
+
97
+
98
+ def terminal_frame(stream, marker, display):
99
+ """Stream prompts as they arrive, even when they have no newline."""
100
+ after = terminal_marker(stream, marker, display)
101
+ if after is not None:
102
+ return (after + stream.read()).partition(b"\n")[0].rstrip(b"\r")
103
+ return None
104
+
105
+
106
+ def terminal_marker(stream, marker, display):
107
+ pending = b""
108
+ while chunk := stream.read1():
109
+ data = pending + chunk
110
+ before, found, after = data.partition(marker)
111
+ if found:
112
+ display(before)
113
+ return after
114
+ start = data.rfind(b"\x1e")
115
+ pending = data[start:] if start != -1 and marker.startswith(data[start:]) else b""
116
+ display(data[:-len(pending)] if pending else data)
117
+ display(pending)
118
+ return None
119
+
120
+
121
+ def sftp_socket_path(token):
122
+ # Both endpoints derive the path without trusting text from the terminal.
123
+ return Path("/tmp") / f"caisson-sftp-{token}" / "data"
124
+
125
+
126
+ def relay_sftp(path):
127
+ """scp -D adapter: relay the binary protocol, never open a terminal."""
128
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
129
+ peer.connect(path)
130
+
131
+ def upload():
132
+ try:
133
+ while chunk := os.read(sys.stdin.fileno(), 65536):
134
+ peer.sendall(chunk)
135
+ peer.shutdown(socket.SHUT_WR)
136
+ except OSError:
137
+ # The main thread observes remote closure on its read side.
138
+ pass
139
+
140
+ threading.Thread(target=upload, daemon=True).start()
141
+ while chunk := peer.recv(65536):
142
+ sys.stdout.buffer.write(chunk)
143
+ sys.stdout.buffer.flush()
144
+
145
+
146
+ class SSH:
147
+ def __init__(self, *, reuse=True):
148
+ # Short, private paths also work on macOS's small Unix socket limit.
149
+ self.directory = tempfile.TemporaryDirectory(prefix="caisson-")
150
+ self.targets = {}
151
+ self.reuse = reuse
152
+
153
+ def options(self, target, *, multiplex=True):
154
+ if not is_ssh_destination(target):
155
+ raise click.ClickException("Invalid SSH destination returned by management")
156
+ if multiplex and target not in self.targets:
157
+ if self.reuse:
158
+ alias = hashlib.sha256(target.encode()).hexdigest()[:12]
159
+ # Native %C keys by resolved user, host, port and jump route.
160
+ self.targets[target] = str(control_directory() / (alias + "-%C"))
161
+ else:
162
+ self.targets[target] = str(Path(self.directory.name) / str(len(self.targets)))
163
+ connection = [
164
+ "-o",
165
+ # OpenSSH shows authentication banners and security-key prompts at INFO.
166
+ "LogLevel=INFO",
167
+ "-o",
168
+ "ConnectTimeout=10",
169
+ "-o",
170
+ "ConnectionAttempts=1",
171
+ "-o",
172
+ "ServerAliveInterval=15",
173
+ "-o",
174
+ "ServerAliveCountMax=3",
175
+ "-o",
176
+ "StrictHostKeyChecking=ask",
177
+ ]
178
+ if not multiplex:
179
+ return ["-o", "ControlMaster=no", "-o", "ControlPath=none", *connection]
180
+ return [
181
+ "-o",
182
+ "ControlMaster=auto",
183
+ "-o",
184
+ "ControlPersist=60",
185
+ "-o",
186
+ f"ControlPath={self.targets[target]}",
187
+ *connection,
188
+ ]
189
+
190
+ def command(self, target, args, *, tty=False):
191
+ return [
192
+ "ssh", *self.options(target), *(["-tt"] if tty else []), "--", target,
193
+ *([shlex.join(args)] if args else []),
194
+ ]
195
+
196
+ def execute(self, target, args=(), *, capture=False, tty=False):
197
+ return run(self.command(target, args, tty=tty), capture=capture)
198
+
199
+ def capture_terminal(self, target, args):
200
+ token = secrets.token_hex(16)
201
+ marker = b"\x1e" + token.encode() + b":"
202
+ argv = self.command(target, [args[0], "--capture", token, *args[1:]], tty=True)
203
+
204
+ def display(data):
205
+ if data:
206
+ sys.stderr.buffer.write(data)
207
+ sys.stderr.buffer.flush()
208
+
209
+ try:
210
+ with subprocess.Popen(argv, stdout=subprocess.PIPE) as process:
211
+ payload = terminal_frame(process.stdout, marker, display)
212
+ code = process.wait()
213
+ except FileNotFoundError as exc:
214
+ raise click.ClickException("Required executable not found: ssh") from exc
215
+ if code:
216
+ raise click.exceptions.Exit(code if code > 0 else 130)
217
+ if payload is not None:
218
+ try:
219
+ return base64.b64decode(payload, validate=True).decode()
220
+ except (binascii.Error, UnicodeDecodeError):
221
+ pass
222
+ raise click.ClickException("Invalid response from the Podman target terminal")
223
+
224
+ def forward(self, target, local_port, remote_port):
225
+ # Do not use agentctl exec: that intentionally clears SSH forwarding.
226
+ inner = [
227
+ "ssh",
228
+ *guest_ssh_options(),
229
+ "-o",
230
+ "ExitOnForwardFailure=yes",
231
+ "-N",
232
+ "-L",
233
+ f"127.0.0.1:{remote_port}:127.0.0.1:{remote_port}",
234
+ "agent@192.0.2.2",
235
+ ]
236
+ # A TTY ensures disconnect hangs up the inner client.
237
+ # Tunnels own their connection: a multiplexed -L can outlive the exec
238
+ # channel and leave a listener in the shared master after Ctrl-C.
239
+ options = self.options(target, multiplex=False)
240
+ run(
241
+ [
242
+ "ssh",
243
+ *options,
244
+ "-tt",
245
+ "-o",
246
+ "ExitOnForwardFailure=yes",
247
+ "-L",
248
+ f"127.0.0.1:{local_port}:127.0.0.1:{remote_port}",
249
+ "--",
250
+ target,
251
+ shlex.join(inner),
252
+ ]
253
+ )
254
+
255
+ def scp(self, target, source, destination, *, recursive=False, preserve=False):
256
+ self._scp(
257
+ self._sftp_over_ssh(target, guest_sftp_command()), source, destination,
258
+ recursive=recursive, preserve=preserve,
259
+ )
260
+
261
+ def podman_scp(self, target, workspace, source, destination, *, recursive=False, preserve=False):
262
+ helper = ["caisson-podman", "sftp", workspace]
263
+ flags = {"recursive": recursive, "preserve": preserve}
264
+ if target == "local":
265
+ return self._scp(helper, source, destination, **flags)
266
+ target = target.removeprefix("ssh://")
267
+ if sys.stdin.isatty():
268
+ try:
269
+ tty = open("/dev/tty", "r+b", buffering=0)
270
+ except OSError:
271
+ pass
272
+ else:
273
+ with tty:
274
+ return self._podman_scp_terminal(
275
+ target, workspace, tty, source, destination, **flags,
276
+ )
277
+ return self._scp(self._sftp_over_ssh(target, helper), source, destination, **flags)
278
+
279
+ def _podman_scp_terminal(self, target, workspace, tty, source, destination, **flags):
280
+ token = secrets.token_hex(16)
281
+ # This connection owns the forward; don't attach it to a shared master.
282
+ with tempfile.TemporaryDirectory(prefix="caisson-sftp-") as directory:
283
+ local = Path(directory).resolve() / "data"
284
+ remote = sftp_socket_path(token)
285
+ argv = [
286
+ "ssh", *self.options(target, multiplex=False), "-tt", "-e", "none",
287
+ "-o", "ForwardAgent=no", "-o", "ExitOnForwardFailure=yes",
288
+ "-L", f"{local}:{remote}", "--", target,
289
+ shlex.join(["caisson-podman", "sftp", workspace, "--socket", token]),
290
+ ]
291
+ try:
292
+ process = subprocess.Popen(argv, stdin=tty, stdout=subprocess.PIPE, stderr=tty)
293
+ except FileNotFoundError as exc:
294
+ raise click.ClickException("Required executable not found: ssh") from exc
295
+ with process:
296
+ display = None
297
+ try:
298
+ marker = b"\x1e" + token.encode() + b":"
299
+ after = terminal_marker(process.stdout, marker, tty.write)
300
+ if after is not None:
301
+ def drain_terminal():
302
+ tty.write(after)
303
+ while chunk := process.stdout.read1():
304
+ tty.write(chunk)
305
+
306
+ display = threading.Thread(target=drain_terminal)
307
+ display.start()
308
+ self._scp(
309
+ [sys.executable, "-m", "caisson_tools.transport", str(local)],
310
+ source, destination, **flags,
311
+ )
312
+ code = process.wait()
313
+ if code:
314
+ raise click.exceptions.Exit(code if code > 0 else 130)
315
+ if after is None:
316
+ raise click.ClickException("Podman target did not open its SFTP socket")
317
+ finally:
318
+ if process.poll() is None:
319
+ process.terminate()
320
+ process.wait()
321
+ if display is not None:
322
+ display.join()
323
+
324
+ def _sftp_over_ssh(self, target, command):
325
+ return [
326
+ "ssh", *self.options(target), "-T", "-o", "ForwardAgent=no",
327
+ "-o", "ClearAllForwardings=yes", "--", target, shlex.join(command),
328
+ ]
329
+
330
+ def _scp(self, command, source, destination, *, recursive, preserve):
331
+ # Modern scp's -D speaks SFTP to a local executable over stdin/stdout.
332
+ # The helper relays that stream to guest SFTP without staging files.
333
+ with tempfile.TemporaryDirectory(dir=self.directory.name, prefix="scp-") as directory:
334
+ helper = Path(directory) / "sftp"
335
+ helper.write_text("#!/bin/sh\nexec " + shlex.join(command) + "\n")
336
+ helper.chmod(0o700)
337
+ run(
338
+ [
339
+ "scp",
340
+ "-D",
341
+ helper,
342
+ *(["-r"] if recursive else []),
343
+ *(["-p"] if preserve else []),
344
+ "--",
345
+ source,
346
+ destination,
347
+ ]
348
+ )
349
+
350
+ def close(self):
351
+ # Shared masters expire after 60 idle seconds. Do not close another
352
+ # invocation/REPL's live channels or lose cross-invocation reuse.
353
+ for target, path in () if self.reuse else self.targets.items():
354
+ if Path(path).exists():
355
+ subprocess.run(
356
+ ["ssh", "-S", path, "-O", "exit", "--", target],
357
+ stdin=subprocess.DEVNULL,
358
+ stdout=subprocess.DEVNULL,
359
+ stderr=subprocess.DEVNULL,
360
+ check=False,
361
+ )
362
+ self.directory.cleanup()
363
+
364
+
365
+ if __name__ == "__main__":
366
+ try:
367
+ relay_sftp(sys.argv[1])
368
+ except OSError as exc:
369
+ print(f"caisson SFTP relay: {exc}", file=sys.stderr)
370
+ raise SystemExit(1) from None