#![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;
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));
}
}
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()
}
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> {
teter_client::account::secret_hash(
teter_client::account::registration_auth(®istration.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"));
let store = scratch.store();
let hash = secret_hash(®istration);
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()
);
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(®istration), now())
.unwrap()
.is_none()
);
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(®istration));
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(®istration), now())
.unwrap()
.is_none()
);
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"));
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"));
}