//! The server as seen from a socket, with a stand-in for sccache so that the real one is never touched. use std::io::{Read, Write}; use std::net::{SocketAddr, TcpStream}; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; use std::sync::Arc; use std::thread; use sccache_dash::app::{unix_now, App, Config}; use sccache_dash::stats; use sccache_dash::view; use sccache_dash_api::{Range, Status, Totals, View}; const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json"); const ZEROED: &str = "{\"stats\":{\"compile_requests\":0,\"cache_hits\":{\"counts\":{},\"adv_counts\":{}},\"cache_misses\":{\"counts\":{},\"adv_counts\":{}},\"cache_errors\":{\"counts\":{},\"adv_counts\":{}}},\"version\":\"0.18.0\"}"; const NOW: i64 = 1_764_000_000; /// A script that answers like sccache: it prints a fixture for `--show-stats` and swaps in /// `ZEROED` when asked to zero the stats. Every call is logged. struct Fake { _dir: tempfile::TempDir, script: PathBuf, log: PathBuf, history: PathBuf, } impl Fake { fn new() -> Fake { let dir = tempfile::tempdir().unwrap(); let script = dir.path().join("sccache"); std::fs::write( &script, r#"#!/bin/sh printf '%s\n' "$*" >> "$0.log" case "$1" in --version) echo 'sccache 0.18.0' ;; --zero-stats) cp "$0.zeroed" "$0.out" ;; *) cat "$0.out" ;; esac "#, ) .unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap(); std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap(); Fake { script, log: dir.path().join("sccache.log"), history: dir.path().join("data").join("history.jsonl"), _dir: dir, } } /// The arguments of every call so far, one entry per call. fn calls(&self) -> Vec { std::fs::read_to_string(&self.log) .unwrap_or_default() .lines() .map(str::to_owned) .collect() } } /// A server on a free port, polled once, answering in the background. fn start(fake: &Fake) -> (Arc, SocketAddr) { let cfg = Config { sccache: fake.script.clone().into(), history: fake.history.clone(), }; let app = Arc::new(App::new(cfg, NOW).unwrap()); app.poll_at(NOW); let server = tiny_http::Server::http("127.0.0.1:0").unwrap(); let addr = server.server_addr().to_ip().unwrap(); let answering = Arc::clone(&app); thread::spawn(move || sccache_dash::http::answer(server, answering)); (app, addr) } /// Sends one raw request (`{port}` stands for the server's port) and returns the whole response. fn send(addr: SocketAddr, request: &str) -> String { let request = request.replace("{port}", &addr.port().to_string()); let mut stream = TcpStream::connect(addr).unwrap(); stream.write_all(request.as_bytes()).unwrap(); let mut response = String::new(); stream.read_to_string(&mut response).unwrap(); response } const GET: &str = " HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"; /// `POST /api/zero` with the given `Host` and `Origin` headers; returns the status and the response. fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, String) { let mut request = String::from("POST /api/zero HTTP/1.1\r\n"); for (name, value) in [("Host:", host), ("Origin:", origin)] { if let Some(value) = value { request.push_str(&format!("{name} {value}\r\n")); } } request.push_str("Content-Length: 0\r\nConnection: close\r\n\r\n"); let response = send(addr, &request); let code = response .split_whitespace() .nth(1) .and_then(|c| c.parse().ok()); (code.unwrap_or(0), response) } #[test] fn zero_is_refused_for_a_foreign_origin_or_host() { let fake = Fake::new(); let (app, addr) = start(&fake); // A page anywhere else, in any shape: a bare host, another port, or "null". for origin in [ "https://evil.example", "http://127.0.0.1:1", "http://localhost.evil.example:{port}", "null", ] { let (code, response) = zero(addr, Some("127.0.0.1:{port}"), Some(origin)); assert_eq!( (code, response.contains("refused")), (403, true), "Origin {origin}" ); } // A host name that merely leads here (DNS rebinding) or is not plainly localhost. for host in [ "evil.example:{port}", "127.0.0.1.evil.example:{port}", "localhost:{port}@evil.example", "[::1]:{port}", ] { let (code, _) = zero(addr, Some(host), None); assert_eq!(code, 403, "Host {host}"); } let (code, _) = zero(addr, None, None); assert_eq!(code, 403, "no Host at all"); assert!( !fake.calls().iter().any(|c| c == "--zero-stats"), "sccache was never asked to zero: {:?}", fake.calls() ); assert_eq!(app.lock().readings.len(), 1, "and the history is as it was"); } #[test] fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() { let fake = Fake::new(); let (app, addr) = start(&fake); assert_eq!( app.lock().readings.len(), 1, "the first reading is saved as the baseline" ); let (code, response) = zero( addr, Some("127.0.0.1:{port}"), Some("http://127.0.0.1:{port}"), ); assert_eq!( (code, response.contains("the saved history is kept")), (200, true), "{response}" ); assert_eq!( zero(addr, Some("localhost:{port}"), None).0, 200, "no Origin, as from curl" ); let calls = fake.calls(); assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2); assert_eq!( calls.last().unwrap(), "--show-stats --stats-format json", "the counters are read again right after zeroing" ); let state = app.lock(); assert_eq!( state.readings.len(), 2, "the baseline is kept and a line was added for the reset" ); assert_eq!(state.intervals.len(), 1); assert!( state.intervals[0].reset, "the zeroing shows in the history as a reset" ); let v = view::build(&state, Range::SinceReset, unix_now()); assert_eq!( v.totals, Totals::default(), "sccache's counters read zero now" ); assert!(v.buckets[0].reset); } #[test] fn view_export_and_the_page_answer() { let fake = Fake::new(); let (_app, addr) = start(&fake); let response = send(addr, &format!("GET /api/view?range=reset{GET}")); assert!( response.starts_with("HTTP/1.1 200 OK\r\n") && response.contains("Content-Type: application/json\r\n"), "{response}" ); let body = response.split("\r\n\r\n").nth(1).unwrap(); let v: View = serde_json::from_str(body).unwrap(); assert_eq!(v.totals, stats::parse(LIVE).unwrap().counters.totals); assert_eq!( (v.range, v.server.status), (Some(Range::SinceReset), Status::Idle) ); assert_eq!( ( v.server.version.as_deref(), v.server.client_version.as_deref() ), (Some("0.18.0"), Some("0.18.0")) ); assert!(v .summary_markdown .starts_with("**sccache, since last reset**\n")); let response = send(addr, &format!("GET /api/export{GET}")); assert!( response.contains("Content-Type: application/json\r\n"), "{response}" ); assert!( response.contains(&format!( "Content-Disposition: attachment; filename=\"sccache-stats-{}.json\"", sccache_dash::pretty::stamp(NOW) )), "{response}" ); assert!(response.ends_with(LIVE), "exactly as sccache printed it"); let response = send(addr, &format!("GET /{GET}")); assert!( response.starts_with("HTTP/1.1 200 OK\r\n") && response.contains("Content-Type: text/html; charset=utf-8\r\n"), "{response}" ); assert!(send(addr, &format!("HEAD /{GET}")).starts_with("HTTP/1.1 200 OK\r\n")); assert!(send(addr, &format!("GET /api/view?range=bogus{GET}")).starts_with("HTTP/1.1 400")); assert!( send(addr, &format!("GET /api/view{GET}")).starts_with("HTTP/1.1 400"), "no range at all" ); assert!(send(addr, &format!("GET /../Cargo.toml{GET}")).starts_with("HTTP/1.1 404")); assert!(send(addr, &format!("GET /no-such-file.wasm{GET}")).starts_with("HTTP/1.1 404")); assert!(send(addr, &format!("PUT /api/zero{GET}")).starts_with("HTTP/1.1 405")); } #[test] fn lines_are_saved_when_counters_change_and_at_most_once_a_minute() { let fake = Fake::new(); let cfg = Config { sccache: fake.script.clone().into(), history: fake.history.clone(), }; let app = App::new(cfg, NOW).unwrap(); let lines = |app: &App| app.lock().readings.len(); app.poll_at(NOW); assert_eq!(lines(&app), 1, "the first reading is the baseline"); app.poll_at(NOW + 10); assert_eq!(lines(&app), 1, "nothing changed"); std::fs::write( fake._dir.path().join("sccache.out"), LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"), ) .unwrap(); app.poll_at(NOW + 30); assert_eq!( lines(&app), 1, "changed, but less than a minute after the last line" ); app.poll_at(NOW + 60); assert_eq!( lines(&app), 2, "a minute after the last line, the change is saved" ); assert_eq!(app.lock().intervals[0].delta.totals.requests, 1); app.poll_at(NOW + 60 + sccache_dash::app::HEARTBEAT_SECS - 1); assert_eq!(lines(&app), 2, "unchanged, and not yet ten minutes"); app.poll_at(NOW + 60 + sccache_dash::app::HEARTBEAT_SECS); assert_eq!( lines(&app), 3, "every ten minutes a line marks that the service is running" ); assert!( app.lock().intervals[1].delta.totals == Totals::default(), "the heartbeat line records no change" ); }