Skip to content
Merged
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
141 changes: 131 additions & 10 deletions app/src/http/hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -106,27 +107,117 @@ 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, 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 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<()> {
let set = |u: &Option<String>| 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 = [
("VISUALCI_SITE_URL", &hosts.site),
("VISUALCI_APP_URL", &hosts.app),
("VISUALCI_API_URL", &hosts.api),
("VISUALCI_MCP_URL", &hosts.mcp),
];
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 (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) {
Some((_, other)) => problems.push(format!("{name} has the same host as {other} ({host})")),
None => seen.push((host, name)),
},
},
}
}
if problems.is_empty() {
return 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<HostUrls>, 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());
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!(
"<!doctype html><meta charset=\"utf-8\"><title>Not found · VisualCI</title>\
<p>There's nothing here. See <a href=\"{site}/\">VisualCI</a> or <a href=\"{site}/docs/\">the docs</a>.</p>\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!(
"<!doctype html><meta charset=\"utf-8\"><title>Not found · VisualCI</title>\
<p>There's nothing here. See <a href=\"{site}/\">VisualCI</a> or <a href=\"{site}/docs/\">the docs</a>.</p>\n"
);
Response::new(laravel::view::Html::raw(page)).with_status(404).with_header("cache-control", "no-store")
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -154,6 +245,36 @@ 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(), "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());
assert!(check(&urls(Some("https://api.visualci.com")), true).is_err());
}

#[test]
fn host_names_come_from_the_urls() {
assert_eq!(name_of("https://App.VisualCI.com/").as_deref(), Some("app.visualci.com"));
Expand Down
5 changes: 5 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,17 @@ pub fn configure() -> ApplicationBuilder {
config.section::<http::hosts::HostUrls>(),
config.app.env.is_production(),
)?;
http::hosts::check(config.section::<http::hosts::HostUrls>(), config.app.env.is_production())?;
Ok(())
})
.with_middleware(|middleware, _| {
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");
Expand Down
115 changes: 114 additions & 1 deletion app/tests/hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,119 @@ 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/");
// Any other host (a pod's own address) gets every path
// 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);
}
// 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"),
("S3_ENDPOINT", "http://127.0.0.1:59000"),
("S3_BUCKET", "visualci-test"),
("S3_ACCESS_KEY_ID", "visualci"),
("S3_SECRET_ACCESS_KEY", "visualci-dev-secret"),
])
}

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"),
("OAUTH_ISSUER", "https://mcp.visualci.test"),
("OAUTH_AUTHORIZATION_ENDPOINT", "https://app.visualci.test/oauth/authorize"),
])
.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");
}

/// 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);
}

/// 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");
}
Loading