use super::*;
use crate::credentials::{
AuthContext, CredentialProbe, CredentialResolution, CredentialSource,
context::ProcessAuthContext,
};
pub fn resolve_credential_source(
config: &Config,
identity: &ProviderIdentity,
) -> CredentialResolution {
resolve_credential_source_with(config, identity, &ProcessAuthContext)
}
pub(crate) fn resolve_credential_source_with(
config: &Config,
identity: &ProviderIdentity,
ctx: &dyn AuthContext,
) -> CredentialResolution {
if let Err(error) = config.verify_provider_identity(identity) {
return CredentialResolution::missing(vec![CredentialProbe::with_fix(
error,
"repair the exact provider kind/id pair",
)]);
}
if config.required_account_model_owner.is_some() {
return if config.account_model_api_key(identity).is_some() {
CredentialResolution::found(CredentialSource::AccountSession)
} else {
CredentialResolution::missing(vec![CredentialProbe::with_fix(
"required Codewhale account model access",
"reconnect model access for the signed-in Codewhale account",
)])
};
}
if config.session_provider_api_key(identity).is_some() {
return CredentialResolution::found(CredentialSource::SessionKey);
}
if let Some(source) = config.session_policy_without_key(identity) {
return CredentialResolution { source };
}
let provider = identity.provider;
let mut probed: Vec<CredentialProbe> = Vec::new();
let auth_mode = config.auth_mode_for_provider(identity);
if auth_mode_disables_api_key(auth_mode.as_deref()) {
return CredentialResolution::found(CredentialSource::AuthModeNone);
}
if codewhale_config::credentials::auth_mode_is_claude_org(auth_mode.as_deref()) {
return if provider == ProviderKind::Anthropic
&& !config.provider_uses_custom_endpoint(identity)
{
CredentialResolution::found(CredentialSource::ClaudeOrgLink)
} else {
CredentialResolution::missing(vec![CredentialProbe::with_fix(
"auth_mode = \"claude-org\" (anthropic official endpoint only)",
format!(
"remove base_url or auth_mode from [providers.{}]",
identity.key.as_str()
),
)])
};
}
if provider == ProviderKind::Anthropic && auth_mode.as_deref() == Some("oauth") {
return CredentialResolution::missing(vec![CredentialProbe::with_fix(
"Claude subscription sign-in (removed in 0.10.3)",
"codewhale auth set --provider anthropic",
)]);
}
if provider == ProviderKind::OpenaiCodex && !config.provider_uses_custom_endpoint(identity) {
if let Some(sign_in) =
crate::oauth::usable_sign_in(crate::oauth::OAuthProvider::Chatgpt, config)
{
return CredentialResolution::found(CredentialSource::OAuth {
flow: "ChatGPT".to_string(),
account: sign_in.account_label,
});
}
probed.push(CredentialProbe::with_fix(
"Codewhale-owned ChatGPT sign-in",
"codewhale auth chatgpt",
));
return CredentialResolution::missing(probed);
}
if config
.active_provider_identity()
.is_ok_and(|active| active == *identity)
&& !provider_uses_oauth_credentials(config, identity)
&& explicit_cli_api_key_override().is_some()
{
return CredentialResolution::found(CredentialSource::CliOverride);
}
if let Some(var) = bound_provider_api_key_env_name(config, identity) {
if provider_config_env_api_key(config, identity).is_some() {
return CredentialResolution::found(CredentialSource::ProviderConfigEnv { var });
}
probed.push(CredentialProbe::with_fix(
format!("env {var} (bound by api_key_env)"),
format!("export {var}=<key>"),
));
}
let skip_secret_store = config.should_skip_secret_store_for_provider(identity);
if !skip_secret_store {
if let Some(var) = provider
.provider()
.env_vars()
.iter()
.find(|var| ctx.env(var).is_some())
{
return CredentialResolution::found(CredentialSource::AmbientEnv {
var: (*var).to_string(),
});
}
if let Some(var) = provider.provider().env_vars().first() {
probed.push(CredentialProbe::with_fix(
format!("env {}", provider.provider().env_vars().join(" / ")),
format!("export {var}=<key>"),
));
}
}
if provider == ProviderKind::Moonshot && provider_uses_oauth_credentials(config, identity) {
probed.push(CredentialProbe::with_fix(
"Kimi CLI credentials (never imported)",
"codewhale auth set --provider moonshot",
));
return CredentialResolution::missing(probed);
}
if provider == ProviderKind::Xai
&& !config.provider_uses_custom_endpoint(identity)
&& let Some(sign_in) =
crate::oauth::usable_sign_in(crate::oauth::OAuthProvider::Xai, config)
{
return CredentialResolution::found(CredentialSource::OAuth {
flow: "xAI".to_string(),
account: sign_in.account_label,
});
}
if matches!(
provider,
ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic
) && identity.key.as_str() != codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
&& !config.provider_uses_custom_endpoint(identity)
{
match resolve_external_grant(
config,
identity,
codewhale_config::ExternalCredentialSource::DshCli,
"DeepSeek Harness",
"codewhale auth external-consent --provider deepseek --mode read-only",
|grant| {
crate::dsh_credentials::deepseek_api_key_from_grant(grant)
.ok()
.flatten()
.is_some()
},
) {
Ok(source) => return CredentialResolution::found(source),
Err(probe) => probed.push(probe),
}
}
if !auth_mode_requires_api_key(auth_mode.as_deref())
&& (provider_route_is_keyless_self_hosted(provider, &config.base_url_for_route(identity))
|| (config
.active_provider_identity()
.is_ok_and(|active| active == *identity)
&& base_url_uses_local_host(&config.active_route_base_url())))
{
return CredentialResolution::found(CredentialSource::KeylessRoute {
base_url: config.base_url_for_route(identity),
});
}
if config.config_credentials_are_bound_to_provider_endpoint(identity) {
if config
.provider_route_string_with_deepseek_fallback(identity, |entry| entry.api_key.clone())
.is_some_and(|key| {
classify_config_api_key_value(&key) == ConfigApiKeyValueKind::Literal
})
{
return CredentialResolution::found(CredentialSource::ProviderConfigApiKey {
table: provider_config_table_name(identity)
.unwrap_or_else(|_| format!("providers.{}", identity.key.as_str())),
});
}
if let Ok(table) = provider_config_table_name(identity) {
probed.push(CredentialProbe::with_fix(
format!("[{table}] api_key"),
format!("add api_key to [{table}] in ~/.codewhale/config.toml"),
));
}
}
if !skip_secret_store {
let slot = provider_secret_store_slot(provider).to_string();
if config
.active_provider_identity()
.is_ok_and(|active| active == *identity)
{
if provider_secret_store_api_key(config, identity).is_some() {
return CredentialResolution::found(CredentialSource::SecretStore { slot });
}
probed.push(secret_store_probe(&slot, identity));
} else if secret_slot_save_marker_on_shared_slot(config, identity) {
if provider_secret_store_api_key_with_mode(config, identity, true).is_some() {
return CredentialResolution::found(CredentialSource::SecretStore { slot });
}
probed.push(secret_store_probe(&slot, identity));
} else {
probed.push(CredentialProbe::with_fix(
format!(
"secret store \"{slot}\" (not read: inactive provider, no api-key marker)"
),
format!(
"codewhale auth set --provider {} writes the marker that makes this slot readable while inactive",
identity.key.as_str()
),
));
}
}
if user_global_config_api_key(identity).is_some() {
return CredentialResolution::found(CredentialSource::UserGlobalConfig);
}
probed.push(CredentialProbe::with_fix(
"~/.codewhale/config.toml",
format!("codewhale auth set --provider {}", identity.key.as_str()),
));
if config.account_model_api_key(identity).is_some() {
return CredentialResolution::found(CredentialSource::AccountSession);
}
CredentialResolution::missing(probed)
}
fn secret_store_probe(slot: &str, identity: &ProviderIdentity) -> CredentialProbe {
CredentialProbe::with_fix(
format!("secret store \"{slot}\""),
format!("codewhale auth set --provider {}", identity.key.as_str()),
)
}
fn resolve_external_grant(
config: &Config,
identity: &ProviderIdentity,
source: codewhale_config::ExternalCredentialSource,
cli: &str,
consent_command: &str,
validate: impl FnOnce(&codewhale_config::ExternalCredentialReadGrant) -> bool,
) -> Result<CredentialSource, CredentialProbe> {
let Some(consent) = config
.provider_config_for(identity)
.and_then(|entry| entry.external_credentials.as_ref())
else {
return Err(CredentialProbe::with_fix(
format!("{cli} credentials (no read-only consent recorded)"),
consent_command.to_string(),
));
};
let Ok(grant) = config.external_credential_read_grant(identity, source, &consent.path) else {
return Err(CredentialProbe::with_fix(
format!("{cli} credentials (consent dormant until this provider is selected)"),
format!("codewhale config set provider {}", identity.key.as_str()),
));
};
if validate(&grant) {
return Ok(CredentialSource::ExternalGrant {
cli: cli.to_string(),
path: consent.path.display().to_string(),
});
}
Err(CredentialProbe::with_fix(
format!("{cli} credentials (consented, but no usable credential in that file)"),
format!(
"log in again with {cli}, or run codewhale auth set --provider {}",
identity.key.as_str()
),
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::EnvVarGuard;
use crate::test_support::lock_test_env;
use crate::credentials::context::MapAuthContext;
fn deepseek_config() -> Config {
Config {
provider: Some("deepseek".to_string()),
..Config::default()
}
}
#[test]
fn a_named_env_binding_resolves_and_names_itself() {
let _lock = lock_test_env();
let _key = EnvVarGuard::set("CW_TEST_BOUND_KEY", "bound-value");
let config = Config {
provider: Some("openrouter".to_string()),
providers: Some(
toml::from_str("[openrouter]\napi_key_env = \"CW_TEST_BOUND_KEY\"\n")
.expect("provider table"),
),
..Config::default()
};
let resolution = resolve_credential_source(
&config,
&(config).test_identity_for_kind(ProviderKind::Openrouter),
);
assert_eq!(
resolution.source,
CredentialSource::ProviderConfigEnv {
var: "CW_TEST_BOUND_KEY".to_string()
},
"a route that names its variable must resolve from it and say so"
);
assert_eq!(resolution.source.label(), "api_key_env CW_TEST_BOUND_KEY");
}
#[test]
fn ambient_env_names_the_variable_that_won() {
let _lock = lock_test_env();
let ctx = MapAuthContext::new().with_env("OPENROUTER_API_KEY", "value");
let config = Config::default();
let resolution = resolve_credential_source_with(
&config,
&(config).test_identity_for_kind(ProviderKind::Openrouter),
&ctx,
);
assert_eq!(
resolution.source,
CredentialSource::AmbientEnv {
var: "OPENROUTER_API_KEY".to_string()
}
);
assert_eq!(resolution.source.label(), "OPENROUTER_API_KEY");
}
#[test]
fn a_missing_credential_names_every_place_that_was_checked() {
let _lock = lock_test_env();
let ctx = MapAuthContext::new();
let config = Config::default();
let resolution = resolve_credential_source_with(
&config,
&(config).test_identity_for_kind(ProviderKind::Openrouter),
&ctx,
);
assert!(!resolution.is_present());
let checked = resolution.checked_places();
assert!(
checked.contains("OPENROUTER_API_KEY"),
"the ambient variable must be named: {checked}"
);
assert!(
checked.contains("secret store \"openrouter\""),
"the durable slot must be named: {checked}"
);
assert!(
checked.contains("~/.codewhale/config.toml"),
"the user-global config must be named: {checked}"
);
assert_eq!(
resolution.first_fix(),
Some("export OPENROUTER_API_KEY=<key>"),
"the first probed place must carry the command that fixes it"
);
}
#[test]
fn an_unread_secret_slot_says_it_was_not_read_and_why() {
let _lock = lock_test_env();
let ctx = MapAuthContext::new();
let config = deepseek_config();
let resolution = resolve_credential_source_with(
&config,
&(config).test_identity_for_kind(ProviderKind::Openrouter),
&ctx,
);
let checked = resolution.checked_places();
assert!(
checked.contains("(not read: inactive provider, no api-key marker)"),
"an unread slot must not look like an empty one: {checked}"
);
}
#[test]
fn no_auth_routes_resolve_to_the_auth_mode_itself() {
let _lock = lock_test_env();
let config = Config {
providers: Some(
toml::from_str("[openrouter]\nauth_mode = \"none\"\n").expect("provider table"),
),
..Config::default()
};
let resolution = resolve_credential_source(
&config,
&(config).test_identity_for_kind(ProviderKind::Openrouter),
);
assert_eq!(resolution.source, CredentialSource::AuthModeNone);
assert!(resolution.is_present());
assert!(resolution.checked_places().is_empty());
}
}