intelligent_test_auth_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package service
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/json"
  8. "encoding/pem"
  9. "fmt"
  10. "net/http"
  11. "net/http/httptest"
  12. "sync"
  13. "testing"
  14. "time"
  15. "github.com/Wei-Shaw/sub2api/internal/config"
  16. "github.com/Wei-Shaw/sub2api/internal/pkg/geminicli"
  17. "github.com/stretchr/testify/require"
  18. )
  19. func intelligentAuthContext() context.Context {
  20. return context.WithValue(context.Background(), intelligentRunKey{}, &intelligentRunContext{capture: &intelligentCapture{}})
  21. }
  22. type intelligentAuthRepo struct {
  23. AccountRepository
  24. account *Account
  25. reads, writes int
  26. }
  27. func (r *intelligentAuthRepo) GetByID(context.Context, int64) (*Account, error) {
  28. r.reads++
  29. return r.account, nil
  30. }
  31. func (r *intelligentAuthRepo) Update(context.Context, *Account) error {
  32. r.writes++
  33. return nil
  34. }
  35. type intelligentAuthCache struct {
  36. GeminiTokenCache
  37. reads int
  38. token string
  39. }
  40. func (c *intelligentAuthCache) GetAccessToken(context.Context, string) (string, error) {
  41. c.reads++
  42. return c.token, nil
  43. }
  44. type intelligentAuthExecutor struct{ calls int }
  45. func (e *intelligentAuthExecutor) CacheKey(*Account) string { e.calls++; return "test" }
  46. func (e *intelligentAuthExecutor) CanRefresh(*Account) bool { e.calls++; return true }
  47. func (e *intelligentAuthExecutor) NeedsRefresh(*Account, time.Duration) bool {
  48. e.calls++
  49. return true
  50. }
  51. func (e *intelligentAuthExecutor) Refresh(context.Context, *Account) (map[string]any, error) {
  52. e.calls++
  53. return map[string]any{"access_token": "rotated", "refresh_token": "rotated-refresh"}, nil
  54. }
  55. func TestIntelligentOAuthProvidersUseSnapshotWithoutCacheOrRotation(t *testing.T) {
  56. for _, platform := range []string{PlatformGemini, PlatformAnthropic, PlatformAntigravity, PlatformGrok} {
  57. for _, state := range []string{"valid-within-refresh-skew", "expired", "missing-expiry", "missing-access-token"} {
  58. t.Run(platform+"/"+state, func(t *testing.T) {
  59. account := &Account{ID: 87, Platform: platform, Type: AccountTypeOAuth, Status: StatusActive, Credentials: map[string]any{
  60. "access_token": "existing-access", "refresh_token": "existing-refresh",
  61. "expires_at": time.Now().Add(time.Minute).Format(time.RFC3339), "auto_detect_project_id": true,
  62. }}
  63. switch state {
  64. case "expired":
  65. account.Credentials["expires_at"] = time.Now().Add(-time.Minute).Format(time.RFC3339)
  66. case "missing-expiry":
  67. delete(account.Credentials, "expires_at")
  68. case "missing-access-token":
  69. delete(account.Credentials, "access_token")
  70. }
  71. before := shallowCopyMap(account.Credentials)
  72. repo := &intelligentAuthRepo{account: account}
  73. cache := &intelligentAuthCache{token: "newer-shared-cache-token"}
  74. executor := &intelligentAuthExecutor{}
  75. api := NewOAuthRefreshAPI(repo, cache)
  76. var get func(context.Context, *Account) (string, error)
  77. switch platform {
  78. case PlatformGemini:
  79. p := NewGeminiTokenProvider(repo, cache, &GeminiOAuthService{})
  80. p.SetRefreshAPI(api, executor)
  81. get = p.GetAccessToken
  82. case PlatformAnthropic:
  83. p := NewClaudeTokenProvider(repo, cache, &OAuthService{})
  84. p.SetRefreshAPI(api, executor)
  85. get = p.GetAccessToken
  86. case PlatformAntigravity:
  87. p := NewAntigravityTokenProvider(repo, cache, &AntigravityOAuthService{})
  88. p.SetRefreshAPI(api, executor)
  89. get = p.GetAccessToken
  90. case PlatformGrok:
  91. p := NewGrokTokenProvider(repo, cache)
  92. p.SetRefreshAPI(api, executor)
  93. get = p.GetAccessToken
  94. }
  95. token, err := get(intelligentAuthContext(), account)
  96. if state == "valid-within-refresh-skew" {
  97. require.NoError(t, err)
  98. require.Equal(t, "existing-access", token)
  99. } else {
  100. require.ErrorIs(t, err, errIntelligentCredentialRefreshRequired)
  101. require.Empty(t, token)
  102. }
  103. require.Equal(t, before, account.Credentials)
  104. require.Zero(t, cache.reads)
  105. require.Zero(t, executor.calls)
  106. require.Zero(t, repo.reads)
  107. require.Zero(t, repo.writes)
  108. })
  109. }
  110. }
  111. }
  112. type intelligentAuthCodeAssist struct {
  113. GeminiCliCodeAssistClient
  114. calls int
  115. }
  116. func (c *intelligentAuthCodeAssist) LoadCodeAssist(context.Context, string, string, *geminicli.LoadCodeAssistRequest) (*geminicli.LoadCodeAssistResponse, error) {
  117. c.calls++
  118. return &geminicli.LoadCodeAssistResponse{CloudAICompanionProject: "auto-detected-project"}, nil
  119. }
  120. func TestIntelligentGeminiRunnerDoesNotDiscoverProjectOrChangeRoute(t *testing.T) {
  121. requests := 0
  122. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  123. requests++
  124. require.Contains(t, r.URL.Path, "/models/gemini-test:streamGenerateContent")
  125. require.Equal(t, "Bearer existing-access", r.Header.Get("Authorization"))
  126. var payload map[string]any
  127. require.NoError(t, json.NewDecoder(r.Body).Decode(&payload))
  128. require.NotContains(t, payload, "project")
  129. w.Header().Set("Content-Type", "text/event-stream")
  130. fmt.Fprint(w, "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ANSWER: 12\"}]},\"finishReason\":\"STOP\"}]}\n\n")
  131. }))
  132. defer server.Close()
  133. account := &Account{ID: 88, Platform: PlatformGemini, Type: AccountTypeOAuth, Concurrency: 1, Credentials: map[string]any{
  134. "access_token": "existing-access", "refresh_token": "existing-refresh", "auto_detect_project_id": true,
  135. "base_url": server.URL, "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339),
  136. }}
  137. before := shallowCopyMap(account.Credentials)
  138. repo := &intelligentAuthRepo{account: account}
  139. codeAssist := &intelligentAuthCodeAssist{}
  140. provider := NewGeminiTokenProvider(repo, nil, &GeminiOAuthService{codeAssist: codeAssist})
  141. cfg := &config.Config{}
  142. cfg.Security.URLAllowlist.AllowInsecureHTTP = true
  143. svc := NewAccountTestService(repo, provider, nil, nil, nil, intelligentNetworkUpstream{client: server.Client()}, cfg, nil)
  144. record := &IntelligentTestRecord{AccountID: account.ID, Input: "Configured candy prompt", Model: "gemini-test", ConfigSnapshot: &IntelligentTestConfig{Model: "gemini-test"}}
  145. require.NoError(t, svc.RunIntelligentTest(context.Background(), record))
  146. require.Equal(t, "ANSWER: 12", record.Result)
  147. require.Equal(t, 1, requests)
  148. require.Zero(t, codeAssist.calls)
  149. require.Zero(t, repo.writes)
  150. require.Equal(t, before, account.Credentials)
  151. // Expired authentication is a recorded account error with no upstream work.
  152. account.Credentials["expires_at"] = time.Now().Add(-time.Hour).Format(time.RFC3339)
  153. record = &IntelligentTestRecord{AccountID: account.ID, Input: "test", Model: "gemini-test", ConfigSnapshot: &IntelligentTestConfig{}}
  154. require.Error(t, svc.RunIntelligentTest(context.Background(), record))
  155. require.Equal(t, "account_error", record.Status)
  156. require.Contains(t, record.ErrorMessage, "单独刷新认证")
  157. require.Equal(t, 1, requests)
  158. require.Zero(t, codeAssist.calls)
  159. require.Zero(t, repo.writes)
  160. }
  161. func TestIntelligentRefreshAPIBlocksBeforeExecutorAndRepository(t *testing.T) {
  162. repo := &intelligentAuthRepo{}
  163. cache := &intelligentAuthCache{}
  164. executor := &intelligentAuthExecutor{}
  165. api := NewOAuthRefreshAPI(repo, cache)
  166. result, err := api.RefreshIfNeeded(intelligentAuthContext(), &Account{ID: 90}, executor, time.Minute)
  167. require.ErrorIs(t, err, errIntelligentCredentialRefreshRequired)
  168. require.Nil(t, result)
  169. require.Zero(t, executor.calls)
  170. require.Zero(t, repo.reads)
  171. require.Zero(t, repo.writes)
  172. require.Zero(t, cache.reads)
  173. }
  174. func TestIntelligentGrokManualTestUsesExistingTokenAndHonorsProxy(t *testing.T) {
  175. account := &Account{ID: 91, Platform: PlatformGrok, Type: AccountTypeOAuth, Credentials: map[string]any{
  176. "access_token": "existing", "expires_at": time.Now().Add(time.Minute).Format(time.RFC3339),
  177. }}
  178. provider := NewGrokTokenProvider(nil, nil)
  179. token, err := provider.GetAccessTokenForManualTest(intelligentAuthContext(), account)
  180. require.NoError(t, err)
  181. require.Equal(t, "existing", token)
  182. account.Credentials["expires_at"] = time.Now().Add(-time.Minute).Format(time.RFC3339)
  183. _, err = provider.GetAccessTokenForManualTest(intelligentAuthContext(), account)
  184. require.ErrorIs(t, err, errIntelligentCredentialRefreshRequired)
  185. proxyID := int64(1)
  186. account.ProxyID = &proxyID
  187. _, err = provider.GetAccessTokenForManualTest(intelligentAuthContext(), account)
  188. require.ErrorIs(t, err, errGrokOAuthConfiguredProxyMiss)
  189. _, err = provider.GetAccessToken(intelligentAuthContext(), account)
  190. require.ErrorIs(t, err, errGrokOAuthConfiguredProxyMiss)
  191. }
  192. func TestIntelligentAgentIdentityNeverRegistersOrReplacesTask(t *testing.T) {
  193. key, privateKey := newTestAgentIdentityKey(t)
  194. account := &Account{ID: 92, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{
  195. "auth_mode": OpenAIAuthModeAgentIdentity, "agent_runtime_id": key.runtimeID, "agent_private_key": privateKey, "task_id": key.taskID,
  196. }}
  197. repo := &intelligentAuthRepo{account: account}
  198. registerCalls := 0
  199. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  200. registerCalls++
  201. fmt.Fprint(w, `{"task_id":"new-task"}`)
  202. }))
  203. defer server.Close()
  204. oldBase := openAIAgentIdentityAuthAPIBaseURL
  205. openAIAgentIdentityAuthAPIBaseURL = server.URL
  206. t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase })
  207. ctx := intelligentAuthContext()
  208. before := shallowCopyMap(account.Credentials)
  209. headers, err := buildAgentIdentityAuthenticationHeaders(ctx, repo, nil, &sync.Mutex{}, account)
  210. require.NoError(t, err)
  211. require.Contains(t, headers.Get("Authorization"), "AgentAssertion ")
  212. require.ErrorIs(t, ensureAgentIdentityTaskForAccount(ctx, repo, nil, &sync.Mutex{}, account, key.taskID), errIntelligentCredentialRefreshRequired)
  213. require.Equal(t, before, account.Credentials)
  214. delete(account.Credentials, "task_id")
  215. _, err = buildAgentIdentityAuthenticationHeaders(ctx, repo, nil, &sync.Mutex{}, account)
  216. require.ErrorIs(t, err, errIntelligentCredentialRefreshRequired)
  217. require.Zero(t, registerCalls)
  218. require.Zero(t, repo.writes)
  219. }
  220. func TestIntelligentVertexServiceAccountCacheRemainsUsable(t *testing.T) {
  221. for _, platform := range []string{PlatformGemini, PlatformAnthropic} {
  222. t.Run(platform, func(t *testing.T) {
  223. account := &Account{ID: 93, Platform: platform, Type: AccountTypeServiceAccount, Credentials: map[string]any{
  224. "service_account_json": `{"type":"service_account","project_id":"vertex-test","client_email":"test@example.iam.gserviceaccount.com","private_key":"test-pem"}`,
  225. }}
  226. before := shallowCopyMap(account.Credentials)
  227. cache := &intelligentAuthCache{token: "short-lived-vertex-token"}
  228. var token string
  229. var err error
  230. if platform == PlatformGemini {
  231. token, err = NewGeminiTokenProvider(nil, cache, nil).GetAccessToken(intelligentAuthContext(), account)
  232. } else {
  233. token, err = NewClaudeTokenProvider(nil, cache, nil).GetAccessToken(intelligentAuthContext(), account)
  234. }
  235. require.NoError(t, err)
  236. require.Equal(t, "short-lived-vertex-token", token)
  237. require.Equal(t, 1, cache.reads)
  238. require.Equal(t, before, account.Credentials)
  239. })
  240. }
  241. }
  242. func TestIntelligentVertexServiceAccountCanMintEphemeralToken(t *testing.T) {
  243. privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  244. require.NoError(t, err)
  245. key := &vertexServiceAccountKey{ClientEmail: "test@example.iam.gserviceaccount.com", PrivateKey: string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}))}
  246. requests := 0
  247. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  248. requests++
  249. require.NoError(t, r.ParseForm())
  250. require.Equal(t, "urn:ietf:params:oauth:grant-type:jwt-bearer", r.PostForm.Get("grant_type"))
  251. require.NotEmpty(t, r.PostForm.Get("assertion"))
  252. fmt.Fprint(w, `{"access_token":"ephemeral-token","token_type":"Bearer","expires_in":3600}`)
  253. }))
  254. defer server.Close()
  255. key.TokenURI = server.URL
  256. before := *key
  257. token, ttl, err := exchangeVertexServiceAccountToken(intelligentAuthContext(), key, "")
  258. require.NoError(t, err)
  259. require.Equal(t, "ephemeral-token", token)
  260. require.Equal(t, 55*time.Minute, ttl)
  261. require.Equal(t, 1, requests)
  262. require.Equal(t, before, *key)
  263. }