teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter attach` in a real pseudo-terminal: raw mode while
//! attached, and the terminal's settings restored on every way out.
// 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::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();
    }

    /// The next message, with a sealed input or resize opened.
    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:?}"),
            }
        }
    }
}

/// The channel the frontends join (a link serves every session on one).
const TEST_CHANNEL: &str = "c0ffee";

/// The secret every test session uses, as 64 hex digits.
fn test_secret() -> String {
    "5a".repeat(32)
}

/// A shell in a PTY that runs the frontend between two `stty -g`, and says
/// whether the settings after match the ones before.
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); // the shell ends with the test process
    let frontend = concat!(env!("CARGO_BIN_EXE_teter"), " attach");
    let secret = test_secret();
    // The settings without PENDIN: macOS sets that state bit, not a setting,
    // while input waits typed ahead of the shell, keeps it across any change
    // of the settings and clears it only on a read, so whether a snapshot has
    // it is down to timing. GNU `stty -a` does not show it. The first line,
    // speed and size, is left out too: a test resizes the terminal.
    let settings = "stty -a | sed '1d; s/-*pendin//'";
    let line = format!(
        "b=$({settings}); TETER_SECRET={secret} {frontend} --relay {relay} --session {session} --token {token} --channel {TEST_CHANNEL}; \
         a=$({settings}); [ \"$b\" = \"$a\" ] && r=ok || r=bad; printf 'term-%s.\\n' \"$r\"\n"
    );
    pty.write_all(line.as_bytes()).await.unwrap();
    pty
}

/// Read from `pty` until the shell reports whether the terminal's settings
/// came back (`term-ok.` or `term-bad.`).
async fn until_restored_or_not(pty: &Pty) -> String {
    read_until_any(pty, &["term-ok.", "term-bad."]).await
}

/// Read from `pty` until the output contains one of `needles`.
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;
    // Attached: the size of the frontend's terminal comes first.
    assert_eq!(
        backend.recv_clear().await,
        Message::resize(backend.session, 80, 24)
    );

    // In raw mode keys go out at once, without waiting for Enter.
    pty.write_all(b"zz").await.unwrap();
    assert_eq!(
        backend.recv_clear().await,
        Message::input(backend.session, b"zz".to_vec())
    );

    // A size change reaches the backend.
    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; // its size: attached
    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() {
    // A stand-in relay: it confirms the join, then drops the connection and
    // takes no other (#81): the frontend stays offline, trying again.
    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; // auth, session_join
        }
        let joined = Message::session_joined(session, "t".repeat(64));
        ws.send(Frame::text(serialize_message(&joined).unwrap()))
            .await
            .unwrap();
        // Wait until attached (its resize), then vanish.
        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;
    // The notice on the bottom row, then the detach key, which works
    // offline too, and the terminal comes back.
    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}");
    // With every argument it needs: only --secret can be what clap refuses.
    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}"
    );
}