From c8b7e19ec558bd2f0562b4307db393254805e319 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 02:34:08 +1300 Subject: [PATCH 1/5] Routing by hostname, hardened (sc-8900, review of #53): production refuses to boot without all four host URLs; the host check judges a normalised path (percent-decoded, repeated slashes collapsed, lowercased), so /%61pi/v1, //api/v1 and /API/v1 can't reach the API through the app host; tests --- app/src/http/hosts.rs | 80 ++++++++++++++++++++++++++++++++++++++++++- app/src/lib.rs | 1 + app/tests/hosts.rs | 4 +++ 3 files changed, 84 insertions(+), 1 deletion(-) diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs index e3044514..81030842 100644 --- a/app/src/http/hosts.rs +++ b/app/src/http/hosts.rs @@ -106,11 +106,64 @@ pub fn serves(host: Host, path: &str) -> bool { } } +/// The path the host check judges: percent-decoded, repeated slashes collapsed and lowercased, so `/%61pi/v1`, +/// `//api/v1` and `/API/v1` are all `/api/v1` and can't reach another host's routes through a lenient router. +#[must_use] +pub fn normalized(path: &str) -> String { + let bytes = path.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && i + 2 < bytes.len() + && let Ok(byte) = u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("zz"), 16) + { + decoded.push(byte); + i += 3; + } else { + decoded.push(bytes[i]); + i += 1; + } + } + let text = String::from_utf8_lossy(&decoded).to_ascii_lowercase(); + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + if !(c == '/' && out.ends_with('/')) { + out.push(c); + } + } + if out.is_empty() { "/".to_string() } else { out } +} + +/// In production, all four host URLs must be set: without them every host would serve every path. Called at boot. +/// +/// # Errors +/// In production, when any of them is missing. +pub fn check(hosts: &HostUrls, production: bool) -> laravel::Result<()> { + let missing: Vec<&str> = [ + ("VISUALCI_SITE_URL", &hosts.site), + ("VISUALCI_APP_URL", &hosts.app), + ("VISUALCI_API_URL", &hosts.api), + ("VISUALCI_MCP_URL", &hosts.mcp), + ] + .into_iter() + .filter(|(_, url)| url.as_deref().is_none_or(|u| u.trim().is_empty())) + .map(|(name, _)| name) + .collect(); + if production && !missing.is_empty() { + return Err(laravel::Error::msg(format!( + "routing by hostname needs every host's URL in production: {} not set", + missing.join(", ") + ))); + } + Ok(()) +} + /// Global middleware: each host serves only its own paths. #[middleware] pub async fn route_by_host(hosts: Section, request: Request, next: Next) -> Response { let Some(here) = hosts.classify(&request.host().to_ascii_lowercase()) else { return next.run(request).await }; - let path = request.path().to_string(); + let path = normalized(request.path()); // `/` on the app is the list of your organizations; without a session, the landing page if here == Host::App && path == "/" && request.cookie(&hosts.session_cookie).is_none() { return Response::new(laravel::http::Redirect::to(format!("{}/", hosts.site())).status(307)) @@ -154,6 +207,31 @@ mod tests { assert!(!serves(Host::Mcp, "/") && !serves(Host::Mcp, "/api/v1/builds")); } + #[test] + fn odd_paths_are_judged_as_what_they_reach() { + for odd in ["/%61pi/v1/builds", "//api/v1/builds", "/API/v1", "/api//v1/x", "/%2Fapi/v1"] { + let path = normalized(odd); + assert!(!serves(Host::App, &path), "{odd} ({path}) on the app host"); + assert!(serves(Host::Api, &path), "{odd} ({path}) on the API host"); + } + assert_eq!(normalized(""), "/"); + assert_eq!(normalized("/a%zz"), "/a%zz", "an invalid escape stays as it is"); + } + + #[test] + fn production_needs_all_four_urls() { + let urls = |app: Option<&str>| HostUrls { + site: Some("https://visualci.com".into()), + app: app.map(str::to_string), + api: Some("https://api.visualci.com".into()), + mcp: Some("https://mcp.visualci.com".into()), + session_cookie: "visualci_session".into(), + }; + assert!(check(&urls(None), true).is_err()); + assert!(check(&urls(None), false).is_ok(), "development serves every path"); + assert!(check(&urls(Some("https://app.visualci.com")), true).is_ok()); + } + #[test] fn host_names_come_from_the_urls() { assert_eq!(name_of("https://App.VisualCI.com/").as_deref(), Some("app.visualci.com")); diff --git a/app/src/lib.rs b/app/src/lib.rs index a2fb8294..7b44bb3c 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -36,6 +36,7 @@ pub fn configure() -> ApplicationBuilder { config.section::(), config.app.env.is_production(), )?; + http::hosts::check(config.section::(), config.app.env.is_production())?; Ok(()) }) .with_middleware(|middleware, _| { diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index da6ad020..637ed9ce 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -22,6 +22,10 @@ async fn each_host_serves_only_its_own_paths(app: Application) { app.get("/up").header("host", "mcp.visualci.test").await.assert_ok(); // The app's front page sends a visitor without a session to the landing page app.get("/").header("host", "app.visualci.test").await.assert_redirect_to("https://visualci.test/"); + // Encoded, doubled or upper-case paths can't reach the API through the app host + for odd in ["/%61pi/v1/version", "//api/v1/version", "/API/v1/version"] { + app.get(odd).header("host", "app.visualci.test").await.assert_status(404); + } // Any other host (a pod's own address) gets every path app.get("/api/v1/version").header("host", "10.0.0.7").await.assert_ok(); } From dc8dad9739aba1f2adf83bbdea73240426a94a02 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:28:44 +1300 Subject: [PATCH 2/5] Routing by hostname, review fixes: production boots only when all four host URLs name a host and no two are the same (a bare app.visualci.com fails); in production a request for any other host reaches only /up and the renderers' /internal paths; Laravel's TrustHosts trusts every host, since it would refuse the API and MCP hosts and the pods' probes and route_by_host is the host check; tested in production for an unknown host and a boot that fails --- app/src/http/hosts.rs | 83 +++++++++++++++++++++++++++++++------------ app/src/lib.rs | 4 +++ app/tests/hosts.rs | 52 ++++++++++++++++++++++++++- 3 files changed, 115 insertions(+), 24 deletions(-) diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs index 81030842..adb86b23 100644 --- a/app/src/http/hosts.rs +++ b/app/src/http/hosts.rs @@ -9,8 +9,9 @@ //! and so does any path a host doesn't serve. The one redirect is the app's `/` for a visitor without a session, which //! goes to the landing page. `/up` answers on every host. //! -//! Requests for any other host (a pod's own address for probes, the cluster-internal address the renderers use, a dev -//! server) get every path, and so does everything when the hosts aren't configured. +//! In production, a request for any other host (a pod's own address for probes, the cluster-internal address the +//! renderers use) reaches only `/up` and the renderers' `/internal` paths. Elsewhere (a dev server) it gets every path, +//! and so does everything when the hosts aren't configured. use laravel::config::Section; use laravel::http::{Next, Request, Response, middleware}; @@ -135,51 +136,84 @@ pub fn normalized(path: &str) -> String { if out.is_empty() { "/".to_string() } else { out } } -/// In production, all four host URLs must be set: without them every host would serve every path. Called at boot. +/// In production, all four host URLs must be set, each with a host name, and no two the same: otherwise every host +/// would serve every path, or one host would be taken for another. Called at boot. /// /// # Errors -/// In production, when any of them is missing. +/// In production, when one is missing, has no host name (`app.visualci.com` without `https://`), or repeats another. pub fn check(hosts: &HostUrls, production: bool) -> laravel::Result<()> { - let missing: Vec<&str> = [ + if !production { + return Ok(()); + } + let urls = [ ("VISUALCI_SITE_URL", &hosts.site), ("VISUALCI_APP_URL", &hosts.app), ("VISUALCI_API_URL", &hosts.api), ("VISUALCI_MCP_URL", &hosts.mcp), - ] - .into_iter() - .filter(|(_, url)| url.as_deref().is_none_or(|u| u.trim().is_empty())) - .map(|(name, _)| name) - .collect(); - if production && !missing.is_empty() { - return Err(laravel::Error::msg(format!( - "routing by hostname needs every host's URL in production: {} not set", - missing.join(", ") - ))); + ]; + let mut problems = Vec::new(); + let mut seen: Vec<(String, &str)> = Vec::new(); + for (name, url) in urls { + match url.as_deref().map(str::trim).filter(|u| !u.is_empty()) { + None => problems.push(format!("{name} isn't set")), + Some(url) => match name_of(url) { + None => problems.push(format!("{name} has no host name ({url:?}: it needs https://)")), + Some(host) => match seen.iter().find(|(h, _)| *h == host) { + Some((_, other)) => problems.push(format!("{name} has the same host as {other} ({host})")), + None => seen.push((host, name)), + }, + }, + } + } + if problems.is_empty() { + return Ok(()); } - Ok(()) + Err(laravel::Error::msg(format!("routing by hostname in production: {}", problems.join("; ")))) +} + +/// Whether every host's URL is set. +fn configured(hosts: &HostUrls) -> bool { + [&hosts.site, &hosts.app, &hosts.api, &hosts.mcp].iter().all(|u| u.as_deref().is_some_and(|u| !u.trim().is_empty())) +} + +/// What a request for any other host may reach in production: the health check (probes on a pod's own address) and +/// the renderers' paths (the cluster-internal address they call). Anything else is a 404, so a host header nobody +/// configured can't reach the app's, the API's or the MCP server's routes. +#[must_use] +pub fn unknown_host_serves(path: &str) -> bool { + path == "/up" || under(path, "/internal") } /// Global middleware: each host serves only its own paths. #[middleware] pub async fn route_by_host(hosts: Section, request: Request, next: Next) -> Response { - let Some(here) = hosts.classify(&request.host().to_ascii_lowercase()) else { return next.run(request).await }; let path = normalized(request.path()); + let Some(here) = hosts.classify(&request.host().to_ascii_lowercase()) else { + if configured(&hosts) && laravel::config().app.env.is_production() && !unknown_host_serves(&path) { + return not_found(&hosts); + } + return next.run(request).await; + }; // `/` on the app is the list of your organizations; without a session, the landing page if here == Host::App && path == "/" && request.cookie(&hosts.session_cookie).is_none() { return Response::new(laravel::http::Redirect::to(format!("{}/", hosts.site())).status(307)) .with_header("cache-control", "no-store"); } if !serves(here, &path) { - let site = hosts.site(); - let page = format!( - "Not found · VisualCI\ -

There's nothing here. See VisualCI or the docs.

\n" - ); - return Response::new(laravel::view::Html::raw(page)).with_status(404).with_header("cache-control", "no-store"); + return not_found(&hosts); } next.run(request).await } +fn not_found(hosts: &HostUrls) -> Response { + let site = hosts.site(); + let page = format!( + "Not found · VisualCI\ +

There's nothing here. See VisualCI or the docs.

\n" + ); + Response::new(laravel::view::Html::raw(page)).with_status(404).with_header("cache-control", "no-store") +} + #[cfg(test)] mod tests { use super::*; @@ -230,6 +264,9 @@ mod tests { assert!(check(&urls(None), true).is_err()); assert!(check(&urls(None), false).is_ok(), "development serves every path"); assert!(check(&urls(Some("https://app.visualci.com")), true).is_ok()); + // A bare host name, or the same host twice, would route nothing to it + assert!(check(&urls(Some("app.visualci.com")), true).is_err()); + assert!(check(&urls(Some("https://api.visualci.com")), true).is_err()); } #[test] diff --git a/app/src/lib.rs b/app/src/lib.rs index 7b44bb3c..8afdb3a9 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -43,6 +43,10 @@ pub fn configure() -> ApplicationBuilder { middleware.prepend(http::hosts::route_by_host); // The site's signed-in hint is read by its script: plain, not encrypted middleware.replace(laravel::cookie::EncryptCookies::except([auth::sign_in::SIGNED_IN_HINT])); + // Laravel's TrustHosts would trust APP_URL's host alone, refusing the API and MCP hosts and the pods' own + // addresses (probes). `route_by_host` is the host check instead: each configured host reaches only its + // own paths, and in production any other host only `/up` and the renderers' paths. + middleware.trust_hosts(["*"]); }) .with_routing(|routing, _| { routing.web(auth::routes).api(http::api::routes).health("/up"); diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 637ed9ce..68bce5cc 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -26,6 +26,56 @@ async fn each_host_serves_only_its_own_paths(app: Application) { for odd in ["/%61pi/v1/version", "//api/v1/version", "/API/v1/version"] { app.get(odd).header("host", "app.visualci.test").await.assert_status(404); } - // Any other host (a pod's own address) gets every path + // Outside production, any other host (a dev server's address) gets every path app.get("/api/v1/version").header("host", "10.0.0.7").await.assert_ok(); } + +/// The app in production, without the test database (nothing here needs it, and tests only refresh one in testing). +fn in_production() -> laravel::foundation::ApplicationBuilder { + app::configure().for_testing(env!("CARGO_MANIFEST_DIR")).with_envs([ + ("APP_ENV", "production"), + ("SESSION_DRIVER", "memory"), + ("CACHE_STORE", "memory"), + ("QUEUE_CONNECTION", "sync"), + ("DB_CONNECTION", "pgsql"), + ("DATABASE_URL", "postgres://loco:loco@127.0.0.1:55433/visualci_app_test"), + ]) +} + +fn production() -> Application { + in_production() + .with_envs([ + ("VISUALCI_SITE_URL", "https://visualci.test"), + ("VISUALCI_APP_URL", "https://app.visualci.test"), + ("VISUALCI_API_URL", "https://api.visualci.test"), + ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), + ]) + .create() +} + +#[tokio::test(flavor = "multi_thread")] +async fn in_production_an_unknown_host_reaches_only_health_and_the_renderers() { + let app = production(); + app.boot().await.expect("it boots"); + app.get("/up").header("host", "10.0.0.7").await.assert_ok(); + for path in ["/api/v1/version", "/auth/session", "/mcp", "/", "/%61pi/v1/version"] { + app.get(path).header("host", "10.0.0.7").await.assert_status(404); + } + app.get("/api/v1/version").header("host", "api.visualci.test").await.assert_ok(); +} + +fn misconfigured() -> laravel::foundation::ApplicationBuilder { + in_production().with_envs([ + ("VISUALCI_SITE_URL", "https://visualci.test"), + ("VISUALCI_APP_URL", "app.visualci.test"), + ("VISUALCI_API_URL", "https://api.visualci.test"), + ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), + ]) +} + +#[tokio::test] +async fn production_doesnt_boot_with_a_host_url_that_names_no_host() { + let app = misconfigured().create(); + let booted = app.boot().await; + assert!(booted.is_err(), "a bare app.visualci.test would route nothing to the app"); +} From 6348db14a8a3dbff359964fe1ceb171b08620c81 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:38:34 +1300 Subject: [PATCH 3/5] Routing by hostname: test that a forged Host gets no URL with its name in production (sign-in's callback, OAuth metadata, the device code and redirects are unreachable from it; every other URL comes from the configured host URLs) --- app/tests/hosts.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 68bce5cc..37946790 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -79,3 +79,36 @@ async fn production_doesnt_boot_with_a_host_url_that_names_no_host() { let booted = app.boot().await; assert!(booted.is_err(), "a bare app.visualci.test would route nothing to the app"); } + +/// Every host is trusted (Laravel's TrustHosts would refuse the API and MCP hosts), so nothing may build a URL from a +/// forged Host header: in production such a request reaches nothing that builds one (sign-in's callback, OAuth +/// metadata, the device code, redirects), and nothing it gets back names the forged host. +#[tokio::test(flavor = "multi_thread")] +async fn a_forged_host_gets_no_url_with_its_name() { + let app = production(); + app.boot().await.expect("it boots"); + let paths = [ + "/", + "/up", + "/auth/github", + "/auth/github/callback", + "/auth/session", + "/login", + "/oauth/authorize?client_id=x&response_type=code", + "/.well-known/oauth-authorization-server", + "/.well-known/oauth-protected-resource/mcp", + "/api/v1/version", + "/account", + ]; + for path in paths { + let response = app.get(path).header("host", "evil.example").await; + let headers = format!("{:?}", response.headers()); + assert!(!headers.contains("evil.example"), "{path}: {headers}"); + assert!(!response.text().contains("evil.example"), "{path}"); + if path != "/up" { + response.assert_status(404); + } + } + let device = app.post("/api/v1/device/code").header("host", "evil.example").json(json!({})).await; + device.assert_status(404); +} From 5235c919a4e0ff664fde307a202cac7262f0f6a3 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 03:59:57 +1300 Subject: [PATCH 4/5] Routing by hostname: production boots with none of the four host URLs (one host serves everything, as a self-hosted VisualCI does, every URL from APP_URL) or all four, each naming a host and no two the same; only some of them is a boot error; tested in production for one host, the partial case, and four --- app/src/http/hosts.rs | 18 ++++++++++++------ app/tests/hosts.rs | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs index adb86b23..66477b5b 100644 --- a/app/src/http/hosts.rs +++ b/app/src/http/hosts.rs @@ -136,13 +136,17 @@ pub fn normalized(path: &str) -> String { if out.is_empty() { "/".to_string() } else { out } } -/// In production, all four host URLs must be set, each with a host name, and no two the same: otherwise every host -/// would serve every path, or one host would be taken for another. Called at boot. +/// In production, either none of the four host URLs is set (one host serves everything: a self-hosted VisualCI, whose +/// URLs all come from `APP_URL`) or all four are, each with a host name and no two the same. Setting only some would +/// leave the others' paths on every host, and a URL without a host, or a repeated one, would route nothing to it. +/// Called at boot. /// /// # Errors -/// In production, when one is missing, has no host name (`app.visualci.com` without `https://`), or repeats another. +/// In production, when only some are set, or one has no host name (`app.visualci.com` without `https://`) or repeats +/// another. pub fn check(hosts: &HostUrls, production: bool) -> laravel::Result<()> { - if !production { + let set = |u: &Option| u.as_deref().is_some_and(|u| !u.trim().is_empty()); + if !production || ![&hosts.site, &hosts.app, &hosts.api, &hosts.mcp].into_iter().any(set) { return Ok(()); } let urls = [ @@ -155,7 +159,7 @@ pub fn check(hosts: &HostUrls, production: bool) -> laravel::Result<()> { let mut seen: Vec<(String, &str)> = Vec::new(); for (name, url) in urls { match url.as_deref().map(str::trim).filter(|u| !u.is_empty()) { - None => problems.push(format!("{name} isn't set")), + None => problems.push(format!("{name} isn't set (set all four host URLs, or none for one host)")), Some(url) => match name_of(url) { None => problems.push(format!("{name} has no host name ({url:?}: it needs https://)")), Some(host) => match seen.iter().find(|(h, _)| *h == host) { @@ -261,8 +265,10 @@ mod tests { mcp: Some("https://mcp.visualci.com".into()), session_cookie: "visualci_session".into(), }; - assert!(check(&urls(None), true).is_err()); + assert!(check(&urls(None), true).is_err(), "only some of them"); assert!(check(&urls(None), false).is_ok(), "development serves every path"); + let none = HostUrls { site: None, app: None, api: None, mcp: None, session_cookie: "visualci_session".into() }; + assert!(check(&none, true).is_ok(), "one host serves everything"); assert!(check(&urls(Some("https://app.visualci.com")), true).is_ok()); // A bare host name, or the same host twice, would route nothing to it assert!(check(&urls(Some("app.visualci.com")), true).is_err()); diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 37946790..8cf78b20 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -112,3 +112,23 @@ async fn a_forged_host_gets_no_url_with_its_name() { let device = app.post("/api/v1/device/code").header("host", "evil.example").json(json!({})).await; device.assert_status(404); } + +/// A self-hosted VisualCI on one host: none of the four URLs set, so it boots, and any Host gets every path. +#[tokio::test(flavor = "multi_thread")] +async fn one_host_serves_everything_in_production() { + let app = in_production().with_env("APP_URL", "https://visualci.example.com").create(); + app.boot().await.expect("it boots on one host"); + app.get("/api/v1/version").header("host", "visualci.example.com").await.assert_ok(); + app.get("/auth/session").header("host", "10.0.0.7").await.assert_ok(); +} + +#[tokio::test] +async fn production_doesnt_boot_with_only_some_host_urls() { + let app = in_production() + .with_envs([ + ("VISUALCI_APP_URL", "https://app.visualci.test"), + ("VISUALCI_API_URL", "https://api.visualci.test"), + ]) + .create(); + assert!(app.boot().await.is_err(), "the site's and MCP's paths would be on every host"); +} From 4dbdbb21a661ce4957a8f87cd3fd51c44864b253 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 04:22:39 +1300 Subject: [PATCH 5/5] Routing by hostname on main: production-mode tests get storage and OAuth settings; one Cargo.toml tracing entry; the OAuth discovery test expects the tests' APP_URL (https://app.visualci.test, since #59) --- app/tests/hosts.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/tests/hosts.rs b/app/tests/hosts.rs index 8cf78b20..4787f8c1 100644 --- a/app/tests/hosts.rs +++ b/app/tests/hosts.rs @@ -39,6 +39,10 @@ fn in_production() -> laravel::foundation::ApplicationBuilder { ("QUEUE_CONNECTION", "sync"), ("DB_CONNECTION", "pgsql"), ("DATABASE_URL", "postgres://loco:loco@127.0.0.1:55433/visualci_app_test"), + ("S3_ENDPOINT", "http://127.0.0.1:59000"), + ("S3_BUCKET", "visualci-test"), + ("S3_ACCESS_KEY_ID", "visualci"), + ("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"), ]) } @@ -49,6 +53,8 @@ fn production() -> Application { ("VISUALCI_APP_URL", "https://app.visualci.test"), ("VISUALCI_API_URL", "https://api.visualci.test"), ("VISUALCI_MCP_URL", "https://mcp.visualci.test"), + ("OAUTH_ISSUER", "https://mcp.visualci.test"), + ("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"), ]) .create() }