mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-11-27 20:32:41 +08:00
fix(auth): honor request-scoped-errors, Retry-After, and credential scope on PrepareRequestAuth failure
- Route errPrepare through the same error pipeline as execution errors in all four conductor paths (Execute/CountTokens/Stream/Home): record RetryAfter and CredentialScope, match request-scoped error rules, stop on stop-actions and invalid requests, and preserve the upstream attempt via markUpstreamExecutionAttemptFromContext plus annotateTrustedRetryAfterByHint/syncPreferredUpstreamError so stop responses keep their retry hint. - Mark upstream attempts only at real HTTP boundaries (OAuth token refresh, project discovery) and propagate upstream Retry-After and credential scope from Antigravity prepare failures, while keeping local missing-credential errors and status-less transport faults from being misclassified or outranking a genuine upstream rejection. Closes: #7726
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -34,6 +35,7 @@ type userInfo struct {
|
||||
type HTTPStatusError struct {
|
||||
StatusCodeValue int
|
||||
Message string
|
||||
RetryAfterValue *time.Duration
|
||||
}
|
||||
|
||||
func (e *HTTPStatusError) Error() string {
|
||||
@@ -50,6 +52,15 @@ func (e *HTTPStatusError) StatusCode() int {
|
||||
return e.StatusCodeValue
|
||||
}
|
||||
|
||||
// RetryAfter exposes the upstream Retry-After hint so the conductor can record
|
||||
// the provider-supplied recovery deadline on the result.
|
||||
func (e *HTTPStatusError) RetryAfter() *time.Duration {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.RetryAfterValue
|
||||
}
|
||||
|
||||
// AntigravityAuth handles Antigravity OAuth authentication
|
||||
type AntigravityAuth struct {
|
||||
httpClient *http.Client
|
||||
@@ -245,6 +256,34 @@ func (o *AntigravityAuth) FetchUserInfo(ctx context.Context, accessToken string)
|
||||
return email, nil
|
||||
}
|
||||
|
||||
// retryAfterFromHeaders parses the Retry-After response header. It accepts both
|
||||
// the delta-seconds form and the absolute HTTP-date form, returning nil when the
|
||||
// header is absent or unparsable.
|
||||
func retryAfterFromHeaders(header http.Header) *time.Duration {
|
||||
if len(header) == 0 {
|
||||
return nil
|
||||
}
|
||||
raw := strings.TrimSpace(header.Get("Retry-After"))
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
if seconds, errParse := strconv.Atoi(raw); errParse == nil {
|
||||
if seconds < 0 {
|
||||
return nil
|
||||
}
|
||||
d := time.Duration(seconds) * time.Second
|
||||
return &d
|
||||
}
|
||||
if when, errParse := http.ParseTime(raw); errParse == nil {
|
||||
d := time.Until(when)
|
||||
if d <= 0 {
|
||||
return nil
|
||||
}
|
||||
return &d
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FetchProjectID retrieves the project ID for the authenticated user via loadCodeAssist
|
||||
func (o *AntigravityAuth) FetchProjectID(ctx context.Context, accessToken string) (string, error) {
|
||||
userAgent := o.shortUserAgent()
|
||||
@@ -285,6 +324,7 @@ func (o *AntigravityAuth) FetchProjectID(ctx context.Context, accessToken string
|
||||
return "", &HTTPStatusError{
|
||||
StatusCodeValue: resp.StatusCode,
|
||||
Message: fmt.Sprintf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes))),
|
||||
RetryAfterValue: retryAfterFromHeaders(resp.Header),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,6 +438,7 @@ func (o *AntigravityAuth) OnboardUser(ctx context.Context, accessToken, tierID s
|
||||
return "", &HTTPStatusError{
|
||||
StatusCodeValue: resp.StatusCode,
|
||||
Message: fmt.Sprintf("http %d: %s", resp.StatusCode, responseErr),
|
||||
RetryAfterValue: retryAfterFromHeaders(resp.Header),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type roundTripperFunc func(*http.Request) (*http.Response, error)
|
||||
@@ -170,3 +171,30 @@ func jsonResponse(body string) *http.Response {
|
||||
Body: io.NopCloser(strings.NewReader(body)),
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchProjectIDTooManyRequestsPreservesRetryAfter(t *testing.T) {
|
||||
auth := NewAntigravityAuth(nil, &http.Client{Transport: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
header := make(http.Header)
|
||||
header.Set("Retry-After", "45")
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusTooManyRequests,
|
||||
Header: header,
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":{"code":429,"message":"rate limited"}}`)),
|
||||
}, nil
|
||||
})})
|
||||
|
||||
_, err := auth.FetchProjectID(context.Background(), "access-token")
|
||||
if err == nil {
|
||||
t.Fatalf("expected error from 429 response")
|
||||
}
|
||||
type retryAfterProvider interface {
|
||||
RetryAfter() *time.Duration
|
||||
}
|
||||
rap, ok := err.(retryAfterProvider)
|
||||
if !ok {
|
||||
t.Fatalf("expected error to expose RetryAfter, got %T (%v)", err, err)
|
||||
}
|
||||
if got := rap.RetryAfter(); got == nil || *got != 45*time.Second {
|
||||
t.Fatalf("RetryAfter() = %v, want 45s", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
|
||||
sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth"
|
||||
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
||||
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/sdk/httptransport"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -32,7 +33,7 @@ func (e *AntigravityExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Au
|
||||
if auth == nil {
|
||||
return auth, nil
|
||||
}
|
||||
updated, errRefresh := e.refreshToken(ctx, auth.Clone())
|
||||
updated, errRefresh := e.refreshToken(ctx, auth.Clone(), ctx)
|
||||
if errRefresh != nil {
|
||||
return nil, errRefresh
|
||||
}
|
||||
@@ -62,10 +63,10 @@ func (e *AntigravityExecutor) PrepareRequestAuth(ctx context.Context, auth *clip
|
||||
|
||||
projectID, errProject := e.fetchAntigravityProjectID(ctx, updated, token)
|
||||
if errProject != nil {
|
||||
return nil, missingAntigravityProjectIDError(errProject)
|
||||
return nil, prepareAntigravityProjectIDError(errProject)
|
||||
}
|
||||
if projectID == "" {
|
||||
return nil, missingAntigravityProjectIDError(nil)
|
||||
return nil, prepareAntigravityProjectIDError(nil)
|
||||
}
|
||||
if updated.Metadata == nil {
|
||||
updated.Metadata = make(map[string]any)
|
||||
@@ -102,14 +103,14 @@ func (e *AntigravityExecutor) ensureAccessToken(ctx context.Context, auth *clipr
|
||||
return token, refreshed, nil
|
||||
}
|
||||
|
||||
updated, errRefresh := e.refreshToken(refreshCtx, auth.Clone())
|
||||
updated, errRefresh := e.refreshToken(refreshCtx, auth.Clone(), ctx)
|
||||
if errRefresh != nil {
|
||||
return "", nil, errRefresh
|
||||
}
|
||||
return metaStringValue(updated.Metadata, "access_token"), updated, nil
|
||||
}
|
||||
|
||||
func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyauth.Auth, requestCtx context.Context) (*cliproxyauth.Auth, error) {
|
||||
if auth == nil {
|
||||
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing auth"}
|
||||
}
|
||||
@@ -129,6 +130,12 @@ func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyau
|
||||
return e.refreshTokenSingleFlight(refreshCtx, auth, refreshToken)
|
||||
})
|
||||
if errRefresh != nil {
|
||||
// Any error returned by the shared flight came from the real OAuth HTTP
|
||||
// call inside the closure (local missing-credential checks return above,
|
||||
// before the group call). Attribute it as an upstream attempt on THIS
|
||||
// request's tracker so concurrent callers sharing the flight each record
|
||||
// the upstream failure on their own tracker, not just the leader's.
|
||||
cliproxyexecutor.MarkUpstreamAttempt(requestCtx)
|
||||
return auth, errRefresh
|
||||
}
|
||||
tokenResp, ok := result.(*antigravityTokenRefreshData)
|
||||
@@ -188,7 +195,9 @@ func (e *AntigravityExecutor) refreshTokenSingleFlight(ctx context.Context, auth
|
||||
}
|
||||
|
||||
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
|
||||
sErr := statusErr{code: httpResp.StatusCode, msg: string(bodyBytes)}
|
||||
// Token refresh failures are credential-scoped: the credential cannot be
|
||||
// used for any model until it recovers.
|
||||
sErr := statusErr{code: httpResp.StatusCode, msg: string(bodyBytes), credentialScoped: true}
|
||||
if httpResp.StatusCode == http.StatusTooManyRequests {
|
||||
if retryAfter, parseErr := helps.ParseRetryDelay(bodyBytes); parseErr == nil && retryAfter != nil {
|
||||
sErr.retryAfter = retryAfter
|
||||
@@ -307,6 +316,7 @@ func (e *AntigravityExecutor) fetchAntigravityProjectID(ctx context.Context, aut
|
||||
tracedClient := helps.WithAntigravityHTTPClientTrace(httpClient, auth, "project_discovery")
|
||||
projectID, errFetch := sdkAuth.FetchAntigravityProjectID(acquisitionCtx, token, tracedClient)
|
||||
if errFetch != nil {
|
||||
cliproxyexecutor.MarkUpstreamAttempt(ctx)
|
||||
return "", errFetch
|
||||
}
|
||||
return strings.TrimSpace(projectID), nil
|
||||
@@ -355,6 +365,29 @@ func missingAntigravityProjectIDError(cause error) statusErr {
|
||||
return statusErr{code: statusCode, msg: msg, retryAfter: retryAfter}
|
||||
}
|
||||
|
||||
// prepareAntigravityProjectIDError wraps a project-discovery failure during
|
||||
// PrepareRequestAuth. A real upstream HTTP status is preserved verbatim so
|
||||
// genuine 400/403/429 responses keep their classification; a cause with no
|
||||
// HTTP status (transport/proxy failure, or no project_id resolved without an
|
||||
// upstream response) is reported as a transient transport problem rather than
|
||||
// an invalid-request 400, so credential rotation is not halted prematurely.
|
||||
// The failure is credential-scoped because the credential cannot serve any
|
||||
// model until discovery succeeds.
|
||||
func prepareAntigravityProjectIDError(cause error) statusErr {
|
||||
base := missingAntigravityProjectIDError(cause)
|
||||
base.credentialScoped = true
|
||||
type statusCoder interface {
|
||||
StatusCode() int
|
||||
}
|
||||
var sc statusCoder
|
||||
hasUpstreamStatus := cause != nil && errors.As(cause, &sc) && sc != nil && sc.StatusCode() > 0
|
||||
if !hasUpstreamStatus {
|
||||
base.code = http.StatusServiceUnavailable
|
||||
base.transientTransport = true
|
||||
}
|
||||
return base
|
||||
}
|
||||
|
||||
func metaStringValue(metadata map[string]any, key string) string {
|
||||
if metadata == nil {
|
||||
return ""
|
||||
|
||||
@@ -2,9 +2,11 @@ package executor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -733,3 +735,128 @@ func TestAntigravityExecutorSynthesizedSessionIDScopedPerCredential(t *testing.T
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAntigravityPrepareRequestAuth_DiscoveryTransportErrorIsNotClientFault
|
||||
// verifies that a project-discovery failure without an upstream HTTP status
|
||||
// (for example a proxy connect error) is reported as a transient transport
|
||||
// problem rather than an invalid-request 400, so the conductor does not halt
|
||||
// credential rotation on a request that could succeed on another credential.
|
||||
func TestAntigravityPrepareRequestAuth_DiscoveryTransportErrorIsNotClientFault(t *testing.T) {
|
||||
executor := &AntigravityExecutor{}
|
||||
auth := &cliproxyauth.Auth{Metadata: map[string]any{
|
||||
"access_token": "token",
|
||||
"expired": time.Now().Add(1 * time.Hour).Format(time.RFC3339),
|
||||
}}
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("proxy connect: connection refused")
|
||||
}))
|
||||
|
||||
_, err := executor.PrepareRequestAuth(ctx, auth)
|
||||
if err == nil {
|
||||
t.Fatalf("PrepareRequestAuth should fail on transport error")
|
||||
}
|
||||
status, ok := err.(interface{ StatusCode() int })
|
||||
if !ok {
|
||||
t.Fatalf("error should expose StatusCode(), got %T (%v)", err, err)
|
||||
}
|
||||
if got := status.StatusCode(); got == http.StatusBadRequest {
|
||||
t.Fatalf("status code = %d, transport failure must not masquerade as invalid-request 400", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAntigravityPrepareRequestAuth_MissingRefreshTokenIsNotUpstreamAttempt
|
||||
// verifies that a credential missing a refresh token fails as a local
|
||||
// preparation error and does not mark an upstream attempt, so it cannot
|
||||
// outrank a genuine upstream rejection recorded earlier in the round.
|
||||
func TestAntigravityPrepareRequestAuth_MissingRefreshTokenIsNotUpstreamAttempt(t *testing.T) {
|
||||
executor := &AntigravityExecutor{}
|
||||
auth := &cliproxyauth.Auth{Metadata: map[string]any{
|
||||
// access_token present but already expired and no refresh_token: the
|
||||
// credential fails locally before any HTTP request is issued.
|
||||
"access_token": "expired-token",
|
||||
"expired": time.Now().Add(-1 * time.Hour).Format(time.RFC3339),
|
||||
}}
|
||||
ctx := cliproxyexecutor.WithUpstreamAttemptTracker(context.Background())
|
||||
|
||||
_, err := executor.PrepareRequestAuth(ctx, auth)
|
||||
if err == nil {
|
||||
t.Fatalf("PrepareRequestAuth should fail without refresh token")
|
||||
}
|
||||
if cliproxyexecutor.UpstreamAttempted(ctx) {
|
||||
t.Fatalf("missing refresh token must not mark an upstream attempt")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAntigravityPrepareRequestAuth_OAuthRefreshFailureMarksUpstreamAttempt
|
||||
// verifies that a genuine upstream rejection during OAuth token refresh (e.g.
|
||||
// a 403 from the token endpoint) marks the request's upstream-attempt tracker,
|
||||
// so the conductor can attribute it as a real upstream error that outranks
|
||||
// later local credential-preparation failures.
|
||||
func TestAntigravityPrepareRequestAuth_OAuthRefreshFailureMarksUpstreamAttempt(t *testing.T) {
|
||||
executor := &AntigravityExecutor{}
|
||||
auth := &cliproxyauth.Auth{Metadata: map[string]any{
|
||||
// expired access token + refresh token: forces the OAuth refresh path,
|
||||
// which performs a real upstream HTTP call that fails with 403.
|
||||
"access_token": "expired-token",
|
||||
"refresh_token": "refresh-token",
|
||||
"expired": time.Now().Add(-1 * time.Hour).Format(time.RFC3339),
|
||||
}}
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusForbidden,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":"access_denied"}`)),
|
||||
}, nil
|
||||
}))
|
||||
ctx = cliproxyexecutor.WithUpstreamAttemptTracker(ctx)
|
||||
|
||||
_, err := executor.PrepareRequestAuth(ctx, auth)
|
||||
if err == nil {
|
||||
t.Fatalf("PrepareRequestAuth should fail on upstream 403 during refresh")
|
||||
}
|
||||
if !cliproxyexecutor.UpstreamAttempted(ctx) {
|
||||
t.Fatalf("upstream refresh 403 should mark the upstream attempt tracker")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAntigravityPrepareRequestAuth_SharedRefreshFailureMarksEachTracker
|
||||
// verifies that when concurrent requests share one singleflight OAuth refresh
|
||||
// that fails upstream, EACH request's own upstream-attempt tracker is marked —
|
||||
// not only the tracker of the request that led the flight.
|
||||
func TestAntigravityPrepareRequestAuth_SharedRefreshFailureMarksEachTracker(t *testing.T) {
|
||||
executor := &AntigravityExecutor{}
|
||||
newAuth := func() *cliproxyauth.Auth {
|
||||
return &cliproxyauth.Auth{Metadata: map[string]any{
|
||||
"access_token": "expired-token",
|
||||
"refresh_token": "shared-refresh-token",
|
||||
"expired": time.Now().Add(-1 * time.Hour).Format(time.RFC3339),
|
||||
}}
|
||||
}
|
||||
rt := roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
// Slow enough that both callers join the same singleflight refresh.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusForbidden,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"error":"access_denied"}`)),
|
||||
}, nil
|
||||
})
|
||||
newCtx := func() context.Context {
|
||||
c := context.WithValue(context.Background(), "cliproxy.roundtripper", rt)
|
||||
return cliproxyexecutor.WithUpstreamAttemptTracker(c)
|
||||
}
|
||||
|
||||
ctxA, ctxB := newCtx(), newCtx()
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() { defer wg.Done(); _, _ = executor.PrepareRequestAuth(ctxA, newAuth()) }()
|
||||
go func() { defer wg.Done(); _, _ = executor.PrepareRequestAuth(ctxB, newAuth()) }()
|
||||
wg.Wait()
|
||||
|
||||
if !cliproxyexecutor.UpstreamAttempted(ctxA) {
|
||||
t.Fatalf("request A tracker was not marked on shared upstream refresh failure")
|
||||
}
|
||||
if !cliproxyexecutor.UpstreamAttempted(ctxB) {
|
||||
t.Fatalf("request B tracker was not marked on shared upstream refresh failure")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1098,6 +1098,10 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req
|
||||
var errPrepare error
|
||||
auth, errPrepare = m.prepareRequestAuth(execCtx, executor, auth)
|
||||
if errPrepare != nil {
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if hasUpstreamExecutionAttempt(errPrepare) {
|
||||
upstreamErr = errPrepare
|
||||
}
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
return cliproxyexecutor.Response{}, errCtx
|
||||
}
|
||||
@@ -1109,7 +1113,23 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req
|
||||
stateModel = canonicalModelKey(routeModel)
|
||||
}
|
||||
result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch}
|
||||
if ra := retryAfterFromError(errPrepare); ra != nil {
|
||||
result.RetryAfter = ra
|
||||
}
|
||||
if isCredentialScopedError(errPrepare) {
|
||||
result.CredentialScope = true
|
||||
}
|
||||
action, okAction := matchRequestScopedErrorAction(auth, errPrepare, m.requestScopedErrorConfig(execCtx))
|
||||
applyRequestScopedActionToResult(action, okAction, &result)
|
||||
m.MarkResult(execCtx, result)
|
||||
errPrepare = annotateTrustedRetryAfterByHint(errPrepare)
|
||||
syncPreferredUpstreamError(&upstreamErr, errPrepare)
|
||||
if isRequestScopedStop(action, okAction) {
|
||||
return cliproxyexecutor.Response{}, wrapRequestStopError(errPrepare)
|
||||
}
|
||||
if !okAction && isRequestInvalidError(errPrepare) {
|
||||
return cliproxyexecutor.Response{}, errPrepare
|
||||
}
|
||||
lastErr = keepPreferredCandidateError(lastErr, errPrepare)
|
||||
continue
|
||||
}
|
||||
@@ -1340,6 +1360,10 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string,
|
||||
var errPrepare error
|
||||
auth, errPrepare = m.prepareRequestAuth(execCtx, executor, auth)
|
||||
if errPrepare != nil {
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if hasUpstreamExecutionAttempt(errPrepare) {
|
||||
upstreamErr = errPrepare
|
||||
}
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
return cliproxyexecutor.Response{}, errCtx
|
||||
}
|
||||
@@ -1351,7 +1375,23 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string,
|
||||
stateModel = canonicalModelKey(routeModel)
|
||||
}
|
||||
result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, SkipQuotaObservation: true, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch}
|
||||
if ra := retryAfterFromError(errPrepare); ra != nil {
|
||||
result.RetryAfter = ra
|
||||
}
|
||||
if isCredentialScopedError(errPrepare) {
|
||||
result.CredentialScope = true
|
||||
}
|
||||
action, okAction := matchRequestScopedErrorAction(auth, errPrepare, m.requestScopedErrorConfig(execCtx))
|
||||
applyRequestScopedActionToResult(action, okAction, &result)
|
||||
m.MarkResult(execCtx, result)
|
||||
errPrepare = annotateTrustedRetryAfterByHint(errPrepare)
|
||||
syncPreferredUpstreamError(&upstreamErr, errPrepare)
|
||||
if isRequestScopedStop(action, okAction) {
|
||||
return cliproxyexecutor.Response{}, wrapRequestStopError(errPrepare)
|
||||
}
|
||||
if !okAction && isRequestInvalidError(errPrepare) {
|
||||
return cliproxyexecutor.Response{}, errPrepare
|
||||
}
|
||||
lastErr = keepPreferredCandidateError(lastErr, errPrepare)
|
||||
continue
|
||||
}
|
||||
@@ -1742,6 +1782,10 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string
|
||||
auth, errPrepare = m.prepareRequestAuth(execCtx, executor, auth)
|
||||
}
|
||||
if errPrepare != nil {
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if hasUpstreamExecutionAttempt(errPrepare) {
|
||||
upstreamErr = errPrepare
|
||||
}
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
if selection != nil {
|
||||
releaseAttempt()
|
||||
@@ -1770,12 +1814,34 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string
|
||||
stateModel = canonicalModelKey(routeModel)
|
||||
}
|
||||
result := Result{AuthID: auth.ID, Provider: provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: pickOpts, AccessToken: authAccessTokenForRequest(execCtx, auth, pickOpts.Headers), RefreshToken: authRefreshToken(auth), CredentialVersion: auth.CredentialVersion, RegistrationEpoch: auth.RegistrationEpoch}
|
||||
if ra := retryAfterFromError(errPrepare); ra != nil {
|
||||
result.RetryAfter = ra
|
||||
}
|
||||
if isCredentialScopedError(errPrepare) {
|
||||
result.CredentialScope = true
|
||||
}
|
||||
action, okAction := matchRequestScopedErrorAction(auth, errPrepare, m.requestScopedErrorConfig(execCtx))
|
||||
applyRequestScopedActionToResult(action, okAction, &result)
|
||||
if selection != nil {
|
||||
m.reportHomeResult(execCtx, result, auth)
|
||||
releaseAttempt()
|
||||
} else {
|
||||
m.MarkResult(execCtx, result)
|
||||
}
|
||||
errPrepare = annotateTrustedRetryAfterByHint(errPrepare)
|
||||
syncPreferredUpstreamError(&upstreamErr, errPrepare)
|
||||
if isRequestScopedStop(action, okAction) {
|
||||
if selection != nil {
|
||||
selection.End("request_stopped")
|
||||
}
|
||||
return nil, wrapRequestStopError(errPrepare)
|
||||
}
|
||||
if !okAction && isRequestInvalidError(errPrepare) {
|
||||
if selection != nil {
|
||||
selection.End("request_invalid")
|
||||
}
|
||||
return nil, errPrepare
|
||||
}
|
||||
lastErr = keepPreferredCandidateError(lastErr, errPrepare)
|
||||
if homeMode {
|
||||
roundTiming.Observe(errPrepare)
|
||||
|
||||
@@ -275,6 +275,10 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c
|
||||
}
|
||||
preparedAuth, errPrepare := m.prepareHomeRequestAuth(execCtx, selection.Executor, selection)
|
||||
if errPrepare != nil {
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if hasUpstreamExecutionAttempt(errPrepare) {
|
||||
upstreamErr = errPrepare
|
||||
}
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
releaseAttempt()
|
||||
selection.End("attempt_canceled")
|
||||
@@ -284,8 +288,27 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c
|
||||
if stateModel == "" {
|
||||
stateModel = canonicalModelKey(routeModel)
|
||||
}
|
||||
m.reportHomeResult(execCtx, Result{AuthID: auth.ID, Provider: selection.Provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: opts}, auth)
|
||||
result := Result{AuthID: auth.ID, Provider: selection.Provider, Model: stateModel, RouteModel: routeModel, Success: false, Error: resultErrorFromError(errPrepare), Options: opts}
|
||||
if ra := retryAfterFromError(errPrepare); ra != nil {
|
||||
result.RetryAfter = ra
|
||||
}
|
||||
if isCredentialScopedError(errPrepare) {
|
||||
result.CredentialScope = true
|
||||
}
|
||||
action, okAction := matchRequestScopedErrorAction(auth, errPrepare, m.requestScopedErrorConfig(execCtx))
|
||||
applyRequestScopedActionToResult(action, okAction, &result)
|
||||
m.reportHomeResult(execCtx, result, auth)
|
||||
releaseAttempt()
|
||||
errPrepare = annotateTrustedRetryAfterByHint(errPrepare)
|
||||
syncPreferredUpstreamError(&upstreamErr, errPrepare)
|
||||
if isRequestScopedStop(action, okAction) {
|
||||
selection.End("request_stopped")
|
||||
return cliproxyexecutor.Response{}, wrapRequestStopError(errPrepare)
|
||||
}
|
||||
if !okAction && isRequestInvalidError(errPrepare) {
|
||||
selection.End("request_invalid")
|
||||
return cliproxyexecutor.Response{}, errPrepare
|
||||
}
|
||||
if errEnd := m.endHomeSelectionBeforeRedispatch(ctx, selection, "prepare_failed"); errEnd != nil {
|
||||
return cliproxyexecutor.Response{}, errEnd
|
||||
}
|
||||
|
||||
288
sdk/cliproxy/auth/conductor_prepare_request_auth_errors_test.go
Normal file
288
sdk/cliproxy/auth/conductor_prepare_request_auth_errors_test.go
Normal file
@@ -0,0 +1,288 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
|
||||
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
||||
)
|
||||
|
||||
// credentialScopedStatusError mirrors antigravity's statusErr for a
|
||||
// credential-scoped upstream failure (e.g. a 429 from project discovery) so
|
||||
// isCredentialScopedError can classify it correctly.
|
||||
type credentialScopedStatusError struct {
|
||||
code int
|
||||
msg string
|
||||
retryAfter *time.Duration
|
||||
}
|
||||
|
||||
func (e credentialScopedStatusError) Error() string { return e.msg }
|
||||
func (e credentialScopedStatusError) StatusCode() int { return e.code }
|
||||
func (e credentialScopedStatusError) RetryAfter() *time.Duration { return e.retryAfter }
|
||||
func (e credentialScopedStatusError) IsCredentialScoped() bool { return true }
|
||||
|
||||
// countingPrepareExecutor returns a configurable error from PrepareRequestAuth
|
||||
// and counts how many credentials were prepared so tests can assert that a
|
||||
// request-scoped stop prevents rotation across the remaining pool.
|
||||
type countingPrepareExecutor struct {
|
||||
prepareCalls atomic.Int32
|
||||
prepareErr error
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) Identifier() string { return "antigravity" }
|
||||
|
||||
func (e *countingPrepareExecutor) ShouldPrepareRequestAuth(auth *Auth) bool {
|
||||
return auth == nil || auth.Metadata == nil || testStringValue(auth.Metadata["project_id"]) == ""
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) PrepareRequestAuth(ctx context.Context, auth *Auth) (*Auth, error) {
|
||||
e.prepareCalls.Add(1)
|
||||
if e.prepareErr != nil {
|
||||
cliproxyexecutor.MarkUpstreamAttempt(ctx)
|
||||
return nil, e.prepareErr
|
||||
}
|
||||
updated := auth.Clone()
|
||||
if updated.Metadata == nil {
|
||||
updated.Metadata = make(map[string]any)
|
||||
}
|
||||
updated.Metadata["project_id"] = "prepared-project"
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) Execute(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
return cliproxyexecutor.Response{Payload: []byte("ok")}, nil
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) {
|
||||
chunks := make(chan cliproxyexecutor.StreamChunk, 1)
|
||||
chunks <- cliproxyexecutor.StreamChunk{Payload: []byte(`{"type":"response.completed"}`)}
|
||||
close(chunks)
|
||||
return &cliproxyexecutor.StreamResult{Chunks: chunks}, nil
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) {
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
return cliproxyexecutor.Response{Payload: []byte("ok")}, nil
|
||||
}
|
||||
|
||||
func (e *countingPrepareExecutor) HttpRequest(context.Context, *Auth, *http.Request) (*http.Response, error) {
|
||||
return nil, &Error{HTTPStatus: http.StatusNotImplemented, Message: "http not implemented"}
|
||||
}
|
||||
|
||||
// registerPrepareAuths registers three antigravity credentials sharing the same
|
||||
// request-scoped error rules so every prepared credential evaluates the same
|
||||
// rule set.
|
||||
func registerPrepareAuths(t *testing.T, manager *Manager, model string, rules []internalconfig.RequestScopedErrorRule) []*Auth {
|
||||
t.Helper()
|
||||
auths := make([]*Auth, 0, 3)
|
||||
reg := registry.GetGlobalRegistry()
|
||||
for _, id := range []string{"prepare-auth-1", "prepare-auth-2", "prepare-auth-3"} {
|
||||
auth := &Auth{
|
||||
ID: id,
|
||||
Provider: "antigravity",
|
||||
Status: StatusActive,
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-" + id,
|
||||
"request_scoped_errors": rules,
|
||||
},
|
||||
}
|
||||
if _, errRegister := manager.Register(WithSkipPersist(context.Background()), auth); errRegister != nil {
|
||||
t.Fatalf("register auth %s: %v", id, errRegister)
|
||||
}
|
||||
reg.RegisterClient(id, "antigravity", []*registry.ModelInfo{{ID: model}})
|
||||
auths = append(auths, auth)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
for _, auth := range auths {
|
||||
reg.UnregisterClient(auth.ID)
|
||||
}
|
||||
})
|
||||
return auths
|
||||
}
|
||||
|
||||
func TestPrepareRequestAuthScopedStopDoesNotRotate(t *testing.T) {
|
||||
previous := quotaCooldownDisabled.Load()
|
||||
quotaCooldownDisabled.Store(false)
|
||||
t.Cleanup(func() { quotaCooldownDisabled.Store(previous) })
|
||||
|
||||
const model = "gemini-3.1-pro"
|
||||
rules := []internalconfig.RequestScopedErrorRule{
|
||||
{Status: http.StatusForbidden, Match: []string{"TOS_VIOLATION"}, Action: "stop"},
|
||||
}
|
||||
executor := &countingPrepareExecutor{
|
||||
prepareErr: customStatusError{code: http.StatusForbidden, msg: `{"error":{"reason":"TOS_VIOLATION"}}`},
|
||||
}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(executor)
|
||||
registerPrepareAuths(t, manager, model, rules)
|
||||
|
||||
_, errExecute := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{})
|
||||
if errExecute == nil {
|
||||
t.Fatal("expected Execute error on 403 prepare failure")
|
||||
}
|
||||
if got := executor.prepareCalls.Load(); got != 1 {
|
||||
t.Fatalf("prepare calls = %d, want 1 (request-scoped stop must prevent rotation)", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareRequestAuthRetryAfterAndCredentialScopeRecorded(t *testing.T) {
|
||||
previous := quotaCooldownDisabled.Load()
|
||||
quotaCooldownDisabled.Store(false)
|
||||
t.Cleanup(func() { quotaCooldownDisabled.Store(previous) })
|
||||
|
||||
const model = "gemini-3.1-pro"
|
||||
retryAfter := 45 * time.Second
|
||||
executor := &countingPrepareExecutor{
|
||||
prepareErr: credentialScopedStatusError{
|
||||
code: http.StatusTooManyRequests,
|
||||
msg: "rate limited",
|
||||
retryAfter: &retryAfter,
|
||||
},
|
||||
}
|
||||
hook := &captureResultHook{done: make(chan Result, 1)}
|
||||
manager := NewManager(nil, nil, hook)
|
||||
manager.RegisterExecutor(executor)
|
||||
registerPrepareAuths(t, manager, model, nil)
|
||||
|
||||
_, errExecute := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{})
|
||||
if errExecute == nil {
|
||||
t.Fatal("expected Execute error on 429 prepare failure")
|
||||
}
|
||||
|
||||
recorded := <-hook.done
|
||||
if recorded.RetryAfter == nil || *recorded.RetryAfter != retryAfter {
|
||||
t.Fatalf("recorded.RetryAfter = %v, want %v", recorded.RetryAfter, retryAfter)
|
||||
}
|
||||
// A 429 from PrepareRequestAuth is credential-scoped: the failing credential
|
||||
// must cool down so sibling models on the same credential are not retried.
|
||||
if !recorded.CredentialScope {
|
||||
t.Fatal("recorded.CredentialScope = false, want true for credential-scoped prepare failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareRequestAuthInvalidRequestStopsRotation(t *testing.T) {
|
||||
previous := quotaCooldownDisabled.Load()
|
||||
quotaCooldownDisabled.Store(false)
|
||||
t.Cleanup(func() { quotaCooldownDisabled.Store(previous) })
|
||||
|
||||
const model = "gemini-3.1-pro"
|
||||
executor := &countingPrepareExecutor{
|
||||
prepareErr: customStatusError{code: http.StatusBadRequest, msg: `{"error":{"message":"invalid request"}}`},
|
||||
}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(executor)
|
||||
registerPrepareAuths(t, manager, model, nil)
|
||||
|
||||
_, errExecute := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{})
|
||||
if errExecute == nil {
|
||||
t.Fatal("expected Execute error on 400 prepare failure")
|
||||
}
|
||||
if got := executor.prepareCalls.Load(); got != 1 {
|
||||
t.Fatalf("prepare calls = %d, want 1 (400 invalid request must stop rotation)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareRequestAuthUpstreamErrorPreferred verifies the upstream error from
|
||||
// PrepareRequestAuth is preferred over the synthetic auth_unavailable pick error
|
||||
// once the pool is exhausted.
|
||||
func TestPrepareRequestAuthUpstreamErrorPreferred(t *testing.T) {
|
||||
previous := quotaCooldownDisabled.Load()
|
||||
quotaCooldownDisabled.Store(false)
|
||||
t.Cleanup(func() { quotaCooldownDisabled.Store(previous) })
|
||||
|
||||
const model = "gemini-3.1-pro"
|
||||
prepareErr := customStatusError{code: http.StatusForbidden, msg: "upstream tos violation"}
|
||||
executor := &countingPrepareExecutor{prepareErr: prepareErr}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(executor)
|
||||
registerPrepareAuths(t, manager, model, nil)
|
||||
|
||||
_, errExecute := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{})
|
||||
if errExecute == nil {
|
||||
t.Fatal("expected Execute error")
|
||||
}
|
||||
// The surfaced error must be the upstream 403, not an auth_unavailable pick
|
||||
// failure that masks the real upstream rejection.
|
||||
var statusCoder interface{ StatusCode() int }
|
||||
if !errors.As(errExecute, &statusCoder) || statusCoder.StatusCode() != http.StatusForbidden {
|
||||
t.Fatalf("Execute() error = %T/%v, want upstream 403 status", errExecute, errExecute)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareRequestAuthTransportErrorKeepsRotating verifies that a prepare
|
||||
// failure with no upstream HTTP status (e.g. a transport/network error or a
|
||||
// locally synthesized missing-project-id error) is not mistaken for a client
|
||||
// request fault, so credential rotation continues to the next credential.
|
||||
func TestPrepareRequestAuthTransportErrorKeepsRotating(t *testing.T) {
|
||||
previous := quotaCooldownDisabled.Load()
|
||||
quotaCooldownDisabled.Store(false)
|
||||
t.Cleanup(func() { quotaCooldownDisabled.Store(previous) })
|
||||
|
||||
const model = "gemini-3.1-pro"
|
||||
executor := &countingPrepareExecutor{
|
||||
// No HTTP status code: mirrors a transport/proxy failure or a locally
|
||||
// synthesized missing-project_id error, which must not be classified as
|
||||
// a client request fault.
|
||||
prepareErr: errors.New("proxy connect: connection refused"),
|
||||
}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(executor)
|
||||
registerPrepareAuths(t, manager, model, nil)
|
||||
|
||||
_, errExecute := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{})
|
||||
if errExecute == nil {
|
||||
t.Fatal("expected Execute error")
|
||||
}
|
||||
// A transport-style failure is not a client request fault, so the manager
|
||||
// must keep rotating through the remaining credentials rather than stopping
|
||||
// after the first.
|
||||
if got := executor.prepareCalls.Load(); got != 3 {
|
||||
t.Fatalf("prepare calls = %d, want 3 (transport failure must keep rotating)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPrepareRequestAuthStopPreservesRetryAfterHeader verifies that when a
|
||||
// request-scoped stop rule matches an upstream 429 from PrepareRequestAuth, the
|
||||
// returned stop error still exposes the trusted Retry-After header so the
|
||||
// client receives the provider-supplied recovery deadline.
|
||||
func TestPrepareRequestAuthStopPreservesRetryAfterHeader(t *testing.T) {
|
||||
previous := quotaCooldownDisabled.Load()
|
||||
quotaCooldownDisabled.Store(false)
|
||||
t.Cleanup(func() { quotaCooldownDisabled.Store(previous) })
|
||||
|
||||
const model = "gemini-3.1-pro"
|
||||
retryAfter := 45 * time.Second
|
||||
rules := []internalconfig.RequestScopedErrorRule{
|
||||
{Status: http.StatusTooManyRequests, Match: []string{"rate limited"}, Action: "stop"},
|
||||
}
|
||||
executor := &countingPrepareExecutor{
|
||||
prepareErr: credentialScopedStatusError{
|
||||
code: http.StatusTooManyRequests,
|
||||
msg: "rate limited",
|
||||
retryAfter: &retryAfter,
|
||||
},
|
||||
}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(executor)
|
||||
registerPrepareAuths(t, manager, model, rules)
|
||||
|
||||
_, errExecute := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{Model: model}, cliproxyexecutor.Options{})
|
||||
if errExecute == nil {
|
||||
t.Fatal("expected Execute error on 429 stop prepare failure")
|
||||
}
|
||||
if got := executor.prepareCalls.Load(); got != 1 {
|
||||
t.Fatalf("prepare calls = %d, want 1 (request-scoped stop must prevent rotation)", got)
|
||||
}
|
||||
if hdr := SafeResponseHeaders(errExecute).Get("Retry-After"); hdr == "" {
|
||||
t.Fatalf("expected Retry-After header on stop error, headers=%v", SafeResponseHeaders(errExecute))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user