"""Optional real localhost OpenSSH integration. Isolated host/user keys, no GPU. Requires Unix ssh, ssh-keygen and a runnable sshd. Never changes ~/.ssh or services. """ import asyncio import getpass import json import os from pathlib import Path import secrets import shlex import shutil import signal import socket import tempfile async def main(): root = Path(__file__).resolve().parents[2] sshd = shutil.which("sshd") or "/usr/sbin/sshd" ssh = shutil.which("ssh") if os.name == "nt" or not ssh or not Path(sshd).is_file(): raise RuntimeError("This optional integration requires a disposable Unix sshd") binary = root / "desktop-core/target/debug/strata-desktop" dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll" processes = [] with tempfile.TemporaryDirectory(prefix="strata-ssh-integration-") as folder: p = Path(folder) env = os.environ.copy() env["STRATA_NODE_TOKEN"] = secrets.token_hex(32) env.pop("STRATA_NODE_ENDPOINT", None) async def launch(*args, **kwargs): process = await asyncio.create_subprocess_exec(*args, **kwargs) processes.append(process) return process async def output(*args): process = await launch(*args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) out, err = await asyncio.wait_for(process.communicate(), 5) if process.returncode: raise RuntimeError("Fixture command failed") return out try: for key in ("host", "client"): await output("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(p / key)) (p / "authorized").write_text((p / "client.pub").read_text()) with socket.socket() as listener: listener.bind(("127.0.0.1", 0)) port = listener.getsockname()[1] (p / "sshd.conf").write_text( f"Port {port}\nListenAddress 127.0.0.1\nHostKey {p}/host\n" f"PidFile {p}/pid\nUsePAM no\nPasswordAuthentication no\n" f"KbdInteractiveAuthentication no\nAuthorizedKeysFile {p}/authorized\n" f"AllowUsers {getpass.getuser()}\nAllowTcpForwarding local\nLogLevel ERROR\n") daemon = await launch(sshd, "-D", "-e", "-f", str(p / "sshd.conf"), stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE) await asyncio.sleep(.2) if daemon.returncode is not None: raise RuntimeError("Isolated sshd could not start") public = " ".join((p / "host.pub").read_text().split()[:2]) (p / "known_hosts").write_text(f"[127.0.0.1]:{port} {public}\n") (p / "ssh.conf").write_text(f'UserKnownHostsFile "{p}/known_hosts"\nIdentitiesOnly yes\n') bindir = p / "bin" bindir.mkdir() wrapper = bindir / "ssh" wrapper.write_text("#!/bin/sh\nprintf '%s\\n' \"$$\" > " + shlex.quote(str(p / "ssh.pid")) + "\nexec " + shlex.quote(ssh) + " -F " + shlex.quote(str(p / "ssh.conf")) + ' "$@"\n') wrapper.chmod(0o700) env["PATH"] = str(bindir) + os.pathsep + env["PATH"] node = await launch(str(binary), "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_NODE_TOKEN", env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) node_endpoint = json.loads(await asyncio.wait_for(node.stdout.readline(), 5))["endpoint"] profile = p / "tunnel.json" profile.write_text(json.dumps({ "schema_version": 1, "ssh": {"schema_version": 1, "id": "fixture", "host": "127.0.0.1", "user": getpass.getuser(), "port": port, "identity_file": str(p / "client")}, "listen": "127.0.0.1:0", "remote_port": int(node_endpoint.rsplit(":", 1)[1]), "max_connections": 4, })) editor = await launch("dotnet", str(dll), "--self-check-connection", str(profile), env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) editor_out, editor_err = await asyncio.wait_for(editor.communicate(), 35) assert editor.returncode == 0, editor_err.decode()[:250] assert b"desktop connection selection" in editor_out assert node.returncode is None, "connection editor must preserve remote node" tunnel = await launch(str(binary), "ssh-tunnel", str(profile), env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) endpoint = json.loads(await asyncio.wait_for(tunnel.stdout.readline(), 5))["endpoint"] env["STRATA_NODE_ENDPOINT"] = endpoint for _ in range(2): app = await launch("dotnet", str(dll), "--self-check", env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await asyncio.wait_for(app.communicate(), 25) if app.returncode: raise RuntimeError("C# through real SSH failed: " + stderr.decode()[:250]) observer = await launch("dotnet", str(dll), "--self-check-tunnel-reconnect", env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) interrupted = False while True: line = await asyncio.wait_for(observer.stdout.readline(), 28) if not line: break message = line.decode().strip() if message.startswith("{") and json.loads(message)["Phase"] == "ready" and not interrupted: pid = int((p / "ssh.pid").read_text()) parent = int((await output("ps", "-o", "ppid=", "-p", str(pid))).strip()) assert parent == tunnel.pid, "refusing to signal an unowned process" os.kill(pid, signal.SIGTERM) interrupted = True assert await asyncio.wait_for(observer.wait(), 5) == 0 and interrupted # Existing listener reconnects through newly spawned owned SSH connections. tunnel.send_signal(signal.SIGINT) assert await asyncio.wait_for(tunnel.wait(), 5) == 0 assert node.returncode is None and daemon.returncode is None print("PASS: C# -> owned loopback tunnel -> real isolated OpenSSH -> Rust gRPC node; two client sessions, forced SSH disconnect/recovery with unchanged node, graceful cleanup.") finally: for process in reversed(processes): if process.returncode is None: if process is locals().get("tunnel"): process.send_signal(signal.SIGINT) try: await asyncio.wait_for(process.wait(), 5) continue except asyncio.TimeoutError: pass process.kill() await process.wait() if __name__ == "__main__": asyncio.run(main())