diff --git a/app/src/auth/mod.rs b/app/src/auth/mod.rs index 62c53f28..034488f4 100644 --- a/app/src/auth/mod.rs +++ b/app/src/auth/mod.rs @@ -244,4 +244,6 @@ pub fn routes(route: &mut laravel::prelude::Router) { route.get("/auth/{forge}/callback", sign_in::callback); route.get("/auth/session", sign_in::session); route.post("/auth/logout", sign_in::logout); + // Anything else on the web group is a page of the React app + route.fallback(crate::http::app_shell::app_shell); } diff --git a/app/src/http/app_shell.rs b/app/src/http/app_shell.rs new file mode 100644 index 00000000..423aec88 --- /dev/null +++ b/app/src/http/app_shell.rs @@ -0,0 +1,60 @@ +//! The React app (sc-8900): Laravel serves the built frontend's files from `public/` as they are, and any other page +//! path gets the app's `index.html`, so client-side routes such as `/docspring/billing` load. A path that names a file +//! (`/favicon.ico`, `/logo.png`) and isn't there gets a 404 instead of the page: crawlers would take the HTML for the +//! file, and Cloudflare caches by extension for hours. So does anything under `/api/`, and anything but GET or HEAD. + +use axum::http::{Method, Uri}; + +use super::hosts::{Host, HostUrls}; + +/// Whether the path's last segment names a file (`logo.png`), other than an HTML page. +#[must_use] +pub fn names_a_file(path: &str) -> bool { + path.rsplit('/') + .next() + .and_then(|last| last.rsplit_once('.')) + .is_some_and(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && !ext.eq_ignore_ascii_case("html")) +} + +/// The web group's fallback. Only the app host serves the app's pages (or every host, when the hosts aren't +/// configured): another host's unknown paths, such as an MCP or API path that doesn't exist, are a 404, never the app. +pub async fn app_shell( + method: Method, + uri: Uri, + headers: axum::http::HeaderMap, + hosts: laravel::config::Section, +) -> laravel::Result { + let path = uri.path(); + if !(method == Method::GET || method == Method::HEAD) || names_a_file(path) || path.starts_with("/api/") { + return Err(laravel::abort(404)); + } + let configured = [&hosts.site, &hosts.app, &hosts.api, &hosts.mcp].iter().all(|u| u.is_some()); + let host = headers.get(axum::http::header::HOST).and_then(|h| h.to_str().ok()).unwrap_or_default(); + let host = host.rsplit_once(':').filter(|(_, p)| p.bytes().all(|b| b.is_ascii_digit())).map_or(host, |(h, _)| h); + if configured && hosts.classify(&host.to_ascii_lowercase()) != Some(Host::App) { + return Err(laravel::abort(404)); + } + // The page the security policy was built from at boot; read now only when there was none then (a dev server) + let html = match super::security::index_html() { + Some(html) => html.to_string(), + None => tokio::fs::read_to_string(laravel::config().app.public_path("index.html")) + .await + .map_err(|_| laravel::abort(404))?, + }; + Ok(laravel::http::Response::new(laravel::view::Html::raw(html)).with_header("cache-control", "no-cache")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_paths_are_told_apart_from_pages() { + for page in ["/", "/docspring/billing", "/account", "/docs.html", "/a.b/c"] { + assert!(!names_a_file(page), "{page}"); + } + for file in ["/favicon.ico", "/logo.png", "/assets/app-1234.js", "/robots.txt"] { + assert!(names_a_file(file), "{file}"); + } + } +} diff --git a/app/src/http/mod.rs b/app/src/http/mod.rs index e19f4abb..ad182af1 100644 --- a/app/src/http/mod.rs +++ b/app/src/http/mod.rs @@ -1,5 +1,6 @@ //! HTTP handlers. pub mod api; +pub mod app_shell; pub mod hosts; pub mod security; diff --git a/app/src/http/security.rs b/app/src/http/security.rs index fc2d11c6..e23a5285 100644 --- a/app/src/http/security.rs +++ b/app/src/http/security.rs @@ -25,6 +25,14 @@ const CLOUDFLARE_SCRIPT: &str = "https://static.cloudflareinsights.com"; const CLOUDFLARE_REPORT: &str = "https://cloudflareinsights.com"; static POLICY: OnceLock = OnceLock::new(); +/// The page the policy was built from, served as it was read (`app_shell`), so the hashes always match it. +static INDEX: OnceLock = OnceLock::new(); + +/// The app's `index.html` as it was at boot, when there was one. +#[must_use] +pub fn index_html() -> Option<&'static str> { + INDEX.get().map(String::as_str) +} /// `'sha256-…'` for each inline `").unwrap(); + } + app.get("/docspring/billing") + .await + .assert_ok() + .assert_see("VisualCI") + .assert_header("cache-control", "no-cache"); + app.get("/logo.png").await.assert_status(404); + app.get("/api/ui/nothing-here") + .header("accept", "application/json") + .await + .assert_status(404) + .assert_header_contains("content-type", "application/json"); + app.post("/docspring/billing").header("sec-fetch-site", "same-origin").await.assert_status(404); + if had.is_none() { + std::fs::remove_file(&index).unwrap(); + } +} + +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() +} + +/// Only the app host serves the app; another host's unknown paths are a 404, and every page is checked again. +#[laravel::test(app = hosts)] +async fn only_the_app_host_serves_the_app(app: Application) { + let index = laravel::config().app.public_path("index.html"); + std::fs::create_dir_all(index.parent().unwrap()).unwrap(); + let had = std::fs::read_to_string(&index).ok(); + if had.is_none() { + std::fs::write(&index, "VisualCI").unwrap(); + } + app.get("/acme").header("host", "app.visualci.test").await.assert_ok().assert_header("cache-control", "no-cache"); + app.get("/mcp/unknown").header("host", "mcp.visualci.test").await.assert_status(404); + app.get("/webhooks/unknown").header("host", "api.visualci.test").await.assert_status(404); + if had.is_none() { + std::fs::remove_file(&index).unwrap(); + } +}