teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! The account's approval of its machines and the machines' signed records
//! (#133), against a relay that lies: the test edits the relay's store as a
//! compromised relay would, and a logged-in device must refuse what the
//! account did not sign.
// 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::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::PathBuf;
use std::time::Duration;

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

use tokio::time::timeout;

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

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

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

    fn store(&self) -> teter_relay::storage::Store {
        teter_relay::storage::Store::open(&self.dir.join("store.db")).unwrap()
    }

    async fn teter(&self, device: &str, args: &[&str]) -> std::process::Output {
        let device = self.device(device);
        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()
    }

    async fn ok(&self, device: &str, args: &[&str]) -> String {
        let out = self.teter(device, args).await;
        assert!(out.status.success(), "{device} {args:?}: {out:?}");
        String::from_utf8(out.stdout).unwrap()
    }

    async fn fails(&self, device: &str, args: &[&str]) -> String {
        let out = self.teter(device, args).await;
        assert!(
            !out.status.success(),
            "{device} {args:?} succeeded: {out:?}"
        );
        String::from_utf8(out.stderr).unwrap()
    }

    /// Registers device `machine` as `name` with a token device `maker`
    /// made; links it.
    async fn machine(&self, maker: &str, machine: &str, name: &str) -> tokio::process::Child {
        // Two uses: the token stays listed after it registered the machine.
        let token = self
            .ok(maker, &["token", "create", "--uses", "2"])
            .await
            .trim()
            .to_owned();
        let out = self
            .ok(machine, &["register", "--token", &token, "--name", name])
            .await;
        assert!(out.contains("fingerprint"), "{out:?}");
        let sockets = self.dir.join(format!("{machine}-sockets"));
        let device = self.device(machine);
        tokio::process::Command::new(env!("CARGO_BIN_EXE_teter"))
            .args(["link", "--shell", "/bin/sh", "--sockets"])
            .arg(&sockets)
            .env("XDG_CONFIG_HOME", &device)
            .env("XDG_STATE_HOME", device.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 named `machine`'s ID, from its host.json.
    fn id_of(&self, machine: &str) -> String {
        let host: serde_json::Value = serde_json::from_slice(
            &std::fs::read(self.device(machine).join("teter/host.json")).unwrap(),
        )
        .unwrap();
        host["machine"].as_str().unwrap().to_owned()
    }

    /// Waits until the relay holds a record of `machine`.
    async fn served(&self, machine: &str) {
        let (store, id) = (self.store(), self.id_of(machine));
        let found = timeout(WAIT, async {
            while store.session_records(&id).unwrap().is_empty() {
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        })
        .await;
        assert!(found.is_ok(), "{machine} never kept a record");
    }
}

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

async fn world(tag: &str) -> World {
    let dir = std::env::temp_dir().join(format!("tappr{tag}{}", std::process::id()));
    std::fs::remove_dir_all(&dir).ok();
    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}"),
    };
    world
        .ok("laptop", &["signup", &world.relay, "--name", "ana"])
        .await;
    world
}

#[tokio::test]
async fn the_token_maker_approves_on_its_own_and_forged_records_are_refused() {
    let world = world("own").await;
    // A token made and revoked approves nothing: its secret is gone here.
    let revoked = world.ok("laptop", &["token", "create"]).await;
    let listed = world.ok("laptop", &["token", "ls"]).await;
    let id = listed.split_whitespace().next().unwrap().to_owned();
    world.ok("laptop", &["token", "revoke", &id]).await;
    assert!(!revoked.is_empty());
    let pending = std::fs::read_to_string(world.device("laptop").join("teter/pending-tokens.json"))
        .unwrap_or_default();
    assert!(!pending.contains("secret"), "{pending:?}");

    let _link = world.machine("laptop", "box", "jupiter").await;
    world.served("box").await;

    // Approved on the laptop's first look, on the machine's proof.
    let listed = world.ok("laptop", &["machine", "ls"]).await;
    assert!(
        listed.contains("jupiter") && !listed.contains("not approved"),
        "{listed:?}"
    );
    world.ok("laptop", &["ls", "jupiter"]).await;

    // The relay swaps the main session's key for one of its own, keeping
    // the machine's signature: the device sees no such session.
    let store = world.store();
    let id = world.id_of("box");
    let record = store.session_records(&id).unwrap().remove(0);
    let keys = teter_client::account::AccountKeys::generate().unwrap();
    let forged = teter_client::account::seal_to(
        &keys.public_keys(),
        &teter_local::session_key_info(&record.id),
        b"0".repeat(64).as_slice(),
    )
    .unwrap();
    store
        .put_session_record(
            &id,
            &record.id,
            &record.sealed_name,
            &forged,
            &record.signature,
            "forged",
        )
        .unwrap();
    let err = world.fails("laptop", &["attach", "jupiter:main"]).await;
    assert!(err.contains("did not sign"), "{err:?}");
}

