Cotton code
261 lines · 9.2 KB · RustRaw
//! `cotton-session-host hook <event>`, against a fake daemon.//!//! The fake is a unix listener this test owns: it reads the line the hook//! sent, checks it, and answers whatever the case needs. That is the whole//! contract between an agent's hook and this host, and it is provable without//! an agent, a session or a subscription.//!//! The BINARY is driven too, not just the function — the subcommand parsing,//! the stdin read and what lands on stdout are the part a person can get wrong//! in `main.rs`.use std::io::Write as _;use std::path::Path;use std::process::Stdio;use std::time::Duration;use cotton_session_host::hook::{run, HookOutcome};use cotton_session_host::protocol::{line, parse, Event, Request};use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader};use tokio::net::UnixListener;/// A daemon that reads one line and answers `answer`.////// It hands back what it read, so a test can assert on the message the hook/// actually sent rather than on the one it meant to.fn fake_daemon(    socket: &Path,    answer: Option<Event>,) -> (    tokio::sync::oneshot::Receiver<Request>,    tokio::task::JoinHandle<()>,) {    let listener = UnixListener::bind(socket).expect("the fake daemon binds");    let (saw, seen) = tokio::sync::oneshot::channel();    let task = tokio::spawn(async move {        let Ok((stream, _)) = listener.accept().await else {            return;        };        let (read, mut write) = stream.into_split();        let mut lines = BufReader::new(read).lines();        if let Ok(Some(text)) = lines.next_line().await {            if let Ok(request) = parse::<Request>(&text) {                let _ = saw.send(request);            }        }        if let Some(answer) = answer {            if let Ok(text) = line(&answer) {                let _ = write.write_all(text.as_bytes()).await;                let _ = write.flush().await;            }        }        // Hold the connection open until the hook goes away, so a timeout is        // really a timeout and not a closed socket.        tokio::time::sleep(Duration::from_secs(30)).await;    });    (seen, task)}#[tokio::test]async fn a_blocking_hook_prints_exactly_the_json_the_daemon_encoded() {    let dir = tempfile::tempdir().expect("a scratch directory");    let socket = dir.path().join("session-host.sock");    let stdout_json = serde_json::json!({        "hookSpecificOutput": {            "hookEventName": "PermissionRequest",            "permissionDecision": "allow"        }    });    let (seen, task) = fake_daemon(        &socket,        Some(Event::Decision {            session_id: "s-1".to_string(),            request_id: "req-1".to_string(),            stdout: stdout_json.clone(),        }),    );    let outcome = run(        "PermissionRequest",        &socket,        r#"{"session_id":"s-1","request_id":"req-1","hook_event_name":"PermissionRequest"}"#,        Duration::from_secs(5),    )    .await;    assert_eq!(outcome.stdout, format!("{stdout_json}\n"));    let sent = seen.await.expect("the daemon saw the hook's message");    let Request::Hook {        event, session_id, ..    } = sent    else {        panic!("a hook sends a hook message");    };    assert_eq!(event, "PermissionRequest");    assert_eq!(session_id.as_deref(), Some("s-1"));    task.abort();}#[tokio::test]async fn a_blocking_hook_that_nobody_answers_in_time_prints_nothing() {    let dir = tempfile::tempdir().expect("a scratch directory");    let socket = dir.path().join("session-host.sock");    let (_seen, task) = fake_daemon(&socket, None);    let outcome = run(        "PermissionRequest",        &socket,        r#"{"session_id":"s-1"}"#,        Duration::from_millis(200),    )    .await;    assert_eq!(        outcome,        HookOutcome::silent(),        "nothing printed is what makes the agent fall back to its own prompt"    );    task.abort();}#[tokio::test]async fn a_non_blocking_hook_forwards_and_returns_without_waiting_for_anything() {    let dir = tempfile::tempdir().expect("a scratch directory");    let socket = dir.path().join("session-host.sock");    let (seen, task) = fake_daemon(&socket, None);    let outcome = tokio::time::timeout(        Duration::from_secs(5),        run(            "Stop",            &socket,            r#"{"session_id":"s-1","transcript_path":"/work/t.jsonl"}"#,            Duration::from_secs(600),        ),    )    .await    .expect("a Stop hook does not block on a decision");    assert_eq!(outcome, HookOutcome::silent());    let Request::Hook { event, payload, .. } = seen.await.expect("the daemon saw it") else {        panic!("a hook sends a hook message");    };    assert_eq!(event, "Stop");    assert_eq!(payload["transcript_path"], "/work/t.jsonl");    task.abort();}#[tokio::test]async fn the_binary_reads_stdin_forwards_it_and_prints_the_decision() {    let dir = tempfile::tempdir().expect("a scratch directory");    let data_dir = dir.path().join("CottonDB");    std::fs::create_dir_all(&data_dir).expect("the data directory is made");    let socket = data_dir.join("session-host.sock");    let stdout_json = serde_json::json!({        "hookSpecificOutput": {            "hookEventName": "PermissionRequest",            "decision": {"behavior": "deny", "message": "no"}        }    });    let (_seen, task) = fake_daemon(        &socket,        Some(Event::Decision {            session_id: "s-1".to_string(),            request_id: "req-1".to_string(),            stdout: stdout_json.clone(),        }),    );    let said = tokio::task::spawn_blocking(move || {        let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_cotton-session-host"))            .args(["hook", "PermissionRequest"])            .env("COTTON_MAC_DATA_DIR", &data_dir)            .stdin(Stdio::piped())            .stdout(Stdio::piped())            .spawn()            .expect("the host binary runs");        child            .stdin            .take()            .expect("stdin is a pipe")            .write_all(br#"{"session_id":"s-1","request_id":"req-1"}"#)            .expect("the hook's stdin is written");        let out = child.wait_with_output().expect("the hook finishes");        assert!(out.status.success(), "a hook always exits 0");        String::from_utf8_lossy(&out.stdout).to_string()    })    .await    .expect("the blocking half joins");    let printed: serde_json::Value =        serde_json::from_str(said.trim()).expect("what it printed is JSON");    assert_eq!(printed, stdout_json);    task.abort();}#[tokio::test]async fn the_binary_prints_nothing_and_still_exits_zero_when_no_host_is_listening() {    let dir = tempfile::tempdir().expect("a scratch directory");    let data_dir = dir.path().join("CottonDB");    std::fs::create_dir_all(&data_dir).expect("the data directory is made");    let out = tokio::task::spawn_blocking(move || {        let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_cotton-session-host"))            .args(["hook", "PermissionRequest"])            .env("COTTON_MAC_DATA_DIR", &data_dir)            .stdin(Stdio::piped())            .stdout(Stdio::piped())            .spawn()            .expect("the host binary runs");        child            .stdin            .take()            .expect("stdin is a pipe")            .write_all(b"{}")            .expect("the hook's stdin is written");        child.wait_with_output().expect("the hook finishes")    })    .await    .expect("the blocking half joins");    assert!(out.status.success(), "a hook always exits 0");    assert!(        out.stdout.is_empty(),        "no daemon is no opinion — got {:?}",        String::from_utf8_lossy(&out.stdout)    );}/// RULE: Cotton Dev's helper (COTTON_FLAVOR unset) refuses the real app's folder — a command fails naming it, a hook stays silent and exits 0.#[test]fn the_helper_refuses_the_other_app_s_folder_before_touching_it() {    let home = tempfile::tempdir().expect("a synthetic home");    let real = home.path().join("CottonDB");    let sessions = std::process::Command::new(env!("CARGO_BIN_EXE_cotton-session-host"))        .arg("sessions")        .env("HOME", home.path())        .env("COTTON_MAC_DATA_DIR", &real)        .env_remove("COTTON_FLAVOR")        .output()        .expect("the host binary runs");    assert!(!sessions.status.success(), "a refused folder is a failed command");    let said = String::from_utf8_lossy(&sessions.stderr);    assert!(said.contains(&real.display().to_string()), "the refusal names the folder: {said}");    let mut hook = std::process::Command::new(env!("CARGO_BIN_EXE_cotton-session-host"))        .args(["hook", "Stop"])        .env("HOME", home.path())        .env("COTTON_MAC_DATA_DIR", &real)        .env_remove("COTTON_FLAVOR")        .stdin(Stdio::piped())        .stdout(Stdio::piped())        .stderr(Stdio::piped())        .spawn()        .expect("the host binary runs");    hook.stdin.take().expect("stdin").write_all(b"{}").expect("stdin written");    let out = hook.wait_with_output().expect("the hook finishes");    assert!(out.status.success(), "a hook always exits 0");    assert!(out.stdout.is_empty(), "and has no opinion");    assert!(!real.exists(), "the real app's folder was never made");}