| 1 | //! Truthful, session-local provider readiness. |
| 2 | //! |
| 3 | //! Static configuration can prove that credential material exists, but not |
| 4 | //! that an endpoint is reachable or an OAuth token is still entitled to a |
| 5 | //! model. `Ready` is therefore reserved for observed success in this session. |
| 6 | |
| 7 | use std::borrow::Cow; |
| 8 | |
| 9 | use codewhale_config::ProviderKind; |
| 10 | use codewhale_config::route::{LogicalModelRef, RouteRequest, RouteResolver}; |
| 11 | use codewhale_error_taxonomy::{ErrorCategory, ErrorEnvelope}; |
| 12 | use codewhale_runtime::config::{ |
| 13 | Config, ProviderIdentity, provider_is_configured, resolve_credential_source, |
| 14 | }; |
| 15 | |
| 16 | /// Check if the active provider has any API key configured anywhere the |
| 17 | /// runtime can resolve it. |
| 18 | /// |
| 19 | /// The default secret store is file-backed and prompt-free. An OS credential |
| 20 | /// store is queried only when the user explicitly selects the system backend. |
| 21 | /// |
| 22 | /// Used by the TUI app constructor to decide whether to gate |
| 23 | /// the user behind the in-TUI api-key onboarding screen — getting |
| 24 | /// this wrong made users get prompted for credentials in situations |
| 25 | /// where normal env/config auth was already available. |
| 26 | pub fn has_api_key(config: &Config) -> bool { |
| 27 | config |
| 28 | .active_provider_identity() |
| 29 | .is_ok_and(|identity| has_api_key_for(config, &identity)) |
| 30 | } |
| 31 | |
| 32 | /// Check whether the given provider has any usable API key — via env var, |
| 33 | /// provider/root config. Used by the `/provider` picker to decide whether to |
| 34 | /// prompt for a key inline. |
| 35 | #[must_use] |
| 36 | pub fn has_api_key_for(config: &Config, identity: &ProviderIdentity) -> bool { |
| 37 | if identity.provider == ProviderKind::Custom |
| 38 | && config |
| 39 | .provider_config_for(identity) |
| 40 | .is_some_and(|entry| entry.oauth.is_some()) |
| 41 | { |
| 42 | return credential_state_for_provider(config, identity) == CredentialState::Saved; |
| 43 | } |
| 44 | resolve_credential_source(config, identity).is_present() |
| 45 | } |
| 46 | |
| 47 | /// Convenience wrapper around [`provider_is_configured`] for callers that |
| 48 | /// just want "is this provider configured given the active one," without |
| 49 | /// the provider picker's multi-row named-custom-provider bookkeeping |
| 50 | /// (`is_named_custom_entry`) — e.g. the `/model` picker (#3830), which only |
| 51 | /// ever resolves the single, currently-selected `Custom` slot via |
| 52 | /// [`Config::provider_config_for`], the same way model/route resolution |
| 53 | /// does everywhere else. |
| 54 | #[must_use] |
| 55 | pub fn provider_is_configured_for_active( |
| 56 | config: &Config, |
| 57 | identity: &ProviderIdentity, |
| 58 | active: &ProviderIdentity, |
| 59 | ) -> bool { |
| 60 | provider_is_configured( |
| 61 | identity.provider, |
| 62 | identity == active, |
| 63 | has_api_key_for(config, identity), |
| 64 | config.provider_config_for(identity), |
| 65 | identity.provider == ProviderKind::Custom, |
| 66 | ) |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 70 | pub enum CredentialState { |
| 71 | MissingKey, |
| 72 | MissingLogin, |
| 73 | /// Structurally valid read-only consent exists for another CLI's file, |
| 74 | /// but the provider is not active so no read capability has been minted. |
| 75 | ExternalConsent, |
| 76 | Saved, |
| 77 | ImportedToken, |
| 78 | NoAuth, |
| 79 | Local, |
| 80 | Legacy, |
| 81 | } |
| 82 | |
| 83 | /// Credential route whose observed health may be reused. A provider can |
| 84 | /// expose more than one auth route (notably xAI and Moonshot), so provider id |
| 85 | /// alone is not a safe cache key: a successful API-key request must not make a |
| 86 | /// newly selected imported-token or OAuth route appear verified. |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 88 | pub enum ProviderAuthClass { |
| 89 | ApiKey, |
| 90 | OAuth, |
| 91 | ImportedToken, |
| 92 | NoAuth, |
| 93 | Local, |
| 94 | Legacy, |
| 95 | } |
| 96 | |
| 97 | /// Exact route whose observed health may be reused. This deliberately keeps |
| 98 | /// custom provider id, endpoint, model, and auth class together: success on |
| 99 | /// one private endpoint or model entitlement is not evidence for another. |
| 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 101 | pub struct ProviderRouteIdentity { |
| 102 | identity: ProviderIdentity, |
| 103 | endpoint: String, |
| 104 | model: String, |
| 105 | auth_class: ProviderAuthClass, |
| 106 | credential_generation: Option<codewhale_config::credentials::CredentialGeneration>, |
| 107 | } |
| 108 | |
| 109 | impl ProviderRouteIdentity { |
| 110 | pub(crate) fn has_keyless_credential(&self, base_url: &str) -> bool { |
| 111 | self.credential_generation.as_ref() |
| 112 | == Some(&codewhale_config::credentials::CredentialGeneration::derive(base_url, "")) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | pub fn route_identity_for_model( |
| 117 | config: &codewhale_runtime::config::Config, |
| 118 | identity: &ProviderIdentity, |
| 119 | model: &str, |
| 120 | ) -> ProviderRouteIdentity { |
| 121 | let endpoint = crate::route_receipt::endpoint_identity(&config.base_url_for_route(identity)); |
| 122 | ProviderRouteIdentity { |
| 123 | identity: identity.clone(), |
| 124 | endpoint, |
| 125 | model: model.trim().to_string(), |
| 126 | auth_class: auth_class_for_provider(config, identity), |
| 127 | credential_generation: config.readonly_health_credential_generation(identity), |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | pub fn inventory_observation_for_route( |
| 132 | config: &Config, |
| 133 | identity: &ProviderIdentity, |
| 134 | ) -> ProviderRouteIdentity { |
| 135 | let mut observation = route_identity_for_model(config, identity, ""); |
| 136 | if observation.credential_generation.is_none() { |
| 137 | let mut scoped = config.clone(); |
| 138 | scoped.plugin_oauth_read_only = true; |
| 139 | if scoped.scope_to_provider_identity(identity).is_ok() { |
| 140 | observation.credential_generation = |
| 141 | scoped |
| 142 | .active_route_api_key_read_only() |
| 143 | .ok() |
| 144 | .map(|credential| { |
| 145 | codewhale_config::credentials::CredentialGeneration::derive( |
| 146 | &scoped.base_url_for_route(identity), |
| 147 | &credential, |
| 148 | ) |
| 149 | }); |
| 150 | } |
| 151 | } |
| 152 | observation |
| 153 | } |
| 154 | |
| 155 | pub fn auth_class_for_provider( |
| 156 | config: &codewhale_runtime::config::Config, |
| 157 | identity: &ProviderIdentity, |
| 158 | ) -> ProviderAuthClass { |
| 159 | let provider = identity.provider; |
| 160 | if config.verify_provider_identity(identity).is_err() { |
| 161 | return ProviderAuthClass::Legacy; |
| 162 | } |
| 163 | if config.required_account_model_owner.is_some() |
| 164 | || config.session_provider_api_key(identity).is_some() |
| 165 | { |
| 166 | return ProviderAuthClass::ApiKey; |
| 167 | } |
| 168 | if config.session_provider_keys_only { |
| 169 | return match credential_state_for_provider(config, identity) { |
| 170 | CredentialState::NoAuth => ProviderAuthClass::NoAuth, |
| 171 | CredentialState::Local => ProviderAuthClass::Local, |
| 172 | _ => ProviderAuthClass::ApiKey, |
| 173 | }; |
| 174 | } |
| 175 | let auth_mode = config.auth_mode_for_provider(identity); |
| 176 | if provider == ProviderKind::Custom |
| 177 | && config |
| 178 | .provider_config_for(identity) |
| 179 | .is_some_and(|entry| entry.oauth.is_some()) |
| 180 | { |
| 181 | return ProviderAuthClass::OAuth; |
| 182 | } |
| 183 | if codewhale_config::auth_mode_disables_api_key(auth_mode.as_deref()) { |
| 184 | return ProviderAuthClass::NoAuth; |
| 185 | } |
| 186 | let official_endpoint = !config.provider_uses_custom_endpoint(identity); |
| 187 | if provider == ProviderKind::OpenaiCodex && official_endpoint { |
| 188 | return ProviderAuthClass::OAuth; |
| 189 | } |
| 190 | if provider == ProviderKind::Moonshot |
| 191 | && official_endpoint |
| 192 | && auth_mode |
| 193 | .as_deref() |
| 194 | .is_some_and(codewhale_config::auth_mode_uses_kimi_imported_token) |
| 195 | { |
| 196 | return ProviderAuthClass::ImportedToken; |
| 197 | } |
| 198 | if provider == ProviderKind::Xai |
| 199 | && official_endpoint |
| 200 | && auth_mode |
| 201 | .as_deref() |
| 202 | .is_some_and(codewhale_runtime::oauth::auth_mode_uses_xai_oauth) |
| 203 | { |
| 204 | return ProviderAuthClass::OAuth; |
| 205 | } |
| 206 | match credential_state_for_provider(config, identity) { |
| 207 | CredentialState::NoAuth => ProviderAuthClass::NoAuth, |
| 208 | CredentialState::Local => ProviderAuthClass::Local, |
| 209 | CredentialState::Legacy => ProviderAuthClass::Legacy, |
| 210 | CredentialState::ExternalConsent => ProviderAuthClass::OAuth, |
| 211 | _ => ProviderAuthClass::ApiKey, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | pub fn credential_state_for_provider( |
| 216 | config: &codewhale_runtime::config::Config, |
| 217 | identity: &ProviderIdentity, |
| 218 | ) -> CredentialState { |
| 219 | let provider = identity.provider; |
| 220 | if provider == ProviderKind::Antigravity { |
| 221 | return CredentialState::Legacy; |
| 222 | } |
| 223 | if config.verify_provider_identity(identity).is_err() { |
| 224 | return CredentialState::MissingKey; |
| 225 | } |
| 226 | if config.required_account_model_owner.is_some() { |
| 227 | return if config.account_model_api_key(identity).is_some() { |
| 228 | CredentialState::Saved |
| 229 | } else { |
| 230 | CredentialState::MissingKey |
| 231 | }; |
| 232 | } |
| 233 | if config.session_provider_api_key(identity).is_some() { |
| 234 | return CredentialState::Saved; |
| 235 | } |
| 236 | if let Some(source) = config.session_policy_without_key(identity) { |
| 237 | return match source { |
| 238 | codewhale_runtime::credentials::CredentialSource::AuthModeNone => { |
| 239 | CredentialState::NoAuth |
| 240 | } |
| 241 | codewhale_runtime::credentials::CredentialSource::KeylessRoute { .. } => { |
| 242 | CredentialState::Local |
| 243 | } |
| 244 | _ => CredentialState::MissingKey, |
| 245 | }; |
| 246 | } |
| 247 | let auth_mode = config.auth_mode_for_provider(identity); |
| 248 | if provider == ProviderKind::Anthropic && auth_mode.as_deref() == Some("oauth") { |
| 249 | return CredentialState::MissingKey; |
| 250 | } |
| 251 | if provider == ProviderKind::Anthropic |
| 252 | && codewhale_config::credentials::auth_mode_is_claude_org(auth_mode.as_deref()) |
| 253 | { |
| 254 | return if config.provider_uses_custom_endpoint(identity) { |
| 255 | CredentialState::MissingKey |
| 256 | } else { |
| 257 | CredentialState::Saved |
| 258 | }; |
| 259 | } |
| 260 | // Plugin OAuth takes precedence over local/keyless and legacy custom |
| 261 | // classifications. Diagnostics only read the bound credential; they never |
| 262 | // refresh, migrate storage or turn a missing login into API-key fallback. |
| 263 | if provider == ProviderKind::Custom |
| 264 | && config |
| 265 | .provider_config_for(identity) |
| 266 | .is_some_and(|entry| entry.oauth.is_some()) |
| 267 | { |
| 268 | let stored = config.provider_config_for(identity).is_some_and(|entry| { |
| 269 | let Some(authority) = entry.plugin_authority.as_ref() else { |
| 270 | return false; |
| 271 | }; |
| 272 | if codewhale_plugins::registry::verify_plugin_component_authority( |
| 273 | authority, |
| 274 | codewhale_plugins::activation::PluginActivationCapability::Providers, |
| 275 | ) |
| 276 | .is_err() |
| 277 | { |
| 278 | return false; |
| 279 | } |
| 280 | codewhale_runtime::oauth::plugin_oauth_credentials_present( |
| 281 | identity.key.as_str(), |
| 282 | &config.base_url_for_route(identity), |
| 283 | entry.oauth.as_ref().unwrap(), |
| 284 | ) |
| 285 | .unwrap_or(false) |
| 286 | }); |
| 287 | return if config.auth_mode_for_provider(identity).as_deref() == Some("oauth") && stored { |
| 288 | CredentialState::Saved |
| 289 | } else { |
| 290 | CredentialState::MissingLogin |
| 291 | }; |
| 292 | } |
| 293 | if codewhale_config::auth_mode_disables_api_key(auth_mode.as_deref()) { |
| 294 | return CredentialState::NoAuth; |
| 295 | } |
| 296 | let api_key_required = codewhale_config::auth_mode_requires_api_key(auth_mode.as_deref()); |
| 297 | let official_endpoint = !config.provider_uses_custom_endpoint(identity); |
| 298 | |
| 299 | // A built-in provider can intentionally target a local OpenAI-compatible |
| 300 | // runtime. That route is keyless unless the operator explicitly declares |
| 301 | // an API-key auth contract. Classify it before provider-specific hosted |
| 302 | // branches (including the DeepSeek-CN compatibility alias) so readiness |
| 303 | // and cache identity describe the effective endpoint, not just the |
| 304 | // provider enum. |
| 305 | if config |
| 306 | .active_provider_identity() |
| 307 | .is_ok_and(|active| active == *identity) |
| 308 | && !official_endpoint |
| 309 | && codewhale_runtime::config::base_url_uses_local_host(&config.active_route_base_url()) |
| 310 | { |
| 311 | return if api_key_required { |
| 312 | if has_api_key_for(config, identity) { |
| 313 | CredentialState::Saved |
| 314 | } else { |
| 315 | CredentialState::MissingKey |
| 316 | } |
| 317 | } else { |
| 318 | CredentialState::Local |
| 319 | }; |
| 320 | } |
| 321 | |
| 322 | if provider == ProviderKind::Antigravity { |
| 323 | return CredentialState::Legacy; |
| 324 | } |
| 325 | if provider == ProviderKind::Custom { |
| 326 | let Some(configured) = config.provider_config_for(identity) else { |
| 327 | return CredentialState::MissingKey; |
| 328 | }; |
| 329 | let auth_optional = configured |
| 330 | .base_url |
| 331 | .as_deref() |
| 332 | .is_some_and(codewhale_runtime::config::base_url_uses_local_host) |
| 333 | && !api_key_required; |
| 334 | if auth_optional { |
| 335 | return CredentialState::Local; |
| 336 | } |
| 337 | // The literal `custom` route (older top-level shape, now |
| 338 | // `[providers.custom]`) also owns the generic `custom` secret slot. |
| 339 | let has_auth = (config |
| 340 | .active_provider_identity() |
| 341 | .is_ok_and(|active| active == *identity) |
| 342 | && codewhale_runtime::config::explicit_cli_api_key_override().is_some()) |
| 343 | || (config.selects_literal_custom_provider() && has_api_key_for(config, identity)) |
| 344 | || configured.api_key.as_deref().is_some_and(|value| { |
| 345 | codewhale_config::classify_config_api_key_value(value) |
| 346 | == codewhale_config::ConfigApiKeyValueKind::Literal |
| 347 | }) |
| 348 | || configured |
| 349 | .api_key_env |
| 350 | .as_deref() |
| 351 | .map(str::trim) |
| 352 | .filter(|name| !name.is_empty()) |
| 353 | .is_some_and(|name| { |
| 354 | std::env::var(name).is_ok_and(|value| !value.trim().is_empty()) |
| 355 | }); |
| 356 | return if has_auth { |
| 357 | CredentialState::Saved |
| 358 | } else { |
| 359 | CredentialState::MissingKey |
| 360 | }; |
| 361 | } |
| 362 | if codewhale_runtime::config::provider_route_is_keyless_self_hosted( |
| 363 | provider, |
| 364 | &config.base_url_for_route(identity), |
| 365 | ) { |
| 366 | return if api_key_required { |
| 367 | if has_api_key_for(config, identity) { |
| 368 | CredentialState::Saved |
| 369 | } else { |
| 370 | CredentialState::MissingKey |
| 371 | } |
| 372 | } else { |
| 373 | CredentialState::Local |
| 374 | }; |
| 375 | } |
| 376 | |
| 377 | let uses_kimi_imported_token = provider == ProviderKind::Moonshot |
| 378 | && official_endpoint |
| 379 | && auth_mode |
| 380 | .as_deref() |
| 381 | .is_some_and(codewhale_config::auth_mode_uses_kimi_imported_token); |
| 382 | if uses_kimi_imported_token { |
| 383 | // Kimi remains API-key-only until Codewhale has its own registered |
| 384 | // OAuth client identity. Never inspect Kimi CLI storage here. |
| 385 | return CredentialState::MissingKey; |
| 386 | } |
| 387 | if provider == ProviderKind::OpenaiCodex && official_endpoint { |
| 388 | return if has_api_key_for(config, identity) { |
| 389 | CredentialState::Saved |
| 390 | } else if config |
| 391 | .active_provider_identity() |
| 392 | .is_ok_and(|active| active != *identity) |
| 393 | && config.external_credential_read_consent_configured( |
| 394 | identity, |
| 395 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 396 | ) |
| 397 | { |
| 398 | CredentialState::ExternalConsent |
| 399 | } else { |
| 400 | CredentialState::MissingLogin |
| 401 | }; |
| 402 | } |
| 403 | let xai_oauth_selected = provider == ProviderKind::Xai |
| 404 | && official_endpoint |
| 405 | && auth_mode |
| 406 | .as_deref() |
| 407 | .is_some_and(codewhale_runtime::oauth::auth_mode_uses_xai_oauth); |
| 408 | if xai_oauth_selected { |
| 409 | // #5772: `Saved` means a credential was actually found. A surviving |
| 410 | // consent record whose file is gone or expired resolves below as |
| 411 | // `ExternalConsent` (dormant) or `MissingLogin`, never as `Saved`. |
| 412 | return if codewhale_runtime::oauth::credentials_valid( |
| 413 | codewhale_runtime::oauth::OAuthProvider::Xai, |
| 414 | config, |
| 415 | ) || explicit_provider_credential_present(config, identity) |
| 416 | { |
| 417 | CredentialState::Saved |
| 418 | } else if config |
| 419 | .active_provider_identity() |
| 420 | .is_ok_and(|active| active != *identity) |
| 421 | && config.external_credential_read_consent_configured( |
| 422 | identity, |
| 423 | codewhale_config::ExternalCredentialSource::GrokCli, |
| 424 | ) |
| 425 | { |
| 426 | CredentialState::ExternalConsent |
| 427 | } else { |
| 428 | CredentialState::MissingLogin |
| 429 | }; |
| 430 | } |
| 431 | if provider == ProviderKind::Xai && explicit_provider_credential_present(config, identity) { |
| 432 | return CredentialState::Saved; |
| 433 | } |
| 434 | if provider == ProviderKind::Xai { |
| 435 | return CredentialState::MissingKey; |
| 436 | } |
| 437 | |
| 438 | if has_api_key_for(config, identity) { |
| 439 | CredentialState::Saved |
| 440 | } else if matches!( |
| 441 | provider, |
| 442 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 443 | ) && official_endpoint |
| 444 | && config |
| 445 | .active_provider_identity() |
| 446 | .is_ok_and(|active| active != *identity) |
| 447 | && config.external_credential_read_consent_configured( |
| 448 | identity, |
| 449 | codewhale_config::ExternalCredentialSource::DshCli, |
| 450 | ) |
| 451 | { |
| 452 | CredentialState::ExternalConsent |
| 453 | } else { |
| 454 | CredentialState::MissingKey |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | fn explicit_provider_credential_present( |
| 459 | config: &codewhale_runtime::config::Config, |
| 460 | identity: &ProviderIdentity, |
| 461 | ) -> bool { |
| 462 | let provider = identity.provider; |
| 463 | if config.verify_provider_identity(identity).is_err() { |
| 464 | return false; |
| 465 | } |
| 466 | (config |
| 467 | .active_provider_identity() |
| 468 | .is_ok_and(|active| active == *identity) |
| 469 | && codewhale_runtime::config::explicit_cli_api_key_override().is_some()) |
| 470 | || (!config.provider_uses_custom_endpoint(identity) |
| 471 | && provider |
| 472 | .provider() |
| 473 | .env_vars() |
| 474 | .iter() |
| 475 | .any(|name| std::env::var(name).is_ok_and(|value| !value.trim().is_empty()))) |
| 476 | || (config.config_credentials_are_bound_to_provider_endpoint(identity) |
| 477 | && config.provider_config_for(identity).is_some_and(|entry| { |
| 478 | entry.api_key.as_deref().is_some_and(|value| { |
| 479 | codewhale_config::classify_config_api_key_value(value) |
| 480 | == codewhale_config::ConfigApiKeyValueKind::Literal |
| 481 | }) || entry |
| 482 | .api_key_env |
| 483 | .as_deref() |
| 484 | .map(str::trim) |
| 485 | .filter(|name| !name.is_empty()) |
| 486 | .is_some_and(|name| { |
| 487 | std::env::var(name).is_ok_and(|value| !value.trim().is_empty()) |
| 488 | }) |
| 489 | })) |
| 490 | } |
| 491 | |
| 492 | /// Validate the configured provider/model/endpoint route without making a |
| 493 | /// network request. This is shared by model inventory, `/model`, and Fleet so |
| 494 | /// none of them can mark a route selectable when `/provider` would reject it. |
| 495 | pub fn route_is_valid_for_model( |
| 496 | config: &codewhale_runtime::config::Config, |
| 497 | identity: &ProviderIdentity, |
| 498 | model: Option<&str>, |
| 499 | ) -> bool { |
| 500 | let provider = identity.provider; |
| 501 | if config.verify_provider_identity(identity).is_err() || provider == ProviderKind::Antigravity { |
| 502 | return false; |
| 503 | } |
| 504 | let kind = provider; |
| 505 | let configured = config.provider_config_for(identity); |
| 506 | let configured_model = model |
| 507 | .map(str::trim) |
| 508 | .filter(|value| !value.is_empty()) |
| 509 | .map(str::to_string) |
| 510 | .or_else(|| { |
| 511 | configured |
| 512 | .and_then(|entry| entry.model.as_deref()) |
| 513 | .map(str::trim) |
| 514 | .filter(|value| !value.is_empty()) |
| 515 | .map(str::to_string) |
| 516 | }); |
| 517 | let active_model = (config |
| 518 | .active_provider_identity() |
| 519 | .is_ok_and(|active| active == *identity)) |
| 520 | .then(|| config.default_model()) |
| 521 | .filter(|model| !model.trim().is_empty() && !model.eq_ignore_ascii_case("auto")); |
| 522 | let request = RouteRequest { |
| 523 | explicit_provider: Some(kind), |
| 524 | model_selector: configured_model.or(active_model).map(LogicalModelRef::from), |
| 525 | saved_provider_model: None, |
| 526 | base_url_override: Some(config.base_url_for_route(identity)), |
| 527 | limit_overrides: Vec::new(), |
| 528 | // Readiness validates the route the turn would mint, so a custom |
| 529 | // table's wire dialect rides here exactly as it does at runtime. |
| 530 | wire_override: (kind == ProviderKind::Custom) |
| 531 | .then(|| { |
| 532 | codewhale_config::provider::wire_dialect_override( |
| 533 | identity.key.as_str(), |
| 534 | config.provider_wire_dialect(identity), |
| 535 | ) |
| 536 | }) |
| 537 | .flatten(), |
| 538 | responses_profile_override: match codewhale_config::provider::responses_profile_override( |
| 539 | kind, |
| 540 | identity.key.as_str(), |
| 541 | config.provider_wire_dialect(identity), |
| 542 | config.provider_responses_profile(identity), |
| 543 | ) { |
| 544 | Ok(profile) => profile, |
| 545 | Err(_) => return false, |
| 546 | }, |
| 547 | }; |
| 548 | if kind == ProviderKind::OpencodeGo { |
| 549 | let base = config.base_url_for_route(identity); |
| 550 | let scope = identity.key.as_str(); |
| 551 | let catalog = crate::provider_lake::runtime_catalog_resolver_for_identity( |
| 552 | kind, |
| 553 | Some(scope), |
| 554 | &base, |
| 555 | crate::provider_catalog_live::status_for_route(kind, scope, &base), |
| 556 | ); |
| 557 | if catalog.endpoint_catalog_authoritative { |
| 558 | return catalog |
| 559 | .resolver |
| 560 | .resolve_with_endpoint_catalog_authority(&request) |
| 561 | .is_ok_and(|candidate| candidate.validation().ok); |
| 562 | } |
| 563 | } |
| 564 | RouteResolver::bundled() |
| 565 | .resolve(&request) |
| 566 | .is_ok_and(|candidate| candidate.validation().ok) |
| 567 | } |
| 568 | |
| 569 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 570 | pub enum LastProviderCheck { |
| 571 | Passed, |
| 572 | /// A 2xx `/models` response proves reachability only — never model readiness. |
| 573 | ModelsEndpointPassed, |
| 574 | Failed { |
| 575 | category: ErrorCategory, |
| 576 | message: String, |
| 577 | }, |
| 578 | } |
| 579 | |
| 580 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 581 | #[serde(rename_all = "snake_case")] |
| 582 | pub enum ResolvedProviderReadiness { |
| 583 | MissingKey, |
| 584 | MissingLogin, |
| 585 | ExternalConsentPendingSelection, |
| 586 | SavedUnchecked, |
| 587 | ImportedTokenUnchecked, |
| 588 | NoAuthUnchecked, |
| 589 | LocalUnchecked, |
| 590 | Ready, |
| 591 | ConnectionCheckedModelUnchecked, |
| 592 | SavedLastCheckFailed { |
| 593 | category: ErrorCategory, |
| 594 | message: String, |
| 595 | }, |
| 596 | InvalidRoute, |
| 597 | Legacy, |
| 598 | } |
| 599 | |
| 600 | impl ResolvedProviderReadiness { |
| 601 | pub fn label(&self) -> Cow<'static, str> { |
| 602 | match self { |
| 603 | Self::MissingKey => Cow::Borrowed("needs key"), |
| 604 | Self::MissingLogin => Cow::Borrowed("missing login"), |
| 605 | Self::ExternalConsentPendingSelection => { |
| 606 | Cow::Borrowed("external consent · select to check") |
| 607 | } |
| 608 | Self::SavedUnchecked => Cow::Borrowed("key saved · not checked"), |
| 609 | Self::ImportedTokenUnchecked => Cow::Borrowed("imported token · not checked"), |
| 610 | Self::NoAuthUnchecked => Cow::Borrowed("no auth · not checked"), |
| 611 | Self::LocalUnchecked => Cow::Borrowed("local · not checked"), |
| 612 | Self::Ready => Cow::Borrowed("ready"), |
| 613 | Self::ConnectionCheckedModelUnchecked => { |
| 614 | Cow::Borrowed("endpoint reachable · model not checked") |
| 615 | } |
| 616 | Self::SavedLastCheckFailed { category, .. } => { |
| 617 | Cow::Owned(format!("last check failed ({category})")) |
| 618 | } |
| 619 | Self::InvalidRoute => Cow::Borrowed("invalid route"), |
| 620 | Self::Legacy => Cow::Borrowed("legacy"), |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | pub fn detail(&self) -> Option<&str> { |
| 625 | match self { |
| 626 | Self::SavedLastCheckFailed { message, .. } => Some(message), |
| 627 | _ => None, |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | pub fn can_attempt(&self) -> bool { |
| 632 | matches!( |
| 633 | self, |
| 634 | Self::SavedUnchecked |
| 635 | | Self::NoAuthUnchecked |
| 636 | | Self::LocalUnchecked |
| 637 | | Self::ImportedTokenUnchecked |
| 638 | | Self::Ready |
| 639 | | Self::SavedLastCheckFailed { .. } |
| 640 | ) |
| 641 | } |
| 642 | |
| 643 | /// Whether the provider needs an explicit human activation step before it |
| 644 | /// can be used. Fleet uses this to turn a dormant external-consent route |
| 645 | /// into a real selection without weakening the global readiness boundary. |
| 646 | pub fn requires_explicit_activation(&self) -> bool { |
| 647 | matches!(self, Self::ExternalConsentPendingSelection) |
| 648 | } |
| 649 | |
| 650 | /// A short, non-sensitive reason this row cannot be activated. `None` |
| 651 | /// means the row is either ready or requires explicit activation. |
| 652 | pub fn blocked_reason(&self) -> Option<Cow<'static, str>> { |
| 653 | match self { |
| 654 | Self::MissingKey => Some(Cow::Borrowed("missing API key")), |
| 655 | Self::MissingLogin => Some(Cow::Borrowed("missing login")), |
| 656 | Self::InvalidRoute => Some(Cow::Borrowed("invalid route")), |
| 657 | Self::Legacy => Some(Cow::Borrowed("legacy route")), |
| 658 | Self::ConnectionCheckedModelUnchecked => Some(Cow::Borrowed("model not checked")), |
| 659 | Self::SavedLastCheckFailed { message, .. } => Some(Cow::Owned(message.clone())), |
| 660 | Self::SavedUnchecked |
| 661 | | Self::ImportedTokenUnchecked |
| 662 | | Self::NoAuthUnchecked |
| 663 | | Self::LocalUnchecked |
| 664 | | Self::Ready |
| 665 | | Self::ExternalConsentPendingSelection => None, |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | #[derive(Debug, Clone, Default)] |
| 671 | pub struct ProviderReadinessSnapshot { |
| 672 | checks: Vec<(ProviderRouteIdentity, LastProviderCheck)>, |
| 673 | /// Credentials the provider refused (authentication failures), keyed by |
| 674 | /// route without the model: a rejected key is rejected for every model. |
| 675 | /// Unlike `checks`, an entry may carry no credential generation — an |
| 676 | /// ambient `*_API_KEY`, a secret-store key or a command source cannot be |
| 677 | /// fingerprinted read-only, and without this the picker kept offering a |
| 678 | /// refused env key as "key saved · not checked". |
| 679 | /// |
| 680 | /// Known limitation: an opaque (generation-less) rejection cannot see a |
| 681 | /// key rotated outside this process; it lasts until the next success on |
| 682 | /// that route, or until a saved key makes the generation provable. |
| 683 | credential_rejections: Vec<(ProviderRouteIdentity, LastProviderCheck)>, |
| 684 | } |
| 685 | |
| 686 | pub type ProviderReadinessHandle = std::sync::Arc<parking_lot::Mutex<ProviderReadinessSnapshot>>; |
| 687 | |
| 688 | fn same_credential(candidate: &ProviderRouteIdentity, identity: &ProviderRouteIdentity) -> bool { |
| 689 | candidate.identity == identity.identity |
| 690 | && candidate.endpoint == identity.endpoint |
| 691 | && candidate.auth_class == identity.auth_class |
| 692 | && candidate.credential_generation == identity.credential_generation |
| 693 | } |
| 694 | |
| 695 | impl ProviderReadinessSnapshot { |
| 696 | fn last(&self, identity: &ProviderRouteIdentity) -> Option<&LastProviderCheck> { |
| 697 | // A refused credential outranks any older per-model success with it; |
| 698 | // a later success on the route clears the rejection. |
| 699 | if let Some(check) = self |
| 700 | .credential_rejections |
| 701 | .iter() |
| 702 | .rev() |
| 703 | .find_map(|(candidate, check)| same_credential(candidate, identity).then_some(check)) |
| 704 | { |
| 705 | return Some(check); |
| 706 | } |
| 707 | identity.credential_generation.as_ref()?; |
| 708 | if let Some(check) = self |
| 709 | .checks |
| 710 | .iter() |
| 711 | .rev() |
| 712 | .find_map(|(candidate, check)| (candidate == identity).then_some(check)) |
| 713 | { |
| 714 | return Some(check); |
| 715 | } |
| 716 | // The auto model route never records under the literal "auto" — |
| 717 | // successes and failures are recorded against the concrete model |
| 718 | // the router actually ran. Without this fallback every auto-mode |
| 719 | // read would report "not checked" forever, even after hundreds of |
| 720 | // successful turns on that route. |
| 721 | if identity.model != "auto" { |
| 722 | return None; |
| 723 | } |
| 724 | self.checks |
| 725 | .iter() |
| 726 | .rev() |
| 727 | .find_map(|(candidate, check)| same_credential(candidate, identity).then_some(check)) |
| 728 | } |
| 729 | |
| 730 | #[must_use] |
| 731 | pub fn last_for_provider(&self, identity: &ProviderIdentity) -> Option<&LastProviderCheck> { |
| 732 | self.checks |
| 733 | .iter() |
| 734 | .rev() |
| 735 | .find_map(|(candidate, check)| (candidate.identity == *identity).then_some(check)) |
| 736 | } |
| 737 | |
| 738 | pub fn record_success( |
| 739 | &mut self, |
| 740 | config: &codewhale_runtime::config::Config, |
| 741 | receipt: &crate::route_receipt::TurnRouteReceipt, |
| 742 | model: &str, |
| 743 | ) { |
| 744 | let identity = receipt.admitted_identity(); |
| 745 | let mut route = route_identity_for_model(config, identity, model); |
| 746 | route.endpoint = receipt.endpoint_identity().to_string(); |
| 747 | route.credential_generation = Some(receipt.credential_generation().clone()); |
| 748 | self.credential_rejections.retain(|(candidate, _)| { |
| 749 | candidate.identity != route.identity || candidate.endpoint != route.endpoint |
| 750 | }); |
| 751 | self.replace(route, LastProviderCheck::Passed); |
| 752 | } |
| 753 | |
| 754 | /// Records a failed `/models` probe. Unlike [`Self::record_failure`], |
| 755 | /// this always stores the result so Test Connection can refresh a |
| 756 | /// stuck `not checked` row. |
| 757 | pub fn record_models_probe_failure( |
| 758 | &mut self, |
| 759 | config: &codewhale_runtime::config::Config, |
| 760 | identity: &ProviderIdentity, |
| 761 | model: &str, |
| 762 | generation: codewhale_config::credentials::CredentialGeneration, |
| 763 | category: ErrorCategory, |
| 764 | message: &str, |
| 765 | ) { |
| 766 | let mut route = route_identity_for_model(config, identity, model); |
| 767 | route.credential_generation = Some(generation); |
| 768 | self.replace( |
| 769 | route, |
| 770 | LastProviderCheck::Failed { |
| 771 | category, |
| 772 | message: sanitize_message(message), |
| 773 | }, |
| 774 | ); |
| 775 | } |
| 776 | |
| 777 | /// Records a 2xx `/models` probe as connection-checked, never `Ready`. |
| 778 | pub fn record_models_probe_success( |
| 779 | &mut self, |
| 780 | config: &codewhale_runtime::config::Config, |
| 781 | identity: &ProviderIdentity, |
| 782 | model: &str, |
| 783 | generation: codewhale_config::credentials::CredentialGeneration, |
| 784 | ) { |
| 785 | let mut route = route_identity_for_model(config, identity, model); |
| 786 | route.credential_generation = Some(generation); |
| 787 | self.replace(route, LastProviderCheck::ModelsEndpointPassed); |
| 788 | } |
| 789 | |
| 790 | pub fn record_failure( |
| 791 | &mut self, |
| 792 | config: &codewhale_runtime::config::Config, |
| 793 | receipt: &crate::route_receipt::TurnRouteReceipt, |
| 794 | model: &str, |
| 795 | envelope: &ErrorEnvelope, |
| 796 | ) { |
| 797 | let identity = receipt.admitted_identity(); |
| 798 | let mut route = route_identity_for_model(config, identity, model); |
| 799 | route.endpoint = receipt.endpoint_identity().to_string(); |
| 800 | route.credential_generation = Some(receipt.credential_generation().clone()); |
| 801 | if !provider_owned_failure(envelope) { |
| 802 | return; |
| 803 | } |
| 804 | let check = LastProviderCheck::Failed { |
| 805 | category: envelope.category, |
| 806 | message: sanitize_message(&envelope.message), |
| 807 | }; |
| 808 | if envelope.category == ErrorCategory::Authentication { |
| 809 | // Record the rejection under the generation the picker will |
| 810 | // compute. When that projection proves a different credential is |
| 811 | // configured now, the refused one is already gone. |
| 812 | let current = config.readonly_health_credential_generation(identity); |
| 813 | if current |
| 814 | .as_ref() |
| 815 | .is_none_or(|generation| generation == receipt.credential_generation()) |
| 816 | { |
| 817 | let mut rejected = route.clone(); |
| 818 | rejected.model.clear(); |
| 819 | rejected.credential_generation = current; |
| 820 | self.credential_rejections |
| 821 | .retain(|(candidate, _)| !same_credential(candidate, &rejected)); |
| 822 | self.credential_rejections.push((rejected, check.clone())); |
| 823 | } |
| 824 | } |
| 825 | self.replace(route, check); |
| 826 | } |
| 827 | |
| 828 | #[cfg(any(test, feature = "test-support"))] |
| 829 | pub fn record_failure_message( |
| 830 | &mut self, |
| 831 | config: &codewhale_runtime::config::Config, |
| 832 | identity: &ProviderIdentity, |
| 833 | model: &str, |
| 834 | category: ErrorCategory, |
| 835 | message: &str, |
| 836 | ) { |
| 837 | self.replace( |
| 838 | route_identity_for_model(config, identity, model), |
| 839 | LastProviderCheck::Failed { |
| 840 | category, |
| 841 | message: sanitize_message(message), |
| 842 | }, |
| 843 | ); |
| 844 | } |
| 845 | |
| 846 | fn replace(&mut self, identity: ProviderRouteIdentity, check: LastProviderCheck) { |
| 847 | self.checks.retain(|(candidate, _)| candidate != &identity); |
| 848 | self.checks.push((identity, check)); |
| 849 | } |
| 850 | } |
| 851 | |
| 852 | pub fn resolve_with_identity( |
| 853 | identity: &ProviderRouteIdentity, |
| 854 | credentials: CredentialState, |
| 855 | route_ok: bool, |
| 856 | checks: &ProviderReadinessSnapshot, |
| 857 | ) -> ResolvedProviderReadiness { |
| 858 | if !route_ok { |
| 859 | return ResolvedProviderReadiness::InvalidRoute; |
| 860 | } |
| 861 | match credentials { |
| 862 | CredentialState::Legacy => ResolvedProviderReadiness::Legacy, |
| 863 | CredentialState::MissingKey => ResolvedProviderReadiness::MissingKey, |
| 864 | CredentialState::MissingLogin => ResolvedProviderReadiness::MissingLogin, |
| 865 | CredentialState::ExternalConsent => match checks.last(identity) { |
| 866 | Some(LastProviderCheck::Passed) => ResolvedProviderReadiness::Ready, |
| 867 | Some(LastProviderCheck::ModelsEndpointPassed) => { |
| 868 | ResolvedProviderReadiness::ConnectionCheckedModelUnchecked |
| 869 | } |
| 870 | Some(LastProviderCheck::Failed { category, message }) => { |
| 871 | ResolvedProviderReadiness::SavedLastCheckFailed { |
| 872 | category: *category, |
| 873 | message: message.clone(), |
| 874 | } |
| 875 | } |
| 876 | None => ResolvedProviderReadiness::ExternalConsentPendingSelection, |
| 877 | }, |
| 878 | CredentialState::Saved |
| 879 | | CredentialState::ImportedToken |
| 880 | | CredentialState::NoAuth |
| 881 | | CredentialState::Local => match checks.last(identity) { |
| 882 | Some(LastProviderCheck::Passed) => ResolvedProviderReadiness::Ready, |
| 883 | Some(LastProviderCheck::ModelsEndpointPassed) => { |
| 884 | ResolvedProviderReadiness::ConnectionCheckedModelUnchecked |
| 885 | } |
| 886 | Some(LastProviderCheck::Failed { category, message }) => { |
| 887 | ResolvedProviderReadiness::SavedLastCheckFailed { |
| 888 | category: *category, |
| 889 | message: message.clone(), |
| 890 | } |
| 891 | } |
| 892 | None if credentials == CredentialState::NoAuth => { |
| 893 | ResolvedProviderReadiness::NoAuthUnchecked |
| 894 | } |
| 895 | None if credentials == CredentialState::Local => { |
| 896 | ResolvedProviderReadiness::LocalUnchecked |
| 897 | } |
| 898 | None if credentials == CredentialState::ImportedToken => { |
| 899 | ResolvedProviderReadiness::ImportedTokenUnchecked |
| 900 | } |
| 901 | None => ResolvedProviderReadiness::SavedUnchecked, |
| 902 | }, |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | pub fn resolve_for_model( |
| 907 | config: &codewhale_runtime::config::Config, |
| 908 | identity: &ProviderIdentity, |
| 909 | model: &str, |
| 910 | checks: &ProviderReadinessSnapshot, |
| 911 | ) -> ResolvedProviderReadiness { |
| 912 | RouteReadinessScope::for_route(config, identity).resolve(config, model, checks) |
| 913 | } |
| 914 | |
| 915 | /// Route-scoped readiness facts that do not change per model. |
| 916 | /// |
| 917 | /// [`resolve_for_model`] re-resolves the credential source and the auth class |
| 918 | /// for every model it is asked about. A caller that asks once per model on one |
| 919 | /// route walks the credential resolver, secret store included, once per model |
| 920 | /// for an answer that cannot change between them. |
| 921 | #[derive(Debug, Clone)] |
| 922 | pub struct RouteReadinessScope { |
| 923 | identity: ProviderIdentity, |
| 924 | endpoint: String, |
| 925 | credentials: CredentialState, |
| 926 | auth_class: ProviderAuthClass, |
| 927 | credential_generation: Option<codewhale_config::credentials::CredentialGeneration>, |
| 928 | } |
| 929 | |
| 930 | impl RouteReadinessScope { |
| 931 | pub fn for_route( |
| 932 | config: &codewhale_runtime::config::Config, |
| 933 | identity: &ProviderIdentity, |
| 934 | ) -> Self { |
| 935 | Self { |
| 936 | identity: identity.clone(), |
| 937 | endpoint: crate::route_receipt::endpoint_identity(&config.base_url_for_route(identity)), |
| 938 | credentials: credential_state_for_provider(config, identity), |
| 939 | auth_class: auth_class_for_provider(config, identity), |
| 940 | credential_generation: config.readonly_health_credential_generation(identity), |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | /// The single-model answer, with the route-scoped facts reused. |
| 945 | pub fn resolve( |
| 946 | &self, |
| 947 | config: &codewhale_runtime::config::Config, |
| 948 | model: &str, |
| 949 | checks: &ProviderReadinessSnapshot, |
| 950 | ) -> ResolvedProviderReadiness { |
| 951 | let route = ProviderRouteIdentity { |
| 952 | identity: self.identity.clone(), |
| 953 | endpoint: self.endpoint.clone(), |
| 954 | model: model.trim().to_string(), |
| 955 | auth_class: self.auth_class, |
| 956 | credential_generation: self.credential_generation.clone(), |
| 957 | }; |
| 958 | resolve_with_identity( |
| 959 | &route, |
| 960 | self.credentials, |
| 961 | route_is_valid_for_model(config, &self.identity, Some(model)), |
| 962 | checks, |
| 963 | ) |
| 964 | } |
| 965 | } |
| 966 | |
| 967 | fn provider_owned_failure(envelope: &ErrorEnvelope) -> bool { |
| 968 | matches!( |
| 969 | envelope.category, |
| 970 | ErrorCategory::Network |
| 971 | | ErrorCategory::Authentication |
| 972 | | ErrorCategory::Authorization |
| 973 | | ErrorCategory::RateLimit |
| 974 | | ErrorCategory::Timeout |
| 975 | ) |
| 976 | } |
| 977 | |
| 978 | fn sanitize_message(message: &str) -> String { |
| 979 | codewhale_util::utils::truncate_with_ellipsis(message.trim(), 120, "…") |
| 980 | } |
| 981 | |
| 982 | #[cfg(test)] |
| 983 | mod tests { |
| 984 | use super::*; |
| 985 | |
| 986 | #[test] |
| 987 | fn plugin_oauth_readiness_requires_login_even_on_a_local_custom_route() { |
| 988 | let mut config = { |
| 989 | let __cw_config_init_0_0 = Some("plugin-test".into()); |
| 990 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = |
| 991 | Default::default(); |
| 992 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 993 | __cw_config_init_0_value |
| 994 | }; |
| 995 | let entry = config |
| 996 | .providers |
| 997 | .get_or_insert_with(Default::default) |
| 998 | .custom |
| 999 | .entry("plugin-test".into()) |
| 1000 | .or_default(); |
| 1001 | entry.kind = Some("openai-compatible".into()); |
| 1002 | entry.base_url = Some("http://127.0.0.1:12345/api".into()); |
| 1003 | entry.auth_mode = Some("oauth".into()); |
| 1004 | entry.oauth = Some(codewhale_runtime::oauth::PluginOAuthConfig { |
| 1005 | issuer: "http://127.0.0.1:12345".into(), |
| 1006 | authorization_endpoint: "http://127.0.0.1:12345/authorize".into(), |
| 1007 | token_endpoint: "http://127.0.0.1:12345/token".into(), |
| 1008 | client_id: "plugin-test".into(), |
| 1009 | scopes: vec!["models:invoke".into()], |
| 1010 | resource: None, |
| 1011 | callback_path: "/oauth/callback".into(), |
| 1012 | }); |
| 1013 | let identity = config.active_provider_identity().unwrap(); |
| 1014 | // An absent receipt is rejected before any credential file is read. |
| 1015 | assert_eq!( |
| 1016 | auth_class_for_provider(&config, &identity), |
| 1017 | ProviderAuthClass::OAuth |
| 1018 | ); |
| 1019 | assert_eq!( |
| 1020 | credential_state_for_provider(&config, &identity), |
| 1021 | CredentialState::MissingLogin |
| 1022 | ); |
| 1023 | config.auth_mode = Some("none".into()); |
| 1024 | assert_eq!( |
| 1025 | credential_state_for_provider(&config, &identity), |
| 1026 | CredentialState::MissingLogin |
| 1027 | ); |
| 1028 | } |
| 1029 | |
| 1030 | use codewhale_error_taxonomy::ErrorSeverity; |
| 1031 | |
| 1032 | fn literal_health_config(kind: ProviderKind) -> codewhale_runtime::config::Config { |
| 1033 | let mut config = { |
| 1034 | let __cw_config_init_1_0 = Some(kind.as_str().into()); |
| 1035 | let mut __cw_config_init_1_value: codewhale_runtime::config::Config = |
| 1036 | Default::default(); |
| 1037 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 1038 | __cw_config_init_1_value |
| 1039 | }; |
| 1040 | let identity = config.builtin_provider_identity(kind).unwrap(); |
| 1041 | config.provider_config_for_mut(&identity).unwrap().api_key = |
| 1042 | Some("health-fixture-key".into()); |
| 1043 | config |
| 1044 | } |
| 1045 | |
| 1046 | fn resolve_test_route( |
| 1047 | config: &codewhale_runtime::config::Config, |
| 1048 | provider: ProviderKind, |
| 1049 | model: &str, |
| 1050 | credentials: CredentialState, |
| 1051 | route_ok: bool, |
| 1052 | checks: &ProviderReadinessSnapshot, |
| 1053 | ) -> ResolvedProviderReadiness { |
| 1054 | resolve_with_identity( |
| 1055 | &route_identity_for_model(config, &(config).test_identity_for_kind(provider), model), |
| 1056 | credentials, |
| 1057 | route_ok, |
| 1058 | checks, |
| 1059 | ) |
| 1060 | } |
| 1061 | |
| 1062 | #[test] |
| 1063 | fn saved_credentials_are_never_ready_without_observed_success() { |
| 1064 | let config = codewhale_runtime::config::Config::default(); |
| 1065 | let checks = ProviderReadinessSnapshot::default(); |
| 1066 | assert_eq!( |
| 1067 | resolve_test_route( |
| 1068 | &config, |
| 1069 | ProviderKind::Deepseek, |
| 1070 | "deepseek-v4-pro", |
| 1071 | CredentialState::Saved, |
| 1072 | true, |
| 1073 | &checks, |
| 1074 | ), |
| 1075 | ResolvedProviderReadiness::SavedUnchecked |
| 1076 | ); |
| 1077 | } |
| 1078 | |
| 1079 | #[test] |
| 1080 | fn deepseek_cn_compatibility_alias_uses_real_key_readiness() { |
| 1081 | let _lock = crate::test_support::lock_test_env(); |
| 1082 | let _key = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY"); |
| 1083 | let missing = { |
| 1084 | let __cw_config_init_2_0 = Some("deepseek-cn".to_string()); |
| 1085 | let mut __cw_config_init_2_value: codewhale_runtime::config::Config = |
| 1086 | Default::default(); |
| 1087 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 1088 | __cw_config_init_2_value |
| 1089 | }; |
| 1090 | assert_eq!( |
| 1091 | credential_state_for_provider( |
| 1092 | &missing, |
| 1093 | &(missing) |
| 1094 | .resolve_provider_selection_identity("deepseek-cn") |
| 1095 | .unwrap() |
| 1096 | ), |
| 1097 | CredentialState::MissingKey |
| 1098 | ); |
| 1099 | |
| 1100 | let configured = { |
| 1101 | let __cw_config_init_3_0 = Some("deepseek-cn".to_string()); |
| 1102 | let __cw_config_init_3_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1103 | deepseek_cn: codewhale_runtime::config::ProviderConfig { |
| 1104 | api_key: Some("deepseek-cn-test-key".to_string()), |
| 1105 | ..Default::default() |
| 1106 | }, |
| 1107 | ..Default::default() |
| 1108 | }); |
| 1109 | let mut __cw_config_init_3_value: codewhale_runtime::config::Config = |
| 1110 | Default::default(); |
| 1111 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 1112 | __cw_config_init_3_value.providers = __cw_config_init_3_1; |
| 1113 | __cw_config_init_3_value |
| 1114 | }; |
| 1115 | assert_eq!( |
| 1116 | credential_state_for_provider( |
| 1117 | &configured, |
| 1118 | &(configured) |
| 1119 | .resolve_provider_selection_identity("deepseek-cn") |
| 1120 | .unwrap() |
| 1121 | ), |
| 1122 | CredentialState::Saved |
| 1123 | ); |
| 1124 | } |
| 1125 | |
| 1126 | #[test] |
| 1127 | fn custom_readiness_identity_preserves_case_sensitive_route_parts() { |
| 1128 | let custom = std::collections::HashMap::from([ |
| 1129 | ( |
| 1130 | "CUSTOM".to_string(), |
| 1131 | codewhale_runtime::config::ProviderConfig { |
| 1132 | kind: Some("openai-compatible".to_string()), |
| 1133 | base_url: Some("https://example.test/TenantA/v1".to_string()), |
| 1134 | model: Some("Vendor/ModelA".to_string()), |
| 1135 | api_key: Some("test-key-a".to_string()), |
| 1136 | ..Default::default() |
| 1137 | }, |
| 1138 | ), |
| 1139 | ( |
| 1140 | "custom".to_string(), |
| 1141 | codewhale_runtime::config::ProviderConfig { |
| 1142 | kind: Some("openai-compatible".to_string()), |
| 1143 | base_url: Some("https://example.test/tenanta/v1".to_string()), |
| 1144 | model: Some("vendor/modela".to_string()), |
| 1145 | api_key: Some("test-key-b".to_string()), |
| 1146 | ..Default::default() |
| 1147 | }, |
| 1148 | ), |
| 1149 | ]); |
| 1150 | let upper = { |
| 1151 | let __cw_config_init_4_0 = Some("CUSTOM".to_string()); |
| 1152 | let __cw_config_init_4_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1153 | custom: custom.clone(), |
| 1154 | ..Default::default() |
| 1155 | }); |
| 1156 | let mut __cw_config_init_4_value: codewhale_runtime::config::Config = |
| 1157 | Default::default(); |
| 1158 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 1159 | __cw_config_init_4_value.providers = __cw_config_init_4_1; |
| 1160 | __cw_config_init_4_value |
| 1161 | }; |
| 1162 | let lower = { |
| 1163 | let __cw_config_init_5_0 = Some("custom".to_string()); |
| 1164 | let __cw_config_init_5_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1165 | custom, |
| 1166 | ..Default::default() |
| 1167 | }); |
| 1168 | let mut __cw_config_init_5_value: codewhale_runtime::config::Config = |
| 1169 | Default::default(); |
| 1170 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 1171 | __cw_config_init_5_value.providers = __cw_config_init_5_1; |
| 1172 | __cw_config_init_5_value |
| 1173 | }; |
| 1174 | let upper_identity = route_identity_for_model( |
| 1175 | &upper, |
| 1176 | &(upper).test_identity_for_kind(ProviderKind::Custom), |
| 1177 | "Vendor/ModelA", |
| 1178 | ); |
| 1179 | let lower_identity = route_identity_for_model( |
| 1180 | &lower, |
| 1181 | &(lower).test_identity_for_kind(ProviderKind::Custom), |
| 1182 | "vendor/modela", |
| 1183 | ); |
| 1184 | |
| 1185 | assert_ne!(upper_identity, lower_identity); |
| 1186 | assert_eq!(upper_identity.identity.key.as_str(), "CUSTOM"); |
| 1187 | assert_eq!(upper_identity.endpoint, "https://example.test/TenantA/v1"); |
| 1188 | assert_eq!(upper_identity.model, "Vendor/ModelA"); |
| 1189 | |
| 1190 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1191 | checks.record_success( |
| 1192 | &upper, |
| 1193 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1194 | &upper, |
| 1195 | ProviderKind::Custom, |
| 1196 | "Vendor/ModelA", |
| 1197 | ), |
| 1198 | "Vendor/ModelA", |
| 1199 | ); |
| 1200 | assert_eq!( |
| 1201 | resolve_for_model( |
| 1202 | &lower, |
| 1203 | &(lower).test_identity_for_kind(ProviderKind::Custom), |
| 1204 | "vendor/modela", |
| 1205 | &checks |
| 1206 | ), |
| 1207 | ResolvedProviderReadiness::SavedUnchecked |
| 1208 | ); |
| 1209 | } |
| 1210 | |
| 1211 | #[test] |
| 1212 | fn external_consent_cached_turn_cannot_prove_current_opaque_generation() { |
| 1213 | let config = codewhale_runtime::config::Config::default(); |
| 1214 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1215 | checks.record_success( |
| 1216 | &config, |
| 1217 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1218 | &config, |
| 1219 | ProviderKind::OpenaiCodex, |
| 1220 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL, |
| 1221 | ), |
| 1222 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL, |
| 1223 | ); |
| 1224 | assert_eq!( |
| 1225 | resolve_test_route( |
| 1226 | &config, |
| 1227 | ProviderKind::OpenaiCodex, |
| 1228 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL, |
| 1229 | CredentialState::ExternalConsent, |
| 1230 | true, |
| 1231 | &checks, |
| 1232 | ), |
| 1233 | ResolvedProviderReadiness::ExternalConsentPendingSelection |
| 1234 | ); |
| 1235 | } |
| 1236 | |
| 1237 | #[test] |
| 1238 | fn external_consent_cached_failure_cannot_prove_current_opaque_generation() { |
| 1239 | let config = codewhale_runtime::config::Config::default(); |
| 1240 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1241 | checks.record_failure_message( |
| 1242 | &config, |
| 1243 | &(config).test_identity_for_kind(ProviderKind::Xai), |
| 1244 | "grok-4.5", |
| 1245 | ErrorCategory::Authentication, |
| 1246 | "consent revoked", |
| 1247 | ); |
| 1248 | assert_eq!( |
| 1249 | resolve_test_route( |
| 1250 | &config, |
| 1251 | ProviderKind::Xai, |
| 1252 | "grok-4.5", |
| 1253 | CredentialState::ExternalConsent, |
| 1254 | true, |
| 1255 | &checks |
| 1256 | ), |
| 1257 | ResolvedProviderReadiness::ExternalConsentPendingSelection |
| 1258 | ); |
| 1259 | } |
| 1260 | |
| 1261 | #[test] |
| 1262 | fn external_consent_without_check_stays_pending_selection() { |
| 1263 | let config = codewhale_runtime::config::Config::default(); |
| 1264 | let checks = ProviderReadinessSnapshot::default(); |
| 1265 | assert_eq!( |
| 1266 | resolve_test_route( |
| 1267 | &config, |
| 1268 | ProviderKind::OpenaiCodex, |
| 1269 | codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL, |
| 1270 | CredentialState::ExternalConsent, |
| 1271 | true, |
| 1272 | &checks, |
| 1273 | ), |
| 1274 | ResolvedProviderReadiness::ExternalConsentPendingSelection |
| 1275 | ); |
| 1276 | } |
| 1277 | |
| 1278 | #[test] |
| 1279 | fn models_probe_success_marks_connection_checked_not_ready() { |
| 1280 | let _lock = crate::test_support::lock_test_env(); |
| 1281 | let _cli = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 1282 | let _source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 1283 | let config = literal_health_config(ProviderKind::Deepseek); |
| 1284 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1285 | checks.record_models_probe_success( |
| 1286 | &config, |
| 1287 | &(config).test_identity_for_kind(ProviderKind::Deepseek), |
| 1288 | "deepseek-v4-pro", |
| 1289 | crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1290 | &config, |
| 1291 | ProviderKind::Deepseek, |
| 1292 | "deepseek-v4-pro", |
| 1293 | ) |
| 1294 | .credential_generation() |
| 1295 | .clone(), |
| 1296 | ); |
| 1297 | assert_eq!( |
| 1298 | resolve_test_route( |
| 1299 | &config, |
| 1300 | ProviderKind::Deepseek, |
| 1301 | "deepseek-v4-pro", |
| 1302 | CredentialState::Saved, |
| 1303 | true, |
| 1304 | &checks, |
| 1305 | ), |
| 1306 | ResolvedProviderReadiness::ConnectionCheckedModelUnchecked |
| 1307 | ); |
| 1308 | assert_eq!( |
| 1309 | ResolvedProviderReadiness::ConnectionCheckedModelUnchecked.label(), |
| 1310 | "endpoint reachable · model not checked" |
| 1311 | ); |
| 1312 | assert!(!ResolvedProviderReadiness::ConnectionCheckedModelUnchecked.can_attempt()); |
| 1313 | } |
| 1314 | |
| 1315 | #[test] |
| 1316 | fn success_and_provider_failure_replace_session_evidence() { |
| 1317 | let _lock = crate::test_support::lock_test_env(); |
| 1318 | let _cli = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 1319 | let _source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 1320 | let config = literal_health_config(ProviderKind::Zai); |
| 1321 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1322 | checks.record_success( |
| 1323 | &config, |
| 1324 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1325 | &config, |
| 1326 | ProviderKind::Zai, |
| 1327 | "glm-5.2", |
| 1328 | ), |
| 1329 | "glm-5.2", |
| 1330 | ); |
| 1331 | assert_eq!( |
| 1332 | resolve_test_route( |
| 1333 | &config, |
| 1334 | ProviderKind::Zai, |
| 1335 | "glm-5.2", |
| 1336 | CredentialState::Saved, |
| 1337 | true, |
| 1338 | &checks, |
| 1339 | ), |
| 1340 | ResolvedProviderReadiness::Ready |
| 1341 | ); |
| 1342 | |
| 1343 | checks.record_failure( |
| 1344 | &config, |
| 1345 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1346 | &config, |
| 1347 | ProviderKind::Zai, |
| 1348 | "glm-5.2", |
| 1349 | ), |
| 1350 | "glm-5.2", |
| 1351 | &ErrorEnvelope::new( |
| 1352 | ErrorCategory::Authentication, |
| 1353 | ErrorSeverity::Error, |
| 1354 | false, |
| 1355 | "auth_failed", |
| 1356 | "token rejected", |
| 1357 | ), |
| 1358 | ); |
| 1359 | let resolved = resolve_test_route( |
| 1360 | &config, |
| 1361 | ProviderKind::Zai, |
| 1362 | "glm-5.2", |
| 1363 | CredentialState::Saved, |
| 1364 | true, |
| 1365 | &checks, |
| 1366 | ); |
| 1367 | assert!(matches!( |
| 1368 | resolved, |
| 1369 | ResolvedProviderReadiness::SavedLastCheckFailed { |
| 1370 | category: ErrorCategory::Authentication, |
| 1371 | .. |
| 1372 | } |
| 1373 | )); |
| 1374 | assert!(resolved.can_attempt()); |
| 1375 | } |
| 1376 | |
| 1377 | #[test] |
| 1378 | fn tool_failures_do_not_poison_provider_health() { |
| 1379 | let _lock = crate::test_support::lock_test_env(); |
| 1380 | let _cli = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 1381 | let _source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 1382 | let config = literal_health_config(ProviderKind::Deepseek); |
| 1383 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1384 | checks.record_success( |
| 1385 | &config, |
| 1386 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1387 | &config, |
| 1388 | ProviderKind::Deepseek, |
| 1389 | "deepseek-v4-pro", |
| 1390 | ), |
| 1391 | "deepseek-v4-pro", |
| 1392 | ); |
| 1393 | checks.record_failure( |
| 1394 | &config, |
| 1395 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1396 | &config, |
| 1397 | ProviderKind::Deepseek, |
| 1398 | "deepseek-v4-pro", |
| 1399 | ), |
| 1400 | "deepseek-v4-pro", |
| 1401 | &ErrorEnvelope::new( |
| 1402 | ErrorCategory::Tool, |
| 1403 | ErrorSeverity::Error, |
| 1404 | false, |
| 1405 | "tool_failed", |
| 1406 | "shell failed", |
| 1407 | ), |
| 1408 | ); |
| 1409 | assert!(matches!( |
| 1410 | resolve_test_route( |
| 1411 | &config, |
| 1412 | ProviderKind::Deepseek, |
| 1413 | "deepseek-v4-pro", |
| 1414 | CredentialState::Saved, |
| 1415 | true, |
| 1416 | &checks, |
| 1417 | ), |
| 1418 | ResolvedProviderReadiness::Ready |
| 1419 | )); |
| 1420 | } |
| 1421 | |
| 1422 | #[test] |
| 1423 | fn route_and_missing_auth_states_dominate_health() { |
| 1424 | let config = { |
| 1425 | let __cw_config_init_6_0 = Some("openai-codex".to_string()); |
| 1426 | let mut __cw_config_init_6_value: codewhale_runtime::config::Config = |
| 1427 | Default::default(); |
| 1428 | __cw_config_init_6_value.provider = __cw_config_init_6_0; |
| 1429 | __cw_config_init_6_value |
| 1430 | }; |
| 1431 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1432 | checks.record_success( |
| 1433 | &config, |
| 1434 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1435 | &config, |
| 1436 | ProviderKind::OpenaiCodex, |
| 1437 | "gpt-5.5", |
| 1438 | ), |
| 1439 | "gpt-5.5", |
| 1440 | ); |
| 1441 | assert_eq!( |
| 1442 | resolve_test_route( |
| 1443 | &config, |
| 1444 | ProviderKind::OpenaiCodex, |
| 1445 | "gpt-5.5", |
| 1446 | CredentialState::MissingLogin, |
| 1447 | true, |
| 1448 | &checks |
| 1449 | ), |
| 1450 | ResolvedProviderReadiness::MissingLogin |
| 1451 | ); |
| 1452 | assert_eq!( |
| 1453 | resolve_test_route( |
| 1454 | &config, |
| 1455 | ProviderKind::OpenaiCodex, |
| 1456 | "gpt-5.5", |
| 1457 | CredentialState::Saved, |
| 1458 | false, |
| 1459 | &checks |
| 1460 | ), |
| 1461 | ResolvedProviderReadiness::InvalidRoute |
| 1462 | ); |
| 1463 | } |
| 1464 | |
| 1465 | #[test] |
| 1466 | fn api_key_success_does_not_verify_new_xai_oauth_route() { |
| 1467 | let _lock = crate::test_support::lock_test_env(); |
| 1468 | let temp = tempfile::tempdir().expect("oauth fixture root"); |
| 1469 | let oauth_path = temp.path().join("grok-auth.json"); |
| 1470 | std::fs::write( |
| 1471 | &oauth_path, |
| 1472 | serde_json::to_vec(&serde_json::json!({ |
| 1473 | "test-scope": { |
| 1474 | "key": "expired-access-token", |
| 1475 | "refresh_token": "saved-refresh-token", |
| 1476 | "expires_at": "2000-01-01T00:00:00Z", |
| 1477 | "auth_mode": "oidc" |
| 1478 | } |
| 1479 | })) |
| 1480 | .expect("oauth json"), |
| 1481 | ) |
| 1482 | .expect("oauth fixture"); |
| 1483 | let _oauth_path = crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &oauth_path); |
| 1484 | |
| 1485 | let api_key_config = { |
| 1486 | let __cw_config_init_7_0 = Some("xai".to_string()); |
| 1487 | let __cw_config_init_7_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1488 | xai: codewhale_runtime::config::ProviderConfig { |
| 1489 | api_key: Some("xai-test-key".to_string()), |
| 1490 | auth_mode: Some("api_key".to_string()), |
| 1491 | ..Default::default() |
| 1492 | }, |
| 1493 | ..Default::default() |
| 1494 | }); |
| 1495 | let mut __cw_config_init_7_value: codewhale_runtime::config::Config = |
| 1496 | Default::default(); |
| 1497 | __cw_config_init_7_value.provider = __cw_config_init_7_0; |
| 1498 | __cw_config_init_7_value.providers = __cw_config_init_7_1; |
| 1499 | __cw_config_init_7_value |
| 1500 | }; |
| 1501 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1502 | let api_key_model = api_key_config.default_model(); |
| 1503 | checks.record_success( |
| 1504 | &api_key_config, |
| 1505 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1506 | &api_key_config, |
| 1507 | ProviderKind::Xai, |
| 1508 | &api_key_model, |
| 1509 | ), |
| 1510 | &api_key_model, |
| 1511 | ); |
| 1512 | |
| 1513 | let mut oauth_config = api_key_config; |
| 1514 | oauth_config |
| 1515 | .providers |
| 1516 | .as_mut() |
| 1517 | .expect("providers") |
| 1518 | .xai |
| 1519 | .auth_mode = Some("oauth".to_string()); |
| 1520 | assert_eq!( |
| 1521 | credential_state_for_provider( |
| 1522 | &oauth_config, |
| 1523 | &(oauth_config).test_identity_for_kind(ProviderKind::Xai) |
| 1524 | ), |
| 1525 | CredentialState::Saved, |
| 1526 | "fixture must have structurally valid OAuth material" |
| 1527 | ); |
| 1528 | let model = oauth_config.default_model(); |
| 1529 | assert_eq!( |
| 1530 | resolve_for_model( |
| 1531 | &oauth_config, |
| 1532 | &(oauth_config).test_identity_for_kind(ProviderKind::Xai), |
| 1533 | &model, |
| 1534 | &checks |
| 1535 | ), |
| 1536 | ResolvedProviderReadiness::SavedUnchecked, |
| 1537 | "API-key evidence must not cross the auth-class boundary" |
| 1538 | ); |
| 1539 | } |
| 1540 | |
| 1541 | #[test] |
| 1542 | fn observed_success_is_scoped_to_exact_model_endpoint_and_custom_provider() { |
| 1543 | let deepseek = <codewhale_runtime::config::Config as Default>::default() |
| 1544 | .with_legacy_root(Some("deepseek-test-key".to_string()), None); |
| 1545 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1546 | checks.record_success( |
| 1547 | &deepseek, |
| 1548 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1549 | &deepseek, |
| 1550 | ProviderKind::Deepseek, |
| 1551 | "deepseek-v4-pro", |
| 1552 | ), |
| 1553 | "deepseek-v4-pro", |
| 1554 | ); |
| 1555 | assert_eq!( |
| 1556 | resolve_for_model( |
| 1557 | &deepseek, |
| 1558 | &(deepseek).test_identity_for_kind(ProviderKind::Deepseek), |
| 1559 | "deepseek-v4-flash", |
| 1560 | &checks, |
| 1561 | ), |
| 1562 | ResolvedProviderReadiness::SavedUnchecked, |
| 1563 | "one model entitlement must not verify a sibling model" |
| 1564 | ); |
| 1565 | |
| 1566 | let custom_config = |id: &str, endpoint: &str| { |
| 1567 | let __cw_config_init_9_0 = Some(id.to_string()); |
| 1568 | let __cw_config_init_9_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1569 | custom: std::collections::HashMap::from([( |
| 1570 | id.to_string(), |
| 1571 | codewhale_runtime::config::ProviderConfig { |
| 1572 | kind: Some("openai-compatible".to_string()), |
| 1573 | base_url: Some(endpoint.to_string()), |
| 1574 | model: Some("private-coder".to_string()), |
| 1575 | api_key: Some("custom-test-key".to_string()), |
| 1576 | ..Default::default() |
| 1577 | }, |
| 1578 | )]), |
| 1579 | ..Default::default() |
| 1580 | }); |
| 1581 | let mut __cw_config_init_9_value: codewhale_runtime::config::Config = |
| 1582 | Default::default(); |
| 1583 | __cw_config_init_9_value.provider = __cw_config_init_9_0; |
| 1584 | __cw_config_init_9_value.providers = __cw_config_init_9_1; |
| 1585 | __cw_config_init_9_value |
| 1586 | }; |
| 1587 | let alpha = custom_config("alpha", "https://alpha.example/v1"); |
| 1588 | checks.record_success( |
| 1589 | &alpha, |
| 1590 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1591 | &alpha, |
| 1592 | ProviderKind::Custom, |
| 1593 | "private-coder", |
| 1594 | ), |
| 1595 | "private-coder", |
| 1596 | ); |
| 1597 | |
| 1598 | let beta = custom_config("beta", "https://alpha.example/v1"); |
| 1599 | assert_eq!( |
| 1600 | resolve_for_model( |
| 1601 | &beta, |
| 1602 | &(beta).test_identity_for_kind(ProviderKind::Custom), |
| 1603 | "private-coder", |
| 1604 | &checks |
| 1605 | ), |
| 1606 | ResolvedProviderReadiness::SavedUnchecked, |
| 1607 | "named custom providers must not share observed health" |
| 1608 | ); |
| 1609 | |
| 1610 | let alpha_moved = custom_config("alpha", "https://other.example/v1"); |
| 1611 | assert_eq!( |
| 1612 | resolve_for_model( |
| 1613 | &alpha_moved, |
| 1614 | &(alpha_moved).test_identity_for_kind(ProviderKind::Custom), |
| 1615 | "private-coder", |
| 1616 | &checks, |
| 1617 | ), |
| 1618 | ResolvedProviderReadiness::SavedUnchecked, |
| 1619 | "changing endpoints must invalidate observed health" |
| 1620 | ); |
| 1621 | } |
| 1622 | |
| 1623 | #[test] |
| 1624 | fn auto_model_readiness_follows_the_route_not_the_literal_identity() { |
| 1625 | let config = <codewhale_runtime::config::Config as Default>::default() |
| 1626 | .with_legacy_root(Some("test-key".to_string()), None); |
| 1627 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1628 | |
| 1629 | // Before any observed turn, auto honestly reports unchecked. |
| 1630 | assert_eq!( |
| 1631 | resolve_for_model( |
| 1632 | &config, |
| 1633 | &(config).test_identity_for_kind(ProviderKind::Deepseek), |
| 1634 | "auto", |
| 1635 | &checks |
| 1636 | ), |
| 1637 | ResolvedProviderReadiness::SavedUnchecked, |
| 1638 | "auto with no observed history must stay unchecked" |
| 1639 | ); |
| 1640 | |
| 1641 | // A successful concrete-model turn on the route verifies auto too — |
| 1642 | // the router picks the model, so per-model scoping cannot apply. |
| 1643 | checks.record_success( |
| 1644 | &config, |
| 1645 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1646 | &config, |
| 1647 | ProviderKind::Deepseek, |
| 1648 | "deepseek-v4-flash", |
| 1649 | ), |
| 1650 | "deepseek-v4-flash", |
| 1651 | ); |
| 1652 | assert_eq!( |
| 1653 | resolve_for_model( |
| 1654 | &config, |
| 1655 | &(config).test_identity_for_kind(ProviderKind::Deepseek), |
| 1656 | "auto", |
| 1657 | &checks |
| 1658 | ), |
| 1659 | ResolvedProviderReadiness::Ready, |
| 1660 | "a passed turn on the route must clear auto's not-checked badge" |
| 1661 | ); |
| 1662 | |
| 1663 | // A later failure on the same route must surface for auto as well. |
| 1664 | checks.record_failure_message( |
| 1665 | &config, |
| 1666 | &(config).test_identity_for_kind(ProviderKind::Deepseek), |
| 1667 | "deepseek-v4-pro", |
| 1668 | codewhale_error_taxonomy::ErrorCategory::Authentication, |
| 1669 | "401 unauthorized", |
| 1670 | ); |
| 1671 | assert!( |
| 1672 | matches!( |
| 1673 | resolve_for_model( |
| 1674 | &config, |
| 1675 | &(config).test_identity_for_kind(ProviderKind::Deepseek), |
| 1676 | "auto", |
| 1677 | &checks |
| 1678 | ), |
| 1679 | ResolvedProviderReadiness::SavedLastCheckFailed { .. } |
| 1680 | ), |
| 1681 | "the most recent route check must win for auto, including failures" |
| 1682 | ); |
| 1683 | } |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn auto_readiness_does_not_leak_across_providers_or_endpoints() { |
| 1687 | let custom_config = |id: &str, endpoint: &str| { |
| 1688 | let __cw_config_init_11_0 = Some(id.to_string()); |
| 1689 | let __cw_config_init_11_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1690 | custom: std::collections::HashMap::from([( |
| 1691 | id.to_string(), |
| 1692 | codewhale_runtime::config::ProviderConfig { |
| 1693 | kind: Some("openai-compatible".to_string()), |
| 1694 | base_url: Some(endpoint.to_string()), |
| 1695 | model: Some("private-coder".to_string()), |
| 1696 | api_key: Some("test-key".to_string()), |
| 1697 | ..Default::default() |
| 1698 | }, |
| 1699 | )]), |
| 1700 | ..Default::default() |
| 1701 | }); |
| 1702 | let mut __cw_config_init_11_value: codewhale_runtime::config::Config = |
| 1703 | Default::default(); |
| 1704 | __cw_config_init_11_value.provider = __cw_config_init_11_0; |
| 1705 | __cw_config_init_11_value.providers = __cw_config_init_11_1; |
| 1706 | __cw_config_init_11_value |
| 1707 | }; |
| 1708 | let mut checks = ProviderReadinessSnapshot::default(); |
| 1709 | let alpha = custom_config("alpha", "https://alpha.example/v1"); |
| 1710 | checks.record_success( |
| 1711 | &alpha, |
| 1712 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 1713 | &alpha, |
| 1714 | ProviderKind::Custom, |
| 1715 | "private-coder", |
| 1716 | ), |
| 1717 | "private-coder", |
| 1718 | ); |
| 1719 | |
| 1720 | // Same endpoint, different named provider: no leak. |
| 1721 | let beta = custom_config("beta", "https://alpha.example/v1"); |
| 1722 | assert_eq!( |
| 1723 | resolve_for_model( |
| 1724 | &beta, |
| 1725 | &(beta).test_identity_for_kind(ProviderKind::Custom), |
| 1726 | "auto", |
| 1727 | &checks |
| 1728 | ), |
| 1729 | ResolvedProviderReadiness::SavedUnchecked, |
| 1730 | "auto fallback is scoped to the route, not the workspace" |
| 1731 | ); |
| 1732 | |
| 1733 | // Same named provider, different endpoint: no leak. |
| 1734 | let alpha_moved = custom_config("alpha", "https://other.example/v1"); |
| 1735 | assert_eq!( |
| 1736 | resolve_for_model( |
| 1737 | &alpha_moved, |
| 1738 | &(alpha_moved).test_identity_for_kind(ProviderKind::Custom), |
| 1739 | "auto", |
| 1740 | &checks |
| 1741 | ), |
| 1742 | ResolvedProviderReadiness::SavedUnchecked, |
| 1743 | "changing endpoints must invalidate the auto fallback too" |
| 1744 | ); |
| 1745 | } |
| 1746 | |
| 1747 | #[test] |
| 1748 | fn disabled_external_imports_are_not_probed_by_readiness() { |
| 1749 | let _lock = crate::test_support::lock_test_env(); |
| 1750 | let temp = tempfile::tempdir().expect("oauth fixture root"); |
| 1751 | let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 1752 | let kimi_home = temp.path().join("kimi"); |
| 1753 | std::fs::create_dir_all(kimi_home.join("credentials")).expect("kimi credentials dir"); |
| 1754 | std::fs::write(kimi_home.join("credentials/kimi-code.json"), "{not-json") |
| 1755 | .expect("malformed kimi fixture"); |
| 1756 | let _kimi_home = crate::test_support::EnvVarGuard::set( |
| 1757 | "KIMI_CODE_HOME", |
| 1758 | kimi_home.to_str().expect("utf8 path"), |
| 1759 | ); |
| 1760 | let grok_path = temp.path().join("grok-auth.json"); |
| 1761 | std::fs::write(&grok_path, "{}").expect("empty grok fixture"); |
| 1762 | let _grok_path = crate::test_support::EnvVarGuard::set( |
| 1763 | "GROK_AUTH_PATH", |
| 1764 | grok_path.to_str().expect("utf8 path"), |
| 1765 | ); |
| 1766 | |
| 1767 | let config = { |
| 1768 | let __cw_config_init_12_0 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1769 | moonshot: codewhale_runtime::config::ProviderConfig { |
| 1770 | auth_mode: Some("kimi_oauth".to_string()), |
| 1771 | ..Default::default() |
| 1772 | }, |
| 1773 | xai: codewhale_runtime::config::ProviderConfig { |
| 1774 | auth_mode: Some("oauth".to_string()), |
| 1775 | ..Default::default() |
| 1776 | }, |
| 1777 | ..Default::default() |
| 1778 | }); |
| 1779 | let mut __cw_config_init_12_value: codewhale_runtime::config::Config = |
| 1780 | Default::default(); |
| 1781 | __cw_config_init_12_value.providers = __cw_config_init_12_0; |
| 1782 | __cw_config_init_12_value |
| 1783 | }; |
| 1784 | |
| 1785 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 1786 | assert_eq!( |
| 1787 | credential_state_for_provider( |
| 1788 | &config, |
| 1789 | &(config).test_identity_for_kind(ProviderKind::Moonshot) |
| 1790 | ), |
| 1791 | CredentialState::MissingKey, |
| 1792 | "an unusable Kimi import must recover through the supported API-key route" |
| 1793 | ); |
| 1794 | assert_eq!( |
| 1795 | credential_state_for_provider( |
| 1796 | &config, |
| 1797 | &(config).test_identity_for_kind(ProviderKind::Xai) |
| 1798 | ), |
| 1799 | CredentialState::MissingLogin |
| 1800 | ); |
| 1801 | assert_eq!( |
| 1802 | codewhale_runtime::external_credentials::side_effect_trap_counts(), |
| 1803 | (0, 0), |
| 1804 | "readiness must not inspect external OAuth files without consent" |
| 1805 | ); |
| 1806 | assert_eq!( |
| 1807 | std::fs::read_to_string(kimi_home.join("credentials/kimi-code.json")) |
| 1808 | .expect("Kimi fixture unchanged"), |
| 1809 | "{not-json" |
| 1810 | ); |
| 1811 | assert_eq!( |
| 1812 | std::fs::read_to_string(&grok_path).expect("Grok fixture unchanged"), |
| 1813 | "{}" |
| 1814 | ); |
| 1815 | |
| 1816 | let api_key_config = { |
| 1817 | let __cw_config_init_13_0 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1818 | xai: codewhale_runtime::config::ProviderConfig { |
| 1819 | api_key: Some("explicit-xai-key".to_string()), |
| 1820 | ..Default::default() |
| 1821 | }, |
| 1822 | ..Default::default() |
| 1823 | }); |
| 1824 | let mut __cw_config_init_13_value: codewhale_runtime::config::Config = |
| 1825 | Default::default(); |
| 1826 | __cw_config_init_13_value.providers = __cw_config_init_13_0; |
| 1827 | __cw_config_init_13_value |
| 1828 | }; |
| 1829 | assert_eq!( |
| 1830 | credential_state_for_provider( |
| 1831 | &api_key_config, |
| 1832 | &(api_key_config).test_identity_for_kind(ProviderKind::Xai) |
| 1833 | ), |
| 1834 | CredentialState::Saved, |
| 1835 | "an unrelated stale Grok OAuth file must not shadow an explicit xAI API key" |
| 1836 | ); |
| 1837 | assert_eq!( |
| 1838 | credential_state_for_provider( |
| 1839 | &codewhale_runtime::config::Config::default(), |
| 1840 | &(codewhale_runtime::config::Config::default()) |
| 1841 | .test_identity_for_kind(ProviderKind::Xai) |
| 1842 | ), |
| 1843 | CredentialState::MissingKey, |
| 1844 | "a Grok file is not active until xAI OAuth is selected in config" |
| 1845 | ); |
| 1846 | let stale_root_config = { |
| 1847 | let __cw_config_init_14_0 = Some("xai".to_string()); |
| 1848 | let mut __cw_config_init_14_value: codewhale_runtime::config::Config = |
| 1849 | Default::default(); |
| 1850 | __cw_config_init_14_value.provider = __cw_config_init_14_0; |
| 1851 | __cw_config_init_14_value |
| 1852 | } |
| 1853 | .with_legacy_root(Some("legacy-deepseek-root-key".to_string()), None); |
| 1854 | assert_eq!( |
| 1855 | credential_state_for_provider( |
| 1856 | &stale_root_config, |
| 1857 | &(stale_root_config).test_identity_for_kind(ProviderKind::Xai) |
| 1858 | ), |
| 1859 | CredentialState::MissingKey, |
| 1860 | "the legacy root DeepSeek key is not an xAI credential" |
| 1861 | ); |
| 1862 | |
| 1863 | let _cli_source = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY_SOURCE", "cli"); |
| 1864 | let _cli_key = |
| 1865 | crate::test_support::EnvVarGuard::set("CODEWHALE_CLI_API_KEY", "explicit-cli-key"); |
| 1866 | let cli_config = { |
| 1867 | let __cw_config_init_15_0 = Some("xai".to_string()); |
| 1868 | let mut __cw_config_init_15_value: codewhale_runtime::config::Config = |
| 1869 | Default::default(); |
| 1870 | __cw_config_init_15_value.provider = __cw_config_init_15_0; |
| 1871 | __cw_config_init_15_value |
| 1872 | }; |
| 1873 | assert_eq!( |
| 1874 | credential_state_for_provider( |
| 1875 | &cli_config, |
| 1876 | &(cli_config).test_identity_for_kind(ProviderKind::Xai) |
| 1877 | ), |
| 1878 | CredentialState::Saved, |
| 1879 | "the source-marked CLI override is valid for the active xAI provider" |
| 1880 | ); |
| 1881 | } |
| 1882 | |
| 1883 | #[test] |
| 1884 | fn custom_provider_env_and_local_no_auth_states_match_runtime() { |
| 1885 | let _lock = crate::test_support::lock_test_env(); |
| 1886 | let _custom_key = crate::test_support::EnvVarGuard::set("ACME_CUSTOM_KEY", "custom-secret"); |
| 1887 | let remote = { |
| 1888 | let __cw_config_init_16_0 = Some("acme".to_string()); |
| 1889 | let __cw_config_init_16_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1890 | custom: std::collections::HashMap::from([( |
| 1891 | "acme".to_string(), |
| 1892 | codewhale_runtime::config::ProviderConfig { |
| 1893 | kind: Some("openai-compatible".to_string()), |
| 1894 | base_url: Some("https://api.acme.test/v1".to_string()), |
| 1895 | model: Some("acme-coder".to_string()), |
| 1896 | api_key_env: Some("ACME_CUSTOM_KEY".to_string()), |
| 1897 | ..Default::default() |
| 1898 | }, |
| 1899 | )]), |
| 1900 | ..Default::default() |
| 1901 | }); |
| 1902 | let mut __cw_config_init_16_value: codewhale_runtime::config::Config = |
| 1903 | Default::default(); |
| 1904 | __cw_config_init_16_value.provider = __cw_config_init_16_0; |
| 1905 | __cw_config_init_16_value.providers = __cw_config_init_16_1; |
| 1906 | __cw_config_init_16_value |
| 1907 | }; |
| 1908 | assert_eq!( |
| 1909 | credential_state_for_provider( |
| 1910 | &remote, |
| 1911 | &(remote).test_identity_for_kind(ProviderKind::Custom) |
| 1912 | ), |
| 1913 | CredentialState::Saved |
| 1914 | ); |
| 1915 | |
| 1916 | let local = { |
| 1917 | let __cw_config_init_17_0 = Some("local-acme".to_string()); |
| 1918 | let __cw_config_init_17_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1919 | custom: std::collections::HashMap::from([( |
| 1920 | "local-acme".to_string(), |
| 1921 | codewhale_runtime::config::ProviderConfig { |
| 1922 | kind: Some("openai-compatible".to_string()), |
| 1923 | base_url: Some("http://127.0.0.1:8080/v1".to_string()), |
| 1924 | model: Some("local-model".to_string()), |
| 1925 | auth_mode: Some("none".to_string()), |
| 1926 | ..Default::default() |
| 1927 | }, |
| 1928 | )]), |
| 1929 | ..Default::default() |
| 1930 | }); |
| 1931 | let mut __cw_config_init_17_value: codewhale_runtime::config::Config = |
| 1932 | Default::default(); |
| 1933 | __cw_config_init_17_value.provider = __cw_config_init_17_0; |
| 1934 | __cw_config_init_17_value.providers = __cw_config_init_17_1; |
| 1935 | __cw_config_init_17_value |
| 1936 | }; |
| 1937 | assert_eq!( |
| 1938 | credential_state_for_provider( |
| 1939 | &local, |
| 1940 | &(local).test_identity_for_kind(ProviderKind::Custom) |
| 1941 | ), |
| 1942 | CredentialState::NoAuth |
| 1943 | ); |
| 1944 | assert_eq!( |
| 1945 | resolve_for_model( |
| 1946 | &local, |
| 1947 | &(local).test_identity_for_kind(ProviderKind::Custom), |
| 1948 | "local-model", |
| 1949 | &ProviderReadinessSnapshot::default(), |
| 1950 | ), |
| 1951 | ResolvedProviderReadiness::NoAuthUnchecked |
| 1952 | ); |
| 1953 | } |
| 1954 | |
| 1955 | #[test] |
| 1956 | fn no_auth_has_distinct_readiness_and_cache_identity_from_implicit_local() { |
| 1957 | let local = { |
| 1958 | let __cw_config_init_18_0 = Some("vllm".to_string()); |
| 1959 | let __cw_config_init_18_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1960 | vllm: codewhale_runtime::config::ProviderConfig { |
| 1961 | base_url: Some("http://127.0.0.1:8000/v1".to_string()), |
| 1962 | model: Some("local-model".to_string()), |
| 1963 | ..Default::default() |
| 1964 | }, |
| 1965 | ..Default::default() |
| 1966 | }); |
| 1967 | let mut __cw_config_init_18_value: codewhale_runtime::config::Config = |
| 1968 | Default::default(); |
| 1969 | __cw_config_init_18_value.provider = __cw_config_init_18_0; |
| 1970 | __cw_config_init_18_value.providers = __cw_config_init_18_1; |
| 1971 | __cw_config_init_18_value |
| 1972 | }; |
| 1973 | let mut no_auth = local.clone(); |
| 1974 | no_auth |
| 1975 | .providers |
| 1976 | .as_mut() |
| 1977 | .expect("providers") |
| 1978 | .vllm |
| 1979 | .auth_mode = Some("no-auth".to_string()); |
| 1980 | |
| 1981 | assert_eq!( |
| 1982 | credential_state_for_provider( |
| 1983 | &local, |
| 1984 | &(local).test_identity_for_kind(ProviderKind::Vllm) |
| 1985 | ), |
| 1986 | CredentialState::Local |
| 1987 | ); |
| 1988 | assert_eq!( |
| 1989 | credential_state_for_provider( |
| 1990 | &no_auth, |
| 1991 | &(no_auth).test_identity_for_kind(ProviderKind::Vllm) |
| 1992 | ), |
| 1993 | CredentialState::NoAuth |
| 1994 | ); |
| 1995 | assert_eq!( |
| 1996 | auth_class_for_provider(&local, &(local).test_identity_for_kind(ProviderKind::Vllm)), |
| 1997 | ProviderAuthClass::Local |
| 1998 | ); |
| 1999 | assert_eq!( |
| 2000 | auth_class_for_provider( |
| 2001 | &no_auth, |
| 2002 | &(no_auth).test_identity_for_kind(ProviderKind::Vllm) |
| 2003 | ), |
| 2004 | ProviderAuthClass::NoAuth |
| 2005 | ); |
| 2006 | |
| 2007 | let mut checks = ProviderReadinessSnapshot::default(); |
| 2008 | checks.record_success( |
| 2009 | &local, |
| 2010 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 2011 | &local, |
| 2012 | ProviderKind::Vllm, |
| 2013 | "local-model", |
| 2014 | ), |
| 2015 | "local-model", |
| 2016 | ); |
| 2017 | assert_eq!( |
| 2018 | resolve_for_model( |
| 2019 | &no_auth, |
| 2020 | &(no_auth).test_identity_for_kind(ProviderKind::Vllm), |
| 2021 | "local-model", |
| 2022 | &checks |
| 2023 | ), |
| 2024 | ResolvedProviderReadiness::NoAuthUnchecked, |
| 2025 | "implicit-local success must not verify an explicitly no-auth route" |
| 2026 | ); |
| 2027 | assert!(ResolvedProviderReadiness::NoAuthUnchecked.can_attempt()); |
| 2028 | assert_eq!( |
| 2029 | ResolvedProviderReadiness::NoAuthUnchecked.label(), |
| 2030 | "no auth · not checked" |
| 2031 | ); |
| 2032 | } |
| 2033 | |
| 2034 | #[test] |
| 2035 | fn ollama_readiness_distinguishes_local_from_cloud_credentials() { |
| 2036 | let _lock = crate::test_support::lock_test_env(); |
| 2037 | let temp = tempfile::tempdir().expect("isolated credential home"); |
| 2038 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 2039 | let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2040 | let _ollama_cloud_key = crate::test_support::EnvVarGuard::remove("OLLAMA_CLOUD_API_KEY"); |
| 2041 | let _ollama_key = crate::test_support::EnvVarGuard::remove("OLLAMA_API_KEY"); |
| 2042 | let _cli_source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 2043 | let _cli_key = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 2044 | |
| 2045 | let local = { |
| 2046 | let __cw_config_init_19_0 = Some("ollama".to_string()); |
| 2047 | let mut __cw_config_init_19_value: codewhale_runtime::config::Config = |
| 2048 | Default::default(); |
| 2049 | __cw_config_init_19_value.provider = __cw_config_init_19_0; |
| 2050 | __cw_config_init_19_value |
| 2051 | }; |
| 2052 | assert_eq!( |
| 2053 | credential_state_for_provider( |
| 2054 | &local, |
| 2055 | &(local).test_identity_for_kind(ProviderKind::Ollama) |
| 2056 | ), |
| 2057 | CredentialState::Local |
| 2058 | ); |
| 2059 | assert_eq!( |
| 2060 | auth_class_for_provider( |
| 2061 | &local, |
| 2062 | &(local).test_identity_for_kind(ProviderKind::Ollama) |
| 2063 | ), |
| 2064 | ProviderAuthClass::Local |
| 2065 | ); |
| 2066 | |
| 2067 | let mut cloud = { |
| 2068 | let __cw_config_init_20_0 = Some("ollama".to_string()); |
| 2069 | let __cw_config_init_20_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2070 | ollama: codewhale_runtime::config::ProviderConfig { |
| 2071 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 2072 | ..Default::default() |
| 2073 | }, |
| 2074 | ..Default::default() |
| 2075 | }); |
| 2076 | let mut __cw_config_init_20_value: codewhale_runtime::config::Config = |
| 2077 | Default::default(); |
| 2078 | __cw_config_init_20_value.provider = __cw_config_init_20_0; |
| 2079 | __cw_config_init_20_value.providers = __cw_config_init_20_1; |
| 2080 | __cw_config_init_20_value |
| 2081 | }; |
| 2082 | assert_eq!( |
| 2083 | cloud.active_provider_identity().unwrap().provider, |
| 2084 | ProviderKind::OllamaCloud |
| 2085 | ); |
| 2086 | assert_eq!( |
| 2087 | credential_state_for_provider( |
| 2088 | &cloud, |
| 2089 | &(cloud).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2090 | ), |
| 2091 | CredentialState::MissingKey |
| 2092 | ); |
| 2093 | assert_eq!( |
| 2094 | auth_class_for_provider( |
| 2095 | &cloud, |
| 2096 | &(cloud).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2097 | ), |
| 2098 | ProviderAuthClass::ApiKey |
| 2099 | ); |
| 2100 | |
| 2101 | cloud.providers.as_mut().expect("providers").ollama.api_key = |
| 2102 | Some("ollama-cloud-key".to_string()); |
| 2103 | assert_eq!( |
| 2104 | credential_state_for_provider( |
| 2105 | &cloud, |
| 2106 | &(cloud).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2107 | ), |
| 2108 | CredentialState::Saved |
| 2109 | ); |
| 2110 | } |
| 2111 | |
| 2112 | #[test] |
| 2113 | fn explicit_api_key_mode_on_loopback_requires_a_real_credential() { |
| 2114 | let _lock = crate::test_support::lock_test_env(); |
| 2115 | let temp = tempfile::tempdir().expect("isolated credential home"); |
| 2116 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 2117 | let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2118 | let _vllm_key = crate::test_support::EnvVarGuard::remove("VLLM_API_KEY"); |
| 2119 | let _cli_source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 2120 | let _cli_key = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 2121 | |
| 2122 | let missing = { |
| 2123 | let __cw_config_init_21_0 = Some("vllm".to_string()); |
| 2124 | let __cw_config_init_21_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2125 | vllm: codewhale_runtime::config::ProviderConfig { |
| 2126 | base_url: Some("http://127.0.0.1:8000/v1".to_string()), |
| 2127 | model: Some("local-model".to_string()), |
| 2128 | auth_mode: Some("api_key".to_string()), |
| 2129 | ..Default::default() |
| 2130 | }, |
| 2131 | ..Default::default() |
| 2132 | }); |
| 2133 | let mut __cw_config_init_21_value: codewhale_runtime::config::Config = |
| 2134 | Default::default(); |
| 2135 | __cw_config_init_21_value.provider = __cw_config_init_21_0; |
| 2136 | __cw_config_init_21_value.providers = __cw_config_init_21_1; |
| 2137 | __cw_config_init_21_value |
| 2138 | }; |
| 2139 | assert_eq!( |
| 2140 | credential_state_for_provider( |
| 2141 | &missing, |
| 2142 | &(missing).test_identity_for_kind(ProviderKind::Vllm) |
| 2143 | ), |
| 2144 | CredentialState::MissingKey |
| 2145 | ); |
| 2146 | assert!(missing.active_route_api_key().is_err()); |
| 2147 | |
| 2148 | let mut configured = missing.clone(); |
| 2149 | configured |
| 2150 | .providers |
| 2151 | .as_mut() |
| 2152 | .expect("providers") |
| 2153 | .vllm |
| 2154 | .api_key = Some("protected-local-key".to_string()); |
| 2155 | assert_eq!( |
| 2156 | credential_state_for_provider( |
| 2157 | &configured, |
| 2158 | &(configured).test_identity_for_kind(ProviderKind::Vllm) |
| 2159 | ), |
| 2160 | CredentialState::Saved |
| 2161 | ); |
| 2162 | assert_eq!( |
| 2163 | configured.active_route_api_key().expect("configured key"), |
| 2164 | "protected-local-key" |
| 2165 | ); |
| 2166 | |
| 2167 | let named_custom = { |
| 2168 | let __cw_config_init_22_0 = Some("protected-local".to_string()); |
| 2169 | let __cw_config_init_22_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2170 | custom: std::collections::HashMap::from([( |
| 2171 | "protected-local".to_string(), |
| 2172 | codewhale_runtime::config::ProviderConfig { |
| 2173 | kind: Some("openai-compatible".to_string()), |
| 2174 | base_url: Some("http://127.0.0.1:9000/v1".to_string()), |
| 2175 | model: Some("private-model".to_string()), |
| 2176 | auth_mode: Some("bearer".to_string()), |
| 2177 | ..Default::default() |
| 2178 | }, |
| 2179 | )]), |
| 2180 | ..Default::default() |
| 2181 | }); |
| 2182 | let mut __cw_config_init_22_value: codewhale_runtime::config::Config = |
| 2183 | Default::default(); |
| 2184 | __cw_config_init_22_value.provider = __cw_config_init_22_0; |
| 2185 | __cw_config_init_22_value.providers = __cw_config_init_22_1; |
| 2186 | __cw_config_init_22_value |
| 2187 | }; |
| 2188 | assert_eq!( |
| 2189 | credential_state_for_provider( |
| 2190 | &named_custom, |
| 2191 | &(named_custom).test_identity_for_kind(ProviderKind::Custom) |
| 2192 | ), |
| 2193 | CredentialState::MissingKey |
| 2194 | ); |
| 2195 | assert!(named_custom.active_route_api_key().is_err()); |
| 2196 | } |
| 2197 | |
| 2198 | #[test] |
| 2199 | fn provider_auth_metadata_is_not_a_runtime_credential() { |
| 2200 | let _lock = crate::test_support::lock_test_env(); |
| 2201 | let temp = tempfile::tempdir().expect("isolated credential home"); |
| 2202 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 2203 | let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2204 | let _openai_key = crate::test_support::EnvVarGuard::remove("OPENAI_API_KEY"); |
| 2205 | let _xai_key = crate::test_support::EnvVarGuard::remove("XAI_API_KEY"); |
| 2206 | let _cli_source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 2207 | let _cli_key = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 2208 | |
| 2209 | let command = { |
| 2210 | let __cw_config_init_23_0 = Some("openai".to_string()); |
| 2211 | let __cw_config_init_23_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2212 | openai: codewhale_runtime::config::ProviderConfig { |
| 2213 | auth: Some(codewhale_config::ProviderAuthSourceToml { |
| 2214 | source: codewhale_config::AuthSourceKind::Command, |
| 2215 | command: vec!["secret-tool".to_string(), "lookup".to_string()], |
| 2216 | timeout_ms: Some(2_000), |
| 2217 | secret_id: None, |
| 2218 | }), |
| 2219 | ..Default::default() |
| 2220 | }, |
| 2221 | ..Default::default() |
| 2222 | }); |
| 2223 | let mut __cw_config_init_23_value: codewhale_runtime::config::Config = |
| 2224 | Default::default(); |
| 2225 | __cw_config_init_23_value.provider = __cw_config_init_23_0; |
| 2226 | __cw_config_init_23_value.providers = __cw_config_init_23_1; |
| 2227 | __cw_config_init_23_value |
| 2228 | }; |
| 2229 | assert_eq!( |
| 2230 | credential_state_for_provider( |
| 2231 | &command, |
| 2232 | &(command).test_identity_for_kind(ProviderKind::Openai) |
| 2233 | ), |
| 2234 | CredentialState::MissingKey |
| 2235 | ); |
| 2236 | |
| 2237 | let secret = { |
| 2238 | let __cw_config_init_24_0 = Some("xai".to_string()); |
| 2239 | let __cw_config_init_24_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2240 | xai: codewhale_runtime::config::ProviderConfig { |
| 2241 | auth: Some(codewhale_config::ProviderAuthSourceToml { |
| 2242 | source: codewhale_config::AuthSourceKind::Secret, |
| 2243 | command: Vec::new(), |
| 2244 | timeout_ms: None, |
| 2245 | secret_id: Some("codewhale/xai".to_string()), |
| 2246 | }), |
| 2247 | ..Default::default() |
| 2248 | }, |
| 2249 | ..Default::default() |
| 2250 | }); |
| 2251 | let mut __cw_config_init_24_value: codewhale_runtime::config::Config = |
| 2252 | Default::default(); |
| 2253 | __cw_config_init_24_value.provider = __cw_config_init_24_0; |
| 2254 | __cw_config_init_24_value.providers = __cw_config_init_24_1; |
| 2255 | __cw_config_init_24_value |
| 2256 | }; |
| 2257 | assert_eq!( |
| 2258 | credential_state_for_provider( |
| 2259 | &secret, |
| 2260 | &(secret).test_identity_for_kind(ProviderKind::Xai) |
| 2261 | ), |
| 2262 | CredentialState::MissingKey |
| 2263 | ); |
| 2264 | } |
| 2265 | |
| 2266 | #[test] |
| 2267 | fn oauth_readiness_is_limited_to_official_endpoints() { |
| 2268 | let _lock = crate::test_support::lock_test_env(); |
| 2269 | let temp = tempfile::tempdir().expect("isolated oauth home"); |
| 2270 | let missing_grok_auth = temp.path().join("missing-grok-auth.json"); |
| 2271 | let _grok_auth = |
| 2272 | crate::test_support::EnvVarGuard::set("GROK_AUTH_PATH", &missing_grok_auth); |
| 2273 | let _xai_key = crate::test_support::EnvVarGuard::remove("XAI_API_KEY"); |
| 2274 | let _codex_key = crate::test_support::EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN"); |
| 2275 | let _legacy_codex_key = crate::test_support::EnvVarGuard::remove("CODEX_ACCESS_TOKEN"); |
| 2276 | |
| 2277 | let custom_xai = { |
| 2278 | let __cw_config_init_25_0 = Some("xai".to_string()); |
| 2279 | let __cw_config_init_25_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2280 | xai: codewhale_runtime::config::ProviderConfig { |
| 2281 | base_url: Some("https://gateway.example.test/v1".to_string()), |
| 2282 | auth_mode: Some("oauth".to_string()), |
| 2283 | ..Default::default() |
| 2284 | }, |
| 2285 | ..Default::default() |
| 2286 | }); |
| 2287 | let mut __cw_config_init_25_value: codewhale_runtime::config::Config = |
| 2288 | Default::default(); |
| 2289 | __cw_config_init_25_value.provider = __cw_config_init_25_0; |
| 2290 | __cw_config_init_25_value.providers = __cw_config_init_25_1; |
| 2291 | __cw_config_init_25_value |
| 2292 | }; |
| 2293 | assert_eq!( |
| 2294 | auth_class_for_provider( |
| 2295 | &custom_xai, |
| 2296 | &(custom_xai).test_identity_for_kind(ProviderKind::Xai) |
| 2297 | ), |
| 2298 | ProviderAuthClass::ApiKey |
| 2299 | ); |
| 2300 | assert_eq!( |
| 2301 | credential_state_for_provider( |
| 2302 | &custom_xai, |
| 2303 | &(custom_xai).test_identity_for_kind(ProviderKind::Xai) |
| 2304 | ), |
| 2305 | CredentialState::MissingKey |
| 2306 | ); |
| 2307 | |
| 2308 | let official_xai = { |
| 2309 | let __cw_config_init_26_0 = Some("xai".to_string()); |
| 2310 | let __cw_config_init_26_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2311 | xai: codewhale_runtime::config::ProviderConfig { |
| 2312 | auth_mode: Some("oauth".to_string()), |
| 2313 | ..Default::default() |
| 2314 | }, |
| 2315 | ..Default::default() |
| 2316 | }); |
| 2317 | let mut __cw_config_init_26_value: codewhale_runtime::config::Config = |
| 2318 | Default::default(); |
| 2319 | __cw_config_init_26_value.provider = __cw_config_init_26_0; |
| 2320 | __cw_config_init_26_value.providers = __cw_config_init_26_1; |
| 2321 | __cw_config_init_26_value |
| 2322 | }; |
| 2323 | assert_eq!( |
| 2324 | auth_class_for_provider( |
| 2325 | &official_xai, |
| 2326 | &(official_xai).test_identity_for_kind(ProviderKind::Xai) |
| 2327 | ), |
| 2328 | ProviderAuthClass::OAuth |
| 2329 | ); |
| 2330 | assert_eq!( |
| 2331 | credential_state_for_provider( |
| 2332 | &official_xai, |
| 2333 | &(official_xai).test_identity_for_kind(ProviderKind::Xai) |
| 2334 | ), |
| 2335 | CredentialState::MissingLogin |
| 2336 | ); |
| 2337 | |
| 2338 | let custom_codex = { |
| 2339 | let __cw_config_init_27_0 = Some("openai-codex".to_string()); |
| 2340 | let __cw_config_init_27_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2341 | openai_codex: codewhale_runtime::config::ProviderConfig { |
| 2342 | base_url: Some("https://gateway.example.test/v1".to_string()), |
| 2343 | ..Default::default() |
| 2344 | }, |
| 2345 | ..Default::default() |
| 2346 | }); |
| 2347 | let mut __cw_config_init_27_value: codewhale_runtime::config::Config = |
| 2348 | Default::default(); |
| 2349 | __cw_config_init_27_value.provider = __cw_config_init_27_0; |
| 2350 | __cw_config_init_27_value.providers = __cw_config_init_27_1; |
| 2351 | __cw_config_init_27_value |
| 2352 | }; |
| 2353 | assert_eq!( |
| 2354 | auth_class_for_provider( |
| 2355 | &custom_codex, |
| 2356 | &(custom_codex).test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 2357 | ), |
| 2358 | ProviderAuthClass::ApiKey |
| 2359 | ); |
| 2360 | assert_eq!( |
| 2361 | credential_state_for_provider( |
| 2362 | &custom_codex, |
| 2363 | &(custom_codex).test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 2364 | ), |
| 2365 | CredentialState::MissingKey |
| 2366 | ); |
| 2367 | } |
| 2368 | |
| 2369 | #[test] |
| 2370 | fn xai_custom_endpoint_does_not_count_ambient_official_key() { |
| 2371 | let _lock = crate::test_support::lock_test_env(); |
| 2372 | let _source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 2373 | let _cli_key = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 2374 | let _ambient = crate::test_support::EnvVarGuard::set("XAI_API_KEY", "ambient-xai-key"); |
| 2375 | let config = { |
| 2376 | let __cw_config_init_28_0 = Some("xai".to_string()); |
| 2377 | let __cw_config_init_28_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2378 | xai: codewhale_runtime::config::ProviderConfig { |
| 2379 | base_url: Some("https://unrelated-gateway.example.test/v1".to_string()), |
| 2380 | model: Some("private-grok-model".to_string()), |
| 2381 | ..Default::default() |
| 2382 | }, |
| 2383 | ..Default::default() |
| 2384 | }); |
| 2385 | let mut __cw_config_init_28_value: codewhale_runtime::config::Config = |
| 2386 | Default::default(); |
| 2387 | __cw_config_init_28_value.provider = __cw_config_init_28_0; |
| 2388 | __cw_config_init_28_value.providers = __cw_config_init_28_1; |
| 2389 | __cw_config_init_28_value |
| 2390 | }; |
| 2391 | |
| 2392 | assert!(!has_api_key_for( |
| 2393 | &config, |
| 2394 | &(config).test_identity_for_kind(ProviderKind::Xai) |
| 2395 | )); |
| 2396 | assert_eq!( |
| 2397 | credential_state_for_provider( |
| 2398 | &config, |
| 2399 | &(config).test_identity_for_kind(ProviderKind::Xai) |
| 2400 | ), |
| 2401 | CredentialState::MissingKey |
| 2402 | ); |
| 2403 | } |
| 2404 | |
| 2405 | #[test] |
| 2406 | fn active_deepseek_routes_validate_models_against_effective_custom_base_url() { |
| 2407 | let official = codewhale_runtime::config::Config::default(); |
| 2408 | assert!(!route_is_valid_for_model( |
| 2409 | &official, |
| 2410 | &(official).test_identity_for_kind(ProviderKind::Deepseek), |
| 2411 | Some("anthropic/private-model") |
| 2412 | )); |
| 2413 | |
| 2414 | for provider_name in ["deepseek", "deepseek-cn"] { |
| 2415 | let config = { |
| 2416 | let __cw_config_init_29_0 = Some(provider_name.to_string()); |
| 2417 | let __cw_config_init_29_1 = Some("anthropic/private-model".to_string()); |
| 2418 | let mut __cw_config_init_29_value: codewhale_runtime::config::Config = |
| 2419 | Default::default(); |
| 2420 | __cw_config_init_29_value.provider = __cw_config_init_29_0; |
| 2421 | __cw_config_init_29_value.default_text_model = __cw_config_init_29_1; |
| 2422 | __cw_config_init_29_value |
| 2423 | } |
| 2424 | .with_legacy_root( |
| 2425 | None, |
| 2426 | Some("https://tenant-gateway.example.test/v1".to_string()), |
| 2427 | ); |
| 2428 | let provider = config.active_provider_identity().unwrap().provider; |
| 2429 | assert!(matches!(provider, ProviderKind::Deepseek)); |
| 2430 | assert!(route_is_valid_for_model( |
| 2431 | &config, |
| 2432 | &(config).test_identity_for_kind(provider), |
| 2433 | Some("anthropic/private-model") |
| 2434 | )); |
| 2435 | } |
| 2436 | } |
| 2437 | |
| 2438 | #[test] |
| 2439 | fn cli_forwarded_deepseek_custom_route_validates_prefixed_model() { |
| 2440 | let _lock = crate::test_support::lock_test_env(); |
| 2441 | let temp = tempfile::tempdir().expect("isolated config home"); |
| 2442 | let config_path = temp.path().join("config.toml"); |
| 2443 | std::fs::write( |
| 2444 | &config_path, |
| 2445 | r#"api_key = "saved-file-key" |
| 2446 | base_url = "https://api.deepseek.com/v1" |
| 2447 | default_text_model = "deepseek-chat" |
| 2448 | "#, |
| 2449 | ) |
| 2450 | .expect("write config"); |
| 2451 | let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 2452 | let _provider = crate::test_support::EnvVarGuard::set("CODEWHALE_PROVIDER", "deepseek"); |
| 2453 | let _legacy_provider = crate::test_support::EnvVarGuard::remove("DEEPSEEK_PROVIDER"); |
| 2454 | let _base = crate::test_support::EnvVarGuard::set( |
| 2455 | "CODEWHALE_BASE_URL", |
| 2456 | "https://tenant-gateway.example.test/v1", |
| 2457 | ); |
| 2458 | let _legacy_base = crate::test_support::EnvVarGuard::remove("DEEPSEEK_BASE_URL"); |
| 2459 | let _model = |
| 2460 | crate::test_support::EnvVarGuard::set("CODEWHALE_MODEL", "anthropic/private-model"); |
| 2461 | let _source = crate::test_support::EnvVarGuard::set("DEEPSEEK_API_KEY_SOURCE", "cli"); |
| 2462 | let _cli_key = |
| 2463 | crate::test_support::EnvVarGuard::set("CODEWHALE_CLI_API_KEY", "explicit-cli-key"); |
| 2464 | |
| 2465 | let config = codewhale_plugins::providers::load_config(Some(config_path), None) |
| 2466 | .expect("load config"); |
| 2467 | assert_eq!(config.default_model(), "anthropic/private-model"); |
| 2468 | assert_eq!( |
| 2469 | config.active_route_api_key().expect("explicit CLI key"), |
| 2470 | "explicit-cli-key" |
| 2471 | ); |
| 2472 | assert!(route_is_valid_for_model( |
| 2473 | &config, |
| 2474 | &(config).test_identity_for_kind(ProviderKind::Deepseek), |
| 2475 | Some("anthropic/private-model") |
| 2476 | )); |
| 2477 | } |
| 2478 | |
| 2479 | #[test] |
| 2480 | fn builtin_loopback_local_and_api_key_routes_have_distinct_cache_identity() { |
| 2481 | let _lock = crate::test_support::lock_test_env(); |
| 2482 | let _openai_key = crate::test_support::EnvVarGuard::remove("OPENAI_API_KEY"); |
| 2483 | let _source = crate::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 2484 | let _cli_key = crate::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 2485 | let local = { |
| 2486 | let __cw_config_init_30_0 = Some("openai".to_string()); |
| 2487 | let __cw_config_init_30_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2488 | openai: codewhale_runtime::config::ProviderConfig { |
| 2489 | base_url: Some("http://127.0.0.1:8080/v1".to_string()), |
| 2490 | model: Some("local-model".to_string()), |
| 2491 | ..Default::default() |
| 2492 | }, |
| 2493 | ..Default::default() |
| 2494 | }); |
| 2495 | let mut __cw_config_init_30_value: codewhale_runtime::config::Config = |
| 2496 | Default::default(); |
| 2497 | __cw_config_init_30_value.provider = __cw_config_init_30_0; |
| 2498 | __cw_config_init_30_value.providers = __cw_config_init_30_1; |
| 2499 | __cw_config_init_30_value |
| 2500 | }; |
| 2501 | let mut protected = local.clone(); |
| 2502 | let protected_route = &mut protected.providers.as_mut().expect("providers").openai; |
| 2503 | protected_route.auth_mode = Some("api_key".to_string()); |
| 2504 | protected_route.api_key = Some("protected-local-key".to_string()); |
| 2505 | |
| 2506 | assert_eq!( |
| 2507 | credential_state_for_provider( |
| 2508 | &local, |
| 2509 | &(local).test_identity_for_kind(ProviderKind::Openai) |
| 2510 | ), |
| 2511 | CredentialState::Local |
| 2512 | ); |
| 2513 | assert_eq!( |
| 2514 | auth_class_for_provider( |
| 2515 | &local, |
| 2516 | &(local).test_identity_for_kind(ProviderKind::Openai) |
| 2517 | ), |
| 2518 | ProviderAuthClass::Local |
| 2519 | ); |
| 2520 | assert_eq!( |
| 2521 | credential_state_for_provider( |
| 2522 | &protected, |
| 2523 | &(protected).test_identity_for_kind(ProviderKind::Openai) |
| 2524 | ), |
| 2525 | CredentialState::Saved |
| 2526 | ); |
| 2527 | assert_eq!( |
| 2528 | auth_class_for_provider( |
| 2529 | &protected, |
| 2530 | &(protected).test_identity_for_kind(ProviderKind::Openai) |
| 2531 | ), |
| 2532 | ProviderAuthClass::ApiKey |
| 2533 | ); |
| 2534 | assert_ne!( |
| 2535 | route_identity_for_model( |
| 2536 | &local, |
| 2537 | &(local).test_identity_for_kind(ProviderKind::Openai), |
| 2538 | "local-model" |
| 2539 | ), |
| 2540 | route_identity_for_model( |
| 2541 | &protected, |
| 2542 | &(protected).test_identity_for_kind(ProviderKind::Openai), |
| 2543 | "local-model" |
| 2544 | ) |
| 2545 | ); |
| 2546 | |
| 2547 | let mut checks = ProviderReadinessSnapshot::default(); |
| 2548 | checks.record_success( |
| 2549 | &local, |
| 2550 | &crate::route_receipt::TurnRouteReceipt::for_test_fixture( |
| 2551 | &local, |
| 2552 | ProviderKind::Openai, |
| 2553 | "local-model", |
| 2554 | ), |
| 2555 | "local-model", |
| 2556 | ); |
| 2557 | assert_eq!( |
| 2558 | resolve_for_model( |
| 2559 | &protected, |
| 2560 | &(protected).test_identity_for_kind(ProviderKind::Openai), |
| 2561 | "local-model", |
| 2562 | &checks |
| 2563 | ), |
| 2564 | ResolvedProviderReadiness::SavedUnchecked |
| 2565 | ); |
| 2566 | |
| 2567 | let deepseek_cn_local = { |
| 2568 | let __cw_config_init_31_0 = Some("deepseek-cn".to_string()); |
| 2569 | let __cw_config_init_31_1 = Some("local-cn-model".to_string()); |
| 2570 | let mut __cw_config_init_31_value: codewhale_runtime::config::Config = |
| 2571 | Default::default(); |
| 2572 | __cw_config_init_31_value.provider = __cw_config_init_31_0; |
| 2573 | __cw_config_init_31_value.default_text_model = __cw_config_init_31_1; |
| 2574 | __cw_config_init_31_value |
| 2575 | } |
| 2576 | .with_legacy_root(None, Some("http://127.0.0.1:9090/v1".to_string())); |
| 2577 | assert_eq!( |
| 2578 | credential_state_for_provider( |
| 2579 | &deepseek_cn_local, |
| 2580 | &(deepseek_cn_local) |
| 2581 | .resolve_provider_selection_identity("deepseek-cn") |
| 2582 | .unwrap() |
| 2583 | ), |
| 2584 | CredentialState::Local |
| 2585 | ); |
| 2586 | } |
| 2587 | #[test] |
| 2588 | fn captured_key_rotation_cannot_reuse_ready_or_failure_evidence() { |
| 2589 | let _env = crate::test_support::lock_test_env(); |
| 2590 | let _cli = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2591 | let mut config = codewhale_runtime::config::Config::from_saved_document( |
| 2592 | r#"provider = "openai" |
| 2593 | [providers.openai] |
| 2594 | api_key = "captured-key" |
| 2595 | model = "gpt-5.5" |
| 2596 | "#, |
| 2597 | None, |
| 2598 | ) |
| 2599 | .unwrap(); |
| 2600 | let identity = config.active_provider_identity().unwrap(); |
| 2601 | let endpoint = config.base_url_for_route(&identity); |
| 2602 | let receipt = crate::route_receipt::TurnRouteReceipt::from_admitted( |
| 2603 | &identity, |
| 2604 | "gpt-5.5", |
| 2605 | &endpoint, |
| 2606 | "captured-key", |
| 2607 | ); |
| 2608 | let mut checks = ProviderReadinessSnapshot::default(); |
| 2609 | checks.record_success(&config, &receipt, "gpt-5.5"); |
| 2610 | let route = route_identity_for_model(&config, &identity, "gpt-5.5"); |
| 2611 | assert!(matches!( |
| 2612 | checks.last(&route), |
| 2613 | Some(LastProviderCheck::Passed) |
| 2614 | )); |
| 2615 | config |
| 2616 | .set_provider_api_key_override(&identity, Some("replacement-key".into())) |
| 2617 | .unwrap(); |
| 2618 | let replaced = route_identity_for_model(&config, &identity, "gpt-5.5"); |
| 2619 | assert_ne!(route.credential_generation, replaced.credential_generation); |
| 2620 | assert!(checks.last(&replaced).is_none()); |
| 2621 | checks.record_failure( |
| 2622 | &config, |
| 2623 | &receipt, |
| 2624 | "gpt-5.5", |
| 2625 | &ErrorEnvelope::new( |
| 2626 | ErrorCategory::Authentication, |
| 2627 | ErrorSeverity::Error, |
| 2628 | false, |
| 2629 | "auth_failed", |
| 2630 | "captured route failed", |
| 2631 | ), |
| 2632 | ); |
| 2633 | assert!( |
| 2634 | checks.last(&replaced).is_none(), |
| 2635 | "a late failure uses its dispatched key generation" |
| 2636 | ); |
| 2637 | assert!(matches!( |
| 2638 | checks.last(&route), |
| 2639 | Some(LastProviderCheck::Failed { .. }) |
| 2640 | )); |
| 2641 | } |
| 2642 | |
| 2643 | #[test] |
| 2644 | fn opaque_command_credentials_do_not_execute_or_inherit_cached_readiness() { |
| 2645 | let _env = crate::test_support::lock_test_env(); |
| 2646 | let _cli = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2647 | let mut config = codewhale_runtime::config::Config::from_saved_document( |
| 2648 | r#"provider = "openai" |
| 2649 | [providers.openai] |
| 2650 | api_key = "captured-key" |
| 2651 | model = "gpt-5.5" |
| 2652 | "#, |
| 2653 | None, |
| 2654 | ) |
| 2655 | .unwrap(); |
| 2656 | let identity = config.active_provider_identity().unwrap(); |
| 2657 | let endpoint = config.base_url_for_route(&identity); |
| 2658 | let receipt = crate::route_receipt::TurnRouteReceipt::from_admitted( |
| 2659 | &identity, |
| 2660 | "gpt-5.5", |
| 2661 | &endpoint, |
| 2662 | "captured-key", |
| 2663 | ); |
| 2664 | let mut checks = ProviderReadinessSnapshot::default(); |
| 2665 | checks.record_success(&config, &receipt, "gpt-5.5"); |
| 2666 | config.provider_config_for_mut(&identity).unwrap().auth = |
| 2667 | Some(codewhale_config::ProviderAuthSourceToml { |
| 2668 | source: codewhale_config::AuthSourceKind::Command, |
| 2669 | command: vec!["this-command-must-never-run".into()], |
| 2670 | timeout_ms: None, |
| 2671 | secret_id: None, |
| 2672 | }); |
| 2673 | assert!( |
| 2674 | config |
| 2675 | .readonly_health_credential_generation(&identity) |
| 2676 | .is_none() |
| 2677 | ); |
| 2678 | let opaque = route_identity_for_model(&config, &identity, "gpt-5.5"); |
| 2679 | assert!(checks.last(&opaque).is_none()); |
| 2680 | assert!(!format!("{opaque:?}").contains("captured-key")); |
| 2681 | assert!(!format!("{receipt:?}").contains("captured-key")); |
| 2682 | } |
| 2683 | |
| 2684 | #[test] |
| 2685 | fn bound_environment_rotation_and_keyless_endpoint_scope_are_exact() { |
| 2686 | let _env = crate::test_support::lock_test_env(); |
| 2687 | let _cli = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2688 | let config = codewhale_runtime::config::Config::from_saved_document( |
| 2689 | r#"provider = "CustomA" |
| 2690 | [providers.CustomA] |
| 2691 | kind = "openai-compatible" |
| 2692 | base_url = "http://127.0.0.1:18180/v1" |
| 2693 | model = "private-model" |
| 2694 | api_key_env = "CODEWHALE_HEALTH_FIXTURE_KEY" |
| 2695 | "#, |
| 2696 | None, |
| 2697 | ) |
| 2698 | .unwrap(); |
| 2699 | let identity = config.active_provider_identity().unwrap(); |
| 2700 | let first = |
| 2701 | crate::test_support::EnvVarGuard::set("CODEWHALE_HEALTH_FIXTURE_KEY", "first-key"); |
| 2702 | let generation = config |
| 2703 | .readonly_health_credential_generation(&identity) |
| 2704 | .unwrap(); |
| 2705 | drop(first); |
| 2706 | let _second = |
| 2707 | crate::test_support::EnvVarGuard::set("CODEWHALE_HEALTH_FIXTURE_KEY", "second-key"); |
| 2708 | assert_ne!( |
| 2709 | config |
| 2710 | .readonly_health_credential_generation(&identity) |
| 2711 | .unwrap(), |
| 2712 | generation |
| 2713 | ); |
| 2714 | let local = codewhale_runtime::config::Config::from_saved_document( |
| 2715 | r#"provider = "CustomA" |
| 2716 | [providers.CustomA] |
| 2717 | kind = "openai-compatible" |
| 2718 | base_url = "http://127.0.0.1:18180/v1" |
| 2719 | auth_mode = "none" |
| 2720 | "#, |
| 2721 | None, |
| 2722 | ) |
| 2723 | .unwrap(); |
| 2724 | let id = local.active_provider_identity().unwrap(); |
| 2725 | assert!(local.readonly_health_credential_generation(&id).is_some()); |
| 2726 | let mut changed = local.clone(); |
| 2727 | changed |
| 2728 | .set_provider_base_url_override(&id, Some("http://127.0.0.1:19191/v1".into())) |
| 2729 | .unwrap(); |
| 2730 | assert_ne!( |
| 2731 | local.readonly_health_credential_generation(&id), |
| 2732 | changed.readonly_health_credential_generation(&id) |
| 2733 | ); |
| 2734 | } |
| 2735 | |
| 2736 | #[test] |
| 2737 | fn last_for_provider_follows_chronological_checks_across_rotations_and_endpoints() { |
| 2738 | let _env = crate::test_support::lock_test_env(); |
| 2739 | let _cli = crate::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 2740 | let mut config = codewhale_runtime::config::Config::from_saved_document( |
| 2741 | r#"provider = "openai" |
| 2742 | [providers.openai] |
| 2743 | api_key = "key-1" |
| 2744 | base_url = "https://endpoint-a.example/v1" |
| 2745 | model = "gpt-5.5" |
| 2746 | "#, |
| 2747 | None, |
| 2748 | ) |
| 2749 | .unwrap(); |
| 2750 | let identity = config.active_provider_identity().unwrap(); |
| 2751 | let endpoint_a = config.base_url_for_route(&identity); |
| 2752 | let receipt_a = crate::route_receipt::TurnRouteReceipt::from_admitted( |
| 2753 | &identity, |
| 2754 | "gpt-5.5", |
| 2755 | &endpoint_a, |
| 2756 | "key-1", |
| 2757 | ); |
| 2758 | |
| 2759 | let mut checks = ProviderReadinessSnapshot::default(); |
| 2760 | checks.record_failure( |
| 2761 | &config, |
| 2762 | &receipt_a, |
| 2763 | "gpt-5.5", |
| 2764 | &ErrorEnvelope::new( |
| 2765 | ErrorCategory::Authentication, |
| 2766 | ErrorSeverity::Error, |
| 2767 | false, |
| 2768 | "auth_failed", |
| 2769 | "HTTP 401: bad key", |
| 2770 | ), |
| 2771 | ); |
| 2772 | assert_eq!( |
| 2773 | checks.last_for_provider(&identity), |
| 2774 | Some(&LastProviderCheck::Failed { |
| 2775 | category: ErrorCategory::Authentication, |
| 2776 | message: "HTTP 401: bad key".to_string(), |
| 2777 | }) |
| 2778 | ); |
| 2779 | |
| 2780 | config |
| 2781 | .set_provider_api_key_override(&identity, Some("key-2".into())) |
| 2782 | .unwrap(); |
| 2783 | let receipt_a_key2 = crate::route_receipt::TurnRouteReceipt::from_admitted( |
| 2784 | &identity, |
| 2785 | "gpt-5.5", |
| 2786 | &endpoint_a, |
| 2787 | "key-2", |
| 2788 | ); |
| 2789 | checks.record_failure( |
| 2790 | &config, |
| 2791 | &receipt_a_key2, |
| 2792 | "gpt-5.5", |
| 2793 | &ErrorEnvelope::new( |
| 2794 | ErrorCategory::RateLimit, |
| 2795 | ErrorSeverity::Error, |
| 2796 | true, |
| 2797 | "rate_limit", |
| 2798 | "HTTP 402: credits depleted", |
| 2799 | ), |
| 2800 | ); |
| 2801 | assert_eq!( |
| 2802 | checks.last_for_provider(&identity), |
| 2803 | Some(&LastProviderCheck::Failed { |
| 2804 | category: ErrorCategory::RateLimit, |
| 2805 | message: "HTTP 402: credits depleted".to_string(), |
| 2806 | }) |
| 2807 | ); |
| 2808 | |
| 2809 | let mut endpoint_checks = ProviderReadinessSnapshot::default(); |
| 2810 | endpoint_checks.record_failure( |
| 2811 | &config, |
| 2812 | &receipt_a_key2, |
| 2813 | "gpt-5.5", |
| 2814 | &ErrorEnvelope::new( |
| 2815 | ErrorCategory::Authentication, |
| 2816 | ErrorSeverity::Error, |
| 2817 | false, |
| 2818 | "auth_failed", |
| 2819 | "HTTP 401: wrong endpoint", |
| 2820 | ), |
| 2821 | ); |
| 2822 | config |
| 2823 | .set_provider_base_url_override(&identity, Some("https://endpoint-b.example/v1".into())) |
| 2824 | .unwrap(); |
| 2825 | let endpoint_b = config.base_url_for_route(&identity); |
| 2826 | let receipt_b = crate::route_receipt::TurnRouteReceipt::from_admitted( |
| 2827 | &identity, |
| 2828 | "gpt-5.5", |
| 2829 | &endpoint_b, |
| 2830 | "key-2", |
| 2831 | ); |
| 2832 | endpoint_checks.record_success(&config, &receipt_b, "gpt-5.5"); |
| 2833 | assert_eq!( |
| 2834 | endpoint_checks.last_for_provider(&identity), |
| 2835 | Some(&LastProviderCheck::Passed) |
| 2836 | ); |
| 2837 | } |
| 2838 | } |
| 2839 |