返回 CodeWhale
lib.rs
根目录 / crates / secrets / src / lib.rs
1 //! Secret storage for CodeWhale API keys, plus the shared output-sanitization
2 //! primitives that keep secrets out of diagnostics and command output.
3 //!
4 //! Secret storage: provides a small abstraction (`KeyringStore`) plus a default
5 //! file-based implementation (`FileKeyringStore`), an opt-in OS keyring
6 //! implementation (`DefaultKeyringStore`), and an in-memory store for tests
7 //! (`InMemoryKeyringStore`).
8 //!
9 //! Higher-level lookup through [`Secrets::resolve`] checks the secret store first
10 //! and falls back to environment variables. Config-file precedence lives in the
11 //! config crate so user-facing commands can keep `config -> secret store -> env`
12 //! explicit at the call site.
13 //!
14 //! Pure sanitization is implemented in `codewhale-sanitize`. The re-exports
15 //! here preserve existing storage consumers' public paths; portable callers
16 //! depend directly on that leaf crate and do not inherit credential backends.
17 #![deny(missing_docs)]
18
19 /// Shared secure-storage contract for the Codewhale account session.
20 pub mod account;
21 mod file_lock;
22 #[cfg(test)]
23 mod file_transactions_tests;
24 /// Pure secret-redaction primitives shared by config diagnostics and the
25 /// portable command sanitizer (FEAT-025 D4).
26 pub use codewhale_sanitize::redact;
27 /// Pure text/URL/ANSI output sanitization shared by the portable command
28 /// helpers (FEAT-025 D4).
29 pub use codewhale_sanitize::sanitize;
30
31 use std::collections::HashMap;
32 use std::fs;
33 use std::path::{Path, PathBuf};
34 use std::sync::{Arc, Mutex};
35
36 use codewhale_paths::codewhale_home_is_explicit;
37
38 const MAX_SECRETS_FILE_BYTES: u64 = 4 * 1024 * 1024;
39 use serde::{Deserialize, Serialize};
40 use thiserror::Error;
41
42 /// Default OS keychain service name. Kept as `deepseek` for compatibility
43 /// with credentials saved before the CodeWhale rename. macOS users can verify
44 /// entries with `security find-generic-password -s deepseek -a <provider>`.
45 pub const DEFAULT_SERVICE: &str = "deepseek";
46 /// On-disk slot name of the retired sandbox token; logout deletes it.
47 pub const LEGACY_SANDBOX_TOKEN_SLOT: &str = "daytona";
48 /// Select the secret storage backend. Supported values are `file` (default)
49 /// and `system`/`keyring` for the OS credential store.
50 pub const SECRET_BACKEND_ENV: &str = "CODEWHALE_SECRET_BACKEND";
51 /// Legacy alias for [`SECRET_BACKEND_ENV`].
52 pub const LEGACY_SECRET_BACKEND_ENV: &str = "DEEPSEEK_SECRET_BACKEND";
53 const FILE_BACKEND_LABEL: &str = "file-based (~/.codewhale/secrets/)";
54
55 /// Errors that may arise from a [`KeyringStore`] backend.
56 #[derive(Debug, Error)]
57 pub enum SecretsError {
58 /// Underlying OS keyring backend reported an error.
59 #[error("keyring backend error: {0}")]
60 Keyring(String),
61 /// File-backed fallback I/O error.
62 #[error("file-backed secret store I/O error: {0}")]
63 Io(#[from] std::io::Error),
64 /// File-backed fallback JSON (de)serialisation error.
65 #[error("file-backed secret store JSON error: {0}")]
66 Json(#[from] serde_json::Error),
67 /// Caught when a stored secret on disk has unsafe permissions.
68 #[error("file-backed secret store at {path} has insecure permissions {mode:o} (expected 0600)")]
69 InsecurePermissions {
70 /// Absolute path to the secrets file.
71 path: PathBuf,
72 /// Observed unix permission mode.
73 mode: u32,
74 },
75 /// A caller attempted to modify a diagnostic-only secret store.
76 #[error("secret store is read-only")]
77 ReadOnly,
78 }
79
80 /// Abstract secret store trait.
81 ///
82 /// Concrete implementations may use the OS keyring ([`DefaultKeyringStore`]),
83 /// a JSON file under `~/.codewhale/secrets/` ([`FileKeyringStore`]), or an
84 /// in-memory map for tests ([`InMemoryKeyringStore`]).
85 ///
86 /// All implementations must be [`Send`] + [`Sync`] so they can be shared
87 /// across threads via [`Arc`].
88 pub trait KeyringStore: Send + Sync {
89 /// Read a secret by key.
90 ///
91 /// Returns `Ok(None)` if no entry exists for the given key. Returns
92 /// `Err` only on backend failures (I/O errors, keyring access issues).
93 fn get(&self, key: &str) -> Result<Option<String>, SecretsError>;
94
95 /// Write a secret, replacing any existing value for the same key.
96 ///
97 /// Creates the backing store (e.g. the JSON file) on first write if
98 /// it does not yet exist.
99 fn set(&self, key: &str, value: &str) -> Result<(), SecretsError>;
100
101 /// Remove a secret by key.
102 ///
103 /// Implementations should succeed (no-op) if the entry is already absent
104 /// rather than returning an error.
105 fn delete(&self, key: &str) -> Result<(), SecretsError>;
106
107 /// Run a non-reentrant entry mutation while holding the backend's authority
108 /// lock. Errors must leave the stored entry unchanged.
109 fn with_entry_transaction(
110 &self,
111 _key: &str,
112 _operation: &mut dyn FnMut(&mut Option<String>) -> Result<(), SecretsError>,
113 ) -> Result<(), SecretsError> {
114 Err(SecretsError::Keyring(
115 "This secret backend does not support atomic updates".into(),
116 ))
117 }
118
119 /// Replace an entry only while its exact bytes still match a snapshot.
120 fn compare_exchange(
121 &self,
122 key: &str,
123 expected: Option<&str>,
124 replacement: Option<&str>,
125 ) -> Result<bool, SecretsError> {
126 let mut changed = false;
127 self.with_entry_transaction(key, &mut |current| {
128 if current.as_deref() == expected {
129 *current = replacement.map(str::to_owned);
130 changed = true;
131 }
132 Ok(())
133 })?;
134 Ok(changed)
135 }
136
137 /// Short, human-readable label for this backend.
138 ///
139 /// Used by diagnostic output (e.g. `doctor` command) to indicate which
140 /// storage backend is active. Examples: `"file-based (~/.codewhale/secrets/)"`,
141 /// `"system keyring"`, `"in-memory (test)"`.
142 fn backend_name(&self) -> &'static str;
143 }
144
145 /// OS-native keyring backend.
146 ///
147 /// Wraps the platform credential store:
148 /// - **macOS**: Keychain (via `security` framework)
149 /// - **Windows**: Credential Manager
150 /// - **Linux**: Secret Service (GNOME Keyring / kwallet via dbus), excluding OHOS
151 ///
152 /// This backend is opt-in -- set the [`SECRET_BACKEND_ENV`] environment
153 /// variable to `system` or `keyring` to activate it. On platforms without
154 /// a configured native keyring dependency, [`probe`](DefaultKeyringStore::probe)
155 /// returns an unsupported error so [`Secrets::auto_detect`] can transparently
156 /// fall back to [`FileKeyringStore`].
157 #[derive(Debug, Clone)]
158 pub struct DefaultKeyringStore {
159 /// Keyring service name used to namespace stored credentials.
160 /// Defaults to [`DEFAULT_SERVICE`].
161 service: String,
162 }
163
164 impl Default for DefaultKeyringStore {
165 fn default() -> Self {
166 Self::new(DEFAULT_SERVICE)
167 }
168 }
169
170 impl DefaultKeyringStore {
171 /// Build a new store with the given service name.
172 #[must_use]
173 pub fn new(service: impl Into<String>) -> Self {
174 Self {
175 service: service.into(),
176 }
177 }
178
179 /// Probe the OS keyring without writing anything. Returns `Ok(())` if
180 /// a backend is reachable, otherwise an error describing why not.
181 ///
182 /// The probe reads a deliberately-nonexistent entry: reaching the
183 /// backend and learning the entry is absent *is* the reachability
184 /// signal. This does not prompt on any supported platform — macOS only
185 /// surfaces Keychain UI when accessing an *existing* item owned by
186 /// another application, and Windows Credential Manager never prompts
187 /// for a missing target — so `__probe__` under our own service name is
188 /// safe to read. `Entry::new` alone validates only argument shapes,
189 /// which left this probe a no-op on macOS/Windows and the documented
190 /// file-store fallback unreachable there (#5172).
191 pub fn probe(&self) -> Result<(), SecretsError> {
192 #[cfg(any(
193 target_os = "macos",
194 target_os = "windows",
195 all(
196 target_os = "linux",
197 not(target_env = "ohos"),
198 not(target_env = "musl")
199 )
200 ))]
201 {
202 let entry = keyring::Entry::new(&self.service, "__probe__")
203 .map_err(|err| SecretsError::Keyring(err.to_string()))?;
204 match entry.get_password() {
205 Ok(_) | Err(keyring::Error::NoEntry) => Ok(()),
206 Err(keyring::Error::PlatformFailure(err)) => {
207 Err(SecretsError::Keyring(format!("platform failure: {err}")))
208 }
209 Err(keyring::Error::NoStorageAccess(err)) => {
210 Err(SecretsError::Keyring(format!("no storage access: {err}")))
211 }
212 Err(other) => Err(SecretsError::Keyring(other.to_string())),
213 }
214 }
215 #[cfg(not(any(
216 target_os = "macos",
217 target_os = "windows",
218 all(
219 target_os = "linux",
220 not(target_env = "ohos"),
221 not(target_env = "musl")
222 )
223 )))]
224 {
225 let _ = &self.service;
226 Err(SecretsError::Keyring(unsupported_keyring_message()))
227 }
228 }
229 }
230
231 impl DefaultKeyringStore {
232 fn get_unlocked(&self, key: &str) -> Result<Option<String>, SecretsError> {
233 #[cfg(any(
234 target_os = "macos",
235 target_os = "windows",
236 all(
237 target_os = "linux",
238 not(target_env = "ohos"),
239 not(target_env = "musl")
240 )
241 ))]
242 {
243 let entry = keyring::Entry::new(&self.service, key)
244 .map_err(|err| SecretsError::Keyring(err.to_string()))?;
245 match entry.get_password() {
246 Ok(value) => Ok(Some(value)),
247 Err(keyring::Error::NoEntry) => Ok(None),
248 Err(err) => Err(SecretsError::Keyring(err.to_string())),
249 }
250 }
251 #[cfg(not(any(
252 target_os = "macos",
253 target_os = "windows",
254 all(
255 target_os = "linux",
256 not(target_env = "ohos"),
257 not(target_env = "musl")
258 )
259 )))]
260 {
261 let _ = key;
262 Err(SecretsError::Keyring(unsupported_keyring_message()))
263 }
264 }
265
266 fn set_unlocked(&self, key: &str, value: &str) -> Result<(), SecretsError> {
267 #[cfg(any(
268 target_os = "macos",
269 target_os = "windows",
270 all(
271 target_os = "linux",
272 not(target_env = "ohos"),
273 not(target_env = "musl")
274 )
275 ))]
276 {
277 let entry = keyring::Entry::new(&self.service, key)
278 .map_err(|err| SecretsError::Keyring(err.to_string()))?;
279 entry
280 .set_password(value)
281 .map_err(|err| SecretsError::Keyring(err.to_string()))
282 }
283 #[cfg(not(any(
284 target_os = "macos",
285 target_os = "windows",
286 all(
287 target_os = "linux",
288 not(target_env = "ohos"),
289 not(target_env = "musl")
290 )
291 )))]
292 {
293 let _ = (key, value);
294 Err(SecretsError::Keyring(unsupported_keyring_message()))
295 }
296 }
297
298 fn delete_unlocked(&self, key: &str) -> Result<(), SecretsError> {
299 #[cfg(any(
300 target_os = "macos",
301 target_os = "windows",
302 all(
303 target_os = "linux",
304 not(target_env = "ohos"),
305 not(target_env = "musl")
306 )
307 ))]
308 {
309 let entry = keyring::Entry::new(&self.service, key)
310 .map_err(|err| SecretsError::Keyring(err.to_string()))?;
311 match entry.delete_credential() {
312 Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
313 Err(err) => Err(SecretsError::Keyring(err.to_string())),
314 }
315 }
316 #[cfg(not(any(
317 target_os = "macos",
318 target_os = "windows",
319 all(
320 target_os = "linux",
321 not(target_env = "ohos"),
322 not(target_env = "musl")
323 )
324 )))]
325 {
326 let _ = key;
327 Err(SecretsError::Keyring(unsupported_keyring_message()))
328 }
329 }
330 }
331
332 impl DefaultKeyringStore {
333 fn with_key_lock<T>(
334 &self,
335 key: &str,
336 operation: impl FnOnce() -> Result<T, SecretsError>,
337 ) -> Result<T, SecretsError> {
338 use sha2::{Digest, Sha256};
339 // OS keyring authority is per user, not per CODEWHALE_HOME/profile.
340 let home = codewhale_paths::user_home()
341 .filter(|p| p.is_absolute())
342 .ok_or_else(home_resolution_error)?;
343 let mut digest = Sha256::new();
344 digest.update(self.service.as_bytes());
345 digest.update([0]);
346 digest.update(key.as_bytes());
347 let path = home.join(".codewhale").join("keyring-locks").join(
348 digest
349 .finalize()
350 .iter()
351 .map(|byte| format!("{byte:02x}"))
352 .collect::<String>(),
353 );
354 file_lock::with_write_lock(&path, |_| operation())
355 }
356 }
357
358 impl KeyringStore for DefaultKeyringStore {
359 fn get(&self, key: &str) -> Result<Option<String>, SecretsError> {
360 self.get_unlocked(key)
361 }
362 fn set(&self, key: &str, value: &str) -> Result<(), SecretsError> {
363 self.with_key_lock(key, || self.set_unlocked(key, value))
364 }
365 fn delete(&self, key: &str) -> Result<(), SecretsError> {
366 self.with_key_lock(key, || self.delete_unlocked(key))
367 }
368 fn with_entry_transaction(
369 &self,
370 key: &str,
371 operation: &mut dyn FnMut(&mut Option<String>) -> Result<(), SecretsError>,
372 ) -> Result<(), SecretsError> {
373 self.with_key_lock(key, || {
374 let before = self.get_unlocked(key)?;
375 let mut current = before.clone();
376 operation(&mut current)?;
377 if current != before {
378 match current {
379 Some(value) => self.set_unlocked(key, &value)?,
380 None => self.delete_unlocked(key)?,
381 }
382 }
383 Ok(())
384 })
385 }
386
387 fn backend_name(&self) -> &'static str {
388 "system keyring"
389 }
390 }
391
392 #[cfg(not(any(
393 target_os = "macos",
394 target_os = "windows",
395 all(
396 target_os = "linux",
397 not(target_env = "ohos"),
398 not(target_env = "musl")
399 )
400 )))]
401 fn unsupported_keyring_message() -> String {
402 "system keyring backend is unsupported on this platform".to_string()
403 }
404
405 /// In-memory keyring store for tests.
406 ///
407 /// Stores secrets in a [`HashMap`] protected by a [`Mutex`]. Not persisted
408 /// to disk -- all entries are lost when the process exits. This is the
409 /// preferred store for unit tests because it requires no filesystem setup
410 /// and is safe to use in parallel test threads.
411 #[derive(Debug, Default)]
412 pub struct InMemoryKeyringStore {
413 /// Thread-safe map of key-value pairs.
414 entries: Mutex<HashMap<String, String>>,
415 }
416
417 impl InMemoryKeyringStore {
418 /// Create an empty store.
419 #[must_use]
420 pub fn new() -> Self {
421 Self::default()
422 }
423 }
424
425 impl KeyringStore for InMemoryKeyringStore {
426 fn get(&self, key: &str) -> Result<Option<String>, SecretsError> {
427 let guard = self.entries.lock().map_err(|e| {
428 SecretsError::Keyring(format!("InMemoryKeyringStore mutex poisoned: {e}"))
429 })?;
430 Ok(guard.get(key).cloned())
431 }
432
433 fn set(&self, key: &str, value: &str) -> Result<(), SecretsError> {
434 let mut guard = self.entries.lock().map_err(|e| {
435 SecretsError::Keyring(format!("InMemoryKeyringStore mutex poisoned: {e}"))
436 })?;
437 guard.insert(key.to_string(), value.to_string());
438 Ok(())
439 }
440
441 fn delete(&self, key: &str) -> Result<(), SecretsError> {
442 let mut guard = self.entries.lock().map_err(|e| {
443 SecretsError::Keyring(format!("InMemoryKeyringStore mutex poisoned: {e}"))
444 })?;
445 guard.remove(key);
446 Ok(())
447 }
448
449 fn with_entry_transaction(
450 &self,
451 key: &str,
452 operation: &mut dyn FnMut(&mut Option<String>) -> Result<(), SecretsError>,
453 ) -> Result<(), SecretsError> {
454 let mut entries = self
455 .entries
456 .lock()
457 .map_err(|_| SecretsError::Keyring("Secret store lock poisoned".into()))?;
458 let mut current = entries.get(key).cloned();
459 operation(&mut current)?;
460 match current {
461 Some(value) => {
462 entries.insert(key.into(), value);
463 }
464 None => {
465 entries.remove(key);
466 }
467 }
468 Ok(())
469 }
470
471 fn backend_name(&self) -> &'static str {
472 "in-memory (test)"
473 }
474 }
475
476 /// JSON-on-disk secret store for headless environments.
477 ///
478 /// This is the default backend. Secrets are serialised as a JSON object
479 /// at `<home>/.codewhale/secrets/secrets.json` with Unix file mode `0600`
480 /// (owner read/write only). The parent directory is created with mode `0700`
481 /// if it does not exist.
482 ///
483 /// On Unix, the store rejects files whose permissions are more permissive
484 /// than `0600` (i.e. group or world bits are set). This prevents other
485 /// users on the system from reading stored credentials. On Windows, the
486 /// ACL model is too different to enforce programmatically; callers are
487 /// responsible for placing the file in a per-user directory.
488 #[derive(Debug, Clone)]
489 pub struct FileKeyringStore {
490 /// Absolute path to the JSON secrets file.
491 path: PathBuf,
492 }
493
494 /// File-backed secret lookup that never migrates or changes either store.
495 ///
496 /// Normal runtime credential resolution keeps its additive legacy migration:
497 /// older entries under `~/.deepseek/secrets/` are copied into the Codewhale
498 /// location before use. Diagnostic commands need the same read precedence
499 /// without creating that destination, so this store reads the primary file
500 /// first and falls back to the legacy file only when the primary has no entry
501 /// and the Codewhale home is not explicitly isolated.
502 #[derive(Debug, Clone)]
503 struct ReadOnlyFileKeyringStore {
504 primary: FileKeyringStore,
505 /// The ambient legacy store is unavailable when `CODEWHALE_HOME` is an
506 /// explicit isolation boundary.
507 legacy: Option<FileKeyringStore>,
508 }
509
510 #[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
511 struct FileSecretsBlob {
512 #[serde(default)]
513 entries: HashMap<String, String>,
514 /// Set once the legacy `~/.deepseek` store has been copied into this one.
515 /// The copy is one-shot: afterwards a key the user deletes here stays
516 /// deleted instead of being re-imported from the legacy file on the next
517 /// launch, and read-only lookup stops falling back to the legacy file.
518 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
519 legacy_deepseek_migrated: bool,
520 #[serde(flatten)]
521 extra: serde_json::Map<String, serde_json::Value>,
522 }
523
524 impl FileKeyringStore {
525 /// Build a store backed by the given JSON file path.
526 #[must_use]
527 pub fn new(path: impl Into<PathBuf>) -> Self {
528 Self { path: path.into() }
529 }
530
531 /// Default path: `<home>/.codewhale/secrets/secrets.json`. Honours
532 /// `CODEWHALE_HOME`, then `HOME`, `USERPROFILE`, and finally the platform
533 /// home directory from the `dirs` crate. On first use, non-conflicting
534 /// entries from the legacy `<home>/.deepseek/secrets/secrets.json` file are
535 /// copied into the CodeWhale store — unless `CODEWHALE_HOME` is explicit,
536 /// in which case ambient `$HOME/.deepseek` credentials are never imported.
537 pub fn default_path() -> Result<PathBuf, SecretsError> {
538 let primary = default_codewhale_secrets_path()?;
539 // Match the diagnostic isolation boundary: an explicit Codewhale home
540 // must not silently pull ambient legacy DeepSeek credentials.
541 if !codewhale_home_is_explicit() {
542 match legacy_deepseek_secrets_path() {
543 Ok(legacy) => {
544 if let Err(err) = Self::migrate_legacy_file_if_needed(&primary, &legacy) {
545 tracing::warn!(
546 "could not migrate legacy secret store from {} to {}: {err}",
547 legacy.display(),
548 primary.display()
549 );
550 }
551 }
552 Err(err) => {
553 tracing::warn!("could not resolve legacy secret store path: {err}");
554 }
555 }
556 }
557 Ok(primary)
558 }
559
560 /// Resolve the primary and legacy secret paths without performing legacy
561 /// migration.
562 ///
563 /// This is intended for diagnostic-only lookup. Runtime and authentication
564 /// flows must keep using [`Self::default_path`] so their existing additive
565 /// migration behavior remains unchanged.
566 pub fn default_paths_read_only() -> Result<(PathBuf, Option<PathBuf>), SecretsError> {
567 let primary = default_codewhale_secrets_path()?;
568 let legacy = (!codewhale_home_is_explicit())
569 .then(legacy_deepseek_secrets_path)
570 .transpose()?;
571 Ok((primary, legacy))
572 }
573
574 fn migrate_legacy_file_if_needed(primary: &Path, legacy: &Path) -> Result<(), SecretsError> {
575 if !legacy.exists() {
576 return Ok(());
577 }
578
579 let primary_store = Self::new(primary.to_path_buf());
580 if primary_store.load_unlocked()?.legacy_deepseek_migrated {
581 return Ok(());
582 }
583
584 let legacy_store = Self::new(legacy.to_path_buf());
585 let legacy_blob = legacy_store.load_unlocked()?;
586 if legacy_blob.entries.is_empty() {
587 return Ok(());
588 }
589
590 primary_store.mutate(|primary_blob| {
591 // Re-check under the write lock: a concurrent process may have
592 // completed the copy, and the user may since have deleted keys.
593 if primary_blob.legacy_deepseek_migrated {
594 return Ok(());
595 }
596 for (key, value) in legacy_blob.entries {
597 primary_blob.entries.entry(key).or_insert(value);
598 }
599 primary_blob.legacy_deepseek_migrated = true;
600 Ok(())
601 })
602 }
603
604 fn mutate<T>(
605 &self,
606 operation: impl FnOnce(&mut FileSecretsBlob) -> Result<T, SecretsError>,
607 ) -> Result<T, SecretsError> {
608 file_lock::with_write_lock(&self.path, |path| {
609 let store = Self::new(path);
610 let mut blob = store.load_unlocked()?;
611 let original = serde_json::to_vec(&blob)?;
612 let result = operation(&mut blob)?;
613 if serde_json::to_vec(&blob)? != original {
614 store.store_unlocked(&blob)?;
615 }
616 Ok(result)
617 })
618 }
619
620 /// Path used for storage.
621 #[must_use]
622 pub fn path(&self) -> &Path {
623 &self.path
624 }
625
626 fn load_unlocked(&self) -> Result<FileSecretsBlob, SecretsError> {
627 use std::io::Read as _;
628 let file = match file_lock::open_private(&self.path, false, file_lock::StoreFile::Content) {
629 Ok(file) => file,
630 Err(SecretsError::Io(error)) if error.kind() == std::io::ErrorKind::NotFound => {
631 return Ok(FileSecretsBlob::default());
632 }
633 Err(error) => return Err(error),
634 };
635 let mut raw = String::new();
636 file.take(MAX_SECRETS_FILE_BYTES + 1)
637 .read_to_string(&mut raw)?;
638 if raw.len() as u64 > MAX_SECRETS_FILE_BYTES {
639 return Err(SecretsError::Io(std::io::Error::new(
640 std::io::ErrorKind::InvalidData,
641 format!(
642 "secrets file {} exceeds {MAX_SECRETS_FILE_BYTES} bytes",
643 self.path.display()
644 ),
645 )));
646 }
647 if raw.trim().is_empty() {
648 return Ok(FileSecretsBlob::default());
649 }
650 let blob: FileSecretsBlob = serde_json::from_str(&raw)?;
651 Ok(blob)
652 }
653
654 fn store_unlocked(&self, blob: &FileSecretsBlob) -> Result<(), SecretsError> {
655 if let Some(parent) = self.path.parent() {
656 fs::create_dir_all(parent)?;
657 #[cfg(unix)]
658 {
659 use std::os::unix::fs::PermissionsExt;
660 let mut perms = fs::metadata(parent)?.permissions();
661 perms.set_mode(0o700);
662 let _ = fs::set_permissions(parent, perms);
663 }
664 }
665 let body = serde_json::to_string_pretty(blob)?;
666 if body.len() as u64 > MAX_SECRETS_FILE_BYTES {
667 return Err(SecretsError::Io(std::io::Error::new(
668 std::io::ErrorKind::InvalidInput,
669 format!(
670 "secrets file {} would exceed {MAX_SECRETS_FILE_BYTES} bytes",
671 self.path.display()
672 ),
673 )));
674 }
675 write_private_file(&self.path, body.as_bytes())?;
676 #[cfg(unix)]
677 {
678 use std::os::unix::fs::PermissionsExt;
679 // Best-effort 0o600 — matches the parent-dir chmod above which
680 // is also `let _ = ...`. Filesystems that don't support Unix
681 // chmod (Docker bind-mounts of NTFS, network shares — #897)
682 // would otherwise fail the whole save here even though the
683 // blob already wrote successfully. The host's native ACLs
684 // are doing access control in those environments.
685 if let Ok(meta) = fs::metadata(&self.path) {
686 let mut perms = meta.permissions();
687 perms.set_mode(0o600);
688 let _ = fs::set_permissions(&self.path, perms);
689 }
690 }
691 Ok(())
692 }
693 }
694
695 impl ReadOnlyFileKeyringStore {
696 fn default_for_diagnostics() -> Result<Self, SecretsError> {
697 let (primary, legacy) = FileKeyringStore::default_paths_read_only()?;
698 Ok(Self::new(primary, legacy))
699 }
700
701 fn new(primary: impl Into<PathBuf>, legacy: Option<PathBuf>) -> Self {
702 Self {
703 primary: FileKeyringStore::new(primary),
704 legacy: legacy.map(FileKeyringStore::new),
705 }
706 }
707 }
708
709 impl KeyringStore for ReadOnlyFileKeyringStore {
710 fn get(&self, key: &str) -> Result<Option<String>, SecretsError> {
711 let primary = self.primary.load_unlocked()?;
712 if let Some(value) = primary.entries.get(key) {
713 return Ok(Some(value.clone()));
714 }
715 // Once the legacy store has been migrated, a key absent from the
716 // primary was deleted there; the legacy copy is stale, not a fallback.
717 if primary.legacy_deepseek_migrated {
718 return Ok(None);
719 }
720 self.legacy
721 .as_ref()
722 .map_or(Ok(None), |legacy| legacy.get(key))
723 }
724
725 fn set(&self, _key: &str, _value: &str) -> Result<(), SecretsError> {
726 Err(SecretsError::ReadOnly)
727 }
728
729 fn delete(&self, _key: &str) -> Result<(), SecretsError> {
730 Err(SecretsError::ReadOnly)
731 }
732
733 fn backend_name(&self) -> &'static str {
734 FILE_BACKEND_LABEL
735 }
736 }
737
738 #[derive(Clone)]
739 struct ReadOnlyKeyringStore {
740 inner: Arc<dyn KeyringStore>,
741 }
742
743 impl ReadOnlyKeyringStore {
744 fn new(inner: Arc<dyn KeyringStore>) -> Self {
745 Self { inner }
746 }
747 }
748
749 impl KeyringStore for ReadOnlyKeyringStore {
750 fn get(&self, key: &str) -> Result<Option<String>, SecretsError> {
751 self.inner.get(key)
752 }
753
754 fn set(&self, _key: &str, _value: &str) -> Result<(), SecretsError> {
755 Err(SecretsError::ReadOnly)
756 }
757
758 fn delete(&self, _key: &str) -> Result<(), SecretsError> {
759 Err(SecretsError::ReadOnly)
760 }
761
762 fn backend_name(&self) -> &'static str {
763 self.inner.backend_name()
764 }
765 }
766
767 fn write_private_file(path: &Path, body: &[u8]) -> Result<(), SecretsError> {
768 atomic_write_private_file(path, body)
769 }
770
771 fn atomic_write_private_file(path: &Path, body: &[u8]) -> Result<(), SecretsError> {
772 #[cfg(unix)]
773 {
774 atomic_write_private_file_with_dir_sync(path, body, fs::File::sync_all)
775 }
776 #[cfg(not(unix))]
777 {
778 persist_private_temp_file(path, body).map(|_| ())
779 }
780 }
781
782 fn persist_private_temp_file(path: &Path, body: &[u8]) -> Result<PathBuf, SecretsError> {
783 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
784 fs::create_dir_all(parent)?;
785 }
786 let dir = path
787 .parent()
788 .filter(|p| !p.as_os_str().is_empty())
789 .unwrap_or_else(|| Path::new("."));
790 let mut tmp = tempfile::NamedTempFile::new_in(dir).map_err(SecretsError::Io)?;
791 use std::io::Write as _;
792 tmp.write_all(body).map_err(SecretsError::Io)?;
793 tmp.flush().map_err(SecretsError::Io)?;
794 tmp.as_file().sync_all().map_err(SecretsError::Io)?;
795 // The temp file is created at 0o600, so this is not about narrowing it: a
796 // mount can apply a mode of its own to a new file, and publishing contents
797 // under one is exactly what the store's own gate exists to prevent. The
798 // same rule that admits the store admits the file about to replace it.
799 #[cfg(unix)]
800 file_lock::require_private_mode(tmp.as_file(), path, file_lock::StoreFile::Content)?;
801 tmp.persist(path).map_err(|e| SecretsError::Io(e.error))?;
802 Ok(dir.to_path_buf())
803 }
804
805 #[cfg(unix)]
806 fn atomic_write_private_file_with_dir_sync(
807 path: &Path,
808 body: &[u8],
809 sync_dir: impl FnOnce(&fs::File) -> std::io::Result<()>,
810 ) -> Result<(), SecretsError> {
811 use std::os::unix::fs::OpenOptionsExt as _;
812
813 let dir = persist_private_temp_file(path, body)?;
814 // Best-effort directory sync so a committed replacement is not reported as a failed write.
815 let _ = fs::OpenOptions::new()
816 .read(true)
817 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
818 .open(&dir)
819 .and_then(|dir_file| sync_dir(&dir_file));
820 Ok(())
821 }
822
823 impl KeyringStore for FileKeyringStore {
824 fn get(&self, key: &str) -> Result<Option<String>, SecretsError> {
825 let blob = self.load_unlocked()?;
826 Ok(blob.entries.get(key).cloned())
827 }
828
829 fn set(&self, key: &str, value: &str) -> Result<(), SecretsError> {
830 self.mutate(|blob| {
831 account::invalidate_device_companion(&mut blob.entries, key, Some(value));
832 blob.entries.insert(key.to_string(), value.to_string());
833 Ok(())
834 })
835 }
836
837 fn delete(&self, key: &str) -> Result<(), SecretsError> {
838 self.mutate(|blob| {
839 account::invalidate_device_companion(&mut blob.entries, key, None);
840 blob.entries.remove(key);
841 Ok(())
842 })
843 }
844
845 fn with_entry_transaction(
846 &self,
847 key: &str,
848 operation: &mut dyn FnMut(&mut Option<String>) -> Result<(), SecretsError>,
849 ) -> Result<(), SecretsError> {
850 self.mutate(|blob| {
851 let before = blob.entries.get(key).cloned();
852 let mut current = before.clone();
853 operation(&mut current)?;
854 if current != before {
855 account::invalidate_device_companion(&mut blob.entries, key, current.as_deref());
856 match current {
857 Some(value) => {
858 blob.entries.insert(key.into(), value);
859 }
860 None => {
861 blob.entries.remove(key);
862 }
863 }
864 }
865 Ok(())
866 })
867 }
868
869 fn backend_name(&self) -> &'static str {
870 FILE_BACKEND_LABEL
871 }
872 }
873
874 fn default_codewhale_secrets_path() -> Result<PathBuf, SecretsError> {
875 Ok(codewhale_paths::codewhale_home()
876 .map_err(|error| {
877 SecretsError::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, error))
878 })?
879 .ok_or_else(home_resolution_error)?
880 .join("secrets")
881 .join("secrets.json"))
882 }
883
884 fn legacy_deepseek_secrets_path() -> Result<PathBuf, SecretsError> {
885 Ok(codewhale_paths::legacy_deepseek_home()
886 .ok_or_else(home_resolution_error)?
887 .join("secrets")
888 .join("secrets.json"))
889 }
890
891 fn home_resolution_error() -> SecretsError {
892 SecretsError::Io(std::io::Error::new(
893 std::io::ErrorKind::NotFound,
894 "could not resolve home directory for FileKeyringStore",
895 ))
896 }
897
898 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
899 enum SecretBackendSelection {
900 File,
901 System,
902 Unknown,
903 }
904
905 /// Secret-store backend selected by configuration for a structural diagnostic.
906 ///
907 /// This type deliberately describes only configuration and filesystem shape.
908 /// It never implies that a provider credential exists.
909 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
910 #[serde(rename_all = "snake_case")]
911 pub enum SecretBackendDiagnosticKind {
912 /// The JSON file store is selected.
913 File,
914 /// The operating-system credential store is selected.
915 System,
916 /// The configured backend value is unsupported.
917 Unknown,
918 }
919
920 /// Whether a secret-store path is present according to metadata only.
921 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
922 #[serde(rename_all = "snake_case")]
923 pub enum SecretBackendPresence {
924 /// A regular file exists at the resolved path.
925 Present,
926 /// No filesystem entry exists at the resolved path.
927 Absent,
928 /// Presence is unavailable or the entry is not a regular file.
929 Unknown,
930 }
931
932 /// Scope of inspection performed for a structural secret-backend diagnostic.
933 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
934 #[serde(rename_all = "snake_case")]
935 pub enum SecretBackendInspection {
936 /// Only filesystem metadata was inspected; file contents were not opened.
937 MetadataOnly,
938 /// The backend was not constructed, probed, or read.
939 NotProbed,
940 }
941
942 /// Secret-safe structural description of the configured credential backend.
943 ///
944 /// File-backed diagnostics expose resolved paths and regular-file presence from
945 /// metadata without opening either store. System backends intentionally report
946 /// `unknown` / `not_probed`: constructing or probing an OS keyring can show a
947 /// user prompt even when no credential value is requested.
948 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
949 pub struct SecretBackendDiagnostic {
950 /// Configured backend family.
951 pub backend: SecretBackendDiagnosticKind,
952 /// Inspection performed to produce this report.
953 pub inspection: SecretBackendInspection,
954 /// Canonical file-store path, when the file backend is selected.
955 pub path: Option<PathBuf>,
956 /// Metadata-only presence of the canonical file-store path.
957 pub presence: SecretBackendPresence,
958 /// Ambient legacy file-store path, suppressed by explicit `CODEWHALE_HOME`.
959 pub legacy_path: Option<PathBuf>,
960 /// Metadata-only presence of the legacy file-store path.
961 pub legacy_presence: SecretBackendPresence,
962 }
963
964 /// Describe the configured credential backend without probing or reading it.
965 ///
966 /// This function never constructs [`DefaultKeyringStore`], calls
967 /// [`KeyringStore::get`], opens a secret file, performs legacy migration, or
968 /// creates filesystem state. It is suitable for ordinary status and doctor
969 /// commands.
970 #[must_use]
971 pub fn diagnose_secret_backend() -> SecretBackendDiagnostic {
972 match secret_backend_selection(configured_secret_backend().as_deref()) {
973 SecretBackendSelection::File => {
974 let (path, legacy_path) = FileKeyringStore::default_paths_read_only()
975 .map(|(path, legacy)| (Some(path), legacy))
976 .unwrap_or((None, None));
977 SecretBackendDiagnostic {
978 backend: SecretBackendDiagnosticKind::File,
979 inspection: SecretBackendInspection::MetadataOnly,
980 presence: metadata_presence(path.as_deref()),
981 legacy_presence: metadata_presence(legacy_path.as_deref()),
982 path,
983 legacy_path,
984 }
985 }
986 SecretBackendSelection::System => SecretBackendDiagnostic {
987 backend: SecretBackendDiagnosticKind::System,
988 inspection: SecretBackendInspection::NotProbed,
989 path: None,
990 presence: SecretBackendPresence::Unknown,
991 legacy_path: None,
992 legacy_presence: SecretBackendPresence::Unknown,
993 },
994 SecretBackendSelection::Unknown => SecretBackendDiagnostic {
995 backend: SecretBackendDiagnosticKind::Unknown,
996 inspection: SecretBackendInspection::NotProbed,
997 path: None,
998 presence: SecretBackendPresence::Unknown,
999 legacy_path: None,
1000 legacy_presence: SecretBackendPresence::Unknown,
1001 },
1002 }
1003 }
1004
1005 fn metadata_presence(path: Option<&Path>) -> SecretBackendPresence {
1006 let Some(path) = path else {
1007 return SecretBackendPresence::Unknown;
1008 };
1009 if let Some(parent) = path.parent() {
1010 for ancestor in parent.ancestors() {
1011 if ancestor.as_os_str().is_empty() {
1012 continue;
1013 }
1014 match fs::symlink_metadata(ancestor) {
1015 Ok(metadata)
1016 if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() =>
1017 {
1018 return SecretBackendPresence::Unknown;
1019 }
1020 Ok(_) => {}
1021 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1022 return SecretBackendPresence::Absent;
1023 }
1024 Err(_) => return SecretBackendPresence::Unknown,
1025 }
1026 }
1027 }
1028 match fs::symlink_metadata(path) {
1029 Ok(metadata) if metadata.file_type().is_file() => SecretBackendPresence::Present,
1030 Ok(_) => SecretBackendPresence::Unknown,
1031 Err(error) if error.kind() == std::io::ErrorKind::NotFound => SecretBackendPresence::Absent,
1032 Err(_) => SecretBackendPresence::Unknown,
1033 }
1034 }
1035
1036 fn secret_backend_selection(value: Option<&str>) -> SecretBackendSelection {
1037 match value.map(str::trim).filter(|value| !value.is_empty()) {
1038 None => SecretBackendSelection::File,
1039 Some(value) => match value.to_ascii_lowercase().as_str() {
1040 "file" | "local" | "json" => SecretBackendSelection::File,
1041 "system" | "keyring" | "os" | "os-keyring" => SecretBackendSelection::System,
1042 _ => SecretBackendSelection::Unknown,
1043 },
1044 }
1045 }
1046
1047 fn configured_secret_backend() -> Option<String> {
1048 std::env::var(SECRET_BACKEND_ENV)
1049 .ok()
1050 .filter(|value| !value.trim().is_empty())
1051 .or_else(|| std::env::var(LEGACY_SECRET_BACKEND_ENV).ok())
1052 }
1053
1054 /// High-level facade combining a [`KeyringStore`] with environment variable fallbacks.
1055 ///
1056 /// Lookup precedence: **secret store -> env -> none**. Callers that also
1057 /// have a TOML config layer must wire that themselves at the very end
1058 /// of the chain (the config crate handles this).
1059 ///
1060 /// # Examples
1061 ///
1062 /// ```no_run
1063 /// use codewhale_secrets::Secrets;
1064 ///
1065 /// let secrets = Secrets::auto_detect();
1066 /// if let Some(key) = secrets.resolve("deepseek", &["DEEPSEEK_API_KEY"]) {
1067 /// // use the API key
1068 /// }
1069 /// ```
1070 #[derive(Clone)]
1071 pub struct Secrets {
1072 /// Underlying secret store backend.
1073 pub store: Arc<dyn KeyringStore>,
1074 /// Owner identifier within the secret store (typically `"deepseek"`).
1075 /// The `name` passed to [`resolve`](Secrets::resolve) is forwarded to
1076 /// the store as-is; the environment variables tried after it are the
1077 /// caller's list (see [`env_first`]).
1078 service: String,
1079 }
1080
1081 /// Identifies which layer in the resolution chain supplied a secret.
1082 ///
1083 /// Returned by [`Secrets::resolve_with_source`] so callers can
1084 /// distinguish whether a value came from the configured store or from
1085 /// a process environment variable.
1086 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1087 pub enum SecretSource {
1088 /// The secret was returned by the configured [`KeyringStore`] backend.
1089 Keyring,
1090 /// The secret was found in a process environment variable.
1091 Env,
1092 }
1093
1094 impl std::fmt::Debug for Secrets {
1095 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1096 f.debug_struct("Secrets")
1097 .field("backend", &self.store.backend_name())
1098 .field("service", &self.service)
1099 .finish()
1100 }
1101 }
1102
1103 impl Secrets {
1104 /// Build a new facade around the given store, using the
1105 /// [`DEFAULT_SERVICE`] service name.
1106 #[must_use]
1107 pub fn new(store: Arc<dyn KeyringStore>) -> Self {
1108 Self {
1109 store,
1110 service: DEFAULT_SERVICE.to_string(),
1111 }
1112 }
1113
1114 /// Auto-detect the best available backend based on the environment.
1115 ///
1116 /// Selection logic:
1117 /// 1. If [`SECRET_BACKEND_ENV`] is set to `system`/`keyring`/`os`/`os-keyring`,
1118 /// probe the OS keyring. If the probe succeeds, use it; otherwise
1119 /// fall back to the file-based store with a warning.
1120 /// 2. If the env var is unset, empty, or `file`/`local`/`json`, use
1121 /// the file-based store directly.
1122 /// 3. If the env var is set to an unrecognised value, log a warning
1123 /// and use the file-based store.
1124 pub fn auto_detect() -> Self {
1125 match secret_backend_selection(configured_secret_backend().as_deref()) {
1126 SecretBackendSelection::File => Self::file_backed_default(),
1127 SecretBackendSelection::Unknown => {
1128 tracing::warn!(
1129 "{SECRET_BACKEND_ENV}/{LEGACY_SECRET_BACKEND_ENV} has an unsupported value; using file-backed secret store"
1130 );
1131 Self::file_backed_default()
1132 }
1133 SecretBackendSelection::System => {
1134 let default_store = DefaultKeyringStore::default();
1135 match default_store.probe() {
1136 Ok(()) => Self::new(Arc::new(default_store)),
1137 Err(err) => {
1138 tracing::warn!(
1139 "OS keyring unavailable ({err}); falling back to file-backed secret store"
1140 );
1141 Self::file_backed_default()
1142 }
1143 }
1144 }
1145 }
1146 }
1147
1148 /// Auto-detect a secret backend for diagnostics without permitting writes
1149 /// or legacy migration.
1150 ///
1151 /// The selected backend and lookup precedence match [`Self::auto_detect`],
1152 /// but file-backed lookup reads the Codewhale location first and the legacy
1153 /// location second instead of copying legacy entries into a new file. This
1154 /// lets status and doctor reports label a saved credential without changing
1155 /// user state.
1156 #[must_use]
1157 pub fn auto_detect_read_only() -> Self {
1158 match secret_backend_selection(configured_secret_backend().as_deref()) {
1159 SecretBackendSelection::File => Self::file_backed_read_only(),
1160 SecretBackendSelection::Unknown => {
1161 tracing::warn!(
1162 "{SECRET_BACKEND_ENV}/{LEGACY_SECRET_BACKEND_ENV} has an unsupported value; using file-backed secret store"
1163 );
1164 Self::file_backed_read_only()
1165 }
1166 SecretBackendSelection::System => {
1167 let default_store = DefaultKeyringStore::default();
1168 match default_store.probe() {
1169 Ok(()) => {
1170 Self::new(Arc::new(ReadOnlyKeyringStore::new(Arc::new(default_store))))
1171 }
1172 Err(err) => {
1173 tracing::warn!(
1174 "OS keyring unavailable ({err}); falling back to file-backed secret store"
1175 );
1176 Self::file_backed_read_only()
1177 }
1178 }
1179 }
1180 }
1181 }
1182
1183 fn file_backed_default() -> Self {
1184 Self::file_backed_from_default_path(FileKeyringStore::default_path())
1185 }
1186
1187 /// Build the writable default store only when the resolved path is safe.
1188 ///
1189 /// Keeping the resolution result as an argument gives the no-home and
1190 /// relative-path branches direct regression coverage. Both must refuse
1191 /// writes rather than placing credentials in the caller's workspace.
1192 fn file_backed_from_default_path(path_result: Result<PathBuf, SecretsError>) -> Self {
1193 // Never fall back to a workspace-relative secrets path. Writing
1194 // credential material beside the cwd is readable by tools and easy to
1195 // commit. If home resolution fails, use a write-refusing store.
1196 match path_result {
1197 Ok(path) if path.is_absolute() => Self::new(Arc::new(FileKeyringStore::new(path))),
1198 Ok(path) => {
1199 tracing::error!(
1200 "refusing relative file-backed secret path {}; credentials will not be read or persisted",
1201 path.display()
1202 );
1203 Self::read_only_empty_store()
1204 }
1205 Err(err) => {
1206 tracing::error!(
1207 "could not resolve file-backed secret path ({err}); credentials will not be read or persisted"
1208 );
1209 Self::read_only_empty_store()
1210 }
1211 }
1212 }
1213
1214 /// An unavailable default path must be hermetic: neither inspect an
1215 /// accidental workspace file nor create one. The read-only wrapper keeps
1216 /// the public API's write failure explicit while reads safely report empty.
1217 fn read_only_empty_store() -> Self {
1218 Self::new(Arc::new(ReadOnlyKeyringStore::new(Arc::new(
1219 InMemoryKeyringStore::new(),
1220 ))))
1221 }
1222
1223 /// Construct a file-backed diagnostic store without migration or write
1224 /// capability.
1225 ///
1226 /// This reads the Codewhale file first and the legacy file second (unless
1227 /// `CODEWHALE_HOME` is explicit), but never copies legacy entries into a
1228 /// primary store. It intentionally bypasses an opted-in OS keyring so
1229 /// callers that only need non-secret diagnostics do not cause a platform
1230 /// credential prompt.
1231 #[must_use]
1232 pub fn file_backed_read_only() -> Self {
1233 // Fail closed like the writable path in `file_backed_from_default_path`:
1234 // never fall back to a cwd-relative credential path. A planted
1235 // `.codewhale-secrets.json` beside the working directory must not
1236 // become the credential store when home resolution fails.
1237 match ReadOnlyFileKeyringStore::default_for_diagnostics() {
1238 Ok(store) => Self::new(Arc::new(store)),
1239 Err(err) => {
1240 tracing::error!(
1241 "could not resolve the file-backed secret path ({err}); credentials will not be read. \
1242 Fix: set CODEWHALE_HOME to an absolute path or make HOME/USERPROFILE resolvable"
1243 );
1244 Self::read_only_empty_store()
1245 }
1246 }
1247 }
1248
1249 /// Construct the file-backed default backend directly.
1250 #[must_use]
1251 pub fn file_backed() -> Self {
1252 Self::file_backed_default()
1253 }
1254
1255 /// Backend label, suitable for `doctor` output.
1256 #[must_use]
1257 pub fn backend_name(&self) -> &'static str {
1258 self.store.backend_name()
1259 }
1260
1261 /// Resolve a secret with `secret store → env → none` precedence.
1262 ///
1263 /// `name` is the secret-store slot; `env_vars` are the environment
1264 /// variables to try after it, in order (see [`env_first`]). Empty strings
1265 /// on either layer are treated as "not set".
1266 #[must_use]
1267 pub fn resolve(&self, name: &str, env_vars: &[&str]) -> Option<String> {
1268 self.resolve_with_source(name, env_vars)
1269 .map(|(value, _)| value)
1270 }
1271
1272 /// Resolve a secret and report which layer supplied it.
1273 #[must_use]
1274 pub fn resolve_with_source(
1275 &self,
1276 name: &str,
1277 env_vars: &[&str],
1278 ) -> Option<(String, SecretSource)> {
1279 if let Ok(Some(v)) = self.store.get(name)
1280 && !v.trim().is_empty()
1281 {
1282 return Some((v, SecretSource::Keyring));
1283 }
1284 env_first(env_vars).map(|(_, value)| (value, SecretSource::Env))
1285 }
1286
1287 /// Convenience: write a secret through the underlying store.
1288 pub fn set(&self, name: &str, value: &str) -> Result<(), SecretsError> {
1289 self.store.set(name, value)
1290 }
1291
1292 /// Convenience: delete a secret through the underlying store.
1293 pub fn delete(&self, name: &str) -> Result<(), SecretsError> {
1294 self.store.delete(name)
1295 }
1296
1297 /// Convenience: read a secret directly (no env fallback).
1298 pub fn get(&self, name: &str) -> Result<Option<String>, SecretsError> {
1299 self.store.get(name)
1300 }
1301
1302 /// Run one non-reentrant callback under the backend's entry authority.
1303 pub fn with_entry_transaction<T>(
1304 &self,
1305 name: &str,
1306 operation: impl FnOnce(&mut Option<String>) -> Result<T, SecretsError>,
1307 ) -> Result<T, SecretsError> {
1308 let mut operation = Some(operation);
1309 let mut result = None;
1310 self.store.with_entry_transaction(name, &mut |value| {
1311 let call = operation.take().ok_or_else(|| {
1312 SecretsError::Keyring("Secret transaction invoked more than once".into())
1313 })?;
1314 result = Some(call(value)?);
1315 Ok(())
1316 })?;
1317 result.ok_or_else(|| SecretsError::Keyring("Secret transaction was not invoked".into()))
1318 }
1319
1320 /// Atomically update one secret only while its exact stored bytes match.
1321 pub fn compare_exchange(
1322 &self,
1323 name: &str,
1324 expected: Option<&str>,
1325 replacement: Option<&str>,
1326 ) -> Result<bool, SecretsError> {
1327 self.store.compare_exchange(name, expected, replacement)
1328 }
1329 }
1330
1331 /// Remove characters a copy-paste adds to an API key but no provider issues
1332 /// (#6528): Unicode whitespace anywhere (including NBSP and internal
1333 /// spaces/newlines), control characters, and invisible format characters —
1334 /// BOM, zero-width space/joiner/non-joiner, word joiner and invisible
1335 /// operators, soft hyphen, and bidi marks/embeddings/isolates. Every API-key
1336 /// entry path (onboarding, `/provider`, `auth set`, env import, and the
1337 /// runtime resolver) goes through this one helper.
1338 #[must_use]
1339 pub fn normalize_api_key(raw: &str) -> String {
1340 raw.chars()
1341 .filter(|ch| {
1342 !(ch.is_whitespace()
1343 || ch.is_control()
1344 || matches!(
1345 ch,
1346 '\u{00ad}'
1347 | '\u{061c}'
1348 | '\u{180e}'
1349 | '\u{200b}'..='\u{200f}'
1350 | '\u{202a}'..='\u{202e}'
1351 | '\u{2060}'..='\u{2064}'
1352 | '\u{2066}'..='\u{206f}'
1353 | '\u{feff}'
1354 ))
1355 })
1356 .collect()
1357 }
1358
1359 /// The first of `vars` set to a non-empty value (after
1360 /// [`normalize_api_key`]), with the variable's name so auth errors can point
1361 /// at it.
1362 ///
1363 /// The variable list is the caller's: a provider's list lives on its
1364 /// descriptor (`codewhale_config::Provider::env_vars`), not in a second
1365 /// table here that can drift from it.
1366 #[must_use]
1367 pub fn env_first<'a>(vars: &[&'a str]) -> Option<(&'a str, String)> {
1368 vars.iter().find_map(|var| {
1369 let value = normalize_api_key(&std::env::var(var).ok()?);
1370 (!value.is_empty()).then_some((*var, value))
1371 })
1372 }
1373
1374 #[cfg(test)]
1375 mod tests {
1376 use super::*;
1377 use std::sync::{Mutex, OnceLock};
1378
1379 #[test]
1380 fn file_store_rejects_an_oversized_secrets_file() {
1381 let tmp = tempfile::tempdir().unwrap();
1382 let path = tmp.path().join("secrets.json");
1383 let store = FileKeyringStore::new(&path);
1384 store.set("key", "value").unwrap();
1385 let oversized = vec![b' '; MAX_SECRETS_FILE_BYTES as usize + 1];
1386 std::fs::OpenOptions::new()
1387 .write(true)
1388 .truncate(true)
1389 .open(&path)
1390 .and_then(|mut file| std::io::Write::write_all(&mut file, &oversized))
1391 .unwrap();
1392 let err = store.get("key").unwrap_err();
1393 assert!(err.to_string().contains("exceeds"), "{err}");
1394 }
1395
1396 #[test]
1397 fn file_store_refuses_a_save_that_would_exceed_the_read_cap() {
1398 let tmp = tempfile::tempdir().unwrap();
1399 let store = FileKeyringStore::new(tmp.path().join("secrets.json"));
1400 store.set("key", "value").unwrap();
1401 let huge = "x".repeat(MAX_SECRETS_FILE_BYTES as usize);
1402 assert!(store.set("big", &huge).is_err());
1403 assert_eq!(store.get("key").unwrap().as_deref(), Some("value"));
1404 store.delete("key").unwrap();
1405 }
1406
1407 #[cfg(unix)]
1408 #[test]
1409 fn atomic_write_private_file_syncs_parent_directory_after_persist() {
1410 let tmp = tempfile::tempdir().unwrap();
1411 let path = tmp.path().join("secrets.json");
1412 let mut synced = false;
1413 atomic_write_private_file_with_dir_sync(&path, b"{\"entries\":{}}", |dir_file| {
1414 // Persisted file must already be visible when directory sync runs.
1415 assert_eq!(fs::read(&path).unwrap(), b"{\"entries\":{}}");
1416 assert!(dir_file.metadata().unwrap().is_dir());
1417 synced = true;
1418 dir_file.sync_all()
1419 })
1420 .unwrap();
1421 assert!(synced, "directory sync must be invoked after persist");
1422
1423 // A failing directory sync must not report a committed replacement as failed.
1424 atomic_write_private_file_with_dir_sync(&path, b"{\"entries\":{\"k\":\"v\"}}", |_| {
1425 Err(std::io::Error::other("simulated dir sync error"))
1426 })
1427 .unwrap();
1428 assert_eq!(fs::read(&path).unwrap(), b"{\"entries\":{\"k\":\"v\"}}");
1429 }
1430
1431 #[test]
1432 fn normalize_api_key_strips_each_invisible_character_class() {
1433 let cases = [
1434 ("byte-order mark", "\u{feff}sk-abc123"),
1435 ("zero-width space", "sk-abc\u{200b}123"),
1436 ("zero-width non-joiner", "sk-abc\u{200c}123"),
1437 ("zero-width joiner", "sk-abc\u{200d}123"),
1438 ("no-break space", "sk-abc123\u{a0}"),
1439 ("word joiner", "sk-\u{2060}abc123"),
1440 ("soft hyphen", "sk-abc\u{ad}123"),
1441 (
1442 "bidi marks",
1443 "\u{200e}sk-abc123\u{200f}\u{202a}\u{202c}\u{2066}\u{2069}",
1444 ),
1445 ("internal whitespace", " sk-abc\n 123\t\r\n"),
1446 ];
1447 for (class, raw) in cases {
1448 assert_eq!(normalize_api_key(raw), "sk-abc123", "{class}");
1449 }
1450 assert_eq!(normalize_api_key("\u{feff}\u{200b} "), "");
1451 assert_eq!(normalize_api_key("tp-Key_9.x/+="), "tp-Key_9.x/+=");
1452 }
1453
1454 /// Serialise env-mutating tests: tests in this module poke
1455 /// `DEEPSEEK_API_KEY` etc., which is process-global.
1456 pub(crate) fn env_lock() -> std::sync::MutexGuard<'static, ()> {
1457 static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1458 LOCK.get_or_init(|| Mutex::new(()))
1459 .lock()
1460 .unwrap_or_else(|p| p.into_inner())
1461 }
1462
1463 fn clear_known_envs() {
1464 for var in [
1465 "CODEWHALE_HOME",
1466 "DEEPSEEK_API_KEY",
1467 "OPENROUTER_API_KEY",
1468 "NOVITA_API_KEY",
1469 "NVIDIA_API_KEY",
1470 "NVIDIA_NIM_API_KEY",
1471 "FIREWORKS_API_KEY",
1472 "TOGETHER_API_KEY",
1473 "DEEPINFRA_API_KEY",
1474 "DEEPINFRA_TOKEN",
1475 "SILICONFLOW_API_KEY",
1476 "ARCEE_API_KEY",
1477 "SGLANG_API_KEY",
1478 "VLLM_API_KEY",
1479 "OLLAMA_API_KEY",
1480 "OLLAMA_CLOUD_API_KEY",
1481 "OPENAI_API_KEY",
1482 "ATLASCLOUD_API_KEY",
1483 "WANJIE_ARK_API_KEY",
1484 "WANJIE_API_KEY",
1485 "WANJIE_MAAS_API_KEY",
1486 "XIAOMI_MIMO_API_KEY",
1487 "XIAOMI_API_KEY",
1488 "MIMO_API_KEY",
1489 "FUGU_API_KEY",
1490 "SAKANA_API_KEY",
1491 "LONGCAT_API_KEY",
1492 "OPENCODE_GO_API_KEY",
1493 "OPENCODE_ZEN_API_KEY",
1494 "OPENCODE_API_KEY",
1495 "META_MODEL_API_KEY",
1496 "MODEL_API_KEY",
1497 "XAI_API_KEY",
1498 "TELECOMJS_API_KEY",
1499 "EDENAI_API_KEY",
1500 "ZENMUX_API_KEY",
1501 "CSDN_API_KEY",
1502 "CONCENTRATE_API_KEY",
1503 "MODELSTUDIO_API_KEY",
1504 "DASHSCOPE_API_KEY",
1505 SECRET_BACKEND_ENV,
1506 LEGACY_SECRET_BACKEND_ENV,
1507 ] {
1508 // Safety: tests serialise on env_lock(); the broader
1509 // workspace has the same pattern in `crates/config`.
1510 unsafe { std::env::remove_var(var) };
1511 }
1512 }
1513
1514 struct EnvVarGuard {
1515 name: &'static str,
1516 previous: Option<std::ffi::OsString>,
1517 }
1518
1519 impl EnvVarGuard {
1520 fn set(name: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
1521 let previous = std::env::var_os(name);
1522 unsafe { std::env::set_var(name, value) };
1523 Self { name, previous }
1524 }
1525 }
1526
1527 impl Drop for EnvVarGuard {
1528 fn drop(&mut self) {
1529 match self.previous.take() {
1530 Some(value) => unsafe { std::env::set_var(self.name, value) },
1531 None => unsafe { std::env::remove_var(self.name) },
1532 }
1533 }
1534 }
1535
1536 /// Live check for #5172: on macOS/Windows the probe used to return Ok
1537 /// without touching the backend at all. Run explicitly with
1538 /// `cargo test -p codewhale-secrets -- --ignored` on a desktop machine:
1539 /// a healthy native keyring answers a read of the deliberately absent
1540 /// `__probe__` entry with NoEntry, silently, and the probe succeeds.
1541 #[test]
1542 #[ignore = "touches the real OS keyring; run on a desktop machine"]
1543 fn probe_performs_a_real_backend_read() {
1544 let store = DefaultKeyringStore::new("codewhale-probe-live-check");
1545 store
1546 .probe()
1547 .expect("the native keyring backend should be reachable on this machine");
1548 }
1549
1550 #[test]
1551 fn backend_selection_defaults_to_file() {
1552 assert_eq!(secret_backend_selection(None), SecretBackendSelection::File);
1553 assert_eq!(
1554 secret_backend_selection(Some("")),
1555 SecretBackendSelection::File
1556 );
1557 assert_eq!(
1558 secret_backend_selection(Some(" file ")),
1559 SecretBackendSelection::File
1560 );
1561 }
1562
1563 #[test]
1564 fn backend_selection_accepts_explicit_system_keyring() {
1565 assert_eq!(
1566 secret_backend_selection(Some("system")),
1567 SecretBackendSelection::System
1568 );
1569 assert_eq!(
1570 secret_backend_selection(Some("keyring")),
1571 SecretBackendSelection::System
1572 );
1573 assert_eq!(
1574 secret_backend_selection(Some("os-keyring")),
1575 SecretBackendSelection::System
1576 );
1577 }
1578
1579 #[test]
1580 fn auto_detect_is_file_backed_by_default() {
1581 let _lock = env_lock();
1582 clear_known_envs();
1583 let tmp = tempfile::tempdir().unwrap();
1584 let _home = EnvVarGuard::set("HOME", tmp.path());
1585 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1586
1587 let secrets = Secrets::auto_detect();
1588
1589 assert_eq!(secrets.backend_name(), FILE_BACKEND_LABEL);
1590 }
1591
1592 #[test]
1593 fn auto_detect_honors_explicit_file_backend() {
1594 let _lock = env_lock();
1595 clear_known_envs();
1596 let tmp = tempfile::tempdir().unwrap();
1597 let _home = EnvVarGuard::set("HOME", tmp.path());
1598 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1599 // Safety: env mutation guarded by env_lock().
1600 unsafe { std::env::set_var(SECRET_BACKEND_ENV, "local") };
1601
1602 let secrets = Secrets::auto_detect();
1603
1604 assert_eq!(secrets.backend_name(), FILE_BACKEND_LABEL);
1605 // Safety: env mutation guarded by env_lock().
1606 unsafe { std::env::remove_var(SECRET_BACKEND_ENV) };
1607 }
1608
1609 #[test]
1610 fn read_only_auto_detect_reads_legacy_without_migrating_or_allowing_writes() {
1611 let _lock = env_lock();
1612 clear_known_envs();
1613 let tmp = tempfile::tempdir().unwrap();
1614 let _home = EnvVarGuard::set("HOME", tmp.path());
1615 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1616 let _backend = EnvVarGuard::set(SECRET_BACKEND_ENV, "file");
1617 let legacy = tmp
1618 .path()
1619 .join(".deepseek")
1620 .join("secrets")
1621 .join("secrets.json");
1622 let primary = tmp
1623 .path()
1624 .join(".codewhale")
1625 .join("secrets")
1626 .join("secrets.json");
1627 FileKeyringStore::new(&legacy)
1628 .set("moonshot", "fixture-legacy-value")
1629 .unwrap();
1630
1631 let secrets = Secrets::auto_detect_read_only();
1632
1633 assert_eq!(
1634 secrets.get("moonshot").unwrap().as_deref(),
1635 Some("fixture-legacy-value")
1636 );
1637 assert!(
1638 !primary.exists(),
1639 "diagnostic lookup must not migrate the legacy store"
1640 );
1641 assert!(
1642 matches!(
1643 secrets.set("moonshot", "replacement"),
1644 Err(SecretsError::ReadOnly)
1645 ),
1646 "the diagnostic secret facade must refuse writes"
1647 );
1648 assert!(
1649 !primary.exists(),
1650 "a refused diagnostic write must not create the primary store"
1651 );
1652 }
1653
1654 #[test]
1655 fn read_only_auto_detect_respects_explicit_codewhale_home_isolation() {
1656 let _lock = env_lock();
1657 clear_known_envs();
1658 let tmp = tempfile::tempdir().unwrap();
1659 let codewhale_home = tmp.path().join("isolated-codewhale-home");
1660 let _home = EnvVarGuard::set("HOME", tmp.path());
1661 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1662 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home);
1663 let _backend = EnvVarGuard::set(SECRET_BACKEND_ENV, "file");
1664 let legacy = tmp
1665 .path()
1666 .join(".deepseek")
1667 .join("secrets")
1668 .join("secrets.json");
1669 let primary = codewhale_home.join("secrets").join("secrets.json");
1670 FileKeyringStore::new(&legacy)
1671 .set("deepseek", "synthetic-ambient-legacy-value")
1672 .unwrap();
1673
1674 let secrets = Secrets::auto_detect_read_only();
1675
1676 assert_eq!(
1677 secrets.get("deepseek").unwrap(),
1678 None,
1679 "an explicit CODEWHALE_HOME must not read ambient legacy secrets"
1680 );
1681 assert!(
1682 !primary.exists(),
1683 "diagnostic lookup must not create an isolated primary store"
1684 );
1685 assert!(
1686 matches!(
1687 secrets.set("deepseek", "replacement"),
1688 Err(SecretsError::ReadOnly)
1689 ),
1690 "the isolated diagnostic facade must refuse writes"
1691 );
1692 assert!(
1693 !primary.exists(),
1694 "a refused isolated diagnostic write must not create the primary store"
1695 );
1696 }
1697
1698 /// Cwd is process-global, so tests that move it serialise on `env_lock`
1699 /// like the env-mutating tests and restore on drop.
1700 struct CwdGuard {
1701 previous: PathBuf,
1702 }
1703
1704 impl CwdGuard {
1705 fn enter(path: &Path) -> Self {
1706 let previous = std::env::current_dir().unwrap();
1707 std::env::set_current_dir(path).unwrap();
1708 Self { previous }
1709 }
1710 }
1711
1712 impl Drop for CwdGuard {
1713 fn drop(&mut self) {
1714 std::env::set_current_dir(&self.previous).unwrap();
1715 }
1716 }
1717
1718 #[test]
1719 fn file_backed_read_only_never_reads_a_cwd_relative_store() {
1720 let _lock = env_lock();
1721 clear_known_envs();
1722 let tmp = tempfile::tempdir().unwrap();
1723 // A relative override fails home resolution deterministically, which
1724 // used to fall back to a planted `.codewhale-secrets.json` in the cwd.
1725 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", "relative-codewhale-home");
1726 let planted = tmp.path().join(".codewhale-secrets.json");
1727 std::fs::write(
1728 &planted,
1729 r#"{"entries":{"deepseek":"planted-cwd-credential"}}"#,
1730 )
1731 .unwrap();
1732 let _cwd = CwdGuard::enter(tmp.path());
1733
1734 let secrets = Secrets::file_backed_read_only();
1735
1736 assert_eq!(
1737 secrets.get("deepseek").unwrap(),
1738 None,
1739 "a failed home resolution must not turn a planted cwd file into the credential store"
1740 );
1741 assert!(
1742 matches!(
1743 secrets.set("deepseek", "replacement"),
1744 Err(SecretsError::ReadOnly)
1745 ),
1746 "the failed-resolution diagnostic facade must still refuse writes"
1747 );
1748 }
1749
1750 #[test]
1751 fn read_only_auto_detect_reads_the_explicit_primary_store() {
1752 let _lock = env_lock();
1753 clear_known_envs();
1754 let tmp = tempfile::tempdir().unwrap();
1755 let codewhale_home = tmp.path().join("isolated-codewhale-home");
1756 let _home = EnvVarGuard::set("HOME", tmp.path());
1757 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1758 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home);
1759 let _backend = EnvVarGuard::set(SECRET_BACKEND_ENV, "file");
1760 let primary = codewhale_home.join("secrets").join("secrets.json");
1761 FileKeyringStore::new(&primary)
1762 .set("deepseek", "synthetic-isolated-primary-value")
1763 .unwrap();
1764
1765 let secrets = Secrets::auto_detect_read_only();
1766
1767 assert_eq!(
1768 secrets.get("deepseek").unwrap().as_deref(),
1769 Some("synthetic-isolated-primary-value")
1770 );
1771 }
1772
1773 #[test]
1774 fn auto_detect_honors_legacy_backend_env_alias() {
1775 let _lock = env_lock();
1776 clear_known_envs();
1777 let tmp = tempfile::tempdir().unwrap();
1778 let _home = EnvVarGuard::set("HOME", tmp.path());
1779 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1780 unsafe { std::env::set_var(LEGACY_SECRET_BACKEND_ENV, "local") };
1781
1782 let secrets = Secrets::auto_detect();
1783
1784 assert_eq!(secrets.backend_name(), FILE_BACKEND_LABEL);
1785 clear_known_envs();
1786 }
1787
1788 #[test]
1789 fn file_default_path_uses_codewhale_home() {
1790 let _lock = env_lock();
1791 clear_known_envs();
1792 let tmp = tempfile::tempdir().unwrap();
1793 let _home = EnvVarGuard::set("HOME", tmp.path());
1794 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1795
1796 let path = FileKeyringStore::default_path().unwrap();
1797
1798 assert_eq!(
1799 path,
1800 tmp.path()
1801 .join(".codewhale")
1802 .join("secrets")
1803 .join("secrets.json")
1804 );
1805 }
1806
1807 #[test]
1808 fn file_default_path_honors_codewhale_home() {
1809 let _lock = env_lock();
1810 clear_known_envs();
1811 let tmp = tempfile::tempdir().unwrap();
1812 let custom = tmp.path().join("custom-codewhale");
1813 let _home = EnvVarGuard::set("HOME", tmp.path());
1814 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1815 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &custom);
1816
1817 let path = FileKeyringStore::default_path().unwrap();
1818
1819 assert_eq!(path, custom.join("secrets").join("secrets.json"));
1820 }
1821
1822 #[test]
1823 fn file_default_path_migrates_legacy_entries_to_codewhale() {
1824 let _lock = env_lock();
1825 clear_known_envs();
1826 let tmp = tempfile::tempdir().unwrap();
1827 let _home = EnvVarGuard::set("HOME", tmp.path());
1828 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1829 let legacy = tmp
1830 .path()
1831 .join(".deepseek")
1832 .join("secrets")
1833 .join("secrets.json");
1834 FileKeyringStore::new(legacy.clone())
1835 .set("xiaomi-mimo", "legacy-mimo")
1836 .unwrap();
1837
1838 let primary = FileKeyringStore::default_path().unwrap();
1839 let primary_store = FileKeyringStore::new(primary.clone());
1840
1841 assert_eq!(
1842 primary,
1843 tmp.path()
1844 .join(".codewhale")
1845 .join("secrets")
1846 .join("secrets.json")
1847 );
1848 assert_eq!(
1849 primary_store.get("xiaomi-mimo").unwrap().as_deref(),
1850 Some("legacy-mimo")
1851 );
1852 assert!(
1853 legacy.exists(),
1854 "migration copies; it does not delete legacy data"
1855 );
1856 }
1857
1858 #[test]
1859 fn file_default_path_migration_preserves_primary_values() {
1860 let _lock = env_lock();
1861 clear_known_envs();
1862 let tmp = tempfile::tempdir().unwrap();
1863 let _home = EnvVarGuard::set("HOME", tmp.path());
1864 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1865 let legacy = tmp
1866 .path()
1867 .join(".deepseek")
1868 .join("secrets")
1869 .join("secrets.json");
1870 let primary = tmp
1871 .path()
1872 .join(".codewhale")
1873 .join("secrets")
1874 .join("secrets.json");
1875 FileKeyringStore::new(legacy)
1876 .set("openrouter", "legacy-openrouter")
1877 .unwrap();
1878 let primary_store = FileKeyringStore::new(primary.clone());
1879 primary_store
1880 .set("openrouter", "primary-openrouter")
1881 .unwrap();
1882
1883 let resolved = FileKeyringStore::default_path().unwrap();
1884
1885 assert_eq!(resolved, primary);
1886 assert_eq!(
1887 primary_store.get("openrouter").unwrap().as_deref(),
1888 Some("primary-openrouter")
1889 );
1890 }
1891
1892 #[test]
1893 fn file_default_path_migration_is_one_shot_so_deleted_keys_stay_deleted() {
1894 let _lock = env_lock();
1895 clear_known_envs();
1896 let tmp = tempfile::tempdir().unwrap();
1897 let _home = EnvVarGuard::set("HOME", tmp.path());
1898 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
1899 let _backend = EnvVarGuard::set(SECRET_BACKEND_ENV, "file");
1900 let legacy = tmp
1901 .path()
1902 .join(".deepseek")
1903 .join("secrets")
1904 .join("secrets.json");
1905 FileKeyringStore::new(&legacy)
1906 .set("openrouter", "legacy-openrouter")
1907 .unwrap();
1908
1909 let primary_store = FileKeyringStore::new(FileKeyringStore::default_path().unwrap());
1910 assert_eq!(
1911 primary_store.get("openrouter").unwrap().as_deref(),
1912 Some("legacy-openrouter"),
1913 "the first launch still copies legacy entries"
1914 );
1915
1916 primary_store.delete("openrouter").unwrap();
1917 let resolved = FileKeyringStore::default_path().unwrap();
1918 assert_eq!(resolved, primary_store.path());
1919 assert_eq!(
1920 primary_store.get("openrouter").unwrap(),
1921 None,
1922 "a deleted key must not be re-imported from the legacy store"
1923 );
1924 assert_eq!(
1925 Secrets::auto_detect_read_only().get("openrouter").unwrap(),
1926 None,
1927 "read-only lookup must not fall back to a migrated legacy store"
1928 );
1929 assert!(legacy.exists(), "migration never deletes legacy data");
1930 }
1931
1932 #[test]
1933 fn in_memory_store_round_trips() {
1934 let store = InMemoryKeyringStore::new();
1935 assert_eq!(store.get("deepseek").unwrap(), None);
1936 store.set("deepseek", "sk-test").unwrap();
1937 assert_eq!(store.get("deepseek").unwrap(), Some("sk-test".to_string()));
1938 store.set("deepseek", "sk-replaced").unwrap();
1939 assert_eq!(
1940 store.get("deepseek").unwrap(),
1941 Some("sk-replaced".to_string())
1942 );
1943 store.delete("deepseek").unwrap();
1944 assert_eq!(store.get("deepseek").unwrap(), None);
1945 // Deleting an absent key is a no-op.
1946 store.delete("missing").unwrap();
1947 }
1948
1949 #[test]
1950 fn resolve_prefers_keyring_over_env() {
1951 let _lock = env_lock();
1952 clear_known_envs();
1953 // Safety: env mutation guarded by env_lock().
1954 unsafe { std::env::set_var("DEEPSEEK_API_KEY", "env-key") };
1955
1956 let store = Arc::new(InMemoryKeyringStore::new());
1957 store.set("deepseek", "ring-key").unwrap();
1958 let secrets = Secrets::new(store);
1959
1960 assert_eq!(
1961 secrets
1962 .resolve("deepseek", &["DEEPSEEK_API_KEY"])
1963 .as_deref(),
1964 Some("ring-key")
1965 );
1966 assert_eq!(
1967 secrets.resolve_with_source("deepseek", &["DEEPSEEK_API_KEY"]),
1968 Some(("ring-key".to_string(), SecretSource::Keyring))
1969 );
1970 // Safety: env mutation guarded by env_lock().
1971 unsafe { std::env::remove_var("DEEPSEEK_API_KEY") };
1972 }
1973
1974 #[test]
1975 fn resolve_falls_back_to_env_when_keyring_empty() {
1976 let _lock = env_lock();
1977 clear_known_envs();
1978 // Safety: env mutation guarded by env_lock().
1979 unsafe { std::env::set_var("DEEPSEEK_API_KEY", "env-fallback") };
1980
1981 let secrets = Secrets::new(Arc::new(InMemoryKeyringStore::new()));
1982 assert_eq!(
1983 secrets
1984 .resolve("deepseek", &["DEEPSEEK_API_KEY"])
1985 .as_deref(),
1986 Some("env-fallback")
1987 );
1988 assert_eq!(
1989 secrets.resolve_with_source("deepseek", &["DEEPSEEK_API_KEY"]),
1990 Some(("env-fallback".to_string(), SecretSource::Env))
1991 );
1992 // Safety: env mutation guarded by env_lock().
1993 unsafe { std::env::remove_var("DEEPSEEK_API_KEY") };
1994 }
1995
1996 #[test]
1997 fn resolve_returns_none_when_both_layers_empty() {
1998 let _lock = env_lock();
1999 clear_known_envs();
2000 let secrets = Secrets::new(Arc::new(InMemoryKeyringStore::new()));
2001 assert_eq!(secrets.resolve("deepseek", &["DEEPSEEK_API_KEY"]), None);
2002 }
2003
2004 #[test]
2005 fn resolve_treats_blank_keyring_value_as_unset() {
2006 let _lock = env_lock();
2007 clear_known_envs();
2008 // Safety: env mutation guarded by env_lock().
2009 unsafe { std::env::set_var("DEEPSEEK_API_KEY", "env-real") };
2010
2011 let store = Arc::new(InMemoryKeyringStore::new());
2012 store.set("deepseek", " ").unwrap();
2013 let secrets = Secrets::new(store);
2014 assert_eq!(
2015 secrets
2016 .resolve("deepseek", &["DEEPSEEK_API_KEY"])
2017 .as_deref(),
2018 Some("env-real")
2019 );
2020 // Safety: env mutation guarded by env_lock().
2021 unsafe { std::env::remove_var("DEEPSEEK_API_KEY") };
2022 }
2023
2024 #[test]
2025 fn env_first_takes_the_first_non_empty_normalized_value() {
2026 let _lock = env_lock();
2027 clear_known_envs();
2028 let vars = ["OLLAMA_CLOUD_API_KEY", "OLLAMA_API_KEY"];
2029 assert_eq!(env_first(&vars), None);
2030 // Safety: env mutation guarded by env_lock().
2031 unsafe {
2032 std::env::set_var("OLLAMA_CLOUD_API_KEY", " \u{200b} ");
2033 std::env::set_var("OLLAMA_API_KEY", " fallback-key\n");
2034 }
2035 assert_eq!(
2036 env_first(&vars),
2037 Some(("OLLAMA_API_KEY", "fallback-key".to_string()))
2038 );
2039 // Safety: env mutation guarded by env_lock().
2040 unsafe { std::env::set_var("OLLAMA_CLOUD_API_KEY", "cloud-key") };
2041 assert_eq!(
2042 env_first(&vars),
2043 Some(("OLLAMA_CLOUD_API_KEY", "cloud-key".to_string()))
2044 );
2045 clear_known_envs();
2046 }
2047
2048 #[cfg(unix)]
2049 #[test]
2050 fn file_store_round_trips_with_secure_perms() {
2051 use std::os::unix::fs::PermissionsExt;
2052
2053 let tmp = tempfile::tempdir().unwrap();
2054 let path = tmp.path().join("nested").join("secrets.json");
2055 let store = FileKeyringStore::new(path.clone());
2056 assert_eq!(store.get("deepseek").unwrap(), None);
2057 store.set("deepseek", "sk-disk").unwrap();
2058 assert_eq!(store.get("deepseek").unwrap(), Some("sk-disk".to_string()));
2059
2060 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2061 assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
2062
2063 store.set("openrouter", "or-disk").unwrap();
2064 assert_eq!(
2065 store.get("openrouter").unwrap(),
2066 Some("or-disk".to_string())
2067 );
2068 // First entry must still be intact.
2069 assert_eq!(store.get("deepseek").unwrap(), Some("sk-disk".to_string()));
2070
2071 store.delete("deepseek").unwrap();
2072 assert_eq!(store.get("deepseek").unwrap(), None);
2073 }
2074
2075 #[cfg(unix)]
2076 #[test]
2077 fn file_store_rejects_world_readable_file() {
2078 use std::os::unix::fs::PermissionsExt;
2079 let tmp = tempfile::tempdir().unwrap();
2080 let path = tmp.path().join("secrets.json");
2081 fs::write(&path, "{\"entries\":{\"deepseek\":\"leak\"}}").unwrap();
2082 let mut perms = fs::metadata(&path).unwrap().permissions();
2083 perms.set_mode(0o644);
2084 fs::set_permissions(&path, perms).unwrap();
2085
2086 let store = FileKeyringStore::new(path);
2087 let err = store.get("deepseek").unwrap_err();
2088 assert!(
2089 matches!(err, SecretsError::InsecurePermissions { .. }),
2090 "unexpected error: {err}"
2091 );
2092 }
2093
2094 // Regression for #281: `set` and `delete` used to call
2095 // `load_unlocked().unwrap_or_default()`, which silently wiped every
2096 // existing secret whenever the read failed (insecure permissions,
2097 // corrupt JSON, or any other I/O error).
2098
2099 #[cfg(unix)]
2100 #[test]
2101 fn file_store_set_does_not_clobber_secrets_when_perms_are_bad() {
2102 use std::os::unix::fs::PermissionsExt;
2103 let tmp = tempfile::tempdir().unwrap();
2104 let path = tmp.path().join("secrets.json");
2105 let original = "{\"entries\":{\"deepseek\":\"sk-keep\",\"nvidia\":\"nv-keep\"}}";
2106 fs::write(&path, original).unwrap();
2107 let mut perms = fs::metadata(&path).unwrap().permissions();
2108 perms.set_mode(0o644);
2109 fs::set_permissions(&path, perms).unwrap();
2110
2111 let store = FileKeyringStore::new(path.clone());
2112 let err = store.set("openrouter", "or-new").unwrap_err();
2113 assert!(
2114 matches!(err, SecretsError::InsecurePermissions { .. }),
2115 "set must surface the read error rather than overwriting; got: {err}"
2116 );
2117
2118 let on_disk = fs::read_to_string(&path).unwrap();
2119 assert_eq!(
2120 on_disk, original,
2121 "set must not modify the file when load_unlocked errored"
2122 );
2123 }
2124
2125 #[cfg(unix)]
2126 #[test]
2127 fn file_store_delete_does_not_clobber_secrets_when_perms_are_bad() {
2128 use std::os::unix::fs::PermissionsExt;
2129 let tmp = tempfile::tempdir().unwrap();
2130 let path = tmp.path().join("secrets.json");
2131 let original = "{\"entries\":{\"deepseek\":\"sk-keep\",\"nvidia\":\"nv-keep\"}}";
2132 fs::write(&path, original).unwrap();
2133 let mut perms = fs::metadata(&path).unwrap().permissions();
2134 perms.set_mode(0o644);
2135 fs::set_permissions(&path, perms).unwrap();
2136
2137 let store = FileKeyringStore::new(path.clone());
2138 let err = store.delete("nvidia").unwrap_err();
2139 assert!(
2140 matches!(err, SecretsError::InsecurePermissions { .. }),
2141 "delete must surface the read error rather than wiping the file; got: {err}"
2142 );
2143 let on_disk = fs::read_to_string(&path).unwrap();
2144 assert_eq!(on_disk, original);
2145 }
2146
2147 #[test]
2148 fn file_store_set_does_not_clobber_secrets_when_json_is_corrupt() {
2149 let tmp = tempfile::tempdir().unwrap();
2150 let path = tmp.path().join("secrets.json");
2151 // Corrupt JSON. Permissions ok where unix; on Windows the perm-check
2152 // doesn't run so we exercise the json-error path directly.
2153 fs::write(&path, "{ this is not valid json").unwrap();
2154 #[cfg(unix)]
2155 {
2156 use std::os::unix::fs::PermissionsExt;
2157 let mut perms = fs::metadata(&path).unwrap().permissions();
2158 perms.set_mode(0o600);
2159 fs::set_permissions(&path, perms).unwrap();
2160 }
2161
2162 let store = FileKeyringStore::new(path.clone());
2163 let err = store.set("deepseek", "sk-new").unwrap_err();
2164 assert!(
2165 matches!(err, SecretsError::Json(_)),
2166 "set must surface the parse error rather than wiping the file; got: {err}"
2167 );
2168 let on_disk = fs::read_to_string(&path).unwrap();
2169 assert_eq!(on_disk, "{ this is not valid json");
2170 }
2171
2172 #[test]
2173 fn file_store_set_still_creates_file_when_missing() {
2174 // Regression guard: the #281 fix removed `unwrap_or_default()` from
2175 // the load call. Make sure the original first-write-creates-the-file
2176 // ergonomic still works — `load_unlocked` returns `Ok(default)` for
2177 // a missing file, so the `?` should pass through cleanly.
2178 let tmp = tempfile::tempdir().unwrap();
2179 let path = tmp.path().join("nested").join("secrets.json");
2180 let store = FileKeyringStore::new(path.clone());
2181
2182 store.set("deepseek", "sk-fresh").unwrap();
2183 assert_eq!(store.get("deepseek").unwrap(), Some("sk-fresh".to_string()));
2184 }
2185
2186 #[test]
2187 fn file_store_default_path_uses_home() {
2188 let _lock = env_lock();
2189 clear_known_envs();
2190 let tmp = tempfile::tempdir().unwrap();
2191 let _home = EnvVarGuard::set("HOME", tmp.path());
2192 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
2193
2194 let path = FileKeyringStore::default_path().unwrap();
2195 assert_eq!(
2196 path,
2197 tmp.path()
2198 .join(".codewhale")
2199 .join("secrets")
2200 .join("secrets.json")
2201 );
2202 }
2203
2204 #[test]
2205 fn default_path_with_explicit_codewhale_home_does_not_migrate_ambient_legacy() {
2206 // FR003-C001: explicit CODEWHALE_HOME must not silently import ambient
2207 // `$HOME/.deepseek/secrets` credentials into the isolated home.
2208 let _lock = env_lock();
2209 clear_known_envs();
2210 let tmp = tempfile::tempdir().unwrap();
2211 let codewhale_home = tmp.path().join("isolated-codewhale-home");
2212 let _home = EnvVarGuard::set("HOME", tmp.path());
2213 let _userprofile = EnvVarGuard::set("USERPROFILE", tmp.path());
2214 let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home);
2215 let legacy = tmp
2216 .path()
2217 .join(".deepseek")
2218 .join("secrets")
2219 .join("secrets.json");
2220 FileKeyringStore::new(&legacy)
2221 .set("deepseek", "synthetic-ambient-legacy-value")
2222 .unwrap();
2223
2224 let path = FileKeyringStore::default_path().unwrap();
2225 assert_eq!(path, codewhale_home.join("secrets").join("secrets.json"));
2226 assert!(
2227 !path.exists(),
2228 "explicit CODEWHALE_HOME must not create/migrate a primary store from ambient legacy"
2229 );
2230
2231 let secrets = Secrets::auto_detect();
2232 assert_eq!(
2233 secrets.get("deepseek").unwrap(),
2234 None,
2235 "explicit CODEWHALE_HOME must not surface ambient legacy credentials"
2236 );
2237 }
2238
2239 #[test]
2240 fn file_backed_default_refuses_relative_secret_path() {
2241 // FR003-C002: a relative fallback would resolve against the workspace
2242 // and risk committing credentials. It must be write-refusing instead.
2243 let secrets =
2244 Secrets::file_backed_from_default_path(Ok(PathBuf::from(".codewhale-secrets.json")));
2245 assert!(matches!(
2246 secrets.set("deepseek", "must-not-land-relative"),
2247 Err(SecretsError::ReadOnly)
2248 ));
2249 assert_eq!(
2250 secrets.get("deepseek").unwrap(),
2251 None,
2252 "unsafe relative fallback must not read a workspace secret file"
2253 );
2254 }
2255
2256 #[test]
2257 fn file_backed_default_refuses_writes_when_home_resolution_fails() {
2258 // Force the exact fallback branch instead of relying on the shared
2259 // platform-home resolver, which normally succeeds with HOME unset.
2260 let err = SecretsError::Io(std::io::Error::new(
2261 std::io::ErrorKind::NotFound,
2262 "synthetic unresolved home",
2263 ));
2264 let secrets = Secrets::file_backed_from_default_path(Err(err));
2265 assert!(matches!(
2266 secrets.set("deepseek", "must-not-persist"),
2267 Err(SecretsError::ReadOnly)
2268 ));
2269 assert_eq!(secrets.get("deepseek").unwrap(), None);
2270 }
2271
2272 #[path = "diagnostic_tests.rs"]
2273 mod diagnostic_tests;
2274 }
2275
2275 lines RUST