Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(mcp): use only https OAuth endpoints, and open only http(s) sign-in URLs
James Damadc61ee2cc15
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex ab6ce7cc6..5a81c4874 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -629,7 +629,12 @@ pub async fn authorize_mcp_server<R: Runtime>(log::error!("Failed to emit mcp-oauth-url event: {e}");}// Best-effort: the url has already been emitted, so a session with no- // browser can still finish by opening it by hand.+ // browser can still finish by opening it by hand. Only http(s) is handed+ // to the system opener, which would otherwise launch whatever handles the+ // scheme.+ if !oauth::is_allowed_oauth_url(&pending.authorization_url) {+ return Err(format!("'{name}' produced a sign-in URL Jan will not open"));+ }if let Err(e) = app.opener().open_url(&pending.authorization_url, None::<&str>) {log::warn!("Could not open the browser for '{name}': {e}");}diff --git a/src-tauri/src/core/mcp/oauth.rs b/src-tauri/src/core/mcp/oauth.rsindex dcdb2c4ea..3f2d00d90 100644--- a/src-tauri/src/core/mcp/oauth.rs+++ b/src-tauri/src/core/mcp/oauth.rs@@ -293,6 +293,26 @@ pub async fn advertises_oauth(url: &str) -> bool {manager.resolve_metadata().await.is_ok()}+/// Whether `url` may be an OAuth endpoint, or be opened in a browser during+/// sign-in: `https`, or `http` to this computer (a local dev server). The+/// server supplies these URLs, and the consent page is opened with the+/// system's default handler for its scheme.+pub(crate) fn is_allowed_oauth_url(url: &str) -> bool {+ let Ok(parsed) = reqwest::Url::parse(url) else {+ return false;+ };+ match parsed.scheme() {+ "https" => true,+ "http" => match parsed.host() {+ Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),+ Some(url::Host::Ipv4(ip)) => ip.is_loopback(),+ Some(url::Host::Ipv6(ip)) => ip.is_loopback(),+ None => false,+ },+ _ => false,+ }+}+type CodeClient = oauth2::basic::BasicClient<oauth2::EndpointSet,oauth2::EndpointNotSet,@@ -347,6 +367,14 @@ pub async fn begin(server: &str, url: &str) -> Result<PendingAuth, String> {let resolution = manager.resolve_metadata().await.map_err(|e| format!("'{server}' does not offer OAuth we can use: {e}"))?;let metadata = resolution.metadata;+ for endpoint in [&metadata.authorization_endpoint, &metadata.token_endpoint] {+ if !is_allowed_oauth_url(endpoint) {+ return Err(format!(+ "'{server}' advertised the OAuth endpoint '{endpoint}', which Jan will not use: \+ it must be https (or http on this computer)"+ ));+ }+ }let endpoint = metadata.registration_endpoint.as_deref().ok_or_else(|| format!("'{server}' requires a pre-registered OAuth client; no registration endpoint was advertised"))?;let http = reqwest::Client::builder()@@ -396,6 +424,9 @@ pub async fn begin(server: &str, url: &str) -> Result<PendingAuth, String> {let (challenge, verifier) = oauth2::PkceCodeChallenge::new_random_sha256();let (authorization_url, csrf) = client.authorize_url(oauth2::CsrfToken::new_random).set_pkce_challenge(challenge).url();+ if !is_allowed_oauth_url(authorization_url.as_str()) {+ return Err(format!("'{server}' produced a sign-in URL Jan will not open"));+ }Ok(PendingAuth {client,@@ -691,6 +722,22 @@ mod tests {async fn registration_server(status: u16,registration_body: &'static str,+ ) -> (String, tokio::task::JoinHandle<()>) {+ provider_server(status, registration_body, None).await+ }++ /// A provider whose metadata advertises `value` for `field`.+ async fn metadata_server(+ field: &'static str,+ value: &'static str,+ ) -> (String, tokio::task::JoinHandle<()>) {+ provider_server(201, r#"{"client_id":"c"}"#, Some((field, value))).await+ }++ async fn provider_server(+ status: u16,+ registration_body: &'static str,+ metadata_override: Option<(&'static str, &'static str)>,) -> (String, tokio::task::JoinHandle<()>) {use tokio::io::{AsyncReadExt, AsyncWriteExt};let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();@@ -737,12 +784,16 @@ mod tests {"authorization_servers": [origin.clone()],}).to_string())} else {- (200, json!({+ let mut metadata = json!({"issuer": origin.clone(),"authorization_endpoint": format!("{origin}/authorize"),"token_endpoint": format!("{origin}/token"),"registration_endpoint": format!("{origin}/register"),- }).to_string())+ });+ if let Some((field, value)) = metadata_override {+ metadata[field] = json!(value);+ }+ (200, metadata.to_string())};let reply = format!("HTTP/1.1 {code} Response\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",@@ -1012,6 +1063,47 @@ mod tests {assert!(err.contains("https://old/mcp"), "{err}");}+ #[test]+ fn oauth_urls_must_be_https_or_loopback_http() {+ for ok in [+ "https://auth.example.com/authorize",+ "HTTPS://auth.example.com/token",+ "http://127.0.0.1:8080/authorize",+ "http://localhost:3000/token",+ "http://LOCALHOST/token",+ "http://[::1]:9000/authorize",+ ] {+ assert!(is_allowed_oauth_url(ok), "{ok}");+ }+ for bad in [+ "http://auth.example.com/authorize",+ "http://localhost.example.com/authorize",+ "http://10.0.0.1/token",+ "file:///Users/u/Downloads/payload.command",+ "javascript:alert(1)",+ "smb://host/share",+ "ftp://auth.example.com/",+ "/authorize",+ "",+ ] {+ assert!(!is_allowed_oauth_url(bad), "{bad}");+ }+ }++ #[tokio::test]+ async fn begin_refuses_a_non_https_authorization_endpoint() {+ for (field, value) in [+ ("authorization_endpoint", "file:///tmp/payload.command"),+ ("token_endpoint", "http://auth.example.com/token"),+ ] {+ let (base, task) = metadata_server(field, value).await;+ let err = begin("bad", &format!("{base}/mcp")).await.err().unwrap();+ task.abort();+ assert!(err.contains("will not use"), "{err}");+ assert!(err.contains(value), "{err}");+ }+ }+#[test]fn callback_query_parsing() {let ok = parse_callback_query("code=abc&state=xyz").unwrap().unwrap();