#[tokio::test]
async fn a_machine_another_device_made_the_token_for_waits_for_approval_by_fingerprint() {
    let world = world("other").await;
    world
        .ok("phone", &["login", &world.relay, "--name", "ana"])
        .await;
    // The phone makes the token; the laptop never saw it.
    let _link = world.machine("phone", "box", "saturn").await;
    world.served("box").await;

    let err = world.fails("laptop", &["ls", "saturn"]).await;
    assert!(
        err.contains("not approved") && err.contains("fingerprint"),
        "{err:?}"
    );
    let listed = world.ok("laptop", &["machine", "ls"]).await;
    assert!(listed.contains("not approved"), "{listed:?}");

    // A wrong fingerprint is refused; the one the machine shows approves it.
    let err = world
        .fails(
            "laptop",
            &[
                "machine",
                "approve",
                "saturn",
                "--fingerprint",
                "00112233445566778899aabbccddeeff",
            ],
        )
        .await;
    assert!(err.contains("not approved"), "{err:?}");
    let fingerprint = world.ok("box", &["machine", "fingerprint"]).await;
    world
        .ok(
            "laptop",
            &[
                "machine",
                "approve",
                "saturn",
                "--fingerprint",
                fingerprint.trim(),
            ],
        )
        .await;
    let listed = world.ok("laptop", &["ls", "saturn"]).await;
    assert!(listed.contains("main"), "{listed:?}");

    // The relay copies saturn's approval onto another machine of the
    // account: it does not hold there.
    let _other = world.machine("phone", "box2", "pluto").await;
    world.served("box2").await;
    let store = world.store();
    let cert = store.machine(&world.id_of("box")).unwrap().unwrap().cert;
    let account = store.account_by_name("ana").unwrap().unwrap().id;
    assert!(
        store
            .approve_machine(account, &world.id_of("box2"), &cert)
            .unwrap()
    );
    let err = world.fails("laptop", &["ls", "pluto"]).await;
    assert!(err.contains("not approved"), "{err:?}");
}

#[tokio::test]
async fn logging_out_forgets_the_tokens_this_device_made() {
    let world = world("logout").await;
    world.ok("laptop", &["token", "create"]).await;
    let pending = world.device("laptop").join("teter/pending-tokens.json");
    assert!(pending.exists());
    world.ok("laptop", &["logout"]).await;
    assert!(!pending.exists(), "token secrets outlived the login");
}

#[tokio::test]
async fn a_token_revoked_before_its_machine_was_approved_approves_nothing() {
    // A leaked token, revoked: the machine it registered waits for an
    // approval by hand.
    let world = world("revoke").await;
    let _link = world.machine("laptop", "box", "jupiter").await;
    world.served("box").await;
    let listed = world.ok("laptop", &["token", "ls"]).await;
    let id = listed.split_whitespace().next().unwrap().to_owned();
    world.ok("laptop", &["token", "revoke", &id]).await;
    let err = world.fails("laptop", &["ls", "jupiter"]).await;
    assert!(err.contains("not approved"), "{err:?}");
}