teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter password` and `teter rotate-keys` (#89), run as the binary from a
//! logged-in "laptop" against a registered, linked machine: the old
//! password stops working, other devices' logins end, and the machine
//! follows the rotation its account's old keys signed, keeps the new keys,
//! and seals its sessions' records to them.
// 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::panic,
    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_client::account::AccountKeys;
use teter_common::account::{AccountReply, AccountRequest, unhex};
use tokio::time::timeout;

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

/// The test's folder, removed (and the session processes ended) when it
/// drops.
struct World {
    dir: PathBuf,
}

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

    fn device(&self, name: &str) -> PathBuf {
        self.dir.join(name)
    }

    /// `teter args` on `device` with `password` (and `new_password`, for
    /// `teter password`).
    async fn teter(
        &self,
        device: &Path,
        password: &str,
        new_password: Option<&str>,
        args: &[&str],
    ) -> std::process::Output {
        let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"));
        command
            .args(args)
            .env("XDG_CONFIG_HOME", device)
            .env("XDG_STATE_HOME", device.join("state"))
            .env("TETER_PASSWORD", password)
            .env_remove("TETER_NEW_PASSWORD")
            .env_remove("TETER_RELAY")
            .stdin(std::process::Stdio::null());
        if let Some(new) = new_password {
            command.env("TETER_NEW_PASSWORD", new);
        }
        command.output().await.unwrap()
    }

    /// `teter args` on `device`: its stdout, after asserting it succeeded.
    async fn ok(&self, device: &str, password: &str, args: &[&str]) -> String {
        let out = self.teter(&self.device(device), password, None, args).await;
        assert!(out.status.success(), "{args:?}: {out:?}");
        String::from_utf8(out.stdout).unwrap()
    }

    /// `teter args` on `device`: its stderr, after asserting it failed.
    async fn fails(&self, device: &str, password: &str, args: &[&str]) -> String {
        let out = self.teter(&self.device(device), password, None, args).await;
        assert!(!out.status.success(), "{args:?} succeeded: {out:?}");
        String::from_utf8(out.stderr).unwrap()
    }

    /// A field of a device's or machine's saved JSON file.
    fn saved(&self, device: &str, file: &str, field: &str) -> String {
        let text = std::fs::read(self.device(device).join("teter").join(file)).unwrap();
        let value: serde_json::Value = serde_json::from_slice(&text).unwrap();
        value
            .get(field)
            .and_then(|v| v.as_str())
            .unwrap()
            .to_owned()
    }
}

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

/// Whether the relay's record of the machine's `main` session opens with
/// the laptop's keys now: its name and its key (#87).
async fn main_record_opens(world: &World, relay: &str) -> bool {
    let keys = AccountKeys::from_private_bytes(
        &unhex(&world.saved("laptop", "account.json", "private_keys")).unwrap(),
    )
    .unwrap();
    let login = world.saved("laptop", "account.json", "token");
    let seed = std::fs::read_to_string(world.device("laptop").join("teter/device.key")).unwrap();
    let device = teter_client::account::DeviceKey::from_seed(&unhex(seed.trim()).unwrap()).unwrap();
    let Ok(AccountReply::Sessions { machines, .. }) = teter_client::account::request_signed(
        relay,
        None,
        &AccountRequest::Sessions { login },
        &device,
    )
    .await
    else {
        return false;
    };
    machines.iter().any(|machine| {
        machine.sessions.iter().any(|record| {
            let name = keys.open_sealed(
                &teter_common::account::session_name_info(&machine.id, &record.channel),
                &record.sealed_name,
            );
            let key = keys.open_sealed(
                &teter_common::account::session_key_info(&record.channel),
                &record.sealed_key,
            );
            name.is_ok_and(|name| *name == *b"main") && key.is_ok()
        })
    })
}

#[tokio::test]
async fn a_password_change_and_a_key_rotation_the_machine_follows() {
    let world = World {
        dir: std::env::temp_dir().join(format!("trotation{}", std::process::id())),
    };
    std::fs::create_dir_all(&world.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(world.dir.join("store.db")),
        open_signup: true,
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    let relay = format!("ws://{addr}");
    let (old, new) = ("correct horse", "battery staple");

    let signed_up = world
        .ok("laptop", old, &["signup", &relay, "--name", "ana"])
        .await;
    assert!(signed_up.contains("nothing can recover it"), "{signed_up}");
    let token = world
        .ok("laptop", old, &["token", "create"])
        .await
        .trim()
        .to_owned();
    world
        .ok(
            "machine",
            old,
            &["register", "--token", &token, "--name", "jupiter"],
        )
        .await;
    let machine_dir = world.device("machine");
    let _link = tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
        .args(["link", "--shell", "/bin/sh", "--sockets"])
        .arg(world.sockets())
        .env("XDG_CONFIG_HOME", &machine_dir)
        .env("XDG_STATE_HOME", machine_dir.join("state"))
        .env_remove("TETER_RELAY")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .kill_on_drop(true)
        .spawn()
        .unwrap();
    // The machine connected, the laptop approved it (its token), and main's
    // record opens.
    timeout(WAIT, async {
        while !(world
            .teter(&world.device("laptop"), old, None, &["ls", "jupiter"])
            .await
            .status
            .success()
            && main_record_opens(&world, &relay).await)
        {
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    })
    .await
    .expect("the machine never served main");
    world
        .ok("phone", old, &["login", &relay, "--name", "ana"])
        .await;

    // The password: a wrong current one is refused; then the old one no
    // longer logs in, the new one does, and the phone's login ended.
    let out = world
        .teter(&world.device("laptop"), "wrong", Some(new), &["password"])
        .await;
    assert!(!out.status.success(), "{out:?}");
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("the current password is wrong"),
        "{out:?}"
    );
    let out = world
        .teter(&world.device("laptop"), old, Some(new), &["password"])
        .await;
    assert!(out.status.success(), "{out:?}");
    let err = world.fails("phone", old, &["ls", "jupiter"]).await;
    assert!(err.contains("not logged in"), "{err}");
    let err = world
        .fails("tablet", old, &["login", &relay, "--name", "ana"])
        .await;
    assert!(err.contains("wrong account name or password"), "{err}");
    world
        .ok("tablet", new, &["login", &relay, "--name", "ana"])
        .await;
    // The laptop keeps working with the login the change gave it.
    world.ok("laptop", new, &["ls", "jupiter"]).await;

    // The keys: the machine follows the rotation, keeps the new keys, and
    // seals main's record to them; commands work with them.
    let before = world.saved("laptop", "account.json", "public_keys");
    assert_eq!(world.saved("machine", "host.json", "account_keys"), before);
    let rotated = world.ok("laptop", new, &["rotate-keys"]).await;
    assert!(rotated.contains("replaced the keys of ana"), "{rotated}");
    let after = world.saved("laptop", "account.json", "public_keys");
    assert_ne!(after, before);
    timeout(WAIT, async {
        while world.saved("machine", "host.json", "account_keys") != after
            || !main_record_opens(&world, &relay).await
        {
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    })
    .await
    .expect("the machine never followed the rotation");
    let listed = world.ok("laptop", new, &["ls", "jupiter"]).await;
    assert!(listed.contains("main\trunning"), "{listed}");
    let created = world.ok("laptop", new, &["new", "jupiter:build"]).await;
    assert!(created.contains("created jupiter:build"), "{created}");
    // The tablet logged in before: its login ended with the old keys.
    let err = world.fails("tablet", new, &["ls", "jupiter"]).await;
    assert!(err.contains("not logged in"), "{err}");
    // A registration token made before names the old keys: refused.
    let err = world
        .fails(
            "other-machine",
            new,
            &["register", "--token", &token, "--name", "saturn"],
        )
        .await;
    assert!(!err.is_empty(), "{err}");
}