Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-cli/tests/e2e_login_cancellation.rs

Raw
//! SMH-SPEC-SPEC0001, SMH-SPEC-PLUG0001: interrupted OAuth login process boundary.

#![cfg(target_os = "linux")]

use nix::sys::signal::{Signal, kill};
use nix::unistd::Pid;
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{Ipv4Addr, TcpListener, TcpStream};
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc;
use std::time::Duration;

const DEADLINE: Duration = Duration::from_secs(15);
fn binary() -> PathBuf {
    std::env::current_exe()
        .unwrap()
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join(format!("smith{}", std::env::consts::EXE_SUFFIX))
}

#[test]
#[expect(
    clippy::disallowed_methods,
    reason = "fixture reads its owned bounded OAuth store"
)]
fn interrupting_login_during_discovery_exits_without_publishing_profile() {
    let root = std::env::temp_dir().join(format!(
        "smith-login-cancellation-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&root).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
    }
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
    let origin = format!("http://{}", listener.local_addr().unwrap());
    let (ready_send, ready_receive) = mpsc::sync_channel(1);
    let (closed_send, closed_receive) = mpsc::sync_channel(1);
    let fixture = std::thread::spawn(move || {
        let mut stream = accept(&listener, DEADLINE).unwrap();
        stream.set_read_timeout(Some(DEADLINE)).unwrap();
        let mut request = Vec::new();
        let mut byte = [0];
        while !request.ends_with(b"\r\n\r\n") {
            stream.read_exact(&mut byte).unwrap();
            request.push(byte[0]);
            assert!(request.len() <= 8192);
        }
        assert!(request.starts_with(b"GET /.well-known/openid-configuration HTTP/1.1\r\n"));
        ready_send.send(()).unwrap();
        let mut byte = [0];
        assert_eq!(
            stream.read(&mut byte).unwrap(),
            0,
            "cancelled discovery request wrote after dispatch"
        );
        closed_send.send(()).unwrap();
    });
    let mut command = Command::new(binary());
    command
        .env_clear()
        .env("HOME", &root)
        .env("XDG_DATA_HOME", root.join("data"))
        .env("XDG_CONFIG_HOME", root.join("config"))
        .env("XDG_STATE_HOME", root.join("state"))
        .env("XDG_RUNTIME_DIR", &root)
        .args(["login", "--fixture-issuer", &origin])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = command.spawn().unwrap();
    let process = Pid::from_raw(i32::try_from(child.id()).unwrap());
    ready_receive.recv_timeout(DEADLINE).unwrap();
    kill(process, Signal::SIGINT).unwrap();
    let (status_send, status_receive) = mpsc::sync_channel(1);
    std::thread::spawn(move || {
        let _sent = status_send.send(child.wait());
    });
    let status = match status_receive.recv_timeout(DEADLINE) {
        Ok(status) => status.unwrap(),
        Err(error) => {
            let _killed = kill(process, Signal::SIGKILL);
            panic!("interrupted login missed exit deadline: {error}");
        }
    };
    closed_receive.recv_timeout(DEADLINE).unwrap();
    fixture.join().unwrap();
    assert!(status.success());
    let path = root
        .join("data/smith/auth/oauth-fixtures")
        .join(smith::sha256::digest_hex(origin.as_bytes()))
        .join("profiles.json");
    let store: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
    assert_eq!(store["profiles"], serde_json::json!([]));
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
#[expect(
    clippy::disallowed_methods,
    reason = "fixture reads its owned bounded OAuth store"
)]
fn interrupting_with_partial_callback_exits_without_publishing_profile() {
    let root = std::env::temp_dir().join(format!(
        "smith-login-cancellation-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&root).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
    }
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
    let origin = format!("http://{}", listener.local_addr().unwrap());
    let issuer = origin.clone();
    let fixture = std::thread::spawn(move || {
        let mut discovery = accept(&listener, DEADLINE).unwrap();
        assert_eq!(route(&mut discovery), "/.well-known/openid-configuration");
        respond(
            &mut discovery,
            json!({"issuer":issuer,"authorization_endpoint":format!("{issuer}/authorize"),"token_endpoint":format!("{issuer}/token"),"jwks_uri":format!("{issuer}/keys")}),
        );
    });
    let mut command = Command::new(binary());
    command
        .env_clear()
        .env("HOME", &root)
        .env("XDG_DATA_HOME", root.join("data"))
        .env("XDG_CONFIG_HOME", root.join("config"))
        .env("XDG_STATE_HOME", root.join("state"))
        .env("XDG_RUNTIME_DIR", &root)
        .args(["login", "--fixture-issuer", &origin])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = command.spawn().unwrap();
    fixture.join().unwrap();
    let stdout = child.stdout.take().unwrap();
    let (send, receive) = mpsc::sync_channel(1);
    std::thread::spawn(move || {
        let mut line = String::new();
        BufReader::new(stdout).read_line(&mut line).unwrap();
        let _sent = send.send(line);
    });
    let line = receive.recv_timeout(DEADLINE).unwrap();
    let url = line.trim().strip_prefix("Continue with ChatGPT: ").unwrap();
    assert!(url.starts_with(&format!("{origin}/authorize?")));
    let query = url.split_once('?').unwrap().1;
    let redirect = query
        .split('&')
        .find_map(|field| field.strip_prefix("redirect_uri="))
        .unwrap();
    let authority = decode(redirect)
        .strip_prefix("http://")
        .unwrap()
        .split_once('/')
        .unwrap()
        .0
        .to_string();
    let mut callback = TcpStream::connect_timeout(&authority.parse().unwrap(), DEADLINE).unwrap();
    callback.set_read_timeout(Some(DEADLINE)).unwrap();
    callback
        .write_all(b"GET /auth/callback?state=partial")
        .unwrap();
    let process = Pid::from_raw(i32::try_from(child.id()).unwrap());
    kill(process, Signal::SIGINT).unwrap();
    wait_for_exit(child, process);
    let mut response = Vec::new();
    callback.read_to_end(&mut response).unwrap();
    assert!(response.is_empty(), "partial callback received a response");
    let path = root
        .join("data/smith/auth/oauth-fixtures")
        .join(smith::sha256::digest_hex(origin.as_bytes()))
        .join("profiles.json");
    let store: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
    assert_eq!(store["profiles"], json!([]));
    std::fs::remove_dir_all(root).unwrap();
}

#[derive(Clone, Copy)]
enum OAuthWait {
    Token,
    Jwks,
}

#[test]
fn interrupting_after_accepted_callback_closes_token_or_jwks_without_publishing_profile() {
    for wait in [OAuthWait::Token, OAuthWait::Jwks] {
        interrupt_after_callback(wait);
    }
}

#[expect(
    clippy::disallowed_methods,
    reason = "fixture reads its owned bounded OAuth store"
)]
fn interrupt_after_callback(wait: OAuthWait) {
    let root = std::env::temp_dir().join(format!(
        "smith-login-cancellation-{}",
        smith::id::SessionId::new()
    ));
    std::fs::create_dir(&root).unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
    }
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
    let origin = format!("http://{}", listener.local_addr().unwrap());
    let (ready_send, ready_receive) = mpsc::sync_channel(1);
    let (closed_send, closed_receive) = mpsc::sync_channel(1);
    let issuer = origin.clone();
    let fixture = std::thread::spawn(move || {
        let mut discovery = accept(&listener, DEADLINE).unwrap();
        assert_eq!(route(&mut discovery), "/.well-known/openid-configuration");
        respond(
            &mut discovery,
            json!({"issuer":issuer,"authorization_endpoint":format!("{issuer}/authorize"),"token_endpoint":format!("{issuer}/token"),"jwks_uri":format!("{issuer}/keys")}),
        );
        let mut token = accept(&listener, DEADLINE).unwrap();
        assert_eq!(route(&mut token), "/token");
        if matches!(wait, OAuthWait::Token) {
            ready_send.send(()).unwrap();
            await_close(token);
            closed_send.send(()).unwrap();
            return;
        }
        respond(
            &mut token,
            json!({"access_token":"fixture-access","refresh_token":"fixture-refresh","id_token":"eyJhbGciOiJFZERTQSIsImtpZCI6ImZpeHR1cmUiLCJ0eXAiOiJKV1QifQ.e30.AA","token_type":"Bearer","expires_in":3600,"scope":"openid chatgpt.tokens.use.direct"}),
        );
        let mut keys = accept(&listener, DEADLINE).unwrap();
        assert_eq!(route(&mut keys), "/keys");
        ready_send.send(()).unwrap();
        await_close(keys);
        closed_send.send(()).unwrap();
    });
    let mut command = Command::new(binary());
    command
        .env_clear()
        .env("HOME", &root)
        .env("XDG_DATA_HOME", root.join("data"))
        .env("XDG_CONFIG_HOME", root.join("config"))
        .env("XDG_STATE_HOME", root.join("state"))
        .env("XDG_RUNTIME_DIR", &root)
        .args(["login", "--fixture-issuer", &origin])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = command.spawn().unwrap();
    send_accepted_callback(&mut child, &origin);
    let process = Pid::from_raw(i32::try_from(child.id()).unwrap());
    ready_receive.recv_timeout(DEADLINE).unwrap();
    kill(process, Signal::SIGINT).unwrap();
    wait_for_exit(child, process);
    closed_receive.recv_timeout(DEADLINE).unwrap();
    fixture.join().unwrap();
    let path = root
        .join("data/smith/auth/oauth-fixtures")
        .join(smith::sha256::digest_hex(origin.as_bytes()))
        .join("profiles.json");
    let store: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
    assert_eq!(store["profiles"], json!([]));
    std::fs::remove_dir_all(root).unwrap();
}

