brazen 0.0.26

A stateless, swiss-army-knife adapter for every LLM provider and protocol.
Documentation
//! The key-exchange policy of [`super::tls_config`], proven by execution: the REAL
//! `HttpTransport::send` completes a TLS 1.3 handshake and an HTTP round-trip against
//! a loopback rustls server whose provider accepts exactly ONE key-exchange group.
//!
//! 1. X25519MLKEM768 only — succeeds, so the hybrid post-quantum group is offered.
//! 2. X25519 only — succeeds, so a peer that has not upgraded still interoperates.
//! 3. MLKEM1024 only (a group this client never offers) — fails, so the server's
//!    restriction is real and 1 and 2 are not vacuous.
//!
//! That X25519MLKEM768 is offered FIRST is pinned separately, on the shipped binary:
//! `tests/fixtures/transport/builtin_clienthello.txt` leads its groups with 4588.
//!
//! Certificates are out of scope here and deliberately absent: the client under test
//! is the shipped `tls_config()` with verification switched off, and the server
//! presents a placeholder certificate with a placeholder signature. Nothing about
//! the key exchange is faked — a handshake only finishes when both sides derived the
//! same secret, and the server reports the group it negotiated.

use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::mpsc::{channel, Receiver};
use std::sync::Arc;
use std::thread;

use brazen::{Transport, WireRequest};
use rustls::crypto::aws_lc_rs::{default_provider, kx_group};
use rustls::crypto::{CryptoProvider, SupportedKxGroup};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::{CertifiedKey, Signer, SigningKey};
use rustls::{NamedGroup, SignatureAlgorithm, SignatureScheme};

use super::{tls_config, HttpTransport};

/// The request body; the server reads until it has seen it.
const BODY: &[u8] = b"{}";

/// A server identity nobody verifies: one placeholder certificate, "signed" with
/// placeholder bytes. Only a client with verification off completes against it.
#[derive(Debug)]
struct Unverified;

impl ResolvesServerCert for Unverified {
    fn resolve(&self, _hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        Some(Arc::new(CertifiedKey::new(
            vec![vec![0u8; 8].into()],
            Arc::new(Unverified),
        )))
    }
}

impl SigningKey for Unverified {
    fn choose_scheme(&self, _offered: &[SignatureScheme]) -> Option<Box<dyn Signer>> {
        Some(Box::new(Unverified))
    }
    fn algorithm(&self) -> SignatureAlgorithm {
        SignatureAlgorithm::ED25519
    }
}

impl Signer for Unverified {
    fn sign(&self, _message: &[u8]) -> Result<Vec<u8>, rustls::Error> {
        Ok(vec![0u8; 64])
    }
    fn scheme(&self) -> SignatureScheme {
        SignatureScheme::ED25519
    }
}

/// A one-shot loopback HTTPS server accepting ONLY `group`. Returns its URL and a
/// channel carrying the group the handshake negotiated (`None` if it never did).
fn serve_only(group: &'static dyn SupportedKxGroup) -> (String, Receiver<Option<NamedGroup>>) {
    let provider = CryptoProvider {
        kx_groups: vec![group],
        ..default_provider()
    };
    let config = rustls::ServerConfig::builder_with_provider(Arc::new(provider))
        .with_protocol_versions(&[&rustls::version::TLS13])
        .expect("TLS 1.3")
        .with_no_client_auth()
        .with_cert_resolver(Arc::new(Unverified));
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let (tx, rx) = channel();
    thread::spawn(move || {
        let (mut tcp, _) = listener.accept().unwrap();
        let mut conn = rustls::ServerConnection::new(Arc::new(config)).unwrap();
        let mut tls = rustls::Stream::new(&mut conn, &mut tcp);
        // The first read drives the handshake; a client with no shared group gets a
        // fatal alert here and the read fails. Read the WHOLE request (it ends with
        // the body) and, after answering, read to the client's close: dropping a
        // socket with bytes unread resets it and can destroy the response in flight.
        let mut request = Vec::new();
        let mut buf = [0u8; 4096];
        while !request.ends_with(BODY) {
            match tls.read(&mut buf) {
                Ok(n) if n > 0 => request.extend_from_slice(&buf[..n]),
                _ => break,
            }
        }
        if request.ends_with(BODY) {
            let _ = tls.write_all(b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nok");
            tls.conn.send_close_notify();
            let _ = tls.flush();
            while matches!(tls.read(&mut buf), Ok(n) if n > 0) {}
        }
        let _ = tx.send(conn.negotiated_key_exchange_group().map(|g| g.name()));
    });
    (format!("https://127.0.0.1:{port}/"), rx)
}

/// POST through the shipped TLS policy — `tls_config()` verbatim, plus only the
/// verification switch the placeholder identity above needs — and return the
/// status, or the transport error message.
fn post(url: &str) -> Result<u16, String> {
    let transport = HttpTransport {
        agent: ureq::Agent::config_builder()
            .http_status_as_error(false)
            .tls_config(tls_config().disable_verification(true).build())
            .build()
            .into(),
    };
    transport
        .send(WireRequest::new(url, BODY.to_vec()))
        .map(|resp| resp.status)
        .map_err(|e| e.message)
}

#[test]
fn a_peer_accepting_only_x25519mlkem768_is_reached() {
    let (url, negotiated) = serve_only(kx_group::X25519MLKEM768);
    assert_eq!(post(&url), Ok(200));
    assert_eq!(negotiated.recv().unwrap(), Some(NamedGroup::X25519MLKEM768));
}

#[test]
fn a_peer_accepting_only_x25519_is_still_reached() {
    let (url, negotiated) = serve_only(kx_group::X25519);
    assert_eq!(post(&url), Ok(200));
    assert_eq!(negotiated.recv().unwrap(), Some(NamedGroup::X25519));
}

#[test]
fn a_peer_accepting_only_a_group_never_offered_is_refused() {
    let (url, negotiated) = serve_only(kx_group::MLKEM1024);
    let err = post(&url).expect_err("no shared key-exchange group");
    assert!(err.starts_with("HTTP transport: "), "{err}");
    assert_eq!(negotiated.recv().unwrap(), None);
}