Skip to content

Commit b33685f

Browse files
committed
Routing by hostname, hardened (sc-8900, review of #53): production refuses to boot without all four host URLs; the host check judges a normalised path (percent-decoded, repeated slashes collapsed, lowercased), so /%61pi/v1, //api/v1 and /API/v1 can't reach the API through the app host; tests
1 parent a61f6ff commit b33685f

3 files changed

Lines changed: 84 additions & 1 deletion

File tree

‎app/src/http/hosts.rs‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,64 @@ pub fn serves(host: Host, path: &str) -> bool {
106106
}
107107
}
108108

109+
/// The path the host check judges: percent-decoded, repeated slashes collapsed and lowercased, so `/%61pi/v1`,
110+
/// `//api/v1` and `/API/v1` are all `/api/v1` and can't reach another host's routes through a lenient router.
111+
#[must_use]
112+
pub fn normalized(path: &str) -> String {
113+
let bytes = path.as_bytes();
114+
let mut decoded = Vec::with_capacity(bytes.len());
115+
let mut i = 0;
116+
while i < bytes.len() {
117+
if bytes[i] == b'%'
118+
&& i + 2 < bytes.len()
119+
&& let Ok(byte) = u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("zz"), 16)
120+
{
121+
decoded.push(byte);
122+
i += 3;
123+
} else {
124+
decoded.push(bytes[i]);
125+
i += 1;
126+
}
127+
}
128+
let text = String::from_utf8_lossy(&decoded).to_ascii_lowercase();
129+
let mut out = String::with_capacity(text.len());
130+
for c in text.chars() {
131+
if !(c == '/' && out.ends_with('/')) {
132+
out.push(c);
133+
}
134+
}
135+
if out.is_empty() { "/".to_string() } else { out }
136+
}
137+
138+
/// In production, all four host URLs must be set: without them every host would serve every path. Called at boot.
139+
///
140+
/// # Errors
141+
/// In production, when any of them is missing.
142+
pub fn check(hosts: &HostUrls, production: bool) -> laravel::Result<()> {
143+
let missing: Vec<&str> = [
144+
("VISUALCI_SITE_URL", &hosts.site),
145+
("VISUALCI_APP_URL", &hosts.app),
146+
("VISUALCI_API_URL", &hosts.api),
147+
("VISUALCI_MCP_URL", &hosts.mcp),
148+
]
149+
.into_iter()
150+
.filter(|(_, url)| url.as_deref().is_none_or(|u| u.trim().is_empty()))
151+
.map(|(name, _)| name)
152+
.collect();
153+
if production && !missing.is_empty() {
154+
return Err(laravel::Error::msg(format!(
155+
"routing by hostname needs every host's URL in production: {} not set",
156+
missing.join(", ")
157+
)));
158+
}
159+
Ok(())
160+
}
161+
109162
/// Global middleware: each host serves only its own paths.
110163
#[middleware]
111164
pub async fn route_by_host(hosts: Section<HostUrls>, request: Request, next: Next) -> Response {
112165
let Some(here) = hosts.classify(&request.host().to_ascii_lowercase()) else { return next.run(request).await };
113-
let path = request.path().to_string();
166+
let path = normalized(request.path());
114167
// `/` on the app is the list of your organizations; without a session, the landing page
115168
if here == Host::App && path == "/" && request.cookie(&hosts.session_cookie).is_none() {
116169
return Response::new(laravel::http::Redirect::to(format!("{}/", hosts.site())).status(307))
@@ -154,6 +207,31 @@ mod tests {
154207
assert!(!serves(Host::Mcp, "/") && !serves(Host::Mcp, "/api/v1/builds"));
155208
}
156209

210+
#[test]
211+
fn odd_paths_are_judged_as_what_they_reach() {
212+
for odd in ["/%61pi/v1/builds", "//api/v1/builds", "/API/v1", "/api//v1/x", "/%2Fapi/v1"] {
213+
let path = normalized(odd);
214+
assert!(!serves(Host::App, &path), "{odd} ({path}) on the app host");
215+
assert!(serves(Host::Api, &path), "{odd} ({path}) on the API host");
216+
}
217+
assert_eq!(normalized(""), "/");
218+
assert_eq!(normalized("/a%zz"), "/a%zz", "an invalid escape stays as it is");
219+
}
220+
221+
#[test]
222+
fn production_needs_all_four_urls() {
223+
let urls = |app: Option<&str>| HostUrls {
224+
site: Some("https://visualci.com".into()),
225+
app: app.map(str::to_string),
226+
api: Some("https://api.visualci.com".into()),
227+
mcp: Some("https://mcp.visualci.com".into()),
228+
session_cookie: "visualci_session".into(),
229+
};
230+
assert!(check(&urls(None), true).is_err());
231+
assert!(check(&urls(None), false).is_ok(), "development serves every path");
232+
assert!(check(&urls(Some("https://app.visualci.com")), true).is_ok());
233+
}
234+
157235
#[test]
158236
fn host_names_come_from_the_urls() {
159237
assert_eq!(name_of("https://App.VisualCI.com/").as_deref(), Some("app.visualci.com"));

‎app/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ pub fn configure() -> ApplicationBuilder {
3636
config.section::<http::hosts::HostUrls>(),
3737
config.app.env.is_production(),
3838
)?;
39+
http::hosts::check(config.section::<http::hosts::HostUrls>(), config.app.env.is_production())?;
3940
Ok(())
4041
})
4142
.with_middleware(|middleware, _| {

‎app/tests/hosts.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ async fn each_host_serves_only_its_own_paths(app: Application) {
2222
app.get("/up").header("host", "mcp.visualci.test").await.assert_ok();
2323
// The app's front page sends a visitor without a session to the landing page
2424
app.get("/").header("host", "app.visualci.test").await.assert_redirect_to("https://visualci.test/");
25+
// Encoded, doubled or upper-case paths can't reach the API through the app host
26+
for odd in ["/%61pi/v1/version", "//api/v1/version", "/API/v1/version"] {
27+
app.get(odd).header("host", "app.visualci.test").await.assert_status(404);
28+
}
2529
// Any other host (a pod's own address) gets every path
2630
app.get("/api/v1/version").header("host", "10.0.0.7").await.assert_ok();
2731
}

0 commit comments

Comments
 (0)