Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
60 changes: 60 additions & 0 deletions app/src/http/app_shell.rs
Original file line number Diff line number Diff line change
@@ -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<HostUrls>,
) -> laravel::Result<laravel::http::Response> {
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}");
}
}
}
1 change: 1 addition & 0 deletions app/src/http/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! HTTP handlers.

pub mod api;
pub mod app_shell;
pub mod hosts;
pub mod security;
26 changes: 25 additions & 1 deletion app/src/http/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ const CLOUDFLARE_SCRIPT: &str = "https://static.cloudflareinsights.com";
const CLOUDFLARE_REPORT: &str = "https://cloudflareinsights.com";

static POLICY: OnceLock<HeaderValue> = 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<String> = 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 `<script>` (one without `src`) in `html`.
#[must_use]
Expand Down Expand Up @@ -102,7 +110,11 @@ pub fn policy_for(page: &std::path::Path, storage: Option<&str>) -> Result<Strin
/// In production, when the page is missing or has no inline scripts to allow; elsewhere that's only logged.
pub fn check(config: &laravel::config::Config, production: bool) -> laravel::Result<()> {
let storage = config.section::<Frontend>().storage_endpoint.as_deref().and_then(origin);
let value = match policy_for(&config.app.public_path("index.html"), storage.as_deref()) {
let page = config.app.public_path("index.html");
if let Ok(html) = std::fs::read_to_string(&page) {
let _ = INDEX.set(html);
}
let value = match policy_for(&page, storage.as_deref()) {
Ok(p) => p,
Err(message) if production => return Err(laravel::Error::msg(message)),
Err(message) => {
Expand All @@ -118,6 +130,7 @@ pub fn check(config: &laravel::config::Config, production: bool) -> laravel::Res
#[middleware]
pub async fn security_headers(request: Request, next: Next) -> Response {
let gallery = request.path().starts_with("/g/");
let assets = request.path().starts_with("/assets/");
let mut response = next.run(request).await;
let h = response.headers_mut();
h.remove("x-powered-by");
Expand All @@ -129,6 +142,17 @@ pub async fn security_headers(request: Request, next: Next) -> Response {
h.entry(header::REFERRER_POLICY).or_insert(HeaderValue::from_static("strict-origin-when-cross-origin"));
// Laravel's own default is SAMEORIGIN; VisualCI's pages are never framed (the policy's `frame-ancestors 'none'`)
h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
// A page is always checked again (a stale one after a deploy would load assets that are gone); the built assets,
// named by their content's hash, never change
let html = h.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).is_some_and(|v| v.starts_with("text/html"));
if html {
h.entry(header::CACHE_CONTROL).or_insert(HeaderValue::from_static("no-cache"));
} else if assets && response.status().is_success() {
response
.headers_mut()
.insert(header::CACHE_CONTROL, HeaderValue::from_static("public, max-age=31536000, immutable"));
}
let h = response.headers_mut();
let policy = POLICY.get().cloned().unwrap_or(HeaderValue::from_static("default-src 'self'"));
h.entry(header::CONTENT_SECURITY_POLICY).or_insert(policy);
response
Expand Down
56 changes: 56 additions & 0 deletions app/tests/app_shell.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//! The React app's pages: any page path gets public/index.html; a missing file, an API path, or a POST doesn't.

use laravel::testing::prelude::*;

#[laravel::test]
async fn client_side_routes_get_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, "<!doctype html><title>VisualCI</title><script>theme()</script>").unwrap();
}
app.get("/docspring/billing")
.await
.assert_ok()
.assert_see("<title>VisualCI</title>")
.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, "<!doctype html><title>VisualCI</title><script>theme()</script>").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();
}
}
Loading