feat: support config-driven OAuth endpoints on the claude client

- ClaudeConfig gains an oauth: block (custom endpoints, e.g. a private
  gateway); without it, auth: oauth keeps the stock Claude Pro/Max provider
- Claude-Code system-prefix spoof + anthropic-beta header are only sent on
  the stock provider path
- OAuth tokens are stamped with an issuer fingerprint (token_url|client_id)
  so switching endpoints never replays a token against the wrong issuer
- All auth flows refresh the in-memory access-token cache on save, so
  .authenticate mid-session takes effect immediately
- A custom oauth: block now requires api_base: refusing to silently fall
  back to api.anthropic.com prevents sending a gateway token to the wrong
  host
This commit is contained in:
Dark-Alex-17 committed 2026-09-15 23:51:51 -06:00
1 parent fcc0049ab2
commit 4cc5563ba8
4 files changed
+798 -31

No files matched your search

+14
View File
@@ -385,6 +385,20 @@ clients:
auth: null # When set to 'oauth', Coyote will use OAuth instead of an API key auth: null # When set to 'oauth', Coyote will use OAuth instead of an API key
# Authenticate with `coyote --authenticate` or `.authenticate` in the REPL # Authenticate with `coyote --authenticate` or `.authenticate` in the REPL
prompt_cache: true # Optional - enable Anthropic prompt caching (default: true) prompt_cache: true # Optional - enable Anthropic prompt caching (default: true)
# Optional: custom OAuth endpoints (e.g. a private gateway). Requires `auth: oauth` above.
# With `auth: oauth` and no `oauth:` block you get the stock Claude Pro/Max provider; adding
# `oauth:` switches to generic OAuth against your endpoints (the Claude-Code system-prefix
# and anthropic-beta header are not sent). An `oauth:` block makes `api_base` REQUIRED —
# Coyote refuses to fall back to api.anthropic.com with a gateway token.
# auth: oauth
# api_base: https://gateway.example/anthropic/v1
# oauth:
# client_id: '{{GATEWAY_CLIENT_ID}}'
# device_authorization_url: https://auth.gateway.example/oauth/device_authorization
# token_url: https://auth.gateway.example/oauth/token
# flow: device_code
# scopes: [claude.chat]
# resource: https://gateway.example/v1
# See https://docs.mistral.ai/ # See https://docs.mistral.ai/
- type: openai-compatible - type: openai-compatible
+329 -12
View File
@@ -2,13 +2,12 @@ use std::collections::HashSet;
use std::mem; use std::mem;
use super::access_token::get_access_token; use super::access_token::get_access_token;
use super::claude_oauth::ClaudeOAuthProvider; use super::oauth::{self, OAuthConfig};
use super::oauth::{self, OAuthProvider};
use super::*; use super::*;
use crate::utils::strip_think_tag; use crate::utils::strip_think_tag;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, anyhow, bail};
use reqwest::{Client as ReqwestClient, RequestBuilder}; use reqwest::{Client as ReqwestClient, RequestBuilder};
use serde::Deserialize; use serde::Deserialize;
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -22,6 +21,7 @@ pub struct ClaudeConfig {
pub api_key: Option<String>, pub api_key: Option<String>,
pub api_base: Option<String>, pub api_base: Option<String>,
pub auth: Option<String>, pub auth: Option<String>,
pub oauth: Option<Box<OAuthConfig>>,
#[serde(default)] #[serde(default)]
pub models: Vec<ModelData>, pub models: Vec<ModelData>,
pub prompt_cache: Option<bool>, pub prompt_cache: Option<bool>,
@@ -71,9 +71,7 @@ async fn prepare_chat_completions(
client: &ReqwestClient, client: &ReqwestClient,
data: ChatCompletionsData, data: ChatCompletionsData,
) -> Result<RequestData> { ) -> Result<RequestData> {
let api_base = self_ let api_base = resolve_api_base(self_)?;
.get_api_base()
.unwrap_or_else(|_| API_BASE.to_string());
let url = format!("{}/messages", api_base.trim_end_matches('/')); let url = format!("{}/messages", api_base.trim_end_matches('/'));
let body = claude_build_chat_completions_body( let body = claude_build_chat_completions_body(
@@ -88,22 +86,46 @@ async fn prepare_chat_completions(
let uses_oauth = self_.config.auth.as_deref() == Some("oauth"); let uses_oauth = self_.config.auth.as_deref() == Some("oauth");
if !uses_oauth && self_.config.oauth.is_some() {
bail!(
"'{}' has an `oauth:` block configured but `auth: oauth` is not set; the oauth block would be ignored. Set `auth: oauth` (and run 'coyote --authenticate {}') or remove the oauth block.",
self_.name(),
self_.name()
);
}
if uses_oauth { if uses_oauth {
let provider = ClaudeOAuthProvider; let client_name = self_.name();
let ready = oauth::prepare_oauth_access_token(client, &provider, self_.name()).await?; let app_config = self_.app_config();
let cc = app_config
.clients
.iter()
.find(|cc| {
matches!(
cc,
ClientConfig::ClaudeConfig(c)
if c.name.as_deref().unwrap_or(ClaudeClient::NAME) == client_name
)
})
.ok_or_else(|| anyhow!("Could not locate ClientConfig entry for '{}'", client_name))?;
let (provider, uses_stock_provider) =
oauth::claude_oauth_provider_for_client(cc, &ALL_PROVIDER_MODELS);
let ready = oauth::prepare_oauth_access_token(client, &*provider, client_name).await?;
if !ready { if !ready {
bail!( bail!(
"OAuth configured but no tokens found for '{}'. Run: 'coyote --authenticate {}' or '.authenticate' in the REPL", "OAuth configured but no tokens found for '{}'. Run: 'coyote --authenticate {}' or '.authenticate' in the REPL",
self_.name(), client_name,
self_.name() client_name
); );
} }
let token = get_access_token(self_.name())?; let token = get_access_token(client_name)?;
request_data.bearer_auth(token); request_data.bearer_auth(token);
for (key, value) in provider.extra_request_headers() { for (key, value) in provider.extra_request_headers() {
request_data.header(key, value); request_data.header(key, value);
} }
inject_oauth_system_prompt(&mut request_data.body); if uses_stock_provider {
inject_oauth_system_prompt(&mut request_data.body);
}
} else if let Ok(api_key) = self_.get_api_key() { } else if let Ok(api_key) = self_.get_api_key() {
request_data.header("x-api-key", api_key); request_data.header("x-api-key", api_key);
} else { } else {
@@ -117,6 +139,21 @@ async fn prepare_chat_completions(
Ok(request_data) Ok(request_data)
} }
/// A config-driven `oauth:` block requires an explicit `api_base`; the stock fallback would send
/// the oauth token to the wrong host.
fn resolve_api_base(self_: &ClaudeClient) -> Result<String> {
match self_.get_api_base() {
Ok(api_base) => Ok(api_base),
Err(_) if self_.config.oauth.is_none() => Ok(API_BASE.to_string()),
Err(_) => bail!(
"'{}' has a custom `oauth:` block but no `api_base`; refusing to fall back to {} (the oauth token would be sent to the wrong host). Set `api_base` on the '{}' client entry.",
self_.name(),
API_BASE,
self_.name()
),
}
}
/// Anthropic requires OAuth-authenticated requests to include a Claude Code /// Anthropic requires OAuth-authenticated requests to include a Claude Code
/// system prompt prefix in order to consider a request body as "valid". /// system prompt prefix in order to consider a request body as "valid".
/// ///
@@ -632,7 +669,11 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::client::access_token::set_access_token;
use crate::config::AppConfig;
use crate::function::{FunctionDeclaration, ToolCall, ToolResult}; use crate::function::{FunctionDeclaration, ToolCall, ToolResult};
use chrono::Utc;
use std::sync::Arc;
fn tool_result(id: &str, text: Option<&str>) -> ToolResult { fn tool_result(id: &str, text: Option<&str>) -> ToolResult {
ToolResult { ToolResult {
@@ -905,4 +946,280 @@ mod tests {
assert_eq!(usage.cache_creation_input_tokens, Some(100)); assert_eq!(usage.cache_creation_input_tokens, Some(100));
assert_eq!(usage.cache_read_input_tokens, Some(200)); assert_eq!(usage.cache_read_input_tokens, Some(200));
} }
fn claude_config(name: &str, auth: Option<&str>, oauth: Option<OAuthConfig>) -> ClaudeConfig {
ClaudeConfig {
name: Some(name.into()),
api_key: None,
api_base: oauth.as_ref().map(|_| "https://gateway.example/v1".to_string()),
auth: auth.map(str::to_string),
oauth: oauth.map(Box::new),
models: vec![],
prompt_cache: None,
patch: None,
extra: None,
}
}
fn minimal_oauth_config() -> OAuthConfig {
serde_yaml::from_str("client_id: gateway\ntoken_url: https://gateway.example/token")
.unwrap()
}
fn make_client(config: ClaudeConfig, clients: Vec<ClientConfig>) -> ClaudeClient {
ClaudeClient {
app_config: Arc::new(AppConfig {
clients,
..AppConfig::default()
}),
config,
model: Model::new("claude", "claude-test"),
}
}
fn prepare(client: &ClaudeClient) -> Result<RequestData> {
let data = ChatCompletionsData {
messages: vec![Message::new(
MessageRole::User,
MessageContent::Text("hello".to_string()),
)],
temperature: None,
top_p: None,
reasoning_effort: None,
functions: None,
stream: false,
};
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(prepare_chat_completions(
client,
&ReqwestClient::new(),
data,
))
}
#[test]
fn oauth_stock_provider_applies_claude_code_spoof() {
let name = "claude-gate-stock-test";
let config = claude_config(name, Some("oauth"), None);
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
set_access_token(name, "stock-at".into(), Utc::now().timestamp() + 3600, None);
let request_data = prepare(&client).unwrap();
assert_eq!(
request_data
.headers
.get("authorization")
.map(String::as_str),
Some("Bearer stock-at")
);
assert_eq!(
request_data
.headers
.get("anthropic-beta")
.map(String::as_str),
Some("oauth-2025-04-20")
);
assert_eq!(request_data.body["system"][0]["text"], CLAUDE_CODE_PREFIX);
}
#[test]
fn oauth_config_provider_skips_claude_code_spoof() {
let name = "claude-gate-gateway-test";
let config = claude_config(name, Some("oauth"), Some(minimal_oauth_config()));
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
set_access_token(name, "gateway-at".into(), Utc::now().timestamp() + 3600, None);
let request_data = prepare(&client).unwrap();
assert_eq!(
request_data
.headers
.get("authorization")
.map(String::as_str),
Some("Bearer gateway-at")
);
assert!(
!request_data.headers.contains_key("anthropic-beta"),
"headers: {:?}",
request_data.headers
);
assert!(
request_data.body.get("system").is_none(),
"body: {}",
request_data.body
);
}
#[test]
fn api_key_auth_sets_x_api_key_without_spoof() {
let name = "claude-gate-apikey-test";
let mut config = claude_config(name, None, None);
config.api_key = Some("sk-test".into());
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
let request_data = prepare(&client).unwrap();
assert_eq!(
request_data.headers.get("x-api-key").map(String::as_str),
Some("sk-test")
);
assert!(!request_data.headers.contains_key("authorization"));
assert!(!request_data.headers.contains_key("anthropic-beta"));
assert!(
request_data.body.get("system").is_none(),
"body: {}",
request_data.body
);
}
#[test]
fn oauth_block_without_auth_oauth_is_rejected() {
let name = "claude-gate-contradiction-test";
let mut config = claude_config(name, None, Some(minimal_oauth_config()));
config.api_key = Some("sk-test".into());
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
let err = match prepare(&client) {
Ok(_) => panic!("expected the contradictory config to be rejected"),
Err(err) => err.to_string(),
};
assert!(
err.contains("has an `oauth:` block configured but `auth: oauth` is not set"),
"unexpected error: {err}"
);
}
#[test]
fn oauth_block_without_api_base_is_rejected() {
let name = "claude-gate-apibase-missing-test";
let mut config = claude_config(name, Some("oauth"), Some(minimal_oauth_config()));
config.api_base = None;
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
let err = resolve_api_base(&client).unwrap_err().to_string();
assert!(
err.contains(name) && err.contains("refusing to fall back"),
"unexpected error: {err}"
);
}
#[test]
fn oauth_block_with_api_base_resolves_it() {
let name = "claude-gate-apibase-set-test";
let config = claude_config(name, Some("oauth"), Some(minimal_oauth_config()));
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
let api_base = resolve_api_base(&client).unwrap();
assert_eq!(api_base, "https://gateway.example/v1");
}
#[test]
fn no_oauth_block_falls_back_to_stock_api_base() {
let name = "claude-gate-apibase-fallback-test";
let config = claude_config(name, None, None);
let client = make_client(config.clone(), vec![ClientConfig::ClaudeConfig(config)]);
let api_base = resolve_api_base(&client).unwrap();
assert_eq!(api_base, API_BASE);
}
#[test]
fn oauth_lookup_resolves_entry_matching_client_name() {
let name = "claude-gate-lookup-test";
// The sibling entry resolves to the stock provider; if the lookup
// ignored the name it would apply the Claude Code spoof here.
let sibling = claude_config("claude-gate-lookup-sibling-test", Some("oauth"), None);
let config = claude_config(name, Some("oauth"), Some(minimal_oauth_config()));
let client = make_client(
config.clone(),
vec![
ClientConfig::ClaudeConfig(sibling),
ClientConfig::ClaudeConfig(config),
],
);
set_access_token(name, "lookup-at".into(), Utc::now().timestamp() + 3600, None);
let request_data = prepare(&client).unwrap();
assert_eq!(
request_data
.headers
.get("authorization")
.map(String::as_str),
Some("Bearer lookup-at")
);
assert!(!request_data.headers.contains_key("anthropic-beta"));
assert!(request_data.body.get("system").is_none());
}
#[test]
fn oauth_lookup_falls_back_to_default_name_for_unnamed_entry() {
// An entry with `name: None` must match a client named "claude" via
// the `unwrap_or(ClaudeClient::NAME)` fallback.
let sibling = claude_config("claude-gate-fallback-sibling-test", Some("oauth"), None);
let mut config = claude_config("ignored", Some("oauth"), Some(minimal_oauth_config()));
config.name = None;
let client = make_client(
config.clone(),
vec![
ClientConfig::ClaudeConfig(sibling),
ClientConfig::ClaudeConfig(config),
],
);
set_access_token(
ClaudeClient::NAME,
"fallback-at".into(),
Utc::now().timestamp() + 3600,
None,
);
let request_data = prepare(&client).unwrap();
assert_eq!(
request_data
.headers
.get("authorization")
.map(String::as_str),
Some("Bearer fallback-at")
);
assert!(!request_data.headers.contains_key("anthropic-beta"));
assert!(request_data.body.get("system").is_none());
}
#[test]
fn oauth_lookup_errors_when_config_entry_missing() {
let config = claude_config("claude-gate-missing-test", Some("oauth"), None);
let client = make_client(config, vec![]);
let err = match prepare(&client) {
Ok(_) => panic!("expected the lookup to fail"),
Err(err) => err.to_string(),
};
assert!(
err.contains("Could not locate ClientConfig entry"),
"unexpected error: {err}"
);
}
#[test]
fn shipped_catalog_resolves_stock_claude_provider() {
let cc = ClientConfig::ClaudeConfig(claude_config("claude", Some("oauth"), None));
let bundled: Vec<ProviderModels> = serde_yaml::from_str(MODELS_YAML).unwrap();
let (_, is_stock) = oauth::claude_oauth_provider_for_client(&cc, &bundled);
assert!(
is_stock,
"bundled models.yaml must not carry a claude oauth block: it would silently drop the Claude Code spoof for stock Pro/Max users"
);
}
} }
+450 -19
View File
@@ -211,6 +211,9 @@ pub trait OAuthProvider: Send + Sync {
fn use_pkce_in_device_flow(&self) -> bool { fn use_pkce_in_device_flow(&self) -> bool {
false false
} }
fn requires_issuer_stamp(&self) -> bool {
false
}
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -221,6 +224,10 @@ pub struct OAuthTokens {
pub expires_at: i64, pub expires_at: i64,
#[serde(default)] #[serde(default)]
pub account_id: Option<String>, pub account_id: Option<String>,
/// `"{token_url}|{client_id}"` of the issuing provider, stamped on save.
/// `None` on files predating the stamp; those are grandfathered.
#[serde(default)]
pub issuer: Option<String>,
} }
const TOKEN_ENDPOINT_TIMEOUT: Duration = Duration::from_secs(30); const TOKEN_ENDPOINT_TIMEOUT: Duration = Duration::from_secs(30);
@@ -376,9 +383,10 @@ async fn run_pkce_flow(provider: &dyn OAuthProvider, client_name: &str) -> Resul
refresh_token, refresh_token,
expires_at, expires_at,
account_id, account_id,
issuer: None,
}; };
save_oauth_tokens(client_name, &tokens)?; store_tokens(client_name, provider, tokens)?;
println!( println!(
"Successfully authenticated client '{}' with {} via OAuth. Tokens saved.", "Successfully authenticated client '{}' with {} via OAuth. Tokens saved.",
@@ -430,8 +438,9 @@ async fn run_client_credentials_flow(
refresh_token: None, refresh_token: None,
expires_at, expires_at,
account_id: provider.extract_account_id(&response), account_id: provider.extract_account_id(&response),
issuer: None,
}; };
save_oauth_tokens(client_name, &tokens)?; store_tokens(client_name, provider, tokens)?;
Ok(()) Ok(())
} }
@@ -597,8 +606,9 @@ async fn run_device_code_flow(provider: &dyn OAuthProvider, client_name: &str) -
refresh_token, refresh_token,
expires_at, expires_at,
account_id, account_id,
issuer: None,
}; };
save_oauth_tokens(client_name, &tokens)?; store_tokens(client_name, provider, tokens)?;
println!( println!(
"Successfully authenticated client '{}' with {} via OAuth (device_code). Tokens saved.", "Successfully authenticated client '{}' with {} via OAuth (device_code). Tokens saved.",
client_name, client_name,
@@ -637,12 +647,22 @@ pub fn load_oauth_tokens(client_name: &str) -> Option<OAuthTokens> {
serde_json::from_str(&content).ok() serde_json::from_str(&content).ok()
} }
fn save_oauth_tokens(client_name: &str, tokens: &OAuthTokens) -> Result<()> { /// Stamps the issuer fingerprint of `provider` before writing so stored
/// tokens stay bound to the provider that issued them.
fn save_oauth_tokens(
client_name: &str,
provider: &(impl OAuthProvider + ?Sized),
tokens: &OAuthTokens,
) -> Result<()> {
let tokens = OAuthTokens {
issuer: Some(issuer_fingerprint(provider)),
..tokens.clone()
};
let path = paths::token_file(client_name); let path = paths::token_file(client_name);
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
} }
let json = serde_json::to_string_pretty(tokens)?; let json = serde_json::to_string_pretty(&tokens)?;
// Write-then-rename so a crash mid-write never truncates the live token file. // Write-then-rename so a crash mid-write never truncates the live token file.
let mut tmp = path.clone().into_os_string(); let mut tmp = path.clone().into_os_string();
tmp.push(".tmp"); tmp.push(".tmp");
@@ -660,6 +680,35 @@ fn save_oauth_tokens(client_name: &str, tokens: &OAuthTokens) -> Result<()> {
Ok(()) Ok(())
} }
/// Persists freshly-minted tokens and primes the in-memory cache so a running
/// session picks them up immediately instead of the stale token.
fn store_tokens(
client_name: &str,
provider: &(impl OAuthProvider + ?Sized),
tokens: OAuthTokens,
) -> Result<()> {
save_oauth_tokens(client_name, provider, &tokens)?;
set_access_token(
client_name,
tokens.access_token,
tokens.expires_at,
tokens.account_id,
);
clear_rejected(client_name);
Ok(())
}
fn issuer_fingerprint(provider: &(impl OAuthProvider + ?Sized)) -> String {
format!("{}|{}", provider.token_url(), provider.client_id())
}
fn issuer_matches(tokens: &OAuthTokens, provider: &(impl OAuthProvider + ?Sized)) -> bool {
match &tokens.issuer {
Some(issuer) => *issuer == issuer_fingerprint(provider),
None => !provider.requires_issuer_stamp(),
}
}
pub(crate) fn token_response_keys(response: &Value) -> String { pub(crate) fn token_response_keys(response: &Value) -> String {
match response.as_object() { match response.as_object() {
Some(map) => { Some(map) => {
@@ -764,9 +813,10 @@ pub async fn refresh_oauth_token(
refresh_token, refresh_token,
expires_at, expires_at,
account_id, account_id,
issuer: None,
}; };
save_oauth_tokens(client_name, &new_tokens)?; save_oauth_tokens(client_name, provider, &new_tokens)?;
Ok(new_tokens) Ok(new_tokens)
} }
@@ -799,6 +849,10 @@ pub async fn prepare_oauth_access_token(
None => return Ok(false), None => return Ok(false),
}; };
if !issuer_matches(&tokens, provider) {
return Ok(false);
}
let tokens = if Utc::now().timestamp() >= tokens.expires_at let tokens = if Utc::now().timestamp() >= tokens.expires_at
|| is_rejected(client_name, &tokens.access_token) || is_rejected(client_name, &tokens.access_token)
{ {
@@ -817,6 +871,10 @@ pub async fn prepare_oauth_access_token(
None => return Ok(false), None => return Ok(false),
}; };
if !issuer_matches(&tokens, provider) {
return Ok(false);
}
if Utc::now().timestamp() >= tokens.expires_at if Utc::now().timestamp() >= tokens.expires_at
|| is_rejected(client_name, &tokens.access_token) || is_rejected(client_name, &tokens.access_token)
{ {
@@ -1005,6 +1063,46 @@ pub fn get_oauth_provider(provider_type: &str) -> Option<Box<dyn OAuthProvider>>
} }
} }
pub(crate) fn config_oauth_for_client(
client_config: &ClientConfig,
all_provider_models: &[ProviderModels],
) -> Option<OAuthConfig> {
let (client_name, _, _) = client_config_info(client_config);
let user_oauth = match client_config {
ClientConfig::OpenAICompatibleConfig(c) => c.oauth.clone().map(|b| *b),
ClientConfig::ClaudeConfig(c) => c.oauth.clone().map(|b| *b),
_ => return None,
};
let base = all_provider_models
.iter()
.find(|p| p.provider == client_name)
.and_then(|p| p.oauth.clone());
match (base, user_oauth) {
(None, None) => None,
(Some(b), None) => Some(b),
(None, Some(u)) => Some(u),
(Some(b), Some(u)) => Some(b.merge(u)),
}
}
pub(crate) fn claude_oauth_provider_for_client(
client_config: &ClientConfig,
all_provider_models: &[ProviderModels],
) -> (Box<dyn OAuthProvider>, bool) {
let (client_name, _, _) = client_config_info(client_config);
match config_oauth_for_client(client_config, all_provider_models) {
Some(merged) => (
Box::new(OpenAICompatibleOAuthProvider {
config: merged,
client_name: client_name.to_string(),
requires_issuer_stamp: true,
}),
false,
),
None => (Box::new(super::claude_oauth::ClaudeOAuthProvider), true),
}
}
pub fn get_oauth_provider_for_client( pub fn get_oauth_provider_for_client(
client_config: &ClientConfig, client_config: &ClientConfig,
all_provider_models: &[ProviderModels], all_provider_models: &[ProviderModels],
@@ -1015,23 +1113,19 @@ pub fn get_oauth_provider_for_client(
} }
match client_config { match client_config {
ClientConfig::OpenAICompatibleConfig(c) => { ClientConfig::OpenAICompatibleConfig(_) => {
let base = all_provider_models let merged = config_oauth_for_client(client_config, all_provider_models)?;
.iter()
.find(|p| p.provider == client_name)
.and_then(|p| p.oauth.clone());
let user_oauth = c.oauth.clone().map(|b| *b);
let merged = match (base, user_oauth) {
(None, None) => return None,
(Some(b), None) => b,
(None, Some(u)) => u,
(Some(b), Some(u)) => b.merge(u),
};
Some(Box::new(OpenAICompatibleOAuthProvider { Some(Box::new(OpenAICompatibleOAuthProvider {
config: merged, config: merged,
client_name: client_name.to_string(), client_name: client_name.to_string(),
requires_issuer_stamp: false,
})) }))
} }
ClientConfig::ClaudeConfig(_) => {
let (provider, _) =
claude_oauth_provider_for_client(client_config, all_provider_models);
Some(provider)
}
_ => get_oauth_provider(provider_type), _ => get_oauth_provider(provider_type),
} }
} }
@@ -1097,6 +1191,7 @@ mod tests {
use super::*; use super::*;
use crate::client::access_token::{distrust_access_token, get_access_token}; use crate::client::access_token::{distrust_access_token, get_access_token};
use crate::client::claude::ClaudeConfig;
use crate::client::openai_compatible::OpenAICompatibleConfig; use crate::client::openai_compatible::OpenAICompatibleConfig;
use crate::client::{ModelData, ProviderModels}; use crate::client::{ModelData, ProviderModels};
use crate::utils::get_env_name; use crate::utils::get_env_name;
@@ -1324,6 +1419,24 @@ echo_pkce_in_token_exchange: true
}) })
} }
fn make_claude_client(
name: &str,
auth: Option<&str>,
oauth: Option<OAuthConfig>,
) -> ClientConfig {
ClientConfig::ClaudeConfig(ClaudeConfig {
name: Some(name.into()),
api_key: None,
api_base: None,
auth: auth.map(str::to_string),
oauth: oauth.map(Box::new),
models: vec![],
prompt_cache: None,
patch: None,
extra: None,
})
}
#[test] #[test]
fn get_oauth_provider_for_client_merges_defaults_with_user_override() { fn get_oauth_provider_for_client_merges_defaults_with_user_override() {
let base = base_config(); let base = base_config();
@@ -1386,6 +1499,87 @@ echo_pkce_in_token_exchange: true
assert!(get_oauth_provider_for_client(&cc, &models).is_none()); assert!(get_oauth_provider_for_client(&cc, &models).is_none());
} }
#[test]
fn claude_client_with_user_oauth_block_uses_generic_provider() {
let mut user = empty_user_override("gateway-id", "https://gateway.example/token");
user.device_authorization_url = Some("https://gateway.example/device".into());
let cc = make_claude_client("claude", Some("oauth"), Some(user));
let provider = get_oauth_provider_for_client(&cc, &[]).unwrap();
assert_eq!(provider.provider_name(), "claude");
assert_eq!(provider.client_id(), "gateway-id");
assert_eq!(provider.token_url(), "https://gateway.example/token");
assert_eq!(
provider.device_authorization_url(),
Some("https://gateway.example/device")
);
}
#[test]
fn claude_client_without_oauth_block_falls_back_to_stock_provider() {
let cc = make_claude_client("claude", Some("oauth"), None);
let provider = get_oauth_provider_for_client(&cc, &[]).unwrap();
assert_eq!(provider.provider_name(), "claude");
assert_eq!(provider.client_id(), "9d1c250a-e61b-44d9-88ed-5944d1962f5e");
assert_eq!(
provider.extra_request_headers(),
vec![("anthropic-beta", "oauth-2025-04-20")]
);
}
#[test]
fn claude_client_merges_bundled_defaults_with_user_override() {
let base = base_config();
let user = empty_user_override("user-id", "https://user.example/token");
let models = vec![make_provider_models("claude", Some(base))];
let cc = make_claude_client("claude", Some("oauth"), Some(user));
let provider = get_oauth_provider_for_client(&cc, &models).unwrap();
assert_eq!(provider.provider_name(), "claude");
assert_eq!(provider.client_id(), "user-id");
assert_eq!(provider.token_url(), "https://user.example/token");
assert_eq!(provider.authorize_url(), "https://base.example/authorize");
}
#[test]
fn claude_bundled_only_oauth_block_uses_generic_provider() {
let base = base_config();
let models = vec![make_provider_models("claude", Some(base))];
let cc = make_claude_client("claude", Some("oauth"), None);
let (provider, is_stock) = claude_oauth_provider_for_client(&cc, &models);
assert!(!is_stock);
assert_eq!(provider.client_id(), "base-id");
assert_eq!(provider.token_url(), "https://base.example/token");
assert!(provider.extra_request_headers().is_empty());
}
#[test]
fn claude_config_provider_requires_issuer_stamp() {
let user = empty_user_override("gateway-id", "https://gateway.example/token");
let cc = make_claude_client("claude", Some("oauth"), Some(user));
let (provider, is_stock) = claude_oauth_provider_for_client(&cc, &[]);
assert!(!is_stock);
assert!(provider.requires_issuer_stamp());
}
#[test]
fn claude_stock_provider_grandfathers_legacy_tokens() {
let cc = make_claude_client("claude", Some("oauth"), None);
let (provider, is_stock) = claude_oauth_provider_for_client(&cc, &[]);
assert!(is_stock);
assert!(!provider.requires_issuer_stamp());
}
#[test] #[test]
fn openai_compatible_provider_joins_scopes_with_spaces() { fn openai_compatible_provider_joins_scopes_with_spaces() {
let mut cfg = base_config(); let mut cfg = base_config();
@@ -1394,6 +1588,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert_eq!(provider.scopes(), "one two three"); assert_eq!(provider.scopes(), "one two three");
@@ -1408,6 +1603,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert_eq!( assert_eq!(
@@ -1425,6 +1621,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert!(provider.uses_localhost_redirect()); assert!(provider.uses_localhost_redirect());
@@ -1436,6 +1633,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: base_config(), config: base_config(),
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert!(provider.extra_token_params().is_empty()); assert!(provider.extra_token_params().is_empty());
@@ -1546,6 +1744,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert_eq!( assert_eq!(
@@ -1559,6 +1758,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: base_config(), config: base_config(),
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert!(provider.device_authorization_url().is_none()); assert!(provider.device_authorization_url().is_none());
@@ -1569,6 +1769,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: base_config(), config: base_config(),
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert!(!provider.use_pkce_in_device_flow()); assert!(!provider.use_pkce_in_device_flow());
@@ -1582,6 +1783,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert!(provider.use_pkce_in_device_flow()); assert!(provider.use_pkce_in_device_flow());
@@ -1596,6 +1798,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert_eq!(provider.resource(), Some("https://rs.example/")); assert_eq!(provider.resource(), Some("https://rs.example/"));
@@ -1655,6 +1858,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert!(provider.fixed_redirect_uri().is_none()); assert!(provider.fixed_redirect_uri().is_none());
@@ -1669,6 +1873,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert_eq!( assert_eq!(
@@ -1686,6 +1891,7 @@ echo_pkce_in_token_exchange: true
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
assert_eq!( assert_eq!(
@@ -1815,6 +2021,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let request = build_token_request( let request = build_token_request(
@@ -1967,6 +2174,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: base_config(), config: base_config(),
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let request = build_token_request( let request = build_token_request(
@@ -1991,6 +2199,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let url = build_authorize_url( let url = build_authorize_url(
@@ -2010,6 +2219,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: base_config(), config: base_config(),
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let url = build_authorize_url( let url = build_authorize_url(
@@ -2032,6 +2242,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let url = build_authorize_url( let url = build_authorize_url(
@@ -2062,6 +2273,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: cfg, config: cfg,
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let params = build_device_authorization_params(&provider, "a b", None); let params = build_device_authorization_params(&provider, "a b", None);
@@ -2076,6 +2288,7 @@ extra_token_params:
let provider = OpenAICompatibleOAuthProvider { let provider = OpenAICompatibleOAuthProvider {
config: base_config(), config: base_config(),
client_name: "test".into(), client_name: "test".into(),
requires_issuer_stamp: false,
}; };
let params = build_device_authorization_params(&provider, "a b", Some("challenge")); let params = build_device_authorization_params(&provider, "a b", Some("challenge"));
@@ -2094,9 +2307,10 @@ extra_token_params:
refresh_token: Some("rt-456".into()), refresh_token: Some("rt-456".into()),
expires_at: 1234567890, expires_at: 1234567890,
account_id: Some("acct-789".into()), account_id: Some("acct-789".into()),
issuer: None,
}; };
save_oauth_tokens("atomic-test", &tokens).unwrap(); save_oauth_tokens("atomic-test", &ResourceStubProvider, &tokens).unwrap();
let loaded = load_oauth_tokens("atomic-test").unwrap(); let loaded = load_oauth_tokens("atomic-test").unwrap();
assert_eq!(loaded.access_token, "at-123"); assert_eq!(loaded.access_token, "at-123");
@@ -2130,11 +2344,13 @@ extra_token_params:
let expires_at = Utc::now().timestamp() + 3600; let expires_at = Utc::now().timestamp() + 3600;
save_oauth_tokens( save_oauth_tokens(
client_name, client_name,
&ResourceStubProvider,
&OAuthTokens { &OAuthTokens {
access_token: "rejected-at".into(), access_token: "rejected-at".into(),
refresh_token: None, refresh_token: None,
expires_at, expires_at,
account_id: None, account_id: None,
issuer: None,
}, },
) )
.unwrap(); .unwrap();
@@ -2169,11 +2385,13 @@ extra_token_params:
assert!(distrust_access_token(client_name, "rejected-at")); assert!(distrust_access_token(client_name, "rejected-at"));
save_oauth_tokens( save_oauth_tokens(
client_name, client_name,
&ResourceStubProvider,
&OAuthTokens { &OAuthTokens {
access_token: "fresh-at".into(), access_token: "fresh-at".into(),
refresh_token: None, refresh_token: None,
expires_at, expires_at,
account_id: None, account_id: None,
issuer: None,
}, },
) )
.unwrap(); .unwrap();
@@ -2198,6 +2416,219 @@ extra_token_params:
}); });
} }
#[test]
#[serial]
fn store_tokens_caches_token_and_clears_rejection() {
with_temp_cache(|| {
let client_name = "store-tokens-test";
let expires_at = Utc::now().timestamp() + 3600;
set_access_token(client_name, "old-at".into(), expires_at, None);
assert!(distrust_access_token(client_name, "old-at"));
store_tokens(
client_name,
&ResourceStubProvider,
OAuthTokens {
access_token: "fresh-at".into(),
refresh_token: None,
expires_at,
account_id: None,
issuer: None,
},
)
.unwrap();
assert_eq!(get_access_token(client_name).unwrap(), "fresh-at");
assert!(is_valid_access_token(client_name));
assert!(
!is_rejected(client_name, "old-at"),
"rejection marker not cleared by store_tokens"
);
});
}
fn write_raw_token_file(client_name: &str, json: &str) {
let path = paths::token_file(client_name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, json).unwrap();
}
#[test]
#[serial]
fn save_oauth_tokens_stamps_issuer_fingerprint() {
with_temp_cache(|| {
save_oauth_tokens(
"issuer-stamp-test",
&ResourceStubProvider,
&OAuthTokens {
access_token: "at".into(),
refresh_token: None,
expires_at: 1234567890,
account_id: None,
issuer: None,
},
)
.unwrap();
let loaded = load_oauth_tokens("issuer-stamp-test").unwrap();
assert_eq!(
loaded.issuer.as_deref(),
Some("https://as.example/token|stub-client")
);
});
}
#[test]
#[serial]
fn prepare_rejects_unexpired_tokens_with_mismatched_issuer() {
with_temp_cache(|| {
let client_name = "issuer-mismatch-valid-test";
let expires_at = Utc::now().timestamp() + 3600;
write_raw_token_file(
client_name,
&format!(
r#"{{"access_token":"foreign-at","expires_at":{expires_at},"issuer":"https://old.example/token|old-client"}}"#
),
);
let ready = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(prepare_oauth_access_token(
&ReqwestClient::new(),
&ResourceStubProvider,
client_name,
))
.unwrap();
assert!(!ready);
assert!(
get_access_token(client_name).is_err(),
"foreign token must not enter the cache"
);
});
}
#[test]
#[serial]
fn prepare_rejects_expired_mismatched_issuer_without_refreshing() {
with_temp_cache(|| {
let client_name = "issuer-mismatch-expired-test";
write_raw_token_file(
client_name,
r#"{"access_token":"foreign-at","refresh_token":"foreign-rt","expires_at":0,"issuer":"https://old.example/token|old-client"}"#,
);
// A refresh attempt would POST to the stub's token_url and fail
// with a transport error; Ok(false) proves the refresh token was
// never forwarded.
let ready = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(prepare_oauth_access_token(
&ReqwestClient::new(),
&ResourceStubProvider,
client_name,
))
.unwrap();
assert!(!ready);
});
}
#[test]
#[serial]
fn prepare_accepts_legacy_tokens_without_issuer() {
with_temp_cache(|| {
let client_name = "issuer-legacy-test";
let expires_at = Utc::now().timestamp() + 3600;
write_raw_token_file(
client_name,
&format!(r#"{{"access_token":"legacy-at","expires_at":{expires_at}}}"#),
);
let ready = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(prepare_oauth_access_token(
&ReqwestClient::new(),
&ResourceStubProvider,
client_name,
))
.unwrap();
assert!(ready);
assert_eq!(get_access_token(client_name).unwrap(), "legacy-at");
});
}
#[test]
#[serial]
fn prepare_rejects_legacy_tokens_for_claude_config_provider() {
with_temp_cache(|| {
let client_name = "issuer-legacy-claude-config-test";
let user = empty_user_override("gateway-id", "https://gateway.example/token");
let cc = make_claude_client(client_name, Some("oauth"), Some(user));
let (provider, _) = claude_oauth_provider_for_client(&cc, &[]);
write_raw_token_file(
client_name,
r#"{"access_token":"legacy-at","refresh_token":"legacy-rt","expires_at":0}"#,
);
// Legacy files predate config-driven claude oauth, so they are
// Anthropic-issued; Ok(false) proves neither the access token
// nor the refresh token reaches the configured endpoint.
let ready = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(prepare_oauth_access_token(
&ReqwestClient::new(),
&*provider,
client_name,
))
.unwrap();
assert!(!ready);
assert!(
get_access_token(client_name).is_err(),
"legacy token must not enter the cache"
);
});
}
#[test]
#[serial]
fn prepare_accepts_legacy_tokens_for_stock_claude_provider() {
with_temp_cache(|| {
let client_name = "issuer-legacy-claude-stock-test";
let cc = make_claude_client(client_name, Some("oauth"), None);
let (provider, _) = claude_oauth_provider_for_client(&cc, &[]);
let expires_at = Utc::now().timestamp() + 3600;
write_raw_token_file(
client_name,
&format!(r#"{{"access_token":"legacy-at","expires_at":{expires_at}}}"#),
);
let ready = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
.block_on(prepare_oauth_access_token(
&ReqwestClient::new(),
&*provider,
client_name,
))
.unwrap();
assert!(ready);
assert_eq!(get_access_token(client_name).unwrap(), "legacy-at");
});
}
#[test] #[test]
fn parse_refresh_response_invalid_grant_redacts_and_prompts_reauth() { fn parse_refresh_response_invalid_grant_redacts_and_prompts_reauth() {
let response = serde_json::json!({ let response = serde_json::json!({
+5
View File
@@ -5,6 +5,7 @@ use super::oauth::{OAuthConfig, OAuthFlow, OAuthProvider, TokenRequestFormat};
pub struct OpenAICompatibleOAuthProvider { pub struct OpenAICompatibleOAuthProvider {
pub config: OAuthConfig, pub config: OAuthConfig,
pub client_name: String, pub client_name: String,
pub requires_issuer_stamp: bool,
} }
fn is_loopback_uri(uri: &str) -> bool { fn is_loopback_uri(uri: &str) -> bool {
@@ -122,4 +123,8 @@ impl OAuthProvider for OpenAICompatibleOAuthProvider {
fn use_pkce_in_device_flow(&self) -> bool { fn use_pkce_in_device_flow(&self) -> bool {
self.config.use_pkce_in_device_flow self.config.use_pkce_in_device_flow
} }
fn requires_issuer_stamp(&self) -> bool {
self.requires_issuer_stamp
}
} }