Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Merge remote-tracking branch 'origin/main' into thinhlpg/9107-hide-secrets
thinhlpge48cbb8981c1
diff --cc src-tauri/src/core/agent/loop.rsindex d77e8254e,a34500342..9a742129b--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@@ -458,12 -457,19 +461,22 @@@ impl ModelInvoker for HttpModelInvoker// URL + credential have already been resolved from that qualifier, so// the body must carry the bare model id - providers like OpenCode GO// reject a provider-qualified id with "model not supported".- let mut normalized = request.clone();+ let mut normalized = match &self.secrets {+ Some(filter) => filter.filter_request(request),+ None => request.clone(),+ };+ // The serving provider's custom headers, looked up through the same+ // routing order the upstream was resolved by, so every invoker -- the+ // turn, compaction, `/goal`, side calls, subagents -- sends the headers+ // of the provider it is actually talking to.+ let mut custom_headers = Vec::new();if let Some(model) = normalized.get("model").and_then(|m| m.as_str()) {let pc = self.provider_configs.lock().await;+ if let Some(config) = crate::core::agent::upstream::pick_provider_for_model(model, &pc)+ .and_then(|provider| pc.get(&provider))+ {+ custom_headers = config.custom_headers.clone();+ }let bare = crate::core::agent::upstream::strip_provider_prefix(model, &pc);if bare != model {normalized["model"] = serde_json::json!(bare);@@@ -502,19 -515,10 +522,19 @@@None,&normalized,events,- self.client_request_id.as_deref(),+ &extra_headers,).await+ };+ if self.secrets.is_some() {+ // The model saw placeholders; the tool and the saved thread get the+ // real values back. The next request hides them again.+ return completion.map(|mut c| {+ crate::core::agent::secrets::restore_completion(&mut c);+ c+ });}+ completion}}@@@ -5300,88 -5300,101 +5320,184 @@@ mod tests);}+ /// Hide Secrets, end to end through the invoker: the body a provider+ /// receives holds a placeholder and never the secret, and a tool call the+ /// model writes with that placeholder comes back holding the real value.+ #[tokio::test]+ async fn hide_secrets_filters_the_wire_body_and_restores_the_tool_call() {+ use std::io::{BufRead, BufReader, Read, Write};++ const SECRET: &str = "live-value-1234567890";+ let filter = Arc::new(crate::core::agent::secrets::SecretFilter::for_tests(&[(+ "OPENAI_API_KEY",+ SECRET,+ )]));+ let placeholder = filter.hide(SECRET);+ assert!(placeholder.starts_with("$$OPENAI_API_KEY_"), "{placeholder}");++ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!("http://{}/v1/chat/completions", listener.local_addr().unwrap());+ let (seen_tx, seen_rx) = std::sync::mpsc::channel::<String>();+ let reply_args = serde_json::json!({ "command": format!("login {placeholder}") })+ .to_string();+ std::thread::spawn(move || {+ let Some(Ok(mut stream)) = listener.incoming().next() else { return };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut length = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ if let Some(n) = line.to_ascii_lowercase().strip_prefix("content-length:") {+ length = n.trim().parse().unwrap_or(0);+ }+ }+ let mut body = vec![0; length];+ let _ = reader.read_exact(&mut body);+ let _ = seen_tx.send(String::from_utf8_lossy(&body).into_owned());+ let chunk = serde_json::json!({"id":"s","object":"chat.completion.chunk","created":1,"model":"m",+ "choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[+ {"index":0,"id":"c1","type":"function","function":{"name":"bash","arguments":reply_args}}]},+ "finish_reason":null}]});+ let done = serde_json::json!({"id":"s","object":"chat.completion.chunk","created":1,"model":"m",+ "choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}],+ "usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}});+ let answer = format!("data: {chunk}\n\ndata: {done}\n\ndata: [DONE]\n\n");+ write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len()).unwrap();+ });++ let (events, _rx) = mpsc::unbounded_channel();+ let invoker = HttpModelInvoker {+ client: crate::core::agent::upstream::agent_http_client(),+ upstream_url: url,+ api_keys: Vec::new(),+ provider_configs: Arc::new(Mutex::new(HashMap::new())),+ converter: None,+ converter_client: converter_http_client(),+ client_request_id: None,+ session_id: None,+ provenance: RequestIdentityOwned {+ run_id: None,+ provider: Some("stub".to_string()),+ api_type: None,+ oauth: false,+ },+ provenance_events: None,+ secrets: Some(filter),+ };+ let request = json!({"model":"m","messages":[+ {"role":"user","content":format!("my key is {SECRET}")}]});+ let completion = invoker.invoke(&request, &events).await.expect("the stub answers");++ let wire = seen_rx.recv_timeout(std::time::Duration::from_secs(5)).expect("a request");+ assert!(!wire.contains(SECRET), "the secret reached the provider: {wire}");+ assert!(wire.contains(&placeholder), "the placeholder is what it saw: {wire}");++ let args = completion["choices"][0]["message"]["tool_calls"][0]["function"]["arguments"]+ .as_str()+ .expect("a tool call came back");+ let parsed: serde_json::Value = serde_json::from_str(args).unwrap();+ assert_eq!(parsed["command"], format!("login {SECRET}"), "the tool gets the real value");+ assert_eq!(request["messages"][0]["content"], format!("my key is {SECRET}"), "the caller's history is untouched");+ }++ /// The invoker sends the custom headers of the provider that serves the+ /// request's model -- looked up the way the upstream was resolved, so a+ /// `provider/model` id finds its provider -- plus Jan's session headers, and+ /// never a second `Authorization`. This is also the desktop's path: the+ /// headers it registers for a provider now reach the wire.+ #[tokio::test]+ async fn the_serving_providers_headers_reach_the_default_path() {+ use std::io::{BufRead, BufReader, Write};++ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let url = format!(+ "http://{}/v1/chat/completions",+ listener.local_addr().unwrap()+ );+ let (seen_tx, seen_rx) = std::sync::mpsc::channel::<String>();+ std::thread::spawn(move || {+ let Ok((mut stream, _)) = listener.accept() else { return };+ let mut reader = BufReader::new(stream.try_clone().unwrap());+ let mut headers = String::new();+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {+ break;+ }+ headers.push_str(&line);+ }+ let _ = seen_tx.send(headers);+ let answer = concat!(+ "data: {\"id\":\"s\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"m\",",+ "\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n",+ "data: [DONE]\n\n",+ );+ let _ = write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", answer.len());+ });++ let mut configs = HashMap::new();+ configs.insert(+ "gateway".to_string(),+ ProviderConfig {+ provider: "gateway".into(),+ base_url: Some(url.trim_end_matches("/chat/completions").to_string()),+ api_key: Some("real-key".into()),+ api_keys: vec!["real-key".into()],+ custom_headers: vec![+ crate::core::state::ProviderCustomHeader {+ header: "X-Client-Name".into(),+ value: "jan-agent".into(),+ },+ crate::core::state::ProviderCustomHeader {+ header: "authorization".into(),+ value: "Bearer smuggled".into(),+ },+ ],+ ..Default::default()+ },+ );+ let (run, _run_events) = mpsc::unbounded_channel();+ let invoker = HttpModelInvoker {+ client: crate::core::agent::upstream::agent_http_client(),+ upstream_url: url,+ api_keys: vec!["real-key".into()],+ provider_configs: Arc::new(Mutex::new(configs)),+ converter: None,+ converter_client: converter_http_client(),+ client_request_id: crate::core::agent::correlation::session_request_id(Some(+ "sess-9",+ )),+ session_id: Some("sess-9".to_string()),+ provenance: RequestIdentityOwned::default(),+ provenance_events: Some(run),++ secrets: None,+ };+ let (tx, _rx) = mpsc::unbounded_channel();+ invoker+ .invoke(+ &json!({"model":"gateway/m","messages":[{"role":"user","content":"hi"}]}),+ &tx,+ )+ .await+ .expect("the stub answers");++ let seen = seen_rx+ .recv_timeout(std::time::Duration::from_secs(10))+ .expect("the request reached the stub")+ .to_ascii_lowercase();+ assert!(seen.contains("\r\nx-client-name: jan-agent\r\n"), "{seen}");+ assert!(seen.contains("\r\nx-client-request-id: jan-sess-9\r\n"), "{seen}");+ assert!(seen.contains("\r\nx-session-id: sess-9\r\n"), "{seen}");+ assert_eq!(seen.matches("\r\nauthorization: ").count(), 1, "{seen}");+ assert!(seen.contains("\r\nauthorization: bearer real-key\r\n"), "{seen}");+ assert!(+ !seen.contains("\r\nuser-agent:"),+ "a library build sets no User-Agent; only the jan binary does: {seen}"+ );+ }+#[derive(Default)]struct MockTool {calls: StdMutex<Vec<Vec<serde_json::Value>>>,diff --cc src-tauri/src/core/agent/mod.rsindex 4665cf699,80dcda43b..ade7c6e0e--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@@ -46,7 -46,7 +46,8 @@@ pub mod projectpub mod prompt;pub mod provenance;pub mod reminder;+ pub mod request_headers;+pub mod secrets;pub mod session;pub mod skill_hub;pub mod skills;