From c79021ca78307efb50e481271ab7c446a853f472 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Thu, 3 Dec 2026 01:49:52 +1300 Subject: [PATCH] app/: routing by hostname (sc-8900): with VISUALCI_{SITE,APP,API,MCP}_URL set, the app, API and MCP hosts each serve only their own paths (a 404 page otherwise), the app's / sends a visitor without a session to the landing page, and any other host gets every path; ported from server/src/hosts.rs --- app/src/http/hosts.rs | 163 ++++++++++++++++++++++++++++++++++++++++++ app/src/http/mod.rs | 1 + app/src/lib.rs | 3 + app/tests/hosts.rs | 27 +++++++ 4 files changed, 194 insertions(+) create mode 100644 app/src/http/hosts.rs create mode 100644 app/tests/hosts.rs diff --git a/app/src/http/hosts.rs b/app/src/http/hosts.rs new file mode 100644 index 00000000..e3044514 --- /dev/null +++ b/app/src/http/hosts.rs @@ -0,0 +1,163 @@ +//! Routing by hostname, ported from today's server (sc-8900). One server answers for the app, API and MCP hosts, and +//! each serves only its own paths: +//! +//! - the app (`app.visualci.com`): the React app, sign-in and the app's own `/api/ui` calls. +//! - the API (`api.visualci.com`): `/api/v1` for the CLI and clients, the webhooks and `/status`. +//! - the MCP server (`mcp.visualci.com`): `/mcp` and the OAuth endpoints MCP clients call. +//! +//! The site (`visualci.com`) is a static Cloudflare Worker; a request for it that reaches the server anyway gets a 404, +//! 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. + +use laravel::config::Section; +use laravel::http::{Next, Request, Response, middleware}; + +/// The four hosts' URLs (`VISUALCI_SITE_URL`, `VISUALCI_APP_URL`, `VISUALCI_API_URL`, `VISUALCI_MCP_URL`). Without +/// all four, every host serves every path. +#[derive(Clone, laravel::config::Section)] +pub struct HostUrls { + #[env("VISUALCI_SITE_URL")] + pub site: Option, + #[env("VISUALCI_APP_URL")] + pub app: Option, + #[env("VISUALCI_API_URL")] + pub api: Option, + #[env("VISUALCI_MCP_URL")] + pub mcp: Option, + /// The session cookie's name, to tell a signed-in visitor at the app's `/` from a new one + #[env("SESSION_COOKIE", default = "visualci_session")] + pub session_cookie: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Host { + Site, + App, + Api, + Mcp, +} + +/// A URL's host name, lowercased. +fn name_of(url: &str) -> Option { + let rest = url.split_once("://")?.1; + let authority = rest.split('/').next()?; + let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h); + let host = host.rsplit_once(':').filter(|(_, p)| p.chars().all(|c| c.is_ascii_digit())).map_or(host, |(h, _)| h); + (!host.is_empty()).then(|| host.to_ascii_lowercase()) +} + +impl HostUrls { + /// Which of the four hosts a request's host name is, when they're all configured. + #[must_use] + pub fn classify(&self, name: &str) -> Option { + let all = [(Host::Site, &self.site), (Host::App, &self.app), (Host::Api, &self.api), (Host::Mcp, &self.mcp)]; + if all.iter().any(|(_, url)| url.is_none()) { + return None; + } + all.into_iter() + .find(|(_, url)| url.as_deref().and_then(name_of).is_some_and(|n| n == name)) + .map(|(host, _)| host) + } + + fn site(&self) -> &str { + self.site.as_deref().unwrap_or("").trim_end_matches('/') + } +} + +fn under(path: &str, prefix: &str) -> bool { + path == prefix || path.strip_prefix(prefix).is_some_and(|rest| rest.starts_with('/')) +} + +/// The OAuth paths an MCP client calls itself, on the MCP host. The authorization endpoint, `/oauth/authorize`, is the +/// app's. +fn is_oauth_server_path(path: &str) -> bool { + under(path, "/.well-known/oauth-authorization-server") + || under(path, "/.well-known/oauth-protected-resource") + || matches!(path, "/oauth/register" | "/oauth/token" | "/oauth/revoke" | "/oauth/introspect") +} + +fn is_site_path(path: &str) -> bool { + path == "/" || under(path, "/docs") || matches!(path, "/llms.txt" | "/llms-full.txt" | "/install.sh") +} + +/// Whether `host` serves `path`. +#[must_use] +pub fn serves(host: Host, path: &str) -> bool { + let health = path == "/up"; + match host { + Host::Site => false, + Host::Api => health || under(path, "/api/v1") || under(path, "/webhooks") || path == "/status", + Host::Mcp => health || under(path, "/mcp") || is_oauth_server_path(path), + // The app's client-side routes (`/account`, `//...`) can be any path, so the app serves everything that + // isn't another host's. + Host::App => { + path == "/" + || !(is_site_path(path) + || is_oauth_server_path(path) + || under(path, "/api/v1") + || under(path, "/webhooks") + || under(path, "/internal") + || under(path, "/mcp") + || path == "/status") + } + } +} + +/// 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(); + // `/` 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"); + } + next.run(request).await +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_host_serves_only_its_own_paths() { + for path in ["/", "/docs/", "/llms.txt", "/account", "/api/v1/builds", "/mcp", "/status"] { + assert!(!serves(Host::Site, path), "site {path}"); + } + for path in ["/", "/account", "/docspring/pdfs/builds/2", "/auth/github/callback", "/api/ui/me", "/assets/x.js"] + { + assert!(serves(Host::App, path), "app {path}"); + } + for path in ["/docs/", "/llms.txt", "/install.sh", "/api/v1/builds", "/mcp", "/webhooks/stripe"] { + assert!(!serves(Host::App, path), "app {path}"); + } + assert!(serves(Host::App, "/mcpx")); + for path in ["/api/v1/builds/x", "/webhooks/stripe", "/status", "/up"] { + assert!(serves(Host::Api, path), "api {path}"); + } + for path in ["/", "/mcp", "/api/ui/me", "/favicon.ico", "/internal/renderer/claim"] { + assert!(!serves(Host::Api, path), "api {path}"); + } + assert!(serves(Host::Mcp, "/mcp") && serves(Host::Mcp, "/up")); + assert!(!serves(Host::Mcp, "/") && !serves(Host::Mcp, "/api/v1/builds")); + } + + #[test] + fn host_names_come_from_the_urls() { + assert_eq!(name_of("https://App.VisualCI.com/").as_deref(), Some("app.visualci.com")); + assert_eq!(name_of("http://docspring-dev.hs:5250").as_deref(), Some("docspring-dev.hs")); + assert_eq!(name_of("not a url"), None); + } +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index 1e6a6bd5..44cc1f01 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -1,3 +1,4 @@ //! HTTP handlers. pub mod api; +pub mod hosts; diff --git a/app/src/lib.rs b/app/src/lib.rs index f37c18c3..bfebd697 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -17,6 +17,9 @@ pub fn configure() -> ApplicationBuilder { .with_auth(|auth, _| { auth.session::(); }) + .with_middleware(|middleware, _| { + middleware.prepend(http::hosts::route_by_host); + }) .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 new file mode 100644 index 00000000..da6ad020 --- /dev/null +++ b/app/tests/hosts.rs @@ -0,0 +1,27 @@ +//! Routing by hostname: with the four hosts configured, each serves only its own paths. + +use laravel::testing::prelude::*; + +fn hosts() -> Application { + app::testing::configure() + .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() +} + +#[laravel::test(app = hosts)] +async fn each_host_serves_only_its_own_paths(app: Application) { + app.get("/api/v1/version").header("host", "api.visualci.test").await.assert_ok(); + app.get("/api/v1/version").header("host", "app.visualci.test").await.assert_status(404).assert_see("nothing here"); + app.get("/auth/session").header("host", "api.visualci.test").await.assert_status(404); + app.get("/auth/session").header("host", "app.visualci.test").await.assert_ok(); + 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/"); + // 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(); +}