// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! The API's edges (ROADMAP §6 phase 2, tests first): requests without a valid token are //! rejected on every route and tokens never reach a log, an error or a state file; request //! bodies are hostile input; the routes repository holds only host files; control only //! listens on loopback; the OpenAPI document covers the API. #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] #[cfg(unix)] mod common; // On Windows this target has nothing to run: it shows as one *ignored* test, never as a // pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] #[ignore = "needs Linux (edge admin socket): run it in WSL2, see CLAUDE.md"] fn needs_linux() {} #[cfg(unix)] mod unix { use std::time::Duration; use crate::common::{Env, EnvSpec, host}; use ianitor_testkit::more::tcp_raw; use ianitor_testkit::upstream::Echo; use serde_json::{Value, json}; /// Every (method, path) in the OpenAPI document, with path parameters filled in. fn routes(doc: &Value) -> Vec<(String, String)> { let mut out = Vec::new(); for (path, item) in doc["paths"].as_object().unwrap() { // The one-time device download is the one call without a token: the link is // the secret (G15). Every other call needs one. if path.starts_with("/api/v1/device-bundles/") { continue; } for method in ["get", "post", "put", "patch", "delete"] { if item.get(method).is_some() { let p = path .replace("{hostname}", "a.test") .replace("{id}", "x") .replace("{change_id}", "x"); out.push((method.to_uppercase(), p)); } } } out } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn requests_without_a_valid_token_are_rejected_and_tokens_are_never_logged() { let good = Echo::start("good").await; let mut env = Env::new(EnvSpec::default()).await; env.start_control(None); let doc = env.call("GET", "/api/v1/openapi.json", None).await; assert_eq!(doc.status, 200, "{}", doc.text); let routes = routes(&doc.json); assert!(routes.len() >= 25, "{routes:?}"); // Make a second token through the API and revoke it, to test a revoked one too. let made = env .call("POST", "/api/v1/tokens", Some(json!({ "name": "script" }))) .await; assert_eq!(made.status, 201, "{}", made.text); let revoked = made.json["token"].as_str().unwrap().to_owned(); let rid = made.json["id"].as_str().unwrap().to_owned(); assert_eq!( env.call("DELETE", &format!("/api/v1/tokens/{rid}"), None) .await .status, 204 ); // A listing never shows values or hashes. let list = env.call("GET", "/api/v1/tokens", None).await; assert!( !list.text.contains(&revoked) && !list.text.contains("sha256"), "{}", list.text ); assert!(!list.text.contains(&env.token)); let mut wrong = env.token.clone(); wrong.pop(); wrong.push(if env.token.ends_with('A') { 'B' } else { 'A' }); type Case = (String, Vec<(String, String)>, &'static str); let cases: Vec = vec![ ("no header".into(), vec![], "token.missing"), ( "not bearer".into(), vec![("Authorization".into(), env.token.clone())], "token.unknown", ), ( "basic".into(), vec![("Authorization".into(), "Basic YWRtaW46YWRtaW4=".into())], "token.unknown", ), ( "one char off".into(), vec![("Authorization".into(), format!("Bearer {wrong}"))], "token.unknown", ), ( "made up".into(), vec![( "Authorization".into(), "Bearer ian_0000000000000000_xxxxxxxx".into(), )], "token.unknown", ), ( "revoked".into(), vec![("Authorization".into(), format!("Bearer {revoked}"))], "token.revoked", ), ( "empty bearer".into(), vec![("Authorization".into(), "Bearer ".into())], "token.unknown", ), // Identity headers without edge's proof are refused (docs/ui-api.md G14). ( "remote-user".into(), vec![ ("Remote-User".into(), "mark".into()), ("Remote-Groups".into(), "admins".into()), ], "ui.no_proof", ), ]; for (what, headers, code) in &cases { let hs: Vec<(&str, &str)> = headers .iter() .map(|(a, b)| (a.as_str(), b.as_str())) .collect(); for (method, path) in &routes { let body = (method != "GET" && method != "DELETE").then(|| json!({})); let r = env.call_with(method, path, &hs, body).await; assert_eq!(r.status, 401, "{what}: {method} {path}: {}", r.text); assert_eq!(r.json["error"]["code"], *code, "{what}: {method} {path}"); assert!(r.json["error"]["message"].as_str().unwrap().len() > 10); assert!(r.json["request_id"].is_string() && r.json["server_time"].is_string()); } } // Unknown paths are refused the same way, before anything else. assert_eq!( env.call_with("GET", "/api/v1/nope", &[], None).await.status, 401 ); // Outside /api/ only the built UI is served (no data, no token); none is set up here. assert_eq!(env.call_with("GET", "/", &[], None).await.status, 404); // A wrong Host header (DNS rebinding) is refused even with a good token. let auth = format!("Bearer {}", env.token); let raw = format!( "GET /api/v1/overview HTTP/1.1\r\nHost: evil.example\r\nAuthorization: {auth}\r\nConnection: close\r\n\r\n" ); let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); assert_eq!(r.status, 403, "{}", r.text()); // A browser write without the UI header is refused (CSRF). let r = env .call_with( "POST", "/api/v1/hosts", &[("Authorization", &auth), ("Origin", "https://evil.example")], Some(json!({ "host": host("a.test", &good.url(), false) })), ) .await; assert_eq!(r.status, 403, "{}", r.text); assert_eq!(r.json["error"]["code"], "request.csrf"); let r = env .call_with( "POST", "/api/v1/hosts", &[ ("Authorization", &auth), ("Origin", "http://127.0.0.1"), ("X-Ianitor-UI", "1"), ], Some(json!({ "host": host("a.test", &good.url(), false) })), ) .await; assert_eq!(r.status, 202, "{}", r.text); env.wait_apply(r.json["apply"]["id"].as_str().unwrap()) .await; // Exercise the rest with the good token, then look for any token anywhere. for (method, path) in &routes { if method == "GET" { env.call(method, path, None).await; } } tokio::time::sleep(Duration::from_millis(300)).await; env.kill_control(); let mut everything = env.control_log(); for f in [ "applies.json", "push.json", "share-links.json", "journal.json", ] { everything.push_str(&env.file(&format!("state/{f}"))); } everything.push_str(&env.file("edge/edge.json")); everything.push_str(&env.git(&["log", "-p", "--all"])); // `ian_<16 hex>_`; the secret itself may contain '_'. let secret_part = |t: &str| { assert!(t.starts_with("ian_") && t.as_bytes()[20] == b'_'); t[21..].to_owned() }; for t in [&env.token, &revoked] { assert!( !everything.contains(secret_part(t).as_str()), "a token leaked" ); } let stored = env.file("state/tokens.json"); for t in [&env.token, &revoked] { assert!( !stored.contains(secret_part(t).as_str()), "tokens.json holds a value, not a hash" ); } #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(env.dir.join("state/tokens.json")) .unwrap() .permissions() .mode(); assert_eq!(mode & 0o077, 0, "tokens.json is private"); } } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn bodies_are_hostile_input() { let good = Echo::start("good").await; let mut env = Env::new(EnvSpec::default()).await; env.start_control(None); let auth = format!("Bearer {}", env.token); // Unknown fields, at the top and inside the host. let r = env .call( "POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "colour": 1 })), ) .await; assert_eq!(r.status, 422, "{}", r.text); assert_eq!(r.json["error"]["code"], "request.body_unknown_field"); assert_eq!(r.json["error"]["field"], "colour"); let mut h = host("a.test", &good.url(), false); h["upstream"] = json!("typo"); let r = env .call("POST", "/api/v1/hosts", Some(json!({ "host": h }))) .await; assert_eq!( r.json["error"]["code"], "request.body_unknown_field", "{}", r.text ); // Wrong types never echo the value sent. let r = env .call( "POST", "/api/v1/tokens", Some(json!({ "name": ["secret-ish-value"] })), ) .await; assert_eq!(r.status, 400, "{}", r.text); assert!(!r.text.contains("secret-ish-value"), "{}", r.text); // Nor do odd field names, path parameters or credentials in an upstream URL. let r = env .call("POST", "/api/v1/tokens", Some(json!({ "pass:hunter2": 1 }))) .await; assert_eq!(r.status, 422, "{}", r.text); assert!(!r.text.contains("hunter2"), "{}", r.text); let r = env.call("GET", "/api/v1/hosts/x%3Chunter2%3E", None).await; assert_eq!(r.status, 404, "{}", r.text); assert!(!r.text.contains("hunter2"), "{}", r.text); let mut leaky = host("a.test", "http://admin:hunter2@10.0.0.2:3000", false); leaky["upstreams"] = json!(["http://admin:hunter2@10.0.0.2:3000", "ftp://u:hunter2@x"]); let r = env .call("POST", "/api/v1/hosts", Some(json!({ "host": leaky }))) .await; assert_eq!(r.status, 422, "{}", r.text); assert!(!r.text.contains("hunter2"), "{}", r.text); // Not JSON, wrong content type, too large. let raw = format!( "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{", env.api ); let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); assert_eq!(r.status, 400, "{}", r.text()); let raw = format!( "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}", env.api ); let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); assert_eq!(r.status, 415, "{}", r.text()); let big = "x".repeat(70 * 1024); let r = env .call("POST", "/api/v1/tokens", Some(json!({ "name": big }))) .await; assert_eq!(r.status, 413, "{}", &r.text[..r.text.len().min(300)]); // Field errors come back as one envelope with codes and field paths. let mut bad = host("a.test", "ftp://x", true); bad["health_check"]["interval_secs"] = json!(0); let r = env .call("POST", "/api/v1/hosts", Some(json!({ "host": bad }))) .await; assert_eq!(r.status, 422, "{}", r.text); let fields: Vec<&str> = r.json["errors"] .as_array() .unwrap() .iter() .filter_map(|e| e["field"].as_str()) .collect(); assert!(fields.contains(&"upstreams[0]"), "{fields:?}"); assert!(fields.contains(&"health_check.interval_secs"), "{fields:?}"); assert_eq!(r.json["error"]["code"], "apply.failed.validation"); let codes: Vec<&str> = r.json["errors"] .as_array() .unwrap() .iter() .filter_map(|e| e["code"].as_str()) .collect(); assert!(codes.contains(&"host.upstream.scheme"), "{codes:?}"); let msg = r.json["errors"][0]["message"].as_str().unwrap(); assert!( !msg.contains("TOML") && !msg.contains("hosts/"), "plain English: {msg}" ); // Validate without applying. let r = env .call( "POST", "/api/v1/hosts/validate?mode=create", Some(host("a.test", &good.url(), false)), ) .await; assert_eq!(r.status, 200, "{}", r.text); // A hostname that does not match the path, a host that does not exist. let r = env .call( "PUT", "/api/v1/hosts/b.test", Some(json!({ "host": host("a.test", &good.url(), false) })), ) .await; assert_eq!( r.json["error"]["code"], "host.hostname.mismatch", "{}", r.text ); let r = env.call("DELETE", "/api/v1/hosts/nope.test", None).await; assert_eq!(r.status, 404); let r = env.call("GET", "/api/v1/hosts/..%2f..%2fetc", None).await; assert_eq!(r.status, 404); // base_rev must be a commit of the history. let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "0".repeat(40) }))).await; assert_eq!(r.json["error"]["code"], "request.base_rev", "{}", r.text); let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "--upload-pack=touch /tmp/x" }))).await; assert_eq!(r.status, 422, "{}", r.text); // Idempotency-Key: a retry returns the same apply; another body with it is refused. let body = json!({ "host": host("a.test", &good.url(), false) }); let k = [ ("Authorization", auth.as_str()), ("Idempotency-Key", "click-1"), ]; let first = env .call_with("POST", "/api/v1/hosts", &k, Some(body.clone())) .await; assert_eq!(first.status, 202, "{}", first.text); let again = env.call_with("POST", "/api/v1/hosts", &k, Some(body)).await; assert_eq!(again.status, 202, "{}", again.text); assert_eq!(again.json["apply"]["id"], first.json["apply"]["id"]); let other = env .call_with( "POST", "/api/v1/hosts", &k, Some(json!({ "host": host("b.test", &good.url(), false) })), ) .await; assert_eq!(other.status, 422); assert_eq!(other.json["error"]["code"], "request.idempotency"); env.wait_apply(first.json["apply"]["id"].as_str().unwrap()) .await; // Taken hostname. let r = env .call( "POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false) })), ) .await; assert_eq!(r.json["error"]["code"], "host.hostname.taken", "{}", r.text); assert_eq!(r.json["error"]["field"], "hostname"); // The overview answers 304 to its own ETag. let o = env.call("GET", "/api/v1/overview", None).await; let etag = o.header("etag").unwrap().to_owned(); let r = env .call_with( "GET", "/api/v1/overview", &[("Authorization", &auth), ("If-None-Match", &etag)], None, ) .await; assert_eq!(r.status, 304); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn the_routes_repository_holds_only_host_files() { let good = Echo::start("good").await; let mut env = Env::new(EnvSpec::default()).await; env.start_control(None); assert_eq!( env.add_host(host("a.test", &good.url(), false)).await["state"], "kept" ); let good_edge = env.file("edge/edge.json"); env.kill_control(); // Someone pushes a stray file and a nested folder straight into the repository. let work = env.dir.join("work"); let git = |args: &[&str], cwd: &std::path::Path| { let o = std::process::Command::new("git") .args(["-c", "user.name=t", "-c", "user.email=t@t"]) .args(args) .current_dir(cwd) .output() .unwrap(); assert!( o.status.success(), "{args:?} {}", String::from_utf8_lossy(&o.stderr) ); }; git( &[ "clone", "--quiet", &env.repo().to_string_lossy(), &work.to_string_lossy(), ], &env.dir.join("."), ); std::fs::create_dir_all(work.join("hosts/sub")).unwrap(); std::fs::write(work.join("README.md"), "hello").unwrap(); std::fs::write( work.join("hosts/sub/b.test.toml"), "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", ) .unwrap(); git(&["add", "-A"], &work); git(&["commit", "--quiet", "-m", "stray"], &work); git(&["push", "--quiet", "origin", "HEAD:main"], &work); env.start_control(None); let o = env.call("GET", "/api/v1/overview", None).await; assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); let r = env .call( "POST", "/api/v1/hosts", Some(json!({ "host": host("c.test", &good.url(), false) })), ) .await; assert_eq!(r.status, 409, "{}", r.text); assert_eq!(r.json["error"]["code"], "control.paused"); // Edge keeps the last good config; nothing stray was compiled. assert_eq!(env.file("edge/edge.json"), good_edge); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn control_only_listens_on_loopback() { let env = Env::new(EnvSpec::default()).await; let text = std::fs::read_to_string(env.config_path()).unwrap(); let open = text.replace( &format!("listen = \"{}\"", env.api), "listen = \"0.0.0.0:7979\"", ); std::fs::write(env.config_path(), open).unwrap(); let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) .arg("--config") .arg(env.config_path()) .output() .unwrap(); assert!(!out.status.success()); assert!( String::from_utf8_lossy(&out.stderr).contains("loopback"), "{}", String::from_utf8_lossy(&out.stderr) ); assert!(std::net::TcpStream::connect("127.0.0.1:7979").is_err()); } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn the_overview_has_everything_the_main_screen_needs() { let good = Echo::start("good").await; let mut env = Env::new(EnvSpec::default()).await; env.start_control(None); env.add_host(host("a.test", &good.url(), true)).await; tokio::time::sleep(Duration::from_secs(2)).await; let o = env.call("GET", "/api/v1/overview", None).await; assert_eq!(o.status, 200, "{}", o.text); for k in [ "counts", "hosts", "engine", "last_apply", "undo", "repo", "site", "server_time", "rev", ] { assert!(o.json.get(k).is_some(), "{k} missing: {}", o.text); } assert_eq!(o.json["counts"]["hosts"], 1); assert_eq!(o.json["counts"]["healthy"], 1, "{}", o.text); let h = &o.json["hosts"][0]; assert_eq!(h["health"]["state"], "healthy"); assert!(h["health"]["latency_ms"].is_u64()); assert_eq!(h["certificate"]["state"], "ok"); assert_eq!(o.json["engine"]["running"], "pingora"); assert_eq!(o.json["engine"]["state"], "running"); assert_eq!(o.json["last_apply"]["state"], "kept"); assert_eq!(o.json["undo"]["available"], true); assert!(o.json["intermediate"].is_null()); // The CLI lists tokens without values. let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) .args(["token", "list", "--config"]) .arg(env.config_path()) .output() .unwrap(); let text = String::from_utf8_lossy(&out.stdout); assert!(text.contains("test") && !text.contains(&env.token[21..])); } }