#[expect(
    clippy::disallowed_methods,
    reason = "fixture bounds every HTTP header before retaining it"
)]
fn route(stream: &mut TcpStream) -> String {
    stream.set_read_timeout(Some(DEADLINE)).unwrap();
    let mut reader = BufReader::new(stream);
    let mut line = String::new();
    assert_ne!(reader.read_line(&mut line).unwrap(), 0, "request EOF");
    while !line.ends_with("\r\n\r\n") {
        let mut header = String::new();
        assert_ne!(reader.read_line(&mut header).unwrap(), 0, "header EOF");
        line.push_str(&header);
        assert!(line.len() <= 8192);
        if header == "\r\n" {
            break;
        }
    }
    line.split_whitespace().nth(1).unwrap().to_string()
}

fn accept(listener: &TcpListener, timeout: Duration) -> std::io::Result<TcpStream> {
    use std::os::fd::AsRawFd;
    listener.set_nonblocking(true)?;
    let mut descriptor = nix::libc::pollfd {
        fd: listener.as_raw_fd(),
        events: nix::libc::POLLIN,
        revents: 0,
    };
    // SAFETY: one initialized descriptor borrows the live listener for this call.
    match unsafe {
        nix::libc::poll(
            &raw mut descriptor,
            1,
            timeout.as_millis().try_into().unwrap(),
        )
    } {
        -1 => Err(std::io::Error::last_os_error()),
        0 => Err(std::io::ErrorKind::TimedOut.into()),
        _ => listener.accept().map(|(stream, _)| stream),
    }
}

