agent-ssh 0.4.4

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
#![cfg(windows)]

use serde_json::{Value, json};
use std::{
    fs,
    path::PathBuf,
    process::{Command, Stdio},
    thread,
    time::{Duration, Instant},
};

struct Fixture(PathBuf);

impl Fixture {
    fn new() -> Self {
        let root = std::env::temp_dir().join(format!(
            "agent-ssh-checkpoint-test-{}",
            uuid::Uuid::new_v4()
        ));
        let directory = root.join("System32/WindowsPowerShell/v1.0");
        fs::create_dir_all(&directory).unwrap();
        let source = root.join("collector.cs");
        fs::write(&source, include_str!("checkpoint_collector.cs")).unwrap();
        let compiler = PathBuf::from(std::env::var_os("SystemRoot").unwrap())
            .join("Microsoft.NET/Framework64/v4.0.30319/csc.exe");
        let output = Command::new(compiler)
            .args(["/nologo", "/target:exe"])
            .arg(format!(
                "/out:{}",
                directory.join("powershell.exe").display()
            ))
            .arg(source)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stdout)
        );
        Self(root)
    }

    fn command(&self, name: &str) -> Command {
        let mut command = Command::new(env!("CARGO_BIN_EXE_agent-ssh"));
        command
            .args([
                "save",
                self.0.join(name).to_str().unwrap(),
                "--shell-directory",
                self.0.to_str().unwrap(),
            ])
            .args(["--window", "original-caption"])
            .env("SystemRoot", &self.0)
            .env("CHECKPOINT_TEST_ROOT", &self.0);
        command
    }

    fn replies(&self, first: Value, next: Option<Value>) {
        let _ = fs::remove_file(self.0.join("attempts"));
        let _ = fs::remove_file(self.0.join("selectors"));
        fs::write(self.0.join("reply-0.json"), first.to_string()).unwrap();
        let _ = fs::remove_file(self.0.join("reply-1.json"));
        let _ = fs::remove_file(self.0.join("reply-2.json"));
        if let Some(next) = next {
            fs::write(self.0.join("reply-1.json"), next.to_string()).unwrap();
        }
    }

    fn attempts(&self) -> usize {
        fs::read_to_string(self.0.join("attempts"))
            .unwrap_or_default()
            .parse()
            .unwrap_or(0)
    }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        let root = self.0.canonicalize().unwrap();
        assert_eq!(
            root.parent(),
            Some(std::env::temp_dir().canonicalize().unwrap().as_path())
        );
        assert!(
            root.file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .starts_with("agent-ssh-checkpoint-test-")
        );
        let _ = fs::remove_dir_all(root);
    }
}

fn observation(complete: bool) -> Value {
    let records: Vec<_> = (1..=2).map(|n| json!({
        "pid":n+10,"parent_pid":1,"start_ticks":504911232000000100u64+n,
        "executable":"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
        "argv":["powershell.exe"],"session_id":format!("00000000-0000-0000-0000-{n:012}"),"terminal_pid":20
    })).collect();
    let mut actions = vec![
        json!({"action":"newTab","sessionId":"00000000-0000-0000-0000-000000000001","tabTitle":"first"}),
    ];
    if complete {
        actions.push(json!({"action":"splitPane","sessionId":"00000000-0000-0000-0000-000000000002","tabTitle":"second","splitMode":"manual","split":"right","size":0.4}));
    }
    json!({"hwnd":"100","scope":{"hwnd":"100","terminal_pid":20,"terminal_start_ticks":100},"age_seconds":3.0,"records":records,"connections":[],"layout":{"persistedWindowLayouts":[{"tabLayout":actions}]}})
}

fn wait_for_sample(fixture: &Fixture) {
    let deadline = Instant::now() + Duration::from_secs(10);
    while fixture.attempts() == 0 {
        assert!(Instant::now() < deadline, "collector was not invoked");
        thread::sleep(Duration::from_millis(10));
    }
    thread::sleep(Duration::from_millis(150));
}

