//! Credential resolution without context exposure (`SMH-SPEC-SPEC0001`, //! Providers: authentication). //! //! Credentials come from environment variables or explicit values, resolve //! without any network access, and can be checked for readiness //! independently of a model request. Registered holders are redacted in //! diagnostics, and updating one provider's credential can never disturb //! another. use std::collections::HashMap; use std::io::Read; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, SystemTime}; use crate::models::ProviderKind; /// Explicit authority identity for one stored credential. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum CredentialKey { /// A provider's default credential identity. Provider(ProviderKind), /// Z.ai Coding Plan authority, separate from metered Z.ai API storage. ZaiCodingPlan, } impl From for CredentialKey { fn from(kind: ProviderKind) -> Self { Self::Provider(kind) } } impl CredentialKey { /// Every host-supported stored credential identity. pub const ALL: [Self; 6] = [ Self::Provider(ProviderKind::Anthropic), Self::Provider(ProviderKind::Google), Self::Provider(ProviderKind::OpenAiCompatible), Self::Provider(ProviderKind::Plugin), Self::Provider(ProviderKind::Zai), Self::ZaiCodingPlan, ]; /// Stable file name and diagnostic identity for this credential. #[must_use] pub const fn slug(self) -> &'static str { match self { Self::Provider(kind) => kind.slug(), Self::ZaiCodingPlan => "zai-coding-plan", } } } /// Largest credential file accepted from the local auth store. const CREDENTIAL_BYTES_MAX: usize = 64 * 1024; /// Where a credential comes from. #[derive(Clone, Debug, PartialEq, Eq)] pub enum CredentialSource { /// Read from this environment variable at resolve time. Env(String), /// An explicit value, typically from configuration or a plugin. Explicit(String), } /// A host-owned credential locator. /// /// This reference carries authority identity, never a value obtained from an /// auth store or environment variable. Resolve it only at the effect boundary. #[derive(Clone)] pub enum CredentialReference { /// A caller supplied secret; never expose this in diagnostics. Explicit(String), /// The selected store identity, followed by its ordered environment fallbacks. StoreOrEnv(CredentialKey), } impl CredentialReference { /// Build an explicit host-owned credential reference. #[must_use] pub fn explicit(value: impl Into) -> Self { Self::Explicit(value.into()) } /// Build the standard store then environment reference for one authority. #[must_use] pub const fn store_or_env(key: CredentialKey) -> Self { Self::StoreOrEnv(key) } /// Resolve plaintext only at an authorized host effect boundary. /// /// # Errors /// /// Returns an authentication failure naming only source identities. pub fn resolve(&self, store: &AuthStore) -> smith::error::Result { match self { Self::Explicit(value) if !value.is_empty() => Ok(value.clone()), Self::Explicit(_) => Err(auth("explicit credential is empty")), Self::StoreOrEnv(key) => { if let Some(secret) = store.load(*key)? { return Ok(secret); } let vars = credential_key_env_vars(*key); if let Some(var) = credential_key_env_var_present(*key) { return std::env::var(var) .ok() .filter(|value| !value.is_empty()) .ok_or_else(|| { auth(format!( "environment variable {var} changed during resolution" )) }); } Err(auth(format!( "no credential for {} (tried store, env {})", key.slug(), vars.join(", ") ))) } } } } /// A resolved credential with optional renewal. /// /// Carries a renewal closure, so it deliberately implements neither /// [`std::fmt::Debug`] nor equality; use [`Credential::describe`] for /// diagnostics. #[derive(Clone)] pub struct Credential { source: CredentialSource, expires_at: Option, renewed: Option Option + Send + Sync>>, } impl Credential { /// A credential read from an environment variable when needed. #[must_use] pub fn from_env(var: impl Into) -> Self { Self { source: CredentialSource::Env(var.into()), expires_at: None, renewed: None, } } /// A credential with an explicit value. #[must_use] pub fn explicit(value: impl Into) -> Self { Self { source: CredentialSource::Explicit(value.into()), expires_at: None, renewed: None, } } /// Attach an expiry; expired values must renew before use. #[must_use] pub fn expires_in(mut self, after: Duration) -> Self { self.expires_at = SystemTime::now().checked_add(after); self } /// Attach an absolute expiry; the injectable form of [`Self::expires_in`]. #[must_use] pub const fn expires_at(mut self, at: SystemTime) -> Self { self.expires_at = Some(at); self } /// Attach a renewal closure that returns a fresh value. #[must_use] pub fn renew_with(mut self, renew: Arc Option + Send + Sync>) -> Self { self.renewed = Some(renew); self } fn is_expired(&self) -> bool { self.expires_at.is_some_and(|at| SystemTime::now() >= at) } /// The secret value, resolving lazily and renewing when expired. /// /// # Errors /// /// Returns a [`smith::error::ProviderFault::Authentication`] fault when /// the source is empty, the value expired, or renewal failed. pub fn secret(&self) -> smith::error::Result { if self.is_expired() { if let Some(renew) = &self.renewed && let Some(fresh) = renew() { return Ok(fresh); } return Err(auth("credential expired and renewal failed")); } match &self.source { CredentialSource::Env(var) => std::env::var(var) .ok() .filter(|value| !value.is_empty()) .ok_or_else(|| auth(format!("environment variable {var} is empty or unset"))), CredentialSource::Explicit(value) => Ok(value.clone()), } } /// Whether a request could be dispatched with this credential now, /// checked without any network access. #[must_use] pub fn is_ready(&self) -> bool { !self.is_expired() && match &self.source { CredentialSource::Env(var) => { std::env::var(var).is_ok_and(|value| !value.is_empty()) } CredentialSource::Explicit(_) => true, } } } /// Redacted description; the secret value never appears. impl Credential { /// A redacted description safe for logs and diagnostics. #[must_use] pub fn describe(&self) -> String { match &self.source { CredentialSource::Env(var) => format!("env:{var}"), CredentialSource::Explicit(_) => "explicit:".to_string(), } } } /// Per-provider credential registry; one owner, updates never touch /// unrelated providers. #[derive(Default)] pub struct AuthRegistry { credentials: HashMap, } impl AuthRegistry { /// An empty registry. #[must_use] pub fn new() -> Self { Self::default() } /// Register or replace the credential for one provider. pub fn set(&mut self, provider: impl Into, credential: Credential) { self.credentials.insert(provider.into(), credential); } /// The registered credential, when present. #[must_use] pub fn get(&self, provider: &str) -> Option<&Credential> { self.credentials.get(provider) } /// Whether the provider has a ready credential, without network access. #[must_use] pub fn is_ready(&self, provider: &str) -> bool { self.get(provider).is_some_and(Credential::is_ready) } } /// Ordered environment variables carrying a provider's credential. /// /// The first non-empty value wins. #[must_use] pub const fn credential_env_vars(kind: ProviderKind) -> &'static [&'static str] { credential_key_env_vars(CredentialKey::Provider(kind)) } /// Ordered environment variables for an explicit credential authority. #[must_use] pub const fn credential_key_env_vars(key: CredentialKey) -> &'static [&'static str] { match key { CredentialKey::Provider(ProviderKind::OpenAiCompatible) => &["OPENAI_API_KEY"], CredentialKey::Provider(ProviderKind::Anthropic) => &["ANTHROPIC_API_KEY"], CredentialKey::Provider(ProviderKind::Google) => &["GOOGLE_API_KEY", "GEMINI_API_KEY"], CredentialKey::Provider(ProviderKind::Zai) | CredentialKey::ZaiCodingPlan => { &["ZAI_API_KEY"] } CredentialKey::Provider(ProviderKind::Plugin) => &["SMITH_PLUGIN_API_KEY"], } } /// First configured nonempty Unicode environment source in resolution order. /// /// This only reports local presence; it neither resolves a credential nor /// establishes remote account access. #[must_use] pub fn credential_key_env_var_present(key: CredentialKey) -> Option<&'static str> { credential_key_env_vars(key) .iter() .copied() .find(|var| std::env::var(var).is_ok_and(|value| !value.is_empty())) } /// The primary environment variable carrying a provider's credential. #[must_use] pub const fn credential_env_var(kind: ProviderKind) -> &'static str { credential_env_vars(kind)[0] } /// The default endpoint base URL for a provider. #[must_use] pub const fn default_base_url(kind: ProviderKind) -> &'static str { match kind { ProviderKind::OpenAiCompatible => "https://api.openai.com/v1", ProviderKind::Anthropic => "https://api.anthropic.com", ProviderKind::Google => "https://generativelanguage.googleapis.com", ProviderKind::Zai => "https://api.z.ai", ProviderKind::Plugin => "https://localhost", } } /// Durable credential store under the Smith data directory. /// /// One plaintext file per provider, user-only permissions where the /// platform supports them, no keychain dependency. #[derive(Clone, Debug)] pub struct AuthStore { dir: PathBuf, } impl AuthStore { /// The store under the platform Smith data directory. #[must_use] pub fn at_default() -> Self { Self { dir: smith::config::auth_dir(), } } /// A store at an explicit directory, primarily for tests. #[must_use] pub fn at(dir: impl Into) -> Self { Self { dir: dir.into() } } /// The backing directory. #[must_use] pub fn dir(&self) -> &Path { &self.dir } fn path(&self, key: CredentialKey) -> PathBuf { self.dir.join(key.slug()) } /// Persist one provider credential with user-only permissions. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Storage`] fault when the secret /// is empty or exceeds the store's byte limit, or the directory or file /// cannot be written. pub fn save(&self, key: impl Into, secret: &str) -> smith::error::Result<()> { let key = key.into(); if secret.is_empty() { return Err(store_io( smith::error::StorageOperation::Write, &self.path(key), &std::io::Error::new( std::io::ErrorKind::InvalidInput, "credential must not be empty", ), )); } if secret.len() > CREDENTIAL_BYTES_MAX { return Err(store_io( smith::error::StorageOperation::Write, &self.path(key), &std::io::Error::new( std::io::ErrorKind::InvalidInput, format!( "credential contains {} bytes; auth-store limit is {CREDENTIAL_BYTES_MAX} bytes; provide a credential within the limit", secret.len() ), ), )); } std::fs::create_dir_all(&self.dir).map_err(|error| { store_io( smith::error::StorageOperation::CreateDirAll, &self.dir, &error, ) })?; let path = self.path(key); std::fs::write(&path, secret) .map_err(|error| store_io(smith::error::StorageOperation::Write, &path, &error))?; restrict_permissions(&path).map_err(|error| { store_io( smith::error::StorageOperation::SetPermissions, &path, &error, ) })?; Ok(()) } /// The stored credential for a provider, when present. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Storage`] fault when the stored /// credential is empty or cannot be read. pub fn load(&self, key: impl Into) -> smith::error::Result> { let path = self.path(key.into()); let mut secret = String::new(); match std::fs::File::open(&path).and_then(|file| { #[expect( clippy::disallowed_methods, reason = "Take caps this read at CREDENTIAL_BYTES_MAX + 1 before overflow is reported" )] file.take((CREDENTIAL_BYTES_MAX + 1) as u64) .read_to_string(&mut secret) }) { Ok(_) if secret.is_empty() => Err(store_io( smith::error::StorageOperation::ReadToString, &path, &std::io::Error::new( std::io::ErrorKind::InvalidData, "stored credential is empty", ), )), Ok(_) if secret.len() <= CREDENTIAL_BYTES_MAX => Ok(Some(secret)), Ok(_) => Err(store_io( smith::error::StorageOperation::ReadToString, &path, &std::io::Error::new( std::io::ErrorKind::InvalidData, format!("credential exceeds {CREDENTIAL_BYTES_MAX} bytes"), ), )), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(error) => Err(store_io( smith::error::StorageOperation::ReadToString, &path, &error, )), } } /// Delete one provider credential; reports whether an entry existed. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Storage`] fault when deletion /// fails for a reason other than absence. pub fn remove(&self, key: impl Into) -> smith::error::Result { let path = self.path(key.into()); match std::fs::remove_file(&path) { Ok(()) => Ok(true), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), Err(error) => Err(store_io( smith::error::StorageOperation::RemoveFile, &path, &error, )), } } /// The providers with a stored credential. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Storage`] fault when the store /// directory cannot be listed or a stored credential is empty or not a /// regular file. pub fn list(&self) -> smith::error::Result> { let mut keys = Vec::new(); let entries = match std::fs::read_dir(&self.dir) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(keys), Err(error) => { return Err(store_io( smith::error::StorageOperation::ReadDir, &self.dir, &error, )); } }; for entry in entries { let entry = entry.map_err(|error| { store_io( smith::error::StorageOperation::ReadDirEntry, &self.dir, &error, ) })?; let file_name = entry.file_name(); let slug = file_name.to_string_lossy(); let key = if slug == CredentialKey::ZaiCodingPlan.slug() { Some(CredentialKey::ZaiCodingPlan) } else { ProviderKind::from_slug(&slug).map(CredentialKey::Provider) }; if let Some(key) = key { let path = entry.path(); let metadata = entry.metadata().map_err(|error| { store_io(smith::error::StorageOperation::Stat, &path, &error) })?; if !metadata.is_file() { return Err(store_io( smith::error::StorageOperation::Stat, &path, &std::io::Error::new( std::io::ErrorKind::InvalidData, "stored credential is not a regular file", ), )); } if metadata.len() == 0 { return Err(store_io( smith::error::StorageOperation::Stat, &path, &std::io::Error::new( std::io::ErrorKind::InvalidData, "stored credential is empty", ), )); } keys.push(key); } } keys.sort(); Ok(keys) } } fn store_io( operation: smith::error::StorageOperation, path: &Path, error: &std::io::Error, ) -> smith::error::SmithError { smith::error::SmithError::Storage { code: smith::error::StorageCode::AuthStore, operation, path: path.to_path_buf(), message: error.to_string(), publication: None, } } #[cfg(unix)] fn restrict_permissions(path: &Path) -> std::io::Result<()> { use std::os::unix::fs::PermissionsExt; let permissions = std::fs::Permissions::from_mode(0o600); std::fs::set_permissions(path, permissions) } #[cfg(not(unix))] fn restrict_permissions(_path: &Path) -> std::io::Result<()> { Ok(()) } fn auth(message: impl Into) -> smith::error::SmithError { smith::error::SmithError::Provider { fault: smith::error::ProviderFault::Authentication { message: message.into(), }, } } #[cfg(test)] mod tests { use super::*; #[test] fn explicit_credential_resolves_and_redacts() { let credential = Credential::explicit("sk-test"); assert!(credential.is_ready()); assert_eq!(credential.secret().unwrap_or_default(), "sk-test"); assert_eq!(credential.describe(), "explicit:"); } #[test] fn expired_credential_renews_or_fails_explicitly() { // inject: expiry is a fixed past instant, never a race against the clock. let past = SystemTime::UNIX_EPOCH; let credential = Credential::explicit("old") .expires_at(past) .renew_with(Arc::new(|| Some("fresh".to_string()))); assert_eq!(credential.secret().unwrap_or_default(), "fresh"); let live = Credential::explicit("old").expires_in(Duration::from_secs(3_600)); assert_eq!(live.secret().unwrap_or_default(), "old"); let dead = Credential::explicit("old").expires_at(past); assert_eq!( dead.secret().err().map(|e| e.code().to_string()), Some("PROVIDER_AUTH".to_string()) ); assert!(!dead.is_ready()); } #[test] fn env_credential_resolves_when_set_and_fails_when_unset() { // Cargo and nextest set CARGO_MANIFEST_DIR for the test process. let set = Credential::from_env("CARGO_MANIFEST_DIR"); assert!(set.is_ready()); assert_eq!(set.secret().unwrap_or_default(), env!("CARGO_MANIFEST_DIR")); let unset = Credential::from_env("SMITH_TEST_UNSET_CREDENTIAL_VAR"); assert!(!unset.is_ready()); assert_eq!( unset.secret().err().map(|e| e.code().to_string()), Some("PROVIDER_AUTH".to_string()) ); } #[test] fn unregistered_provider_is_not_ready() { let mut registry = AuthRegistry::new(); registry.set("anthropic", Credential::explicit("a")); assert!(!registry.is_ready("openai")); } #[test] fn credential_env_vars_are_exact() { for (kind, var) in [ (ProviderKind::OpenAiCompatible, "OPENAI_API_KEY"), (ProviderKind::Anthropic, "ANTHROPIC_API_KEY"), (ProviderKind::Google, "GOOGLE_API_KEY"), (ProviderKind::Zai, "ZAI_API_KEY"), (ProviderKind::Plugin, "SMITH_PLUGIN_API_KEY"), ] { assert_eq!(credential_env_var(kind), var); } assert_eq!( credential_env_vars(ProviderKind::Google), ["GOOGLE_API_KEY", "GEMINI_API_KEY"] ); assert_eq!(credential_env_vars(ProviderKind::Zai), ["ZAI_API_KEY"]); assert_eq!( credential_key_env_vars(CredentialKey::ZaiCodingPlan), ["ZAI_API_KEY"] ); } /// A fresh store directory per test process, removed before use. fn scratch(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("smith_ai_{name}_{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); dir } #[test] fn store_round_trip_lists_saved_providers_and_forgets_removed_ones() { let dir = scratch("store_round_trip"); let store = AuthStore::at(&dir); assert_eq!(store.list().ok(), Some(vec![]), "missing dir lists empty"); assert_eq!(store.remove(ProviderKind::Google).ok(), Some(false)); assert_eq!(store.load(ProviderKind::Google).ok(), Some(None)); for (kind, secret) in [(ProviderKind::Google, "g"), (ProviderKind::Anthropic, "a")] { assert!(store.save(kind, secret).is_ok()); } assert_eq!( store.list().ok(), Some(vec![ CredentialKey::Provider(ProviderKind::Anthropic), CredentialKey::Provider(ProviderKind::Google), ]) ); assert_eq!(store.remove(ProviderKind::Google).ok(), Some(true)); assert_eq!(store.remove(ProviderKind::Google).ok(), Some(false)); assert_eq!( store.list().ok(), Some(vec![CredentialKey::Provider(ProviderKind::Anthropic)]) ); assert_eq!(store.load(ProviderKind::Google).ok(), Some(None)); assert_eq!( store.load(ProviderKind::Anthropic).ok(), Some(Some("a".to_string())) ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn zai_coding_plan_credential_never_aliases_plugin_or_metered_storage() { let dir = scratch("zai_coding_plan_identity"); let store = AuthStore::at(&dir); assert!(store.save(ProviderKind::Plugin, "plugin-secret").is_ok()); assert!(store.save(ProviderKind::Zai, "metered-secret").is_ok()); assert!( store .save(CredentialKey::ZaiCodingPlan, "plan-secret") .is_ok() ); assert_eq!( store.load(CredentialKey::ZaiCodingPlan).ok(), Some(Some("plan-secret".to_string())) ); assert_eq!( store.load(ProviderKind::Plugin).ok(), Some(Some("plugin-secret".to_string())) ); assert_eq!( store.load(ProviderKind::Zai).ok(), Some(Some("metered-secret".to_string())) ); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn saving_an_oversized_credential_does_not_create_or_replace_storage() { // Reject over-limit input before any filesystem mutation; preserve existing secrets. let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../target/style-exec") .join(format!("auth-save-limit-{}", std::process::id())); let store = AuthStore::at(&dir); let kind = ProviderKind::OpenAiCompatible; let oversized = "x".repeat(CREDENTIAL_BYTES_MAX + 1); let error = store.save(kind, &oversized).unwrap_err(); assert_eq!(error.code(), "AUTH_STORE"); assert!(!error.to_string().contains(&oversized)); assert!(!dir.exists(), "rejected input created the store directory"); let at_limit = "x".repeat(CREDENTIAL_BYTES_MAX); store.save(kind, &at_limit).unwrap(); assert_eq!( store.load(kind).unwrap().as_deref(), Some(at_limit.as_str()) ); assert!(store.save(kind, &oversized).is_err()); assert_eq!( store.load(kind).unwrap().as_deref(), Some(at_limit.as_str()) ); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn empty_stored_credentials_are_invalid_and_empty_saves_do_not_mutate_storage() { let dir = scratch("empty_credential"); let store = AuthStore::at(&dir); let path = dir.join(ProviderKind::Google.slug()); assert!(store.save(ProviderKind::Google, "").is_err()); assert!(!dir.exists(), "empty save created the store directory"); assert!(store.save(ProviderKind::Google, "valid").is_ok()); assert!(store.save(ProviderKind::Google, "").is_err()); assert_eq!( std::fs::read_to_string(&path).ok().as_deref(), Some("valid") ); assert!(std::fs::write(&path, "").is_ok()); let load_error = store .load(ProviderKind::Google) .expect_err("empty file is invalid"); assert_eq!(load_error.code(), "AUTH_STORE"); assert!(!load_error.to_string().contains("secret")); let list_error = store.list().expect_err("empty file is invalid for listing"); assert_eq!(list_error.code(), "AUTH_STORE"); assert!(!list_error.to_string().contains("secret")); let _ = std::fs::remove_dir_all(&dir); } #[test] fn credential_read_rejects_bytes_above_the_named_limit() { let dir = scratch("credential_read_limit"); let store = AuthStore::at(&dir); let path = dir.join(ProviderKind::OpenAiCompatible.slug()); assert!(std::fs::create_dir_all(&dir).is_ok()); assert!(std::fs::write(&path, vec![b'x'; CREDENTIAL_BYTES_MAX + 1]).is_ok()); assert_eq!( store .load(ProviderKind::OpenAiCompatible) .err() .map(|error| error.code().to_string()), Some("AUTH_STORE".to_string()) ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn store_io_failures_other_than_absence_surface() { let dir = scratch("store_io_failures"); // A directory where the provider file belongs: read and unlink fail. assert!(std::fs::create_dir_all(dir.join(ProviderKind::Plugin.slug())).is_ok()); let store = AuthStore::at(&dir); let check = |result: smith::error::Result<()>, operation: &str, path: &Path| { let error = result.expect_err("filesystem fault"); assert_eq!(error.code(), "AUTH_STORE"); assert!(error.to_string().contains("storage [AUTH_STORE]")); assert!(!error.to_string().contains("credential-secret")); match &error { smith::error::SmithError::Storage { code, operation: actual_operation, path: actual_path, message, .. } => { assert_eq!(*code, smith::error::StorageCode::AuthStore); assert_eq!(actual_operation.as_str(), operation); assert_eq!(actual_path, path); assert!(!message.contains("credential-secret")); let serialized = serde_json::to_value(&error).expect("serialize error"); assert_eq!(serialized["Storage"]["code"], "AUTH_STORE"); assert_eq!( serialized["Storage"]["path"], path.to_string_lossy().as_ref() ); assert!(!serialized.to_string().contains("credential-secret")); } other => panic!("expected storage error, got {other:?}"), } }; let provider_path = dir.join(ProviderKind::Plugin.slug()); check( store.load(ProviderKind::Plugin).map(drop), "read_to_string", &provider_path, ); check( store.remove(ProviderKind::Plugin).map(drop), "remove_file", &provider_path, ); // A file where the store directory belongs: listing fails. let file = dir.join("not-a-dir"); assert!(std::fs::write(&file, "").is_ok()); check(AuthStore::at(&file).list().map(drop), "read_dir", &file); // A file parent deterministically blocks store directory creation. let blocked = dir.join("blocked"); assert!(std::fs::write(&blocked, "").is_ok()); let attempted_dir = blocked.join("auth"); check( AuthStore::at(&attempted_dir).save(ProviderKind::Plugin, "credential-secret"), "create_dir_all", &attempted_dir, ); let _ = std::fs::remove_dir_all(&dir); } #[cfg(unix)] #[test] fn saved_credentials_are_user_only() { use std::os::unix::fs::PermissionsExt; let dir = scratch("store_permissions"); let store = AuthStore::at(&dir); assert!(store.save(ProviderKind::Anthropic, "a").is_ok()); let mode = std::fs::metadata(dir.join(ProviderKind::Anthropic.slug())) .map(|meta| meta.permissions().mode() & 0o777) .ok(); assert_eq!(mode, Some(0o600)); let _ = std::fs::remove_dir_all(&dir); } #[test] fn interleaved_updates_preserve_unrelated_providers() { let mut registry = AuthRegistry::new(); registry.set("anthropic", Credential::explicit("a")); registry.set("openai", Credential::explicit("o")); for round in 0..100 { registry.set("anthropic", Credential::explicit(format!("a{round}"))); assert!(registry.is_ready("openai")); assert!(registry.is_ready("anthropic")); } assert_eq!( registry.get("openai").map(Credential::describe), Some("explicit:".to_string()) ); } }