1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! OAuth refresh and durable rotation handling for vendor subscriptions.
//!
//! When a token read from disk has expired, this module exchanges its
//! `refresh_token` for a fresh access token using the vendor's public OAuth
//! client (the same client ids embedded in each vendor's open-source CLI) and
//! caches the result in memory.
//!
//! Production callers register a recovery-aware store. Any refreshed token is
//! durably persisted there before it can be used; if neither the vendor file
//! nor its recovery sidecar can be committed, serving and diagnostics fail
//! closed. The legacy stateless refresh API still accepts a caller-provided
//! token and cannot provide that transaction guarantee.
//!
//! This is the same behavior `ProxyPal` relies on so the proxy keeps working even
//! when the vendor CLI is not running to refresh its own credential file.
//!
//! Claude is included here too: the runtime container image ships no Claude CLI,
//! so nothing else would keep `~/.claude/.credentials.json` current. The
//! `refreshToken` stored in the nested `claudeAiOauth` block is exchanged the
//! same way.
//!
//! Secrets (access/refresh tokens) are never logged.
use std::collections::HashMap;
use std::sync::Mutex;
use serde::Deserialize;
#[path = "refresh_state.rs"]
mod refresh_state;
use refresh_state::RefreshAttempts;
#[path = "refresh_journal.rs"]
mod refresh_journal;
#[path = "refresh_recovery.rs"]
mod refresh_recovery;
#[path = "refresh_registry.rs"]
mod refresh_registry;
pub use refresh_journal::direct_exchange_shape;
use refresh_journal::{journal_request, journal_response};
use refresh_recovery::{Exchange, RecoveryMode, Rejected, exchange_with_recovery};
use std::sync::Arc;
use crate::credential_store::CredentialStore;
use crate::subscription::{SubscriptionProvider, SubscriptionToken};
/// How a provider's token endpoint expects the refresh request body encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BodyStyle {
/// `application/json` body (Codex / `ChatGPT`).
Json,
/// `application/x-www-form-urlencoded` body (Google, Qwen).
Form,
}
/// Public OAuth refresh parameters for one provider.
#[derive(Debug, Clone, Copy)]
struct RefreshConfig {
token_url: &'static str,
client_id: &'static str,
style: BodyStyle,
}
/// `User-Agent` the Claude Code OAuth provider sends with a refresh.
///
/// Mirrors the published client rather than identifying the router, because the
/// value participates in client attestation at the token endpoint.
pub const CLAUDE_OAUTH_USER_AGENT: &str = "anthropic-sdk-typescript/0.112.1 userOAuthProvider";
pub const ANTHROPIC_SDK_VERSION: &str = "0.112.1";
pub const GEMINI_CLI_VERSION: &str = "0.58.0";
pub const GOOGLE_AUTH_LIBRARY_VERSION: &str = "10.9.0";
pub const QWEN_CODE_VERSION: &str = "0.23.0";
/// Atomic custom Gemini installed-app client override.
pub const GEMINI_CLIENT_ID_ENV: &str = "GEMINI_OAUTH_CLIENT_ID";
pub const GEMINI_CLIENT_SECRET_ENV: &str = "GEMINI_OAUTH_CLIENT_SECRET";
pub const GEMINI_CLIENT_ID: &str =
"681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
pub const GEMINI_CLIENT_SECRET: &str = concat!("GOCSPX-4uHgMPm", "-1o7Sk-geV6Cu5clXFsxl");
pub const GEMINI_AUTH_USER_AGENT: &str = "google-api-nodejs-client/10.9.0";
pub const GEMINI_API_CLIENT: &str = "gl-node/22.14.0";
/// Public OAuth client id of the Claude Code CLI.
///
/// Same value the CLI embeds; used only for the `refresh_token` grant, which
/// needs no client secret.
pub const CLAUDE_CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
/// Anthropic's OAuth token endpoint.
pub const CLAUDE_TOKEN_URL: &str = "https://platform.claude.com/v1/oauth/token";
/// How long before a token's stated expiry it is treated as due for refresh.
///
/// Refreshing reactively — only once a token is already expired — means the
/// request that discovers the expiry has to fail first, and leaves an idle
/// deployment's refresh token sitting unused until it too goes stale
/// (issue #203). Renewing ahead of the failure costs a few minutes of a token's
/// usable life and removes a whole class of mid-flight expiries; five minutes
/// matches what the vendor clients themselves use (issue #239).
const REFRESH_SKEW_MS: i64 = 5 * 60_000;
/// How recently this process must have rotated a credential for a terminal
/// rejection of it to be attributed here rather than to another holder.
///
/// Wider than the grace period: the grace period decides whether to spend a
/// token, while this only decides how the death is explained, and an
/// explanation that is a few minutes stale is still the right one (issue #319).
const ROTATION_ATTRIBUTION_MS: i64 = 60 * 60_000;
/// Refresh parameters for a provider. Every subscription provider now has a
/// public OAuth client, so this is total.
const fn refresh_config(provider: SubscriptionProvider) -> RefreshConfig {
match provider {
// The Claude Code CLI's public OAuth client (no client secret). Lets a
// container renew an expired `~/.claude` token without the CLI.
SubscriptionProvider::Claude => RefreshConfig {
token_url: CLAUDE_TOKEN_URL,
client_id: CLAUDE_CLIENT_ID,
style: BodyStyle::Json,
},
// The Codex CLI's public OAuth client (no client secret).
SubscriptionProvider::Codex => RefreshConfig {
token_url: "https://auth.openai.com/oauth/token",
client_id: "app_EMoamEEZ73f0CkXaXp7hrann",
style: BodyStyle::Json,
},
// Gemini CLI's public installed-app client; both values are deliberately
// embedded by the official client and are not confidential credentials.
SubscriptionProvider::Gemini => RefreshConfig {
token_url: "https://oauth2.googleapis.com/token",
client_id: GEMINI_CLIENT_ID,
style: BodyStyle::Form,
},
// The qwen-code CLI's public OAuth client (no client secret).
SubscriptionProvider::Qwen => RefreshConfig {
token_url: "https://chat.qwen.ai/api/v1/oauth2/token",
client_id: "f0304373b74a44d2b584a3fb70ca9e56",
style: BodyStyle::Form,
},
}
}
fn refresh_headers(provider: SubscriptionProvider) -> Vec<(String, String)> {
match provider {
SubscriptionProvider::Claude => vec![
(
"anthropic-beta".into(),
crate::proxy::OAUTH_BETA_FLAG.into(),
),
("user-agent".into(), CLAUDE_OAUTH_USER_AGENT.into()),
],
SubscriptionProvider::Codex => crate::codex_identity::headers(None)
.iter()
.filter(|(name, _)| name.as_str() != "chatgpt-account-id")
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_string(), value.to_string()))
})
.collect(),
SubscriptionProvider::Gemini => vec![
("x-goog-api-client".into(), GEMINI_API_CLIENT.into()),
("user-agent".into(), GEMINI_AUTH_USER_AGENT.into()),
],
SubscriptionProvider::Qwen => vec![("accept".into(), "application/json".into())],
}
}
fn oauth_client(
provider: SubscriptionProvider,
config: RefreshConfig,
) -> Result<(String, Option<String>), RefreshError> {
oauth_client_from(provider, config, |name| std::env::var(name).ok())
}
fn oauth_client_from(
provider: SubscriptionProvider,
config: RefreshConfig,
lookup: impl Fn(&str) -> Option<String>,
) -> Result<(String, Option<String>), RefreshError> {
if provider != SubscriptionProvider::Gemini {
return Ok((config.client_id.to_string(), None));
}
let custom_id = lookup(GEMINI_CLIENT_ID_ENV).filter(|value| !value.trim().is_empty());
let custom_secret = lookup(GEMINI_CLIENT_SECRET_ENV).filter(|value| !value.trim().is_empty());
match (custom_id, custom_secret) {
(None, None) => Ok((GEMINI_CLIENT_ID.into(), Some(GEMINI_CLIENT_SECRET.into()))),
(Some(id), Some(secret)) => Ok((id, Some(secret))),
_ => Err(RefreshError::Request(format!(
"custom Gemini OAuth client requires both {GEMINI_CLIENT_ID_ENV} and {GEMINI_CLIENT_SECRET_ENV}"
))),
}
}
fn refresh_token_url(provider: SubscriptionProvider) -> String {
#[cfg(debug_assertions)]
if let Ok(url) = std::env::var("LINK_ASSISTANT_ROUTER_TEST_TOKEN_URL") {
return url;
}
refresh_config(provider).token_url.to_string()
}
/// Encode key/value pairs as an `application/x-www-form-urlencoded` body.
///
/// Percent-encodes every byte that is not an unreserved character so OAuth
/// tokens containing `+`, `/`, `=`, or other reserved bytes survive transit.
fn encode_form(pairs: &[(&str, &str)]) -> String {
fn encode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
out.push(byte as char);
} else {
out.push('%');
out.push(
char::from_digit(u32::from(byte >> 4), 16)
.unwrap()
.to_ascii_uppercase(),
);
out.push(
char::from_digit(u32::from(byte & 0x0f), 16)
.unwrap()
.to_ascii_uppercase(),
);
}
}
out
}
pairs
.iter()
.map(|(k, v)| format!("{}={}", encode(k), encode(v)))
.collect::<Vec<_>>()
.join("&")
}
/// The subset of an OAuth token-endpoint response the router consumes.
#[derive(Debug, Deserialize, Default)]
struct RefreshResponse {
access_token: Option<String>,
refresh_token: Option<String>,
expires_in: Option<i64>,
}
/// Errors that can occur while refreshing a subscription token.
pub enum RefreshError {
/// The provider does not support router-driven refresh.
///
/// No provider reports this today — every subscription provider has a
/// public OAuth client — but it is kept so callers matching on this enum
/// keep compiling.
Unsupported,
/// The token had no `refresh_token` to exchange.
NoRefreshToken,
/// The HTTP request to the token endpoint failed.
Request(String),
/// The token endpoint returned a non-success status.
///
/// Carries only a secret-free classification and the `Retry-After` delay
/// in seconds. The response body is discarded immediately after it is
/// classified and can never reach errors, health, doctor, or logs.
Status(u16, RefreshStatusClass, Option<i64>),
/// The response body could not be parsed or lacked an access token.
Parse(String),
/// The refresh transaction could not acquire or durably update its
/// credential store.
Storage(String),
}
impl std::fmt::Debug for RefreshError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unsupported => formatter.write_str("Unsupported"),
Self::NoRefreshToken => formatter.write_str("NoRefreshToken"),
Self::Request(_) => formatter.write_str("Request(transport_failure)"),
Self::Status(code, class, retry_after) => formatter
.debug_tuple("Status")
.field(code)
.field(class)
.field(retry_after)
.finish(),
Self::Parse(_) => formatter.write_str("Parse(invalid_token_response)"),
Self::Storage(_) => formatter.write_str("Storage(persistence_failure)"),
}
}
}
/// Secret-free classification of an OAuth refresh endpoint failure.
///
/// The endpoint body is used only to recognize the small OAuth terminal-error
/// allowlist. Unknown codes, descriptions, and all other response content are
/// deliberately discarded (issue #430).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshStatusClass {
/// The refresh grant is no longer usable.
InvalidGrant,
/// The public OAuth client was rejected.
InvalidClient,
/// The OAuth client is not authorized for this grant.
UnauthorizedClient,
/// The endpoint does not support this refresh grant.
UnsupportedGrantType,
/// The endpoint asked the client to retry later.
RateLimited,
/// Another client-side rejection whose body is not safe to retain.
ClientRejected,
/// A server-side failure that should be retried.
Transient,
/// A non-success response outside the usual client/server ranges.
UnexpectedStatus,
}
impl RefreshStatusClass {
/// Stable, secret-free identifier for diagnostics and machine assertions.
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::InvalidGrant => "invalid_grant",
Self::InvalidClient => "invalid_client",
Self::UnauthorizedClient => "unauthorized_client",
Self::UnsupportedGrantType => "unsupported_grant_type",
Self::RateLimited => "rate_limited",
Self::ClientRejected => "client_rejected",
Self::Transient => "transient",
Self::UnexpectedStatus => "unexpected_status",
}
}
const fn is_terminal(self) -> bool {
matches!(
self,
Self::InvalidGrant
| Self::InvalidClient
| Self::UnauthorizedClient
| Self::UnsupportedGrantType
)
}
}
/// Machine-relevant classification of a failed import refresh-chain check.
///
/// Import callers must know whether the vendor definitely refused the
/// candidate or might already have advanced a rotating chain. The diagnostic
/// text deliberately remains separate so no caller has to parse English to
/// make that availability decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportRefreshFailureKind {
/// No request that could advance the refresh chain was attempted.
NotAttempted,
/// The provider explicitly rejected the refresh token.
ExchangeRejected,
/// The request or response was inconclusive after an exchange was attempted.
ExchangeUncertain,
/// The provider answered successfully, but durable persistence or reread failed.
PersistenceUncertain,
}
/// Secret-free failure returned by classified import validation.
#[derive(Debug)]
pub struct ImportRefreshFailure {
kind: ImportRefreshFailureKind,
message: String,
}
impl ImportRefreshFailure {
pub(super) const fn new(kind: ImportRefreshFailureKind, message: String) -> Self {
Self { kind, message }
}
/// Stable classification for machine-readable import recovery output.
#[must_use]
pub const fn kind(&self) -> ImportRefreshFailureKind {
self.kind
}
}
impl std::fmt::Display for ImportRefreshFailure {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for ImportRefreshFailure {}
/// OAuth error codes that mean the refresh token itself will never work again.
///
/// Deliberately an allowlist rather than a substring search: only these codes,
/// and only under a client-error status, justify telling an operator to
/// re-authenticate (issue #203).
/// The `error` field of an OAuth error response, when the body is one.
///
/// Parsed rather than matched textually so a proxy error page or a success body
/// that merely *mentions* a code cannot be mistaken for the endpoint reporting
/// it. Accepts the nested `{"error": {"type": …}}` shape vendors also use.
#[must_use]
fn oauth_error_code(body: &str) -> Option<String> {
let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
let error = parsed.get("error")?;
if let Some(code) = error.as_str() {
return Some(code.to_string());
}
error
.get("type")
.or_else(|| error.get("code"))
.and_then(serde_json::Value::as_str)
.map(str::to_string)
}
impl RefreshError {
/// Classify a non-success response, retaining no response content.
fn from_status(code: u16, body: &str, retry_after: Option<i64>) -> Self {
let oauth_code = oauth_error_code(body);
let class = match (code, oauth_code.as_deref()) {
(400 | 401 | 403, Some("invalid_grant")) => RefreshStatusClass::InvalidGrant,
(400 | 401 | 403, Some("invalid_client")) => RefreshStatusClass::InvalidClient,
(400 | 401 | 403, Some("unauthorized_client")) => {
RefreshStatusClass::UnauthorizedClient
}
(400 | 401 | 403, Some("unsupported_grant_type")) => {
RefreshStatusClass::UnsupportedGrantType
}
(429, _) => RefreshStatusClass::RateLimited,
(400..=499, _) => RefreshStatusClass::ClientRejected,
(500..=599, _) => RefreshStatusClass::Transient,
_ => RefreshStatusClass::UnexpectedStatus,
};
Self::Status(code, class, retry_after)
}
/// Stable failure class for a token-endpoint response.
#[must_use]
pub const fn status_class(&self) -> Option<RefreshStatusClass> {
match self {
Self::Status(_, class, _) => Some(*class),
_ => None,
}
}
/// Whether the token endpoint rejected the *refresh token itself*.
///
/// True only when a client-error status (`400`, `401`, `403`) is paired
/// with a parsed OAuth error code from a small terminal allowlist. This is
/// the one case waiting cannot fix, so it is the only case that may stop
/// the router from retrying.
///
/// Everything else — `429`, `5xx`, timeouts, connection resets, and any
/// body that merely contains the text `invalid_grant` under an unrelated
/// status — is retryable (issue #203).
#[must_use]
pub const fn is_invalid_grant(&self) -> bool {
matches!(self, Self::Status(_, class, _) if class.is_terminal())
}
/// Whether the endpoint rate-limited this refresh.
///
/// Rate limiting is explicitly *not* terminal: the credential is fine and
/// the correct response is to wait, which is precisely the case the old
/// substring classifier reported as permanently revoked.
#[must_use]
pub const fn is_rate_limited(&self) -> bool {
matches!(self, Self::Status(429, _, _))
}
/// The delay the endpoint asked callers to wait, in milliseconds.
#[must_use]
pub const fn retry_after_ms(&self) -> Option<i64> {
match self {
Self::Status(_, _, Some(seconds)) => Some(seconds.saturating_mul(1_000)),
_ => None,
}
}
}
impl std::fmt::Display for RefreshError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unsupported => write!(f, "provider does not support router-driven refresh"),
Self::NoRefreshToken => write!(f, "no refresh token available"),
Self::Request(_) => write!(
f,
"refresh token endpoint transport failed; it will be retried automatically"
),
Self::Status(code, class, _) if class.is_terminal() => write!(
f,
"refresh credential was rejected (HTTP {code}, class {}) — re-authenticate this \
subscription with `link-assistant-router auth <provider>`; waiting will not \
help",
class.label()
),
// Say plainly that this one *is* recoverable, so the operator is
// not told to re-authenticate over a transient rate limit.
Self::Status(429, _, retry_after) => write!(
f,
"refresh endpoint rate-limited this request (HTTP 429, class rate_limited{}); it \
will be retried automatically and the subscription remains usable",
retry_after.map_or_else(String::new, |seconds| format!(", retry after {seconds}s"))
),
Self::Status(code, RefreshStatusClass::Transient, retry_after) => write!(
f,
"refresh endpoint is temporarily unavailable (HTTP {code}, class transient{}); \
it will be retried automatically",
retry_after.map_or_else(String::new, |seconds| format!(", retry after {seconds}s"))
),
Self::Status(code, class, retry_after) => write!(
f,
"refresh endpoint rejected the request (HTTP {code}, class {}{}); verify the \
provider configuration",
class.label(),
retry_after.map_or_else(String::new, |seconds| format!(", retry after {seconds}s"))
),
Self::Parse(_) => write!(
f,
"refresh response parse error (class invalid_token_response); verify the provider configuration"
),
Self::Storage(_) => write!(
f,
"refresh credential storage failed (class persistence_failure); verify writable credential storage"
),
}
}
}
/// What real upstream calls have said about a credential, as opposed to what
/// its `expiresAt` timestamp claims.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialEvidence {
/// An upstream call succeeded with this credential.
Working,
/// An upstream call rejected this credential (HTTP 401/403).
Rejected,
}
impl std::error::Error for RefreshError {}
/// Merge a refresh-endpoint response into a fresh [`SubscriptionToken`],
/// carrying over routing metadata (`account_id`, `resource_url`) and reusing
/// the previous refresh token when the endpoint did not rotate it.
fn merge_refresh_response(
prev: &SubscriptionToken,
resp: &RefreshResponse,
now_ms: i64,
) -> Result<SubscriptionToken, RefreshError> {
let access_token = resp
.access_token
.clone()
.filter(|s| !s.is_empty())
.ok_or_else(|| RefreshError::Parse("response contained no access_token".to_string()))?;
let expires_at_ms = match resp.expires_in {
None => None,
Some(seconds) if seconds < 0 => {
return Err(RefreshError::Parse(
"response contained a negative expires_in".to_string(),
));
}
Some(seconds) => Some(
seconds
.checked_mul(1_000)
.and_then(|lifetime_ms| now_ms.checked_add(lifetime_ms))
.ok_or_else(|| {
RefreshError::Parse("response expires_in is not representable".to_string())
})?,
),
};
Ok(SubscriptionToken {
access_token,
refresh_token: resp
.refresh_token
.clone()
.filter(|s| !s.is_empty())
.or_else(|| prev.refresh_token.clone()),
expires_at_ms,
account_id: prev.account_id.clone(),
resource_url: prev.resource_url.clone(),
})
}
/// Exchange a token's `refresh_token` for a fresh access token via the
/// provider's public OAuth client. Returns the refreshed token on success.
///
/// # Errors
///
/// Returns [`RefreshError`] when the provider is unsupported, no refresh token
/// is present, the HTTP request fails, the endpoint reports an error status, or
/// the response cannot be parsed.
pub async fn refresh(
client: &reqwest::Client,
provider: SubscriptionProvider,
prev: &SubscriptionToken,
now_ms: i64,
) -> Result<SubscriptionToken, RefreshError> {
let token_url = refresh_token_url(provider);
refresh_at(client, &token_url, provider, prev, now_ms).await
}
/// [`refresh`] against an explicit token endpoint.
///
/// Only the URL is overridden — client id, body encoding, and response
/// handling stay exactly as they are in production, so a test pointing this at
/// a stub server exercises the real request shape.
async fn refresh_at(
client: &reqwest::Client,
token_url: &str,
provider: SubscriptionProvider,
prev: &SubscriptionToken,
now_ms: i64,
) -> Result<SubscriptionToken, RefreshError> {
let config = refresh_config(provider);
let refresh_token = prev
.refresh_token
.as_deref()
.filter(|s| !s.is_empty())
.ok_or(RefreshError::NoRefreshToken)?;
let (client_id, client_secret) = oauth_client(provider, config)?;
let headers = refresh_headers(provider);
let (request, content_type, body_fields) = match config.style {
BodyStyle::Json => {
let mut body = serde_json::json!({
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": client_id,
});
let mut fields = vec!["grant_type", "refresh_token", "client_id"];
if let Some(secret) = client_secret.as_deref() {
body["client_secret"] = serde_json::Value::String(secret.to_string());
fields.push("client_secret");
}
(
client.post(token_url).json(&body),
"application/json",
fields,
)
}
BodyStyle::Form => {
let mut form = vec![
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", client_id.as_str()),
];
if let Some(secret) = client_secret.as_deref() {
form.push(("client_secret", secret));
}
let fields = form.iter().map(|(name, _)| *name).collect();
(
client
.post(token_url)
.header("content-type", "application/x-www-form-urlencoded")
.body(encode_form(&form)),
"application/x-www-form-urlencoded",
fields,
)
}
};
let request = headers.iter().fold(request, |request, (name, value)| {
request.header(name, value)
});
journal_request(provider, token_url, content_type, &headers, &body_fields);
let response = request
.send()
.await
.map_err(|e| RefreshError::Request(e.to_string()))?;
let status = response.status();
if !status.is_success() {
// Read `Retry-After` before the body is consumed, so a rate limit can
// be paced by the vendor's own figure rather than by our backoff alone.
// Reuses the shared parser, which also accepts the HTTP-date form.
let retry_after = crate::request_routing::retry_after_duration(response.headers())
.and_then(|delay| i64::try_from(delay.as_secs()).ok());
let body = response.text().await.unwrap_or_default();
let error = RefreshError::from_status(status.as_u16(), &body, retry_after);
tracing::debug!(
"{provider} token exchange answered HTTP {} (class {})",
status.as_u16(),
error
.status_class()
.map_or("unexpected_status", RefreshStatusClass::label)
);
return Err(error);
}
let body = response
.text()
.await
.map_err(|e| RefreshError::Parse(e.to_string()))?;
let document: serde_json::Value =
serde_json::from_str(&body).map_err(|e| RefreshError::Parse(e.to_string()))?;
journal_response(provider, status.as_u16(), &document);
let parsed: RefreshResponse =
serde_json::from_value(document).map_err(|e| RefreshError::Parse(e.to_string()))?;
merge_refresh_response(prev, &parsed, now_ms)
}
/// Process-wide cache of refreshed subscription tokens, keyed by provider and
/// account. Two subscriptions for the same vendor must never reuse each
/// other's bearer token.
///
/// Registered production subscriptions persist every usable refresh result to
/// their authoritative credential store or recovery sidecar before serving it
/// (issue #239). A dual persistence failure is recorded and fails closed. The
/// legacy stateless methods retain their caller-owned, in-memory behavior.
/// The cache also records what upstreams actually said about each credential,
/// so health decisions can be based on observed behaviour rather than on
/// `expiresAt`.
#[derive(Debug, Default)]
pub struct TokenCache {
inner: Mutex<HashMap<SubscriptionKey, SubscriptionToken>>,
/// Per-subscription refresh state. Each async mutex is held across the
/// exchange so concurrent requests share one attempt.
attempts: RefreshAttempts,
/// Latest observed verdict per provider from real upstream calls.
evidence: Mutex<HashMap<SubscriptionKey, CredentialEvidence>>,
/// Latest refresh failure per provider, cleared by a successful refresh.
refresh_errors: Mutex<HashMap<SubscriptionKey, String>>,
/// Providers whose terminal failure has already been announced.
///
/// The transition healthy -> permanently unauthenticated is one event and
/// deserves one loud record. Re-deriving it every five minutes and logging
/// it at full volume buried the line that mattered under 146 restatements
/// of its consequence (issue #321).
announced_terminal: Mutex<std::collections::HashSet<SubscriptionKey>>,
/// How the last successful refresh was obtained, per provider.
///
/// These OAuth endpoints are undocumented; when a credential recovers only
/// because a newer link was picked up from disk, that fact is worth keeping
/// where diagnostics can read it back (issue #239).
recoveries: Mutex<HashMap<SubscriptionProvider, &'static str>>,
/// Credentials a refresh has already been refused for, per subscription.
///
/// Keyed by account *and* by a fingerprint of the credential that was
/// rejected, so the verdict answers "has this exact chain link been tried
/// and refused?" rather than the weaker "does a refresh token exist?" that
/// let a revoked chain report itself refreshable (issue #245). Storing the
/// fingerprint rather than the token keeps the secret out of this map, and
/// makes the record expire by itself: once another holder rotates the file
/// forward, the fingerprint no longer matches and the account recovers
/// without a restart, which is the rule the ladder already follows (#239).
rejections: crate::refresh_rejections::RejectionRecord,
/// Where each subscription's credential lives, when it is known.
///
/// Without this the cache can only ever reason about the token it was
/// handed, which is what let a rotated credential look revoked and a
/// rotation performed while serving vanish at restart (issue #239).
stores: Mutex<HashMap<SubscriptionKey, Arc<dyn CredentialStore>>>,
/// Vendor clients that may be asked to rotate a credential the router
/// could not (issue #239). Empty unless an operator configured one.
vendor_clis: Mutex<HashMap<SubscriptionKey, Arc<crate::vendor_cli_refresh::VendorCli>>>,
}
/// A subscription is identified by provider *and* account: two accounts of the
/// same vendor must never share a bearer token or a credential file.
type SubscriptionKey = (SubscriptionProvider, String);
#[path = "refresh_cache.rs"]
mod refresh_cache;
/// Fingerprint of a credential's contents, for the durable refusal record.
///
/// Re-exported from the private attempt state so [`crate::refresh_rejections`]
/// identifies a chain link exactly as the in-memory ladder does (issue #245).
#[must_use]
pub(crate) fn credential_fingerprint(credential: &SubscriptionToken) -> [u8; 32] {
refresh_state::credential_fingerprint(credential)
}
#[path = "refresh_evidence.rs"]
mod refresh_evidence;
#[cfg(test)]
#[path = "refresh_test_support.rs"]
pub(crate) mod test_support;
#[cfg(test)]
#[path = "refresh_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "refresh_contract_tests.rs"]
mod contract_tests;
#[cfg(test)]
#[path = "refresh_redaction_tests.rs"]
mod redaction_tests;
#[cfg(test)]
#[path = "refresh_inference_evidence_tests.rs"]
mod inference_evidence_tests;