#[test]
fn save_waits_for_all_panes_and_never_writes_incomplete_or_fatal_capture() {
    let fixture = Fixture::new();
    let mut closed = observation(true);
    closed["layout"]["persistedWindowLayouts"][0]["tabLayout"]
        .as_array_mut()
        .unwrap()
        .push(json!({
            "action":"splitPane","sessionId":"00000000-0000-0000-0000-000000000003",
            "splitMode":"manual","split":"down","size":0.5,
        }));
    for (name, initial) in [
        ("complete.json", observation(false)),
        ("closed.json", closed),
    ] {
        fixture.replies(initial, Some(observation(true)));
        if name == "complete.json" {
            fs::copy(
                fixture.0.join("reply-0.json"),
                fixture.0.join("reply-1.json"),
            )
            .unwrap();
            fs::write(
                fixture.0.join("reply-2.json"),
                observation(true).to_string(),
            )
            .unwrap();
        }
        let mut waiting = fixture
            .command(name)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap();
        wait_for_sample(&fixture);
        assert!(waiting.try_wait().unwrap().is_none());
        assert!(!fixture.0.join(name).exists());
        let output = waiting.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let expected_attempts = if name == "complete.json" { 3 } else { 2 };
        assert_eq!(fixture.attempts(), expected_attempts);
        assert_eq!(
            fs::read_to_string(fixture.0.join("selectors")).unwrap(),
            if expected_attempts == 3 {
                "original-caption\n100\n100\n"
            } else {
                "original-caption\n100\n"
            }
        );
        let errors = String::from_utf8(output.stderr).unwrap();
        assert_eq!(errors.matches("Waiting for Terminal layout").count(), 1);
        assert!(!errors.contains('\u{1b}'));
        let state = agent_ssh::snapshot::SavedState::parse(
            &fs::read_to_string(fixture.0.join(name)).unwrap(),
        )
        .unwrap();
        assert_eq!(state.panes().len(), 2);
        assert_eq!(state.tabs.len(), 1);
        let saved_output = String::from_utf8(output.stdout).unwrap();
        assert!(saved_output.contains("Saved 2 panes"));
        assert!(!saved_output.contains("Waiting for Terminal layout"));
    }

    let mut flagged = observation(true);
    flagged["records"][0]["argv"] = json!([
        "powershell.exe",
        "-NoExit",
        "-File",
        "SYNTHETIC_STARTUP_SECRET"
    ]);
    fixture.replies(flagged, None);
    let output = fixture.command("flagged.json").output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let saved = fs::read_to_string(fixture.0.join("flagged.json")).unwrap();
    let state = agent_ssh::snapshot::SavedState::parse(&saved).unwrap();
    assert_eq!(state.panes().len(), 2);
    assert!(!state.restorable);
    assert_eq!(
        state
            .panes()
            .iter()
            .filter(|pane| matches!(
                pane.target,
                agent_ssh::snapshot::RecoveryTarget::Unavailable { .. }
            ))
            .count(),
        1
    );
    assert!(!saved.contains("SYNTHETIC_STARTUP_SECRET"));
    assert!(!String::from_utf8_lossy(&output.stderr).contains("SYNTHETIC_STARTUP_SECRET"));

    fixture.replies(observation(false), None);
    let mut cancelled = fixture
        .command("cancelled.json")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();
    wait_for_sample(&fixture);
    assert!(cancelled.try_wait().unwrap().is_none());
    cancelled.kill().unwrap();
    cancelled.wait().unwrap();
    assert!(!fixture.0.join("cancelled.json").exists());

    for (name, scope) in [
        (
            "replacement.json",
            json!({"hwnd":"101","terminal_pid":21,"terminal_start_ticks":200}),
        ),
        (
            "reused.json",
            json!({"hwnd":"100","terminal_pid":20,"terminal_start_ticks":200}),
        ),
    ] {
        let mut replacement = observation(true);
        replacement["hwnd"] = scope["hwnd"].clone();
        replacement["scope"] = scope;
        fixture.replies(observation(false), Some(replacement));
        let failed = fixture.command(name).output().unwrap();
        assert!(!failed.status.success());
        assert!(String::from_utf8_lossy(&failed.stderr).contains("window identity changed"));
        assert_eq!(fixture.attempts(), 2);
        assert!(!fixture.0.join(name).exists());
    }

    fixture.replies(json!({"invalid":true}), Some(observation(true)));
    let failed = fixture.command("invalid.json").output().unwrap();
    assert!(!failed.status.success());
    assert_eq!(fixture.attempts(), 1);
    assert!(!fixture.0.join("invalid.json").exists());
}

