teter 26.11.5

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter register`, `teter link` with the machine's key, `teter machine ls`
//! and `rm`, and `teter unregister`, against a relay with a store: a laptop
//! (the account) and a machine, each a config directory of its own.
// 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::unused_result_ok,
    clippy::unwrap_used,
    reason = "a test reports by panicking; its helpers live as long as the test"
)]

use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::time::Duration;

use teter_common::account::Registration;
use tokio::io::AsyncBufReadExt;

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

impl World {
    async fn new(tag: &str) -> Self {
        let dir = std::env::temp_dir().join(format!("tmach{}-{tag}", 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 = Self {
            dir,
            relay: format!("ws://{addr}"),
        };
        let out = world
            .teter(&world.laptop(), &["signup", &world.relay, "--name", "ana"])
            .await;
        assert!(out.status.success(), "{out:?}");
        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")
    }

    /// `teter <args>` on the device whose config is `device`.
    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()
    }

    /// A registration token made on the laptop.
    async fn token(&self) -> String {
        let out = self.teter(&self.laptop(), &["token", "create"]).await;
        assert!(out.status.success(), "{out:?}");
        String::from_utf8(out.stdout).unwrap().trim().to_owned()
    }

    /// `teter link` on the machine, until it prints its session or ends;
    /// whether it got a session, and what it said on stderr.
    async fn link(&self) -> (bool, String) {
        let mut 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::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        let mut stdout = tokio::io::BufReader::new(child.stdout.take().unwrap()).lines();
        let line = tokio::time::timeout(Duration::from_secs(10), stdout.next_line())
            .await
            .expect("the link neither connected nor ended")
            .unwrap();
        let connected = line.is_some_and(|line| line.starts_with("session: "));
        child.kill().await.ok();
        let out = child.wait_with_output().await.unwrap();
        (connected, String::from_utf8_lossy(&out.stderr).into_owned())
    }
}

impl Drop for World {
    fn drop(&mut self) {
        // The session processes the links started outlive them.
        let sockets = self.sockets().to_string_lossy().into_owned();
        for entry in std::fs::read_dir("/proc").into_iter().flatten().flatten() {
            let Ok(pid) = entry.file_name().to_string_lossy().parse::<i32>() else {
                continue;
            };
            let cmdline = std::fs::read(entry.path().join("cmdline")).unwrap_or_default();
            if String::from_utf8_lossy(&cmdline).contains(&sockets)
                && let Some(pid) = rustix::process::Pid::from_raw(pid)
            {
                rustix::process::kill_process(pid, rustix::process::Signal::KILL).ok();
            }
        }
        drop(std::fs::remove_dir_all(&self.dir));
    }
}

#[tokio::test]
async fn a_registered_machine_links_with_its_key_and_shows_under_its_account() {
    let world = World::new("register").await;
    let token = world.token().await;
    let out = world
        .teter(
            &world.machine(),
            &["register", "--token", &token, "--name", "jupiter"],
        )
        .await;
    assert!(out.status.success(), "{out:?}");
    let host = world.machine().join("teter/host.json");
    assert_eq!(
        std::fs::metadata(&host).unwrap().permissions().mode() & 0o777,
        0o600
    );

    // No backend token: the machine's key.
    let (connected, stderr) = world.link().await;
    assert!(connected, "{stderr}");

    let out = world.teter(&world.laptop(), &["machine", "ls"]).await;
    assert!(out.status.success(), "{out:?}");
    let listed = String::from_utf8(out.stdout).unwrap();
    assert!(listed.contains("jupiter"), "{listed}");
    assert!(listed.contains("last connected"), "{listed}");

    // Unregistered, it is gone from the account and from the machine.
    let out = world.teter(&world.machine(), &["unregister"]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(!host.exists());
    let out = world.teter(&world.laptop(), &["machine", "ls"]).await;
    assert!(
        String::from_utf8(out.stdout)
            .unwrap()
            .contains("no machines")
    );
}

#[tokio::test]
async fn a_token_whose_fingerprint_does_not_match_the_account_keys_is_refused() {
    let world = World::new("fingerprint").await;
    let token = world.token().await;
    let mut swapped = Registration::parse(&token).unwrap();
    swapped.fingerprint[0] ^= 1;
    let out = world
        .teter(
            &world.machine(),
            &["register", "--token", &swapped.to_text()],
        )
        .await;
    assert!(!out.status.success());
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("do not match the token's fingerprint"),
        "{stderr}"
    );
    assert!(!world.machine().join("teter/host.json").exists());
    // The token was not used: the right one still registers.
    let out = world
        .teter(&world.machine(), &["register", "--token", &token])
        .await;
    assert!(out.status.success(), "{out:?}");
}

#[tokio::test]
async fn a_machine_removed_by_its_account_is_cut_off_and_can_unregister_and_register_again() {
    let world = World::new("removed").await;
    let token = world.token().await;
    let out = world
        .teter(&world.machine(), &["register", "--token", &token])
        .await;
    assert!(out.status.success(), "{out:?}");
    let host: serde_json::Value =
        serde_json::from_slice(&std::fs::read(world.machine().join("teter/host.json")).unwrap())
            .unwrap();
    let id = host["machine"].as_str().unwrap().to_owned();

    // Linked, then removed: the relay cuts it off, and it cannot come back.
    let mut link = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(["link", "--shell", "/bin/sh", "--sockets"])
        .arg(world.sockets())
        .env("XDG_CONFIG_HOME", world.machine())
        .env("XDG_STATE_HOME", world.machine().join("state"))
        .env_remove("TETER_RELAY")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true)
        .spawn()
        .unwrap();
    let mut stdout = tokio::io::BufReader::new(link.stdout.take().unwrap()).lines();
    let first = tokio::time::timeout(Duration::from_secs(10), stdout.next_line())
        .await
        .unwrap()
        .unwrap();
    assert!(first.is_some_and(|line| line.starts_with("session: ")));
    let out = world
        .teter(&world.laptop(), &["machine", "rm", id.get(..8).unwrap()])
        .await;
    assert!(out.status.success(), "{out:?}");
    // Cut off, its reconnection is refused, and it stops by itself with the
    // status a service does not restart on, saying how to come back (#138).
    let out = tokio::time::timeout(Duration::from_secs(30), link.wait_with_output())
        .await
        .expect("the link did not stop by itself")
        .unwrap();
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(3), "{stderr}");
    assert!(stderr.contains("removed from its account"), "{stderr}");
    assert!(stderr.contains("teter unregister"), "{stderr}");
    let (connected, stderr) = world.link().await;
    assert!(!connected);
    assert!(stderr.contains("refused this machine"), "{stderr}");

    // The machine can still unregister (the relay forgot it already), and
    // register again.
    let out = world.teter(&world.machine(), &["unregister"]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(!world.machine().join("teter/host.json").exists());
    let token = world.token().await;
    let out = world
        .teter(&world.machine(), &["register", "--token", &token])
        .await;
    assert!(out.status.success(), "{out:?}");
}