Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
test(cli): isolate config, OAuth logs and Claude keychain lookups (#9463)
James Dam9c2d004518b1
diff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex 4e3af0549..a5e66d9f0 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -356,8 +356,11 @@ pub(crate) struct ProviderUpdate {/// `~/.jan`, the user-wide config directory.pub(crate) fn global_jan_dir() -> Result<PathBuf, String> {- dirs::home_dir()- .map(|home| home.join(".jan"))+ #[cfg(test)]+ let home = TEST_HOME.with(|home| Some(home.borrow().path().to_path_buf()));+ #[cfg(not(test))]+ let home = dirs::home_dir();+ home.map(|home| home.join(".jan")).ok_or_else(|| "could not resolve the user's home directory".to_string())}@@ -1041,30 +1044,54 @@ pub(crate) fn ensure_global_config() -> Result<PathBuf, String> {Ok(path)}-/// Redirect `HOME` to a scratch dir for the duration of `f`. Every test that-/// touches `~/.jan` must go through this one helper: `HOME` is process-wide, so-/// a second lock elsewhere would let those tests race each other.+// Resolve config paths independently of platform home APIs in unit tests. Each+// thread starts with a fresh directory, including tests outside with_temp_home.+#[cfg(test)]+thread_local! {+ static TEST_HOME: std::cell::RefCell<tempfile::TempDir> =+ std::cell::RefCell::new(tempfile::tempdir().expect("test config home"));+}++/// Give config resolution a fresh scratch home on every platform. Keep HOME+/// redirected for existing callers that also exercise HOME-based code. That+/// environment variable is process-wide, so all such callers share this lock.+/// Both overrides are restored on unwind; the scratch directory is RAII-owned.+///+/// All fixture config access must run on the calling OS thread: `TEST_HOME` is+/// thread-local and is not inherited by spawned threads or runtime workers.+/// A runtime's root `block_on` future stays on the caller and is safe; do not+/// move fixture-dependent work into `std::thread::spawn`, `spawn_blocking`, or+/// `tokio::spawn` tasks that may run on another OS thread.#[cfg(test)]pub(crate) fn with_temp_home<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {- use std::sync::atomic::{AtomicU32, Ordering};use std::sync::Mutex;static ENV_LOCK: Mutex<()> = Mutex::new(());- static COUNTER: AtomicU32 = AtomicU32::new(0);-let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());- let n = COUNTER.fetch_add(1, Ordering::SeqCst);- let home = std::env::temp_dir().join(format!("jan_global_cfg_test_{n}"));- std::fs::create_dir_all(&home).unwrap();- let prev = std::env::var_os("HOME");- std::env::set_var("HOME", &home);- let result = f(&home);- match prev {- Some(p) => std::env::set_var("HOME", p),- None => std::env::remove_var("HOME"),+ let home = tempfile::tempdir().expect("test config home");+ let path = home.path().to_path_buf();+ let previous = TEST_HOME.with(|slot| slot.replace(home));+ struct Restore {+ home: Option<tempfile::TempDir>,+ env: Option<std::ffi::OsString>,+ }+ impl Drop for Restore {+ fn drop(&mut self) {+ TEST_HOME.with(|slot| {+ slot.replace(self.home.take().unwrap());+ });+ match &self.env {+ Some(value) => std::env::set_var("HOME", value),+ None => std::env::remove_var("HOME"),+ }+ }}- let _ = std::fs::remove_dir_all(&home);- result+ let _restore = Restore {+ home: Some(previous),+ env: std::env::var_os("HOME"),+ };+ std::env::set_var("HOME", &path);+ f(&path)}// The suite covers the provider records and the TUI's settings writers, which@@ -1074,6 +1101,23 @@ pub(crate) fn with_temp_home<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {mod tests {use super::*;+ #[test]+ fn config_resolver_uses_fixture_and_restores_after_panic() {+ let before = global_config_path().unwrap();+ let mut scratch = None;+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ with_temp_home(|home| {+ scratch = Some(home.to_path_buf());+ assert_eq!(global_config_path().unwrap(), home.join(".jan/config.toml"));+ ensure_global_config().unwrap();+ panic!("exercise fixture cleanup");+ });+ }));+ assert!(result.is_err());+ assert_eq!(global_config_path().unwrap(), before);+ assert!(!scratch.unwrap().exists());+ }+#[test]fn missing_file_yields_empty_map() {with_temp_home(|_| {diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rsindex 5f8ab7a36..61efafdda 100644--- a/src-tauri/src/core/agent/skills.rs+++ b/src-tauri/src/core/agent/skills.rs@@ -27,9 +27,10 @@ pub(crate) fn skills_dir(root: &Path) -> PathBuf {}/// The user-wide skill store root: `~/.jan` (skills live in its `skills/`,-/// beside the user memory scope `~/.jan/memory`). Resolved through-/// [`crate::core::agent::project::jan_home`], so test builds point at a-/// per-process temp home. `None` when there is no usable home directory.+/// beside the user memory scope `~/.jan/memory`). Resolve through+/// [`crate::core::agent::project::jan_home`] in every build so sandbox hiding+/// and plugin install workers agree on the root. Unit tests use that resolver's+/// shared process scratch home and must run serially when mutating user skills.pub(crate) fn user_store_root() -> Option<PathBuf> {crate::core::agent::project::jan_home()}@@ -994,6 +995,15 @@ pub(crate) fn delete(root: &Path, name: &str) -> Result<(), String> {mod tests {use super::*;+ #[test]+ fn user_skill_store_matches_sandbox_hidden_root() {+ let home = crate::core::agent::project::jan_home().unwrap();+ assert_eq!(user_store_root(), Some(home.clone()));+ assert_eq!(user_skills_dir(), Some(home.join("skills")));+ assert_eq!(crate::core::agent::project::hidden_root(true), Some(home));+ assert_eq!(crate::core::agent::project::hidden_root(false), None);+ }+#[test]fn parse_extracts_description_and_strips_frontmatter() {let p = parse("---\nname: deploy\ndescription: Ship it\n---\n\nRun the script.");diff --git a/src-tauri/src/core/cli/auth/account.rs b/src-tauri/src/core/cli/auth/account.rsindex 7755ddbc7..de67d7218 100644--- a/src-tauri/src/core/cli/auth/account.rs+++ b/src-tauri/src/core/cli/auth/account.rs@@ -138,7 +138,12 @@ pub fn begin(provider: AccountProvider) -> Result<AccountLogin, String> {pub fn debug_log(message: &str) {use std::io::Write;+ #[cfg(not(test))]let data_folder = crate::core::app::commands::resolve_jan_data_folder();+ // Async OAuth tests can log without a TempSecrets fixture. Never consult+ // real app configuration (or process-global JAN_DATA_FOLDER) in unit tests.+ #[cfg(test)]+ let data_folder = TEST_LOG_ROOT.with(|root| root.path().to_path_buf());let path = data_folder.join("logs").join("account-oauth.log");let _ = std::fs::create_dir_all(path.parent().expect("log path has a parent"));let timestamp = std::time::SystemTime::now()@@ -154,6 +159,12 @@ pub fn debug_log(message: &str) {}}+#[cfg(test)]+thread_local! {+ static TEST_LOG_ROOT: tempfile::TempDir = tempfile::tempdir().expect("OAuth test logs");+ static KEYCHAIN_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}+fn random_url_safe(bytes: usize) -> String {let mut value = vec![0; bytes];rand::thread_rng().fill_bytes(&mut value);@@ -660,8 +671,16 @@ fn claude_code_oauth(raw: &str) -> Option<OAuthToken> {})}+/// Test fake: count lookup attempts without accessing OS credentials.+#[cfg(test)]+fn claude_code_keychain_entry() -> Option<keyring::Entry> {+ KEYCHAIN_LOOKUPS.with(|count| count.set(count.get() + 1));+ None // Unit tests must never read or rotate a developer's credential.+}+/// The clean generic macOS keychain descriptor type returned by the keyring/// crate for a `Claude Code-credentials` entry.+#[cfg(not(test))]fn claude_code_keychain_entry() -> Option<keyring::Entry> {// The account name is the macOS login user, which the OS keychain keys the// entry under. Claude Code names its service with the stable literal@@ -1107,6 +1126,15 @@ mod tests {use std::net::TcpListener;use std::sync::{mpsc, MutexGuard};+ #[test]+ fn debug_log_writes_to_test_scratch_directory() {+ debug_log("isolated OAuth diagnostic");+ TEST_LOG_ROOT.with(|root| {+ let log = std::fs::read_to_string(root.path().join("logs/account-oauth.log")).unwrap();+ assert!(log.contains("isolated OAuth diagnostic"));+ });+ }+/// Serializes the tests that mutate the process-global Claude alias latch,/// which cargo runs in parallel threads. A tokio mutex, not a std one:/// these tests hold the guard across `.await`.@@ -1219,8 +1247,14 @@ mod tests {}fn complete_account_for_test(models_base_url: String) -> Result<AccountProvider, String> {- std::thread::spawn(move || {- tokio::runtime::Runtime::new().unwrap().block_on(async move {+ // Stay on the fixture-owning OS thread: global config resolution is+ // thread-local in unit tests. A spawned completion thread would write+ // into a different scratch home from the caller's assertions.+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(async move {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let mut login = begin(AccountProvider::Codex).unwrap();@@ -1241,9 +1275,6 @@ mod tests {client.await.unwrap();result})- })- .join()- .expect("account completion thread must not panic")}@@ -1253,8 +1284,14 @@ mod tests {fn complete_claude_account_for_test(models_base_url: String,) -> Result<AccountProvider, String> {- std::thread::spawn(move || {- tokio::runtime::Runtime::new().unwrap().block_on(async move {+ // Stay on the fixture-owning OS thread: global config resolution is+ // thread-local in unit tests. A spawned completion thread would write+ // into a different scratch home from the caller's assertions.+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(async move {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let address = listener.local_addr().unwrap();let mut login = begin(AccountProvider::Claude).unwrap();@@ -1274,15 +1311,18 @@ mod tests {client.await.unwrap();result})- })- .join()- .expect("claude account completion thread must not panic")}fn complete_account_manually_for_test(models_base_url: String,) -> Result<AccountProvider, String> {- std::thread::spawn(move || {- tokio::runtime::Runtime::new().unwrap().block_on(async move {+ // Stay on the fixture-owning OS thread: global config resolution is+ // thread-local in unit tests. A spawned completion thread would write+ // into a different scratch home from the caller's assertions.+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(async move {let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();let mut login = begin(AccountProvider::Codex).unwrap();login.token_endpoint = codex_token_server("account-321");@@ -1292,9 +1332,6 @@ mod tests {manual.send(manual_input).unwrap();complete_callback_login_with_manual(listener.into(), login, receiver).await})- })- .join()- .expect("manual account completion thread must not panic")}#[test]@@ -1751,6 +1788,8 @@ mod tests {Some(Credential::OAuthToken(token)));+ // Completion must persist in this fixture, not another thread's home.+ assert!(crate::core::agent::global_config::global_config_path().unwrap().is_file());let cfg = load_global_config().unwrap().get("openai").unwrap().clone();assert!(cfg.api_key.is_none());assert!(cfg.api_keys.is_empty());@@ -2069,15 +2108,23 @@ mod tests {async fn claude_alias_toggle_controls_the_lookup_gate() {let _guard = alias_test_lock().await;set_claude_alias(false);- // Off: the keychain is never touched, so this is deterministic None- // even on a machine with Claude Code / omp installed.+ KEYCHAIN_LOOKUPS.with(|count| count.set(0));assert_eq!(claude_code_access_token().await, None);+ assert_eq!(claude_code_subscription_type(), None);+ KEYCHAIN_LOOKUPS.with(|count| assert_eq!(count.get(), 0));set_claude_alias(true);+ // Reset even if an assertion panics, so the gate cannot leak to peers.+ struct ResetAlias;+ impl Drop for ResetAlias {+ fn drop(&mut self) {+ set_claude_alias(false);+ }+ }+ let _reset = ResetAlias;assert!(claude_alias_enabled());- // On: it may surface a real token (on a machine with omp signed in) or- // None (sandboxed/CI); either is a valid gate result, so only assert- // the gate flips without panicking.- let _ = claude_code_access_token().await;+ assert_eq!(claude_code_access_token().await, None);+ assert_eq!(claude_code_subscription_type(), None);+ KEYCHAIN_LOOKUPS.with(|count| assert_eq!(count.get(), 2));set_claude_alias(false);assert!(!claude_alias_enabled());}diff --git a/src-tauri/src/core/cli/auth/providers.rs b/src-tauri/src/core/cli/auth/providers.rsindex aed9bd4f0..5a9396e4c 100644--- a/src-tauri/src/core/cli/auth/providers.rs+++ b/src-tauri/src/core/cli/auth/providers.rs@@ -436,15 +436,14 @@ mod tests {definition: &ProviderDefinition,key: &str,) -> Result<LoginResult, LoginError> {- let definition = definition.clone();- let key = key.to_string();- std::thread::spawn(move || {- tokio::runtime::Runtime::new()- .unwrap()- .block_on(login_with_api_key(&definition, &key))- })- .join()- .expect("verification thread must not panic")+ // Stay on the fixture-owning OS thread: global config resolution is+ // thread-local in unit tests, so a spawned login would write into a+ // different scratch home from the caller's assertions.+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(login_with_api_key(definition, key))}#[test]@@ -539,8 +538,8 @@ mod tests {assert!(matches!(result, Err(LoginError::Unavailable(_))));}- #[tokio::test]- async fn valid_key_persists_secret_and_non_secret_config() {+ #[test]+ fn valid_key_persists_secret_and_non_secret_config() {let _tmp = TempSecrets::new();with_temp_home(|_| {let body = r#"{"data":[{"id":"deepseek-chat"},{"id":"deepseek-reasoner"}]}"#;@@ -574,8 +573,8 @@ mod tests {});}- #[tokio::test]- async fn logout_removes_credential_and_config() {+ #[test]+ fn logout_removes_credential_and_config() {let _tmp = TempSecrets::new();with_temp_home(|_| {let body = r#"{"data":[{"id":"deepseek-chat"}]}"#;@@ -592,8 +591,8 @@ mod tests {});}- #[tokio::test]- async fn legacy_plaintext_key_is_cleared_by_login() {+ #[test]+ fn legacy_plaintext_key_is_cleared_by_login() {let _tmp = TempSecrets::new();with_temp_home(|_| {// Simulate a pre-existing legacy entry with a plaintext key.