#[test]
fn passive_helper_classifies_shell_roots_and_configuration_without_ui_actions() {
    let powershell = PathBuf::from(std::env::var_os("SystemRoot").unwrap())
        .join("System32/WindowsPowerShell/v1.0/powershell.exe");
    let script = std::env::temp_dir().join(format!(
        "agent-ssh-settings-boundary-{}.ps1",
        uuid::Uuid::new_v4()
    ));
    fs::write(&script, r#"param([string]$Source)
$ErrorActionPreference='Stop'
$sourceText=[IO.File]::ReadAllText($Source)
$ancestryStart=$sourceText.IndexOf('function TerminalForProcess(')
$ancestryEnd=$sourceText.IndexOf('$records = @()')
. ([scriptblock]::Create($sourceText.Substring($ancestryStart,$ancestryEnd-$ancestryStart)))
$byPid=@{}
foreach($row in @(
    @{ProcessId=1;ParentProcessId=0;Name='WindowsTerminal.exe'},
    @{ProcessId=2;ParentProcessId=1;Name='powershell.exe';CommandLine='powershell.exe -NoExit -File bootstrap.ps1'},
    @{ProcessId=3;ParentProcessId=2;Name='pwsh.exe'},
    @{ProcessId=$PID;ParentProcessId=2;Name='powershell.exe'},
    @{ProcessId=5;ParentProcessId=$PID;Name='powershell.exe'},
    @{ProcessId=6;ParentProcessId=2;Name='ssh.exe'},
    @{ProcessId=7;ParentProcessId=2;Name='utility.exe'},
    @{ProcessId=8;ParentProcessId=7;Name='powershell.exe'}
)){$byPid[[uint32]$row.ProcessId]=[pscustomobject]$row}
if((TerminalForProcess $byPid[[uint32]2]) -ne 1){throw 'Flagged root shell was omitted'}
foreach($nested in @(3,$PID,5,8)){
    if($null -ne (TerminalForProcess $byPid[[uint32]$nested])){throw 'Nested or collector shell was admitted'}
}
if((TerminalForProcess $byPid[[uint32]6]) -ne 1){throw 'Root shell suppressed its SSH child'}
$start=$sourceText.IndexOf('$settingsPath = ')
$end=$sourceText.IndexOf('if (!(Test-Path -LiteralPath $statePath')
if($start -lt 0 -or $end -le $start){throw 'Settings boundary unavailable'}
$check=[scriptblock]::Create($sourceText.Substring($start,$end-$start))
$root=Join-Path ([IO.Path]::GetTempPath()) ('agent-ssh-settings-test-'+[guid]::NewGuid().ToString('N'))
$null=New-Item -ItemType Directory -Path $root
$statePath=Join-Path $root 'state.json'
try {
    $enabled=@'
{
 // "firstWindowPreference":"defaultProfile",
 "url":"http://localhost/", "text":"quotes\" /* not comment */ ,]",
 "firstWindowPreference":"persistedWindowLayout",
 "array":[1,2,], /* trailing comment */
}
'@
    foreach($mode in @('persistedLayout','persistedLayoutAndContent','persistedWindowLayout')){
        [IO.File]::WriteAllText((Join-Path $root 'settings.json'),$enabled.Replace('persistedWindowLayout',$mode))
        & $check
    }
    foreach($invalid in @('{"firstWindowPreference":"defaultProfile"}', '{"firstWindowPreference":["persistedWindowLayout"]}', '{"firstWindowPreference":"persistedWindowLayout","other":tru/*x*/e}', '{}', '{invalid')){
        [IO.File]::WriteAllText((Join-Path $root 'settings.json'),$invalid)
        $rejected=$false
        try { & $check } catch { $rejected=$true }
        if(!$rejected){throw 'Disabled or invalid settings were accepted'}
    }
    [IO.File]::WriteAllText((Join-Path $root 'settings.json'),$enabled)
    $readEnd=$sourceText.IndexOf('$selectedRecords = ')
    $read=[scriptblock]::Create($sourceText.Substring($start,$readEnd-$start))
    $null=New-Item -ItemType Directory -Path $statePath
    $rejected=$false
    try { & $read } catch { $rejected=$_.Exception.Message -eq 'Native layout checkpoint path is not a file' }
    if(!$rejected){throw 'Non-file checkpoint was not rejected immediately'}
} finally {
    $resolved=[IO.Path]::GetFullPath($root)
    $temporary=[IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\')+'\'
    if(!$resolved.StartsWith($temporary,[StringComparison]::OrdinalIgnoreCase) -or [IO.Path]::GetFileName($resolved) -notmatch '^agent-ssh-settings-test-[0-9a-f]{32}$'){throw 'Invalid private test cleanup path'}
    Remove-Item -LiteralPath $resolved -Recurse -Force
}
"#).unwrap();
    let output = Command::new(powershell)
        .args(["-NoProfile", "-NonInteractive", "-File"])
        .arg(&script)
        .arg("-Source")
        .arg(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("scripts/passive-windows.ps1"))
        .output()
        .unwrap();
    fs::remove_file(script).unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}