@@ -43,6 +43,24 @@ const BROWSER_AUTH_TIMEOUT: Duration = Duration::from_secs(60);
4343#[ async_trait]
4444pub trait TokenSource : Send + Sync {
4545 async fn bearer ( & self ) -> Result < String , AgentError > ;
46+
47+ /// Force a fresh bearer after the server rejected the current one (401).
48+ ///
49+ /// `rejected` is the exact access token that just got the 401. Unlike
50+ /// [`bearer`](Self::bearer), which trusts the local expiry clock, this is
51+ /// driven by the server's verdict: the cached token looked valid to us
52+ /// (well within its local expiry) but the provider rejected it — clock
53+ /// skew, server-side revocation, or a node that never saw it. The clock
54+ /// therefore can't decide whether to refresh; the caller passes the
55+ /// rejected token so the impl can refresh unless a concurrent caller has
56+ /// *already* replaced it. Implementations must obtain a new token without
57+ /// any interactive step, so a headless harness never hangs. The default
58+ /// returns the existing bearer — correct for sources that can't refresh
59+ /// (a static key); the caller's retry then fails terminally rather than
60+ /// looping.
61+ async fn refresh_now ( & self , _rejected : & str ) -> Result < String , AgentError > {
62+ self . bearer ( ) . await
63+ }
4664}
4765
4866/// A token that never changes for the life of the process.
@@ -219,17 +237,28 @@ impl TokenSource for PkceOAuthTokenSource {
219237 async fn bearer ( & self ) -> Result < String , AgentError > {
220238 let mut state = self . state . lock ( ) . await ;
221239
222- // 1. Cache hit, still fresh.
240+ // 1. In-memory cache hit, still fresh.
223241 if let Some ( tok) = state. as_ref ( ) {
224242 if !is_expired ( tok) {
225243 return Ok ( tok. access_token . clone ( ) ) ;
226244 }
227245 }
228246
229- // 2. Cache hit, expired, but we have a refresh token.
247+ // 2. Re-read disk — another process may have refreshed already.
248+ if let Some ( disk_tok) = read_cache ( & self . cache_path ) {
249+ if !is_expired ( & disk_tok) {
250+ let bearer = disk_tok. access_token . clone ( ) ;
251+ * state = Some ( disk_tok) ;
252+ return Ok ( bearer) ;
253+ }
254+ }
255+
256+ // 3. Try refresh if we have a refresh token. Discover endpoints once
257+ // here — deliberately hoisted above the refresh-token check so the
258+ // browser flow at step 5 (which also needs them) reuses this call.
259+ let endpoints = self . endpoints ( ) . await ?;
230260 let refresh = state. as_ref ( ) . and_then ( |t| t. refresh_token . clone ( ) ) ;
231261 if let Some ( rt) = refresh {
232- let endpoints = self . endpoints ( ) . await ?;
233262 match self . refresh ( & endpoints, & rt) . await {
234263 Ok ( fresh) => {
235264 let bearer = fresh. access_token . clone ( ) ;
@@ -240,15 +269,79 @@ impl TokenSource for PkceOAuthTokenSource {
240269 tracing:: warn!( error = %e, "oauth refresh failed; falling back to browser flow" ) ;
241270 }
242271 }
272+
273+ // 4. Re-read disk after refresh failure — another process may have won the race.
274+ if let Some ( disk_tok) = read_cache ( & self . cache_path ) {
275+ if !is_expired ( & disk_tok) {
276+ let bearer = disk_tok. access_token . clone ( ) ;
277+ * state = Some ( disk_tok) ;
278+ return Ok ( bearer) ;
279+ }
280+ }
243281 }
244282
245- // 3. No usable cache: full browser dance.
246- let endpoints = self . endpoints ( ) . await ?;
283+ // 5. No usable cache: full browser dance.
247284 let fresh = browser_pkce_flow ( & self . http , & self . cfg , & endpoints) . await ?;
248285 let bearer = fresh. access_token . clone ( ) ;
249286 self . save ( & mut state, fresh) ?;
250287 Ok ( bearer)
251288 }
289+
290+ /// Force-refresh after a 401, never touching the browser flow.
291+ ///
292+ /// `rejected` is the access token the server just 401'd. Coalescing keys
293+ /// off token *identity*, not the expiry clock: a 401 means the token was
294+ /// rejected while it still looked locally fresh, so `is_expired()` would
295+ /// say "keep it" and no grant would ever run. Instead, under the lock we
296+ /// compare the current cached token to `rejected` — if they differ, a
297+ /// concurrent caller (this process or a sibling) already refreshed, so we
298+ /// return the new token without burning a second grant. If they still
299+ /// match, this is the rejected token and we run the refresh-token grant
300+ /// unconditionally. The whole check→refresh→save runs under one lock hold
301+ /// so concurrent callers serialize. On any failure the refresh token is
302+ /// preserved (never nulled) and the error is terminal `LlmAuth` — no
303+ /// browser, no hang.
304+ async fn refresh_now ( & self , rejected : & str ) -> Result < String , AgentError > {
305+ let mut state = self . state . lock ( ) . await ;
306+
307+ // 1. Coalesce by identity: if the cached token (in-memory, then disk)
308+ // is no longer the one the server rejected, someone already
309+ // refreshed it. Return that instead of grabbing another grant.
310+ if let Some ( tok) = state. as_ref ( ) {
311+ if tok. access_token != rejected {
312+ return Ok ( tok. access_token . clone ( ) ) ;
313+ }
314+ }
315+ if let Some ( disk_tok) = read_cache ( & self . cache_path ) {
316+ if disk_tok. access_token != rejected {
317+ let bearer = disk_tok. access_token . clone ( ) ;
318+ * state = Some ( disk_tok) ;
319+ return Ok ( bearer) ;
320+ }
321+ }
322+
323+ // 2. The cached token is still the rejected one. Run the refresh-token
324+ // grant unconditionally — the expiry clock can't be trusted here, a
325+ // locally-fresh token is exactly what got 401'd.
326+ let refresh = state. as_ref ( ) . and_then ( |t| t. refresh_token . clone ( ) ) ;
327+ let Some ( rt) = refresh else {
328+ return Err ( AgentError :: LlmAuth (
329+ "token rejected and no refresh token available" . into ( ) ,
330+ ) ) ;
331+ } ;
332+ let endpoints = self . endpoints ( ) . await ?;
333+ match self . refresh ( & endpoints, & rt) . await {
334+ Ok ( fresh) => {
335+ let bearer = fresh. access_token . clone ( ) ;
336+ self . save ( & mut state, fresh) ?;
337+ Ok ( bearer)
338+ }
339+ // 3. Refresh token is itself dead. Terminal — surfacing LlmAuth
340+ // stops the retry loop instead of falling to the browser flow,
341+ // which would hang a headless harness.
342+ Err ( e) => Err ( AgentError :: LlmAuth ( format ! ( "token refresh failed: {e}" ) ) ) ,
343+ }
344+ }
252345}
253346
254347// ---- helpers -------------------------------------------------------------
@@ -549,4 +642,88 @@ mod tests {
549642 let v: Value = serde_json:: from_str ( r#"{"access_token":""}"# ) . unwrap ( ) ;
550643 assert ! ( token_from_response( & v, None ) . is_err( ) ) ;
551644 }
645+
646+ #[ tokio:: test]
647+ async fn test_bearer_reuses_disk_token_after_expiry ( ) {
648+ let dir = tempfile:: tempdir ( ) . unwrap ( ) ;
649+ let cfg = PkceOAuthConfig {
650+ discovery_url : "https://example.com/.well-known" . into ( ) ,
651+ client_id : "test-client" . into ( ) ,
652+ scopes : vec ! [ "offline_access" . into( ) ] ,
653+ cache_namespace : "test" . into ( ) ,
654+ cache_dir_override : Some ( dir. path ( ) . to_path_buf ( ) ) ,
655+ } ;
656+ let source = PkceOAuthTokenSource :: new ( cfg) . unwrap ( ) ;
657+
658+ // Expire the in-memory state.
659+ {
660+ let mut state = source. state . lock ( ) . await ;
661+ * state = Some ( CachedToken {
662+ access_token : "stale" . into ( ) ,
663+ refresh_token : None ,
664+ expires_at : Some ( 0 ) , // long expired
665+ } ) ;
666+ }
667+
668+ // Write a valid token to disk (simulating another process refreshing).
669+ let future_exp = SystemTime :: now ( )
670+ . duration_since ( UNIX_EPOCH )
671+ . unwrap ( )
672+ . as_secs ( )
673+ + 7200 ;
674+ let fresh_token = CachedToken {
675+ access_token : "fresh-from-disk" . into ( ) ,
676+ refresh_token : Some ( "rt" . into ( ) ) ,
677+ expires_at : Some ( future_exp) ,
678+ } ;
679+ let body = serde_json:: to_vec_pretty ( & fresh_token) . unwrap ( ) ;
680+ fs:: write ( & source. cache_path , & body) . unwrap ( ) ;
681+
682+ // bearer() should pick up the disk token without any network call.
683+ let result = source. bearer ( ) . await . unwrap ( ) ;
684+ assert_eq ! ( result, "fresh-from-disk" ) ;
685+ }
686+
687+ #[ tokio:: test]
688+ async fn test_bearer_falls_through_to_browser_when_disk_also_expired ( ) {
689+ let dir = tempfile:: tempdir ( ) . unwrap ( ) ;
690+ let cfg = PkceOAuthConfig {
691+ discovery_url : "https://example.com/.well-known" . into ( ) ,
692+ client_id : "test-client" . into ( ) ,
693+ scopes : vec ! [ "offline_access" . into( ) ] ,
694+ cache_namespace : "test" . into ( ) ,
695+ cache_dir_override : Some ( dir. path ( ) . to_path_buf ( ) ) ,
696+ } ;
697+ let source = PkceOAuthTokenSource :: new ( cfg) . unwrap ( ) ;
698+
699+ // Expire the in-memory state.
700+ {
701+ let mut state = source. state . lock ( ) . await ;
702+ * state = Some ( CachedToken {
703+ access_token : "stale" . into ( ) ,
704+ refresh_token : None ,
705+ expires_at : Some ( 0 ) ,
706+ } ) ;
707+ }
708+
709+ // Write an expired token to disk too.
710+ let expired_token = CachedToken {
711+ access_token : "also-stale" . into ( ) ,
712+ refresh_token : None ,
713+ expires_at : Some ( 0 ) ,
714+ } ;
715+ let body = serde_json:: to_vec_pretty ( & expired_token) . unwrap ( ) ;
716+ fs:: write ( & source. cache_path , & body) . unwrap ( ) ;
717+
718+ // bearer() should fall through past the disk check.
719+ // It will fail at the endpoints() discovery call since there's no server,
720+ // which proves it didn't short-circuit on the expired disk token.
721+ let result = source. bearer ( ) . await ;
722+ assert ! ( result. is_err( ) ) ;
723+ let err_msg = format ! ( "{}" , result. unwrap_err( ) ) ;
724+ assert ! (
725+ err_msg. contains( "oauth discovery" ) ,
726+ "expected discovery error, got: {err_msg}"
727+ ) ;
728+ }
552729}
0 commit comments