agent-ssh 0.4.1

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
import errno
import fcntl
import json
import os
from pathlib import Path
import pty
import select
import shutil
import socket
import stat
import struct
import subprocess
import sys
import tempfile
import termios
import time


binary = Path(sys.argv[1]).resolve()
stage = Path(tempfile.mkdtemp(prefix="agent-ssh tmux-"))
socket_path = stage / "a socket.sock"
name = "literal;$(touch INJECTED) 'β' #{pid}"
client = None
master = None


def tmux(*args, check=True):
    result = subprocess.run(
        ["tmux", "-u", "-S", str(socket_path), *args],
        capture_output=True,
        text=True,
    )
    if check:
        assert result.returncode == 0, (args, result.stdout, result.stderr)
    return result


def run(*args, check=True, env=None):
    result = subprocess.run(
        [str(binary), "tmux", "--socket", str(socket_path), *args],
        capture_output=True,
        text=True,
        env=env,
        timeout=15,
    )
    if check:
        assert result.returncode == 0, (args, result.stdout, result.stderr)
    return result


def collect(seconds=0.5):
    end = time.monotonic() + seconds
    output = bytearray()
    while time.monotonic() < end:
        if select.select([master], [], [], 0.05)[0]:
            try:
                output.extend(os.read(master, 16384))
            except OSError:
                break
        assert len(output) <= 262144
    return bytes(output)


def attach(argv, env=None):
    global client, master
    master, slave = pty.openpty()
    fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0))
    settings = {**os.environ, "TERM": "xterm-256color", "LANG": "C", "LC_ALL": "C"}
    if env:
        settings.update(env)
    client = subprocess.Popen(argv, stdin=slave, stdout=slave, stderr=slave, env=settings)
    os.close(slave)
    output = collect()
    assert client.poll() is None, ("attachment exited before terminal input", output)


def detach():
    global client, master
    client.terminate()
    client.wait(timeout=5)
    os.close(master)
    client = None
    master = None


try:
    app = stage / "dummy.py"
    app.write_text("import sys\nprint('READY',flush=True)\nfor line in sys.stdin: print('APP:'+line.strip(),flush=True)\n")
    tmux("-f", "/dev/null", "new-session", "-d", "-s", name.replace("#", "##"), "-c", str(stage), "--", sys.executable, "-u", str(app))
    assert tmux("list-sessions", "-F", "#{session_name}").stdout.strip() == name
    session_id = tmux("list-sessions", "-F", "#{session_id}").stdout.strip()
    tmux("set-option", "-t", session_id, "status", "off")
    identity = tmux("list-panes", "-a", "-F", "#{session_id}|#{pane_id}|#{pane_pid}").stdout
    sessions = json.loads(run("list", "--json").stdout)
    assert len(sessions) == 1 and sessions[0]["name"] == name, sessions
    assert sessions[0]["windows"] == 1 and sessions[0]["attached_clients"] == 0
    for missing in ["literal", "missing", "$(touch INJECTED)"]:
        refused = run("attach", "--", missing, check=False)
        assert refused.returncode != 0 and "does not exist" in refused.stderr, refused
    assert json.loads(run("list", "--json").stdout) == sessions
    attach([str(binary), "tmux", "--socket", str(socket_path), "attach", "--", name])
    observation = json.loads(run("clients", "--json").stdout)
    assert observation["version"] == 1 and observation["socket"] == str(socket_path)
    assert len(observation["clients"]) == 1, observation
    observed = observation["clients"][0]
    assert observed["session"] == name and observed["session_id"] == session_id
    assert observed["pid"] == client.pid and observed["start_time"] > 0
    assert observed["tty"].startswith("/dev/pts/")
    assert isinstance(observed["socket_verified"], bool)
    os.write(master, b"first-client\n")
    assert b"APP:first-client" in collect(), "ordinary input did not reach existing process"
    detach()
    assert json.loads(run("clients", "--json").stdout)["clients"] == []
    assert tmux("list-panes", "-a", "-F", "#{session_id}|#{pane_id}|#{pane_pid}").stdout == identity
    attach([str(binary), "tmux", "--socket", str(socket_path), "attach", "--", name])
    os.write(master, b"reattached-client\n")
    assert b"APP:reattached-client" in collect()
    detach()
    helper = stage / "agent tool 'quoted'"
    shutil.copyfile(binary, helper)
    helper.chmod(0o700)
    ssh = stage / "ssh"
    log = stage / "ssh-argv.json"
    ssh.write_text(
        "#!" + sys.executable + "\nimport json,os,sys\n"
        "open(os.environ['SSH_ARGV_LOG'],'w').write(json.dumps(sys.argv[1:]))\n"
        "os.execv('/bin/sh',['/bin/sh','-c',sys.argv[-1]])\n"
    )
    ssh.chmod(0o700)
    env = {**os.environ, "PATH": str(stage) + os.pathsep + os.environ["PATH"], "SSH_ARGV_LOG": str(log)}
    remote = ["--on", "fixture-host", "--remote-program", str(helper)]
    assert json.loads(run(*remote, "list", "--json", env=env).stdout)[0]["name"] == name
    assert "-t" not in json.loads(log.read_text())
    attach([str(binary), "tmux", "--socket", str(socket_path), *remote, "attach", "--", name], env)
    os.write(master, b"remote-shell-quoted\n")
    assert b"APP:remote-shell-quoted" in collect()
    assert "-t" in json.loads(log.read_text())
    detach()
    assert not (stage / "INJECTED").exists()
    assert tmux("list-panes", "-a", "-F", "#{session_id}|#{pane_id}|#{pane_pid}").stdout == identity
    print(json.dumps({"passed": True, "local_list": True, "missing_attach_did_not_create": True, "pty_input_and_reattach": True, "ssh_shell_argument_boundary": True, "process_identity_preserved": True, "ssh_scope": "local fixture executes the actual remote command through a POSIX shell; not a network SSH test"}))
finally:
    if client is not None:
        detach()
    tmux("kill-server", check=False)
    if socket_path.exists():
        for _ in range(50):
            connection = socket.socket(socket.AF_UNIX)
            code = connection.connect_ex(str(socket_path))
            connection.close()
            if code in (errno.ECONNREFUSED, errno.ENOENT):
                break
            time.sleep(0.02)
        assert code in (errno.ECONNREFUSED, errno.ENOENT)
        if socket_path.exists():
            info = socket_path.lstat()
            assert stat.S_ISSOCK(info.st_mode) and info.st_uid == os.getuid()
            socket_path.unlink()
    shutil.rmtree(stage)