zettcode-ssh 0.5.2__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,500 @@
1
+ """One bounded OpenSSH process per operation, with a fixed command and JSON on stdin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import atexit
7
+ import base64
8
+ import json
9
+ import os
10
+ import re
11
+ import shlex
12
+ import shutil
13
+ import signal
14
+ import tempfile
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass
17
+ from importlib.resources import files
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from zett_agent.messages import ImageBytesSource, ImageContent, TextContent
22
+
23
+ from zettcode.plugin_api import CHILD_STATE_ENV, PLUGIN_ARGS_ENV, subprocess_environment
24
+
25
+ from .remote import MAX_IMAGE, MAX_REQUEST, duration
26
+
27
+ MAX_RESPONSE = 6 * 1024 * 1024
28
+ HOST = re.compile(r"(?:[A-Za-z0-9_][A-Za-z0-9_.-]*@)?(?:[A-Za-z0-9_][A-Za-z0-9_.:-]*|\[[0-9a-fA-F:]+\])\Z")
29
+ USER = re.compile(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,63}\Z")
30
+ AUTHS = ("key", "password")
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Target:
35
+ """Where remote tools run and how OpenSSH signs in; never a secret."""
36
+
37
+ host: str
38
+ path: str
39
+ user: str | None = None
40
+ auth: str = "key"
41
+
42
+ def __post_init__(self) -> None:
43
+ if not isinstance(self.host, str) or not HOST.fullmatch(self.host) or len(self.host) > 255:
44
+ raise ValueError("SSH host must be an OpenSSH alias or [user@]hostname, not options or a URL")
45
+ if not isinstance(self.path, str) or not self.path.startswith("/") or any(ord(c) < 32 for c in self.path):
46
+ raise ValueError("SSH workspace must be an absolute remote path without control characters")
47
+ if self.user is not None and (not isinstance(self.user, str) or not USER.fullmatch(self.user)):
48
+ raise ValueError("SSH user must be a plain account name, not options")
49
+ if self.auth not in AUTHS:
50
+ raise ValueError("SSH sign-in is 'key' or 'password'")
51
+
52
+ @classmethod
53
+ def restore(cls, state: dict[str, Any]) -> Target:
54
+ """Restore a descriptor without ever accepting a credential.
55
+
56
+ Older descriptors carried only ``host`` and ``path``; the user and sign-in method are optional additions.
57
+ """
58
+ if not isinstance(state, dict) or not {"host", "path"} <= set(state) <= {"host", "path", "user", "auth"}:
59
+ raise ValueError("SSH child state may contain only host, path, user and auth (no credentials)")
60
+ return cls(state["host"], state["path"], state.get("user"), state.get("auth", "key"))
61
+
62
+ def export(self) -> dict[str, Any]:
63
+ return {"host": self.host, "path": self.path, "user": self.user, "auth": self.auth}
64
+
65
+
66
+ class Askpass:
67
+ """Hand a password to OpenSSH beside argv, not in it, and never in durable state.
68
+
69
+ OpenSSH reads a password from the terminal, which a tool has none of. With ``SSH_ASKPASS_REQUIRE=force`` it
70
+ runs a helper instead, so the password reaches it through a private file (directory 0700, file 0600) whose path
71
+ is in the helper. The environment and argv of the ssh process carry only that path.
72
+ """
73
+
74
+ def __init__(self) -> None:
75
+ self.directory: Path | None = None
76
+ self._atexit: Callable[[], None] | None = None
77
+
78
+ def environment(self, password: str) -> dict[str, str]:
79
+ """Return the environment additions, writing the helper on first use and reusing it after a reconnect."""
80
+ if self.directory is None:
81
+ self.prepare(password)
82
+ else:
83
+ try:
84
+ saved = (self.directory / "secret").read_text(encoding="utf-8")
85
+ (self.directory / "askpass").read_text(encoding="utf-8")
86
+ except (OSError, UnicodeError):
87
+ self.close()
88
+ return self.prepare(password)
89
+ if saved != password + "\n":
90
+ raise ValueError("An SSH askpass helper cannot change password; close it before preparing another")
91
+ assert self.directory is not None
92
+ return {
93
+ "SSH_ASKPASS": str(self.directory / "askpass"),
94
+ "SSH_ASKPASS_REQUIRE": "force",
95
+ "DISPLAY": os.environ.get("DISPLAY", ":0"),
96
+ }
97
+
98
+ @property
99
+ def ready(self) -> bool:
100
+ return self.directory is not None
101
+
102
+ def prepare(self, password: str) -> dict[str, str]:
103
+ """Write the helper and return the environment additions OpenSSH needs."""
104
+ if not password or any(char in password for char in "\r\n\0"):
105
+ raise ValueError("An SSH password must be non-empty single-line text")
106
+ directory = Path(tempfile.mkdtemp(prefix="zettcode-ssh-askpass-"))
107
+ self.directory = directory
108
+ try:
109
+ os.chmod(directory, 0o700)
110
+ secret = directory / "secret"
111
+ descriptor = os.open(secret, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
112
+ with os.fdopen(descriptor, "w", encoding="utf-8", newline="") as handle:
113
+ handle.write(password + "\n")
114
+ script = directory / "askpass"
115
+ script.write_text(f"#!/bin/sh\nexec /bin/cat {shlex.quote(str(secret))}\n", encoding="utf-8")
116
+ os.chmod(script, 0o700)
117
+ # A process that exits without closing the channel still takes the password with it.
118
+ directory_path = directory
119
+
120
+ def remove() -> None:
121
+ shutil.rmtree(directory_path, ignore_errors=True)
122
+
123
+ atexit.register(remove)
124
+ self._atexit = remove
125
+ except OSError:
126
+ self.close()
127
+ raise
128
+ return self.environment(password)
129
+
130
+ def close(self) -> None:
131
+ """Remove the helper and the password with it."""
132
+ if self._atexit is not None:
133
+ atexit.unregister(self._atexit)
134
+ self._atexit = None
135
+ if self.directory is not None:
136
+ shutil.rmtree(self.directory, ignore_errors=True)
137
+ self.directory = None
138
+
139
+
140
+ async def bounded(stream: asyncio.StreamReader, limit: int) -> bytes:
141
+ chunks = bytearray()
142
+ while True:
143
+ part = await stream.read(min(8192, limit + 1 - len(chunks)))
144
+ if not part:
145
+ return bytes(chunks)
146
+ chunks.extend(part)
147
+ if len(chunks) > limit:
148
+ raise ValueError("SSH response exceeds output limit")
149
+
150
+
151
+ async def cleanup(process: asyncio.subprocess.Process, tasks: list[asyncio.Task[Any]]) -> None:
152
+ """Reap SSH without waiting on paused readers or pipes inherited by a descendant."""
153
+ try:
154
+ if process.returncode is None:
155
+ if os.name == "posix":
156
+ try:
157
+ os.killpg(process.pid, signal.SIGKILL)
158
+ except PermissionError:
159
+ # The group may have disappeared while SSH was exiting; do not hide its diagnostic.
160
+ process.kill()
161
+ else:
162
+ process.kill()
163
+ except (ProcessLookupError, PermissionError):
164
+ pass
165
+ for task in tasks:
166
+ if not task.done():
167
+ task.cancel()
168
+ await asyncio.gather(*tasks, return_exceptions=True)
169
+ if process.stdin is not None:
170
+ process.stdin.close()
171
+
172
+ async def discard(stream: asyncio.StreamReader) -> None:
173
+ while await stream.read(8192):
174
+ pass
175
+
176
+ # Cancelling the bounded readers leaves StreamReader buffers paused. Resume both while
177
+ # waiting for the child: asyncio's process.wait() may otherwise never finish, even after kill.
178
+ pending_tasks: list[asyncio.Task[Any]] = [asyncio.create_task(process.wait())]
179
+ pending_tasks.extend(asyncio.create_task(discard(stream)) for stream in (process.stdout, process.stderr) if stream)
180
+ _, pending = await asyncio.wait(pending_tasks, timeout=1)
181
+ if pending:
182
+ # StreamReader has no public close. A descendant outside SSH's process group can
183
+ # retain its descriptors indefinitely; only this last-resort pipe close needs asyncio internals.
184
+ transport = process._transport # type: ignore[attr-defined]
185
+ for fd in (0, 1, 2):
186
+ pipe = transport.get_pipe_transport(fd)
187
+ if pipe is not None:
188
+ pipe.close()
189
+ await asyncio.wait(pending_tasks, timeout=1)
190
+ for task in pending_tasks:
191
+ if not task.done():
192
+ task.cancel()
193
+ await asyncio.gather(*pending_tasks, return_exceptions=True)
194
+
195
+
196
+ def decode_result(operation: str, result: Any) -> Any:
197
+ if operation == "read" and isinstance(result, dict):
198
+ data = base64.b64decode(result["image"], validate=True)
199
+ if len(data) > MAX_IMAGE or result["media_type"] not in {"image/png", "image/jpeg", "image/gif", "image/webp"}:
200
+ raise ValueError("Invalid remote image")
201
+ return [
202
+ TextContent(text=f"Remote image {result['name']}: {result['media_type']}, {len(data)} bytes"),
203
+ ImageContent(source=ImageBytesSource(data=data, media_type=result["media_type"]), alt_text=result["name"]),
204
+ ]
205
+ if not isinstance(result, str):
206
+ raise ValueError("Invalid SSH tool result")
207
+ return result
208
+
209
+
210
+ async def diagnostic_stream(stream: asyncio.StreamReader, limit: int) -> bytes:
211
+ """Retain a bounded diagnostic while continuously draining a long-lived channel."""
212
+ result = bytearray()
213
+ while True:
214
+ chunk = await stream.read(8192)
215
+ if not chunk:
216
+ return bytes(result)
217
+ result.extend(chunk[: max(0, limit - len(result))])
218
+
219
+
220
+ class Transport:
221
+ def __init__(self, target: Target, *, password: str | None = None, persistent: bool = True) -> None:
222
+ self.target = target
223
+ self.password = password
224
+ self.persistent = persistent
225
+ self._lock = asyncio.Lock()
226
+ self._process: asyncio.subprocess.Process | None = None
227
+ self._stderr: asyncio.Task[bytes] | None = None
228
+ self._failure = ""
229
+ self._closed = False
230
+ self._sequence = 0
231
+ self._askpass = Askpass() if target.auth == "password" else None
232
+
233
+ def _ssh_arguments(self) -> list[str]:
234
+ """Return the OpenSSH options for this target's sign-in method and account."""
235
+ arguments = [
236
+ "-T",
237
+ "-o",
238
+ "StrictHostKeyChecking=yes",
239
+ "-o",
240
+ "ConnectTimeout=10",
241
+ "-o",
242
+ "ConnectionAttempts=1",
243
+ ]
244
+ if self.target.auth == "password":
245
+ arguments += [
246
+ "-o",
247
+ "BatchMode=no",
248
+ "-o",
249
+ "NumberOfPasswordPrompts=1",
250
+ "-o",
251
+ "PreferredAuthentications=password,keyboard-interactive",
252
+ "-o",
253
+ "PubkeyAuthentication=no",
254
+ ]
255
+ else:
256
+ arguments += ["-o", "BatchMode=yes"]
257
+ arguments += ["-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2"]
258
+ if self.target.user is not None:
259
+ arguments += ["-l", self.target.user]
260
+ return arguments
261
+
262
+ def _environment(self) -> dict[str, str]:
263
+ """Return the local environment for ssh; the handoff variables never reach the remote login."""
264
+ environment = dict(subprocess_environment() or os.environ)
265
+ environment.pop(CHILD_STATE_ENV, None)
266
+ environment.pop(PLUGIN_ARGS_ENV, None)
267
+ if self._askpass is not None:
268
+ if self.password is None:
269
+ raise RuntimeError(
270
+ "This SSH target signs in with a password, and no password is available here. "
271
+ "Passwords are never saved or inherited: open /ssh in the terminal and enter it again."
272
+ )
273
+ environment.update(self._askpass.environment(self.password))
274
+ return environment
275
+
276
+ @property
277
+ def status(self) -> str:
278
+ if self._failure:
279
+ return "disconnected: " + self._failure
280
+ if self._process is None:
281
+ return "not connected"
282
+ return "connected" if self._process.returncode is None else "disconnected"
283
+
284
+ async def _start(self) -> asyncio.subprocess.Process:
285
+ if self._closed:
286
+ raise RuntimeError("SSH channel was closed by its owner; old targets cannot reconnect")
287
+ if self._failure:
288
+ # Only a new explicit tool request may reconnect. Never replay the interrupted request.
289
+ self._failure = ""
290
+ if self._process is not None:
291
+ if self._process.returncode is not None:
292
+ raise RuntimeError("SSH channel closed; the next request reconnects (this one was not retried)")
293
+ return self._process
294
+ payload = files("zettcode.ssh").joinpath("remote.py").read_text(encoding="utf-8")
295
+ # Worker has no dependencies and never listens on TCP. Isolated Python excludes repository imports.
296
+ command = "python3 -I -c " + shlex.quote(payload) + " --worker"
297
+ environment = self._environment()
298
+ self._process = await asyncio.create_subprocess_exec(
299
+ "ssh",
300
+ *self._ssh_arguments(),
301
+ "--",
302
+ self.target.host,
303
+ command,
304
+ stdin=asyncio.subprocess.PIPE,
305
+ stdout=asyncio.subprocess.PIPE,
306
+ stderr=asyncio.subprocess.PIPE,
307
+ env=environment,
308
+ start_new_session=os.name == "posix",
309
+ limit=MAX_RESPONSE + 1,
310
+ )
311
+ assert self._process.stderr is not None
312
+ self._stderr = asyncio.create_task(diagnostic_stream(self._process.stderr, 16 * 1024))
313
+ return self._process
314
+
315
+ async def aclose(self) -> None:
316
+ """Close the channel for good, forget the password, and refuse to reconnect.
317
+
318
+ The cleanup is shielded from a second cancellation (a reader pressing Escape twice), exactly as a stuck
319
+ request's is: the helper and the password must not outlive the close because the caller was interrupted.
320
+ """
321
+ self._closed = True
322
+
323
+ async def closing() -> None:
324
+ async with self._lock:
325
+ await self._close()
326
+ if self._askpass is not None:
327
+ self._askpass.close()
328
+ self.password = None
329
+
330
+ task = asyncio.create_task(closing())
331
+ cancelled = False
332
+ while not task.done():
333
+ try:
334
+ await asyncio.shield(task)
335
+ except asyncio.CancelledError:
336
+ cancelled = True
337
+ task.result()
338
+ if cancelled:
339
+ raise asyncio.CancelledError
340
+
341
+ @property
342
+ def needs_password(self) -> bool:
343
+ """Return whether this target signs in with a password that is not here (a restored target)."""
344
+ return self.target.auth == "password" and self.password is None
345
+
346
+ async def _close(self) -> None:
347
+ process, self._process = self._process, None
348
+ tasks = [self._stderr] if self._stderr is not None else []
349
+ self._stderr = None
350
+ if process is not None:
351
+ await cleanup(process, tasks)
352
+
353
+ async def _exchange(self, operation: str, arguments: dict[str, Any]) -> Any:
354
+ async with self._lock:
355
+ self._sequence += 1
356
+ request = json.dumps(
357
+ {"id": self._sequence, "operation": operation, "workspace": self.target.path, "arguments": arguments},
358
+ ensure_ascii=False,
359
+ allow_nan=False,
360
+ ).encode("utf-8")
361
+ if len(request) > MAX_REQUEST:
362
+ raise ValueError("SSH request exceeds 4 MiB")
363
+ timeout = duration(arguments.get("timeout_seconds", 60)) if operation == "bash" else 120.0
364
+ try:
365
+ process = await self._start()
366
+ assert process.stdin is not None and process.stdout is not None
367
+
368
+ async def exchange() -> bytes:
369
+ assert process.stdin is not None and process.stdout is not None
370
+ try:
371
+ process.stdin.write(request + b"\n")
372
+ await process.stdin.drain()
373
+ except (BrokenPipeError, ConnectionResetError):
374
+ pass # Read stderr on EOF so authentication failures retain their diagnostic.
375
+ output = await process.stdout.readline()
376
+ if not output:
377
+ error = await self._stderr if self._stderr is not None else b""
378
+ raise RuntimeError("SSH channel closed: " + error.decode("utf-8", errors="replace"))
379
+ if len(output) > MAX_RESPONSE or not output.endswith(b"\n"):
380
+ raise ValueError("SSH response exceeds output limit or is not framed")
381
+ return output
382
+
383
+ output = await asyncio.wait_for(exchange(), timeout + 15)
384
+ response = json.loads(output)
385
+ if (
386
+ not isinstance(response, dict)
387
+ or response.get("id") != self._sequence
388
+ or type(response.get("ok")) is not bool
389
+ ):
390
+ raise ValueError("Invalid SSH protocol response")
391
+ except BaseException as error:
392
+ self._failure = f"SSH request interrupted ({type(error).__name__}); remote outcome may be unknown"
393
+ cleaning = asyncio.create_task(self._close())
394
+ while not cleaning.done():
395
+ try:
396
+ await asyncio.shield(cleaning)
397
+ except asyncio.CancelledError:
398
+ continue
399
+ cleaning.result()
400
+ raise
401
+ if not response["ok"]:
402
+ raise RuntimeError(f"Remote operation failed: {response.get('error', 'unknown error')}")
403
+ return decode_result(operation, response.get("result"))
404
+
405
+ async def run(self, operation: str, arguments: dict[str, Any]) -> Any:
406
+ if self.persistent:
407
+ return await self._exchange(operation, arguments)
408
+ return await self._run_once(operation, arguments)
409
+
410
+ async def _run_once(self, operation: str, arguments: dict[str, Any]) -> Any:
411
+ timeout = duration(arguments.get("timeout_seconds", 60)) if operation == "bash" else 120.0
412
+ request = json.dumps(
413
+ {"operation": operation, "workspace": self.target.path, "arguments": arguments},
414
+ ensure_ascii=False,
415
+ allow_nan=False,
416
+ ).encode("utf-8")
417
+ if len(request) > MAX_REQUEST:
418
+ raise ValueError("SSH request exceeds 4 MiB")
419
+ payload = files("zettcode.ssh").joinpath("remote.py").read_text(encoding="utf-8")
420
+ # Neither the login directory, remote workspace nor PYTHONPATH may supply payload imports.
421
+ remote_command = "python3 -I -c " + shlex.quote(payload)
422
+ environment = self._environment()
423
+ process = await asyncio.create_subprocess_exec(
424
+ "ssh",
425
+ *self._ssh_arguments(),
426
+ "--",
427
+ self.target.host,
428
+ remote_command,
429
+ stdin=asyncio.subprocess.PIPE,
430
+ stdout=asyncio.subprocess.PIPE,
431
+ stderr=asyncio.subprocess.PIPE,
432
+ env=environment,
433
+ start_new_session=os.name == "posix",
434
+ )
435
+ assert process.stdin is not None and process.stdout is not None and process.stderr is not None
436
+ tasks: list[asyncio.Task[Any]] = []
437
+
438
+ async def send() -> None:
439
+ assert process.stdin is not None
440
+ try:
441
+ process.stdin.write(request)
442
+ await process.stdin.drain()
443
+ process.stdin.close()
444
+ await process.stdin.wait_closed()
445
+ except (BrokenPipeError, ConnectionResetError):
446
+ # Authentication/connection failures may close stdin before a large request is sent.
447
+ # Let the exit-code/stderr path report the actual SSH diagnostic.
448
+ process.stdin.close()
449
+
450
+ try:
451
+ tasks = [
452
+ asyncio.create_task(send()),
453
+ asyncio.create_task(bounded(process.stdout, MAX_RESPONSE)),
454
+ asyncio.create_task(bounded(process.stderr, 16 * 1024)),
455
+ asyncio.create_task(process.wait()),
456
+ ]
457
+ _, output, error, code = await asyncio.wait_for(asyncio.gather(*tasks), timeout=timeout + 15)
458
+ if code:
459
+ raise RuntimeError(f"SSH failed (exit {code}): {error.decode('utf-8', errors='replace')}")
460
+ try:
461
+ response = json.loads(output)
462
+ except (ValueError, UnicodeDecodeError) as failure:
463
+ raise ValueError("Invalid SSH protocol response (remote python3 is required)") from failure
464
+ if not isinstance(response, dict) or type(response.get("ok")) is not bool:
465
+ raise ValueError("Invalid SSH protocol response")
466
+ if not response["ok"]:
467
+ raise RuntimeError(f"Remote operation failed: {response.get('error', 'unknown error')}")
468
+ if "result" not in response:
469
+ raise ValueError("Missing SSH protocol result")
470
+ result = response["result"]
471
+ if operation == "read" and isinstance(result, dict):
472
+ data = base64.b64decode(result["image"], validate=True)
473
+ if len(data) > MAX_IMAGE or result["media_type"] not in {
474
+ "image/png",
475
+ "image/jpeg",
476
+ "image/gif",
477
+ "image/webp",
478
+ }:
479
+ raise ValueError("Invalid remote image")
480
+ return [
481
+ TextContent(text=f"Remote image {result['name']}: {result['media_type']}, {len(data)} bytes"),
482
+ ImageContent(
483
+ source=ImageBytesSource(data=data, media_type=result["media_type"]), alt_text=result["name"]
484
+ ),
485
+ ]
486
+ if not isinstance(result, str):
487
+ raise ValueError("Invalid SSH tool result")
488
+ return result
489
+ finally:
490
+ # Shield cleanup from a second cancellation without suppressing the original failure.
491
+ cleaning = asyncio.create_task(cleanup(process, tasks))
492
+ cancelled = False
493
+ while not cleaning.done():
494
+ try:
495
+ await asyncio.shield(cleaning)
496
+ except asyncio.CancelledError:
497
+ cancelled = True
498
+ cleaning.result()
499
+ if cancelled:
500
+ raise asyncio.CancelledError