teter 26.11.5

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter token create`, `ls` and `revoke` against a relay with a store; the
//! token's uses are taken as a machine's registration takes them (#86),
//! through the store.
// 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::string_slice,
    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::{SystemTime, UNIX_EPOCH};

use teter_common::account::{Registration, unhex};
use teter_relay::storage::Store;

/// A directory of this test's own (the store and the device), removed when
/// it drops.
struct Scratch(PathBuf);

impl Scratch {
    fn new(tag: &str) -> Self {
        let dir = std::env::temp_dir().join(format!("ttok{}-{tag}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        Self(dir)
    }

    fn device(&self) -> PathBuf {
        self.0.join("device")
    }

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

impl Drop for Scratch {
    fn drop(&mut self) {
        drop(std::fs::remove_dir_all(&self.0));
    }
}

/// A relay with a store in `scratch`, and a device signed up to account
/// `ana` on it; the relay's URL.
async fn signed_up(scratch: &Scratch) -> String {
    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(scratch.0.join("store.db")),
        open_signup: true,
        ..teter_relay::Config::new()
    })
    .unwrap();
    tokio::spawn(server.run(listener));
    let relay = format!("ws://{addr}");
    let out = teter(&scratch.device(), &["signup", &relay, "--name", "ana"]).await;
    assert!(out.status.success(), "{out:?}");
    relay
}

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

/// Makes a token with `args`; the token printed.
async fn create(device: &Path, args: &[&str]) -> Registration {
    let mut all = vec!["token", "create"];
    all.extend_from_slice(args);
    let out = teter(device, &all).await;
    assert!(out.status.success(), "{out:?}");
    Registration::parse(&String::from_utf8(out.stdout).unwrap()).expect("a registration token")
}

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

fn now() -> i64 {
    i64::try_from(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs(),
    )
    .unwrap()
}

fn secret_hash(registration: &Registration) -> Vec<u8> {
    // What the relay keeps: the hash of the key derived for it (#133).
    teter_client::account::secret_hash(
        teter_client::account::registration_auth(&registration.secret).as_ref(),
    )
}

#[tokio::test]
async fn a_token_names_the_relay_and_the_account_keys_and_counts_its_uses() {
    let scratch = Scratch::new("uses");
    let relay = signed_up(&scratch).await;
    let registration = create(&scratch.device(), &["--uses", "2"]).await;
    assert_eq!(registration.relay, relay);
    let saved: serde_json::Value = serde_json::from_slice(
        &std::fs::read(scratch.device().join("teter/account.json")).unwrap(),
    )
    .unwrap();
    let public_keys = unhex(saved["public_keys"].as_str().unwrap()).unwrap();
    assert_eq!(
        registration.fingerprint,
        teter_client::account::fingerprint(&public_keys)
    );
    assert!(ls(&scratch.device()).await.contains("2 uses left"));

    // Two machines register with it; a third does not.
    let store = scratch.store();
    let hash = secret_hash(&registration);
    assert!(
        store
            .use_registration_token(&hash, now())
            .unwrap()
            .is_some()
    );
    assert!(
        store
            .use_registration_token(&hash, now())
            .unwrap()
            .is_some()
    );
    assert!(
        store
            .use_registration_token(&hash, now())
            .unwrap()
            .is_none()
    );
    // Used up, it registers nothing more, and goes from the list.
    assert!(
        ls(&scratch.device())
            .await
            .contains("no registration tokens")
    );
}

#[tokio::test]
async fn a_token_stops_working_when_it_expires() {
    let scratch = Scratch::new("expiry");
    signed_up(&scratch).await;
    let registration = create(&scratch.device(), &["--expires", "1s"]).await;
    tokio::time::sleep(std::time::Duration::from_millis(2100)).await;
    let store = scratch.store();
    assert!(
        store
            .use_registration_token(&secret_hash(&registration), now())
            .unwrap()
            .is_none()
    );
    // Expired, it goes from the list.
    assert!(
        ls(&scratch.device())
            .await
            .contains("no registration tokens")
    );
}

#[tokio::test]
async fn a_revoked_token_is_gone_and_registers_nothing() {
    let scratch = Scratch::new("revoke");
    signed_up(&scratch).await;
    let registration = create(&scratch.device(), &[]).await;
    let id = teter_common::account::hex(&secret_hash(&registration));
    let out = teter(&scratch.device(), &["token", "revoke", &id[..8]]).await;
    assert!(out.status.success(), "{out:?}");
    assert!(
        ls(&scratch.device())
            .await
            .contains("no registration tokens")
    );
    assert!(
        scratch
            .store()
            .use_registration_token(&secret_hash(&registration), now())
            .unwrap()
            .is_none()
    );
    // An ID that matches nothing is said so.
    let out = teter(&scratch.device(), &["token", "revoke", "ffff"]).await;
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("no registration token starts with"));
}

#[tokio::test]
async fn tokens_need_a_login_and_stay_within_their_bounds() {
    let scratch = Scratch::new("bounds");
    signed_up(&scratch).await;
    let out = teter(&scratch.device(), &["token", "create", "--expires", "31d"]).await;
    assert!(!out.status.success());
    let out = teter(&scratch.device(), &["token", "create", "--uses", "0"]).await;
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("registers 1 to"));
    // Logged out: no token can be made.
    let out = teter(&scratch.device(), &["logout"]).await;
    assert!(out.status.success(), "{out:?}");
    let out = teter(&scratch.device(), &["token", "ls"]).await;
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("not logged in"));
}