teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! Attaching with nothing carried by hand (#87): an account, a machine
//! registered to it serving its sessions, and a logged-in device attaching
//! by `machine:session`; the relay's store holds no session name or key in
//! the clear.
// An allow, not an expect: clippy exempts a #[test] function already, so an expect would go
// unfulfilled where only those use these. `allow_attributes` skips inner attributes.
#![allow(
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::mem_forget,
    clippy::too_many_lines,
    clippy::unused_result_ok,
    clippy::unwrap_used,
    reason = "a test reports by panicking; its helpers live as long as the test"
)]

use std::path::{Path, PathBuf};
use std::time::Duration;

#[path = "../../test-support/processes.rs"]
mod processes;

use teter_backend::pty::{self, Pty};
use tokio::io::AsyncBufReadExt;
use tokio::time::timeout;

const WAIT: Duration = Duration::from_secs(15);

/// The relay, its store and the devices of the test, removed (and the
/// session processes the link started ended) when it drops.
struct World {
    dir: PathBuf,
    relay: String,
}

impl World {
    fn laptop(&self) -> PathBuf {
        self.dir.join("laptop")
    }

    fn machine(&self) -> PathBuf {
        self.dir.join("machine")
    }

    fn sockets(&self) -> PathBuf {
        self.dir.join("sockets")
    }

    async fn teter(&self, device: &Path, args: &[&str]) -> std::process::Output {
        tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
            .args(args)
            .env("XDG_CONFIG_HOME", device)
            .env("XDG_STATE_HOME", device.join("state"))
            .env("TETER_PASSWORD", "correct horse")
            .env_remove("TETER_RELAY")
            .stdin(std::process::Stdio::null())
            .output()
            .await
            .unwrap()
    }
}

impl World {
    /// `teter link` on the machine, with its key.
    fn link(&self) -> tokio::process::Child {
        tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
            .args(["link", "--shell", "/bin/sh", "--sockets"])
            .arg(self.sockets())
            .env("XDG_CONFIG_HOME", self.machine())
            .env("XDG_STATE_HOME", self.machine().join("state"))
            .env_remove("TETER_RELAY")
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
            .unwrap()
    }

