//! The preview proxy: a room's dev server, served under a signed //! subdomain of the preview origin. //! //! `r-p-.` routes to 127.0.0.1: //! inside the room's sandbox over the same ssh connection settings the //! agent uses. Paths and the origin stay stable, so a dev server's //! absolute asset URLs keep working; the host is per room and port. use std::collections::HashMap; use std::sync::{Arc, Mutex}; use axum::body::Body; use axum::http::{HeaderMap, HeaderName, HeaderValue, Request, StatusCode, Uri, header}; use axum::response::{IntoResponse, Response}; use hyper_util::rt::TokioIo; use crate::config::Config; use crate::crypto::Secrets; use crate::error::AppResult; use crate::room::agent; use crate::state::Shared; /// One ssh connection per sandbox, opened lazily by the first preview /// request and reused by the channels after it. #[derive(Default)] pub struct PreviewTunnels { handles: Mutex>>>, } impl PreviewTunnels { fn get(&self, target: &str) -> Option>> { self.handles .lock() .unwrap_or_else(|err| err.into_inner()) .get(target) .cloned() } fn put(&self, target: &str, handle: Arc>) { self.handles .lock() .unwrap_or_else(|err| err.into_inner()) .insert(target.to_owned(), handle); } pub(crate) fn forget(&self, target: &str) { self.handles .lock() .unwrap_or_else(|err| err.into_inner()) .remove(target); } } /// The preview scheme and host for this configuration, if previews /// are on. fn domain(config: &Config) -> Option<(&str, &str)> { let origin = config.preview_origin.trim_end_matches('/'); let (scheme, rest) = origin.split_once("://")?; let (host, _port) = match rest.rsplit_once(':') { Some((host, port)) if port.chars().all(|c| c.is_ascii_digit()) => (host, Some(port)), _ => (rest, None), }; if host.is_empty() { return None; } Some((scheme, host)) } /// Whether a Host header belongs to the preview listener. pub fn is_preview_host(config: &Config, host: &str) -> bool { let Some((_, domain)) = domain(config) else { return false; }; let name = host.split(':').next().unwrap_or(host); name.ends_with(&format!(".{domain}")) } /// How long a preview host stays valid. The browser keeps using the /// host it was given; a reload of the room mints a fresh one. const PREVIEW_TTL_SECONDS: i64 = 24 * 60 * 60; /// The signed URL for one room and port. pub fn url(config: &Config, secrets: &Secrets, room: &str, port: u16) -> AppResult { let Some((scheme, domain)) = domain(config) else { return Err(crate::error::AppError::bad_request( "the preview proxy is not configured", )); }; let expires = crate::util::now_ms() / 1000 + PREVIEW_TTL_SECONDS; let signature = secrets.sign(&format!("{room}:{port}:{expires}")); let port_part = config .preview_origin .split_once("://") .map(|(_, rest)| rest) .unwrap_or("") .rsplit_once(':') .filter(|(_, value)| value.chars().all(|c| c.is_ascii_digit())) .map(|(_, value)| format!(":{value}")) .unwrap_or_default(); Ok(format!( "{scheme}://r{room}-p{port}-{expires}-{signature}.{domain}{port_part}/" )) } /// Splits `r-p--` from the Host header. fn target_of_host(config: &Config, host: &str) -> Option<(String, u16, i64, String)> { let (_, domain) = domain(config)?; let name = host.split(':').next().unwrap_or(host); let label = name.strip_suffix(&format!(".{domain}"))?; let rest = label.strip_prefix('r')?; let (room, rest) = rest.rsplit_once("-p")?; let mut fields = rest.split('-'); let port: u16 = fields.next()?.parse().ok()?; let expires: i64 = fields.next()?.parse().ok()?; let signature = fields.next()?; if room.is_empty() || signature.is_empty() || fields.next().is_some() { return None; } Some((room.to_owned(), port, expires, signature.to_owned())) } fn signatures_match(a: &str, b: &str) -> bool { if a.len() != b.len() { return false; } let mut diff = 0u8; for (left, right) in a.as_bytes().iter().zip(b.as_bytes()) { diff |= left ^ right; } diff == 0 } fn no_referrer(mut response: Response) -> Response { response.headers_mut().insert( header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"), ); response } /// Verifies the signature in the Host header against the room and port /// it names, then proxies the request. pub async fn proxy(state: Shared, request: Request) -> Response { let host = request .headers() .get(header::HOST) .and_then(|value| value.to_str().ok()) .unwrap_or("") .to_owned(); let Some((room, port, expires, signature)) = target_of_host(&state.config, &host) else { return (StatusCode::NOT_FOUND, "not a preview host").into_response(); }; if expires < crate::util::now_ms() / 1000 { return (StatusCode::NOT_FOUND, "this preview link has expired").into_response(); } let expected = state.secrets.sign(&format!("{room}:{port}:{expires}")); if !signatures_match(&signature, &expected) { return (StatusCode::NOT_FOUND, "not a preview host").into_response(); } match try_proxy(&state, &room, port, request).await { Ok(response) => no_referrer(response), Err(message) => no_referrer( ( StatusCode::BAD_GATEWAY, format!("the preview did not answer: {message}"), ) .into_response(), ), } } async fn try_proxy( state: &Shared, room: &str, port: u16, request: Request, ) -> Result { let (workspace, target) = agent::load_room_target(state, room).map_err(|err| err.message)?; let _ = workspace; let key = state .secrets .open_str(&target.private_key_ciphertext) .map_err(|err| err.message)?; let handle = match state.previews.get(&target.id) { Some(handle) => handle, None => { let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?; crate::ssh::remember_host_key(state, &target, learned); let handle = Arc::new(handle); state.previews.put(&target.id, handle.clone()); handle } }; let channel = match handle .channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0) .await { Ok(channel) => channel, Err(_) => { state.previews.forget(&target.id); let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?; crate::ssh::remember_host_key(state, &target, learned); let handle = Arc::new(handle); state.previews.put(&target.id, handle.clone()); handle .channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0) .await .map_err(|err| format!("the sandbox refused port {port}: {err}"))? } }; let stream = channel.into_stream(); let io = TokioIo::new(stream); let (mut sender, connection) = hyper::client::conn::http1::handshake(io) .await .map_err(|err| format!("http handshake failed: {err}"))?; tokio::spawn(async move { let _ = connection.await; }); let path = request .uri() .path_and_query() .map(|value| value.as_str()) .unwrap_or("/"); let uri: Uri = path.parse().map_err(|err| format!("bad path: {err}"))?; let (parts, body) = request.into_parts(); let mut outbound = Request::builder() .method(parts.method) .uri(uri) .body(body) .map_err(|err| format!("could not build the request: {err}"))?; *outbound.headers_mut() = parts.headers; strip_hop_by_hop(outbound.headers_mut()); outbound.headers_mut().insert( header::HOST, HeaderValue::from_str(&format!("127.0.0.1:{port}")).unwrap(), ); let response = sender .send_request(outbound) .await .map_err(|err| format!("the preview did not answer: {err}"))?; let (parts, body) = response.into_parts(); let mut out = Response::new(Body::new(body)); *out.status_mut() = parts.status; *out.headers_mut() = parts.headers; strip_hop_by_hop(out.headers_mut()); Ok(no_referrer(out)) } fn strip_hop_by_hop(headers: &mut HeaderMap) { for name in [ header::CONNECTION, HeaderName::from_static("keep-alive"), HeaderName::from_static("proxy-authenticate"), HeaderName::from_static("proxy-authorization"), header::TE, header::TRAILER, header::TRANSFER_ENCODING, header::UPGRADE, ] { headers.remove(name); } } #[cfg(test)] mod tests { use super::*; use crate::config::Config; fn secrets() -> (Secrets, std::path::PathBuf) { let path = std::env::temp_dir().join(format!( "rhema-together-preview-test-{}.key", crate::util::random_id(10) )); let secrets = Secrets::load_or_create(&path).expect("test key"); (secrets, path) } #[test] fn a_preview_host_carries_room_port_expiry_and_signature() { let mut config = Config::default(); config.preview_origin = "https://preview.example.com".into(); let (secrets, path) = secrets(); let url = url(&config, &secrets, "room123", 5173).expect("url"); let host = url .trim_start_matches("https://") .split('/') .next() .expect("host"); let (room, port, expires, signature) = target_of_host(&config, host).expect("parsed host"); assert_eq!(room, "room123"); assert_eq!(port, 5173); assert!(expires >= crate::util::now_ms() / 1000); assert_eq!(signature, secrets.sign(&format!("room123:5173:{expires}"))); let _ = std::fs::remove_file(path); } #[test] fn the_old_host_shape_is_not_accepted() { let mut config = Config::default(); config.preview_origin = "https://preview.example.com".into(); assert!( target_of_host( &config, "rroom123-p5173-0123456789abcdef01234567.preview.example.com" ) .is_none() ); } #[test] fn signatures_compare_by_value() { assert!(signatures_match("abcd", "abcd")); assert!(!signatures_match("abcd", "abce")); assert!(!signatures_match("abcd", "abc")); } }