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
163 changes: 163 additions & 0 deletions app/src/http/hosts.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
#[env("VISUALCI_APP_URL")]
pub app: Option<String>,
#[env("VISUALCI_API_URL")]
pub api: Option<String>,
#[env("VISUALCI_MCP_URL")]
pub mcp: Option<String>,
/// 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<String> {
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<Host> {
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`, `/<org>/...`) 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<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();
// `/` 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");
}
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);
}
}
1 change: 1 addition & 0 deletions app/src/http/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! HTTP handlers.

pub mod api;
pub mod hosts;
3 changes: 3 additions & 0 deletions app/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ pub fn configure() -> ApplicationBuilder {
.with_auth(|auth, _| {
auth.session::<models::Users>();
})
.with_middleware(|middleware, _| {
middleware.prepend(http::hosts::route_by_host);
})
.with_routing(|routing, _| {
routing.web(auth::routes).api(http::api::routes).health("/up");
})
Expand Down
27 changes: 27 additions & 0 deletions app/tests/hosts.rs
Original file line number Diff line number Diff line change
@@ -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();
}
Loading