Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(mcp,tools): do not pass gateway credentials to child processes
locnguyen198692c44fbfb234
diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdxindex d79c925ef..b030e45ed 100644--- a/docs/src/pages/docs/agent/mcp.mdx+++ b/docs/src/pages/docs/agent/mcp.mdx@@ -38,6 +38,16 @@ If a connected server later fails to list its tools - a timeout, a transient errits last known tools instead of dropping it for that turn. The toolset stays the same across thehiccup, and so does the prefix your provider is caching.+## A stdio server's environment++A stdio server inherits Jan's environment, minus the credentials Jan was given for its own gateway:+`JAN_API_KEY`, `JAN_CUSTOM_HEADERS`, the `--provider`'s own `<PROVIDER>_API_KEY` (for example+`TOKAMAK_API_KEY` under `jan --provider tokamak`), and, while Jan exports+[telemetry](/docs/agent/telemetry), the `OTEL_EXPORTER_OTLP_*HEADERS` variables. Everything else is+inherited as before, so a server that reads `GITHUB_TOKEN`, or the key of a provider you did not+name with `--provider`, keeps working. To hand a server one of the removed variables, set it in the+server's own `env`, which is applied last.+## Managing servers### In the consolediff --git a/docs/src/pages/docs/agent/permissions.mdx b/docs/src/pages/docs/agent/permissions.mdxindex 5654e8e3d..160a008c3 100644--- a/docs/src/pages/docs/agent/permissions.mdx+++ b/docs/src/pages/docs/agent/permissions.mdx@@ -171,9 +171,11 @@ RUST_LOG = "info"- `env_passthrough` copies the named host variables in if they are set. The two scopes merge: theglobal list and the project list both apply.-- A **secret-looking** name (containing `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `PASSWD`, or- `CREDENTIAL`, case-insensitive) is never copied by a wildcard - so a broad `GIT_*` cannot leak a- `GIT_TOKEN`. To pass one deliberately, name it in `env_set`, which is not filtered.+- A **secret-looking** name (containing `KEY`, `TOKEN`, `SECRET`, `PASSWORD`, `PASSWD`,+ `CREDENTIAL`, `HEADERS` or `AUTHORIZATION`, case-insensitive) is never copied by a wildcard - so a+ broad `GIT_*` cannot leak a `GIT_TOKEN`, and `OTEL_*` cannot copy `OTEL_EXPORTER_OTLP_HEADERS`,+ which holds an API key when a launcher configures telemetry. To pass one deliberately, name it in+ `env_set`, which is not filtered.- `env_set` wins over `env_passthrough` and over the global value for the same key. Under thesandbox, `TMPDIR`/`TMP`/`TEMP` are always pointed at the run's scratch directory regardless.diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rsindex f152647d2..1a411403f 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/proc.rs@@ -298,8 +298,22 @@ fn confine_limits(cmd: &mut Command) {/// Case-insensitive markers a `passthrough` glob must never copy, so a broad/// pattern (`GIT_*`, `*`) cannot leak a credential into the shell. To inject one/// on purpose, name it in [`ShellEnv::set`], which is not scrubbed.+///+/// `HEADERS` covers `OTEL_EXPORTER_OTLP_*HEADERS` and `JAN_CUSTOM_HEADERS`,+/// which carry an API key when a launcher sets them, so `OTEL_*` cannot copy+/// one. `AUTHORIZATION`, not a bare `AUTH`, which would also match+/// `GIT_AUTHOR_NAME`.fn is_secret_name(name: &str) -> bool {- const MARKERS: &[&str] = &["KEY", "SECRET", "TOKEN", "PASSWORD", "PASSWD", "CREDENTIAL"];+ const MARKERS: &[&str] = &[+ "KEY",+ "SECRET",+ "TOKEN",+ "PASSWORD",+ "PASSWD",+ "CREDENTIAL",+ "HEADERS",+ "AUTHORIZATION",+ ];let upper = name.to_ascii_uppercase();MARKERS.iter().any(|m| upper.contains(m))}@@ -926,10 +940,27 @@ mod env_policy_tests {#[test]fn secret_names_are_recognized() {- for name in ["OPENAI_API_KEY", "MY_SECRET", "GH_TOKEN", "DB_PASSWORD", "aws_credential"] {+ for name in [+ "OPENAI_API_KEY",+ "MY_SECRET",+ "GH_TOKEN",+ "DB_PASSWORD",+ "aws_credential",+ "OTEL_EXPORTER_OTLP_HEADERS",+ "OTEL_EXPORTER_OTLP_LOGS_HEADERS",+ "JAN_CUSTOM_HEADERS",+ "HTTP_AUTHORIZATION",+ ] {assert!(is_secret_name(name), "{name} should read as secret");}- for name in ["PATH", "HOME", "GIT_AUTHOR_NAME", "RUST_LOG"] {+ for name in [+ "PATH",+ "HOME",+ "GIT_AUTHOR_NAME",+ "RUST_LOG",+ "OTEL_SERVICE_NAME",+ "OTEL_EXPORTER_OTLP_ENDPOINT",+ ] {assert!(!is_secret_name(name), "{name} should not read as secret");}}@@ -959,6 +990,24 @@ mod env_policy_tests {assert!(!out.iter().any(|(k, _)| k == "UNRELATED"));}+ #[test]+ fn an_otel_glob_never_copies_the_exporters_headers() {+ // A launcher puts its API key in the OTLP headers; `OTEL_*` is a+ // natural pass-through to write, and must not carry it into a shell.+ let pats = vec!["OTEL_*".to_string(), "JAN_*".to_string()];+ let env = ShellEnv { passthrough: &pats, set: &[] };+ let out = resolve_env_overrides(+ host(&[+ ("OTEL_SERVICE_NAME", "jan-agent"),+ ("OTEL_EXPORTER_OTLP_HEADERS", "x-api-key=sk"),+ ("OTEL_EXPORTER_OTLP_METRICS_HEADERS", "x-api-key=sk"),+ ("JAN_CUSTOM_HEADERS", "Authorization: Bearer sk"),+ ]),+ env,+ );+ assert_eq!(out, vec![("OTEL_SERVICE_NAME".to_string(), "jan-agent".to_string())]);+ }+#[test]fn set_wins_over_passthrough_and_injects_verbatim() {let pats = vec!["RUST_LOG".to_string()];diff --git a/src-tauri/src/core/agent/otel/mod.rs b/src-tauri/src/core/agent/otel/mod.rsindex e7861dc7a..f3779e0ac 100644--- a/src-tauri/src/core/agent/otel/mod.rs+++ b/src-tauri/src/core/agent/otel/mod.rs@@ -413,6 +413,13 @@ pub fn init(true}+/// Whether this process exports telemetry ([`init`] turned the exporter on).+/// While it does, the `OTEL_EXPORTER_OTLP_*HEADERS` in the environment are+/// Jan's own collector credentials, which child processes must not inherit.+pub fn is_active() -> bool {+ GLOBAL.get().is_some()+}+/// Hand one consumed event to the exporter, if it is on.pub fn observe(event: &StreamEvent) {if let Some(t) = global() {diff --git a/src-tauri/src/core/cli/mcp.rs b/src-tauri/src/core/cli/mcp.rsindex 94fbd14c9..0dfee2626 100644--- a/src-tauri/src/core/cli/mcp.rs+++ b/src-tauri/src/core/cli/mcp.rs@@ -25,10 +25,12 @@ use tokio::process::Command;use crate::core::app::commands::resolve_jan_data_folder;use crate::core::mcp::models::McpSettings;-use crate::core::mcp::models::{extract_active_status, extract_command_args};+use crate::core::mcp::models::{extract_active_status, extract_command_args, McpServerConfig};use crate::core::mcp::oauth;use crate::core::state::{RunningServiceEnum, SharedMcpServers};+use super::providers::ProviderOverrides;+/// The Jan Browser MCP needs the desktop bridge/lockfile machinery, so it is/// never offered or connected from the CLI.const BROWSER_MCP_NAME: &str = "Jan Browser MCP";@@ -461,25 +463,7 @@ async fn connect_in(}}_ => {- let mut cmd = Command::new(¶ms.command);- #[cfg(windows)]- {- use std::os::windows::process::CommandExt;- cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW- }- #[cfg(unix)]- {- cmd.process_group(0);- }- cmd.kill_on_drop(true);- for arg in params.args.iter().filter_map(Value::as_str) {- cmd.arg(arg);- }- for (k, v) in params.envs.iter() {- if let Some(v) = v.as_str() {- cmd.env(k, v);- }- }+ let cmd = stdio_command(¶ms, &inherited_credentials());let (process, _stderr) = TokioChildProcess::builder(cmd).stderr(Stdio::null()).spawn()@@ -497,6 +481,73 @@ async fn connect_in(Ok(())}+/// A stdio server's command: its args, and this process's environment minus+/// `scrub`, with the server's own `env` entries set last so a server that+/// needs one of the scrubbed variables can still be given it by name.+fn stdio_command(params: &McpServerConfig, scrub: &[String]) -> Command {+ let mut cmd = Command::new(¶ms.command);+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW+ }+ #[cfg(unix)]+ {+ cmd.process_group(0);+ }+ cmd.kill_on_drop(true);+ for arg in params.args.iter().filter_map(Value::as_str) {+ cmd.arg(arg);+ }+ for name in scrub {+ cmd.env_remove(name);+ }+ for (k, v) in params.envs.iter() {+ if let Some(v) = v.as_str() {+ cmd.env(k, v);+ }+ }+ cmd+}++/// The OTLP exporter's header variables. While Jan's own telemetry is on they+/// hold its collector credentials (a launcher puts its API key there).+const OTLP_HEADER_VARS: &[&str] = &[+ "OTEL_EXPORTER_OTLP_HEADERS",+ "OTEL_EXPORTER_OTLP_LOGS_HEADERS",+ "OTEL_EXPORTER_OTLP_METRICS_HEADERS",+ "OTEL_EXPORTER_OTLP_TRACES_HEADERS",+];++/// The variables a stdio MCP server must not inherit from this session: the+/// credentials Jan was given to reach its own model gateway and collector.+fn inherited_credentials() -> Vec<String> {+ credential_vars(+ ProviderOverrides::session().explicit_provider_name(),+ crate::core::agent::otel::is_active(),+ )+}++/// Deliberately narrow. `JAN_API_KEY`, the explicit `--provider`'s own+/// `<PROVIDER>_API_KEY` and `JAN_CUSTOM_HEADERS` only ever address Jan's+/// gateway. A Desktop-selected provider's variable (`OPENAI_API_KEY`, ...) is+/// left alone, because servers commonly read those for themselves, and so are+/// the OTLP header variables while Jan exports nothing: they are then the+/// user's, for a server that exports to its own collector.+fn credential_vars(explicit_provider: Option<&str>, telemetry_on: bool) -> Vec<String> {+ let mut names = vec![+ "JAN_API_KEY".to_string(),+ super::providers::CUSTOM_HEADERS_ENV.to_string(),+ ];+ if let Some(provider) = explicit_provider {+ names.push(super::providers::provider_key_env(provider));+ }+ if telemetry_on {+ names.extend(OTLP_HEADER_VARS.iter().map(|v| v.to_string()));+ }+ names+}+/// Serve the streamable-http transport over any client that implements it, so/// the plain and OAuth-wrapped clients share one code path instead of the/// transport construction being written out twice.@@ -921,6 +972,87 @@ mod tests {assert_eq!(parse_args("npx -y my-mcp"), vec!["npx", "-y", "my-mcp"]);}+ #[test]+ fn gateway_credentials_are_scrubbed_and_a_desktop_providers_key_is_not() {+ // No explicit provider, no telemetry: only Jan's own gateway variables.+ assert_eq!(credential_vars(None, false), ["JAN_API_KEY", "JAN_CUSTOM_HEADERS"]);++ // A launcher's session: the named provider's key and, while Jan+ // exports, its collector headers too.+ let launched = credential_vars(Some("tokamak"), true);+ for name in [+ "JAN_API_KEY",+ "JAN_CUSTOM_HEADERS",+ "TOKAMAK_API_KEY",+ "OTEL_EXPORTER_OTLP_HEADERS",+ "OTEL_EXPORTER_OTLP_LOGS_HEADERS",+ "OTEL_EXPORTER_OTLP_METRICS_HEADERS",+ "OTEL_EXPORTER_OTLP_TRACES_HEADERS",+ ] {+ assert!(launched.iter().any(|n| n == name), "{name} in {launched:?}");+ }+ // Keys servers read for themselves stay.+ assert!(!launched.iter().any(|n| n == "OPENAI_API_KEY" || n == "GITHUB_TOKEN"));++ // Telemetry off: the OTLP headers are the user's, for a server that+ // exports to its own collector.+ assert!(!credential_vars(Some("tokamak"), false)+ .iter()+ .any(|n| n.starts_with("OTEL_")));+ }++ #[test]+ fn a_stdio_server_keeps_its_own_env_over_the_scrub() {+ let params = extract_command_args(&serde_json::json!({+ "command": "server",+ "args": ["--stdio"],+ "env": { "TOKAMAK_API_KEY": "the-servers-own" },+ }))+ .unwrap();+ let scrub = credential_vars(Some("tokamak"), true);+ let cmd = stdio_command(¶ms, &scrub);+ let envs: std::collections::HashMap<String, Option<String>> = cmd+ .as_std()+ .get_envs()+ .map(|(k, v)| {+ (+ k.to_string_lossy().into_owned(),+ v.map(|v| v.to_string_lossy().into_owned()),+ )+ })+ .collect();+ assert_eq!(envs.get("JAN_API_KEY"), Some(&None), "removed");+ assert_eq!(envs.get("OTEL_EXPORTER_OTLP_HEADERS"), Some(&None), "removed");+ assert_eq!(+ envs.get("TOKAMAK_API_KEY"),+ Some(&Some("the-servers-own".to_string())),+ "a server's explicit env entry is still set"+ );+ }++ /// The spawned process really goes without a scrubbed variable it would+ /// otherwise inherit. `HOME` stands in for a credential: every test+ /// process has it, so nothing here mutates the shared environment.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_spawned_stdio_server_does_not_inherit_a_scrubbed_variable() {+ assert!(std::env::var_os("HOME").is_some());+ let params = extract_command_args(&serde_json::json!({+ "command": "/usr/bin/env",+ "args": [],+ "env": { "JAN_TEST_SERVER_OWN": "kept" },+ }))+ .unwrap();+ let out = stdio_command(¶ms, &["HOME".to_string()])+ .output()+ .await+ .expect("spawn env");+ let env = String::from_utf8_lossy(&out.stdout);+ assert!(!env.lines().any(|l| l.starts_with("HOME=")), "{env}");+ assert!(env.lines().any(|l| l == "JAN_TEST_SERVER_OWN=kept"), "{env}");+ assert!(env.lines().any(|l| l.starts_with("PATH=")), "the rest is inherited");+ }+#[test]fn browser_mcp_excluded_and_sorted() {// list_servers reads the real data folder; assert only invariants thatdiff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 9831a0071..03f4b003d 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -966,6 +966,10 @@ pub(crate) fn take_migration_notice() -> Option<String> {/// - `session-header`: inference sends `X-Session-Id`./// - `session-scoped-providers`: a session-scoped provider's models and prices/// stay in memory, and its sign-in cannot be changed from inside the session.+/// - `mcp-env-scrub`: stdio MCP servers do not inherit `JAN_API_KEY`,+/// `JAN_CUSTOM_HEADERS`, the explicit provider's `<PROVIDER>_API_KEY`, or+/// (while Jan exports telemetry) the OTLP header variables; the shell tool's+/// pass-through never copies a `*HEADERS*` or `*AUTHORIZATION*` variable.pub const CAPABILITIES: &[&str] = &["provider-overrides","session-overrides",@@ -973,6 +977,7 @@ pub const CAPABILITIES: &[&str] = &["user-agent","session-header","session-scoped-providers",+ "mcp-env-scrub",];/// [`CAPABILITIES`], then telemetry's, in that order.@@ -4785,6 +4790,7 @@ mod tests {"user-agent","session-header","session-scoped-providers",+ "mcp-env-scrub",].iter().map(|c| serde_json::json!(c))diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rsindex 203127779..6e228a8e5 100644--- a/src-tauri/src/core/cli/providers.rs+++ b/src-tauri/src/core/cli/providers.rs@@ -90,7 +90,7 @@ impl ProviderOverrides {}if self.api_key.is_none() {if let Some(provider) = &self.provider {- let var = format!("{}_API_KEY", provider.to_ascii_uppercase());+ let var = provider_key_env(provider);if let Some(k) = env(&var).filter(|k| !k.is_empty()) {self.api_key = Some(k);}@@ -166,6 +166,12 @@ impl ProviderOverrides {}}+/// The environment variable that carries `provider`'s key for an explicit+/// `--provider` (`ANTHROPIC_API_KEY`, `TOKAMAK_API_KEY`, ...).+pub(crate) fn provider_key_env(provider: &str) -> String {+ format!("{}_API_KEY", provider.to_ascii_uppercase())+}+fn warn_once_unscoped() {static WARNED: std::sync::Once = std::sync::Once::new();WARNED.call_once(|| {