    /// Waits until the relay holds `count` records of `machine`.
    async fn records(&self, machine: &str, count: usize) {
        let store = teter_relay::storage::Store::open(&self.dir.join("store.db")).unwrap();
        let found = timeout(WAIT, async {
            while store.session_records(machine).unwrap().len() != count {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await;
        assert!(found.is_ok(), "the relay did not come to {count} records");
    }
}

impl Drop for World {
    fn drop(&mut self) {
        self.kill_sessions();
        std::fs::remove_dir_all(&self.dir).ok();
    }
}

impl World {
    /// `teter kill <name>` on the machine, with no link running.
    async fn kill_offline(&self, name: &str) {
        let sockets = self.sockets();
        let out = self
            .teter(
                &self.machine(),
                &["kill", name, "--sockets", sockets.to_str().unwrap()],
            )
            .await;
        assert!(out.status.success(), "{out:?}");
    }

    /// Whether a session process of the machine still runs.
    fn sessions_running(&self) -> bool {
        let sockets = self.sockets().to_string_lossy().into_owned();
        !processes::naming(&[&sockets, "session"]).is_empty()
    }

    /// Ends every session process of the machine, as a reboot would.
    fn kill_sessions(&self) {
        processes::kill_naming(&self.sockets().to_string_lossy());
    }
}

/// Read from `pty` until the output contains `needle`.
async fn read_until(pty: &Pty, needle: &str) -> String {
    let mut seen = Vec::new();
    let mut buf = [0u8; 4096];
    let found = timeout(WAIT, async {
        loop {
            let n = pty.read(&mut buf).await.unwrap();
            assert!(n > 0, "the terminal closed");
            seen.extend_from_slice(&buf[..n]);
            if String::from_utf8_lossy(&seen).contains(needle) {
                return;
            }
        }
    })
    .await;
    let text = String::from_utf8_lossy(&seen).into_owned();
    assert!(found.is_ok(), "no {needle:?} in {text:?}");
    text
}

#[tokio::test]
async fn a_logged_in_device_attaches_by_name_with_nothing_carried_by_hand() {
    let dir = std::env::temp_dir().join(format!("tsess{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let server = teter_relay::Server::new(teter_relay::Config {
        store: Some(dir.join("store.db")),
        open_signup: true,
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    let world = World {
        dir,
        relay: format!("ws://{addr}"),
    };

    // The account, a token, the machine registered as "jupiter" with a
    // session whose name the relay must never read.
    let out = world
        .teter(&world.laptop(), &["signup", &world.relay, "--name", "ana"])
        .await;
    assert!(out.status.success(), "{out:?}");
    let out = world.teter(&world.laptop(), &["token", "create"]).await;
    let token = String::from_utf8(out.stdout).unwrap().trim().to_owned();
    let out = world
        .teter(
            &world.machine(),
            &["register", "--token", &token, "--name", "jupiter"],
        )
        .await;
    assert!(out.status.success(), "{out:?}");
    teter_backend::registry::Registry::at(world.machine().join("state/teter/sessions"))
        .add("zanzibar-project")
        .unwrap();
    teter_backend::registry::Registry::at(world.machine().join("state/teter/sessions"))
        .add("other")
        .unwrap();

    // The machine links with its key, and keeps its sessions' records.
    let mut link = world.link();
    let mut stdout = tokio::io::BufReader::new(link.stdout.take().unwrap()).lines();
    timeout(WAIT, stdout.next_line()).await.unwrap().unwrap();
    let host: serde_json::Value =
        serde_json::from_slice(&std::fs::read(world.machine().join("teter/host.json")).unwrap())
            .unwrap();
    let machine = host["machine"].as_str().unwrap().to_owned();
    world.records(&machine, 3).await;

    // The laptop attaches by name: no session, token, channel or secret.
    let (pty, child) = pty::spawn("/bin/sh", 80, 24).unwrap();
    std::mem::forget(child);
    let line = format!(
        "XDG_CONFIG_HOME={} {} attach jupiter:zanzibar-project\n",
        world.laptop().display(),
        env!("CARGO_BIN_EXE_teter")
    );
    pty.write_all(line.as_bytes()).await.unwrap();
    tokio::time::sleep(Duration::from_millis(500)).await;
    pty.write_all(b"printf 'by-%s\\n' name\r").await.unwrap();
    read_until(&pty, "by-name").await;
    pty.write_all(&[teter_frontend::DETACH_KEY]).await.unwrap();
    read_until(&pty, "[detached]").await;

    // The store holds neither the session's name nor its key.
    let status = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(["status", "--sockets"])
        .arg(world.sockets())
        .output()
        .await
        .unwrap();
    let status = String::from_utf8(status.stdout).unwrap();
    let mut written = Vec::new();
    for name in ["store.db", "store.db-wal"] {
        written.extend(std::fs::read(world.dir.join(name)).unwrap_or_default());
    }
    let holds = |needle: &[u8]| written.windows(needle.len()).any(|window| window == needle);
    assert!(!holds(b"zanzibar"), "a session name in the store");
    assert!(!holds(b"jupiter"), "a machine name in the store");
    for secret in status
        .lines()
        .filter_map(|line| line.strip_prefix("  secret: "))
    {
        assert!(!holds(secret.as_bytes()), "a session secret in the store");
    }

    // A session ended while no link runs: its record goes once a link
    // serves the machine again (#134), named by the relay session the
    // session processes still running hold.
    link.kill().await.ok();
    world.kill_offline("zanzibar-project").await;
    world.records(&machine, 3).await;
    let mut link = world.link();
    world.records(&machine, 2).await;
    link.kill().await.ok();

    // Again, and no session process left to name the relay session they had
    // (a reboot): the link names it from what it kept on disk.
    world.kill_offline("other").await;
    world.kill_sessions();
    let gone = timeout(WAIT, async {
        while world.sessions_running() {
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await;
    assert!(gone.is_ok(), "the session processes did not end");
    let mut link = world.link();
    world.records(&machine, 1).await;
    link.kill().await.ok();
}