mirror of
https://github.com/outbackdingo/optimclaw.git
synced 2026-08-25 14:53:34 +00:00
fix(llm): persist refreshed Anthropic OAuth token after Keychain re-read (#1213)
* fix(llm): persist refreshed Anthropic OAuth token after Keychain re-read (#1136) The Anthropic OAuth provider stored its token as an immutable SecretString. When a 401 triggered a Keychain re-read, the fresh token was used for a single retry but never persisted — every subsequent request reused the expired original token, causing repeated auth failures. Changes: - Wrap token in RwLock<SecretString> so it can be updated after refresh - Persist refreshed token via update_token() on successful retry - Add 500ms delay before Keychain re-read to give Claude Code time to complete its async token refresh write (reduces race window) - Add regression test verifying token updates persist across reads Closes #1136 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * style: fix formatting Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
58a3eb1366
commit
9e41b8acea
@@ -34,7 +34,9 @@ const DEFAULT_MAX_TOKENS: u32 = 8192;
|
||||
/// Anthropic provider using OAuth Bearer authentication.
|
||||
pub struct AnthropicOAuthProvider {
|
||||
client: Client,
|
||||
token: SecretString,
|
||||
/// OAuth token, wrapped in RwLock so it can be updated after a successful
|
||||
/// Keychain refresh (fixes #1136: stale token reuse after expiry).
|
||||
token: std::sync::RwLock<SecretString>,
|
||||
model: String,
|
||||
base_url: Option<String>,
|
||||
active_model: std::sync::RwLock<String>,
|
||||
@@ -71,7 +73,7 @@ impl AnthropicOAuthProvider {
|
||||
|
||||
Ok(Self {
|
||||
client,
|
||||
token,
|
||||
token: std::sync::RwLock::new(token),
|
||||
model: config.model.clone(),
|
||||
base_url,
|
||||
active_model,
|
||||
@@ -98,6 +100,22 @@ impl AnthropicOAuthProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the current token from the RwLock.
|
||||
fn current_token(&self) -> String {
|
||||
match self.token.read() {
|
||||
Ok(guard) => guard.expose_secret().to_string(),
|
||||
Err(poisoned) => poisoned.into_inner().expose_secret().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the stored token after a successful Keychain refresh.
|
||||
fn update_token(&self, new_token: SecretString) {
|
||||
match self.token.write() {
|
||||
Ok(mut guard) => *guard = new_token,
|
||||
Err(poisoned) => *poisoned.into_inner() = new_token,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_request<R: for<'de> Deserialize<'de>>(
|
||||
&self,
|
||||
body: &AnthropicRequest,
|
||||
@@ -109,7 +127,7 @@ impl AnthropicOAuthProvider {
|
||||
let response = self
|
||||
.client
|
||||
.post(&url)
|
||||
.bearer_auth(self.token.expose_secret())
|
||||
.bearer_auth(self.current_token())
|
||||
.header("anthropic-version", ANTHROPIC_API_VERSION)
|
||||
.header("anthropic-beta", ANTHROPIC_OAUTH_BETA)
|
||||
.header("Content-Type", "application/json")
|
||||
@@ -141,6 +159,11 @@ impl AnthropicOAuthProvider {
|
||||
// OAuth tokens from `claude login` expire in ~8-12h. Attempt
|
||||
// to re-extract a fresh token from the OS credential store
|
||||
// (macOS Keychain / Linux credentials file) before giving up.
|
||||
//
|
||||
// Brief delay to give Claude Code time to complete its async
|
||||
// Keychain refresh write (fixes race in #1136).
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
|
||||
if let Some(fresh) = crate::config::ClaudeCodeConfig::extract_oauth_token() {
|
||||
let fresh_token = SecretString::from(fresh);
|
||||
// Retry once with the refreshed token
|
||||
@@ -159,6 +182,11 @@ impl AnthropicOAuthProvider {
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
if retry.status().is_success() {
|
||||
// Persist the refreshed token so subsequent requests
|
||||
// don't hit 401 again (fixes #1136).
|
||||
self.update_token(fresh_token);
|
||||
tracing::info!("Anthropic OAuth token refreshed from credential store");
|
||||
|
||||
let text = retry.text().await.map_err(|e| LlmError::RequestFailed {
|
||||
provider: "anthropic_oauth".to_string(),
|
||||
reason: format!("Failed to read response body: {}", e),
|
||||
@@ -659,4 +687,22 @@ mod tests {
|
||||
assert_eq!(tool_calls.len(), 1);
|
||||
assert_eq!(tool_calls[0].name, "search");
|
||||
}
|
||||
|
||||
/// Regression test for #1136: token field must be mutable via RwLock
|
||||
/// so that a refreshed token persists across subsequent requests.
|
||||
#[test]
|
||||
fn test_token_update_persists() {
|
||||
let original = SecretString::from("old_token".to_string());
|
||||
let token = std::sync::RwLock::new(original);
|
||||
|
||||
// Read the original
|
||||
assert_eq!(token.read().unwrap().expose_secret(), "old_token");
|
||||
|
||||
// Simulate a successful refresh
|
||||
let refreshed = SecretString::from("new_token".to_string());
|
||||
*token.write().unwrap() = refreshed;
|
||||
|
||||
// Subsequent reads see the updated token
|
||||
assert_eq!(token.read().unwrap().expose_secret(), "new_token");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user