Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(server): reject untrusted origins on API requests
James Dambc0c9dae8269
diff --git a/src-tauri/src/core/server/commands.rs b/src-tauri/src/core/server/commands.rsindex d0aef662d..d7f3bb05f 100644--- a/src-tauri/src/core/server/commands.rs+++ b/src-tauri/src/core/server/commands.rs@@ -17,6 +17,8 @@ pub struct StartServerConfig {pub trusted_hosts: Vec<String>,pub proxy_timeout: u64,pub enable_server_tool_execution: Option<bool>,+ /// "Allow cross-origin requests" toggle. Absent means on, the UI default.+ pub cors_enabled: Option<bool>,}#[tauri::command]@@ -33,6 +35,7 @@ pub async fn start_server<R: Runtime>(trusted_hosts,proxy_timeout,enable_server_tool_execution,+ cors_enabled,} = config;let server_handle = state.server_handle.clone();let llama_state: State<Arc<LlamacppState>> = app_handle.state();@@ -67,6 +70,7 @@ pub async fn start_server<R: Runtime>(.to_string_lossy().into_owned(),enable_server_tool_execution.unwrap_or(false),+ cors_enabled.unwrap_or(true),).await.map_err(|e| e.to_string())?;diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rsindex 58143ac05..5bab5c633 100644--- a/src-tauri/src/core/server/proxy.rs+++ b/src-tauri/src/core/server/proxy.rs@@ -7,7 +7,9 @@ use hyper::server::conn::http1;use hyper::service::service_fn;use hyper::{Request, Response, StatusCode};use hyper_util::rt::TokioIo;-use jan_utils::{extract_host_from_origin, is_cors_header, is_valid_host, remove_prefix};+use jan_utils::{+ is_cors_header, is_same_or_app_origin, is_trusted_origin, is_valid_host, remove_prefix,+};use reqwest::Client;use serde_json;use std::collections::HashMap;@@ -561,6 +563,45 @@ pub struct ProxyConfig {pub host: String,pub port: u16,pub enable_server_tool_execution: bool,+ /// "Allow cross-origin requests" setting. When off, only the server's own+ /// pages and the app webview may call it from a browser context.+ pub cors_enabled: bool,+}++/// Whether a request carrying this `Origin` may proceed. Requests without an+/// Origin (curl, SDKs, CLI tools, LAN clients) always may; browser requests+/// must come from a trusted origin (see `jan_utils::is_trusted_origin`).+///+/// Runs on every non-preflight request, before auth and body parsing, because+/// a browser sends "simple" cross-origin POSTs (e.g. `text/plain`) without a+/// preflight, so CORS headers alone do not stop the request from executing.+pub(crate) fn origin_allowed(+ origin: &str,+ host_header: &str,+ trusted_hosts: &[Vec<String>],+ cors_enabled: bool,+) -> bool {+ if origin.is_empty() {+ return true;+ }+ // Same-origin trust relies on the Host header naming this server, so only+ // a Host that passes validation counts.+ let host = if is_valid_host(host_header, trusted_hosts) {+ host_header+ } else {+ ""+ };+ if cors_enabled {+ is_trusted_origin(origin, host, trusted_hosts)+ } else {+ is_same_or_app_origin(origin, host)+ }+}++/// `/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 {+ config.enable_server_tool_execution}/// Determines the final destination path based on the original request path@@ -781,8 +822,7 @@ async fn proxy_request();if !origin.is_empty() {- let origin_host = extract_host_from_origin(origin);- if is_valid_host(&origin_host, &config.trusted_hosts) {+ if origin_allowed(origin, host, &config.trusted_hosts, config.cors_enabled) {response = response.header("Access-Control-Allow-Origin", origin).header("Access-Control-Allow-Credentials", "true");@@ -813,6 +853,20 @@ async fn proxy_request(.unwrap_or("").to_string();+ if !origin_allowed(+ &origin_header,+ &host_header,+ &config.trusted_hosts,+ config.cors_enabled,+ ) {+ log::warn!("Rejected request from untrusted origin '{origin_header}'");+ return Ok(Response::builder()+ .status(StatusCode::FORBIDDEN)+ .header("Vary", "Origin")+ .body(full("Origin not allowed"))+ .unwrap());+ }+let original_path = parts.uri.path();let headers = parts.headers.clone();@@ -1126,6 +1180,21 @@ async fn proxy_request("Handling POST request to {destination_path} for assistant tool orchestration");+ if !orchestrations_allowed(&config) {+ let mut error_response = Response::builder().status(StatusCode::FORBIDDEN);+ error_response = add_cors_headers_with_host_and_origin(+ error_response,+ &host_header,+ &origin_header,+ &config.trusted_hosts,+ );+ return Ok(error_response+ .body(full(+ "/orchestrations requires server-side tool execution to be enabled in Settings > Local API Server",+ ))+ .unwrap());+ }+let body_bytes = match body.collect().await {Ok(c) => c.to_bytes(),Err(_) => {@@ -2345,18 +2414,20 @@ fn map_bind_error(pub(crate) fn add_cors_headers_with_host_and_origin(builder: hyper::http::response::Builder,- _host: &str,+ host: &str,origin: &str,trusted_hosts: &[Vec<String>],) -> hyper::http::response::Builder {let mut builder = builder;- let origin_trusted = if !origin.is_empty() {- let origin_host = extract_host_from_origin(origin);- is_valid_host(&origin_host, trusted_hosts)- } else {- false- };+ // Requests from an origin `origin_allowed` refuses never reach a handler,+ // so this only decides whether to reflect an already-admitted origin.+ let origin_trusted = !origin.is_empty()+ && is_trusted_origin(+ origin,+ if is_valid_host(host, trusted_hosts) { host } else { "" },+ trusted_hosts,+ );builder = builder.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")@@ -2399,6 +2470,7 @@ pub async fn start_server(mcp_settings: Arc<Mutex<McpSettings>>,jan_data_folder: String,enable_server_tool_execution: bool,+ cors_enabled: bool,) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {start_server_internal(server_handle,@@ -2416,6 +2488,7 @@ pub async fn start_server(mcp_settings,jan_data_folder,enable_server_tool_execution,+ cors_enabled,).await}@@ -2437,6 +2510,7 @@ async fn start_server_internal(mcp_settings: Arc<Mutex<McpSettings>>,jan_data_folder: String,enable_server_tool_execution: bool,+ cors_enabled: bool,) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {let mut handle_guard = server_handle.lock().await;if handle_guard.is_some() {@@ -2463,6 +2537,7 @@ async fn start_server_internal(host: host.clone(),port,enable_server_tool_execution,+ cors_enabled,};let client = Client::builder()diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rsindex fc890b20f..799451ecd 100644--- a/src-tauri/src/core/server/tests.rs+++ b/src-tauri/src/core/server/tests.rs@@ -70,6 +70,7 @@ mod server_tests {host: "localhost".to_string(),port: 1337,enable_server_tool_execution: false,+ cors_enabled: true,};assert_eq!(config.prefix, "/v1");assert_eq!(config.proxy_api_key, "test-key");@@ -87,6 +88,7 @@ mod server_tests {host: "127.0.0.1".to_string(),port: 8080,enable_server_tool_execution: false,+ cors_enabled: true,};assert_eq!(config.prefix, "");assert_eq!(config.proxy_api_key, "");@@ -1109,6 +1111,7 @@ mod server_tests {host: "h".to_string(),port: 1,enable_server_tool_execution: true,+ cors_enabled: true,};let cloned = cfg.clone();assert_eq!(cloned.prefix, "/p");@@ -1224,4 +1227,173 @@ mod server_tests {proxy::strip_billing_header_in_body(&mut body);assert_eq!(body["messages"][0]["content"][0]["text"], json!(PROMPT));}++ // ---- Origin gate and /orchestrations opt-in, against a running server ----++ fn trusted(hosts: &[&str]) -> Vec<Vec<String>> {+ vec![hosts.iter().map(|h| h.to_string()).collect()]+ }++ #[test]+ fn origin_allowed_absent_origin_always_passes() {+ assert!(proxy::origin_allowed("", "127.0.0.1:1337", &trusted(&[]), true));+ assert!(proxy::origin_allowed("", "192.168.1.10:1337", &trusted(&[]), false));+ }++ #[test]+ fn origin_allowed_matrix() {+ let t = trusted(&[]);+ let h = "127.0.0.1:1337";+ assert!(proxy::origin_allowed("http://localhost:3000", h, &t, true));+ assert!(proxy::origin_allowed("tauri://localhost", h, &t, true));+ assert!(!proxy::origin_allowed("https://evil.com", h, &t, true));+ assert!(!proxy::origin_allowed("null", h, &t, true));+ // Private-IP pages on the LAN are not trusted unless listed.+ assert!(!proxy::origin_allowed("http://192.168.1.20:3000", h, &t, true));+ assert!(proxy::origin_allowed(+ "http://192.168.1.20:3000",+ h,+ &trusted(&["192.168.1.20"]),+ true+ ));+ // CORS off: only the app webview and same-origin pages.+ assert!(!proxy::origin_allowed("http://localhost:3000", h, &t, false));+ assert!(proxy::origin_allowed("tauri://localhost", h, &t, false));+ assert!(proxy::origin_allowed("http://127.0.0.1:1337", h, &t, false));+ // Same-origin needs a valid Host: a rebinding hostname does not count.+ assert!(!proxy::origin_allowed(+ "http://evil.com:1337",+ "evil.com:1337",+ &t,+ true+ ));+ }++ #[test]+ fn orchestrations_follow_tool_execution_opt_in() {+ let mut cfg = proxy::ProxyConfig {+ prefix: "/v1".to_string(),+ proxy_api_key: String::new(),+ trusted_hosts: vec![vec![]],+ host: "127.0.0.1".to_string(),+ port: 1337,+ enable_server_tool_execution: false,+ cors_enabled: true,+ };+ assert!(!proxy::orchestrations_allowed(&cfg));+ cfg.enable_server_tool_execution = true;+ assert!(proxy::orchestrations_allowed(&cfg));+ }++ async fn start_test_server(+ enable_server_tool_execution: bool,+ cors_enabled: bool,+ ) -> (u16, std::sync::Arc<tokio::sync::Mutex<Option<crate::core::state::ServerHandle>>>) {+ use std::collections::HashMap;+ use std::sync::Arc;+ use tokio::sync::Mutex;++ let port = std::net::TcpListener::bind("127.0.0.1:0")+ .unwrap()+ .local_addr()+ .unwrap()+ .port();+ let handle = Arc::new(Mutex::new(None));+ let data = std::env::temp_dir().to_string_lossy().into_owned();+ proxy::start_server(+ handle.clone(),+ Arc::new(tauri_plugin_llamacpp::state::LlamacppState::default()),+ Arc::new(Mutex::new(HashMap::new())),+ "127.0.0.1".to_string(),+ port,+ "/v1".to_string(),+ String::new(),+ vec![vec![]],+ 30,+ Arc::new(Mutex::new(HashMap::new())),+ Arc::new(Mutex::new(HashMap::new())),+ Arc::new(Mutex::new(HashMap::new())),+ Arc::new(Mutex::new(crate::core::mcp::models::McpSettings::default())),+ data,+ enable_server_tool_execution,+ cors_enabled,+ )+ .await+ .expect("server starts");+ (port, handle)+ }++ async fn post(+ port: u16,+ path: &str,+ origin: Option<&str>,+ content_type: &str,+ ) -> reqwest::StatusCode {+ let mut req = reqwest::Client::new()+ .post(format!("http://127.0.0.1:{port}/v1{path}"))+ .header("Content-Type", content_type)+ .body(r#"{"model":"nope","messages":[{"role":"user","content":"hi"}]}"#);+ if let Some(o) = origin {+ req = req.header("Origin", o);+ }+ req.send().await.expect("request sent").status()+ }++ #[tokio::test]+ async fn untrusted_origin_post_is_refused_before_handlers() {+ let (port, handle) = start_test_server(false, true).await;++ // A cross-site "simple" request (no preflight) is refused.+ for path in ["/chat/completions", "/messages", "/orchestrations", "/models"] {+ assert_eq!(+ post(port, path, Some("https://evil.example"), "text/plain").await,+ reqwest::StatusCode::FORBIDDEN,+ "{path}"+ );+ }+ assert_eq!(+ post(port, "/chat/completions", Some("http://192.168.1.20:3000"), "text/plain").await,+ reqwest::StatusCode::FORBIDDEN+ );+ // No Origin (curl, SDKs) and loopback origins reach the handler: no+ // model is loaded, so the handler answers, just not with the gate's 403.+ for origin in [None, Some("http://localhost:3000")] {+ let status = post(port, "/chat/completions", origin, "application/json").await;+ assert_ne!(status, reqwest::StatusCode::FORBIDDEN, "{origin:?}");+ }++ proxy::stop_server(handle).await.unwrap();+ }++ #[tokio::test]+ async fn orchestrations_refused_without_opt_in() {+ let (port, handle) = start_test_server(false, true).await;+ assert_eq!(+ post(port, "/orchestrations", None, "application/json").await,+ reqwest::StatusCode::FORBIDDEN+ );+ proxy::stop_server(handle).await.unwrap();++ let (port, handle) = start_test_server(true, true).await;+ assert_ne!(+ post(port, "/orchestrations", None, "application/json").await,+ reqwest::StatusCode::FORBIDDEN+ );+ proxy::stop_server(handle).await.unwrap();+ }++ #[tokio::test]+ async fn cors_toggle_off_refuses_loopback_pages() {+ let (port, handle) = start_test_server(false, false).await;+ assert_eq!(+ post(port, "/chat/completions", Some("http://localhost:3000"), "application/json")+ .await,+ reqwest::StatusCode::FORBIDDEN+ );+ assert_ne!(+ post(port, "/chat/completions", None, "application/json").await,+ reqwest::StatusCode::FORBIDDEN+ );+ proxy::stop_server(handle).await.unwrap();+ }}diff --git a/src-tauri/static/openapi.json b/src-tauri/static/openapi.jsonindex b0660b55a..0cf7cd275 100644--- a/src-tauri/static/openapi.json+++ b/src-tauri/static/openapi.json@@ -117,7 +117,7 @@"/orchestrations": {"post": {"summary": "Run headless assistant orchestration with tool execution",- "description": "Optionally loads assistant settings by `assistant_id`, executes server-side MCP tool calls, and continues generation until the model returns a final response.",+ "description": "Optionally loads assistant settings by `assistant_id`, executes server-side MCP tool calls, and continues generation until the model returns a final response. Returns 403 unless server-side tool execution is enabled in Settings > Local API Server.","operationId": "createOrchestration","tags": ["Inference"],"requestBody": {diff --git a/src-tauri/utils/src/http.rs b/src-tauri/utils/src/http.rsindex 72d642ec5..36d5c59f3 100644--- a/src-tauri/utils/src/http.rs+++ b/src-tauri/utils/src/http.rs@@ -25,14 +25,7 @@ pub fn is_valid_host(host: &str, trusted_hosts: &[Vec<String>]) -> bool {return false;}- let host_without_port = if host.starts_with('[') {- host.split(']')- .next()- .unwrap_or(host)- .trim_start_matches('[')- } else {- host.split(':').next().unwrap_or(host)- };+ let host_without_port = host_without_port(host);let default_valid_hosts = ["localhost", "127.0.0.1", "0.0.0.0", "host.docker.internal"];if default_valid_hosts@@ -58,6 +51,25 @@ pub fn is_valid_host(host: &str, trusted_hosts: &[Vec<String>]) -> bool {}}+ host_in_trusted_list(host, trusted_hosts)+}++/// Strips the port (and IPv6 brackets) from a `host[:port]` authority.+fn host_without_port(host: &str) -> &str {+ if host.starts_with('[') {+ host.split(']')+ .next()+ .unwrap_or(host)+ .trim_start_matches('[')+ } else {+ host.split(':').next().unwrap_or(host)+ }+}++/// Whether `host` (with optional port) matches an entry the user put in the+/// Trusted Hosts list. Entries match on hostname; ports are ignored.+fn host_in_trusted_list(host: &str, trusted_hosts: &[Vec<String>]) -> bool {+ let host_without_port = host_without_port(host);trusted_hosts.iter().flatten().any(|valid| {let host_lower = host.to_lowercase();let valid_lower = valid.to_lowercase();@@ -66,20 +78,73 @@ pub fn is_valid_host(host: &str, trusted_hosts: &[Vec<String>]) -> bool {return true;}- let valid_without_port = if valid.starts_with('[') {- valid- .split(']')- .next()- .unwrap_or(valid)- .trim_start_matches('[')- } else {- valid.split(':').next().unwrap_or(valid)- };+ let valid_without_port = self::host_without_port(valid);- host_without_port.to_lowercase() == valid_without_port.to_lowercase()+ !valid_without_port.is_empty()+ && host_without_port.to_lowercase() == valid_without_port.to_lowercase()})}+/// Splits a serialized origin into lowercase `(scheme, authority)`. Returns+/// None for `null`, anything with a path/query/userinfo, 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(['/', '?', '#', '@', ' ', '\\'])+ {+ return None;+ }+ Some((scheme.to_ascii_lowercase(), authority.to_ascii_lowercase()))+}++/// The origins that are trusted even with cross-origin requests turned off:+/// the app's own webview (`tauri://localhost`, `http(s)://tauri.localhost`)+/// and a page served by this server itself, i.e. an `http(s)` origin whose+/// authority equals `host_header`. Callers must pass a `host_header` that has+/// already been validated (or "" to skip the same-origin case), otherwise a+/// rebinding hostname would match itself.+pub fn is_same_or_app_origin(origin: &str, host_header: &str) -> bool {+ let Some((scheme, authority)) = parse_origin(origin) else {+ return false;+ };+ let is_http = scheme == "http" || scheme == "https";+ if (scheme == "tauri" && authority == "localhost") || (is_http && authority == "tauri.localhost")+ {+ return true;+ }+ is_http && !host_header.is_empty() && authority == host_header.to_ascii_lowercase()+}++/// Decides whether a browser `Origin` may call the local API server.+///+/// Unlike `is_valid_host` (which validates the `Host` header and accepts any+/// private-range IP so LAN clients can reach a 0.0.0.0 bind), an origin is+/// the page that issued the request, so only these are trusted:+/// - everything `is_same_or_app_origin` accepts;+/// - loopback pages: `http(s)://localhost`, `127.0.0.1`, `[::1]` on any port;+/// - a host the user listed in Trusted Hosts (any scheme, so a browser+/// extension id can be listed), or `*` there.+///+/// A private-range IP origin (another machine on the LAN) is NOT trusted+/// unless listed. `null` and anything malformed are untrusted.+pub fn is_trusted_origin(origin: &str, host_header: &str, trusted_hosts: &[Vec<String>]) -> bool {+ if trusted_hosts.iter().any(|hosts| hosts.iter().any(|h| h == "*")) {+ return true;+ }+ if is_same_or_app_origin(origin, host_header) {+ return true;+ }+ let Some((scheme, authority)) = parse_origin(origin) else {+ return false;+ };+ let is_http = scheme == "http" || scheme == "https";+ if is_http && matches!(host_without_port(&authority), "localhost" | "127.0.0.1" | "::1") {+ return true;+ }+ host_in_trusted_list(&authority, trusted_hosts)+}+#[cfg(test)]mod tests {use super::*;@@ -128,4 +193,88 @@ mod tests {// A public IP literal is NOT auto-trusted.assert!(!is_valid_host("8.8.8.8:1337", &trusted));}++ fn none() -> Vec<Vec<String>> {+ vec![vec![]]+ }++ #[test]+ fn origin_loopback_and_app_origins_trusted() {+ let t = none();+ for o in [+ "http://localhost:3000",+ "https://localhost",+ "http://127.0.0.1:1337",+ "http://[::1]:8080",+ "HTTP://LOCALHOST:5173",+ "tauri://localhost",+ "http://tauri.localhost",+ "https://tauri.localhost",+ ] {+ assert!(is_trusted_origin(o, "127.0.0.1:1337", &t), "{o}");+ }+ }++ #[test]+ fn origin_foreign_sites_untrusted() {+ let t = none();+ for o in [+ "https://evil.com",+ "http://localhost.evil.com",+ "http://127.0.0.1.evil.com",+ "http://evil.com/localhost",+ "http://user@localhost",+ "null",+ "file://",+ "tauri://evil",+ "ftp://localhost",+ "chrome-extension://abcdef",+ "",+ ] {+ assert!(!is_trusted_origin(o, "127.0.0.1:1337", &t), "{o}");+ }+ }++ // 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]+ fn origin_private_ip_untrusted_unless_listed() {+ let t = none();+ assert!(is_valid_host("192.168.1.20:3000", &t));+ assert!(!is_trusted_origin("http://192.168.1.20:3000", "127.0.0.1:1337", &t));+ assert!(!is_trusted_origin("http://10.0.0.5", "127.0.0.1:1337", &t));++ let listed = vec![vec!["192.168.1.20".to_string()]];+ assert!(is_trusted_origin("http://192.168.1.20:3000", "127.0.0.1:1337", &listed));+ assert!(!is_trusted_origin("http://192.168.1.21:3000", "127.0.0.1:1337", &listed));+ }++ #[test]+ fn origin_same_as_host_trusted() {+ let t = none();+ // API docs page opened over the LAN.+ assert!(is_trusted_origin("http://192.168.1.10:1337", "192.168.1.10:1337", &t));+ // Same IP, different port: a different site.+ assert!(!is_trusted_origin("http://192.168.1.10:8080", "192.168.1.10:1337", &t));+ }++ #[test]+ fn same_or_app_origin_only() {+ assert!(is_same_or_app_origin("tauri://localhost", ""));+ assert!(is_same_or_app_origin("http://tauri.localhost", ""));+ assert!(is_same_or_app_origin("http://127.0.0.1:1337", "127.0.0.1:1337"));+ assert!(!is_same_or_app_origin("http://localhost:3000", "127.0.0.1:1337"));+ assert!(!is_same_or_app_origin("http://127.0.0.1:1337", ""));+ }++ #[test]+ fn origin_listed_hosts_and_wildcard() {+ let listed = vec![vec!["myapp.local".to_string(), "abcdef".to_string()]];+ assert!(is_trusted_origin("https://myapp.local:8443", "127.0.0.1:1337", &listed));+ assert!(is_trusted_origin("chrome-extension://abcdef", "127.0.0.1:1337", &listed));+ assert!(!is_trusted_origin("https://other.local", "127.0.0.1:1337", &listed));++ let wildcard = vec![vec!["*".to_string()]];+ assert!(is_trusted_origin("https://evil.com", "127.0.0.1:1337", &wildcard));+ }}diff --git a/web-app/src/lib/service.ts b/web-app/src/lib/service.tsindex c6a133ce9..c2acc6349 100644--- a/web-app/src/lib/service.ts+++ b/web-app/src/lib/service.ts@@ -103,6 +103,11 @@ export const APIs = {'enable_server_tool_execution','enableServerToolExecution',]),+ cors_enabled: pickBoolean(raw, [+ 'cors_enabled',+ 'isCorsEnabled',+ 'corsEnabled',+ ]),}return getServiceHub().core().invoke(command, { config })}