| 1 | //! Canonical provider-credential writes shared by the CLI (`auth set`), |
| 2 | //! the runtime API secret route, and any future host. Owning this here keeps |
| 3 | //! every writer on the same transactional discipline: snapshot the prior |
| 4 | //! secret, write the durable backend, refuse plaintext config fallback, and |
| 5 | //! roll both stores back if either leg fails. |
| 6 | |
| 7 | use anyhow::{Context, Result}; |
| 8 | use sha2::Digest as _; |
| 9 | |
| 10 | use crate::provider_kind::ProviderKind; |
| 11 | use crate::{ConfigStore, Secrets}; |
| 12 | |
| 13 | /// Resolve the store for credential-adjacent writes: provider selection, |
| 14 | /// `auth_mode` markers, and the plaintext-free metadata that accompanies a |
| 15 | /// saved key. |
| 16 | /// |
| 17 | /// Credentials and their metadata are user-global — a key saved while |
| 18 | /// working in one repo must be visible from every other repo, and the secret |
| 19 | /// store already is. When the ambient config path is a workspace-scoped |
| 20 | /// document (`<repo>/.codewhale/config.toml`), credential writes must not |
| 21 | /// bind the provider or write auth markers there: the binding would be |
| 22 | /// invisible from every other repo and would invite plaintext keys into a |
| 23 | /// committable repo file. Returns a store loaded on the user-global document |
| 24 | /// in that case, or `None` when the ambient store is already correctly |
| 25 | /// scoped, so key + provider binding + auth markers share one user-global |
| 26 | /// scope by default. |
| 27 | pub fn credential_metadata_store(store: &ConfigStore) -> Result<Option<ConfigStore>> { |
| 28 | if !crate::config_path_is_workspace_scoped(store.path()) { |
| 29 | return Ok(None); |
| 30 | } |
| 31 | let global = crate::default_config_path()?; |
| 32 | ConfigStore::load(Some(global)).map(Some) |
| 33 | } |
| 34 | |
| 35 | /// The secret-store slot a provider's key occupies. Shared-account families |
| 36 | /// (SiliconFlow China, the Model Studio variants) collapse onto one slot; |
| 37 | /// see [`ProviderKind::secret_store_slot`]. |
| 38 | #[must_use] |
| 39 | pub fn provider_slot(provider: ProviderKind) -> &'static str { |
| 40 | provider.secret_store_slot() |
| 41 | } |
| 42 | |
| 43 | /// Remove any plaintext `api_key` left in the config for `provider`. |
| 44 | pub fn clear_provider_api_key_from_config(store: &mut ConfigStore, provider: ProviderKind) { |
| 45 | store.config.providers.for_provider_mut(provider).api_key = None; |
| 46 | } |
| 47 | |
| 48 | /// Plaintext-free metadata that accompanies a saved key. |
| 49 | /// |
| 50 | /// Saving a credential never writes a model: every provider resolves an |
| 51 | /// unset model to its own default, and model choice belongs to the |
| 52 | /// model/config commands. |
| 53 | pub fn prepare_provider_api_key_metadata(store: &mut ConfigStore, provider: ProviderKind) { |
| 54 | // The root `auth_mode` is the active provider's fallback marker. Writing |
| 55 | // it for an inactive provider would leak `api_key` onto the active route |
| 56 | // (e.g. a keyless local Ollama), so only the saved provider's own table |
| 57 | // is marked unless it is the active one. |
| 58 | if provider == store.config.provider { |
| 59 | store.config.auth_mode = Some("api_key".to_string()); |
| 60 | } |
| 61 | let provider_config = store.config.providers.for_provider_mut(provider); |
| 62 | provider_config.auth_mode = Some("api_key".to_string()); |
| 63 | provider_config.external_credentials = None; |
| 64 | if matches!(provider, ProviderKind::Xai | ProviderKind::Anthropic) { |
| 65 | provider_config.oauth_credential_generation = None; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | /// ChatGPT plan access uses Codewhale's issued OAuth registration. A saved |
| 70 | /// API key would belong to a different billing route. |
| 71 | pub const OPENAI_CODEX_API_KEY_REFUSAL: &str = "Sign in with ChatGPT via `codewhale auth chatgpt` to use your plan allowance with Codewhale-owned credentials. Use the openai provider for a separately billed API key. Codewhale does not store an API key for this provider."; |
| 72 | |
| 73 | pub const CLAUDE_SIGN_IN_REMOVED: &str = "Claude subscription sign-in was removed in Codewhale 0.10.3: it used Claude Code's sign-in, which Anthropic doesn't allow other apps to use. Use an Anthropic API key instead: run `codewhale auth set --provider anthropic`, or set ANTHROPIC_API_KEY and remove `auth_mode = \"oauth\"` from `[providers.anthropic]`."; |
| 74 | |
| 75 | pub const CLAUDE_ORG_AUTH_MODE: &str = "claude-org"; |
| 76 | |
| 77 | pub const CLAUDE_ORG_KEY_SOURCE: &str = "Claude organization link"; |
| 78 | |
| 79 | pub const CLAUDE_ORG_LINK_COMMAND: &str = "codewhale account claude-org link"; |
| 80 | |
| 81 | #[must_use] |
| 82 | pub fn auth_mode_is_claude_org(auth_mode: Option<&str>) -> bool { |
| 83 | auth_mode.is_some_and(|mode| mode.trim().eq_ignore_ascii_case(CLAUDE_ORG_AUTH_MODE)) |
| 84 | } |
| 85 | |
| 86 | /// Persist a provider credential to the durable secret store without silently |
| 87 | /// downgrading a backend failure to plaintext config storage. |
| 88 | /// |
| 89 | /// Returns `true` when the key landed in the secret store (config then holds |
| 90 | /// metadata only). Callers must not print or echo `api_key`. |
| 91 | pub fn set_provider_api_key( |
| 92 | store: &mut ConfigStore, |
| 93 | secrets: &Secrets, |
| 94 | provider: ProviderKind, |
| 95 | api_key: &str, |
| 96 | ) -> Result<bool> { |
| 97 | anyhow::ensure!( |
| 98 | provider != ProviderKind::OpenaiCodex, |
| 99 | OPENAI_CODEX_API_KEY_REFUSAL |
| 100 | ); |
| 101 | // #6528: strip pasted invisible characters and whitespace in one place. |
| 102 | let api_key = codewhale_secrets::normalize_api_key(api_key); |
| 103 | anyhow::ensure!(!api_key.is_empty(), "Refusing to save an empty API key."); |
| 104 | let api_key = api_key.as_str(); |
| 105 | if provider == ProviderKind::Xai { |
| 106 | return crate::with_xai_oauth_revocation_transaction(|| { |
| 107 | set_provider_api_key_unlocked(store, secrets, provider, api_key) |
| 108 | }); |
| 109 | } |
| 110 | set_provider_api_key_unlocked(store, secrets, provider, api_key) |
| 111 | } |
| 112 | |
| 113 | fn set_provider_api_key_unlocked( |
| 114 | store: &mut ConfigStore, |
| 115 | secrets: &Secrets, |
| 116 | provider: ProviderKind, |
| 117 | api_key: &str, |
| 118 | ) -> Result<bool> { |
| 119 | let original_config = store.config.clone(); |
| 120 | prepare_provider_api_key_metadata(store, provider); |
| 121 | let slot = provider_slot(provider); |
| 122 | // A readable prior value is required before a secret-store write so a |
| 123 | // later config failure can restore the exact prior state. If the backend |
| 124 | // cannot provide that snapshot, fail before changing the config file. |
| 125 | let prior_secret = secrets.get(slot); |
| 126 | let secret_store_saved = match prior_secret.as_ref().map_err(|error| error.to_string()) { |
| 127 | Ok(_) => match secrets.set(slot, api_key) { |
| 128 | Ok(()) => { |
| 129 | clear_provider_api_key_from_config(store, provider); |
| 130 | true |
| 131 | } |
| 132 | Err(err) => { |
| 133 | store.config = original_config; |
| 134 | return Err(anyhow::anyhow!( |
| 135 | "Secret storage write failed for {slot}: {err}. Refusing to write the API key in plaintext to {}. Fix the configured secret backend and retry; Codewhale did not change that file.", |
| 136 | crate::quote_os_path(store.path()) |
| 137 | )); |
| 138 | } |
| 139 | }, |
| 140 | Err(error) => { |
| 141 | store.config = original_config; |
| 142 | return Err(anyhow::anyhow!( |
| 143 | "Secret storage snapshot failed for {slot}: {error}. Refusing to write the API key in plaintext to {}. Fix the configured secret backend and retry; Codewhale did not change that file.", |
| 144 | crate::quote_os_path(store.path()) |
| 145 | )); |
| 146 | } |
| 147 | }; |
| 148 | if let Err(error) = store.save() { |
| 149 | store.config = original_config; |
| 150 | if secret_store_saved { |
| 151 | let current = secrets |
| 152 | .get(slot) |
| 153 | .map_err(|rollback| anyhow::anyhow!( |
| 154 | "{error}; additionally could not verify secret-store rollback for {slot}: {rollback}" |
| 155 | ))?; |
| 156 | if current.as_deref() == Some(api_key) { |
| 157 | match prior_secret.expect("snapshot succeeded before secret write") { |
| 158 | Some(previous) => secrets.set(slot, &previous), |
| 159 | None => secrets.delete(slot), |
| 160 | } |
| 161 | .map_err(|rollback| anyhow::anyhow!( |
| 162 | "{error}; additionally failed to restore prior secret-store state for {slot}: {rollback}" |
| 163 | ))?; |
| 164 | } |
| 165 | } |
| 166 | return Err(error); |
| 167 | } |
| 168 | crate::scrub_plaintext_api_keys_from_config_backup(store.path()) |
| 169 | .context("failed to scrub plaintext API keys from config backup")?; |
| 170 | Ok(secret_store_saved) |
| 171 | } |
| 172 | |
| 173 | /// What a credential clear actually accomplished. |
| 174 | /// |
| 175 | /// The secret-store leg can fail after the config leg has already been |
| 176 | /// persisted. Reporting that separately is the point: a caller that prints |
| 177 | /// "cleared" while the key is still sitting in the keyring has lied about a |
| 178 | /// security-relevant action. |
| 179 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 180 | pub struct ClearOutcome { |
| 181 | /// The secret-store slot the clear targeted. |
| 182 | pub slot: &'static str, |
| 183 | /// `None` when the secret store accepted the delete or holds no key for the |
| 184 | /// slot; otherwise the backend error, already stringified so it carries no |
| 185 | /// credential material. |
| 186 | pub secret_store_error: Option<String>, |
| 187 | } |
| 188 | |
| 189 | impl ClearOutcome { |
| 190 | /// True only when both the config and the secret store were cleared. |
| 191 | #[must_use] |
| 192 | pub fn is_complete(&self) -> bool { |
| 193 | self.secret_store_error.is_none() |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | /// Remove a provider credential from config and the durable secret store. |
| 198 | /// |
| 199 | /// Shared by `codewhale auth clear` and the runtime API's credential route so |
| 200 | /// both get the same ordering and the same rollback: the config document is |
| 201 | /// snapshotted and restored if its save fails, and the secret store is only |
| 202 | /// touched once the config write has landed. A secret-store failure is |
| 203 | /// returned rather than swallowed, because the config no longer advertises a |
| 204 | /// key that the backend may still hold. |
| 205 | /// |
| 206 | /// This deliberately does not clear external-consent or environment-sourced |
| 207 | /// credentials: Codewhale does not own those, and a caller must refuse the |
| 208 | /// request instead of implying it revoked something it cannot reach. |
| 209 | pub fn clear_provider_api_key( |
| 210 | store: &mut ConfigStore, |
| 211 | secrets: &Secrets, |
| 212 | provider: ProviderKind, |
| 213 | ) -> Result<ClearOutcome> { |
| 214 | let slot = provider_slot(provider); |
| 215 | let original_config = store.config.clone(); |
| 216 | clear_provider_api_key_from_config(store, provider); |
| 217 | // Only xAI carries OAuth generation and consent state alongside the key, |
| 218 | // and `codewhale auth clear` has always cleared those three together. Every |
| 219 | // other provider keeps its `auth_mode` marker deliberately: the route is |
| 220 | // still an API-key route, it simply has no key now, which is exactly the |
| 221 | // `missing` credential state a client needs to see. |
| 222 | if provider == ProviderKind::Xai { |
| 223 | let xai = store.config.providers.for_provider_mut(provider); |
| 224 | xai.oauth_credential_generation = None; |
| 225 | xai.auth_mode = None; |
| 226 | xai.external_credentials = None; |
| 227 | } |
| 228 | if let Err(error) = store.save() { |
| 229 | store.config = original_config; |
| 230 | return Err(error); |
| 231 | } |
| 232 | // A backend that refuses every delete (a read-only store) but holds no key |
| 233 | // for this slot has nothing left to revoke, so that refusal is not a |
| 234 | // failure. Both callers get this rule from here. |
| 235 | let secret_store_error = secrets |
| 236 | .delete(slot) |
| 237 | .err() |
| 238 | .filter(|_| !matches!(secrets.get(slot), Ok(None))) |
| 239 | .map(|error| error.to_string()); |
| 240 | Ok(ClearOutcome { |
| 241 | slot, |
| 242 | secret_store_error, |
| 243 | }) |
| 244 | } |
| 245 | |
| 246 | /// One-way digest proving a credential (and the endpoint it is bound to) is |
| 247 | /// still the same one. |
| 248 | /// |
| 249 | /// SHA-256 over a domain-separated, length-prefixed preimage, truncated to 128 |
| 250 | /// bits. Length prefixing keeps `(base_url, key)` unambiguous, so no pair of |
| 251 | /// distinct routes can be made to share a generation by moving bytes across the |
| 252 | /// boundary. The value is never rendered: it is credential-derived, and a |
| 253 | /// stable public digest of a secret is a secret's shadow. |
| 254 | #[derive(Clone, PartialEq, Eq)] |
| 255 | pub struct CredentialGeneration(String); |
| 256 | |
| 257 | impl CredentialGeneration { |
| 258 | #[must_use] |
| 259 | pub fn derive(base_url: &str, credential: &str) -> Self { |
| 260 | let mut hasher = sha2::Sha256::new(); |
| 261 | hasher.update(b"codewhale/turn-route/credential-generation/v1\0"); |
| 262 | hasher.update( |
| 263 | u64::try_from(base_url.len()) |
| 264 | .unwrap_or(u64::MAX) |
| 265 | .to_le_bytes(), |
| 266 | ); |
| 267 | hasher.update(base_url.as_bytes()); |
| 268 | hasher.update( |
| 269 | u64::try_from(credential.len()) |
| 270 | .unwrap_or(u64::MAX) |
| 271 | .to_le_bytes(), |
| 272 | ); |
| 273 | hasher.update(credential.as_bytes()); |
| 274 | let digest = hasher.finalize(); |
| 275 | let mut hex = String::with_capacity(32); |
| 276 | for byte in &digest[..16] { |
| 277 | use std::fmt::Write as _; |
| 278 | let _ = write!(hex, "{byte:02x}"); |
| 279 | } |
| 280 | Self(hex) |
| 281 | } |
| 282 | |
| 283 | pub fn seal_for_worker_pool(&self, key: &[u8; 32], scope: &str) -> String { |
| 284 | use std::fmt::Write as _; |
| 285 | let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key); |
| 286 | let mut mac = ring::hmac::Context::with_key(&key); |
| 287 | mac.update(b"codewhale/worker-model-pool/v1\0"); |
| 288 | mac.update(&(scope.len() as u64).to_le_bytes()); |
| 289 | mac.update(scope.as_bytes()); |
| 290 | mac.update(self.0.as_bytes()); |
| 291 | let mut result = String::with_capacity(64); |
| 292 | for byte in mac.sign().as_ref() { |
| 293 | let _ = write!(result, "{byte:02x}"); |
| 294 | } |
| 295 | result |
| 296 | } |
| 297 | |
| 298 | #[must_use] |
| 299 | pub fn is_empty(&self) -> bool { |
| 300 | self.0.is_empty() |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | /// Redacted: see the type docs. There is no accessor for the digest string. |
| 305 | impl std::fmt::Debug for CredentialGeneration { |
| 306 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 307 | f.write_str("<redacted>") |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | #[cfg(test)] |
| 312 | mod tests { |
| 313 | use super::*; |
| 314 | use codewhale_secrets::{KeyringStore, SecretsError}; |
| 315 | use std::sync::Arc; |
| 316 | |
| 317 | /// A store that refuses every delete and holds `.0` for every slot. |
| 318 | struct UndeletableStore(Option<&'static str>); |
| 319 | |
| 320 | impl KeyringStore for UndeletableStore { |
| 321 | fn get(&self, _key: &str) -> Result<Option<String>, SecretsError> { |
| 322 | Ok(self.0.map(str::to_string)) |
| 323 | } |
| 324 | |
| 325 | fn set(&self, _key: &str, _value: &str) -> Result<(), SecretsError> { |
| 326 | Err(SecretsError::ReadOnly) |
| 327 | } |
| 328 | |
| 329 | fn delete(&self, _key: &str) -> Result<(), SecretsError> { |
| 330 | Err(SecretsError::Keyring("test delete failure".to_string())) |
| 331 | } |
| 332 | |
| 333 | fn backend_name(&self) -> &'static str { |
| 334 | "undeletable test store" |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn a_refused_delete_fails_the_clear_only_while_the_store_still_holds_a_key() { |
| 340 | let dir = tempfile::tempdir().expect("tempdir"); |
| 341 | let path = dir.path().join("config.toml"); |
| 342 | for (held, fails) in [(Some("sk-keyring-fixture"), true), (None, false)] { |
| 343 | let mut store = ConfigStore::load(Some(path.clone())).expect("load config"); |
| 344 | store.config.providers.deepseek.api_key = Some("sk-config-fixture".to_string()); |
| 345 | let secrets = Secrets::new(Arc::new(UndeletableStore(held))); |
| 346 | let outcome = clear_provider_api_key(&mut store, &secrets, ProviderKind::Deepseek) |
| 347 | .expect("the config leg saves"); |
| 348 | assert!(store.config.providers.deepseek.api_key.is_none()); |
| 349 | assert_eq!(outcome.is_complete(), !fails, "delete refusal completion"); |
| 350 | if let Some(error) = outcome.secret_store_error { |
| 351 | assert!( |
| 352 | !error.contains("sk-keyring-fixture"), |
| 353 | "credential leaked into error" |
| 354 | ); |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | fn store_with(body: &str) -> (tempfile::TempDir, ConfigStore) { |
| 360 | let dir = tempfile::tempdir().expect("tempdir"); |
| 361 | let path = dir.path().join("config.toml"); |
| 362 | std::fs::write(&path, body).expect("seed config"); |
| 363 | let store = ConfigStore::load(Some(path)).expect("store loads"); |
| 364 | (dir, store) |
| 365 | } |
| 366 | |
| 367 | fn in_memory_secrets() -> Secrets { |
| 368 | Secrets::new(std::sync::Arc::new( |
| 369 | codewhale_secrets::InMemoryKeyringStore::new(), |
| 370 | )) |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn saving_a_key_for_an_inactive_provider_leaves_root_auth_mode_alone() { |
| 375 | let (_dir, mut store) = store_with("provider = \"ollama\"\n"); |
| 376 | let secrets = in_memory_secrets(); |
| 377 | |
| 378 | set_provider_api_key(&mut store, &secrets, ProviderKind::Openrouter, "or-key") |
| 379 | .expect("save succeeds"); |
| 380 | |
| 381 | let saved = ConfigStore::load(Some(store.path().to_path_buf())).expect("reload"); |
| 382 | assert_eq!(saved.config.provider, ProviderKind::Ollama); |
| 383 | assert_eq!(saved.config.auth_mode, None); |
| 384 | assert_eq!( |
| 385 | saved.config.providers.openrouter.auth_mode.as_deref(), |
| 386 | Some("api_key") |
| 387 | ); |
| 388 | } |
| 389 | |
| 390 | #[test] |
| 391 | fn saving_a_key_for_the_active_provider_still_marks_root_auth_mode() { |
| 392 | let (_dir, mut store) = store_with("provider = \"openrouter\"\n"); |
| 393 | let secrets = in_memory_secrets(); |
| 394 | |
| 395 | set_provider_api_key(&mut store, &secrets, ProviderKind::Openrouter, "or-key") |
| 396 | .expect("save succeeds"); |
| 397 | |
| 398 | let saved = ConfigStore::load(Some(store.path().to_path_buf())).expect("reload"); |
| 399 | assert_eq!(saved.config.auth_mode.as_deref(), Some("api_key")); |
| 400 | } |
| 401 | |
| 402 | #[test] |
| 403 | fn openai_codex_key_save_is_refused_and_keeps_external_consent() { |
| 404 | let (_dir, mut store) = store_with( |
| 405 | "provider = \"openai-codex\"\n\n[providers.openai-codex]\nauth_mode = \"oauth\"\n", |
| 406 | ); |
| 407 | store.config.providers.openai_codex.external_credentials = |
| 408 | Some(crate::ExternalCredentialConsentToml::read_only( |
| 409 | ProviderKind::OpenaiCodex, |
| 410 | crate::ExternalCredentialSource::CodexCli, |
| 411 | std::path::PathBuf::from("/synthetic/codex/auth.json"), |
| 412 | )); |
| 413 | store.save().expect("seed consent"); |
| 414 | let before = std::fs::read_to_string(store.path()).expect("config before"); |
| 415 | let secrets = in_memory_secrets(); |
| 416 | |
| 417 | let error = set_provider_api_key(&mut store, &secrets, ProviderKind::OpenaiCodex, "k") |
| 418 | .expect_err("openai-codex keys are not stored"); |
| 419 | |
| 420 | assert!( |
| 421 | error.to_string().contains("Sign in with ChatGPT"), |
| 422 | "{error}" |
| 423 | ); |
| 424 | assert_eq!( |
| 425 | std::fs::read_to_string(store.path()).expect("config after"), |
| 426 | before |
| 427 | ); |
| 428 | assert!( |
| 429 | store |
| 430 | .config |
| 431 | .providers |
| 432 | .openai_codex |
| 433 | .external_credentials |
| 434 | .is_some() |
| 435 | ); |
| 436 | assert_eq!( |
| 437 | secrets |
| 438 | .get(provider_slot(ProviderKind::OpenaiCodex)) |
| 439 | .expect("read"), |
| 440 | None |
| 441 | ); |
| 442 | } |
| 443 | } |
| 444 |