Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(server): refuse an unreadable Origin header and origins with a bad port

James Dam90e539762f46
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 5bab5c633..3c998b8bb 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -598,6 +598,16 @@ pub(crate) fn origin_allowed(
}
}
+/// The request's `Origin` header, or "" when there is none. None when the
+/// header is present but not visible ASCII: such a request must be refused,
+/// not treated as one without an origin.
+pub(crate) fn request_origin(headers: &hyper::HeaderMap) -> Option<&str> {
+ match headers.get(hyper::header::ORIGIN) {
+ None => Some(""),
+ Some(value) => value.to_str().ok(),
+ }
+}
+
/// `/orchestrations` runs MCP tools without per-call approval, so it is only
/// served when the user opted in to server-side tool execution.
pub(crate) fn orchestrations_allowed(config: &ProxyConfig) -> bool {
@@ -839,12 +849,14 @@ async fn proxy_request(
let (parts, body) = req.into_parts();
- let origin_header = parts
- .headers
- .get(hyper::header::ORIGIN)
- .and_then(|v| v.to_str().ok())
- .unwrap_or("")
- .to_string();
+ let Some(origin_header) = request_origin(&parts.headers).map(str::to_string) else {
+ log::warn!("Rejected request with an Origin header that is not visible ASCII");
+ return Ok(Response::builder()
+ .status(StatusCode::FORBIDDEN)
+ .header("Vary", "Origin")
+ .body(full("Origin not allowed"))
+ .unwrap());
+ };
let host_header = parts
.headers
diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rs
index 799451ecd..1b946f800 100644
--- a/src-tauri/src/core/server/tests.rs
+++ b/src-tauri/src/core/server/tests.rs
@@ -1234,6 +1234,25 @@ mod server_tests {
vec![hosts.iter().map(|h| h.to_string()).collect()]
}
+ #[test]
+ fn request_origin_refuses_a_non_ascii_origin_header() {
+ let mut headers = hyper::HeaderMap::new();
+ assert_eq!(proxy::request_origin(&headers), Some(""));
+ headers.insert(
+ hyper::header::ORIGIN,
+ hyper::header::HeaderValue::from_static("http://localhost:3000"),
+ );
+ assert_eq!(
+ proxy::request_origin(&headers),
+ Some("http://localhost:3000")
+ );
+ headers.insert(
+ hyper::header::ORIGIN,
+ hyper::header::HeaderValue::from_bytes(b"http://\xffevil.com").unwrap(),
+ );
+ assert_eq!(proxy::request_origin(&headers), None);
+ }
+
#[test]
fn origin_allowed_absent_origin_always_passes() {
assert!(proxy::origin_allowed("", "127.0.0.1:1337", &trusted(&[]), true));
diff --git a/src-tauri/utils/src/http.rs b/src-tauri/utils/src/http.rs
index 36d5c59f3..83fdb1c73 100644
--- a/src-tauri/utils/src/http.rs
+++ b/src-tauri/utils/src/http.rs
@@ -85,13 +85,49 @@ fn host_in_trusted_list(host: &str, trusted_hosts: &[Vec<String>]) -> bool {
})
}
+/// Whether `port` is a decimal port number in 1-65535.
+fn is_valid_port(port: &str) -> bool {
+ !port.is_empty()
+ && port.bytes().all(|b| b.is_ascii_digit())
+ && matches!(port.parse::<u32>(), Ok(1..=65535))
+}
+
+/// Whether `authority` is a host with an optional valid port: `host`,
+/// `host:port`, `[v6]` or `[v6]:port`.
+fn is_valid_authority(authority: &str) -> bool {
+ let port = if let Some(rest) = authority.strip_prefix('[') {
+ let Some((addr, after)) = rest.split_once(']') else {
+ return false;
+ };
+ if addr.is_empty() {
+ return false;
+ }
+ if after.is_empty() {
+ return true;
+ }
+ match after.strip_prefix(':') {
+ Some(port) => port,
+ None => return false,
+ }
+ } else {
+ match authority.split_once(':') {
+ None => return !authority.is_empty(),
+ Some((host, port)) if !host.is_empty() => port,
+ Some(_) => return false,
+ }
+ };
+ is_valid_port(port)
+}
+
/// Splits a serialized origin into lowercase `(scheme, authority)`. Returns
-/// None for `null`, anything with a path/query/userinfo, or garbage.
+/// None for `null`, anything with a path/query/userinfo, a port that is not a
+/// number in 1-65535, or garbage.
fn parse_origin(origin: &str) -> Option<(String, String)> {
let (scheme, authority) = origin.trim().split_once("://")?;
if scheme.is_empty()
|| authority.is_empty()
|| authority.contains(['/', '?', '#', '@', ' ', '\\'])
+ || !is_valid_authority(authority)
{
return None;
}
@@ -230,11 +266,36 @@ mod tests {
"ftp://localhost",
"chrome-extension://abcdef",
"",
+ "http://localhost:evil",
+ "http://localhost:",
+ "http://localhost:0",
+ "http://localhost:65536",
+ "http://localhost:+80",
+ "http://localhost:80:80",
+ "http://[::1]:evil",
+ "http://[::1]x",
+ "http://[::1",
+ "http://:1337",
] {
assert!(!is_trusted_origin(o, "127.0.0.1:1337", &t), "{o}");
}
}
+ #[test]
+ fn origin_port_must_be_a_valid_number() {
+ let t = none();
+ assert!(is_trusted_origin("http://localhost:65535", "127.0.0.1:1337", &t));
+ assert!(is_trusted_origin("http://[::1]", "127.0.0.1:1337", &t));
+ // The same-origin case cannot be met with a non-numeric port either.
+ assert!(!is_same_or_app_origin("http://evil:x", "evil:x"));
+ let listed = vec![vec!["myapp.local".to_string()]];
+ assert!(!is_trusted_origin(
+ "https://myapp.local:evil",
+ "127.0.0.1:1337",
+ &listed
+ ));
+ }
+
// A page on another LAN machine must not get credentialed CORS just because
// its address is private: the Host check accepts it, the origin check does not.
#[test]