1use std::collections::HashMap;
11use std::sync::{Arc, Mutex};
12use std::time::{Duration, Instant};
13
14use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
15use chrono::{DateTime, SecondsFormat, Utc};
16use cpa_core::credential::{Credential, MetadataPatch};
17use cpa_core::exec::{ExecError, FailureScope, ResponseBody};
18use futures_util::FutureExt;
19use futures_util::future::{BoxFuture, Shared};
20use serde::Serialize;
21use serde_json::{Value, json};
22use sha2::{Digest, Sha256};
23use url::Url;
24
25use crate::proxy::Proxy;
26use crate::tls::Transport;
27use crate::upstream::into_response;
28
29pub const CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
30pub const SCOPE: &str = "user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
31pub const REDIRECT_URI: &str = "http://localhost:54545/callback";
32const TOKEN_URL: &str = "https://platform.claude.com/v1/oauth/token";
33const PROFILE_URL: &str = "https://api.anthropic.com/api/oauth/profile";
34const ROLES_URL: &str = "https://api.anthropic.com/api/oauth/claude_cli/roles";
35
36type RefreshResult = Shared<BoxFuture<'static, Result<MetadataPatch, ExecError>>>;
37
38#[derive(Default)]
41struct Refreshes {
42 in_flight: HashMap<[u8; 32], RefreshResult>,
43 blocked: HashMap<[u8; 32], Instant>,
44}
45
46fn refreshes() -> std::sync::MutexGuard<'static, Refreshes> {
47 static REFRESHES: std::sync::OnceLock<Mutex<Refreshes>> = std::sync::OnceLock::new();
48 REFRESHES
49 .get_or_init(Mutex::default)
50 .lock()
51 .unwrap_or_else(std::sync::PoisonError::into_inner)
52}
53
54#[derive(Clone)]
55enum Source {
56 Fixed(wreq::Client),
57 Transport(Arc<Transport>),
58}
59
60#[derive(Clone)]
61pub struct OAuth {
62 source: Source,
63 proxy: Proxy,
64 token_url: String,
65 profile_url: String,
66 roles_url: String,
67}
68
69impl OAuth {
70 pub fn new(client: wreq::Client) -> Self {
71 Self::with_endpoints(client, TOKEN_URL, PROFILE_URL, ROLES_URL)
72 }
73
74 pub fn with_endpoints(client: wreq::Client, token: &str, profile: &str, roles: &str) -> Self {
76 Self {
77 source: Source::Fixed(client),
78 proxy: Proxy::Inherit,
79 token_url: token.into(),
80 profile_url: profile.into(),
81 roles_url: roles.into(),
82 }
83 }
84
85 pub(crate) fn with_transport(transport: Arc<Transport>) -> Self {
87 Self {
88 source: Source::Transport(transport),
89 proxy: Proxy::Inherit,
90 token_url: TOKEN_URL.into(),
91 profile_url: PROFILE_URL.into(),
92 roles_url: ROLES_URL.into(),
93 }
94 }
95
96 fn client(&self) -> Result<wreq::Client, ExecError> {
97 match &self.source {
98 Source::Fixed(client) => Ok(client.clone()),
99 Source::Transport(t) => t
100 .clients(&self.proxy, None)
101 .map(|c| c.oauth.clone())
102 .map_err(|_| ExecError::local(502, FailureScope::Transport, "OAuth transport failed")),
103 }
104 }
105
106 async fn json(&self, request: wreq::RequestBuilder) -> Result<Value, ExecError> {
107 let response = request
108 .send()
109 .await
110 .map_err(|_| ExecError::local(502, FailureScope::Transport, "OAuth transport failed"))?;
111 let backoff = if response.status().as_u16() == 429 {
112 Some(refresh_backoff(response.headers()))
113 } else {
114 None
115 };
116 let response = into_response(response).await.map_err(|error| {
119 let text = match oauth_error_code(&error.body) {
120 Some(code) => format!("{HTTP_FAILURE}: {code}"),
121 None => HTTP_FAILURE.to_owned(),
122 };
123 let mut safe = ExecError::local(error.status, error.scope, text);
124 safe.retry_after = backoff.or(error.retry_after);
125 safe
126 })?;
127 match response.body {
128 ResponseBody::Buffered(body) => {
129 serde_json::from_slice(&body).map_err(|_| acquisition_error("invalid Claude OAuth response"))
130 }
131 ResponseBody::Stream(_) => Err(acquisition_error("unexpected OAuth event stream")),
132 }
133 }
134
135 fn request(&self, method: wreq::Method, endpoint: &str) -> Result<wreq::RequestBuilder, ExecError> {
136 let headers = if method == wreq::Method::GET {
137 crate::wire::OAUTH_INSPECT
138 } else {
139 crate::wire::OAUTH_TOKEN
140 };
141 Ok(self
142 .client()?
143 .request(method, endpoint)
144 .redirect(wreq::redirect::Policy::none())
145 .orig_headers(crate::wire::order(headers))
146 .header("accept", "application/json, text/plain, */*")
147 .header("content-type", "application/json")
148 .header("user-agent", "axios/1.15.2")
149 .header("accept-encoding", "gzip, compress, deflate, br")
150 .header("connection", "close"))
151 }
152
153 async fn profile(&self, token: &str) -> Result<Value, ExecError> {
154 self.json(
155 self.request(wreq::Method::GET, &self.profile_url)?
156 .header("authorization", format!("Bearer {token}"))
157 .header("cache-control", "no-cache"),
158 )
159 .await
160 }
161
162 async fn tokens(&self, body: Vec<u8>, previous_refresh: &str, login: bool) -> Result<MetadataPatch, ExecError> {
163 let value = tokio::time::timeout(
164 Duration::from_secs(30),
165 self.json(self.request(wreq::Method::POST, &self.token_url)?.body(body)),
166 )
167 .await
168 .map_err(|_| acquisition_error("Claude token acquisition timed out"))??;
169 let access = value["access_token"]
170 .as_str()
171 .filter(|s| !s.trim().is_empty())
172 .ok_or_else(|| acquisition_error("OAuth response has no access token"))?;
173 let expires = value["expires_in"]
174 .as_i64()
175 .ok_or_else(|| acquisition_error("OAuth response has no expiry"))?;
176 let now = Utc::now();
177 let duration =
178 chrono::Duration::try_seconds(expires).ok_or_else(|| acquisition_error("invalid OAuth expiry"))?;
179 let expiry = now
180 .checked_add_signed(duration)
181 .ok_or_else(|| acquisition_error("invalid OAuth expiry"))?;
182 let refresh = value["refresh_token"]
183 .as_str()
184 .filter(|s| !s.trim().is_empty())
185 .unwrap_or(previous_refresh);
186 let mut patch = MetadataPatch::default();
187 patch.set.insert("access_token".into(), access.into());
188 if !refresh.is_empty() {
189 patch.set.insert("refresh_token".into(), refresh.into());
190 }
191 patch.set.insert("expired".into(), timestamp(expiry).into());
192 patch.set.insert("last_refresh".into(), timestamp(now).into());
193 patch.set.insert("type".into(), "claude".into());
194 if login {
195 copy_nonempty(
196 &mut patch,
197 &value,
198 &[
199 ("/account/uuid", "account_uuid"),
200 ("/account/email_address", "email"),
201 ("/organization/uuid", "organization_uuid"),
202 ("/organization/name", "organization_name"),
203 ],
204 );
205 }
206 if let Ok(Ok(profile)) = tokio::time::timeout(Duration::from_secs(10), self.profile(access)).await {
209 copy_profile(&mut patch, &profile);
210 }
211 if login {
212 let _ = tokio::time::timeout(Duration::from_secs(10), async {
213 self.json(
214 self.request(wreq::Method::GET, &self.roles_url)?
215 .header("authorization", format!("Bearer {access}"))
216 .header("cache-control", "no-cache"),
217 )
218 .await
219 })
220 .await;
221 for field in ["id_token", "email", "refresh_token"] {
222 patch
223 .set
224 .entry(field.to_owned())
225 .or_insert(Value::String(String::new()));
226 }
227 patch.set.insert("claude_device_ids".into(), json!([random_hex(32)?]));
228 }
229 Ok(patch)
230 }
231
232 pub async fn refresh(&self, refresh: &str) -> Result<MetadataPatch, ExecError> {
236 if refresh.is_empty() {
237 return Err(acquisition_error("refresh token is required"));
238 }
239 for attempt in 0..3 {
240 if attempt > 0 {
241 tokio::time::sleep(Duration::from_secs(attempt)).await;
242 }
243 match self.refresh_once(refresh).await {
250 Err(error)
251 if error.status >= 500
252 && error.scope == FailureScope::Credential
253 && error.body.starts_with(HTTP_FAILURE.as_bytes())
254 && attempt < 2 =>
255 {
256 continue;
257 }
258 result => return result,
259 }
260 }
261 unreachable!("third attempt always returns")
262 }
263
264 async fn refresh_once(&self, refresh: &str) -> Result<MetadataPatch, ExecError> {
269 let key: [u8; 32] = Sha256::digest(format!("{}\0{refresh}", self.token_url).as_bytes()).into();
270 let result = {
271 let mut state = refreshes();
272 let now = Instant::now();
273 if let Some(until) = state.blocked.get(&key).copied() {
274 if until > now {
275 let mut error =
276 ExecError::local(429, FailureScope::Credential, "Claude refresh temporarily blocked");
277 error.retry_after = Some(until - now);
278 return Err(error);
279 }
280 state.blocked.remove(&key);
281 }
282 if let Some(result) = state.in_flight.get(&key) {
283 result.clone()
284 } else {
285 let oauth = self.clone();
286 let refresh = refresh.to_owned();
287 let task = tokio::spawn(async move {
289 let body = serde_json::to_vec(&json!({
291 "client_id": CLIENT_ID, "grant_type": "refresh_token",
292 "refresh_token": refresh, "scope": SCOPE,
293 }))
294 .map_err(|_| acquisition_error("cannot encode OAuth request"));
295 let result = match body {
296 Ok(body) => oauth.tokens(body, &refresh, false).await,
297 Err(error) => Err(error),
298 };
299 let mut state = refreshes();
300 state.in_flight.remove(&key);
301 match &result {
302 Ok(_) => {
303 state.blocked.remove(&key);
304 }
305 Err(error) if error.status == 429 => {
306 let wait = error.retry_after.unwrap_or(Duration::from_secs(5));
307 state.blocked.insert(key, Instant::now() + wait);
308 }
309 Err(_) => {}
310 }
311 result
312 });
313 let result = async move {
314 task.await
315 .map_err(|_| acquisition_error("Claude refresh task failed"))?
316 }
317 .boxed()
318 .shared();
319 state.in_flight.insert(key, result.clone());
320 result
321 }
322 };
323 result.await
324 }
325
326 pub async fn exchange(&self, code: &str, state: &str, verifier: &str) -> Result<MetadataPatch, ExecError> {
327 #[derive(Serialize)]
328 struct Exchange<'a> {
329 grant_type: &'a str,
330 code: &'a str,
331 redirect_uri: &'a str,
332 client_id: &'a str,
333 code_verifier: &'a str,
334 state: &'a str,
335 }
336 let mut parts = code.split('#');
337 let code = parts.next().unwrap_or_default();
338 let fragment = parts.next().filter(|s| !s.is_empty()).unwrap_or(state);
339 let body = serde_json::to_vec(&Exchange {
340 grant_type: "authorization_code",
341 code,
342 redirect_uri: REDIRECT_URI,
343 client_id: CLIENT_ID,
344 code_verifier: verifier,
345 state: fragment,
346 })
347 .map_err(|_| acquisition_error("cannot encode OAuth request"))?;
348 self.tokens(body, "", true).await
349 }
350
351 pub(crate) fn via(&self, proxy: &Proxy) -> Self {
352 Self {
353 proxy: proxy.clone(),
354 ..self.clone()
355 }
356 }
357
358 pub(crate) async fn refresh_credential(
361 &self,
362 credential: &Credential,
363 proxy: &Proxy,
364 ) -> Result<MetadataPatch, ExecError> {
365 let token = refresh_token(credential);
366 if token.is_empty() {
367 return Ok(MetadataPatch::default());
368 }
369 self.via(proxy).refresh(token).await
370 }
371
372 pub(crate) async fn prepare(&self, credential: &Credential, proxy: &Proxy) -> Result<MetadataPatch, ExecError> {
378 if needs_identity(credential) {
379 self.via(proxy).prepare_inner(credential).await
380 } else {
381 self.refresh_credential(credential, proxy).await
382 }
383 }
384
385 async fn prepare_inner(&self, credential: &Credential) -> Result<MetadataPatch, ExecError> {
386 let mut patch = MetadataPatch::default();
387 let access = credential.str("access_token").unwrap_or_default().to_owned();
388 if access.contains("sk-ant-oat") {
389 if !canonical_pool(credential.metadata.get("claude_device_ids")) {
390 let device = ensure_device_pool(credential).await?;
391 patch.set.insert("claude_device_ids".into(), json!([device]));
392 }
393 if credential.str("account_uuid").unwrap_or_default().trim().is_empty()
394 && !patch.set.contains_key("account_uuid")
395 {
396 let setup = setup_token(credential);
397 let profile = if setup {
398 None
399 } else {
400 match tokio::time::timeout(Duration::from_secs(10), self.profile(&access)).await {
401 Ok(Ok(profile)) => Some(profile),
402 Ok(Err(error)) if error.status == 403 => None,
403 Ok(Err(error)) => return Err(error),
404 Err(_) => return Err(acquisition_error("Claude profile acquisition timed out")),
405 }
406 };
407 if let Some(profile) = profile {
408 copy_profile(&mut patch, &profile);
409 }
410 if !patch.set.contains_key("account_uuid") {
411 let seed = if credential.id.trim().is_empty() {
412 format!(
413 "{}|{access}",
414 if setup {
415 "claude-setup-token"
416 } else {
417 "claude-oauth-fallback"
418 }
419 )
420 } else {
421 format!("auth-id|{}", credential.id.trim())
422 };
423 let identity = uuid::Uuid::new_v5(
424 &uuid::Uuid::NAMESPACE_OID,
425 format!("cpa-claude-code-cli-account|{seed}").as_bytes(),
426 );
427 patch.set.insert("account_uuid".into(), identity.to_string().into());
428 }
429 patch
430 .set
431 .insert("claude_account_profile_checked_at".into(), timestamp(Utc::now()).into());
432 }
433 }
434 Ok(patch)
435 }
436}
437
438pub(crate) fn needs_prepare(credential: &Credential, now: DateTime<Utc>) -> bool {
440 refresh_due(credential, now) || needs_identity(credential)
441}
442
443pub(crate) fn needs_identity(credential: &Credential) -> bool {
446 credential.str("access_token").is_some_and(|s| s.contains("sk-ant-oat"))
447 && (!canonical_pool(credential.metadata.get("claude_device_ids"))
448 || credential.str("account_uuid").unwrap_or_default().trim().is_empty())
449}
450
451fn refresh_token(credential: &Credential) -> &str {
452 credential
453 .str("refresh_token")
454 .filter(|s| !s.is_empty())
455 .or_else(|| credential.str("refreshToken"))
456 .unwrap_or_default()
457}
458
459fn refresh_due(credential: &Credential, now: DateTime<Utc>) -> bool {
460 !refresh_token(credential).is_empty()
461 && credential
462 .str("expired")
463 .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
464 .is_some_and(|expiry| expiry <= now + chrono::Duration::hours(4))
465}
466
467fn setup_token(credential: &Credential) -> bool {
468 ["skip_account_profile", "is_setup_token", "setup_token"]
469 .iter()
470 .any(|key| credential.metadata.get(*key).and_then(Value::as_bool) == Some(true))
471 || credential
472 .attributes
473 .get("auth_kind")
474 .is_some_and(|s| matches!(s.to_ascii_lowercase().as_str(), "setup_token" | "setup-token"))
475 || credential
476 .str("scopes")
477 .filter(|s| !s.is_empty())
478 .or_else(|| credential.str("scope"))
479 .filter(|s| !s.is_empty())
480 .is_some_and(|s| {
481 let scopes = s.to_ascii_lowercase();
482 !scopes.contains("user:profile") && !scopes.contains("user:office")
483 })
484}
485
486fn copy_nonempty(patch: &mut MetadataPatch, value: &Value, fields: &[(&str, &str)]) {
487 for (pointer, key) in fields {
488 if let Some(s) = value
489 .pointer(pointer)
490 .and_then(Value::as_str)
491 .filter(|s| !s.trim().is_empty())
492 {
493 patch.set.insert((*key).into(), s.into());
494 }
495 }
496}
497
498fn copy_profile(patch: &mut MetadataPatch, profile: &Value) {
499 copy_nonempty(
500 patch,
501 profile,
502 &[
503 ("/account/uuid", "account_uuid"),
504 ("/account/email", "email"),
505 ("/organization/uuid", "organization_uuid"),
506 ("/organization/name", "organization_name"),
507 ],
508 );
509}
510
511fn normalize_pool<'a>(values: impl IntoIterator<Item = &'a str>) -> Option<String> {
514 values
515 .into_iter()
516 .map(|s| s.trim().to_ascii_lowercase())
517 .find(|s| valid_device(s))
518}
519
520async fn ensure_device_pool(credential: &Credential) -> Result<String, ExecError> {
524 let candidate = normalize_pool(
525 credential
526 .metadata
527 .get("claude_device_ids")
528 .and_then(Value::as_array)
529 .into_iter()
530 .flatten()
531 .filter_map(Value::as_str),
532 );
533 match cpa_home::kv::current_client() {
534 Ok(None) => candidate.map_or_else(|| random_hex(32), Ok),
535 Ok(Some(client)) => home_device_pool(&client, credential, candidate).await,
536 Err(error) => Err(pool_error(format!("Home KV client: {error}"))),
537 }
538}
539
540fn pool_error(message: String) -> ExecError {
541 ExecError::local(
542 500,
543 FailureScope::Transport,
544 format!("ensure Claude credential device pool: {message}"),
545 )
546}
547
548async fn home_device_pool(
549 client: &cpa_home::Client,
550 credential: &Credential,
551 candidate: Option<String>,
552) -> Result<String, ExecError> {
553 let mut identity = cpa_core::config::credentials::auth_index(credential).trim().to_owned();
554 if identity.is_empty() {
555 identity = credential.id.trim().to_owned();
556 }
557 if identity.is_empty() {
558 return Err(pool_error("credential identity is empty".into()));
559 }
560 let key = format!(
561 "cpa:claude:credential-device-pool:{}",
562 cpa_home::kv::hash_key_part(&identity)
563 );
564 let encode = |device: &str| format!(r#"["{device}"]"#).into_bytes();
565 let stored = client
566 .kv_get(&key)
567 .await
568 .map_err(|e| pool_error(format!("Home KV get: {e}")))?;
569 if let Some(stored) = stored.and_then(|raw| serde_json::from_slice::<Vec<String>>(&raw).ok())
570 && let Some(device) = normalize_pool(stored.iter().map(String::as_str))
571 {
572 if stored.len() != 1 || stored[0] != device {
574 let options = cpa_home::SetOptions {
575 xx: true,
576 ..Default::default()
577 };
578 let written = client
579 .kv_set(&key, &encode(&device), options)
580 .await
581 .map_err(|e| pool_error(format!("canonicalize Home KV value: {e}")))?;
582 if !written {
583 return Err(pool_error("canonical Home KV value was not written".into()));
584 }
585 }
586 return Ok(device);
587 }
588 let device = match candidate {
589 Some(device) => device,
590 None => random_hex(32)?,
591 };
592 let options = cpa_home::SetOptions {
593 nx: true,
594 ..Default::default()
595 };
596 client
597 .kv_set(&key, &encode(&device), options)
598 .await
599 .map_err(|e| pool_error(format!("Home KV set: {e}")))?;
600 let raw = client
601 .kv_get(&key)
602 .await
603 .map_err(|e| pool_error(format!("Home KV reread: {e}")))?
604 .ok_or_else(|| pool_error("Home KV value missing after set".into()))?;
605 let stored: Vec<String> = serde_json::from_slice(&raw).map_err(|e| {
606 pool_error(format!(
607 "decode Home KV value: {}",
608 cpa_home::error::redacted_decode_text(&e)
609 ))
610 })?;
611 normalize_pool(stored.iter().map(String::as_str))
612 .ok_or_else(|| pool_error("Home KV pool has 0 entries, want 1".into()))
613}
614
615fn valid_device(s: &str) -> bool {
616 s.len() == 64 && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
617}
618
619fn canonical_pool(value: Option<&Value>) -> bool {
620 value
621 .and_then(Value::as_array)
622 .is_some_and(|a| a.len() == 1 && a[0].as_str().is_some_and(valid_device))
623}
624
625pub(crate) fn random_hex(n: usize) -> Result<String, ExecError> {
626 let mut bytes = vec![0; n];
627 getrandom::fill(&mut bytes).map_err(|_| acquisition_error("secure random source unavailable"))?;
628 Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
629}
630
631const HTTP_FAILURE: &str = "Claude OAuth acquisition failed";
633
634fn oauth_error_code(body: &[u8]) -> Option<&'static str> {
637 let value: Value = serde_json::from_slice(body).ok()?;
638 let error = value.get("error")?;
639 known_error_code(error.as_str().or_else(|| error.get("type").and_then(Value::as_str))?)
640}
641
642pub fn known_error_code(code: &str) -> Option<&'static str> {
645 const KNOWN: [&str; 15] = [
646 "invalid_request",
648 "invalid_client",
649 "invalid_grant",
650 "unauthorized_client",
651 "unsupported_grant_type",
652 "invalid_scope",
653 "server_error",
654 "temporarily_unavailable",
655 "invalid_request_error",
657 "authentication_error",
658 "permission_error",
659 "not_found_error",
660 "rate_limit_error",
661 "api_error",
662 "overloaded_error",
663 ];
664 KNOWN.into_iter().find(|known| *known == code)
665}
666
667fn acquisition_error(message: &str) -> ExecError {
668 ExecError::local(502, FailureScope::Credential, message)
669}
670fn refresh_backoff(headers: &http::HeaderMap) -> Duration {
671 let now = std::time::SystemTime::now();
672 let read = |key| headers.get(key).and_then(|v| v.to_str().ok()).map(str::trim);
673 read("retry-after")
674 .and_then(|raw| crate::quota::retry_after(raw, now))
675 .and_then(|deadline| deadline.duration_since(now).ok())
676 .or_else(|| {
677 read("retry-after-ms")
678 .and_then(|raw| raw.parse::<f64>().ok())
679 .and_then(|ms| Duration::try_from_secs_f64(ms / 1000.0).ok())
680 })
681 .unwrap_or(Duration::from_secs(5))
682 .clamp(Duration::from_secs(5), Duration::from_secs(300))
683}
684fn timestamp(time: DateTime<Utc>) -> String {
685 time.to_rfc3339_opts(SecondsFormat::Secs, true)
686}
687
688pub fn pkce() -> Result<(String, String), ExecError> {
690 let mut bytes = [0; 96];
691 getrandom::fill(&mut bytes).map_err(|_| acquisition_error("secure random source unavailable"))?;
692 let verifier = URL_SAFE_NO_PAD.encode(bytes);
693 let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
694 Ok((verifier, challenge))
695}
696
697pub(crate) fn authorize_url(state: &str, challenge: &str) -> String {
698 let mut url = Url::parse("https://claude.ai/oauth/authorize").expect("constant URL");
699 url.query_pairs_mut().extend_pairs([
701 ("client_id", CLIENT_ID),
702 ("code", "true"),
703 ("code_challenge", challenge),
704 ("code_challenge_method", "S256"),
705 ("redirect_uri", REDIRECT_URI),
706 ("response_type", "code"),
707 ("scope", SCOPE),
708 ("state", state),
709 ]);
710 url.into()
711}
712
713#[cfg(test)]
714#[path = "oauth_tests.rs"]
715mod tests;