teter-client 26.11.7

Relay connection shared by the teter backend and frontend
Documentation
//! `connect`, `send` and `recv` against a relay from `teter-relay` on a
//! local port, plain and over TLS.
// An allow, not an expect: an integration test's #[test] functions are exempt already, so
// an expect would go unfulfilled where only they use these. `allow_attributes` skips inner
// attributes.
#![allow(
    clippy::unwrap_used,
    reason = "a test reports by panicking; its helpers and stand-in servers live as long as the test"
)]

use std::path::PathBuf;

use teter_common::{Message, MessagePayload, MessageType};
use tokio::net::TcpListener;

#[path = "../../test-support/machine.rs"]
mod machine;

fn fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../teter-relay/tests/fixtures")
        .join(name)
}

/// A relay on a local port; with `tls`, it serves the EC fixture.
async fn relay(tls: bool) -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let config = teter_relay::Config {
        tls: tls.then(|| teter_relay::Tls {
            cert: fixture("ec.crt"),
            key: fixture("ec-pkcs8.key"),
        }),
        ..teter_relay::Config::new()
    };
    machine::serve(listener, config);
    port
}

/// Authenticate as a backend and create a session: the reply proves `send`
/// and `recv` both work.
async fn create_session(relay: &mut teter_client::Relay) {
    machine::authenticate_fixed(relay).await;
    teter_client::send(relay, Message::session_create())
        .await
        .unwrap();
    let reply = teter_client::recv(relay).await.unwrap().unwrap();
    assert_eq!(reply.msg_type, MessageType::SessionJoined);
    assert!(matches!(
        reply.payload,
        Some(MessagePayload::SessionCreated { .. })
    ));
}

#[tokio::test]
async fn plain_ws_connects_and_carries_messages() {
    let port = relay(false).await;
    let mut relay = teter_client::connect(&format!("ws://127.0.0.1:{port}/backend"), None)
        .await
        .unwrap();
    create_session(&mut relay).await;
}

#[tokio::test]
async fn wss_connects_through_the_given_ca() {
    let port = relay(true).await;
    let ca = fixture("ec.crt");
    let mut relay = teter_client::connect(&format!("wss://localhost:{port}/backend"), Some(&ca))
        .await
        .unwrap();
    create_session(&mut relay).await;
}

#[tokio::test]
async fn wss_with_another_ca_is_refused() {
    let port = relay(true).await;
    let ca = fixture("rsa.crt");
    let err = teter_client::connect(&format!("wss://localhost:{port}/backend"), Some(&ca))
        .await
        .err()
        .expect("connected");
    assert!(
        err.to_string().to_lowercase().contains("certificate"),
        "{err}"
    );
}

#[tokio::test]
async fn wss_without_a_ca_uses_the_system_roots() {
    // The self-signed fixture is in no system store: refused.
    let port = relay(true).await;
    let err = teter_client::connect(&format!("wss://localhost:{port}/backend"), None)
        .await
        .err()
        .expect("connected");
    assert!(
        err.to_string().to_lowercase().contains("certificate"),
        "{err}"
    );
}

#[tokio::test]
async fn the_port_defaults_by_scheme() {
    // Nothing listens on 127.0.0.1:80 or :443 in the test environment, so
    // the error is a refused connection to that port, not a URL error.
    for url in ["ws://127.0.0.1/backend", "wss://127.0.0.1/backend"] {
        let err = teter_client::connect(url, None)
            .await
            .err()
            .expect("connected");
        assert_eq!(
            err.kind(),
            std::io::ErrorKind::ConnectionRefused,
            "{url}: {err}"
        );
    }
}

#[tokio::test]
async fn recv_returns_none_once_the_relay_closes() {
    let port = relay(false).await;
    let mut relay = teter_client::connect(&format!("ws://127.0.0.1:{port}/backend"), None)
        .await
        .unwrap();
    // Anything before auth: the relay refuses and closes.
    teter_client::send(&mut relay, Message::ping())
        .await
        .unwrap();
    let refusal = teter_client::recv(&mut relay).await.unwrap().unwrap();
    assert_eq!(refusal.msg_type, MessageType::SessionError);
    assert_eq!(teter_client::recv(&mut relay).await.unwrap(), None);
}

