//! End-to-end HTTP tests for the `texrra serve` binary. //! //! Each test owns a temporary project/web directory and an ephemeral port, so //! the suite can run in parallel and never touches the developer's `projects/`. use std::{ fs, io::{Read, Write}, net::{TcpListener, TcpStream}, path::{Path, PathBuf}, process::{Child, Command, Stdio}, time::{Duration, SystemTime, UNIX_EPOCH}, }; use serde_json::Value; struct Response { status: u16, headers: String, body: Vec, } impl Response { fn text(&self) -> String { String::from_utf8_lossy(&self.body).to_string() } fn header(&self, name: &str) -> Option<&str> { self.headers .lines() .find_map(|line| line.strip_prefix(&format!("{name}: "))) } } struct TestServer { child: Child, port: u16, root: PathBuf, } impl TestServer { fn start(label: &str) -> Self { let stamp = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("clock") .as_nanos(); let root = std::env::temp_dir().join(format!( "texrra-test-{label}-{}-{stamp}", std::process::id() )); let web = root.join("web"); fs::create_dir_all(&web).expect("create web dir"); fs::write( web.join("index.html"), "test-frontend

test-index

", ) .expect("write index"); fs::write(web.join("styles.css"), "body { color: #123456; }").expect("write css"); fs::write(web.join("app.js"), "console.log('test-app');").expect("write js"); fs::copy( Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/hello.tex"), root.join("hello.tex"), ) .expect("copy input"); let port = free_port(); let child = Command::new(env!("CARGO_BIN_EXE_texrra")) .arg("serve") .arg(root.join("hello.tex")) .arg(port.to_string()) .current_dir(&root) .env("TEXRRA_WEB_DIR", &web) .env("TEXRRA_PROJECTS_DIR", root.join("projects")) .stdout(Stdio::null()) .stderr(Stdio::inherit()) .spawn() .expect("spawn texrra serve"); let server = Self { child, port, root }; server.wait_ready(); server } fn wait_ready(&self) { for _ in 0..120 { if let Ok(response) = send(self.port, "GET", "/", &[], "text/plain") { if response.status == 200 { return; } } std::thread::sleep(Duration::from_millis(50)); } panic!("server on port {} did not become ready", self.port); } fn request(&self, method: &str, path: &str, body: &[u8], content_type: &str) -> Response { send(self.port, method, path, body, content_type).expect("HTTP request") } fn get(&self, path: &str) -> Response { self.request("GET", path, &[], "text/plain") } } impl Drop for TestServer { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); let _ = fs::remove_dir_all(&self.root); } } fn free_port() -> u16 { let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port"); listener.local_addr().expect("local addr").port() } fn send( port: u16, method: &str, path: &str, body: &[u8], content_type: &str, ) -> std::io::Result { let mut stream = TcpStream::connect(("127.0.0.1", port))?; stream.set_read_timeout(Some(Duration::from_secs(30)))?; let mut request = format!("{method} {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n"); if method != "GET" || !body.is_empty() { request.push_str(&format!( "Content-Length: {}\r\nContent-Type: {content_type}\r\n", body.len() )); } request.push_str("\r\n"); stream.write_all(request.as_bytes())?; stream.write_all(body)?; let mut raw = Vec::new(); stream.read_to_end(&mut raw)?; let header_end = raw .windows(4) .position(|window| window == b"\r\n\r\n") .ok_or_else(|| std::io::Error::other("missing HTTP header terminator"))?; let headers = String::from_utf8_lossy(&raw[..header_end]).to_string(); let status = headers .lines() .next() .and_then(|line| line.split_whitespace().nth(1)) .and_then(|status| status.parse::().ok()) .ok_or_else(|| std::io::Error::other("missing HTTP status"))?; let headers = headers.to_ascii_lowercase(); let mut body = raw[header_end + 4..].to_vec(); if headers.contains("transfer-encoding: chunked") { body = decode_chunked(&body); } Ok(Response { status, headers, body, }) } fn decode_chunked(body: &[u8]) -> Vec { let mut decoded = Vec::new(); let mut rest = body; loop { let Some(line_end) = rest.windows(2).position(|window| window == b"\r\n") else { break; }; let size_text = std::str::from_utf8(&rest[..line_end]) .ok() .and_then(|line| line.split(';').next()) .map(str::trim) .unwrap_or(""); let Ok(size) = usize::from_str_radix(size_text, 16) else { break; }; rest = &rest[line_end + 2..]; if size == 0 { break; } if rest.len() < size { break; } decoded.extend_from_slice(&rest[..size]); rest = &rest[size..]; if rest.starts_with(b"\r\n") { rest = &rest[2..]; } } decoded } #[test] fn serves_frontend_assets_and_fonts() { let server = TestServer::start("assets"); let index = server.get("/"); assert_eq!(index.status, 200); assert!(index.text().contains("test-frontend")); assert_eq!( index.header("content-type"), Some("text/html; charset=utf-8") ); let styles = server.get("/styles.css"); assert_eq!(styles.status, 200); assert_eq!( styles.header("content-type"), Some("text/css; charset=utf-8") ); assert!(styles.text().contains("#123456")); let script = server.get("/app.js"); assert_eq!(script.status, 200); assert_eq!( script.header("content-type"), Some("text/javascript; charset=utf-8") ); assert!(script.text().contains("test-app")); let fonts = server.get("/fonts.css"); assert_eq!(fonts.status, 200); assert!(fonts.text().contains("TexrraSerif")); let missing = server.get("/missing.txt"); assert_eq!(missing.status, 404); } #[test] fn serves_project_api_preview_and_pdf() { let server = TestServer::start("api"); let projects = server.get("/api/projects"); assert_eq!(projects.status, 200); let value: Value = serde_json::from_slice(&projects.body).expect("projects JSON"); let listed = value["projects"] .as_array() .expect("projects array") .iter() .any(|project| project["id"] == "hello"); assert!(listed, "seeded hello project missing: {value}"); let raw = server.get("/api/projects/hello/raw?path=hello.tex"); assert_eq!(raw.status, 200); assert!(raw.text().contains("\\documentclass")); let preview = server.request( "POST", "/api/projects/hello/preview", &[], "application/json", ); assert_eq!(preview.status, 200); let value: Value = serde_json::from_slice(&preview.body).expect("preview JSON"); assert_eq!(value["status"], "ok", "{}", value["message"]); assert_eq!(value["pages"].as_array().map(Vec::len), Some(1)); assert!((value["pageWidthMm"].as_f64().unwrap() - 210.0).abs() < 0.1); let pdf = server.request("POST", "/api/projects/hello/pdf", &[], "application/pdf"); assert_eq!(pdf.status, 200); assert!(pdf.body.starts_with(b"%PDF-"), "missing PDF header"); } #[test] fn rejects_static_path_traversal() { let server = TestServer::start("traversal"); let encoded = server.get("/%2e%2e/hello.tex"); assert_eq!(encoded.status, 404); let plain = server.get("/assets/../../hello.tex"); assert_eq!(plain.status, 404); } #[test] fn legacy_texrra_endpoint_renders_html_and_old_name_is_gone() { let server = TestServer::start("legacy"); let source = b"\\documentclass{article}\n\\begin{document}\nLegacy endpoint.\n\\end{document}\n"; let response = server.request("POST", "/texrra", source, "text/plain; charset=utf-8"); assert_eq!(response.status, 200); assert_eq!( response.header("content-type"), Some("text/html; charset=utf-8") ); let old = server.request("POST", "/texcraft", source, "text/plain; charset=utf-8"); assert_eq!(old.status, 404); }