返回 CodeWhale
credential_resolve.rs
根目录 / crates / runtime / src / config / credential_resolve.rs
1 //! The one place provider credential precedence is decided.
2 //!
3 //! Ported from pi-mono `packages/ai/src/auth/resolve.ts` (MIT, Copyright (c)
4 //! 2025 Mario Zechner; full notice in `codewhale_runtime::credentials`). The idea taken is
5 //! pi's: a single resolver, one precedence rule stated in a doc comment beside
6 //! it, and a result that names the place it resolved from. The walk itself is
7 //! CodeWhale's — it is the former body of `has_api_key_for`, moved here
8 //! unchanged in order so no existing decision changes, with a
9 //! [`CredentialSource`] attached to each outcome.
10 //!
11 //! # Precedence rule
12 //!
13 //! **An endpoint-bound exact session key on an authenticated eligible route
14 //! outranks durable and ambient sources. Required account ownership forbids
15 //! every fallback.**
16 //!
17 //! CodeWhale's order below is that rule instantiated over the stores it
18 //! actually has. Reading top to bottom:
19 //!
20 //! 1. Required Codewhale account model ownership, with no fallback.
21 //! 2. A process-only session key for the exact provider identity and endpoint,
22 //! subject to the durable secret store's route eligibility rules.
23 //! 3. `auth_mode = "none"` — the route sends no credential at all.
24 //! 4. An explicit `--api-key` on the active, non-OAuth provider.
25 //! 5. `[providers.<name>] api_key_env` — a credential the route *names*.
26 //! 6. An ambient provider environment variable (official endpoints only).
27 //! 7. Provider-owned login state: an explicitly consented supported external
28 //! CLI credential file (Codex or DeepSeek Harness) or CodeWhale's own xAI
29 //! OAuth storage.
30 //! 8. A keyless self-hosted / loopback route.
31 //! 9. `[providers.<name>] api_key` in the config file.
32 //! 10. CodeWhale's durable secret store.
33 //! 11. The root `api_key` compatibility slot.
34 //! 12. The user-global `~/.codewhale/config.toml`.
35 //! 13. Codewhale account model access when no owner is required.
36 //!
37 //! Two departures from pi are deliberate and load-bearing here:
38 //!
39 //! * Ambient env outranks the secret store for a *named* binding (step 5) and
40 //! for official-endpoint provider variables (step 6). That is CodeWhale's
41 //! existing, documented behavior and users depend on it; changing it is not
42 //! in this lane's scope. It is stated here so it is at least *visible*.
43 //! * External CLI credential files are only ever consulted through
44 //! [`Config::external_credential_read_grant`], which enforces the read-only
45 //! consent model (exact path, explicit consent, never refreshed, never
46 //! rewritten). This resolver adds no new way to reach them, and #5772 tightens
47 //! the two ends of that model:
48 //! - **Nothing happens before consent.** With no persisted consent record
49 //! for a provider, this resolver resolves no candidate path, performs no
50 //! filesystem access, and names no location. Deriving a candidate from
51 //! `HOME` just to say "absent" is itself an unconsented disclosure of where
52 //! another CLI keeps credentials.
53 //! - **A consent record is not a credential.** Consent proves the user
54 //! authorized reading one exact file; it does not prove that file still
55 //! holds a usable token. Once consent exists, the consented file is read
56 //! through the secure adapter — the read the user actually authorized — so
57 //! a missing, malformed, or expired external credential resolves as missing
58 //! rather than masquerading as a stored one.
59 //!
60 //! # Redaction
61 //!
62 //! This module never returns, logs, or renders secret material. It returns
63 //! only a [`CredentialSource`] label. Every probe that needs a value calls an
64 //! existing helper and discards the value with `.is_some()`.
65
66 use super::*;
67 use crate::credentials::{
68 AuthContext, CredentialProbe, CredentialResolution, CredentialSource,
69 context::ProcessAuthContext,
70 };
71
72 /// Resolve which place holds a credential for `provider`, using the real
73 /// process environment.
74 pub fn resolve_credential_source(
75 config: &Config,
76 identity: &ProviderIdentity,
77 ) -> CredentialResolution {
78 resolve_credential_source_with(config, identity, &ProcessAuthContext)
79 }
80
81 /// Resolve with an injected [`AuthContext`].
82 ///
83 /// Only the ambient reads this function performs *itself* go through `ctx`.
84 /// The provider-specific helpers it delegates to (secret store, external
85 /// grants, xAI OAuth) still read the real environment and filesystem; making
86 /// those injectable means threading a context through config.rs and is not in
87 /// this lane.
88 pub(crate) fn resolve_credential_source_with(
89 config: &Config,
90 identity: &ProviderIdentity,
91 ctx: &dyn AuthContext,
92 ) -> CredentialResolution {
93 if let Err(error) = config.verify_provider_identity(identity) {
94 return CredentialResolution::missing(vec![CredentialProbe::with_fix(
95 error,
96 "repair the exact provider kind/id pair",
97 )]);
98 }
99 if config.required_account_model_owner.is_some() {
100 return if config.account_model_api_key(identity).is_some() {
101 CredentialResolution::found(CredentialSource::AccountSession)
102 } else {
103 CredentialResolution::missing(vec![CredentialProbe::with_fix(
104 "required Codewhale account model access",
105 "reconnect model access for the signed-in Codewhale account",
106 )])
107 };
108 }
109 if config.session_provider_api_key(identity).is_some() {
110 return CredentialResolution::found(CredentialSource::SessionKey);
111 }
112 if let Some(source) = config.session_policy_without_key(identity) {
113 return CredentialResolution { source };
114 }
115 let provider = identity.provider;
116 let mut probed: Vec<CredentialProbe> = Vec::new();
117
118 let auth_mode = config.auth_mode_for_provider(identity);
119 if auth_mode_disables_api_key(auth_mode.as_deref()) {
120 return CredentialResolution::found(CredentialSource::AuthModeNone);
121 }
122
123 if codewhale_config::credentials::auth_mode_is_claude_org(auth_mode.as_deref()) {
124 return if provider == ProviderKind::Anthropic
125 && !config.provider_uses_custom_endpoint(identity)
126 {
127 CredentialResolution::found(CredentialSource::ClaudeOrgLink)
128 } else {
129 CredentialResolution::missing(vec![CredentialProbe::with_fix(
130 "auth_mode = \"claude-org\" (anthropic official endpoint only)",
131 format!(
132 "remove base_url or auth_mode from [providers.{}]",
133 identity.key.as_str()
134 ),
135 )])
136 };
137 }
138
139 // The public ChatGPT API accepts only Codewhale's own issued registration.
140 // Environment tokens and consented Codex files belong to different clients.
141 if provider == ProviderKind::Anthropic && auth_mode.as_deref() == Some("oauth") {
142 return CredentialResolution::missing(vec![CredentialProbe::with_fix(
143 "Claude subscription sign-in (removed in 0.10.3)",
144 "codewhale auth set --provider anthropic",
145 )]);
146 }
147 if provider == ProviderKind::OpenaiCodex && !config.provider_uses_custom_endpoint(identity) {
148 if let Some(sign_in) =
149 crate::oauth::usable_sign_in(crate::oauth::OAuthProvider::Chatgpt, config)
150 {
151 return CredentialResolution::found(CredentialSource::OAuth {
152 flow: "ChatGPT".to_string(),
153 account: sign_in.account_label,
154 });
155 }
156 probed.push(CredentialProbe::with_fix(
157 "Codewhale-owned ChatGPT sign-in",
158 "codewhale auth chatgpt",
159 ));
160 return CredentialResolution::missing(probed);
161 }
162
163 if config
164 .active_provider_identity()
165 .is_ok_and(|active| active == *identity)
166 && !provider_uses_oauth_credentials(config, identity)
167 && explicit_cli_api_key_override().is_some()
168 {
169 return CredentialResolution::found(CredentialSource::CliOverride);
170 }
171
172 if let Some(var) = bound_provider_api_key_env_name(config, identity) {
173 if provider_config_env_api_key(config, identity).is_some() {
174 return CredentialResolution::found(CredentialSource::ProviderConfigEnv { var });
175 }
176 probed.push(CredentialProbe::with_fix(
177 format!("env {var} (bound by api_key_env)"),
178 format!("export {var}=<key>"),
179 ));
180 }
181
182 let skip_secret_store = config.should_skip_secret_store_for_provider(identity);
183 if !skip_secret_store {
184 if let Some(var) = provider
185 .provider()
186 .env_vars()
187 .iter()
188 .find(|var| ctx.env(var).is_some())
189 {
190 return CredentialResolution::found(CredentialSource::AmbientEnv {
191 var: (*var).to_string(),
192 });
193 }
194 if let Some(var) = provider.provider().env_vars().first() {
195 probed.push(CredentialProbe::with_fix(
196 format!("env {}", provider.provider().env_vars().join(" / ")),
197 format!("export {var}=<key>"),
198 ));
199 }
200 }
201
202 if provider == ProviderKind::Moonshot && provider_uses_oauth_credentials(config, identity) {
203 // Kimi CLI credentials are never imported; the route needs its own key.
204 probed.push(CredentialProbe::with_fix(
205 "Kimi CLI credentials (never imported)",
206 "codewhale auth set --provider moonshot",
207 ));
208 return CredentialResolution::missing(probed);
209 }
210 if provider == ProviderKind::Xai
211 && !config.provider_uses_custom_endpoint(identity)
212 && let Some(sign_in) =
213 crate::oauth::usable_sign_in(crate::oauth::OAuthProvider::Xai, config)
214 {
215 // xAI supports both API keys and OAuth. A Grok-compatible token file is
216 // sufficient, but its absence must fall through to the ordinary API-key
217 // checks below instead of masking a configured key.
218 return CredentialResolution::found(CredentialSource::OAuth {
219 flow: "xAI".to_string(),
220 account: sign_in.account_label,
221 });
222 }
223 if matches!(
224 provider,
225 ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
226 ) && identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
227 && !config.provider_uses_custom_endpoint(identity)
228 {
229 match resolve_external_grant(
230 config,
231 identity,
232 codewhale_config::ExternalCredentialSource::DshCli,
233 "DeepSeek Harness",
234 "codewhale auth external-consent --provider deepseek --mode read-only",
235 |grant| {
236 crate::dsh_credentials::deepseek_api_key_from_grant(grant)
237 .ok()
238 .flatten()
239 .is_some()
240 },
241 ) {
242 Ok(source) => return CredentialResolution::found(source),
243 Err(probe) => probed.push(probe),
244 }
245 }
246
247 if !auth_mode_requires_api_key(auth_mode.as_deref())
248 && (provider_route_is_keyless_self_hosted(provider, &config.base_url_for_route(identity))
249 || (config
250 .active_provider_identity()
251 .is_ok_and(|active| active == *identity)
252 && base_url_uses_local_host(&config.active_route_base_url())))
253 {
254 return CredentialResolution::found(CredentialSource::KeylessRoute {
255 base_url: config.base_url_for_route(identity),
256 });
257 }
258
259 if config.config_credentials_are_bound_to_provider_endpoint(identity) {
260 if config
261 .provider_route_string_with_deepseek_fallback(identity, |entry| entry.api_key.clone())
262 .is_some_and(|key| {
263 classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
264 })
265 {
266 return CredentialResolution::found(CredentialSource::ProviderConfigApiKey {
267 table: provider_config_table_name(identity)
268 .unwrap_or_else(|_| format!("providers.{}", identity.key.as_str())),
269 });
270 }
271 if let Ok(table) = provider_config_table_name(identity) {
272 probed.push(CredentialProbe::with_fix(
273 format!("[{table}] api_key"),
274 format!("add api_key to [{table}] in ~/.codewhale/config.toml"),
275 ));
276 }
277 }
278 // Probe the active provider, plus any provider whose persisted
279 // `[providers.<name>]` table carries the marker the secret-store save
280 // path itself writes (an api-key auth mode with no config literal). A
281 // configured-but-inactive provider must not render as unconfigured just
282 // because the operator switched providers after saving its key (#5033).
283 // Shared-slot families (one account, several provider variants — e.g.
284 // Model Studio Token/Coding Plan × OpenAI/Anthropic dialects) honor the
285 // marker written by ANY sibling variant, since the save path stores one
286 // key under the family's canonical slot. The probe stays bounded to
287 // explicitly configured providers, and the non-active case is strictly
288 // read-only so rendering the catalog never migrates a legacy store or
289 // opens a write-capable backend.
290 if !skip_secret_store {
291 let slot = provider_secret_store_slot(provider).to_string();
292 if config
293 .active_provider_identity()
294 .is_ok_and(|active| active == *identity)
295 {
296 if provider_secret_store_api_key(config, identity).is_some() {
297 return CredentialResolution::found(CredentialSource::SecretStore { slot });
298 }
299 probed.push(secret_store_probe(&slot, identity));
300 } else if secret_slot_save_marker_on_shared_slot(config, identity) {
301 if provider_secret_store_api_key_with_mode(config, identity, true).is_some() {
302 return CredentialResolution::found(CredentialSource::SecretStore { slot });
303 }
304 probed.push(secret_store_probe(&slot, identity));
305 } else {
306 // #5033's marker gate: without a `[providers.<name>]` api-key
307 // auth-mode marker the store is not read at all for an inactive
308 // provider. Say so, because the row is otherwise indistinguishable
309 // from a genuinely empty slot — and the request path *would* read
310 // it once this provider became active.
311 probed.push(CredentialProbe::with_fix(
312 format!(
313 "secret store \"{slot}\" (not read: inactive provider, no api-key marker)"
314 ),
315 format!(
316 "codewhale auth set --provider {} writes the marker that makes this slot readable while inactive",
317 identity.key.as_str()
318 ),
319 ));
320 }
321 }
322
323 // Last resort: the user-global config file. A key saved there must not
324 // disappear just because this process loaded a workspace config.
325 if user_global_config_api_key(identity).is_some() {
326 return CredentialResolution::found(CredentialSource::UserGlobalConfig);
327 }
328 probed.push(CredentialProbe::with_fix(
329 "~/.codewhale/config.toml",
330 format!("codewhale auth set --provider {}", identity.key.as_str()),
331 ));
332
333 if config.account_model_api_key(identity).is_some() {
334 return CredentialResolution::found(CredentialSource::AccountSession);
335 }
336
337 CredentialResolution::missing(probed)
338 }
339
340 fn secret_store_probe(slot: &str, identity: &ProviderIdentity) -> CredentialProbe {
341 CredentialProbe::with_fix(
342 format!("secret store \"{slot}\""),
343 format!("codewhale auth set --provider {}", identity.key.as_str()),
344 )
345 }
346
347 /// Resolve one external CLI credential owner for `provider` (#5772).
348 ///
349 /// The order here is the whole invariant, and each step is gated on the one
350 /// before it:
351 ///
352 /// 1. **No consent record** — nothing is resolved, stat'ed, read, or named.
353 /// The probe offers only the explicit consent command, because deriving a
354 /// candidate path from `HOME` in order to report it would already disclose
355 /// where another CLI keeps credentials.
356 /// 2. **Consent record, provider not active** — the grant is refused by
357 /// [`Config::external_credential_read_grant`], so the record is reported as
358 /// dormant. Still no filesystem access.
359 /// 3. **Consent record, provider active** — the exact consented file is read
360 /// through the secure adapter and `validate` decides whether it holds a
361 /// usable credential. Structural consent alone never resolves as found.
362 fn resolve_external_grant(
363 config: &Config,
364 identity: &ProviderIdentity,
365 source: codewhale_config::ExternalCredentialSource,
366 cli: &str,
367 consent_command: &str,
368 validate: impl FnOnce(&codewhale_config::ExternalCredentialReadGrant) -> bool,
369 ) -> Result<CredentialSource, CredentialProbe> {
370 let Some(consent) = config
371 .provider_config_for(identity)
372 .and_then(|entry| entry.external_credentials.as_ref())
373 else {
374 return Err(CredentialProbe::with_fix(
375 format!("{cli} credentials (no read-only consent recorded)"),
376 consent_command.to_string(),
377 ));
378 };
379 // The pinned path comes from the consent record the user confirmed, never
380 // from an ambient candidate, so no resolver runs here either.
381 let Ok(grant) = config.external_credential_read_grant(identity, source, &consent.path) else {
382 return Err(CredentialProbe::with_fix(
383 format!("{cli} credentials (consent dormant until this provider is selected)"),
384 format!("codewhale config set provider {}", identity.key.as_str()),
385 ));
386 };
387 if validate(&grant) {
388 return Ok(CredentialSource::ExternalGrant {
389 cli: cli.to_string(),
390 path: consent.path.display().to_string(),
391 });
392 }
393 // Consented, read, and unusable: missing, malformed, or expired. Read-only
394 // consent never refreshes another CLI's file, so the fix is to renew it
395 // there — not to re-consent here.
396 Err(CredentialProbe::with_fix(
397 format!("{cli} credentials (consented, but no usable credential in that file)"),
398 format!(
399 "log in again with {cli}, or run codewhale auth set --provider {}",
400 identity.key.as_str()
401 ),
402 ))
403 }
404
405 #[cfg(test)]
406 mod tests {
407 use super::*;
408
409 use crate::test_support::EnvVarGuard;
410
411 use crate::test_support::lock_test_env;
412
413 use crate::credentials::context::MapAuthContext;
414
415 fn deepseek_config() -> Config {
416 Config {
417 provider: Some("deepseek".to_string()),
418 ..Config::default()
419 }
420 }
421
422 /// The precedence rule has to be enforced somewhere a test can see it.
423 #[test]
424 fn a_named_env_binding_resolves_and_names_itself() {
425 let _lock = lock_test_env();
426 let _key = EnvVarGuard::set("CW_TEST_BOUND_KEY", "bound-value");
427 let config = Config {
428 provider: Some("openrouter".to_string()),
429 providers: Some(
430 toml::from_str("[openrouter]\napi_key_env = \"CW_TEST_BOUND_KEY\"\n")
431 .expect("provider table"),
432 ),
433 ..Config::default()
434 };
435 let resolution = resolve_credential_source(
436 &config,
437 &(config).test_identity_for_kind(ProviderKind::Openrouter),
438 );
439 assert_eq!(
440 resolution.source,
441 CredentialSource::ProviderConfigEnv {
442 var: "CW_TEST_BOUND_KEY".to_string()
443 },
444 "a route that names its variable must resolve from it and say so"
445 );
446 assert_eq!(resolution.source.label(), "api_key_env CW_TEST_BOUND_KEY");
447 }
448
449 /// An ambient export must name the exact variable that won, not just
450 /// "configured" — this is pi's `source: "ANTHROPIC_API_KEY"`.
451 #[test]
452 fn ambient_env_names_the_variable_that_won() {
453 let _lock = lock_test_env();
454 let ctx = MapAuthContext::new().with_env("OPENROUTER_API_KEY", "value");
455 let config = Config::default();
456 let resolution = resolve_credential_source_with(
457 &config,
458 &(config).test_identity_for_kind(ProviderKind::Openrouter),
459 &ctx,
460 );
461 assert_eq!(
462 resolution.source,
463 CredentialSource::AmbientEnv {
464 var: "OPENROUTER_API_KEY".to_string()
465 }
466 );
467 assert_eq!(resolution.source.label(), "OPENROUTER_API_KEY");
468 }
469
470 /// The regression this whole lane exists for: a provider with no
471 /// credential anywhere used to report a bare boolean. It must now name
472 /// every place that was probed, in precedence order, and offer a fix.
473 #[test]
474 fn a_missing_credential_names_every_place_that_was_checked() {
475 let _lock = lock_test_env();
476 let ctx = MapAuthContext::new();
477 let config = Config::default();
478 let resolution = resolve_credential_source_with(
479 &config,
480 &(config).test_identity_for_kind(ProviderKind::Openrouter),
481 &ctx,
482 );
483 assert!(!resolution.is_present());
484
485 let checked = resolution.checked_places();
486 assert!(
487 checked.contains("OPENROUTER_API_KEY"),
488 "the ambient variable must be named: {checked}"
489 );
490 assert!(
491 checked.contains("secret store \"openrouter\""),
492 "the durable slot must be named: {checked}"
493 );
494 assert!(
495 checked.contains("~/.codewhale/config.toml"),
496 "the user-global config must be named: {checked}"
497 );
498 assert_eq!(
499 resolution.first_fix(),
500 Some("export OPENROUTER_API_KEY=<key>"),
501 "the first probed place must carry the command that fixes it"
502 );
503 }
504
505 /// #5033's marker gate is a real asymmetry between what the picker
506 /// reports and what the request path would find: for a provider that is
507 /// not active and whose config table carries no api-key marker, the
508 /// durable slot is *not read at all*. That is defensible, but it must be
509 /// visible — a user staring at "missing key" has to be told the slot was
510 /// skipped rather than found empty.
511 #[test]
512 fn an_unread_secret_slot_says_it_was_not_read_and_why() {
513 let _lock = lock_test_env();
514 let ctx = MapAuthContext::new();
515 let config = deepseek_config();
516 let resolution = resolve_credential_source_with(
517 &config,
518 &(config).test_identity_for_kind(ProviderKind::Openrouter),
519 &ctx,
520 );
521
522 let checked = resolution.checked_places();
523 assert!(
524 checked.contains("(not read: inactive provider, no api-key marker)"),
525 "an unread slot must not look like an empty one: {checked}"
526 );
527 }
528
529 /// `auth_mode = "none"` is a resolution, not an absence.
530 #[test]
531 fn no_auth_routes_resolve_to_the_auth_mode_itself() {
532 let _lock = lock_test_env();
533 let config = Config {
534 providers: Some(
535 toml::from_str("[openrouter]\nauth_mode = \"none\"\n").expect("provider table"),
536 ),
537 ..Config::default()
538 };
539 let resolution = resolve_credential_source(
540 &config,
541 &(config).test_identity_for_kind(ProviderKind::Openrouter),
542 );
543 assert_eq!(resolution.source, CredentialSource::AuthModeNone);
544 assert!(resolution.is_present());
545 assert!(resolution.checked_places().is_empty());
546 }
547 }
548
548 lines RUST