#[tokio::test]
async fn bad_urls_and_ca_files_are_refused_with_what_is_wrong() {
    for (url, expected) in [
        ("http://localhost/backend", "not ws:// or wss://"),
        ("not a url", "relay URL"),
        ("ws:///backend", "relay URL"),
    ] {
        let err = teter_client::connect(url, None)
            .await
            .err()
            .expect("connected");
        assert!(err.to_string().contains(expected), "{url}: {err}");
    }
    let port = relay(true).await;
    let missing = PathBuf::from("/nonexistent/ca.crt");
    let err = teter_client::connect(&format!("wss://localhost:{port}/backend"), Some(&missing))
        .await
        .err()
        .expect("connected");
    assert!(err.to_string().contains("/nonexistent/ca.crt"), "{err}");
}

#[tokio::test]
async fn a_relay_older_than_this_client_is_named_as_the_one_to_upgrade() {
    // A stand-in relay that answers a machine's hello with a challenge from
    // an older protocol (#95).
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        let (tcp, _) = listener.accept().await.unwrap();
        let mut ws = tokio_tungstenite::accept_async(tcp).await.unwrap();
        teter_client::recv(&mut ws).await.unwrap();
        let challenge = Message {
            msg_type: MessageType::Challenge,
            session: None,
            channel: None,
            payload: Some(MessagePayload::Challenge {
                nonce: vec![0; 32],
                protocol: teter_common::PROTOCOL - 1,
                rotations: Vec::new(),
            }),
        };
        teter_client::send(&mut ws, challenge).await.unwrap();
        // Held open: the client must refuse on its own.
        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
    });
    let mut relay = teter_client::connect(&format!("ws://{addr}/backend"), None)
        .await
        .unwrap();
    let key = teter_client::account::MachineKey::generate().unwrap();
    let err = teter_client::account::authenticate_machine(&mut relay, "m", &key)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("upgrade the relay"), "{err}");
}

/// A relay on a local port serving the EC fixture and asking for a client
/// certificate of the test client CA (#159).
async fn relay_asking_certificates() -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    let config = teter_relay::Config {
        tls: Some(teter_relay::Tls {
            cert: fixture("ec.crt"),
            key: fixture("ec-pkcs8.key"),
        }),
        client_ca: Some(fixture("client-ca.crt")),
        ..teter_relay::Config::new()
    };
    machine::serve(listener, config);
    port
}

fn identity(name: &str) -> teter_client::Identity {
    teter_client::Identity {
        cert: fixture(&format!("{name}.crt")),
        key: fixture(&format!("{name}.key")),
    }
}

#[tokio::test]
async fn a_client_certificate_of_the_relays_ca_gets_through() {
    let port = relay_asking_certificates().await;
    let ca = fixture("ec.crt");
    let mut relay = teter_client::connect_as(
        &format!("wss://localhost:{port}/backend"),
        Some(&ca),
        Some(&identity("client")),
    )
    .await
    .unwrap();
    create_session(&mut relay).await;
}

#[tokio::test]
async fn no_client_certificate_or_another_cas_is_refused() {
    let port = relay_asking_certificates().await;
    let ca = fixture("ec.crt");
    for presented in [None, Some(identity("other-client"))] {
        let refused = teter_client::connect_as(
            &format!("wss://localhost:{port}/backend"),
            Some(&ca),
            presented.as_ref(),
        )
        .await;
        assert!(refused.is_err(), "connected with {presented:?}");
    }
}

#[tokio::test]
async fn an_unreadable_client_certificate_is_named() {
    let port = relay_asking_certificates().await;
    let ca = fixture("ec.crt");
    let missing = teter_client::Identity {
        cert: PathBuf::from("/nonexistent/client.crt"),
        key: fixture("client.key"),
    };
    let err = teter_client::connect_as(
        &format!("wss://localhost:{port}/backend"),
        Some(&ca),
        Some(&missing),
    )
    .await
    .err()
    .expect("connected");
    assert!(err.to_string().contains("/nonexistent/client.crt"), "{err}");
    // A key that is not the certificate's.
    let mismatched = teter_client::Identity {
        cert: fixture("client.crt"),
        key: fixture("other-client.key"),
    };
    let err = teter_client::connect_as(
        &format!("wss://localhost:{port}/backend"),
        Some(&ca),
        Some(&mismatched),
    )
    .await
    .err()
    .expect("connected");
    assert!(err.to_string().contains("other-client.key"), "{err}");
}