#![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::{Path, PathBuf};
use std::time::Duration;
use teter_backend::registry::Registry;
use teter_client::account::AccountKeys;
use teter_client::command::{Channel, seal_command};
use teter_common::account::{AccountReply, AccountRequest, unhex};
use teter_common::command::{Command, Outcome};
use tokio::time::timeout;
const WAIT: Duration = Duration::from_secs(15);
struct World {
dir: PathBuf,
}
impl World {
fn sockets(&self) -> PathBuf {
self.dir.join("sockets")
}
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()
}
}
impl Drop for World {
fn drop(&mut self) {
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();
}
}
std::fs::remove_dir_all(&self.dir).ok();
}
}
struct Served {
world: World,
channel: Channel,
account: AccountKeys,
machine: String,
registry: Registry,
relay: String,
login: String,
_link: tokio::process::Child,
}
async fn served(tag: &str) -> Served {
let world = World {
dir: std::env::temp_dir().join(format!("tcmd{tag}{}", 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 (laptop, machine_dir) = (world.dir.join("laptop"), world.dir.join("machine"));
let out = world
.teter(&laptop, &["signup", &relay, "--name", "ana"])
.await;
assert!(out.status.success(), "{out:?}");
let out = world.teter(&laptop, &["token", "create"]).await;
let token = String::from_utf8(out.stdout).unwrap().trim().to_owned();
let out = world
.teter(
&machine_dir,
&["register", "--token", &token, "--name", "jupiter"],
)
.await;
assert!(out.status.success(), "{out:?}");
let registry = Registry::at(machine_dir.join("state/teter/sessions"));
registry.add("victim").unwrap();
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();
let saved: serde_json::Value =
serde_json::from_slice(&std::fs::read(laptop.join("teter/account.json")).unwrap()).unwrap();
let account =
AccountKeys::from_private_bytes(&unhex(saved["private_keys"].as_str().unwrap()).unwrap())
.unwrap();
let login = saved["token"].as_str().unwrap().to_owned();
let machine = timeout(WAIT, async {
loop {
let reply = teter_client::account::request(
&relay,
None,
&AccountRequest::Sessions {
login: login.clone(),
},
)
.await
.unwrap();
if let AccountReply::Sessions { machines } = reply
&& let Some(machine) = machines
.into_iter()
.find(|machine| machine.relay.is_some() && machine.sessions.len() == 2)
{
return machine;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.expect("the machine was not served");
let (session, join) = machine.relay.clone().unwrap();
let channel = Channel::open(
&format!("{relay}/frontend"),
None,
session,
join,
machine.id.clone(),
machine.public_key.clone(),
)
.await
.unwrap();
Served {
world,
channel,
account,
machine: machine.id,
registry,
relay,
login,
_link,
}
}
#[tokio::test]
async fn a_signed_command_runs_and_a_replayed_altered_or_foreign_one_does_not() {
let mut held = served("replay").await;
let (account, machine, registry) = (
AccountKeys::from_private_bytes(&*held.account.private_bytes()).unwrap(),
held.machine.clone(),
&held.registry,
);
let channel = &mut held.channel;
let kill = || Command::Kill {
name: "victim".to_owned(),
};
let refused = |result: std::io::Result<Outcome>| {
let e = result.expect_err("the machine ran it");
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e}");
};
let challenge = channel.challenge().await.unwrap();
let stranger = AccountKeys::generate().unwrap();
let sealed = seal_command(&stranger, &machine, &challenge, kill()).unwrap();
refused(
channel
.send_sealed(&account, &challenge.nonce, sealed)
.await,
);
let challenge = channel.challenge().await.unwrap();
let mut sealed = seal_command(&account, &machine, &challenge, kill()).unwrap();
*sealed.last_mut().unwrap() ^= 1;
refused(
channel
.send_sealed(&account, &challenge.nonce, sealed)
.await,
);
assert!(
registry.contains("victim").unwrap(),
"a refused command ran"
);
let challenge = channel.challenge().await.unwrap();
let sealed = seal_command(&account, &machine, &challenge, kill()).unwrap();
let outcome = channel
.send_sealed(&account, &challenge.nonce, sealed.clone())
.await
.unwrap();
assert_eq!(outcome, Outcome::Done);
assert!(
!registry.contains("victim").unwrap(),
"the session is still registered"
);
registry.add("victim").unwrap();
refused(
channel
.send_sealed(&account, &challenge.nonce, sealed.clone())
.await,
);
let fresh = channel.challenge().await.unwrap();
refused(channel.send_sealed(&account, &fresh.nonce, sealed).await);
assert!(
registry.contains("victim").unwrap(),
"a replayed command ran"
);
}
#[tokio::test]
async fn sessions_are_listed_created_and_killed_through_the_relay() {
let mut held = served("ls").await;
let (account, machine, registry) = (
AccountKeys::from_private_bytes(&*held.account.private_bytes()).unwrap(),
held.machine.clone(),
held.registry.clone(),
);
let world_dir = held.world.dir.clone();
let channel = &mut held.channel;
let names = |outcome: Outcome| match outcome {
Outcome::Sessions { sessions } => sessions
.into_iter()
.map(|session| (session.name, session.running))
.collect::<Vec<_>>(),
other @ (Outcome::Done | Outcome::Failed { .. }) => panic!("not a list: {other:?}"),
};
let listed = names(channel.run(&account, Command::List).await.unwrap());
assert!(listed.contains(&("victim".to_owned(), true)), "{listed:?}");
let new = || Command::New {
name: "zanzibar".to_owned(),
};
assert_eq!(channel.run(&account, new()).await.unwrap(), Outcome::Done);
assert!(registry.contains("zanzibar").unwrap());
let listed = names(channel.run(&account, Command::List).await.unwrap());
assert!(
listed.contains(&("zanzibar".to_owned(), true)),
"{listed:?}"
);
let store = teter_relay::storage::Store::open(&world_dir.join("store.db")).unwrap();
let served = timeout(WAIT, async {
while store.session_records(&machine).unwrap().len() < 3 {
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await;
assert!(served.is_ok(), "the link did not serve the new session");
let taken = channel.run(&account, new()).await.unwrap();
assert!(
matches!(&taken, Outcome::Failed { reason } if reason.contains("already exists")),
"{taken:?}"
);
let bad = Command::New {
name: "../x".to_owned(),
};
let bad = channel.run(&account, bad).await.unwrap();
assert!(matches!(bad, Outcome::Failed { .. }), "{bad:?}");
let kill = Command::Kill {
name: "zanzibar".to_owned(),
};
assert_eq!(channel.run(&account, kill).await.unwrap(), Outcome::Done);
let listed = names(channel.run(&account, Command::List).await.unwrap());
assert!(
!listed.iter().any(|(name, _)| name == "zanzibar"),
"{listed:?}"
);
let mut written = Vec::new();
for name in ["store.db", "store.db-wal"] {
written.extend(std::fs::read(world_dir.join(name)).unwrap_or_default());
}
assert!(
!written.windows(8).any(|window| window == b"zanzibar"),
"a session name in the store"
);
}
async fn records(held: &Served) -> Vec<teter_common::account::SessionRecordInfo> {
let reply = teter_client::account::request(
&held.relay,
None,
&AccountRequest::Sessions {
login: held.login.clone(),
},
)
.await
.unwrap();
let AccountReply::Sessions { machines } = reply else {
return Vec::new();
};
machines
.into_iter()
.find(|machine| machine.id == held.machine)
.map(|machine| machine.sessions)
.unwrap_or_default()
}
#[tokio::test]
async fn the_relay_counts_the_frontends_attached_to_each_session() {
let held = served("clients").await;
let record = timeout(WAIT, async {
loop {
if let Some(record) = records(&held)
.await
.into_iter()
.find(|record| record.relay.is_some())
{
return record;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.expect("no session served");
assert_eq!(record.clients, Some(0));
let (session, token) = record.relay.clone().unwrap();
let frontend = teter_frontend::join(&teter_frontend::Config {
relay: format!("{}/frontend", held.relay),
session,
token,
secret: teter_client::e2e::Secret::generate().unwrap(),
ca_cert: None,
channel: Some(record.channel.clone()),
history: 0,
rows: 0,
})
.await
.unwrap();
let count = |want: u32| {
let held = &held;
let channel = record.channel.clone();
async move {
let reached = timeout(WAIT, async {
loop {
let listed = records(held).await;
let now = listed
.iter()
.find(|record| record.channel == channel)
.and_then(|record| record.clients);
if now == Some(want) {
return;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await;
assert!(reached.is_ok(), "never {want} clients");
}
};
count(1).await;
assert!(
records(&held)
.await
.iter()
.filter(|other| other.channel != record.channel)
.all(|other| other.clients == Some(0))
);
drop(frontend);
count(0).await;
}