#![allow(
clippy::expect_used,
clippy::indexing_slicing,
clippy::mem_forget,
clippy::panic,
clippy::unwrap_used,
reason = "a test reports by panicking; its helpers and stand-in servers live as long as the test"
)]
use std::net::SocketAddr;
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use teter_backend::pty::{self, Pty};
use teter_client::e2e::{self, Direction, Keys, Kind, Secret};
use teter_common::{
Message, MessagePayload, MessageType, SessionId, deserialize_message, serialize_message,
};
use tokio::net::{TcpListener, TcpStream};
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::Message as Frame;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
#[path = "../../test-support/machine.rs"]
mod machine;
const WAIT: Duration = Duration::from_secs(10);
async fn start_relay() -> SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
machine::serve(listener, teter_relay::Config::new());
addr
}
struct Backend {
ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
session: SessionId,
token: String,
}
impl Backend {
async fn start(addr: SocketAddr) -> Self {
let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{addr}/backend"))
.await
.unwrap();
machine::authenticate_fixed(&mut ws).await;
for msg in [Message::session_create()] {
ws.send(Frame::text(serialize_message(&msg).unwrap()))
.await
.unwrap();
}
let mut backend = Self {
ws,
session: SessionId::nil(),
token: String::new(),
};
match backend.recv().await.payload {
Some(MessagePayload::SessionCreated {
session_id,
frontend_token,
..
}) => {
backend.session = session_id;
backend.token = frontend_token;
}
other => panic!("no SessionCreated: {other:?}"),
}
backend
}
async fn send(&mut self, msg: Message) {
self.ws
.send(Frame::text(serialize_message(&msg).unwrap()))
.await
.unwrap();
}
async fn recv_clear(&mut self) -> Message {
let msg = self.recv().await;
let secret = Secret::parse(&test_secret()).unwrap();
let mut opener =
Keys::derive_on(&secret, self.session, TEST_CHANNEL).opener(Direction::ToBackend);
match &msg.payload {
Some(MessagePayload::InputData { data, .. }) => {
let data = opener.open(Kind::Input, data).expect("sealed input");
Message::input(self.session, data.to_vec())
}
Some(MessagePayload::Sealed { data }) => {
let size = opener.open(Kind::Resize, data).expect("sealed resize");
let (columns, rows) = e2e::decode_size(&size).expect("a size");
Message::resize(self.session, columns, rows)
}
_ => msg,
}
}
async fn recv(&mut self) -> Message {
loop {
match timeout(WAIT, self.ws.next())
.await
.expect("nothing from the relay")
{
Some(Ok(Frame::Text(text))) => return deserialize_message(&text).unwrap(),
Some(Ok(_)) => {}
other => panic!("the relay closed: {other:?}"),
}
}
}
}
const TEST_CHANNEL: &str = "c0ffee";
fn test_secret() -> String {
"5a".repeat(32)
}
async fn shell_running_frontend(relay: &str, session: SessionId, token: &str) -> Pty {
let (pty, child) = pty::spawn("/bin/sh", 80, 24).unwrap();
std::mem::forget(child); let frontend = concat!(env!("CARGO_BIN_EXE_teter"), " attach");
let secret = test_secret();
let line = format!(
"b=$(stty -g); TETER_SECRET={secret} {frontend} --relay {relay} --session {session} --token {token} --channel {TEST_CHANNEL}; \
a=$(stty -g); [ \"$b\" = \"$a\" ] && r=ok || r=bad; printf 'term-%s.\\n' \"$r\"\n"
);
pty.write_all(line.as_bytes()).await.unwrap();
pty
}
async fn until_restored_or_not(pty: &Pty) -> String {
read_until_any(pty, &["term-ok.", "term-bad."]).await
}
async fn read_until_any(pty: &Pty, needles: &[&str]) -> String {
let mut seen = Vec::new();
let mut buf = [0u8; 4096];
let found = timeout(WAIT, async {
loop {
tokio::task::consume_budget().await;
let n = pty.read(&mut buf).await.unwrap();
assert!(n > 0, "the terminal closed");
seen.extend_from_slice(&buf[..n]);
let text = String::from_utf8_lossy(&seen);
if needles.iter().any(|needle| text.contains(needle)) {
return;
}
}
})
.await;
let text = String::from_utf8_lossy(&seen).into_owned();
assert!(found.is_ok(), "none of {needles:?} in {text:?}");
text
}
#[tokio::test]
async fn raw_while_attached_and_restored_after_detaching() {
let addr = start_relay().await;
let mut backend = Backend::start(addr).await;
let pty = shell_running_frontend(
&format!("ws://{addr}/frontend"),
backend.session,
&backend.token,
)
.await;
assert_eq!(
backend.recv_clear().await,
Message::resize(backend.session, 80, 24)
);
pty.write_all(b"zz").await.unwrap();
assert_eq!(
backend.recv_clear().await,
Message::input(backend.session, b"zz".to_vec())
);
pty.resize(100, 30).unwrap();
assert_eq!(
backend.recv_clear().await,
Message::resize(backend.session, 100, 30)
);
pty.write_all(&[teter_frontend::DETACH_KEY]).await.unwrap();
let text = until_restored_or_not(&pty).await;
assert!(text.contains("[detached]"), "{text:?}");
assert!(text.contains("term-ok."), "{text:?}");
}
#[tokio::test]
async fn restored_when_the_session_ends() {
let addr = start_relay().await;
let mut backend = Backend::start(addr).await;
let pty = shell_running_frontend(
&format!("ws://{addr}/frontend"),
backend.session,
&backend.token,
)
.await;
backend.recv().await; let session = backend.session;
backend.send(Message::session_left(session)).await;
let text = until_restored_or_not(&pty).await;
assert!(
text.contains("[session ended: the backend left the session]"),
"{text:?}"
);
assert!(text.contains("term-ok."), "{text:?}");
}
#[tokio::test]
async fn offline_it_says_so_and_ctrl_bracket_still_detaches_and_restores() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let session = SessionId::new_v4();
tokio::spawn(async move {
let (tcp, _) = listener.accept().await.unwrap();
let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
for _ in 0..2 {
ws.next().await; }
let joined = Message::session_joined(session, "t".repeat(64));
ws.send(Frame::text(serialize_message(&joined).unwrap()))
.await
.unwrap();
loop {
if let Some(Ok(Frame::Text(text))) = ws.next().await
&& deserialize_message(&text).unwrap().msg_type == MessageType::Resize
{
break;
}
}
drop(ws);
});
let pty =
shell_running_frontend(&format!("ws://{addr}/frontend"), session, &"t".repeat(64)).await;
read_until_any(&pty, &["reconnecting"]).await;
pty.write_all(&[teter_frontend::DETACH_KEY]).await.unwrap();
let text = until_restored_or_not(&pty).await;
assert!(text.contains("term-ok."), "{text:?}");
}
#[test]
fn a_refused_join_exits_before_touching_the_terminal() {
let runtime = tokio::runtime::Runtime::new().unwrap();
let addr = runtime.block_on(start_relay());
let out = std::process::Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("attach")
.args(["--channel", TEST_CHANNEL])
.args(["--relay", &format!("ws://{addr}/frontend")])
.args(["--session", &SessionId::new_v4().to_string()])
.args(["--token", &"0".repeat(64)])
.env("TETER_SECRET", test_secret())
.stdin(std::process::Stdio::null())
.output()
.unwrap();
assert_eq!(out.status.code(), Some(1));
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("authentication failed"), "{stderr}");
}
#[test]
fn a_bad_or_missing_secret_is_refused_without_showing_it() {
let run = |secret: Option<&str>| {
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_teter"));
command.arg("attach").args(["--channel", TEST_CHANNEL]);
command
.args(["--relay", "ws://127.0.0.1:9/frontend"])
.args(["--session", &SessionId::new_v4().to_string()])
.args(["--token", &"0".repeat(64)])
.env_remove("TETER_SECRET")
.stdin(std::process::Stdio::null());
if let Some(secret) = secret {
command.env("TETER_SECRET", secret);
}
command.output().unwrap()
};
let out = run(Some("not-the-secret-zq"));
assert_eq!(out.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("TETER_SECRET: the secret is not 64 hex digits"),
"{stderr}"
);
assert!(!stderr.contains("zq"), "the value was shown: {stderr}");
let out = run(None);
assert_eq!(out.status.code(), Some(2));
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("TETER_SECRET is not set"), "{stderr}");
}
#[test]
fn the_secret_is_not_taken_on_the_command_line() {
let out = std::process::Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("attach")
.args(["--channel", TEST_CHANNEL])
.arg("--help")
.output()
.unwrap();
let help = String::from_utf8_lossy(&out.stdout);
assert!(!help.contains("--secret"), "{help}");
assert!(help.contains("TETER_SECRET"), "{help}");
let out = std::process::Command::new(env!("CARGO_BIN_EXE_teter"))
.arg("attach")
.args(["--channel", TEST_CHANNEL])
.args(["--relay", "ws://127.0.0.1:9/frontend"])
.args(["--session", &SessionId::new_v4().to_string()])
.args(["--token", &"0".repeat(64)])
.args(["--secret", &test_secret()])
.env("TETER_SECRET", test_secret())
.stdin(std::process::Stdio::null())
.output()
.unwrap();
assert_eq!(out.status.code(), Some(2), "--secret was taken");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("unexpected argument '--secret'"),
"{stderr}"
);
}