use std::sync::{Arc, Mutex};
use std::time::Duration;
use cpa_core::config::Config;
use crate::proxy::{Hooks, Proxy};
use wreq::tls::session::LruTlsSessionCache;
use wreq::tls::{AlpnProtocol, ExtensionType, KeyShare, TlsOptions, TlsVersion};
pub(crate) const TRANSPORT_CACHE: usize = crate::proxy::CACHE_CAPACITY;
const SESSION_CACHE: usize = 32;
pub(crate) struct Clients {
pub native: wreq::Client,
pub oauth: wreq::Client,
}
pub struct Transport {
hooks: Hooks,
cache: Mutex<Vec<(ClientsKey, Arc<Clients>)>>,
}
type ClientsKey = (Proxy, Option<Duration>);
pub(crate) fn handshake_timeout(cfg: &Config) -> Option<Duration> {
let seconds = cfg
.document
.get("requests")?
.get("tls-handshake-timeout-seconds")?
.as_i64()?;
u64::try_from(seconds).ok().filter(|s| *s > 0).map(|s| match s {
s if s > i64::MAX as u64 / 1_000_000_000 => Duration::from_nanos(i64::MAX as u64),
s => Duration::from_secs(s),
})
}
pub(crate) fn bound_handshake(builder: wreq::ClientBuilder, handshake: Option<Duration>) -> wreq::ClientBuilder {
match handshake {
Some(timeout) => builder.connect_timeout(timeout),
None => builder,
}
}
impl Transport {
pub fn new(hooks: Hooks) -> Self {
Self {
hooks,
cache: Mutex::default(),
}
}
pub(crate) fn clients(&self, proxy: &Proxy, handshake: Option<Duration>) -> wreq::Result<Arc<Clients>> {
let mut cache = self.cache.lock().expect("transport cache");
if let Some(i) = cache.iter().position(|((p, h), _)| p == proxy && *h == handshake) {
let entry = cache.remove(i);
let clients = entry.1.clone();
cache.insert(0, entry);
return Ok(clients);
}
let clients = Arc::new(Clients {
native: self.build(Profile::Native, proxy, handshake)?,
oauth: self.build(Profile::OAuth, proxy, None)?,
});
cache.insert(0, ((proxy.clone(), handshake), clients.clone()));
cache.truncate(TRANSPORT_CACHE);
Ok(clients)
}
fn build(&self, profile: Profile, proxy: &Proxy, handshake: Option<Duration>) -> wreq::Result<wreq::Client> {
let mut builder = bound_handshake(
wreq::Client::builder().redirect(wreq::redirect::Policy::none()),
handshake,
);
builder = match profile {
Profile::Native => crate::proxy::watch_connections(builder)
.http1_only()
.tls_options(options(false))
.tls_session_cache(LruTlsSessionCache::new(SESSION_CACHE)),
Profile::OAuth => builder.tls_options(options(true)),
};
proxy.apply(self.hooks.apply(builder), false)?.build()
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Profile {
Native,
OAuth,
}
pub(crate) fn options(oauth: bool) -> TlsOptions {
let ciphers = concat!(
"TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:",
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:",
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:",
"ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:",
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:",
"ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:",
"AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA:AES256-SHA",
);
let extensions: Vec<ExtensionType> = if oauth {
[0, 23, 65281, 10, 11, 35, 13, 51, 45, 43, 21, 41]
.into_iter()
.map(Into::into)
.collect()
} else {
[0, 23, 65281, 10, 11, 35, 16, 5, 13, 18, 51, 45, 43, 21, 41]
.into_iter()
.map(Into::into)
.collect()
};
TlsOptions::builder()
.min_tls_version(TlsVersion::TLS_1_2).max_tls_version(TlsVersion::TLS_1_3)
.cipher_list(ciphers).preserve_tls13_cipher_list(true)
.curves_list("X25519:P-256:P-384")
.sigalgs_list("ecdsa_secp256r1_sha256:rsa_pss_rsae_sha256:rsa_pkcs1_sha256:ecdsa_secp384r1_sha384:rsa_pss_rsae_sha384:rsa_pkcs1_sha384:rsa_pss_rsae_sha512:rsa_pkcs1_sha512:rsa_pkcs1_sha1")
.key_shares(vec![KeyShare::X25519])
.grease_enabled(false).permute_extensions(false).extension_permutation(extensions)
.alpn_protocols(if oauth { Vec::new() } else { vec![AlpnProtocol::HTTP1] })
.enable_ocsp_stapling(!oauth).enable_signed_cert_timestamps(!oauth)
.session_ticket(true).pre_shared_key(true).psk_dhe_ke(true).renegotiation(true)
.build()
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::AsyncReadExt;
#[derive(Debug)]
struct Hello {
ciphers: Vec<u16>,
extensions: Vec<(u16, Vec<u8>)>,
session_len: usize,
record_len: usize,
}
async fn capture(oauth: bool) -> Hello {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let capture = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
let mut header = [0; 5];
socket.read_exact(&mut header).await.unwrap();
assert_eq!(header[0], 22, "TLS handshake record");
let mut record = vec![0; u16::from_be_bytes([header[3], header[4]]) as usize];
socket.read_exact(&mut record).await.unwrap();
record
});
let transport = Transport::new(Hooks {
trust: None,
resolve: vec![("claude-capture.test".into(), address)],
});
let clients = transport.clients(&Proxy::Inherit, None).unwrap();
let client = if oauth { &clients.oauth } else { &clients.native };
assert!(
client
.get(format!("https://claude-capture.test:{}", address.port()))
.send()
.await
.is_err()
);
let record = capture.await.unwrap();
assert_eq!(record[0], 1);
let mut cursor = 4 + 2 + 32;
let session_len = record[cursor] as usize;
cursor += 1 + session_len;
let cipher_len = u16::from_be_bytes([record[cursor], record[cursor + 1]]) as usize;
cursor += 2;
let ciphers = record[cursor..cursor + cipher_len]
.as_chunks::<2>()
.0
.iter()
.map(|b| u16::from_be_bytes([b[0], b[1]]))
.collect();
cursor += cipher_len;
let compression_len = record[cursor] as usize;
cursor += 1 + compression_len;
let extension_len = u16::from_be_bytes([record[cursor], record[cursor + 1]]) as usize;
cursor += 2;
let end = cursor + extension_len;
let mut extensions = Vec::new();
while cursor < end {
let id = u16::from_be_bytes([record[cursor], record[cursor + 1]]);
let len = u16::from_be_bytes([record[cursor + 2], record[cursor + 3]]) as usize;
cursor += 4;
extensions.push((id, record[cursor..cursor + len].to_vec()));
cursor += len;
}
Hello {
ciphers,
extensions,
session_len,
record_len: record.len(),
}
}
#[tokio::test]
async fn capture_both_clienthellos_against_go_source_profile() {
for oauth in [false, true] {
let hello = capture(oauth).await;
assert_eq!(hello.session_len, 32);
assert_eq!(hello.record_len, if oauth { 251 } else { 512 });
assert_eq!(
hello.ciphers,
[
0x1301, 0x1302, 0x1303, 0xc02b, 0xc02f, 0xc02c, 0xc030, 0xcca9, 0xcca8, 0xc009, 0xc013, 0xc00a,
0xc014, 0x009c, 0x009d, 0x002f, 0x0035
]
);
let extension = |id| {
hello
.extensions
.iter()
.find(|(key, _)| *key == id)
.map(|(_, bytes)| bytes.as_slice())
};
assert_eq!(extension(10), Some([0, 6, 0, 29, 0, 23, 0, 24].as_slice()));
assert_eq!(extension(43), Some([4, 3, 4, 3, 3].as_slice()));
assert_eq!(extension(45), Some([1, 1].as_slice()));
assert_eq!(
extension(0),
Some(b"\x00\x16\x00\x00\x13claude-capture.test".as_slice())
);
assert_eq!(extension(11), Some([1, 0].as_slice()));
assert_eq!(extension(23), Some([].as_slice()));
assert_eq!(extension(35), Some([].as_slice()));
assert_eq!(extension(65281), Some([0].as_slice()));
assert_eq!(
extension(13),
Some([0, 18, 4, 3, 8, 4, 4, 1, 5, 3, 8, 5, 5, 1, 8, 6, 6, 1, 2, 1].as_slice())
);
let key_share = extension(51).unwrap();
assert_eq!(key_share.len(), 38);
assert_eq!(&key_share[..6], [0, 36, 0, 29, 0, 32]);
let ids: Vec<_> = hello.extensions.iter().map(|(id, _)| *id).collect();
if !oauth {
assert_eq!(ids, [0, 23, 65281, 10, 11, 35, 16, 5, 13, 18, 51, 45, 43, 21]);
assert_eq!(extension(16), Some(b"\x00\x09\x08http/1.1".as_slice()));
assert_eq!(extension(5), Some([1, 0, 0, 0, 0].as_slice()));
assert_eq!(extension(18), Some([].as_slice()));
assert_eq!(extension(21), Some([0; 229].as_slice()));
} else {
assert_eq!(ids, [0, 23, 65281, 10, 11, 35, 13, 51, 45, 43]);
}
}
}
#[tokio::test]
async fn native_client_reuses_its_connection() {
let host = "claude-reuse.test";
let (ca, addr, accepted) = crate::test_tls::counting_upstream(host, b"\x08http/1.1").await;
let transport = Transport::new(Hooks {
trust: Some(wreq::tls::trust::CertStore::from_pem_stack(ca).unwrap()),
resolve: vec![(host.into(), addr)],
});
let url = format!("https://{host}:{}/v1/messages", addr.port());
for _ in 0..3 {
let clients = transport.clients(&Proxy::Inherit, None).unwrap();
let response = clients.native.post(&url).body("{}").send().await.unwrap();
assert_eq!(response.bytes().await.unwrap(), "ok");
}
assert_eq!(accepted.load(std::sync::atomic::Ordering::SeqCst), 1, "connections");
}
#[tokio::test]
async fn silent_handshake_fails_only_with_the_bound() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
let mut held = Vec::new();
while let Ok((mut socket, _)) = listener.accept().await {
let mut hello = [0; 5];
let _ = socket.read_exact(&mut hello).await;
held.push(socket);
}
});
let transport = Transport::new(Hooks {
trust: None,
resolve: vec![("claude-silent.test".into(), address)],
});
let url = format!("https://claude-silent.test:{}/v1/messages", address.port());
let send = |handshake| {
let client = transport.clients(&Proxy::Inherit, handshake).unwrap().native.clone();
let url = url.clone();
async move { client.post(url).body("{}").send().await }
};
let started = std::time::Instant::now();
let bounded = tokio::time::timeout(Duration::from_secs(10), send(Some(Duration::from_secs(1))))
.await
.expect("bounded handshake returns");
assert!(bounded.is_err());
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
assert!(
tokio::time::timeout(Duration::from_secs(2), send(None)).await.is_err(),
"unbounded handshake keeps waiting"
);
}
#[test]
fn handshake_timeout_reads_the_root_key_and_its_legacy_spelling() {
let read = |yaml: &str| handshake_timeout(&cpa_core::config::Config::parse(yaml).unwrap());
assert_eq!(
read("requests:\n tls-handshake-timeout-seconds: 7\n"),
Some(Duration::from_secs(7))
);
assert_eq!(read("tls-handshake-timeout-seconds: 3\n"), Some(Duration::from_secs(3)));
assert_eq!(read("requests:\n tls-handshake-timeout-seconds: 0\n"), None);
assert_eq!(read("requests:\n tls-handshake-timeout-seconds: -5\n"), None);
assert_eq!(read("{}\n"), None);
let both =
|v: u32| format!("tls-handshake-timeout-seconds: 7\nrequests:\n tls-handshake-timeout-seconds: {v}\n");
assert_eq!(read(&both(12)), Some(Duration::from_secs(12)));
assert_eq!(read(&both(0)), None);
assert_eq!(
read("upstream:\n claude:\n tls-handshake-timeout-seconds: 99\n"),
None
);
assert_eq!(
read("requests:\n tls-handshake-timeout-seconds: 9223372036854775807\n"),
Some(Duration::from_nanos(i64::MAX as u64))
);
assert_eq!(
read("requests:\n tls-handshake-timeout-seconds: 9223372037\n"),
Some(Duration::from_nanos(i64::MAX as u64))
);
assert_eq!(
read("requests:\n tls-handshake-timeout-seconds: 9223372036\n"),
Some(Duration::from_secs(9_223_372_036))
);
}
#[test]
fn transport_lru_bound() {
let t = Transport::new(Hooks::default());
let first = t.clients(&Proxy::Url("http://p0:1".into()), None).unwrap();
for i in 1..=TRANSPORT_CACHE {
t.clients(&Proxy::Url(format!("http://p{i}:1")), None).unwrap();
}
assert_eq!(t.cache.lock().unwrap().len(), TRANSPORT_CACHE);
let again = t.clients(&Proxy::Url("http://p0:1".into()), None).unwrap();
assert!(!Arc::ptr_eq(&first, &again));
let cached = t.clients(&Proxy::Url("http://p0:1".into()), None).unwrap();
assert!(Arc::ptr_eq(&again, &cached));
}
}