| 1 | use std::sync::{Arc, Mutex as StdMutex, OnceLock}; |
| 2 | |
| 3 | use codewhale_account_cli::{AccountClient, ClaudeOrgError, ClaudeOrgErrorKind, ClaudeOrgToken}; |
| 4 | use codewhale_config::credentials::CLAUDE_ORG_LINK_COMMAND; |
| 5 | use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue}; |
| 6 | use serde_json::{Value, json}; |
| 7 | use tokio::sync::Mutex; |
| 8 | |
| 9 | use crate::llm_client::LlmError; |
| 10 | |
| 11 | pub(super) type ClaudeOrgTokenSource = |
| 12 | Arc<dyn Fn() -> std::result::Result<ClaudeOrgToken, ClaudeOrgError> + Send + Sync>; |
| 13 | |
| 14 | const USER_PROFILES_BETA: &str = "user-profiles-billing-2026-10-01"; |
| 15 | const ISSUED_TOKENS_KEPT: usize = 4; |
| 16 | |
| 17 | type ClaudeOrgResumeIdentity = (String, String, String, String); |
| 18 | |
| 19 | fn resume_identity(token: &ClaudeOrgToken) -> Option<ClaudeOrgResumeIdentity> { |
| 20 | let (issuer, account) = token.account.as_ref()?; |
| 21 | let profile = token.user_profile_id.as_ref()?; |
| 22 | Some(( |
| 23 | issuer.clone(), |
| 24 | account.clone(), |
| 25 | profile.clone(), |
| 26 | token.base_url.clone(), |
| 27 | )) |
| 28 | } |
| 29 | |
| 30 | pub(super) struct ClaudeOrgAuth { |
| 31 | source: ClaudeOrgTokenSource, |
| 32 | default_beta: Option<String>, |
| 33 | cached: Mutex<Option<ClaudeOrgToken>>, |
| 34 | issued: StdMutex<Vec<String>>, |
| 35 | pinned_resume_identity: OnceLock<ClaudeOrgResumeIdentity>, |
| 36 | } |
| 37 | |
| 38 | impl ClaudeOrgAuth { |
| 39 | pub(super) fn for_profile(profile: Option<String>, default_beta: Option<String>) -> Self { |
| 40 | Self::with_source( |
| 41 | Arc::new(move || { |
| 42 | AccountClient::new(profile.as_deref(), None) |
| 43 | .map_err(|error| { |
| 44 | ClaudeOrgError::with_message( |
| 45 | ClaudeOrgErrorKind::NotSignedIn, |
| 46 | error.to_string(), |
| 47 | ) |
| 48 | })? |
| 49 | .claude_org_token() |
| 50 | }), |
| 51 | default_beta, |
| 52 | ) |
| 53 | } |
| 54 | |
| 55 | pub(super) fn with_source(source: ClaudeOrgTokenSource, default_beta: Option<String>) -> Self { |
| 56 | Self { |
| 57 | source, |
| 58 | default_beta, |
| 59 | cached: Mutex::new(None), |
| 60 | issued: StdMutex::new(Vec::new()), |
| 61 | pinned_resume_identity: OnceLock::new(), |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | #[allow(clippy::result_large_err)] |
| 66 | pub(super) async fn pin_resume_identity( |
| 67 | &self, |
| 68 | ) -> Result<Option<ClaudeOrgResumeIdentity>, LlmError> { |
| 69 | let identity = resume_identity(&self.token(None).await?); |
| 70 | if let Some(identity) = identity.as_ref() { |
| 71 | let pinned = self.pinned_resume_identity.get_or_init(|| identity.clone()); |
| 72 | if pinned != identity { |
| 73 | return Err(Self::resume_identity_changed()); |
| 74 | } |
| 75 | } |
| 76 | Ok(identity) |
| 77 | } |
| 78 | |
| 79 | fn resume_identity_changed() -> LlmError { |
| 80 | LlmError::authentication_error( |
| 81 | "Claude organization billing identity changed after route selection. Re-run with an explicit --provider or --model.", |
| 82 | ) |
| 83 | } |
| 84 | |
| 85 | #[allow(clippy::result_large_err)] |
| 86 | fn check_resume_identity(&self, token: &ClaudeOrgToken) -> Result<(), LlmError> { |
| 87 | if let Some(expected) = self.pinned_resume_identity.get() |
| 88 | && resume_identity(token).as_ref() != Some(expected) |
| 89 | { |
| 90 | return Err(Self::resume_identity_changed()); |
| 91 | } |
| 92 | Ok(()) |
| 93 | } |
| 94 | |
| 95 | #[allow(clippy::result_large_err)] |
| 96 | async fn token(&self, rejected: Option<&str>) -> Result<ClaudeOrgToken, LlmError> { |
| 97 | let mut cached = self.cached.lock().await; |
| 98 | if let Some(token) = cached.as_ref().filter(|token| { |
| 99 | token.is_fresh_at(chrono::Utc::now()) |
| 100 | && rejected.is_none_or(|rejected| rejected != token.access_token) |
| 101 | }) { |
| 102 | self.check_resume_identity(token)?; |
| 103 | return Ok(token.clone()); |
| 104 | } |
| 105 | *cached = None; |
| 106 | let source = Arc::clone(&self.source); |
| 107 | let token = tokio::task::spawn_blocking(move || source()) |
| 108 | .await |
| 109 | .map_err(|error| { |
| 110 | LlmError::Other(format!("Claude organization token task failed: {error}")) |
| 111 | })? |
| 112 | .map_err(token_error)?; |
| 113 | self.check_resume_identity(&token)?; |
| 114 | if let Ok(mut issued) = self.issued.lock() { |
| 115 | if !issued.contains(&token.access_token) { |
| 116 | issued.push(token.access_token.clone()); |
| 117 | } |
| 118 | let excess = issued.len().saturating_sub(ISSUED_TOKENS_KEPT); |
| 119 | issued.drain(..excess); |
| 120 | } |
| 121 | *cached = Some(token.clone()); |
| 122 | Ok(token) |
| 123 | } |
| 124 | |
| 125 | #[allow(clippy::result_large_err)] |
| 126 | pub(super) async fn refetch_after_rejection(&self, rejected: &str) -> Result<bool, LlmError> { |
| 127 | Ok(self.token(Some(rejected)).await?.access_token != rejected) |
| 128 | } |
| 129 | |
| 130 | #[allow(clippy::result_large_err)] |
| 131 | pub(super) async fn authorize( |
| 132 | &self, |
| 133 | request: reqwest::RequestBuilder, |
| 134 | test_transport_base: Option<&str>, |
| 135 | ) -> Result<(reqwest::RequestBuilder, String), LlmError> { |
| 136 | let token = self.token(None).await?; |
| 137 | let inspected = request |
| 138 | .try_clone() |
| 139 | .ok_or_else(|| { |
| 140 | LlmError::Other("Claude organization request cannot be inspected".into()) |
| 141 | })? |
| 142 | .build() |
| 143 | .map_err(|error| LlmError::Other(error.without_url().to_string()))?; |
| 144 | let destination = inspected.url().origin(); |
| 145 | let allowed = [Some(token.base_url.as_str()), test_transport_base] |
| 146 | .into_iter() |
| 147 | .flatten() |
| 148 | .filter_map(|base| reqwest::Url::parse(base).ok()) |
| 149 | .any(|base| base.origin() == destination); |
| 150 | if !allowed { |
| 151 | return Err(LlmError::Other( |
| 152 | "Refusing to send the Claude organization token: the request left the Anthropic endpoint the Codewhale service bound it to".into(), |
| 153 | )); |
| 154 | } |
| 155 | let invalid = |what: &str| { |
| 156 | LlmError::Other(format!( |
| 157 | "The Claude organization token carried an invalid {what}" |
| 158 | )) |
| 159 | }; |
| 160 | let mut headers = HeaderMap::new(); |
| 161 | let mut bearer = HeaderValue::from_str(&format!("Bearer {}", token.access_token)) |
| 162 | .map_err(|_| invalid("access token"))?; |
| 163 | bearer.set_sensitive(true); |
| 164 | headers.insert(AUTHORIZATION, bearer); |
| 165 | headers.insert( |
| 166 | HeaderName::from_static("anthropic-version"), |
| 167 | HeaderValue::from_str(&token.anthropic_version).map_err(|_| invalid("API version"))?, |
| 168 | ); |
| 169 | let mut request = request; |
| 170 | if let Some(profile) = token.user_profile_id.as_deref() { |
| 171 | headers.insert( |
| 172 | HeaderName::from_static("anthropic-user-profile-id"), |
| 173 | HeaderValue::from_str(profile).map_err(|_| invalid("user profile id"))?, |
| 174 | ); |
| 175 | let requested: Vec<&str> = inspected |
| 176 | .headers() |
| 177 | .get_all("anthropic-beta") |
| 178 | .iter() |
| 179 | .filter_map(|value| value.to_str().ok()) |
| 180 | .collect(); |
| 181 | let sources = if requested.is_empty() { |
| 182 | self.default_beta.as_deref().into_iter().collect() |
| 183 | } else { |
| 184 | requested |
| 185 | }; |
| 186 | let mut betas: Vec<&str> = Vec::new(); |
| 187 | for beta in sources |
| 188 | .iter() |
| 189 | .flat_map(|value| value.split(',')) |
| 190 | .map(str::trim) |
| 191 | .filter(|beta| !beta.is_empty()) |
| 192 | .chain([USER_PROFILES_BETA]) |
| 193 | { |
| 194 | if !betas.contains(&beta) { |
| 195 | betas.push(beta); |
| 196 | } |
| 197 | } |
| 198 | headers.insert( |
| 199 | HeaderName::from_static("anthropic-beta"), |
| 200 | HeaderValue::from_str(&betas.join(",")).map_err(|_| invalid("beta header"))?, |
| 201 | ); |
| 202 | if inspected.method() == reqwest::Method::POST |
| 203 | && inspected.url().path().ends_with("/v1/messages") |
| 204 | { |
| 205 | let mut body: Value = inspected |
| 206 | .body() |
| 207 | .and_then(reqwest::Body::as_bytes) |
| 208 | .and_then(|bytes| serde_json::from_slice(bytes).ok()) |
| 209 | .ok_or_else(|| { |
| 210 | LlmError::Other("Claude organization Messages body is not JSON".into()) |
| 211 | })?; |
| 212 | body.as_object_mut() |
| 213 | .ok_or_else(|| { |
| 214 | LlmError::Other("Claude organization Messages body is not an object".into()) |
| 215 | })? |
| 216 | .insert( |
| 217 | "billing_policy".into(), |
| 218 | json!({"type": "billing_policy", "bill_to": "user_profile"}), |
| 219 | ); |
| 220 | let body = serde_json::to_vec(&body) |
| 221 | .map_err(|error| LlmError::Other(error.to_string()))?; |
| 222 | request = request.body(body); |
| 223 | } |
| 224 | } |
| 225 | Ok((request.headers(headers), token.access_token)) |
| 226 | } |
| 227 | |
| 228 | pub(super) fn redact(&self, text: &str) -> String { |
| 229 | let Ok(issued) = self.issued.lock() else { |
| 230 | return text.to_string(); |
| 231 | }; |
| 232 | issued.iter().fold(text.to_string(), |text, token| { |
| 233 | text.replace(token.as_str(), codewhale_config::persistence::REDACTED) |
| 234 | }) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | fn token_error(error: ClaudeOrgError) -> LlmError { |
| 239 | match error.kind { |
| 240 | ClaudeOrgErrorKind::NotSignedIn |
| 241 | | ClaudeOrgErrorKind::NotLinked |
| 242 | | ClaudeOrgErrorKind::RelinkRequired |
| 243 | | ClaudeOrgErrorKind::Disabled |
| 244 | | ClaudeOrgErrorKind::AlreadyLinkedElsewhere => { |
| 245 | LlmError::authentication_error(error.to_string()) |
| 246 | } |
| 247 | ClaudeOrgErrorKind::Unavailable => LlmError::ConnectError { |
| 248 | message: error.to_string(), |
| 249 | transient: true, |
| 250 | timed_out: false, |
| 251 | }, |
| 252 | ClaudeOrgErrorKind::Invalid => LlmError::Other(error.to_string()), |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | pub(super) fn http_error(status: u16, raw: &str) -> Option<LlmError> { |
| 257 | if status == 403 && raw.contains("user_profile_not_billable") { |
| 258 | return Some(LlmError::authentication_error(format!( |
| 259 | "Anthropic could not bill your linked Claude organization: the link ended or the organization cannot be billed. Run `{CLAUDE_ORG_LINK_COMMAND}` and check Linked platforms in the Claude Console." |
| 260 | ))); |
| 261 | } |
| 262 | LlmError::from_linked_organization_billing_stop(status, raw) |
| 263 | } |
| 264 | |
| 265 | pub(super) fn relink_hint() -> String { |
| 266 | format!("run `{CLAUDE_ORG_LINK_COMMAND}` to link your Claude organization again") |
| 267 | } |
| 268 | |
| 269 | #[cfg(test)] |
| 270 | mod tests { |
| 271 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 272 | |
| 273 | use codewhale_models::{ContentBlock, Message, MessageRequest, Role}; |
| 274 | use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig}; |
| 275 | use serde_json::json; |
| 276 | use wiremock::matchers::{header, method, path}; |
| 277 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 278 | |
| 279 | use super::*; |
| 280 | use crate::client::CodewhaleClient; |
| 281 | use crate::llm_client::LlmClient; |
| 282 | |
| 283 | fn claude_org_config() -> Config { |
| 284 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 285 | let mut config = Config::default(); |
| 286 | config.provider = Some("anthropic".to_string()); |
| 287 | config.providers = Some(ProvidersConfig { |
| 288 | anthropic: ProviderConfig { |
| 289 | auth_mode: Some("claude-org".to_string()), |
| 290 | ..ProviderConfig::default() |
| 291 | }, |
| 292 | ..ProvidersConfig::default() |
| 293 | }); |
| 294 | config |
| 295 | } |
| 296 | |
| 297 | fn claude_org_client(server: &MockServer) -> (CodewhaleClient, Arc<AtomicUsize>) { |
| 298 | claude_org_client_with(server, None, None) |
| 299 | } |
| 300 | |
| 301 | fn claude_org_client_with( |
| 302 | server: &MockServer, |
| 303 | user_profile_id: Option<&str>, |
| 304 | default_beta: Option<&str>, |
| 305 | ) -> (CodewhaleClient, Arc<AtomicUsize>) { |
| 306 | let mut client = CodewhaleClient::new(&claude_org_config()).expect("claude-org client"); |
| 307 | assert!(client.claude_org.is_some()); |
| 308 | let fetches = Arc::new(AtomicUsize::new(0)); |
| 309 | let counter = Arc::clone(&fetches); |
| 310 | let user_profile_id = user_profile_id.map(str::to_string); |
| 311 | client.claude_org = Some(Arc::new(ClaudeOrgAuth::with_source( |
| 312 | Arc::new(move || { |
| 313 | let n = counter.fetch_add(1, Ordering::SeqCst) + 1; |
| 314 | Ok(ClaudeOrgToken { |
| 315 | account: Some(("fixture-account-service".into(), "fixture-account".into())), |
| 316 | access_token: format!("org-token-{n}"), |
| 317 | expires_at: chrono::Utc::now() + chrono::Duration::hours(1), |
| 318 | base_url: "https://api.anthropic.com".to_string(), |
| 319 | anthropic_version: "2026-10-21".to_string(), |
| 320 | user_profile_id: user_profile_id.clone(), |
| 321 | }) |
| 322 | }), |
| 323 | default_beta.map(str::to_string), |
| 324 | ))); |
| 325 | client.test_messages_transport_base_url = Some(server.uri()); |
| 326 | (client, fetches) |
| 327 | } |
| 328 | |
| 329 | fn request(client: &CodewhaleClient) -> MessageRequest { |
| 330 | MessageRequest { |
| 331 | model: client.default_model.clone(), |
| 332 | messages: vec![Message { |
| 333 | role: Role::User, |
| 334 | content: vec![ContentBlock::Text { |
| 335 | text: "hello".to_string(), |
| 336 | cache_control: None, |
| 337 | }], |
| 338 | }], |
| 339 | max_tokens: 32, |
| 340 | system: None, |
| 341 | tools: None, |
| 342 | tool_choice: None, |
| 343 | metadata: None, |
| 344 | thinking: None, |
| 345 | reasoning_effort: None, |
| 346 | stream: Some(false), |
| 347 | temperature: None, |
| 348 | top_p: None, |
| 349 | safety_check: None, |
| 350 | title: None, |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | fn ok_message() -> ResponseTemplate { |
| 355 | ResponseTemplate::new(200).set_body_json(json!({ |
| 356 | "id": "msg_1", |
| 357 | "type": "message", |
| 358 | "role": "assistant", |
| 359 | "content": [{"type": "text", "text": "ok"}], |
| 360 | "model": "claude", |
| 361 | "stop_reason": "end_turn", |
| 362 | "stop_sequence": null, |
| 363 | "usage": {"input_tokens": 3, "output_tokens": 1} |
| 364 | })) |
| 365 | } |
| 366 | |
| 367 | #[tokio::test] |
| 368 | async fn claude_org_sends_connection_bearer_and_version_and_refetches_once_on_401() { |
| 369 | let server = MockServer::start().await; |
| 370 | Mock::given(method("POST")) |
| 371 | .and(path("/v1/messages")) |
| 372 | .and(header("authorization", "Bearer org-token-1")) |
| 373 | .respond_with(ResponseTemplate::new(401).set_body_json(json!({ |
| 374 | "type": "error", |
| 375 | "error": {"type": "authentication_error", "message": "expired"} |
| 376 | }))) |
| 377 | .expect(1) |
| 378 | .mount(&server) |
| 379 | .await; |
| 380 | Mock::given(method("POST")) |
| 381 | .and(path("/v1/messages")) |
| 382 | .and(header("authorization", "Bearer org-token-2")) |
| 383 | .respond_with(ok_message()) |
| 384 | .expect(1) |
| 385 | .mount(&server) |
| 386 | .await; |
| 387 | let (mut client, fetches) = claude_org_client_with(&server, Some("uprof_fixture"), None); |
| 388 | client |
| 389 | .pin_exec_auth_scope() |
| 390 | .await |
| 391 | .expect("pin Claude billing profile"); |
| 392 | |
| 393 | client |
| 394 | .create_message(request(&client)) |
| 395 | .await |
| 396 | .expect("retried message succeeds"); |
| 397 | |
| 398 | assert_eq!(fetches.load(Ordering::SeqCst), 2); |
| 399 | let requests = server.received_requests().await.expect("requests"); |
| 400 | assert_eq!(requests.len(), 2); |
| 401 | for request in &requests { |
| 402 | assert!(request.headers.get("x-api-key").is_none()); |
| 403 | let versions: Vec<_> = request |
| 404 | .headers |
| 405 | .get_all("anthropic-version") |
| 406 | .iter() |
| 407 | .collect(); |
| 408 | assert_eq!(versions.len(), 1); |
| 409 | assert_eq!(versions[0], "2026-10-21"); |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | #[tokio::test] |
| 414 | async fn pinned_claude_org_profile_cannot_change_during_refetch() { |
| 415 | let fetches = AtomicUsize::new(0); |
| 416 | let auth = ClaudeOrgAuth::with_source( |
| 417 | Arc::new(move || { |
| 418 | let n = fetches.fetch_add(1, Ordering::SeqCst); |
| 419 | Ok(ClaudeOrgToken { |
| 420 | account: Some(("fixture-account-service".into(), "fixture-account".into())), |
| 421 | access_token: format!("fixture-token-{n}"), |
| 422 | expires_at: chrono::Utc::now() + chrono::Duration::hours(1), |
| 423 | base_url: "https://api.anthropic.com".into(), |
| 424 | anthropic_version: "2026-10-21".into(), |
| 425 | user_profile_id: Some(format!("uprof_fixture_{n}")), |
| 426 | }) |
| 427 | }), |
| 428 | None, |
| 429 | ); |
| 430 | assert!(auth.pin_resume_identity().await.unwrap().is_some()); |
| 431 | let error = auth |
| 432 | .refetch_after_rejection("fixture-token-0") |
| 433 | .await |
| 434 | .unwrap_err(); |
| 435 | assert!(error.to_string().contains("billing identity changed")); |
| 436 | } |
| 437 | |
| 438 | #[tokio::test] |
| 439 | async fn claude_org_token_is_refused_for_an_origin_it_was_not_bound_to() { |
| 440 | let fetches = Arc::new(AtomicUsize::new(0)); |
| 441 | let counter = Arc::clone(&fetches); |
| 442 | let auth = ClaudeOrgAuth::with_source( |
| 443 | Arc::new(move || { |
| 444 | counter.fetch_add(1, Ordering::SeqCst); |
| 445 | Ok(ClaudeOrgToken { |
| 446 | account: Some(("fixture-account-service".into(), "fixture-account".into())), |
| 447 | access_token: "org-token-bound".to_string(), |
| 448 | expires_at: chrono::Utc::now() + chrono::Duration::hours(1), |
| 449 | base_url: "https://api.anthropic.com".to_string(), |
| 450 | anthropic_version: "2026-10-21".to_string(), |
| 451 | user_profile_id: None, |
| 452 | }) |
| 453 | }), |
| 454 | None, |
| 455 | ); |
| 456 | let http = crate::platform_client_builder() |
| 457 | .build() |
| 458 | .expect("http client"); |
| 459 | for destination in [ |
| 460 | "https://api.anthropic.com.evil.example/v1/messages", |
| 461 | "http://api.anthropic.com/v1/messages", |
| 462 | "https://api.anthropic.com:8443/v1/messages", |
| 463 | ] { |
| 464 | let error = auth |
| 465 | .authorize(http.post(destination), None) |
| 466 | .await |
| 467 | .expect_err("token must not leave its bound origin"); |
| 468 | assert!( |
| 469 | error.to_string().contains("Refusing to send"), |
| 470 | "{destination}: {error}" |
| 471 | ); |
| 472 | } |
| 473 | let (allowed, _) = auth |
| 474 | .authorize(http.post("https://api.anthropic.com/v1/messages"), None) |
| 475 | .await |
| 476 | .expect("bound origin is allowed"); |
| 477 | let built = allowed.build().expect("request builds"); |
| 478 | assert_eq!( |
| 479 | built |
| 480 | .headers() |
| 481 | .get(AUTHORIZATION) |
| 482 | .and_then(|value| value.to_str().ok()), |
| 483 | Some("Bearer org-token-bound") |
| 484 | ); |
| 485 | assert_eq!(fetches.load(Ordering::SeqCst), 1); |
| 486 | } |
| 487 | |
| 488 | #[tokio::test] |
| 489 | async fn claude_org_spend_cap_is_reported_and_not_retried() { |
| 490 | let server = MockServer::start().await; |
| 491 | Mock::given(method("POST")) |
| 492 | .and(path("/v1/messages")) |
| 493 | .respond_with(ResponseTemplate::new(402).set_body_json(json!({ |
| 494 | "type": "error", |
| 495 | "error": { |
| 496 | "type": "linked_organization_spend_limit_reached", |
| 497 | "message": "spend limit reached" |
| 498 | } |
| 499 | }))) |
| 500 | .expect(1) |
| 501 | .mount(&server) |
| 502 | .await; |
| 503 | let (client, fetches) = claude_org_client(&server); |
| 504 | |
| 505 | let error = client |
| 506 | .create_message(request(&client)) |
| 507 | .await |
| 508 | .expect_err("spend cap stops the request"); |
| 509 | |
| 510 | let llm = error.downcast_ref::<LlmError>().expect("typed error"); |
| 511 | assert!(matches!(llm, LlmError::QuotaExhausted(_)), "{llm:?}"); |
| 512 | assert!(llm.to_string().contains("Claude Console"), "{llm}"); |
| 513 | assert_eq!(fetches.load(Ordering::SeqCst), 1); |
| 514 | } |
| 515 | |
| 516 | #[tokio::test] |
| 517 | async fn claude_org_user_profile_sends_profile_beta_and_billing_policy() { |
| 518 | let server = MockServer::start().await; |
| 519 | Mock::given(method("POST")) |
| 520 | .and(path("/v1/messages")) |
| 521 | .respond_with(ok_message()) |
| 522 | .expect(1) |
| 523 | .mount(&server) |
| 524 | .await; |
| 525 | let (client, _) = claude_org_client_with( |
| 526 | &server, |
| 527 | Some("uprof_test-1"), |
| 528 | Some("prompt-caching-2024-07-31"), |
| 529 | ); |
| 530 | |
| 531 | client |
| 532 | .create_message(request(&client)) |
| 533 | .await |
| 534 | .expect("message succeeds"); |
| 535 | |
| 536 | let requests = server.received_requests().await.expect("requests"); |
| 537 | let request = &requests[0]; |
| 538 | assert_eq!( |
| 539 | request.headers.get("anthropic-user-profile-id").unwrap(), |
| 540 | "uprof_test-1" |
| 541 | ); |
| 542 | let betas: Vec<_> = request.headers.get_all("anthropic-beta").iter().collect(); |
| 543 | assert_eq!(betas.len(), 1); |
| 544 | assert_eq!( |
| 545 | betas[0], |
| 546 | "prompt-caching-2024-07-31,user-profiles-billing-2026-10-01" |
| 547 | ); |
| 548 | let body: Value = serde_json::from_slice(&request.body).expect("json body"); |
| 549 | assert_eq!( |
| 550 | body["billing_policy"], |
| 551 | json!({"type": "billing_policy", "bill_to": "user_profile"}) |
| 552 | ); |
| 553 | assert!(request.headers.get("x-api-key").is_none()); |
| 554 | } |
| 555 | |
| 556 | #[test] |
| 557 | fn claude_org_session_key_wins_over_the_linked_organization() { |
| 558 | let config = claude_org_config(); |
| 559 | let identity = config.active_provider_identity().expect("identity"); |
| 560 | let endpoint = config.base_url_for_route(&identity); |
| 561 | config.session_provider_keys.write().insert( |
| 562 | identity, |
| 563 | ( |
| 564 | endpoint, |
| 565 | codewhale_runtime::credentials::Credential::ApiKey { |
| 566 | key: "sk-ant-session".to_string(), |
| 567 | }, |
| 568 | ), |
| 569 | ); |
| 570 | let client = CodewhaleClient::new(&config).expect("session-key client"); |
| 571 | assert!(client.claude_org.is_none()); |
| 572 | assert_eq!(client.api_key, "sk-ant-session"); |
| 573 | } |
| 574 | } |
| 575 |