#[test]
fn fixture_accept_deadline_handles_absent_and_ready_clients() {
    let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
    assert_eq!(
        accept(&listener, Duration::ZERO).unwrap_err().kind(),
        std::io::ErrorKind::TimedOut
    );
    let _client = TcpStream::connect_timeout(&listener.local_addr().unwrap(), DEADLINE).unwrap();
    accept(&listener, Duration::ZERO).unwrap();
}

fn respond(stream: &mut TcpStream, body: Value) {
    let body = serde_json::to_vec(&body).unwrap();
    write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).unwrap();
    stream.write_all(&body).unwrap();
}

fn await_close(mut stream: TcpStream) {
    stream.set_read_timeout(Some(DEADLINE)).unwrap();
    let mut bytes = 0;
    let mut buffer = [0; 256];
    while let read @ 1.. = stream.read(&mut buffer).unwrap() {
        bytes += read;
        assert!(
            bytes <= 8192,
            "cancelled request wrote beyond request bound"
        );
    }
}

#[expect(
    clippy::disallowed_methods,
    reason = "fixture consumes one bounded CLI URL and callback response"
)]
fn send_accepted_callback(child: &mut Child, origin: &str) {
    let stdout = child.stdout.take().unwrap();
    let (send, receive) = mpsc::sync_channel(1);
    std::thread::spawn(move || {
        let mut line = String::new();
        BufReader::new(stdout).read_line(&mut line).unwrap();
        let _sent = send.send(line);
    });
    let line = receive.recv_timeout(DEADLINE).unwrap();
    let url = line.trim().strip_prefix("Continue with ChatGPT: ").unwrap();
    assert!(url.starts_with(&format!("{origin}/authorize?")));
    let query = url.split_once('?').unwrap().1;
    let state = query
        .split('&')
        .find_map(|field| field.strip_prefix("state="))
        .unwrap();
    let redirect = query
        .split('&')
        .find_map(|field| field.strip_prefix("redirect_uri="))
        .unwrap();
    let redirect = decode(redirect);
    let authority = redirect.strip_prefix("http://").unwrap();
    let (host, path) = authority.split_once('/').unwrap();
    let mut callback = TcpStream::connect_timeout(&host.parse().unwrap(), DEADLINE).unwrap();
    write!(callback, "GET /{path}?state={state}&code=fixture-code&client_id=oaiapp_fixture HTTP/1.1\r\nHost: {host}\r\n\r\n").unwrap();
    callback.set_read_timeout(Some(DEADLINE)).unwrap();
    let mut response = Vec::new();
    callback.read_to_end(&mut response).unwrap();
}

fn decode(value: &str) -> String {
    let mut output = Vec::new();
    let mut bytes = value.bytes();
    while let Some(byte) = bytes.next() {
        output.push(match byte {
            b'%' => u8::from_str_radix(
                std::str::from_utf8(&[bytes.next().unwrap(), bytes.next().unwrap()]).unwrap(),
                16,
            )
            .unwrap(),
            b'+' => b' ',
            byte => byte,
        });
    }
    String::from_utf8(output).unwrap()
}

fn wait_for_exit(mut child: Child, process: Pid) {
    let (send, receive) = mpsc::sync_channel(1);
    std::thread::spawn(move || {
        let _sent = send.send(child.wait());
    });
    match receive.recv_timeout(DEADLINE) {
        Ok(status) => assert!(status.unwrap().success()),
        Err(error) => {
            let _killed = kill(process, Signal::SIGKILL);
            panic!("interrupted login missed exit deadline: {error}");
        }
    }
}