diff --git a/relay/Cargo.toml b/relay/Cargo.toml new file mode 100644 index 00000000..c40b76dc --- /dev/null +++ b/relay/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "rouse-relay" +version = "0.1.0" +edition = "2021" + +[dependencies] +tokio = { version = "1", features = ["full"] } +rustls = "0.23" +rustls-pemfile = "2" +tokio-rustls = "0.26" +serde = { version = "1", features = ["derive"] } +toml = "0.8" +hyper = { version = "1", features = ["server", "http1"] } +tungstenite = "0.24" +tokio-tungstenite = "0.24" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +rand = "0.8" +bytes = "1" +thiserror = "2" + +[dev-dependencies] +tempfile = "3" diff --git a/relay/relay.example.toml b/relay/relay.example.toml new file mode 100644 index 00000000..da515863 --- /dev/null +++ b/relay/relay.example.toml @@ -0,0 +1,19 @@ +[server] +bind_addr = "0.0.0.0:443" +relay_hostname = "relay.rousecontext.com" + +[tls] +cert_path = "/etc/relay/cert.pem" +key_path = "/etc/relay/key.pem" + +[firebase] +project_id = "rouse-context" +service_account_path = "/etc/relay/firebase-sa.json" + +[cloudflare] +zone_id = "your-cloudflare-zone-id" +api_token_env = "CF_API_TOKEN" + +[limits] +max_streams_per_device = 8 +wake_rate_limit = 6 # per minute per subdomain diff --git a/relay/src/config.rs b/relay/src/config.rs new file mode 100644 index 00000000..8fe79bd4 --- /dev/null +++ b/relay/src/config.rs @@ -0,0 +1,131 @@ +use serde::Deserialize; +use std::path::Path; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("failed to read config file: {0}")] + Io(#[from] std::io::Error), + #[error("failed to parse TOML: {0}")] + Parse(#[from] toml::de::Error), + #[error("environment variable '{0}' is not set")] + MissingEnvVar(String), +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct RelayConfig { + pub server: ServerConfig, + pub tls: TlsConfig, + pub firebase: FirebaseConfig, + pub cloudflare: CloudflareConfig, + pub limits: LimitsConfig, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(default)] +pub struct ServerConfig { + pub bind_addr: String, + pub relay_hostname: String, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct TlsConfig { + pub cert_path: String, + pub key_path: String, +} + +#[derive(Debug, Clone, Default, Deserialize)] +#[serde(default)] +pub struct FirebaseConfig { + pub project_id: String, + pub service_account_path: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(default)] +pub struct CloudflareConfig { + pub zone_id: String, + pub api_token_env: String, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(default)] +pub struct LimitsConfig { + pub max_streams_per_device: u32, + pub wake_rate_limit: u32, +} + +impl Default for ServerConfig { + fn default() -> Self { + Self { + bind_addr: "0.0.0.0:443".to_string(), + relay_hostname: "relay.rousecontext.com".to_string(), + } + } +} + +impl Default for CloudflareConfig { + fn default() -> Self { + Self { + zone_id: String::new(), + api_token_env: "CF_API_TOKEN".to_string(), + } + } +} + +impl Default for LimitsConfig { + fn default() -> Self { + Self { + max_streams_per_device: 8, + wake_rate_limit: 6, + } + } +} + +impl RelayConfig { + /// Load config from a TOML file. Missing fields use defaults. + pub fn from_file(path: &Path) -> Result { + let contents = std::fs::read_to_string(path)?; + let config: RelayConfig = toml::from_str(&contents)?; + Ok(config) + } + + /// Load config from a TOML file, then apply environment variable overrides. + pub fn from_file_with_env(path: &Path) -> Result { + let mut config = Self::from_file(path)?; + config.apply_env_overrides(); + Ok(config) + } + + /// Apply environment variable overrides to the config. + fn apply_env_overrides(&mut self) { + if let Ok(val) = std::env::var("RELAY_BIND_ADDR") { + self.server.bind_addr = val; + } + if let Ok(val) = std::env::var("RELAY_HOSTNAME") { + self.server.relay_hostname = val; + } + if let Ok(val) = std::env::var("RELAY_TLS_CERT_PATH") { + self.tls.cert_path = val; + } + if let Ok(val) = std::env::var("RELAY_TLS_KEY_PATH") { + self.tls.key_path = val; + } + if let Ok(val) = std::env::var("RELAY_FIREBASE_PROJECT_ID") { + self.firebase.project_id = val; + } + if let Ok(val) = std::env::var("RELAY_CF_ZONE_ID") { + self.cloudflare.zone_id = val; + } + } +} + +impl CloudflareConfig { + /// Resolve the API token by reading the environment variable named in `api_token_env`. + pub fn resolve_api_token(&self) -> Result { + std::env::var(&self.api_token_env) + .map_err(|_| ConfigError::MissingEnvVar(self.api_token_env.clone())) + } +} diff --git a/relay/src/lib.rs b/relay/src/lib.rs new file mode 100644 index 00000000..6600a452 --- /dev/null +++ b/relay/src/lib.rs @@ -0,0 +1,6 @@ +pub mod config; +pub mod mux; +pub mod router; +pub mod sni; +pub mod subdomain; +pub mod tls; diff --git a/relay/src/main.rs b/relay/src/main.rs new file mode 100644 index 00000000..e8760266 --- /dev/null +++ b/relay/src/main.rs @@ -0,0 +1,33 @@ +use rouse_relay::config::RelayConfig; +use std::path::Path; +use tracing::{error, info}; + +#[tokio::main] +async fn main() { + tracing_subscriber::fmt::init(); + + let config_path = std::env::args() + .nth(1) + .unwrap_or_else(|| "relay.toml".to_string()); + + let config = if Path::new(&config_path).exists() { + match RelayConfig::from_file_with_env(Path::new(&config_path)) { + Ok(cfg) => cfg, + Err(e) => { + error!("Failed to load config from {config_path}: {e}"); + std::process::exit(1); + } + } + } else { + info!("No config file found at {config_path}, using defaults"); + RelayConfig::default() + }; + + info!( + bind_addr = %config.server.bind_addr, + relay_hostname = %config.server.relay_hostname, + "Rouse relay starting" + ); + + // TODO: bind TCP listener, accept connections, route by SNI +} diff --git a/relay/src/mux/connection.rs b/relay/src/mux/connection.rs new file mode 100644 index 00000000..d6202278 --- /dev/null +++ b/relay/src/mux/connection.rs @@ -0,0 +1,89 @@ +//! Per-device mux connection state. +//! +//! Tracks active streams for a single device connection. The relay uses this +//! to enforce `max_streams_per_device` and to clean up when the device +//! disconnects. + +use std::collections::HashMap; + +/// State of a single mux stream. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StreamState { + Open, + Closed, +} + +/// Tracks all mux streams for one device connection. +pub struct MuxConnection { + streams: HashMap, + max_streams: u32, +} + +impl MuxConnection { + pub fn new(max_streams: u32) -> Self { + Self { + streams: HashMap::new(), + max_streams, + } + } + + /// Open a new stream. Returns `false` if the limit has been reached. + pub fn open_stream(&mut self, stream_id: u32) -> bool { + let active = self + .streams + .values() + .filter(|s| **s == StreamState::Open) + .count() as u32; + if active >= self.max_streams { + return false; + } + self.streams.insert(stream_id, StreamState::Open); + true + } + + /// Close a stream. + pub fn close_stream(&mut self, stream_id: u32) { + self.streams.insert(stream_id, StreamState::Closed); + } + + /// Number of currently open streams. + pub fn active_stream_count(&self) -> u32 { + self.streams + .values() + .filter(|s| **s == StreamState::Open) + .count() as u32 + } + + /// Whether a given stream is currently open. + pub fn is_stream_open(&self, stream_id: u32) -> bool { + self.streams.get(&stream_id) == Some(&StreamState::Open) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn open_and_close_streams() { + let mut conn = MuxConnection::new(2); + assert!(conn.open_stream(1)); + assert!(conn.open_stream(2)); + assert!(!conn.open_stream(3)); // limit reached + assert_eq!(conn.active_stream_count(), 2); + + conn.close_stream(1); + assert_eq!(conn.active_stream_count(), 1); + assert!(conn.open_stream(3)); // now there's room + } + + #[test] + fn is_stream_open() { + let mut conn = MuxConnection::new(8); + assert!(!conn.is_stream_open(1)); + conn.open_stream(1); + assert!(conn.is_stream_open(1)); + conn.close_stream(1); + assert!(!conn.is_stream_open(1)); + } +} diff --git a/relay/src/mux/frame.rs b/relay/src/mux/frame.rs new file mode 100644 index 00000000..7d01bd93 --- /dev/null +++ b/relay/src/mux/frame.rs @@ -0,0 +1,123 @@ +use thiserror::Error; + +/// Header size: type (1 byte) + stream_id (4 bytes). +pub const HEADER_SIZE: usize = 5; + +#[derive(Debug, Error)] +pub enum FrameError { + #[error("frame too short: need at least {HEADER_SIZE} bytes, got {0}")] + TooShort(usize), + #[error("unknown frame type: 0x{0:02x}")] + UnknownType(u8), + #[error("unknown error code: {0}")] + UnknownErrorCode(u32), + #[error("error payload too short")] + ErrorPayloadTooShort, +} + +/// Mux frame types matching the Kotlin client. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum FrameType { + Data = 0x00, + Open = 0x01, + Close = 0x02, + Error = 0x03, +} + +impl FrameType { + pub fn from_byte(b: u8) -> Result { + match b { + 0x00 => Ok(FrameType::Data), + 0x01 => Ok(FrameType::Open), + 0x02 => Ok(FrameType::Close), + 0x03 => Ok(FrameType::Error), + other => Err(FrameError::UnknownType(other)), + } + } +} + +/// Error codes for ERROR frames. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u32)] +pub enum ErrorCode { + StreamRefused = 1, + StreamReset = 2, + ProtocolError = 3, + InternalError = 4, +} + +impl ErrorCode { + pub fn from_u32(val: u32) -> Result { + match val { + 1 => Ok(ErrorCode::StreamRefused), + 2 => Ok(ErrorCode::StreamReset), + 3 => Ok(ErrorCode::ProtocolError), + 4 => Ok(ErrorCode::InternalError), + other => Err(FrameError::UnknownErrorCode(other)), + } + } + + /// Encode an error payload: error_code (u32 BE) + optional UTF-8 message. + pub fn encode_payload(&self, message: Option<&str>) -> Vec { + let code = *self as u32; + let mut buf = code.to_be_bytes().to_vec(); + if let Some(msg) = message { + buf.extend_from_slice(msg.as_bytes()); + } + buf + } + + /// Decode an error payload: error_code (u32 BE) + optional UTF-8 message. + pub fn decode_payload(data: &[u8]) -> Result<(ErrorCode, Option), FrameError> { + if data.len() < 4 { + return Err(FrameError::ErrorPayloadTooShort); + } + let code_val = u32::from_be_bytes([data[0], data[1], data[2], data[3]]); + let code = ErrorCode::from_u32(code_val)?; + let msg = if data.len() > 4 { + Some(String::from_utf8_lossy(&data[4..]).into_owned()) + } else { + None + }; + Ok((code, msg)) + } +} + +/// A mux protocol frame. +/// +/// Wire format: type (u8) + stream_id (u32 BE) + payload (remaining bytes). +/// The header is 5 bytes. The payload length is implicit (frame boundary +/// determined by the transport layer, e.g., WebSocket message boundary). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { + pub frame_type: FrameType, + pub stream_id: u32, + pub payload: Vec, +} + +impl Frame { + /// Encode the frame into a byte vector. + pub fn encode(&self) -> Vec { + let mut buf = Vec::with_capacity(HEADER_SIZE + self.payload.len()); + buf.push(self.frame_type as u8); + buf.extend_from_slice(&self.stream_id.to_be_bytes()); + buf.extend_from_slice(&self.payload); + buf + } + + /// Decode a frame from a byte slice. + pub fn decode(data: &[u8]) -> Result { + if data.len() < HEADER_SIZE { + return Err(FrameError::TooShort(data.len())); + } + let frame_type = FrameType::from_byte(data[0])?; + let stream_id = u32::from_be_bytes([data[1], data[2], data[3], data[4]]); + let payload = data[HEADER_SIZE..].to_vec(); + Ok(Frame { + frame_type, + stream_id, + payload, + }) + } +} diff --git a/relay/src/mux/mod.rs b/relay/src/mux/mod.rs new file mode 100644 index 00000000..ad45bd6d --- /dev/null +++ b/relay/src/mux/mod.rs @@ -0,0 +1,2 @@ +pub mod connection; +pub mod frame; diff --git a/relay/src/router.rs b/relay/src/router.rs new file mode 100644 index 00000000..d0f30991 --- /dev/null +++ b/relay/src/router.rs @@ -0,0 +1,32 @@ +//! SNI-based connection routing. +//! +//! The router reads the first bytes of an incoming TCP connection to extract +//! the SNI hostname from the TLS ClientHello, then decides how to handle it: +//! +//! - **Relay API**: SNI matches `relay_hostname` -- terminate TLS and handle +//! HTTP requests (wake endpoint, ACME orchestration). +//! - **Device passthrough**: SNI is `.rousecontext.com` -- pure TLS +//! passthrough. The relay NEVER terminates TLS for device connections. +//! - **Reject**: Unknown or missing SNI -- close the connection. + +use crate::sni::{parse_sni, RouteDecision}; + +/// Route an incoming connection based on the initial bytes (TLS ClientHello). +/// +/// Returns the routing decision and the buffered bytes (which must be forwarded +/// since they've already been read from the socket). +pub fn route_connection(initial_bytes: &[u8], relay_hostname: &str) -> RouteDecision { + let sni = parse_sni(initial_bytes); + RouteDecision::from_sni(sni.as_deref(), relay_hostname) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn route_rejects_garbage() { + let decision = route_connection(b"not a tls handshake", "relay.rousecontext.com"); + assert!(matches!(decision, RouteDecision::Reject)); + } +} diff --git a/relay/src/sni.rs b/relay/src/sni.rs new file mode 100644 index 00000000..d9ada170 --- /dev/null +++ b/relay/src/sni.rs @@ -0,0 +1,138 @@ +/// Parse the SNI hostname from a TLS ClientHello message. +/// +/// Returns `None` if the data is not a valid ClientHello or lacks an SNI extension. +/// This parser is deliberately minimal -- it extracts only the SNI hostname and +/// does not validate the rest of the handshake. +pub fn parse_sni(buf: &[u8]) -> Option { + // TLS record header: type(1) + version(2) + length(2) + if buf.len() < 5 { + return None; + } + // Must be Handshake content type (0x16) + if buf[0] != 0x16 { + return None; + } + let record_len = u16::from_be_bytes([buf[3], buf[4]]) as usize; + let record = buf.get(5..5 + record_len)?; + + // Handshake header: type(1) + length(3) + if record.len() < 4 { + return None; + } + // Must be ClientHello (0x01) + if record[0] != 0x01 { + return None; + } + let handshake_len = + ((record[1] as usize) << 16) | ((record[2] as usize) << 8) | (record[3] as usize); + let hello = record.get(4..4 + handshake_len)?; + + // ClientHello: version(2) + random(32) + session_id_len(1) + ... + if hello.len() < 35 { + return None; + } + let mut pos = 34; // skip version + random + let session_id_len = *hello.get(pos)? as usize; + pos += 1 + session_id_len; + + // Cipher suites: length(2) + suites + if pos + 2 > hello.len() { + return None; + } + let cipher_len = u16::from_be_bytes([hello[pos], hello[pos + 1]]) as usize; + pos += 2 + cipher_len; + + // Compression methods: length(1) + methods + if pos >= hello.len() { + return None; + } + let comp_len = hello[pos] as usize; + pos += 1 + comp_len; + + // Extensions: length(2) + extension data + if pos + 2 > hello.len() { + return None; + } + let ext_total_len = u16::from_be_bytes([hello[pos], hello[pos + 1]]) as usize; + pos += 2; + + let ext_end = pos + ext_total_len; + while pos + 4 <= ext_end && pos + 4 <= hello.len() { + let ext_type = u16::from_be_bytes([hello[pos], hello[pos + 1]]); + let ext_len = u16::from_be_bytes([hello[pos + 2], hello[pos + 3]]) as usize; + pos += 4; + + if ext_type == 0x0000 { + // SNI extension + return parse_sni_extension(hello.get(pos..pos + ext_len)?); + } + pos += ext_len; + } + + None +} + +fn parse_sni_extension(data: &[u8]) -> Option { + if data.len() < 2 { + return None; + } + let list_len = u16::from_be_bytes([data[0], data[1]]) as usize; + let list = data.get(2..2 + list_len)?; + + let mut pos = 0; + while pos + 3 <= list.len() { + let name_type = list[pos]; + let name_len = u16::from_be_bytes([list[pos + 1], list[pos + 2]]) as usize; + pos += 3; + + if name_type == 0x00 { + // host_name + let name_bytes = list.get(pos..pos + name_len)?; + return String::from_utf8(name_bytes.to_vec()).ok(); + } + pos += name_len; + } + None +} + +/// Routing decision based on SNI hostname. +#[derive(Debug, PartialEq)] +pub enum RouteDecision { + /// Route to the relay's own API (HTTPS). + RelayApi, + /// Route to a device via TLS passthrough. + DevicePassthrough { subdomain: String }, + /// Reject the connection (unknown or missing SNI). + Reject, +} + +impl RouteDecision { + /// Determine routing based on the extracted SNI hostname and the relay's own hostname. + pub fn from_sni(sni: Option<&str>, relay_hostname: &str) -> Self { + let sni = match sni { + Some(s) => s, + None => return RouteDecision::Reject, + }; + + if sni == relay_hostname { + return RouteDecision::RelayApi; + } + + // Extract the base domain from relay_hostname. + // relay_hostname = "relay.rousecontext.com" => base = "rousecontext.com" + let base_domain = relay_hostname + .strip_prefix("relay.") + .unwrap_or(relay_hostname); + + // Check if SNI is a subdomain of the base domain: ".rousecontext.com" + if let Some(subdomain) = sni.strip_suffix(&format!(".{base_domain}")) { + if !subdomain.is_empty() && subdomain != "relay" && !subdomain.contains('.') { + return RouteDecision::DevicePassthrough { + subdomain: subdomain.to_string(), + }; + } + } + + RouteDecision::Reject + } +} diff --git a/relay/src/subdomain.rs b/relay/src/subdomain.rs new file mode 100644 index 00000000..7d5929f7 --- /dev/null +++ b/relay/src/subdomain.rs @@ -0,0 +1,44 @@ +use rand::seq::SliceRandom; + +const ADJECTIVES: &str = include_str!("words/adjectives.txt"); +const NOUNS: &str = include_str!("words/nouns.txt"); + +pub struct SubdomainGenerator { + adjectives: Vec<&'static str>, + nouns: Vec<&'static str>, +} + +impl SubdomainGenerator { + pub fn new() -> Self { + let adjectives: Vec<&str> = ADJECTIVES + .lines() + .map(|l| l.trim()) + .filter(|l| !l.is_empty()) + .collect(); + let nouns: Vec<&str> = NOUNS + .lines() + .map(|l| l.trim()) + .filter(|l| !l.is_empty()) + .collect(); + Self { adjectives, nouns } + } + + /// Generate a random adjective-noun subdomain. + pub fn generate(&self) -> String { + let mut rng = rand::thread_rng(); + let adj = self.adjectives.choose(&mut rng).expect("no adjectives"); + let noun = self.nouns.choose(&mut rng).expect("no nouns"); + format!("{adj}-{noun}") + } + + /// Return (adjective_count, noun_count) for testing word list sizes. + pub fn word_counts(&self) -> (usize, usize) { + (self.adjectives.len(), self.nouns.len()) + } +} + +impl Default for SubdomainGenerator { + fn default() -> Self { + Self::new() + } +} diff --git a/relay/src/tls.rs b/relay/src/tls.rs new file mode 100644 index 00000000..c4cd7bb3 --- /dev/null +++ b/relay/src/tls.rs @@ -0,0 +1,43 @@ +//! TLS configuration for the relay's own API endpoint. +//! +//! This is used ONLY for the relay API (wake endpoint, ACME orchestration). +//! Device connections are pure TLS passthrough -- the relay never terminates +//! TLS for device traffic. + +use crate::config::TlsConfig; +use std::io; +use std::sync::Arc; + +/// Build a rustls `ServerConfig` for the relay API endpoint. +/// +/// # Errors +/// Returns an error if the certificate or key files cannot be loaded. +pub fn build_relay_tls_config(config: &TlsConfig) -> io::Result> { + let cert_pem = std::fs::read(&config.cert_path).map_err(|e| { + io::Error::new( + io::ErrorKind::NotFound, + format!("failed to read cert at {}: {e}", config.cert_path), + ) + })?; + let key_pem = std::fs::read(&config.key_path).map_err(|e| { + io::Error::new( + io::ErrorKind::NotFound, + format!("failed to read key at {}: {e}", config.key_path), + ) + })?; + + let certs = rustls_pemfile::certs(&mut cert_pem.as_slice()) + .collect::, _>>() + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("bad cert PEM: {e}")))?; + + let key = rustls_pemfile::private_key(&mut key_pem.as_slice()) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("bad key PEM: {e}")))? + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no private key found in PEM"))?; + + let tls_config = rustls::ServerConfig::builder() + .with_no_client_auth() + .with_single_cert(certs, key) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("TLS config: {e}")))?; + + Ok(Arc::new(tls_config)) +} diff --git a/relay/src/words/adjectives.txt b/relay/src/words/adjectives.txt new file mode 100644 index 00000000..b9981f8b --- /dev/null +++ b/relay/src/words/adjectives.txt @@ -0,0 +1,279 @@ +able +aged +airy +amber +ample +angry +apt +aqua +avid +azure +bare +basic +big +black +bland +bleak +blind +blond +blue +bold +brave +brief +broad +brown +brisk +calm +cheap +chief +civic +clean +clear +close +cold +cool +coral +crisp +cubic +curly +daily +dark +dear +deep +dense +dim +dire +dizzy +dry +dual +dull +dusty +eager +early +easy +elder +elfin +elite +empty +equal +even +every +exact +extra +faint +fair +false +fancy +fast +fatal +fewer +final +fine +firm +first +fixed +flat +fleet +flung +foggy +fond +frank +free +fresh +front +full +funny +fuzzy +giant +glad +gold +good +grand +gray +great +green +grim +grown +handy +happy +hardy +harsh +hasty +heavy +high +hollow +hot +huge +human +humid +icy +ideal +inner +ivory +jade +just +keen +kind +known +large +last +late +lean +left +level +light +like +lime +linen +little +live +local +lone +long +lost +loud +lower +loyal +lucky +lunar +mad +magic +main +major +maple +mean +meek +mild +mint +minor +misty +mixed +moist +moral +muted +naive +named +narrow +naval +near +neat +new +next +noble +north +novel +null +oaken +odd +olive +only +open +other +outer +oval +own +pale +past +pearl +petty +pink +plain +plum +plump +polar +poor +prime +prior +proud +pure +quick +quiet +rapid +rare +raw +ready +real +rich +rigid +ripe +roomy +rosy +rough +round +royal +ruby +rude +rural +rusty +safe +salty +same +sandy +sane +shady +sharp +sheer +short +shy +silky +slim +slow +small +smart +smoky +snowy +soft +solar +solid +spare +split +stark +steep +stern +still +stony +stout +stray +sunny +super +sweet +swift +tame +tan +taut +thick +thin +tidy +tight +timid +tiny +total +tough +trim +true +twin +ultra +unfit +upper +urban +usual +vague +valid +vast +vivid +vocal +warm +wavy +weak +weary +weird +west +wet +whole +wide +wild +wise +witty +woody +young +zippy diff --git a/relay/src/words/nouns.txt b/relay/src/words/nouns.txt new file mode 100644 index 00000000..e1e2bf3a --- /dev/null +++ b/relay/src/words/nouns.txt @@ -0,0 +1,197 @@ +acorn +adder +agate +apple +arrow +aspen +badge +basin +beach +berry +birch +blade +bloom +bluff +board +bonus +booth +brook +brush +cairn +camel +canoe +cedar +chess +chief +chord +clam +cliff +cloud +cobra +comet +conch +coral +crane +creek +crown +daisy +delta +dingo +dodge +dove +drake +dream +drift +drum +dune +eagle +earth +ember +fable +fairy +fawn +feast +fern +finch +fjord +flame +flint +flora +forge +frost +gale +garden +gecko +ghost +giant +glade +gleam +globe +grain +grove +guard +guild +gulch +guppy +haven +hawk +hazel +hedge +heron +holly +hyena +ivory +jade +jewel +kayak +kelp +kite +knoll +koala +larch +lark +lemur +lilac +linen +llama +lodge +lotus +lynx +mango +manor +maple +marsh +mesa +midge +mink +moose +moth +mound +mulch +nest +newt +north +nymph +oasis +ocean +olive +onyx +orbit +otter +owl +panda +pansy +patch +pearl +pecan +perch +petal +pilot +plume +plum +point +polar +pond +poppy +prawn +prism +prowl +pulse +quail +quartz +quest +raven +realm +ridge +robin +rover +sable +sage +scone +scout +shade +shale +shark +shelf +shore +shrub +sloth +snail +solar +south +spark +spire +stag +stake +steam +stone +stork +storm +swamp +swift +talon +thyme +tiger +torch +trail +trout +tulip +tundra +valet +valor +vault +venom +verse +vigor +viola +viper +waltz +whale +wheat +whirl +whelk +wren +yacht +yucca +zebra +zenith diff --git a/relay/tests/config_test.rs b/relay/tests/config_test.rs new file mode 100644 index 00000000..eaa37ea0 --- /dev/null +++ b/relay/tests/config_test.rs @@ -0,0 +1,116 @@ +use rouse_relay::config::RelayConfig; +use std::io::Write; +use tempfile::NamedTempFile; + +fn write_toml(content: &str) -> NamedTempFile { + let mut f = NamedTempFile::new().unwrap(); + f.write_all(content.as_bytes()).unwrap(); + f +} + +const VALID_TOML: &str = r#" +[server] +bind_addr = "0.0.0.0:8443" +relay_hostname = "relay.rousecontext.com" + +[tls] +cert_path = "/etc/relay/cert.pem" +key_path = "/etc/relay/key.pem" + +[firebase] +project_id = "rouse-context" +service_account_path = "/etc/relay/firebase-sa.json" + +[cloudflare] +zone_id = "test-zone-id" +api_token_env = "CF_API_TOKEN" + +[limits] +max_streams_per_device = 8 +wake_rate_limit = 6 +"#; + +#[test] +fn parse_valid_toml() { + let f = write_toml(VALID_TOML); + let cfg = RelayConfig::from_file(f.path()).unwrap(); + assert_eq!(cfg.server.bind_addr, "0.0.0.0:8443"); + assert_eq!(cfg.server.relay_hostname, "relay.rousecontext.com"); + assert_eq!(cfg.tls.cert_path, "/etc/relay/cert.pem"); + assert_eq!(cfg.tls.key_path, "/etc/relay/key.pem"); + assert_eq!(cfg.firebase.project_id, "rouse-context"); + assert_eq!(cfg.cloudflare.zone_id, "test-zone-id"); + assert_eq!(cfg.cloudflare.api_token_env, "CF_API_TOKEN"); + assert_eq!(cfg.limits.max_streams_per_device, 8); + assert_eq!(cfg.limits.wake_rate_limit, 6); +} + +#[test] +fn missing_file_uses_defaults() { + let cfg = RelayConfig::default(); + assert_eq!(cfg.server.bind_addr, "0.0.0.0:443"); + assert_eq!(cfg.limits.max_streams_per_device, 8); + assert_eq!(cfg.limits.wake_rate_limit, 6); +} + +#[test] +fn env_var_overrides_toml() { + let f = write_toml(VALID_TOML); + // Set env var that should override bind_addr + std::env::set_var("RELAY_BIND_ADDR", "127.0.0.1:9443"); + let cfg = RelayConfig::from_file_with_env(f.path()).unwrap(); + assert_eq!(cfg.server.bind_addr, "127.0.0.1:9443"); + std::env::remove_var("RELAY_BIND_ADDR"); +} + +#[test] +fn env_var_overrides_relay_hostname() { + let f = write_toml(VALID_TOML); + std::env::set_var("RELAY_HOSTNAME", "test.example.com"); + let cfg = RelayConfig::from_file_with_env(f.path()).unwrap(); + assert_eq!(cfg.server.relay_hostname, "test.example.com"); + std::env::remove_var("RELAY_HOSTNAME"); +} + +#[test] +fn missing_required_cloudflare_token_env_var_fails() { + let f = write_toml(VALID_TOML); + let cfg = RelayConfig::from_file(f.path()).unwrap(); + // The api_token_env field names an env var. Resolving it should fail + // if that env var is not set. + std::env::remove_var("CF_API_TOKEN"); + let result = cfg.cloudflare.resolve_api_token(); + assert!(result.is_err()); + let err_msg = result.unwrap_err().to_string(); + assert!( + err_msg.contains("CF_API_TOKEN"), + "Error should mention the missing env var name, got: {err_msg}" + ); +} + +#[test] +fn resolve_cloudflare_token_succeeds_when_set() { + let f = write_toml(VALID_TOML); + let cfg = RelayConfig::from_file(f.path()).unwrap(); + std::env::set_var("CF_API_TOKEN", "test-token-value"); + let token = cfg.cloudflare.resolve_api_token().unwrap(); + assert_eq!(token, "test-token-value"); + std::env::remove_var("CF_API_TOKEN"); +} + +#[test] +fn partial_toml_fills_defaults() { + let partial = r#" +[server] +relay_hostname = "custom.example.com" +"#; + let f = write_toml(partial); + let cfg = RelayConfig::from_file(f.path()).unwrap(); + // relay_hostname from file + assert_eq!(cfg.server.relay_hostname, "custom.example.com"); + // bind_addr should be default + assert_eq!(cfg.server.bind_addr, "0.0.0.0:443"); + // limits should be defaults + assert_eq!(cfg.limits.max_streams_per_device, 8); + assert_eq!(cfg.limits.wake_rate_limit, 6); +} diff --git a/relay/tests/mux_frame_test.rs b/relay/tests/mux_frame_test.rs new file mode 100644 index 00000000..b134920b --- /dev/null +++ b/relay/tests/mux_frame_test.rs @@ -0,0 +1,179 @@ +use rouse_relay::mux::frame::{ErrorCode, Frame, FrameType}; + +#[test] +fn encode_decode_data_frame() { + let frame = Frame { + frame_type: FrameType::Data, + stream_id: 42, + payload: b"hello world".to_vec(), + }; + let encoded = frame.encode(); + let decoded = Frame::decode(&encoded).unwrap(); + assert_eq!(decoded.frame_type, FrameType::Data); + assert_eq!(decoded.stream_id, 42); + assert_eq!(decoded.payload, b"hello world"); +} + +#[test] +fn encode_decode_open_frame() { + let frame = Frame { + frame_type: FrameType::Open, + stream_id: 1, + payload: vec![], + }; + let encoded = frame.encode(); + let decoded = Frame::decode(&encoded).unwrap(); + assert_eq!(decoded.frame_type, FrameType::Open); + assert_eq!(decoded.stream_id, 1); + assert!(decoded.payload.is_empty()); +} + +#[test] +fn encode_decode_close_frame() { + let frame = Frame { + frame_type: FrameType::Close, + stream_id: 99, + payload: vec![], + }; + let encoded = frame.encode(); + let decoded = Frame::decode(&encoded).unwrap(); + assert_eq!(decoded.frame_type, FrameType::Close); + assert_eq!(decoded.stream_id, 99); +} + +#[test] +fn encode_decode_error_frame_with_message() { + let payload = ErrorCode::ProtocolError.encode_payload(Some("bad frame")); + let frame = Frame { + frame_type: FrameType::Error, + stream_id: 7, + payload, + }; + let encoded = frame.encode(); + let decoded = Frame::decode(&encoded).unwrap(); + assert_eq!(decoded.frame_type, FrameType::Error); + assert_eq!(decoded.stream_id, 7); + + let (code, msg) = ErrorCode::decode_payload(&decoded.payload).unwrap(); + assert_eq!(code, ErrorCode::ProtocolError); + assert_eq!(msg.as_deref(), Some("bad frame")); +} + +#[test] +fn encode_decode_error_frame_without_message() { + let payload = ErrorCode::InternalError.encode_payload(None); + let frame = Frame { + frame_type: FrameType::Error, + stream_id: 3, + payload, + }; + let encoded = frame.encode(); + let decoded = Frame::decode(&encoded).unwrap(); + + let (code, msg) = ErrorCode::decode_payload(&decoded.payload).unwrap(); + assert_eq!(code, ErrorCode::InternalError); + assert!(msg.is_none()); +} + +#[test] +fn all_error_codes_round_trip() { + let codes = [ + ErrorCode::StreamRefused, + ErrorCode::StreamReset, + ErrorCode::ProtocolError, + ErrorCode::InternalError, + ]; + for code in codes { + let payload = code.encode_payload(Some("test")); + let (decoded_code, msg) = ErrorCode::decode_payload(&payload).unwrap(); + assert_eq!(decoded_code, code); + assert_eq!(msg.as_deref(), Some("test")); + } +} + +#[test] +fn round_trip_large_payload() { + let data = vec![0xAB; 65536]; + let frame = Frame { + frame_type: FrameType::Data, + stream_id: u32::MAX, + payload: data.clone(), + }; + let encoded = frame.encode(); + let decoded = Frame::decode(&encoded).unwrap(); + assert_eq!(decoded.payload, data); + assert_eq!(decoded.stream_id, u32::MAX); +} + +#[test] +fn unknown_frame_type_returns_error() { + let mut encoded = Frame { + frame_type: FrameType::Data, + stream_id: 1, + payload: vec![], + } + .encode(); + // Corrupt the frame type byte + encoded[0] = 0xFF; + let result = Frame::decode(&encoded); + assert!(result.is_err()); +} + +#[test] +fn truncated_header_returns_error() { + let result = Frame::decode(&[0x00, 0x00, 0x01]); + assert!(result.is_err()); +} + +#[test] +fn truncated_payload_returns_error() { + // Valid header claiming payload exists, but data is short + let mut buf = vec![0x00]; // DATA type + buf.extend_from_slice(&1u32.to_be_bytes()); // stream_id + // Header says we should have more data from the length, but decode reads + // remaining bytes as payload -- this tests the header-only case which is valid. + // Instead, test with a frame where we know the encoded length and truncate it. + let frame = Frame { + frame_type: FrameType::Data, + stream_id: 1, + payload: b"hello".to_vec(), + }; + let encoded = frame.encode(); + // Truncate so payload is incomplete + let truncated = &encoded[..encoded.len() - 2]; + // This should still decode but with truncated payload, or error depending on + // implementation. The key invariant: it must not panic. + let _ = Frame::decode(truncated); +} + +#[test] +fn header_encoding_is_5_bytes() { + let frame = Frame { + frame_type: FrameType::Data, + stream_id: 0, + payload: vec![], + }; + let encoded = frame.encode(); + // 5 byte header, no payload + assert_eq!(encoded.len(), 5); + // First byte is frame type + assert_eq!(encoded[0], 0x00); + // Next 4 bytes are stream_id in big-endian + assert_eq!(&encoded[1..5], &[0, 0, 0, 0]); +} + +#[test] +fn error_code_values_match_spec() { + assert_eq!(ErrorCode::StreamRefused as u32, 1); + assert_eq!(ErrorCode::StreamReset as u32, 2); + assert_eq!(ErrorCode::ProtocolError as u32, 3); + assert_eq!(ErrorCode::InternalError as u32, 4); +} + +#[test] +fn unknown_error_code_returns_error() { + let mut payload = 999u32.to_be_bytes().to_vec(); + payload.extend_from_slice(b"unknown"); + let result = ErrorCode::decode_payload(&payload); + assert!(result.is_err()); +} diff --git a/relay/tests/sni_test.rs b/relay/tests/sni_test.rs new file mode 100644 index 00000000..f3afd58e --- /dev/null +++ b/relay/tests/sni_test.rs @@ -0,0 +1,175 @@ +use rouse_relay::sni::{parse_sni, RouteDecision}; + +/// Build a minimal TLS 1.2+ ClientHello with the given SNI hostname. +/// This constructs just enough of the handshake to be parseable. +fn build_client_hello(hostname: &str) -> Vec { + let hostname_bytes = hostname.as_bytes(); + + // SNI extension: type(2) + list_len(2) + entry_type(1) + name_len(2) + name + let sni_entry_len = 1 + 2 + hostname_bytes.len(); + let sni_list_len = sni_entry_len; + let sni_ext_data_len = 2 + sni_list_len; // list_length(2) + list + let sni_ext_len = 2 + 2 + sni_ext_data_len; // type(2) + length(2) + data + + // Extensions block + let extensions_len = sni_ext_len; + + // ClientHello body (after handshake header): + // version(2) + random(32) + session_id_len(1) + cipher_suites_len(2) + one_suite(2) + + // compression_len(1) + null_compression(1) + extensions_length(2) + extensions + let client_hello_body_len = 2 + 32 + 1 + 2 + 2 + 1 + 1 + 2 + extensions_len; + + // Handshake header: type(1) + length(3) + let handshake_len = 1 + 3 + client_hello_body_len; + + // TLS record: type(1) + version(2) + length(2) + handshake + let mut buf = Vec::with_capacity(5 + handshake_len); + + // TLS record header + buf.push(0x16); // ContentType: Handshake + buf.push(0x03); + buf.push(0x01); // TLS 1.0 record version (normal for ClientHello) + let record_len = handshake_len as u16; + buf.extend_from_slice(&record_len.to_be_bytes()); + + // Handshake header + buf.push(0x01); // HandshakeType: ClientHello + let ch_len = client_hello_body_len as u32; + buf.push((ch_len >> 16) as u8); + buf.push((ch_len >> 8) as u8); + buf.push(ch_len as u8); + + // ClientHello body + buf.push(0x03); + buf.push(0x03); // TLS 1.2 + + // Random (32 bytes of zeros) + buf.extend_from_slice(&[0u8; 32]); + + // Session ID length: 0 + buf.push(0); + + // Cipher suites: length 2, one suite (TLS_AES_128_GCM_SHA256) + buf.extend_from_slice(&[0x00, 0x02]); + buf.extend_from_slice(&[0x13, 0x01]); + + // Compression methods: length 1, null + buf.push(0x01); + buf.push(0x00); + + // Extensions length + buf.extend_from_slice(&(extensions_len as u16).to_be_bytes()); + + // SNI extension + buf.extend_from_slice(&[0x00, 0x00]); // extension type: server_name + buf.extend_from_slice(&(sni_ext_data_len as u16).to_be_bytes()); + buf.extend_from_slice(&(sni_list_len as u16).to_be_bytes()); + buf.push(0x00); // host_name type + buf.extend_from_slice(&(hostname_bytes.len() as u16).to_be_bytes()); + buf.extend_from_slice(hostname_bytes); + + buf +} + +#[test] +fn extract_sni_from_client_hello() { + let hello = build_client_hello("cool-penguin.rousecontext.com"); + let sni = parse_sni(&hello).unwrap(); + assert_eq!(sni, "cool-penguin.rousecontext.com"); +} + +#[test] +fn extract_sni_different_hostname() { + let hello = build_client_hello("relay.rousecontext.com"); + let sni = parse_sni(&hello).unwrap(); + assert_eq!(sni, "relay.rousecontext.com"); +} + +#[test] +fn no_sni_returns_none() { + // Minimal ClientHello with no extensions + let mut buf = Vec::new(); + // TLS record header + buf.push(0x16); + buf.push(0x03); + buf.push(0x01); + let body_len: u16 = 4 + 2 + 32 + 1 + 2 + 2 + 1 + 1; + buf.extend_from_slice(&body_len.to_be_bytes()); + // Handshake header + buf.push(0x01); + let ch_len = body_len - 4; + buf.push(0); + buf.push((ch_len >> 8) as u8); + buf.push(ch_len as u8); + // Version + buf.push(0x03); + buf.push(0x03); + // Random + buf.extend_from_slice(&[0u8; 32]); + // Session ID len + buf.push(0); + // Cipher suites + buf.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]); + // Compression + buf.push(0x01); + buf.push(0x00); + // No extensions + + let sni = parse_sni(&buf); + assert!(sni.is_none()); +} + +#[test] +fn truncated_data_returns_none() { + let sni = parse_sni(&[0x16, 0x03, 0x01]); + assert!(sni.is_none()); +} + +#[test] +fn non_handshake_returns_none() { + let mut hello = build_client_hello("example.com"); + hello[0] = 0x17; // Change from Handshake to ApplicationData + let sni = parse_sni(&hello); + assert!(sni.is_none()); +} + +#[test] +fn relay_hostname_routes_to_api() { + let decision = + RouteDecision::from_sni(Some("relay.rousecontext.com"), "relay.rousecontext.com"); + assert!(matches!(decision, RouteDecision::RelayApi)); +} + +#[test] +fn device_subdomain_routes_to_passthrough() { + let decision = RouteDecision::from_sni( + Some("cool-penguin.rousecontext.com"), + "relay.rousecontext.com", + ); + match decision { + RouteDecision::DevicePassthrough { subdomain } => { + assert_eq!(subdomain, "cool-penguin"); + } + other => panic!("Expected DevicePassthrough, got {:?}", other), + } +} + +#[test] +fn unknown_sni_closes_connection() { + let decision = RouteDecision::from_sni(Some("evil.otherdomain.com"), "relay.rousecontext.com"); + assert!(matches!(decision, RouteDecision::Reject)); +} + +#[test] +fn no_sni_closes_connection() { + let decision = RouteDecision::from_sni(None, "relay.rousecontext.com"); + assert!(matches!(decision, RouteDecision::Reject)); +} + +#[test] +fn bare_domain_routes_to_api() { + let decision = RouteDecision::from_sni(Some("rousecontext.com"), "relay.rousecontext.com"); + // Bare domain without relay prefix should reject -- it's not the relay hostname + // and not a valid subdomain pattern + assert!(matches!(decision, RouteDecision::Reject)); +} diff --git a/relay/tests/subdomain_test.rs b/relay/tests/subdomain_test.rs new file mode 100644 index 00000000..e450a331 --- /dev/null +++ b/relay/tests/subdomain_test.rs @@ -0,0 +1,79 @@ +use rouse_relay::subdomain::SubdomainGenerator; +use std::collections::HashSet; + +#[test] +fn generated_subdomain_matches_format() { + let gen = SubdomainGenerator::new(); + let name = gen.generate(); + // Must be adjective-noun format: two parts separated by hyphen + let parts: Vec<&str> = name.split('-').collect(); + assert_eq!(parts.len(), 2, "Expected adjective-noun, got: {name}"); + assert!(!parts[0].is_empty(), "Adjective part is empty"); + assert!(!parts[1].is_empty(), "Noun part is empty"); +} + +#[test] +fn generated_subdomain_is_lowercase() { + let gen = SubdomainGenerator::new(); + for _ in 0..50 { + let name = gen.generate(); + assert_eq!(name, name.to_lowercase(), "Subdomain not lowercase: {name}"); + } +} + +#[test] +fn generated_subdomain_is_dns_safe() { + let gen = SubdomainGenerator::new(); + for _ in 0..100 { + let name = gen.generate(); + // DNS labels: a-z, 0-9, hyphens. Must not start/end with hyphen. + // Max 63 chars per label. + assert!(name.len() <= 63, "Subdomain too long: {name}"); + assert!( + !name.starts_with('-'), + "Subdomain starts with hyphen: {name}" + ); + assert!(!name.ends_with('-'), "Subdomain ends with hyphen: {name}"); + for ch in name.chars() { + assert!( + ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-', + "Invalid DNS char '{ch}' in subdomain: {name}" + ); + } + } +} + +#[test] +fn no_collision_in_1000_generations() { + let gen = SubdomainGenerator::new(); + let mut seen = HashSet::new(); + let mut collision_count = 0; + for _ in 0..1000 { + let name = gen.generate(); + if !seen.insert(name) { + collision_count += 1; + } + } + // With ~200 adjectives * ~200 nouns = ~40,000 combinations, + // the birthday paradox predicts ~12 collisions in 1000 draws. + // We allow up to 30 as a generous tolerance (still catches + // degenerate word lists). + assert!( + collision_count <= 30, + "Too many collisions ({collision_count}) in 1000 generations" + ); +} + +#[test] +fn word_lists_have_sufficient_entries() { + let gen = SubdomainGenerator::new(); + let (adj_count, noun_count) = gen.word_counts(); + assert!( + adj_count >= 100, + "Need at least 100 adjectives, got {adj_count}" + ); + assert!( + noun_count >= 100, + "Need at least 100 nouns, got {noun_count}" + ); +}