| 1 | use std::sync::Arc; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | use axum::Json; |
| 5 | use axum::extract::{Path, State}; |
| 6 | use codewhale_config::ConfigStore; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use serde_json::{Value, json}; |
| 9 | |
| 10 | use codewhale_config::ProviderKind; |
| 11 | |
| 12 | use super::{ApiError, ProviderCredentialState, RuntimeApiState}; |
| 13 | |
| 14 | /// Largest accepted credential payload. Provider keys are single-line |
| 15 | /// tokens; anything larger is a mistake, not a longer secret. |
| 16 | const MAX_KEY_BYTES: usize = 4 * 1024; |
| 17 | |
| 18 | /// Request body cap for the key route — the key plus JSON framing. |
| 19 | pub(super) const PROVIDER_KEY_BODY_LIMIT_BYTES: usize = MAX_KEY_BYTES + 3072; |
| 20 | |
| 21 | #[derive(Deserialize)] |
| 22 | #[serde(deny_unknown_fields)] |
| 23 | pub(super) struct SetProviderKeyRequest { |
| 24 | key: String, |
| 25 | #[serde(default)] |
| 26 | expected_base_url: Option<String>, |
| 27 | #[serde(default)] |
| 28 | scope: ProviderKeyScope, |
| 29 | } |
| 30 | |
| 31 | #[derive(Deserialize)] |
| 32 | #[serde(deny_unknown_fields)] |
| 33 | pub(super) struct CheckProviderKeyRequest { |
| 34 | key: String, |
| 35 | } |
| 36 | |
| 37 | #[derive(Clone, Copy, Default, Deserialize, PartialEq, Eq)] |
| 38 | #[serde(rename_all = "snake_case")] |
| 39 | enum ProviderKeyScope { |
| 40 | #[default] |
| 41 | Durable, |
| 42 | Session, |
| 43 | } |
| 44 | |
| 45 | pub(super) fn session_keys_required() -> Result<bool, ApiError> { |
| 46 | Ok(runtime_key_scope()? == ProviderKeyScope::Session) |
| 47 | } |
| 48 | |
| 49 | fn runtime_key_scope() -> Result<ProviderKeyScope, ApiError> { |
| 50 | match std::env::var("CODEWHALE_RUNTIME_KEY_SCOPE") { |
| 51 | Err(std::env::VarError::NotPresent) => Ok(ProviderKeyScope::Durable), |
| 52 | Ok(value) if value.is_empty() => Ok(ProviderKeyScope::Durable), |
| 53 | Ok(value) if value == "session" => Ok(ProviderKeyScope::Session), |
| 54 | _ => Err(ApiError::conflict( |
| 55 | "CODEWHALE_RUNTIME_KEY_SCOPE must be unset, empty, or 'session'", |
| 56 | )), |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Only the first-party account endpoint can receive an account device key. |
| 61 | /// This endpoint supplies a process-only reversible auth transform; it never |
| 62 | /// mutates a user's provider slot or durable config. Running turns retain their |
| 63 | /// materialized client: server-side device/session revocation is authoritative. |
| 64 | fn account_model_access_receipt(config: &codewhale_runtime::config::Config) -> Value { |
| 65 | let identity = config |
| 66 | .builtin_provider_identity(ProviderKind::Codewhale) |
| 67 | .ok(); |
| 68 | let api_base = identity |
| 69 | .as_ref() |
| 70 | .map(|identity| config.base_url_for_route(identity)) |
| 71 | .unwrap_or_default(); |
| 72 | let supported = api_base.trim_end_matches('/') |
| 73 | == codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL |
| 74 | && codewhale_engine::profile_constitution::runtime_account_api_base() |
| 75 | == codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE; |
| 76 | let access = config.account_model_access.read().clone(); |
| 77 | let live = access |
| 78 | .as_ref() |
| 79 | .filter(|a| a.expires_at > chrono::Utc::now().timestamp()); |
| 80 | json!({ |
| 81 | "apiBase": if supported { api_base.as_str() } else { "" }, |
| 82 | "supported": supported, |
| 83 | "configured": identity.as_ref().and_then(|identity| config.account_model_api_key(identity)).is_some(), |
| 84 | "catalogRefreshNeeded": false, |
| 85 | "sessionId": live.map(|a| a.session_id.as_str()), |
| 86 | "expiresAt": live.map(|a| a.expires_at), |
| 87 | }) |
| 88 | } |
| 89 | |
| 90 | #[derive(Deserialize)] |
| 91 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 92 | pub struct SetAccountModelAccessRequest { |
| 93 | pub api_base: String, |
| 94 | pub session_id: String, |
| 95 | pub expected_session_id: Option<String>, |
| 96 | pub key: String, |
| 97 | pub expires_at: i64, |
| 98 | } |
| 99 | |
| 100 | #[derive(Deserialize)] |
| 101 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 102 | pub(super) struct ClearAccountModelAccessRequest { |
| 103 | session_id: String, |
| 104 | } |
| 105 | |
| 106 | pub(super) async fn get_account_model_access( |
| 107 | State(state): State<RuntimeApiState>, |
| 108 | ) -> Result<Json<Value>, ApiError> { |
| 109 | tokio::task::spawn_blocking(move || { |
| 110 | Ok(Json(account_model_access_receipt(&state.config.read()))) |
| 111 | }) |
| 112 | .await |
| 113 | .map_err(|_| ApiError::internal("account access read failed"))? |
| 114 | } |
| 115 | |
| 116 | pub(super) async fn set_account_model_access( |
| 117 | State(state): State<RuntimeApiState>, |
| 118 | Json(request): Json<SetAccountModelAccessRequest>, |
| 119 | ) -> Result<Json<Value>, ApiError> { |
| 120 | tokio::task::spawn_blocking(move || { |
| 121 | let _credential_change = state.provider_switches.blocking_lock(); |
| 122 | let config = state.config.write(); |
| 123 | let refresh_needed = |
| 124 | install_account_model_access(&config, state.config_profile.as_deref(), request)?; |
| 125 | let mut receipt = account_model_access_receipt(&config); |
| 126 | receipt["catalogRefreshNeeded"] = json!(refresh_needed); |
| 127 | Ok(Json(receipt)) |
| 128 | }) |
| 129 | .await |
| 130 | .map_err(|_| ApiError::internal("account access update failed"))? |
| 131 | } |
| 132 | |
| 133 | pub fn install_account_model_access( |
| 134 | config: &codewhale_runtime::config::Config, |
| 135 | profile: Option<&str>, |
| 136 | request: SetAccountModelAccessRequest, |
| 137 | ) -> Result<bool, ApiError> { |
| 138 | let identity = config |
| 139 | .builtin_provider_identity(ProviderKind::Codewhale) |
| 140 | .map_err(ApiError::conflict)?; |
| 141 | let expected_base = codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL; |
| 142 | if request.api_base.trim_end_matches('/') != expected_base |
| 143 | || config.base_url_for_route(&identity).trim_end_matches('/') != expected_base |
| 144 | || codewhale_engine::profile_constitution::runtime_account_api_base() |
| 145 | != codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE |
| 146 | { |
| 147 | return Err(ApiError::conflict( |
| 148 | "Account model access requires the first-party Codewhale endpoint.", |
| 149 | )); |
| 150 | } |
| 151 | if !request.key.starts_with("cwc_") |
| 152 | || request.key.len() < 32 |
| 153 | || request.key.len() > MAX_KEY_BYTES |
| 154 | || request |
| 155 | .key |
| 156 | .chars() |
| 157 | .any(|c| c.is_control() || c.is_whitespace()) |
| 158 | { |
| 159 | return Err(ApiError::bad_request("Invalid account device credential.")); |
| 160 | } |
| 161 | let now = chrono::Utc::now(); |
| 162 | let secrets = codewhale_secrets::account::secure_account_session_secrets() |
| 163 | .map_err(|_| ApiError::internal("Account session storage is unavailable."))?; |
| 164 | let account = codewhale_secrets::account::AccountSessionStore::new( |
| 165 | secrets, |
| 166 | profile, |
| 167 | codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE, |
| 168 | ) |
| 169 | .runtime_info_at(now) |
| 170 | .map_err(|_| ApiError::conflict("Sign in again before connecting account models."))?; |
| 171 | let session_expiry = account |
| 172 | .expires_at |
| 173 | .as_deref() |
| 174 | .and_then(|date| chrono::DateTime::parse_from_rfc3339(date).ok()) |
| 175 | .map(|date| date.timestamp()); |
| 176 | if account.state != codewhale_secrets::account::AccountSessionState::Authenticated |
| 177 | || account.session_id.as_deref() != Some(request.session_id.as_str()) |
| 178 | || request.expires_at <= now.timestamp() |
| 179 | || session_expiry.is_none_or(|expiry| request.expires_at > expiry) |
| 180 | { |
| 181 | return Err(ApiError::conflict( |
| 182 | "Account session changed or expired; sign in again.", |
| 183 | )); |
| 184 | } |
| 185 | // Probe the existing resolver without the account layer. Scope to Codewhale |
| 186 | // so even an inactive unmarked durable slot is checked. Never replace it. |
| 187 | let mut existing = config.clone(); |
| 188 | existing.account_model_access = Default::default(); |
| 189 | existing |
| 190 | .scope_to_provider_identity(&identity) |
| 191 | .map_err(ApiError::conflict)?; |
| 192 | let stored_key_present = match codewhale_runtime::config::credential_secret_store() { |
| 193 | Some(secrets) => secrets |
| 194 | .get("codewhale") |
| 195 | .map_err(|_| { |
| 196 | ApiError::conflict("The existing Codewhale credential could not be checked.") |
| 197 | })? |
| 198 | .is_some(), |
| 199 | None => false, |
| 200 | }; |
| 201 | if stored_key_present |
| 202 | || existing |
| 203 | .provider_config_for(&identity) |
| 204 | .is_some_and(|entry| entry.auth.is_some() || entry.api_key_env.is_some()) |
| 205 | || !credential_writeability(&existing, &identity).writable |
| 206 | || !matches!( |
| 207 | codewhale_runtime::config::resolve_credential_source(&existing, &identity).source, |
| 208 | codewhale_runtime::credentials::CredentialSource::Missing { .. } |
| 209 | | codewhale_runtime::credentials::CredentialSource::AccountSession |
| 210 | ) |
| 211 | { |
| 212 | return Err(ApiError::conflict( |
| 213 | "This Codewhale route already has its own credential.", |
| 214 | )); |
| 215 | } |
| 216 | let mut access = config.account_model_access.write(); |
| 217 | let owner = access |
| 218 | .as_ref() |
| 219 | .filter(|a| a.expires_at > now.timestamp()) |
| 220 | .map(|a| a.session_id.as_str()); |
| 221 | if owner != request.expected_session_id.as_deref() { |
| 222 | return Err(ApiError::conflict( |
| 223 | "Account model access changed; refresh before retrying.", |
| 224 | )); |
| 225 | } |
| 226 | let changed = access.as_ref().is_none_or(|current| { |
| 227 | current.session_id != request.session_id |
| 228 | || current.profile.as_deref() != profile |
| 229 | || current.credential.expose_secret() != request.key |
| 230 | }); |
| 231 | if changed { |
| 232 | invalidate_account_catalog(config); |
| 233 | } |
| 234 | *access = Some(codewhale_runtime::config::AccountModelAccess { |
| 235 | session_id: request.session_id, |
| 236 | credential: codewhale_runtime::credentials::Credential::ApiKey { key: request.key }, |
| 237 | expires_at: request.expires_at, |
| 238 | profile: profile.map(str::to_string), |
| 239 | }); |
| 240 | Ok(changed) |
| 241 | } |
| 242 | |
| 243 | pub(super) async fn clear_account_model_access( |
| 244 | State(state): State<RuntimeApiState>, |
| 245 | Json(request): Json<ClearAccountModelAccessRequest>, |
| 246 | ) -> Result<Json<Value>, ApiError> { |
| 247 | tokio::task::spawn_blocking(move || { |
| 248 | let _credential_change = state.provider_switches.blocking_lock(); |
| 249 | let config = state.config.write(); |
| 250 | remove_account_model_access(&config, &request.session_id)?; |
| 251 | Ok(Json(account_model_access_receipt(&config))) |
| 252 | }) |
| 253 | .await |
| 254 | .map_err(|_| ApiError::internal("account access removal failed"))? |
| 255 | } |
| 256 | |
| 257 | fn remove_account_model_access( |
| 258 | config: &codewhale_runtime::config::Config, |
| 259 | session_id: &str, |
| 260 | ) -> Result<(), ApiError> { |
| 261 | let mut access = config.account_model_access.write(); |
| 262 | if access.as_ref().is_some_and(|a| a.session_id != session_id) { |
| 263 | return Err(ApiError::conflict( |
| 264 | "Account model access belongs to a different session.", |
| 265 | )); |
| 266 | } |
| 267 | if access.is_some() { |
| 268 | invalidate_account_catalog(config); |
| 269 | } |
| 270 | *access = None; |
| 271 | Ok(()) |
| 272 | } |
| 273 | |
| 274 | // Beginning a generation already invalidates this account-only memory roster |
| 275 | // and all older in-flight tickets. No network request or second cache is needed. |
| 276 | fn invalidate_account_catalog(config: &codewhale_runtime::config::Config) { |
| 277 | let Ok(identity) = config.builtin_provider_identity(ProviderKind::Codewhale) else { |
| 278 | return; |
| 279 | }; |
| 280 | codewhale_engine::provider_catalog_live::begin_refresh_for_identity( |
| 281 | ProviderKind::Codewhale, |
| 282 | "codewhale", |
| 283 | &config.base_url_for_route(&identity), |
| 284 | ); |
| 285 | } |
| 286 | |
| 287 | pub(super) fn invalidate_stale_account_catalog(config: &codewhale_runtime::config::Config) { |
| 288 | let identity = config |
| 289 | .builtin_provider_identity(ProviderKind::Codewhale) |
| 290 | .ok(); |
| 291 | let bound = config.account_model_access.read().is_some(); |
| 292 | if bound |
| 293 | && identity |
| 294 | .as_ref() |
| 295 | .and_then(|identity| config.account_model_api_key(identity)) |
| 296 | .is_none() |
| 297 | { |
| 298 | invalidate_account_catalog(config); |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | /// Write-only credential entry for native clients (APPS-48). |
| 303 | /// |
| 304 | /// `PUT /v1/providers/{id}/key` accepts a key with durable or session scope. |
| 305 | /// Durable writes use the transactional `codewhale auth set` path; session |
| 306 | /// writes update only the process memory overlay. Both return redacted metadata and |
| 307 | /// answers with the redacted receipt: which backend holds the secret and the |
| 308 | /// post-write `credential_state` readback. The key itself — and even its |
| 309 | /// length — never appears in the response, in errors, or in logs. |
| 310 | /// |
| 311 | /// There is deliberately no GET: a route that can return a secret can leak |
| 312 | /// one. Clients needing assurance re-read `credential_state` here or on |
| 313 | /// `GET /v1/providers`. |
| 314 | pub(super) async fn set_provider_key( |
| 315 | State(state): State<RuntimeApiState>, |
| 316 | Path(id): Path<String>, |
| 317 | Json(request): Json<SetProviderKeyRequest>, |
| 318 | ) -> Result<Json<Value>, ApiError> { |
| 319 | #[cfg(any(test, feature = "test-support"))] |
| 320 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 321 | tokio::task::spawn_blocking(move || { |
| 322 | #[cfg(any(test, feature = "test-support"))] |
| 323 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 324 | let _credential_change = state.provider_switches.blocking_lock(); |
| 325 | if state.config.read().session_provider_keys_only |
| 326 | && request.scope != ProviderKeyScope::Session |
| 327 | { |
| 328 | return Err(ApiError::conflict("This Engine accepts session-only keys")); |
| 329 | } |
| 330 | if request.expected_base_url.as_ref().is_some_and(|url| request.scope != ProviderKeyScope::Session || url.len() > 2048) { |
| 331 | return Err(ApiError::bad_request("Endpoint-bound credentials require session scope and a bounded endpoint.")); |
| 332 | } |
| 333 | // Both scopes validate the exact provider and credential authority; |
| 334 | // only session writes may replace an existing eligible memory overlay. |
| 335 | let identity = writable_provider(&state.config.read(), &id, request.scope)?; |
| 336 | let kind = identity.provider; |
| 337 | if kind == codewhale_config::ProviderKind::OpenaiCodex { |
| 338 | return Err(ApiError::bad_request( |
| 339 | codewhale_config::credentials::OPENAI_CODEX_API_KEY_REFUSAL, |
| 340 | )); |
| 341 | } |
| 342 | |
| 343 | let key = codewhale_secrets::normalize_api_key(&request.key); |
| 344 | if key.is_empty() { |
| 345 | return Err(ApiError::bad_request("key must not be empty")); |
| 346 | } |
| 347 | if key.len() > MAX_KEY_BYTES || key.chars().any(char::is_control) { |
| 348 | return Err(ApiError::bad_request( |
| 349 | "key must be a single-line credential at most 4 KiB", |
| 350 | )); |
| 351 | } |
| 352 | |
| 353 | if matches!(kind, ProviderKind::Orcarouter | ProviderKind::Anthropic) |
| 354 | && let Some(attempt) = state |
| 355 | .provider_connect |
| 356 | .0 |
| 357 | .lock() |
| 358 | .as_ref() |
| 359 | .filter(|attempt| attempt.provider == kind) |
| 360 | { |
| 361 | attempt.cancel(); |
| 362 | } |
| 363 | let provider_owned = identity.clone(); |
| 364 | let (backend, saved_config_path) = if request.scope == ProviderKeyScope::Session { |
| 365 | ("memory".to_string(), None) |
| 366 | } else { |
| 367 | let secrets = codewhale_runtime::config::credential_secret_store().ok_or_else(|| { |
| 368 | ApiError::internal("no credential store is available in this environment") |
| 369 | })?; |
| 370 | let store_path = state.config_path.clone(); |
| 371 | let kind_owned = kind; |
| 372 | let key_owned = key.to_string(); |
| 373 | let (backend, saved_config_path) = { |
| 374 | let mut store = ConfigStore::load(store_path).map_err(|error| { |
| 375 | ApiError::internal(format!("config store unavailable: {error}")) |
| 376 | })?; |
| 377 | let mut credential_store = |
| 378 | codewhale_config::credentials::credential_metadata_store(&store).map_err( |
| 379 | |error| ApiError::internal(format!("credential store: {error}")), |
| 380 | )?; |
| 381 | let target = credential_store.as_mut().unwrap_or(&mut store); |
| 382 | let slot = codewhale_config::credentials::provider_slot(kind_owned); |
| 383 | codewhale_runtime::credentials::store::with_provider_write_lock(slot, || { |
| 384 | codewhale_config::credentials::set_provider_api_key( |
| 385 | target, &secrets, kind_owned, &key_owned, |
| 386 | ) |
| 387 | }) |
| 388 | .map_err(|error| { |
| 389 | // The credential-write errors name paths and backends only — the |
| 390 | // key material is never embedded in the message. |
| 391 | ApiError::internal(format!("credential write failed: {error}")) |
| 392 | })?; |
| 393 | Ok::<_, ApiError>(( |
| 394 | secrets.backend_name().to_string(), |
| 395 | target.path().to_path_buf(), |
| 396 | )) |
| 397 | }?; |
| 398 | (backend, Some(saved_config_path)) |
| 399 | }; |
| 400 | |
| 401 | { |
| 402 | let mut config = state.config.write(); |
| 403 | config |
| 404 | .verify_provider_identity(&provider_owned) |
| 405 | .map_err(ApiError::conflict)?; |
| 406 | if request.scope == ProviderKeyScope::Session { |
| 407 | writable_provider(&config, &id, request.scope)?; |
| 408 | let endpoint = config.base_url_for_route(&provider_owned); |
| 409 | if request.expected_base_url.as_ref().is_some_and(|expected| expected.trim_end_matches('/') != endpoint.trim_end_matches('/')) { |
| 410 | return Err(ApiError::conflict("The configured model endpoint differs from this computer. No credential was installed.")); |
| 411 | } |
| 412 | config.session_provider_keys.write().insert( |
| 413 | provider_owned.clone(), |
| 414 | (endpoint, codewhale_runtime::credentials::Credential::ApiKey { key }), |
| 415 | ); |
| 416 | } else { |
| 417 | mirror_saved_key_markers(&mut config, &provider_owned)?; |
| 418 | config.session_provider_keys.write().remove(&provider_owned); |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | let credential_state: ProviderCredentialState = |
| 423 | codewhale_engine::provider_readiness::credential_state_for_provider( |
| 424 | &state.config.read(), |
| 425 | &provider_owned, |
| 426 | ) |
| 427 | .into(); |
| 428 | |
| 429 | let mut receipt = json!({ |
| 430 | "provider": provider_owned.key, |
| 431 | "stored": request.scope == ProviderKeyScope::Durable, |
| 432 | "backend": backend, |
| 433 | "credentialState": credential_state, |
| 434 | }); |
| 435 | if let Some(path) = saved_config_path { |
| 436 | receipt["configPath"] = json!(path); |
| 437 | } else { |
| 438 | receipt["scope"] = json!("session"); |
| 439 | } |
| 440 | Ok(Json(receipt)) |
| 441 | }) |
| 442 | .await |
| 443 | .map_err(|_| ApiError::internal("credential write task failed"))? |
| 444 | } |
| 445 | |
| 446 | fn mirror_saved_key_markers( |
| 447 | config: &mut codewhale_runtime::config::Config, |
| 448 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 449 | ) -> Result<(), ApiError> { |
| 450 | // Match the shared writer: the root marker belongs only to the |
| 451 | // active provider, while an inactive provider keeps its own marker. |
| 452 | config |
| 453 | .verify_provider_identity(identity) |
| 454 | .map_err(ApiError::conflict)?; |
| 455 | if config.active_provider_identity().as_ref().ok() == Some(identity) { |
| 456 | config.auth_mode = Some("api_key".to_string()); |
| 457 | } |
| 458 | let entry = config |
| 459 | .provider_config_for_mut(identity) |
| 460 | .map_err(|error| ApiError::conflict(error.to_string()))?; |
| 461 | entry.auth_mode = Some("api_key".to_string()); |
| 462 | entry.external_credentials = None; |
| 463 | entry.api_key = None; |
| 464 | if identity.provider == ProviderKind::Xai { |
| 465 | entry.oauth_credential_generation = None; |
| 466 | } |
| 467 | // No model is mirrored: saving a key never changes which model runs |
| 468 | // (see `prepare_provider_api_key_metadata`). |
| 469 | Ok(()) |
| 470 | } |
| 471 | |
| 472 | #[derive(Clone, Default)] |
| 473 | pub(super) struct ProviderConnect( |
| 474 | Arc<parking_lot::Mutex<Option<ConnectAttempt>>>, |
| 475 | Arc<ClaudeOrgAvailability>, |
| 476 | ); |
| 477 | |
| 478 | #[derive(Default)] |
| 479 | pub(super) struct ClaudeOrgAvailability { |
| 480 | cached: parking_lot::Mutex<Option<(bool, Instant)>>, |
| 481 | refreshing: std::sync::atomic::AtomicBool, |
| 482 | } |
| 483 | |
| 484 | const CLAUDE_ORG_AVAILABILITY_TTL: Duration = Duration::from_secs(600); |
| 485 | |
| 486 | impl ProviderConnect { |
| 487 | pub(super) fn claude_org_available(&self) -> bool { |
| 488 | self.1.cached.lock().is_some_and(|(available, _)| available) |
| 489 | } |
| 490 | |
| 491 | fn record_claude_org_availability(&self, available: Option<bool>) { |
| 492 | *self.1.cached.lock() = available.map(|available| (available, Instant::now())); |
| 493 | } |
| 494 | |
| 495 | pub(super) fn forget_claude_org_availability(&self) { |
| 496 | self.record_claude_org_availability(None); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | struct AvailabilityRefresh(Arc<ClaudeOrgAvailability>); |
| 501 | |
| 502 | impl Drop for AvailabilityRefresh { |
| 503 | fn drop(&mut self) { |
| 504 | self.0 |
| 505 | .refreshing |
| 506 | .store(false, std::sync::atomic::Ordering::Release); |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | pub(super) fn refresh_claude_org_availability_if_stale(state: &RuntimeApiState) { |
| 511 | let availability = &state.provider_connect.1; |
| 512 | let fresh = availability |
| 513 | .cached |
| 514 | .lock() |
| 515 | .is_some_and(|(_, at)| at.elapsed() < CLAUDE_ORG_AVAILABILITY_TTL); |
| 516 | if fresh |
| 517 | || availability |
| 518 | .refreshing |
| 519 | .swap(true, std::sync::atomic::Ordering::AcqRel) |
| 520 | { |
| 521 | return; |
| 522 | } |
| 523 | #[cfg(any(test, feature = "test-support"))] |
| 524 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 525 | let state = state.clone(); |
| 526 | let refresh = AvailabilityRefresh(Arc::clone(availability)); |
| 527 | drop(tokio::task::spawn_blocking(move || { |
| 528 | let _refresh = refresh; |
| 529 | #[cfg(any(test, feature = "test-support"))] |
| 530 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 531 | let observed = super::account::client(&state) |
| 532 | .ok() |
| 533 | .map(|client| client.claude_org_link_status()); |
| 534 | let connect = &state.provider_connect; |
| 535 | match observed { |
| 536 | Some(Ok(link)) => connect.record_claude_org_availability(Some(link.available)), |
| 537 | None => connect.record_claude_org_availability(Some(false)), |
| 538 | Some(Err(error)) |
| 539 | if matches!( |
| 540 | error.kind, |
| 541 | codewhale_account_cli::ClaudeOrgErrorKind::Disabled |
| 542 | | codewhale_account_cli::ClaudeOrgErrorKind::NotSignedIn |
| 543 | ) => |
| 544 | { |
| 545 | connect.record_claude_org_availability(Some(false)); |
| 546 | } |
| 547 | Some(Err(_)) => { |
| 548 | let previous = connect.claude_org_available(); |
| 549 | connect.record_claude_org_availability(Some(previous)); |
| 550 | } |
| 551 | } |
| 552 | })); |
| 553 | } |
| 554 | |
| 555 | struct ConnectAttempt { |
| 556 | id: String, |
| 557 | provider: ProviderKind, |
| 558 | status: Arc<parking_lot::Mutex<ConnectStatus>>, |
| 559 | } |
| 560 | |
| 561 | const CLAUDE_ORG_CONNECT_TIMEOUT: Duration = Duration::from_secs(600); |
| 562 | const CLAUDE_ORG_POLL_INTERVAL: Duration = Duration::from_secs(3); |
| 563 | const CLAUDE_ORG_POLL_SLICE: Duration = Duration::from_millis(250); |
| 564 | |
| 565 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 566 | enum ConnectStatus { |
| 567 | Waiting, |
| 568 | Exchanging, |
| 569 | Connected, |
| 570 | Declined, |
| 571 | Expired, |
| 572 | Cancelled, |
| 573 | Failed(&'static str), |
| 574 | } |
| 575 | |
| 576 | impl ConnectStatus { |
| 577 | fn parts(self) -> (&'static str, Option<&'static str>) { |
| 578 | match self { |
| 579 | Self::Waiting | Self::Exchanging => ("waiting", None), |
| 580 | Self::Connected => ("connected", None), |
| 581 | Self::Declined => ("declined", None), |
| 582 | Self::Expired => ("expired", None), |
| 583 | Self::Cancelled => ("cancelled", None), |
| 584 | Self::Failed(reason) => ("failed", Some(reason)), |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | impl ConnectAttempt { |
| 590 | fn cancel(&self) -> ConnectStatus { |
| 591 | let mut status = self.status.lock(); |
| 592 | if matches!(*status, ConnectStatus::Waiting | ConnectStatus::Exchanging) { |
| 593 | *status = ConnectStatus::Cancelled; |
| 594 | } |
| 595 | *status |
| 596 | } |
| 597 | |
| 598 | fn receipt(&self, status: ConnectStatus) -> Value { |
| 599 | let (label, reason) = status.parts(); |
| 600 | let mut receipt = json!({ "attemptId": self.id, "status": label }); |
| 601 | if let Some(reason) = reason { |
| 602 | receipt["reason"] = json!(reason); |
| 603 | } |
| 604 | receipt |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | fn connect_provider_kind(id: &str) -> Result<ProviderKind, ApiError> { |
| 609 | let row = codewhale_config::descriptors::compatibility_for_selector(id) |
| 610 | .ok_or_else(|| ApiError::bad_request(format!("Unknown provider id '{id}'")))?; |
| 611 | if row.id != row.kind.as_str() |
| 612 | || !matches!(row.kind, ProviderKind::Orcarouter | ProviderKind::Anthropic) |
| 613 | { |
| 614 | return Err(ApiError::bad_request( |
| 615 | "Browser connect is available only for 'orcarouter' and 'anthropic'.", |
| 616 | )); |
| 617 | } |
| 618 | Ok(row.kind) |
| 619 | } |
| 620 | |
| 621 | fn register_connect_attempt( |
| 622 | state: &RuntimeApiState, |
| 623 | provider: ProviderKind, |
| 624 | id: String, |
| 625 | status: Arc<parking_lot::Mutex<ConnectStatus>>, |
| 626 | ) { |
| 627 | let mut current = state.provider_connect.0.lock(); |
| 628 | if let Some(previous) = current.take() { |
| 629 | previous.cancel(); |
| 630 | } |
| 631 | *current = Some(ConnectAttempt { |
| 632 | id, |
| 633 | provider, |
| 634 | status, |
| 635 | }); |
| 636 | } |
| 637 | |
| 638 | fn finish_connect_attempt( |
| 639 | state: &RuntimeApiState, |
| 640 | status: &parking_lot::Mutex<ConnectStatus>, |
| 641 | finished: ConnectStatus, |
| 642 | provider: &'static str, |
| 643 | ) { |
| 644 | let _credential_change = state.provider_switches.blocking_lock(); |
| 645 | let finished = { |
| 646 | let mut current = status.lock(); |
| 647 | if matches!(*current, ConnectStatus::Waiting | ConnectStatus::Exchanging) { |
| 648 | *current = finished; |
| 649 | } |
| 650 | *current |
| 651 | }; |
| 652 | let (status, reason) = finished.parts(); |
| 653 | tracing::info!( |
| 654 | target: "codewhale::oauth", |
| 655 | provider, |
| 656 | status, |
| 657 | reason = reason.unwrap_or(""), |
| 658 | "provider connect attempt finished" |
| 659 | ); |
| 660 | } |
| 661 | |
| 662 | fn is_current_connect_attempt( |
| 663 | state: &RuntimeApiState, |
| 664 | status: &parking_lot::Mutex<ConnectStatus>, |
| 665 | ) -> bool { |
| 666 | state |
| 667 | .provider_connect |
| 668 | .0 |
| 669 | .lock() |
| 670 | .as_ref() |
| 671 | .is_some_and(|attempt| std::ptr::eq(attempt.status.as_ref(), status)) |
| 672 | } |
| 673 | |
| 674 | fn claude_org_reason(kind: codewhale_account_cli::ClaudeOrgErrorKind) -> &'static str { |
| 675 | use codewhale_account_cli::ClaudeOrgErrorKind; |
| 676 | match kind { |
| 677 | ClaudeOrgErrorKind::NotSignedIn => "not_signed_in", |
| 678 | ClaudeOrgErrorKind::Disabled => "claude_billing_disabled", |
| 679 | ClaudeOrgErrorKind::AlreadyLinkedElsewhere => "already_linked_elsewhere", |
| 680 | ClaudeOrgErrorKind::Unavailable => "unavailable", |
| 681 | ClaudeOrgErrorKind::NotLinked |
| 682 | | ClaudeOrgErrorKind::RelinkRequired |
| 683 | | ClaudeOrgErrorKind::Invalid => "invalid_response", |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | fn claude_org_start_error(error: codewhale_account_cli::ClaudeOrgError) -> ApiError { |
| 688 | let reason = claude_org_reason(error.kind); |
| 689 | let message = error.to_string(); |
| 690 | if reason == "unavailable" { |
| 691 | ApiError::bad_gateway(message).with_code(reason) |
| 692 | } else { |
| 693 | ApiError::conflict(message).with_code(reason) |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | fn claude_org_connect_target( |
| 698 | state: &RuntimeApiState, |
| 699 | id: &str, |
| 700 | ) -> Result<codewhale_runtime::config::ProviderIdentity, ApiError> { |
| 701 | let config = state.config.read(); |
| 702 | if config.session_provider_keys_only { |
| 703 | return Err(ApiError::conflict( |
| 704 | "Browser sign-in is unavailable on an Engine that requires session-only keys", |
| 705 | )); |
| 706 | } |
| 707 | let identity = writable_provider(&config, id, ProviderKeyScope::Durable)?; |
| 708 | if config.provider_uses_custom_endpoint(&identity) { |
| 709 | return Err(ApiError::conflict( |
| 710 | "Claude organization billing works only on the official Anthropic endpoint.", |
| 711 | ) |
| 712 | .with_code("custom_endpoint")); |
| 713 | } |
| 714 | Ok(identity) |
| 715 | } |
| 716 | |
| 717 | async fn start_claude_org_connect( |
| 718 | state: &RuntimeApiState, |
| 719 | id: &str, |
| 720 | ) -> Result<Json<Value>, ApiError> { |
| 721 | let identity = claude_org_connect_target(state, id)?; |
| 722 | #[cfg(any(test, feature = "test-support"))] |
| 723 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 724 | let account_state = state.clone(); |
| 725 | let started_at = chrono::Utc::now(); |
| 726 | let started = tokio::task::spawn_blocking(move || { |
| 727 | #[cfg(any(test, feature = "test-support"))] |
| 728 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 729 | let client = super::account::client(&account_state).map_err(|error| { |
| 730 | codewhale_account_cli::ClaudeOrgError::with_message( |
| 731 | codewhale_account_cli::ClaudeOrgErrorKind::Unavailable, |
| 732 | error.message, |
| 733 | ) |
| 734 | })?; |
| 735 | let status = client.claude_org_link_status()?; |
| 736 | if !status.available { |
| 737 | return Err(codewhale_account_cli::ClaudeOrgError::new( |
| 738 | codewhale_account_cli::ClaudeOrgErrorKind::Disabled, |
| 739 | )); |
| 740 | } |
| 741 | if status.linked { |
| 742 | return Ok(None); |
| 743 | } |
| 744 | client.claude_org_start_link().map(Some) |
| 745 | }) |
| 746 | .await |
| 747 | .map_err(|_| ApiError::internal("Claude organization connect could not start."))?; |
| 748 | let authorize_url = match started { |
| 749 | Ok(url) => { |
| 750 | state |
| 751 | .provider_connect |
| 752 | .record_claude_org_availability(Some(true)); |
| 753 | url |
| 754 | } |
| 755 | Err(error) => { |
| 756 | if error.kind == codewhale_account_cli::ClaudeOrgErrorKind::Disabled { |
| 757 | state |
| 758 | .provider_connect |
| 759 | .record_claude_org_availability(Some(false)); |
| 760 | } |
| 761 | return Err(claude_org_start_error(error)); |
| 762 | } |
| 763 | }; |
| 764 | let _credential_change = state.provider_switches.lock().await; |
| 765 | if claude_org_connect_target(state, id)? != identity { |
| 766 | return Err(ApiError::conflict( |
| 767 | "The Anthropic route changed while Claude organization connect was starting.", |
| 768 | )); |
| 769 | } |
| 770 | |
| 771 | let attempt_id = uuid::Uuid::new_v4().simple().to_string(); |
| 772 | let status = Arc::new(parking_lot::Mutex::new(ConnectStatus::Waiting)); |
| 773 | let deadline = Instant::now() + CLAUDE_ORG_CONNECT_TIMEOUT; |
| 774 | let worker_state = state.clone(); |
| 775 | let worker_status = status.clone(); |
| 776 | std::thread::Builder::new() |
| 777 | .name("claude-org-connect".to_string()) |
| 778 | .spawn(move || { |
| 779 | #[cfg(any(test, feature = "test-support"))] |
| 780 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 781 | let sleep = |duration| std::thread::sleep(duration); |
| 782 | let finished = run_claude_org_connect( |
| 783 | &worker_state, |
| 784 | &identity, |
| 785 | started_at, |
| 786 | deadline, |
| 787 | &worker_status, |
| 788 | &sleep, |
| 789 | ); |
| 790 | finish_connect_attempt(&worker_state, &worker_status, finished, "anthropic"); |
| 791 | }) |
| 792 | .map_err(|_| ApiError::internal("Claude organization connect could not start."))?; |
| 793 | register_connect_attempt(state, ProviderKind::Anthropic, attempt_id.clone(), status); |
| 794 | Ok(Json(json!({ |
| 795 | "attemptId": attempt_id, |
| 796 | "authorizeUrl": authorize_url, |
| 797 | "expiresIn": CLAUDE_ORG_CONNECT_TIMEOUT.as_secs(), |
| 798 | }))) |
| 799 | } |
| 800 | |
| 801 | fn run_claude_org_connect( |
| 802 | state: &RuntimeApiState, |
| 803 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 804 | started_at: chrono::DateTime<chrono::Utc>, |
| 805 | deadline: Instant, |
| 806 | status: &parking_lot::Mutex<ConnectStatus>, |
| 807 | sleep: &dyn Fn(Duration), |
| 808 | ) -> ConnectStatus { |
| 809 | let cancelled = || *status.lock() == ConnectStatus::Cancelled; |
| 810 | let Ok(client) = super::account::client(state) else { |
| 811 | return ConnectStatus::Failed("unavailable"); |
| 812 | }; |
| 813 | let mut tolerated_error = false; |
| 814 | loop { |
| 815 | if cancelled() { |
| 816 | return ConnectStatus::Cancelled; |
| 817 | } |
| 818 | match client.claude_org_link_status() { |
| 819 | Ok(link) if !link.available => { |
| 820 | state |
| 821 | .provider_connect |
| 822 | .record_claude_org_availability(Some(false)); |
| 823 | return ConnectStatus::Failed("claude_billing_disabled"); |
| 824 | } |
| 825 | Ok(link) if link.linked => { |
| 826 | state |
| 827 | .provider_connect |
| 828 | .record_claude_org_availability(Some(true)); |
| 829 | break; |
| 830 | } |
| 831 | Ok(link) if link.failure_since(started_at).is_some() => { |
| 832 | return match link.failure_since(started_at) { |
| 833 | Some(codewhale_account_cli::ClaudeOrgLinkFailure::Declined) => { |
| 834 | ConnectStatus::Declined |
| 835 | } |
| 836 | Some(codewhale_account_cli::ClaudeOrgLinkFailure::AlreadyLinkedElsewhere) => { |
| 837 | ConnectStatus::Failed("already_linked_elsewhere") |
| 838 | } |
| 839 | _ => ConnectStatus::Failed("link_failed"), |
| 840 | }; |
| 841 | } |
| 842 | Ok(_) => tolerated_error = false, |
| 843 | Err(error) |
| 844 | if !tolerated_error |
| 845 | && error.kind == codewhale_account_cli::ClaudeOrgErrorKind::Unavailable => |
| 846 | { |
| 847 | tolerated_error = true; |
| 848 | } |
| 849 | Err(error) => { |
| 850 | if error.kind == codewhale_account_cli::ClaudeOrgErrorKind::Disabled { |
| 851 | state |
| 852 | .provider_connect |
| 853 | .record_claude_org_availability(Some(false)); |
| 854 | } |
| 855 | return ConnectStatus::Failed(claude_org_reason(error.kind)); |
| 856 | } |
| 857 | } |
| 858 | if Instant::now() >= deadline { |
| 859 | return ConnectStatus::Expired; |
| 860 | } |
| 861 | let mut waited = Duration::ZERO; |
| 862 | while waited < CLAUDE_ORG_POLL_INTERVAL && !cancelled() { |
| 863 | sleep(CLAUDE_ORG_POLL_SLICE); |
| 864 | waited += CLAUDE_ORG_POLL_SLICE; |
| 865 | } |
| 866 | } |
| 867 | if !credential_writeability(&state.config.read(), identity).writable { |
| 868 | return ConnectStatus::Failed("not_writable"); |
| 869 | } |
| 870 | { |
| 871 | let mut current = status.lock(); |
| 872 | if *current == ConnectStatus::Cancelled { |
| 873 | return ConnectStatus::Cancelled; |
| 874 | } |
| 875 | *current = ConnectStatus::Exchanging; |
| 876 | } |
| 877 | let _credential_change = state.provider_switches.blocking_lock(); |
| 878 | if !is_current_connect_attempt(state, status) || *status.lock() != ConnectStatus::Exchanging { |
| 879 | return ConnectStatus::Cancelled; |
| 880 | } |
| 881 | { |
| 882 | let config = state.config.read(); |
| 883 | if config.session_provider_keys_only |
| 884 | || config.verify_provider_identity(identity).is_err() |
| 885 | || !credential_writeability(&config, identity).writable |
| 886 | { |
| 887 | return ConnectStatus::Failed("not_writable"); |
| 888 | } |
| 889 | if config.provider_uses_custom_endpoint(identity) { |
| 890 | return ConnectStatus::Failed("custom_endpoint"); |
| 891 | } |
| 892 | } |
| 893 | let Some(table) = identity.compatibility().map(|row| row.base_url_config_key) else { |
| 894 | return ConnectStatus::Failed("config_not_saved"); |
| 895 | }; |
| 896 | let saved = provider_settings_path(state.config_path.clone()).and_then(|path| { |
| 897 | codewhale_runtime::config_persistence::mutate_config_document(&path, |doc| { |
| 898 | codewhale_runtime::config_persistence::set_document_value( |
| 899 | doc, |
| 900 | &["providers", table, "auth_mode"], |
| 901 | codewhale_config::credentials::CLAUDE_ORG_AUTH_MODE, |
| 902 | ) |
| 903 | }) |
| 904 | }); |
| 905 | if saved.is_err() { |
| 906 | return ConnectStatus::Failed("config_not_saved"); |
| 907 | } |
| 908 | let mut config = state.config.write(); |
| 909 | match config.provider_config_for_mut(identity) { |
| 910 | Ok(entry) => { |
| 911 | entry.auth_mode = Some(codewhale_config::credentials::CLAUDE_ORG_AUTH_MODE.to_string()); |
| 912 | } |
| 913 | Err(_) => return ConnectStatus::Failed("config_not_saved"), |
| 914 | } |
| 915 | drop(config); |
| 916 | *status.lock() = ConnectStatus::Connected; |
| 917 | ConnectStatus::Connected |
| 918 | } |
| 919 | |
| 920 | fn provider_settings_path( |
| 921 | config_path: Option<std::path::PathBuf>, |
| 922 | ) -> anyhow::Result<std::path::PathBuf> { |
| 923 | let store = ConfigStore::load(config_path)?; |
| 924 | Ok( |
| 925 | match codewhale_config::credentials::credential_metadata_store(&store)? { |
| 926 | Some(global) => global.path().to_path_buf(), |
| 927 | None => store.path().to_path_buf(), |
| 928 | }, |
| 929 | ) |
| 930 | } |
| 931 | |
| 932 | pub(super) async fn start_provider_connect( |
| 933 | State(state): State<RuntimeApiState>, |
| 934 | Path(id): Path<String>, |
| 935 | ) -> Result<Json<Value>, ApiError> { |
| 936 | let kind = connect_provider_kind(&id)?; |
| 937 | if kind == ProviderKind::Anthropic { |
| 938 | return start_claude_org_connect(&state, &id).await; |
| 939 | } |
| 940 | let _credential_change = state.provider_switches.lock().await; |
| 941 | if state.config.read().session_provider_keys_only { |
| 942 | return Err(ApiError::conflict( |
| 943 | "Browser sign-in is unavailable on an Engine that requires session-only keys", |
| 944 | )); |
| 945 | } |
| 946 | let identity = writable_provider(&state.config.read(), &id, ProviderKeyScope::Durable)?; |
| 947 | let endpoint = state.config.read().base_url_for_route(&identity); |
| 948 | let target = (identity, endpoint); |
| 949 | let (listeners, request, auth_base) = tokio::task::spawn_blocking(|| { |
| 950 | let inputs = codewhale_runtime::oauth::OrcaLoginInputs::from_env(); |
| 951 | let listeners = codewhale_runtime::oauth::bind_orcarouter_callback()?; |
| 952 | let request = codewhale_runtime::oauth::start_orcarouter_auth_request(&listeners, &inputs)?; |
| 953 | Ok::<_, anyhow::Error>((listeners, request, inputs.auth_base)) |
| 954 | }) |
| 955 | .await |
| 956 | .map_err(|_| ApiError::internal("OrcaRouter connect could not start."))? |
| 957 | .map_err(|_| ApiError::internal("OrcaRouter connect could not open its local callback."))?; |
| 958 | |
| 959 | let attempt_id = uuid::Uuid::new_v4().simple().to_string(); |
| 960 | let status = Arc::new(parking_lot::Mutex::new(ConnectStatus::Waiting)); |
| 961 | let authorize_url = request.authorize_url.clone(); |
| 962 | let deadline = Instant::now() + codewhale_runtime::oauth::CALLBACK_TIMEOUT; |
| 963 | let worker_state = state.clone(); |
| 964 | let worker_status = status.clone(); |
| 965 | std::thread::Builder::new() |
| 966 | .name("orcarouter-connect".to_string()) |
| 967 | .spawn(move || { |
| 968 | let finished = run_provider_connect( |
| 969 | &worker_state, |
| 970 | &target, |
| 971 | listeners, |
| 972 | request, |
| 973 | &auth_base, |
| 974 | deadline, |
| 975 | &worker_status, |
| 976 | ); |
| 977 | finish_connect_attempt(&worker_state, &worker_status, finished, "orcarouter"); |
| 978 | }) |
| 979 | .map_err(|_| ApiError::internal("OrcaRouter connect could not start."))?; |
| 980 | |
| 981 | register_connect_attempt(&state, ProviderKind::Orcarouter, attempt_id.clone(), status); |
| 982 | Ok(Json(json!({ |
| 983 | "attemptId": attempt_id, |
| 984 | "authorizeUrl": authorize_url, |
| 985 | "expiresIn": codewhale_runtime::oauth::CALLBACK_TIMEOUT.as_secs(), |
| 986 | }))) |
| 987 | } |
| 988 | |
| 989 | fn run_provider_connect( |
| 990 | state: &RuntimeApiState, |
| 991 | target: &(codewhale_runtime::config::ProviderIdentity, String), |
| 992 | listeners: Vec<std::net::TcpListener>, |
| 993 | request: codewhale_runtime::oauth::BrowserAuthRequest, |
| 994 | auth_base: &str, |
| 995 | deadline: Instant, |
| 996 | status: &parking_lot::Mutex<ConnectStatus>, |
| 997 | ) -> ConnectStatus { |
| 998 | let (identity, endpoint) = target; |
| 999 | let cancelled = || *status.lock() == ConnectStatus::Cancelled; |
| 1000 | let callback = codewhale_runtime::oauth::wait_for_orcarouter_callback( |
| 1001 | &listeners, |
| 1002 | &request.state, |
| 1003 | deadline, |
| 1004 | &cancelled, |
| 1005 | ); |
| 1006 | drop(listeners); |
| 1007 | let code = match callback { |
| 1008 | Ok(codewhale_runtime::oauth::OrcaCallback::Code(code)) => code, |
| 1009 | Ok(codewhale_runtime::oauth::OrcaCallback::Declined) => return ConnectStatus::Declined, |
| 1010 | Ok(codewhale_runtime::oauth::OrcaCallback::Refused) => { |
| 1011 | return ConnectStatus::Failed("authorization_error"); |
| 1012 | } |
| 1013 | Ok(codewhale_runtime::oauth::OrcaCallback::Stopped) if cancelled() => { |
| 1014 | return ConnectStatus::Cancelled; |
| 1015 | } |
| 1016 | Ok(codewhale_runtime::oauth::OrcaCallback::Stopped) => return ConnectStatus::Expired, |
| 1017 | Err(_) => return ConnectStatus::Failed("callback_failed"), |
| 1018 | }; |
| 1019 | if !credential_writeability(&state.config.read(), identity).writable { |
| 1020 | return ConnectStatus::Failed("not_writable"); |
| 1021 | } |
| 1022 | { |
| 1023 | let mut current = status.lock(); |
| 1024 | if *current == ConnectStatus::Cancelled { |
| 1025 | return ConnectStatus::Cancelled; |
| 1026 | } |
| 1027 | *current = ConnectStatus::Exchanging; |
| 1028 | } |
| 1029 | let Ok(credential) = codewhale_runtime::oauth::exchange_orcarouter_code( |
| 1030 | &codewhale_runtime::oauth::ReqwestOAuthFormClient, |
| 1031 | auth_base, |
| 1032 | &code, |
| 1033 | &request.pkce.verifier, |
| 1034 | ) else { |
| 1035 | return ConnectStatus::Failed("exchange_failed"); |
| 1036 | }; |
| 1037 | drop(code); |
| 1038 | drop(request); |
| 1039 | if !credential.scope_satisfies_purpose() { |
| 1040 | return ConnectStatus::Failed("scope_refused"); |
| 1041 | } |
| 1042 | let _credential_change = state.provider_switches.blocking_lock(); |
| 1043 | if !is_current_connect_attempt(state, status) || *status.lock() != ConnectStatus::Exchanging { |
| 1044 | return ConnectStatus::Cancelled; |
| 1045 | } |
| 1046 | { |
| 1047 | let config = state.config.read(); |
| 1048 | if config.session_provider_keys_only |
| 1049 | || config.verify_provider_identity(identity).is_err() |
| 1050 | || config.base_url_for_route(identity) != *endpoint |
| 1051 | || !credential_writeability(&config, identity).writable |
| 1052 | { |
| 1053 | return ConnectStatus::Failed("not_writable"); |
| 1054 | } |
| 1055 | } |
| 1056 | let route_config = state.config.read().clone(); |
| 1057 | if codewhale_runtime::oauth::activate_orcarouter_credential(&credential, &route_config).is_err() |
| 1058 | { |
| 1059 | return ConnectStatus::Failed("key_not_saved"); |
| 1060 | } |
| 1061 | if mirror_saved_key_markers(&mut state.config.write(), identity).is_err() { |
| 1062 | tracing::warn!( |
| 1063 | target: "codewhale::oauth", |
| 1064 | "OrcaRouter key saved; the running config picks it up on reload" |
| 1065 | ); |
| 1066 | } |
| 1067 | *status.lock() = ConnectStatus::Connected; |
| 1068 | ConnectStatus::Connected |
| 1069 | } |
| 1070 | |
| 1071 | fn current_connect_attempt<'a>( |
| 1072 | current: &'a Option<ConnectAttempt>, |
| 1073 | provider: ProviderKind, |
| 1074 | attempt_id: &str, |
| 1075 | ) -> Result<&'a ConnectAttempt, ApiError> { |
| 1076 | current |
| 1077 | .as_ref() |
| 1078 | .filter(|attempt| attempt.id == attempt_id && attempt.provider == provider) |
| 1079 | .ok_or_else(|| ApiError::not_found("No current connect attempt has that id.")) |
| 1080 | } |
| 1081 | |
| 1082 | pub(super) async fn get_provider_connect( |
| 1083 | State(state): State<RuntimeApiState>, |
| 1084 | Path((id, attempt_id)): Path<(String, String)>, |
| 1085 | ) -> Result<Json<Value>, ApiError> { |
| 1086 | let kind = connect_provider_kind(&id)?; |
| 1087 | let current = state.provider_connect.0.lock(); |
| 1088 | let attempt = current_connect_attempt(¤t, kind, &attempt_id)?; |
| 1089 | let status = *attempt.status.lock(); |
| 1090 | Ok(Json(attempt.receipt(status))) |
| 1091 | } |
| 1092 | |
| 1093 | pub(super) async fn cancel_provider_connect( |
| 1094 | State(state): State<RuntimeApiState>, |
| 1095 | Path((id, attempt_id)): Path<(String, String)>, |
| 1096 | ) -> Result<Json<Value>, ApiError> { |
| 1097 | let _credential_change = state.provider_switches.lock().await; |
| 1098 | let kind = connect_provider_kind(&id)?; |
| 1099 | let current = state.provider_connect.0.lock(); |
| 1100 | let attempt = current_connect_attempt(¤t, kind, &attempt_id)?; |
| 1101 | let status = attempt.cancel(); |
| 1102 | Ok(Json(attempt.receipt(status))) |
| 1103 | } |
| 1104 | |
| 1105 | /// The underlying credential owner, independent of a session-key overlay, |
| 1106 | /// as a *class* and never as a value, a path, or an environment variable name. |
| 1107 | /// |
| 1108 | /// This exists so a client can disable its own credential control with a |
| 1109 | /// truthful reason before submitting, instead of letting a write fail late or — |
| 1110 | /// worse — appear to succeed against a source Codewhale does not own. |
| 1111 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 1112 | #[serde(rename_all = "snake_case")] |
| 1113 | pub(super) enum ProviderCredentialSource { |
| 1114 | /// Codewhale's own durable secret backend. |
| 1115 | SecretStore, |
| 1116 | /// The expiring account transform; disconnect through account sign-out. |
| 1117 | AccountSession, |
| 1118 | /// A literal value sitting in a config document. |
| 1119 | Config, |
| 1120 | /// An external consent or auth-command source (OAuth, `auth_source`). |
| 1121 | ExternalAuth, |
| 1122 | /// The route takes no credential at all. |
| 1123 | None, |
| 1124 | } |
| 1125 | |
| 1126 | /// Whether this route's credential can be written through the runtime API, and |
| 1127 | /// the reason when it cannot. The reason is user-facing copy. |
| 1128 | pub(super) struct CredentialWriteability { |
| 1129 | pub(super) source: ProviderCredentialSource, |
| 1130 | pub(super) writable: bool, |
| 1131 | pub(super) reason: Option<&'static str>, |
| 1132 | } |
| 1133 | |
| 1134 | /// Classify a route's underlying credential ownership without its session key. |
| 1135 | /// |
| 1136 | /// Auth mode, consent state and configured `api_key` kinds are structural; |
| 1137 | /// a bound account also requires source resolution with the session overlay |
| 1138 | /// excluded. The result exposes only the owner, never credential material. |
| 1139 | pub(super) fn credential_writeability( |
| 1140 | config: &codewhale_runtime::config::Config, |
| 1141 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 1142 | ) -> CredentialWriteability { |
| 1143 | if config.verify_provider_identity(identity).is_err() { |
| 1144 | return CredentialWriteability { |
| 1145 | source: ProviderCredentialSource::None, |
| 1146 | writable: false, |
| 1147 | reason: Some( |
| 1148 | "This route has no admitted credential authority; repair its provider selection.", |
| 1149 | ), |
| 1150 | }; |
| 1151 | } |
| 1152 | if config.required_account_model_owner.is_some() { |
| 1153 | return CredentialWriteability { |
| 1154 | source: ProviderCredentialSource::AccountSession, |
| 1155 | writable: false, |
| 1156 | reason: Some("This route uses your Codewhale account. Sign out to disconnect it."), |
| 1157 | }; |
| 1158 | } |
| 1159 | let provider = identity.provider; |
| 1160 | let auth_mode = config.auth_mode_for_provider(identity); |
| 1161 | if provider == ProviderKind::Custom |
| 1162 | && config |
| 1163 | .provider_config_for(identity) |
| 1164 | .is_some_and(|entry| entry.oauth.is_some()) |
| 1165 | { |
| 1166 | return CredentialWriteability { |
| 1167 | source: ProviderCredentialSource::ExternalAuth, |
| 1168 | writable: false, |
| 1169 | reason: Some( |
| 1170 | "This provider signs in through its reviewed plugin. Use the plugin login or logout command.", |
| 1171 | ), |
| 1172 | }; |
| 1173 | } |
| 1174 | if codewhale_config::auth_mode_disables_api_key(auth_mode.as_deref()) { |
| 1175 | return CredentialWriteability { |
| 1176 | source: ProviderCredentialSource::None, |
| 1177 | writable: false, |
| 1178 | reason: Some("This route is configured to send no credential."), |
| 1179 | }; |
| 1180 | } |
| 1181 | if provider == ProviderKind::Custom { |
| 1182 | return CredentialWriteability { |
| 1183 | source: ProviderCredentialSource::None, |
| 1184 | writable: false, |
| 1185 | reason: Some("This route has no credential slot."), |
| 1186 | }; |
| 1187 | } |
| 1188 | // An active external consent owns the credential. Overwriting the key slot |
| 1189 | // would not change what the route sends, so a write here must refuse |
| 1190 | // rather than report a success the user cannot observe. |
| 1191 | if config |
| 1192 | .external_credential_consent_status(identity) |
| 1193 | .is_some_and(|status| status.route_state == "active") |
| 1194 | { |
| 1195 | return CredentialWriteability { |
| 1196 | source: ProviderCredentialSource::ExternalAuth, |
| 1197 | writable: false, |
| 1198 | reason: Some( |
| 1199 | "This route signs in through an external consent. Sign out of it before setting a key.", |
| 1200 | ), |
| 1201 | }; |
| 1202 | } |
| 1203 | // A literal key in a config document is a plaintext credential Codewhale |
| 1204 | // did not put there. Writing the secret store would leave the literal in |
| 1205 | // place and still winning, so refuse and name the file-owned source. |
| 1206 | if let Some(entry) = config.provider_config_for(identity) |
| 1207 | && let Some(existing) = entry.api_key.as_deref() |
| 1208 | && codewhale_config::classify_config_api_key_value(existing) |
| 1209 | == codewhale_config::ConfigApiKeyValueKind::Literal |
| 1210 | { |
| 1211 | return CredentialWriteability { |
| 1212 | source: ProviderCredentialSource::Config, |
| 1213 | writable: false, |
| 1214 | reason: Some( |
| 1215 | "This route's key is set literally in a config file. Remove it there before managing it here.", |
| 1216 | ), |
| 1217 | }; |
| 1218 | } |
| 1219 | let account_bound = config.account_model_access.read().is_some(); |
| 1220 | if account_bound && { |
| 1221 | let mut underlying = config.clone(); |
| 1222 | underlying.session_provider_keys = Default::default(); |
| 1223 | matches!( |
| 1224 | codewhale_runtime::config::resolve_credential_source(&underlying, identity).source, |
| 1225 | codewhale_runtime::credentials::CredentialSource::AccountSession |
| 1226 | ) |
| 1227 | } { |
| 1228 | return CredentialWriteability { |
| 1229 | source: ProviderCredentialSource::AccountSession, |
| 1230 | writable: false, |
| 1231 | reason: Some("This route uses your Codewhale account. Sign out to disconnect it."), |
| 1232 | }; |
| 1233 | } |
| 1234 | CredentialWriteability { |
| 1235 | source: ProviderCredentialSource::SecretStore, |
| 1236 | writable: true, |
| 1237 | reason: None, |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | /// Provider validation for writes and the durable leg of clears. |
| 1242 | fn writable_provider( |
| 1243 | config: &codewhale_runtime::config::Config, |
| 1244 | id: &str, |
| 1245 | scope: ProviderKeyScope, |
| 1246 | ) -> Result<codewhale_runtime::config::ProviderIdentity, ApiError> { |
| 1247 | let identity = provider_key_identity(config, id)?; |
| 1248 | if scope == ProviderKeyScope::Session { |
| 1249 | if config.should_skip_secret_store_for_provider(&identity) { |
| 1250 | return Err(ApiError::conflict( |
| 1251 | "This route does not accept a provider key: check its endpoint and auth mode.", |
| 1252 | )); |
| 1253 | } |
| 1254 | if config.required_account_model_owner.is_none() |
| 1255 | && config.session_provider_api_key(&identity).is_some() |
| 1256 | { |
| 1257 | return Ok(identity); |
| 1258 | } |
| 1259 | } |
| 1260 | let writeability = credential_writeability(config, &identity); |
| 1261 | if !writeability.writable { |
| 1262 | return Err(ApiError::conflict( |
| 1263 | writeability |
| 1264 | .reason |
| 1265 | .unwrap_or("This route's credential is not managed by Codewhale."), |
| 1266 | )); |
| 1267 | } |
| 1268 | Ok(identity) |
| 1269 | } |
| 1270 | |
| 1271 | fn provider_key_identity( |
| 1272 | config: &codewhale_runtime::config::Config, |
| 1273 | id: &str, |
| 1274 | ) -> Result<codewhale_runtime::config::ProviderIdentity, ApiError> { |
| 1275 | let row = codewhale_config::descriptors::compatibility_for_selector(id) |
| 1276 | .ok_or_else(|| ApiError::bad_request(format!("Unknown provider id '{id}'")))?; |
| 1277 | if row.id != row.kind.as_str() { |
| 1278 | return Err(ApiError::bad_request(format!( |
| 1279 | "provider '{id}' is a legacy alias; use '{}' instead", |
| 1280 | row.kind.as_str() |
| 1281 | ))); |
| 1282 | } |
| 1283 | let identity = config |
| 1284 | .builtin_provider_identity(row.kind) |
| 1285 | .map_err(ApiError::bad_request)?; |
| 1286 | if identity.provider == ProviderKind::Custom { |
| 1287 | return Err(ApiError::bad_request("provider has no credential slot")); |
| 1288 | } |
| 1289 | Ok(identity) |
| 1290 | } |
| 1291 | |
| 1292 | /// `DELETE /v1/providers/{id}/key` — remove a Codewhale-owned credential. |
| 1293 | /// |
| 1294 | /// Shares `PUT`'s credential-ownership checks: reporting "cleared" for a |
| 1295 | /// credential this route cannot reach would misrepresent a security action. |
| 1296 | /// Unlike creating a new key, clearing can remove a legacy unused Codex key. |
| 1297 | /// The secret-store leg is reported separately because the config write lands |
| 1298 | /// first and the backend can still refuse. |
| 1299 | pub(super) async fn clear_provider_key( |
| 1300 | State(state): State<RuntimeApiState>, |
| 1301 | Path(id): Path<String>, |
| 1302 | ) -> Result<Json<Value>, ApiError> { |
| 1303 | #[cfg(any(test, feature = "test-support"))] |
| 1304 | let env_ticket = codewhale_engine::test_support::env_scope_ticket(); |
| 1305 | tokio::task::spawn_blocking(move || { |
| 1306 | #[cfg(any(test, feature = "test-support"))] |
| 1307 | let _membership = codewhale_engine::test_support::join_env_scope(env_ticket); |
| 1308 | let _credential_change = state.provider_switches.blocking_lock(); |
| 1309 | let (identity, scope) = { |
| 1310 | let config = state.config.write(); |
| 1311 | let identity = provider_key_identity(&config, &id)?; |
| 1312 | config.session_provider_keys.write().remove(&identity); |
| 1313 | let scope = if config.session_provider_keys_only { |
| 1314 | ProviderKeyScope::Session |
| 1315 | } else { |
| 1316 | ProviderKeyScope::Durable |
| 1317 | }; |
| 1318 | if scope == ProviderKeyScope::Durable { |
| 1319 | writable_provider(&config, &id, scope)?; |
| 1320 | } |
| 1321 | (identity, scope) |
| 1322 | }; |
| 1323 | if matches!( |
| 1324 | identity.provider, |
| 1325 | ProviderKind::Orcarouter | ProviderKind::Anthropic |
| 1326 | ) && let Some(attempt) = state |
| 1327 | .provider_connect |
| 1328 | .0 |
| 1329 | .lock() |
| 1330 | .as_ref() |
| 1331 | .filter(|attempt| attempt.provider == identity.provider) |
| 1332 | { |
| 1333 | attempt.cancel(); |
| 1334 | } |
| 1335 | if scope == ProviderKeyScope::Session { |
| 1336 | return Ok(Json(json!({ |
| 1337 | "provider": identity.key, |
| 1338 | "cleared": true, |
| 1339 | "scope": "session", |
| 1340 | "backend": "memory", |
| 1341 | }))); |
| 1342 | } |
| 1343 | let kind = identity.provider; |
| 1344 | |
| 1345 | let secrets = codewhale_runtime::config::credential_secret_store().ok_or_else(|| { |
| 1346 | ApiError::internal("no credential store is available in this environment") |
| 1347 | })?; |
| 1348 | |
| 1349 | let store_path = state.config_path.clone(); |
| 1350 | let outcome = { |
| 1351 | let mut store = ConfigStore::load(store_path).map_err(|error| { |
| 1352 | ApiError::internal(format!("config store unavailable: {error}")) |
| 1353 | })?; |
| 1354 | let mut credential_store = |
| 1355 | codewhale_config::credentials::credential_metadata_store(&store) |
| 1356 | .map_err(|error| ApiError::internal(format!("credential store: {error}")))?; |
| 1357 | let target = credential_store.as_mut().unwrap_or(&mut store); |
| 1358 | let slot = codewhale_config::credentials::provider_slot(kind); |
| 1359 | codewhale_runtime::credentials::store::with_provider_write_lock(slot, || { |
| 1360 | codewhale_config::credentials::clear_provider_api_key(target, &secrets, kind) |
| 1361 | }) |
| 1362 | .map_err(|error| { |
| 1363 | // Clear errors name slots and paths only; no key material can |
| 1364 | // reach this message because none was read. |
| 1365 | ApiError::internal(format!("credential clear failed: {error}")) |
| 1366 | }) |
| 1367 | }?; |
| 1368 | |
| 1369 | // Mirror the cleared markers into the live config for the same reason the |
| 1370 | // write path mirrors them: the durable clear may have landed on the |
| 1371 | // user-global document while this server's ambient config is |
| 1372 | // workspace-scoped, and `credential_state` would otherwise keep reporting |
| 1373 | // the provider as configured until the next process start. |
| 1374 | { |
| 1375 | let mut config = state.config.write(); |
| 1376 | config |
| 1377 | .verify_provider_identity(&identity) |
| 1378 | .map_err(ApiError::conflict)?; |
| 1379 | let entry = config |
| 1380 | .provider_config_for_mut(&identity) |
| 1381 | .map_err(|error| ApiError::conflict(error.to_string()))?; |
| 1382 | entry.api_key = None; |
| 1383 | if kind == ProviderKind::Xai { |
| 1384 | entry.auth_mode = None; |
| 1385 | entry.external_credentials = None; |
| 1386 | entry.oauth_credential_generation = None; |
| 1387 | } |
| 1388 | } |
| 1389 | |
| 1390 | let credential_state: ProviderCredentialState = |
| 1391 | codewhale_engine::provider_readiness::credential_state_for_provider( |
| 1392 | &state.config.read(), |
| 1393 | &identity, |
| 1394 | ) |
| 1395 | .into(); |
| 1396 | |
| 1397 | if let Some(error) = outcome.secret_store_error { |
| 1398 | return Err(ApiError::internal(format!( |
| 1399 | "the config entry was cleared, but the secret store refused to delete {}: {error}", |
| 1400 | outcome.slot |
| 1401 | ))); |
| 1402 | } |
| 1403 | |
| 1404 | Ok(Json(json!({ |
| 1405 | "provider": identity.key, |
| 1406 | "cleared": true, |
| 1407 | "credentialState": credential_state, |
| 1408 | }))) |
| 1409 | }) |
| 1410 | .await |
| 1411 | .map_err(|_| ApiError::internal("credential clear task failed"))? |
| 1412 | } |
| 1413 | |
| 1414 | pub(super) async fn check_provider_key( |
| 1415 | State(state): State<RuntimeApiState>, |
| 1416 | Path(id): Path<String>, |
| 1417 | Json(request): Json<CheckProviderKeyRequest>, |
| 1418 | ) -> Result<Json<Value>, ApiError> { |
| 1419 | let (identity, base_url) = { |
| 1420 | let config = state.config.read(); |
| 1421 | let identity = writable_provider(&config, &id, ProviderKeyScope::Durable)?; |
| 1422 | let base_url = config.base_url_for_route(&identity); |
| 1423 | (identity, base_url) |
| 1424 | }; |
| 1425 | let kind = identity.provider; |
| 1426 | if kind == codewhale_config::ProviderKind::OpenaiCodex { |
| 1427 | return Err(ApiError::bad_request( |
| 1428 | codewhale_config::credentials::OPENAI_CODEX_API_KEY_REFUSAL, |
| 1429 | )); |
| 1430 | } |
| 1431 | let key = codewhale_secrets::normalize_api_key(&request.key); |
| 1432 | if key.is_empty() { |
| 1433 | return Err(ApiError::bad_request("key must not be empty")); |
| 1434 | } |
| 1435 | if key.len() > MAX_KEY_BYTES || key.chars().any(char::is_control) { |
| 1436 | return Err(ApiError::bad_request( |
| 1437 | "key must be a single-line credential at most 4 KiB", |
| 1438 | )); |
| 1439 | } |
| 1440 | let checked = codewhale_engine::client::provider_api_key_verification_is_observed_for_route( |
| 1441 | kind, &base_url, |
| 1442 | ); |
| 1443 | match codewhale_engine::client::verify_provider_api_key(kind, &key, &base_url).await { |
| 1444 | Ok(_) => Ok(Json(json!({ |
| 1445 | "provider": identity.key, |
| 1446 | "valid": true, |
| 1447 | "checked": checked, |
| 1448 | }))), |
| 1449 | Err(reason) if reason.starts_with("HTTP 401") || reason.starts_with("HTTP 403") => Err( |
| 1450 | ApiError::unprocessable("The provider did not accept this key."), |
| 1451 | ), |
| 1452 | Err(_) => Err(ApiError::bad_gateway( |
| 1453 | "Could not check this key with the provider right now.", |
| 1454 | )), |
| 1455 | } |
| 1456 | } |
| 1457 | |
| 1458 | #[cfg(test)] |
| 1459 | mod tests { |
| 1460 | use super::*; |
| 1461 | use codewhale_runtime::config::Config; |
| 1462 | |
| 1463 | fn saved_account_session(session_id: &str) -> codewhale_secrets::account::AccountSessionStore { |
| 1464 | let store = codewhale_secrets::account::AccountSessionStore::new( |
| 1465 | codewhale_secrets::account::secure_account_session_secrets().unwrap(), |
| 1466 | None, |
| 1467 | codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE, |
| 1468 | ); |
| 1469 | store |
| 1470 | .save(codewhale_secrets::account::AccountAuthBundle { |
| 1471 | token_type: "Bearer".into(), |
| 1472 | access_token: "fixture-access-token-for-account-models".into(), |
| 1473 | refresh_token: "fixture-refresh-token-for-account-models".into(), |
| 1474 | session: Some(codewhale_secrets::account::AccountSession { |
| 1475 | id: session_id.into(), |
| 1476 | status: "active".into(), |
| 1477 | expires_at: (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339(), |
| 1478 | refresh_expires_at: (chrono::Utc::now() + chrono::Duration::days(1)) |
| 1479 | .to_rfc3339(), |
| 1480 | ..Default::default() |
| 1481 | }), |
| 1482 | user: Some(codewhale_secrets::account::AccountUser { |
| 1483 | id: "fixture-user".into(), |
| 1484 | ..Default::default() |
| 1485 | }), |
| 1486 | }) |
| 1487 | .unwrap(); |
| 1488 | store |
| 1489 | } |
| 1490 | |
| 1491 | fn account_request(owner: Option<&str>) -> SetAccountModelAccessRequest { |
| 1492 | SetAccountModelAccessRequest { |
| 1493 | api_base: codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL.into(), |
| 1494 | session_id: "fixture-session".into(), |
| 1495 | expected_session_id: owner.map(str::to_string), |
| 1496 | key: "cwc_fixture_device_credential_not_real".into(), |
| 1497 | expires_at: chrono::Utc::now().timestamp() + 1800, |
| 1498 | } |
| 1499 | } |
| 1500 | |
| 1501 | #[test] |
| 1502 | fn account_overlay_resolves_without_disk_residue_and_logout_revokes_clones() { |
| 1503 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 1504 | let tmp = tempfile::tempdir().unwrap(); |
| 1505 | let _home = codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 1506 | let _backend = |
| 1507 | codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 1508 | let _base = codewhale_engine::test_support::EnvVarGuard::set( |
| 1509 | "CODEWHALE_CLOUD_API_BASE", |
| 1510 | codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE, |
| 1511 | ); |
| 1512 | let _api_base = codewhale_engine::test_support::EnvVarGuard::set( |
| 1513 | "CODEWHALE_API_BASE", |
| 1514 | codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL, |
| 1515 | ); |
| 1516 | let _api_key = codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_API_KEY", ""); |
| 1517 | let store = saved_account_session("fixture-session"); |
| 1518 | let config = { |
| 1519 | let __cw_config_init_0_0 = Some("codewhale".into()); |
| 1520 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 1521 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 1522 | __cw_config_init_0_value |
| 1523 | }; |
| 1524 | let cloned_before_install = config.clone(); |
| 1525 | assert!(install_account_model_access(&config, None, account_request(None)).unwrap()); |
| 1526 | assert_eq!( |
| 1527 | cloned_before_install |
| 1528 | .active_route_api_key_read_only() |
| 1529 | .unwrap(), |
| 1530 | "cwc_fixture_device_credential_not_real" |
| 1531 | ); |
| 1532 | assert!(codewhale_engine::provider_readiness::has_api_key_for( |
| 1533 | &config, |
| 1534 | &(config).test_identity_for_kind(ProviderKind::Codewhale) |
| 1535 | )); |
| 1536 | assert!(!format!("{config:?}").contains("cwc_fixture")); |
| 1537 | assert!( |
| 1538 | !account_model_access_receipt(&config) |
| 1539 | .to_string() |
| 1540 | .contains("cwc_fixture") |
| 1541 | ); |
| 1542 | assert!( |
| 1543 | config |
| 1544 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1545 | .is_none() |
| 1546 | ); |
| 1547 | assert!( |
| 1548 | codewhale_runtime::config::credential_secret_store() |
| 1549 | .unwrap() |
| 1550 | .get("codewhale") |
| 1551 | .unwrap() |
| 1552 | .is_none() |
| 1553 | ); |
| 1554 | use codewhale_config::catalog::{ |
| 1555 | CatalogStatus, ProviderCatalogDelta, base_url_fingerprint, |
| 1556 | }; |
| 1557 | let endpoint = codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL; |
| 1558 | let ticket = codewhale_engine::provider_catalog_live::begin_refresh_for_identity( |
| 1559 | ProviderKind::Codewhale, |
| 1560 | "codewhale", |
| 1561 | endpoint, |
| 1562 | ); |
| 1563 | let delta = || ProviderCatalogDelta { |
| 1564 | provider: "codewhale".into(), |
| 1565 | base_url_fingerprint: base_url_fingerprint(endpoint), |
| 1566 | fetched_at: 1, |
| 1567 | offerings: vec![], |
| 1568 | }; |
| 1569 | assert_eq!( |
| 1570 | codewhale_engine::provider_catalog_live::record_success_if_current(&ticket, delta()), |
| 1571 | Some(CatalogStatus::Fresh) |
| 1572 | ); |
| 1573 | assert!( |
| 1574 | !install_account_model_access(&config, None, account_request(Some("fixture-session"))) |
| 1575 | .unwrap() |
| 1576 | ); |
| 1577 | assert!( |
| 1578 | codewhale_engine::provider_catalog_live::cached_entry_for_route( |
| 1579 | ProviderKind::Codewhale, |
| 1580 | "codewhale", |
| 1581 | endpoint |
| 1582 | ) |
| 1583 | .unwrap() |
| 1584 | .is_some() |
| 1585 | ); |
| 1586 | let mut extended = account_request(Some("fixture-session")); |
| 1587 | extended.expires_at += 60; |
| 1588 | assert!(!install_account_model_access(&config, None, extended).unwrap()); |
| 1589 | assert_eq!( |
| 1590 | codewhale_engine::provider_catalog_live::record_success_if_current(&ticket, delta()), |
| 1591 | Some(CatalogStatus::Fresh) |
| 1592 | ); |
| 1593 | let mut strict = config.clone(); |
| 1594 | strict.bind_account_model_owner("fixture-user").unwrap(); |
| 1595 | strict |
| 1596 | .provider_config_for_mut(&strict.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1597 | .unwrap() |
| 1598 | .api_key = Some("other-local-key".into()); |
| 1599 | assert_eq!( |
| 1600 | strict.active_route_api_key_read_only().unwrap(), |
| 1601 | "cwc_fixture_device_credential_not_real" |
| 1602 | ); |
| 1603 | assert!( |
| 1604 | config |
| 1605 | .clone() |
| 1606 | .bind_account_model_owner("other-account") |
| 1607 | .is_err() |
| 1608 | ); |
| 1609 | store.clear().unwrap(); |
| 1610 | assert!(strict.active_route_api_key_read_only().is_err()); |
| 1611 | invalidate_stale_account_catalog(&config); |
| 1612 | assert!( |
| 1613 | codewhale_engine::provider_catalog_live::cached_entry_for_route( |
| 1614 | ProviderKind::Codewhale, |
| 1615 | "codewhale", |
| 1616 | endpoint |
| 1617 | ) |
| 1618 | .unwrap() |
| 1619 | .is_none() |
| 1620 | ); |
| 1621 | assert_eq!( |
| 1622 | codewhale_engine::provider_catalog_live::record_success_if_current(&ticket, delta()), |
| 1623 | None |
| 1624 | ); |
| 1625 | assert!( |
| 1626 | cloned_before_install |
| 1627 | .active_route_api_key_read_only() |
| 1628 | .is_err() |
| 1629 | ); |
| 1630 | assert!( |
| 1631 | install_account_model_access(&config, None, account_request(Some("fixture-session"))) |
| 1632 | .is_err() |
| 1633 | ); |
| 1634 | } |
| 1635 | |
| 1636 | #[test] |
| 1637 | fn account_overlay_refuses_endpoint_credentials_and_stale_session_ownership() { |
| 1638 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 1639 | let tmp = tempfile::tempdir().unwrap(); |
| 1640 | let _home = codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 1641 | let _backend = |
| 1642 | codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 1643 | let _base = codewhale_engine::test_support::EnvVarGuard::set( |
| 1644 | "CODEWHALE_CLOUD_API_BASE", |
| 1645 | codewhale_secrets::account::DEFAULT_ACCOUNT_API_BASE, |
| 1646 | ); |
| 1647 | let _api_base = codewhale_engine::test_support::EnvVarGuard::set( |
| 1648 | "CODEWHALE_API_BASE", |
| 1649 | codewhale_config::descriptors::defaults::DEFAULT_CODEWHALE_BASE_URL, |
| 1650 | ); |
| 1651 | let _api_key = codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_API_KEY", ""); |
| 1652 | saved_account_session("fixture-session"); |
| 1653 | let mut config = { |
| 1654 | let __cw_config_init_1_0 = Some("codewhale".into()); |
| 1655 | let mut __cw_config_init_1_value: Config = Default::default(); |
| 1656 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 1657 | __cw_config_init_1_value |
| 1658 | }; |
| 1659 | config |
| 1660 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1661 | .unwrap() |
| 1662 | .base_url = Some("https://api.codewhale.net/other/v1".into()); |
| 1663 | assert!(install_account_model_access(&config, None, account_request(None)).is_err()); |
| 1664 | config |
| 1665 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1666 | .unwrap() |
| 1667 | .base_url = None; |
| 1668 | config |
| 1669 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1670 | .unwrap() |
| 1671 | .api_key = Some("existing-user-key".into()); |
| 1672 | assert!(install_account_model_access(&config, None, account_request(None)).is_err()); |
| 1673 | config |
| 1674 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1675 | .unwrap() |
| 1676 | .api_key = None; |
| 1677 | let mut expired = account_request(None); |
| 1678 | expired.expires_at = chrono::Utc::now().timestamp() - 1; |
| 1679 | assert!(install_account_model_access(&config, None, expired).is_err()); |
| 1680 | install_account_model_access(&config, None, account_request(None)).unwrap(); |
| 1681 | assert!(install_account_model_access(&config, None, account_request(None)).is_err()); |
| 1682 | install_account_model_access(&config, None, account_request(Some("fixture-session"))) |
| 1683 | .unwrap(); |
| 1684 | assert!(remove_account_model_access(&config, "stale-session").is_err()); |
| 1685 | assert!( |
| 1686 | config |
| 1687 | .account_model_api_key(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1688 | .is_some() |
| 1689 | ); |
| 1690 | config |
| 1691 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1692 | .unwrap() |
| 1693 | .api_key = Some("new-user-key".into()); |
| 1694 | assert_eq!( |
| 1695 | config.active_route_api_key_read_only().unwrap(), |
| 1696 | "new-user-key" |
| 1697 | ); |
| 1698 | config |
| 1699 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1700 | .unwrap() |
| 1701 | .api_key = None; |
| 1702 | config |
| 1703 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1704 | .unwrap() |
| 1705 | .base_url = Some("https://api.codewhale.net/other/v1".into()); |
| 1706 | assert!( |
| 1707 | config |
| 1708 | .account_model_api_key(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1709 | .is_none() |
| 1710 | ); |
| 1711 | } |
| 1712 | |
| 1713 | #[test] |
| 1714 | fn account_overlay_clear_is_shared_and_preserves_manual_config() { |
| 1715 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 1716 | let mut config = Config::default(); |
| 1717 | config |
| 1718 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1719 | .unwrap() |
| 1720 | .api_key = Some("manual-key".into()); |
| 1721 | *config.account_model_access.write() = |
| 1722 | Some(codewhale_runtime::config::AccountModelAccess { |
| 1723 | session_id: "current".into(), |
| 1724 | credential: codewhale_runtime::credentials::Credential::ApiKey { |
| 1725 | key: "cwc_fixture".into(), |
| 1726 | }, |
| 1727 | expires_at: chrono::Utc::now().timestamp() + 60, |
| 1728 | profile: None, |
| 1729 | }); |
| 1730 | let clone = config.clone(); |
| 1731 | assert!(remove_account_model_access(&config, "stale").is_err()); |
| 1732 | assert!(clone.account_model_access.read().is_some()); |
| 1733 | remove_account_model_access(&config, "current").unwrap(); |
| 1734 | assert!(clone.account_model_access.read().is_none()); |
| 1735 | assert_eq!( |
| 1736 | config |
| 1737 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::Codewhale)) |
| 1738 | .unwrap() |
| 1739 | .api_key |
| 1740 | .as_deref(), |
| 1741 | Some("manual-key") |
| 1742 | ); |
| 1743 | } |
| 1744 | |
| 1745 | #[test] |
| 1746 | fn plugin_oauth_credentials_cannot_be_replaced_by_an_api_key() { |
| 1747 | let mut config = { |
| 1748 | let __cw_config_init_2_0 = Some("plugin-test".into()); |
| 1749 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 1750 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 1751 | __cw_config_init_2_value |
| 1752 | }; |
| 1753 | let entry = config |
| 1754 | .providers |
| 1755 | .get_or_insert_with(Default::default) |
| 1756 | .custom |
| 1757 | .entry("plugin-test".into()) |
| 1758 | .or_default(); |
| 1759 | entry.kind = Some("openai-compatible".into()); |
| 1760 | entry.base_url = Some("https://gateway.example/api".into()); |
| 1761 | entry.auth_mode = Some("oauth".into()); |
| 1762 | entry.oauth = Some(codewhale_runtime::oauth::PluginOAuthConfig { |
| 1763 | issuer: "https://gateway.example".into(), |
| 1764 | authorization_endpoint: "https://gateway.example/authorize".into(), |
| 1765 | token_endpoint: "https://gateway.example/token".into(), |
| 1766 | client_id: "plugin-test".into(), |
| 1767 | scopes: vec![], |
| 1768 | resource: None, |
| 1769 | callback_path: "/oauth/callback".into(), |
| 1770 | }); |
| 1771 | let identity = config.active_provider_identity().unwrap(); |
| 1772 | let writeability = credential_writeability(&config, &identity); |
| 1773 | assert!(!writeability.writable); |
| 1774 | assert_eq!(writeability.source, ProviderCredentialSource::ExternalAuth); |
| 1775 | assert!(writeability.reason.unwrap().contains("plugin")); |
| 1776 | } |
| 1777 | |
| 1778 | /// A route Codewhale owns is writable, and says its source is the store it |
| 1779 | /// would actually write. |
| 1780 | #[test] |
| 1781 | fn a_codewhale_owned_route_is_writable_through_the_secret_store() { |
| 1782 | let config = Config::default(); |
| 1783 | let writeability = credential_writeability( |
| 1784 | &config, |
| 1785 | &(config).test_identity_for_kind(ProviderKind::Openai), |
| 1786 | ); |
| 1787 | assert_eq!(writeability.source, ProviderCredentialSource::SecretStore); |
| 1788 | assert!(writeability.writable); |
| 1789 | assert!(writeability.reason.is_none()); |
| 1790 | } |
| 1791 | |
| 1792 | /// The case #6179 exists for: a literal key in a config file still wins at |
| 1793 | /// request time, so a write here must refuse rather than report a success |
| 1794 | /// the user cannot observe. The reason names the file-owned source. |
| 1795 | #[test] |
| 1796 | fn a_literal_config_key_refuses_the_write_and_says_why() { |
| 1797 | let mut config = Config::default(); |
| 1798 | config |
| 1799 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openai)) |
| 1800 | .unwrap() |
| 1801 | .api_key = Some("sk-literal-in-a-config-file".to_string()); |
| 1802 | |
| 1803 | let writeability = credential_writeability( |
| 1804 | &config, |
| 1805 | &(config).test_identity_for_kind(ProviderKind::Openai), |
| 1806 | ); |
| 1807 | assert_eq!(writeability.source, ProviderCredentialSource::Config); |
| 1808 | assert!(!writeability.writable); |
| 1809 | let reason = writeability.reason.expect("a refusal must name its reason"); |
| 1810 | assert!(reason.contains("config file"), "{reason}"); |
| 1811 | // The reason is copy, not a credential: it can never carry the value. |
| 1812 | assert!(!reason.contains("sk-literal-in-a-config-file")); |
| 1813 | } |
| 1814 | |
| 1815 | /// The secret-store sentinel is routing metadata, not a credential, so it |
| 1816 | /// must not be mistaken for a file-owned literal and refused. |
| 1817 | #[test] |
| 1818 | fn the_secret_store_sentinel_is_not_a_file_owned_key() { |
| 1819 | let mut config = Config::default(); |
| 1820 | config |
| 1821 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openai)) |
| 1822 | .unwrap() |
| 1823 | .api_key = Some(codewhale_config::API_KEYRING_SENTINEL.to_string()); |
| 1824 | |
| 1825 | let writeability = credential_writeability( |
| 1826 | &config, |
| 1827 | &(config).test_identity_for_kind(ProviderKind::Openai), |
| 1828 | ); |
| 1829 | assert_eq!(writeability.source, ProviderCredentialSource::SecretStore); |
| 1830 | assert!(writeability.writable); |
| 1831 | } |
| 1832 | |
| 1833 | /// A route declared to send no credential has nothing to manage, and says |
| 1834 | /// so instead of offering a control that would do nothing. |
| 1835 | #[test] |
| 1836 | fn a_no_auth_route_reports_no_credential_source() { |
| 1837 | let mut config = Config::default(); |
| 1838 | config |
| 1839 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openai)) |
| 1840 | .unwrap() |
| 1841 | .auth_mode = Some("none".to_string()); |
| 1842 | |
| 1843 | let writeability = credential_writeability( |
| 1844 | &config, |
| 1845 | &(config).test_identity_for_kind(ProviderKind::Openai), |
| 1846 | ); |
| 1847 | assert_eq!(writeability.source, ProviderCredentialSource::None); |
| 1848 | assert!(!writeability.writable); |
| 1849 | assert!(writeability.reason.is_some()); |
| 1850 | } |
| 1851 | } |
| 1852 |