anthropic_apikey_auth.go 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package service
  2. import (
  3. "net/http"
  4. "strings"
  5. )
  6. const (
  7. anthropicAPIKeyAuthSchemeExtraKey = "anthropic_apikey_auth_scheme"
  8. AnthropicAPIKeyAuthSchemeXAPIKey = "x_api_key"
  9. AnthropicAPIKeyAuthSchemeAuthorizationBearer = "authorization_bearer"
  10. )
  11. // GetAnthropicAPIKeyAuthScheme returns the upstream authentication scheme for
  12. // Anthropic API-key accounts. Missing or invalid values keep the historical
  13. // x-api-key behavior. CN providers using their native Anthropic endpoints
  14. // (api_protocol=anthropic) share the same override knob — Kimi/DeepSeek default
  15. // to x-api-key, Zhipu can opt into Authorization: Bearer.
  16. func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
  17. if a == nil || a.Type != AccountTypeAPIKey {
  18. return AnthropicAPIKeyAuthSchemeXAPIKey
  19. }
  20. if a.Platform != PlatformAnthropic && !a.IsCNProvider() {
  21. return AnthropicAPIKeyAuthSchemeXAPIKey
  22. }
  23. switch strings.TrimSpace(a.GetExtraString(anthropicAPIKeyAuthSchemeExtraKey)) {
  24. case AnthropicAPIKeyAuthSchemeAuthorizationBearer:
  25. return AnthropicAPIKeyAuthSchemeAuthorizationBearer
  26. default:
  27. return AnthropicAPIKeyAuthSchemeXAPIKey
  28. }
  29. }
  30. // isOllamaCloudAnthropicAuthBaseURL 判定本次实际选用的 Anthropic 上游 base_url
  31. // 是否指向 Ollama Cloud。与真实出站 URL 组装同源:先 TrimSpace + TrimRight "/"
  32. // (urlvalidator 与 nativeAnthropicTargetURL 同款归一化,'https://ollama.com/'
  33. // 与 '.../v1' 均合理),再复用既有严格 host helper isOllamaCloudBaseURL(精确
  34. // host、https、无 query/fragment、路径仅空或 /v1),不按 substring 匹配。
  35. func isOllamaCloudAnthropicAuthBaseURL(baseURL string) bool {
  36. return isOllamaCloudBaseURL(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
  37. }
  38. // setAnthropicAPIKeyAuthHeader 写入上游认证头。除 extra 覆写外,Ollama Cloud
  39. // 官方 Anthropic 兼容端点只认 Authorization: Bearer:判定依据是本次实际选用的
  40. // 上游 base_url(与出站 URL 组装同源,而非 account.Platform——Ollama Cloud key
  41. // 可挂在多个平台分组下),即使 extra 缺失或显式 x_api_key 也强制 Bearer;
  42. // 其它上游保持历史 extra/default 行为。baseURL 为该请求实际选用的 Anthropic
  43. // 上游 base(GetBaseURL / GetAnthropicProtocolBaseURL 等),默认官方端点时传空。
  44. func setAnthropicAPIKeyAuthHeader(header http.Header, account *Account, token, baseURL string) {
  45. if account.Type == AccountTypeAPIKey && isOllamaCloudAnthropicAuthBaseURL(baseURL) {
  46. header.Set("Authorization", "Bearer "+token)
  47. return
  48. }
  49. if account.GetAnthropicAPIKeyAuthScheme() == AnthropicAPIKeyAuthSchemeAuthorizationBearer {
  50. header.Set("Authorization", "Bearer "+token)
  51. return
  52. }
  53. header.Set("x-api-key", token)
  54. }