use anyhow::{Context, Result}; use rustls::pki_types::ServerName; use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned}; use std::collections::HashMap; use std::fs::File; use std::io::{BufReader, Read, Write}; use std::net::TcpStream; use std::sync::Arc; pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result { let payload = serde_json::to_string(body)?; request("POST", url, Some(&payload), Some("application/json"), headers) } fn request( method: &str, url: &str, body: Option<&str>, content_type: Option<&str>, headers: &[(&str, &str)], ) -> Result { let (https, host, port, path) = parse_url(url)?; let mut stream: Box = if https { Box::new(connect_mtls(&host, port)?) } else { Box::new(TcpStream::connect((host.as_str(), port)).context("connect")?) }; let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); for (k, v) in headers { req.push_str(&format!("{k}: {v}\r\n")); } if let Some(b) = body { req.push_str(&format!("Content-Length: {}\r\n", b.len())); if let Some(ct) = content_type { req.push_str(&format!("Content-Type: {ct}\r\n")); } req.push_str("\r\n"); req.push_str(b); } else { req.push_str("\r\n"); } stream.write_all(req.as_bytes())?; let mut buf = String::new(); stream.read_to_string(&mut buf)?; let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0); Ok(buf[body_start..].trim().to_string()) } trait ReadWrite: Read + Write {} impl ReadWrite for T {} fn parse_url(url: &str) -> Result<(bool, String, u16, String)> { let (https, rest) = if let Some(rest) = url.strip_prefix("https://") { (true, rest) } else if let Some(rest) = url.strip_prefix("http://") { (false, rest) } else { anyhow::bail!("hub url must start with http:// or https://"); }; let (host_port, path) = rest.split_once('/').unwrap_or((rest, "")); let path = if path.is_empty() { "/".to_string() } else { format!("/{path}") }; let (host, port) = if let Some((host, port)) = host_port.split_once(':') { (host.to_string(), port.parse()?) } else { (host_port.to_string(), if https { 443 } else { 80 }) }; Ok((https, host, port, path)) } fn connect_mtls(host: &str, port: u16) -> Result> { let _ = rustls::crypto::ring::default_provider().install_default(); let ca = std::env::var("TESSERA_WORMHOLE_CA") .context("TESSERA_WORMHOLE_CA is required for an https hub")?; let cert = std::env::var("TESSERA_WORMHOLE_CLIENT_CERT") .context("TESSERA_WORMHOLE_CLIENT_CERT is required for an https hub")?; let key = std::env::var("TESSERA_WORMHOLE_CLIENT_KEY") .context("TESSERA_WORMHOLE_CLIENT_KEY is required for an https hub")?; let mut roots = RootCertStore::empty(); for ca_cert in load_certs(&ca)? { roots.add(ca_cert).map_err(|error| anyhow::anyhow!("hub CA: {error}"))?; } let client = ClientConfig::builder() .with_root_certificates(roots) .with_client_auth_cert(load_certs(&cert)?, load_key(&key)?) .map_err(|error| anyhow::anyhow!("client certificate: {error}"))?; let name = ServerName::try_from(host.to_string()).context("hub hostname")?; let connection = ClientConnection::new(Arc::new(client), name)?; let tcp = TcpStream::connect((host, port)).context("connect")?; Ok(StreamOwned::new(connection, tcp)) } fn load_certs(path: &str) -> Result>> { let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?); rustls_pemfile::certs(&mut reader) .collect::, _>>() .context("parse certificate") } fn load_key(path: &str) -> Result> { let mut reader = BufReader::new(File::open(path).with_context(|| format!("open {path}"))?); rustls_pemfile::private_key(&mut reader) .context("parse private key")? .context("no private key in client key file") } #[allow(dead_code)] pub type HeaderMap = HashMap;