mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-11-26 20:03:32 +08:00
fix(antigravity): persist execution-time token refreshes and preserve refresh context values
- Route Antigravity execution-time OAuth refreshes through a Manager refresh coordinator that serializes per-credential refreshes, persists rotated tokens with detached cancellation, updates in-flight MarkResult auth state, and keeps Home-dispatched snapshots isolated from local credentials. - Preserve non-cancellation context values such as httptransport.Decorator and custom round trippers via context.WithoutCancel while stripping execution-scoped RequestProxyURL across OAuth refresh, project discovery, and credits hint refreshes. - Add race-tested regression tests covering single refresh persistence, client cancellation, project discovery failure, safety-window crossing, unsupported attachments, Home isolation, request preparation context preservation, and proxy isolation. Closes: #7749
This commit is contained in:
@@ -27,6 +27,8 @@ const antigravityCredentialAcquisitionTimeout = 30 * time.Second
|
||||
|
||||
var antigravityInitialBaseTransport = antigravityBaseTransport
|
||||
|
||||
var antigravityNow = time.Now
|
||||
|
||||
// Refresh refreshes the authentication credentials using the refresh token.
|
||||
func (e *AntigravityExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if refreshed, handled, err := helps.RefreshAuthViaHome(ctx, e.cfg, auth); handled {
|
||||
@@ -43,9 +45,36 @@ func (e *AntigravityExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Au
|
||||
}
|
||||
|
||||
func (e *AntigravityExecutor) ShouldPrepareRequestAuth(auth *cliproxyauth.Auth) bool {
|
||||
if auth == nil {
|
||||
return false
|
||||
}
|
||||
return antigravityProjectIDFromAuth(auth) == ""
|
||||
}
|
||||
|
||||
func antigravityNeedsAccessTokenRefresh(auth *cliproxyauth.Auth) bool {
|
||||
if auth == nil {
|
||||
return false
|
||||
}
|
||||
accessToken := metaStringValue(auth.Metadata, "access_token")
|
||||
if accessToken == "" {
|
||||
return true
|
||||
}
|
||||
expiry, _ := auth.ExpirationTime()
|
||||
return !expiry.After(antigravityNow().Add(antigravityRequestTokenSafetyWindow))
|
||||
}
|
||||
|
||||
// detachedAntigravityCredentialContext preserves non-cancellation context
|
||||
// values (such as transport decorators and injected round trippers) while
|
||||
// detaching caller cancellation and stripping execution-scoped request proxy
|
||||
// overrides so credential refresh and credential-wide metadata stay on the
|
||||
// credential or global proxy.
|
||||
func detachedAntigravityCredentialContext(ctx context.Context) context.Context {
|
||||
if ctx == nil {
|
||||
return context.Background()
|
||||
}
|
||||
return cliproxyexecutor.WithoutRequestProxyURL(context.WithoutCancel(ctx))
|
||||
}
|
||||
|
||||
func (e *AntigravityExecutor) PrepareRequestAuth(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if auth == nil || !e.ShouldPrepareRequestAuth(auth) {
|
||||
return nil, nil
|
||||
@@ -83,23 +112,13 @@ func (e *AntigravityExecutor) PrepareRequestAuth(ctx context.Context, auth *clip
|
||||
}
|
||||
updated.Metadata["project_id"] = projectID
|
||||
if refreshedLocal {
|
||||
e.queueAntigravityCreditsRefresh(detachedRoundTripperContext(ctx), updated, token, 0)
|
||||
e.queueAntigravityCreditsRefresh(detachedAntigravityCredentialContext(ctx), updated, token, 0)
|
||||
} else {
|
||||
e.maybeRefreshAntigravityCreditsHint(ctx, updated, token)
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func detachedRoundTripperContext(ctx context.Context) context.Context {
|
||||
detached := context.Background()
|
||||
if ctx != nil {
|
||||
if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil {
|
||||
detached = context.WithValue(detached, "cliproxy.roundtripper", rt)
|
||||
}
|
||||
}
|
||||
return detached
|
||||
}
|
||||
|
||||
func (e *AntigravityExecutor) ensureAccessToken(ctx context.Context, auth *cliproxyauth.Auth) (string, *cliproxyauth.Auth, error) {
|
||||
token, updated, _, errToken := e.ensureAccessTokenWithOptions(ctx, auth, true)
|
||||
return token, updated, errToken
|
||||
@@ -109,34 +128,59 @@ func (e *AntigravityExecutor) ensureAccessTokenWithOptions(ctx context.Context,
|
||||
if auth == nil {
|
||||
return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing auth"}
|
||||
}
|
||||
accessToken := metaStringValue(auth.Metadata, "access_token")
|
||||
expiry, _ := auth.ExpirationTime()
|
||||
if accessToken != "" && expiry.After(time.Now().Add(antigravityRequestTokenSafetyWindow)) {
|
||||
if !antigravityNeedsAccessTokenRefresh(auth) {
|
||||
accessToken := metaStringValue(auth.Metadata, "access_token")
|
||||
if discoverProject {
|
||||
e.maybeRefreshAntigravityCreditsHint(ctx, auth, accessToken)
|
||||
}
|
||||
return accessToken, nil, false, nil
|
||||
}
|
||||
refreshCtx := detachedRoundTripperContext(ctx)
|
||||
if refreshed, handled, err := helps.RefreshAuthViaHome(refreshCtx, e.cfg, auth); handled {
|
||||
if err != nil {
|
||||
return "", nil, false, err
|
||||
var refreshedLocal bool
|
||||
var refreshedViaHome bool
|
||||
updated, errRefresh := cliproxyauth.RefreshExecutionAuth(ctx, auth, func(callCtx context.Context, latest *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
|
||||
if !antigravityNeedsAccessTokenRefresh(latest) {
|
||||
return nil, nil
|
||||
}
|
||||
token := metaStringValue(refreshed.Metadata, "access_token")
|
||||
if strings.TrimSpace(token) == "" {
|
||||
return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing access token"}
|
||||
refreshCtx := detachedAntigravityCredentialContext(callCtx)
|
||||
if refreshed, handled, errHome := helps.RefreshAuthViaHome(refreshCtx, e.cfg, latest); handled {
|
||||
if errHome != nil {
|
||||
return nil, errHome
|
||||
}
|
||||
token := metaStringValue(refreshed.Metadata, "access_token")
|
||||
if strings.TrimSpace(token) == "" {
|
||||
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token"}
|
||||
}
|
||||
refreshedViaHome = true
|
||||
if discoverProject {
|
||||
e.maybeRefreshAntigravityCreditsHint(callCtx, refreshed, token)
|
||||
}
|
||||
return refreshed, nil
|
||||
}
|
||||
if discoverProject {
|
||||
e.maybeRefreshAntigravityCreditsHint(ctx, refreshed, token)
|
||||
refreshed, errToken := e.refreshTokenWithOptions(refreshCtx, latest.Clone(), callCtx, discoverProject)
|
||||
if errToken != nil {
|
||||
return nil, errToken
|
||||
}
|
||||
return token, refreshed, false, nil
|
||||
}
|
||||
|
||||
updated, errRefresh := e.refreshTokenWithOptions(refreshCtx, auth.Clone(), ctx, discoverProject)
|
||||
refreshedLocal = true
|
||||
return refreshed, nil
|
||||
})
|
||||
if errRefresh != nil {
|
||||
return "", nil, false, errRefresh
|
||||
}
|
||||
return metaStringValue(updated.Metadata, "access_token"), updated, true, nil
|
||||
if updated == nil {
|
||||
accessToken := metaStringValue(auth.Metadata, "access_token")
|
||||
if discoverProject {
|
||||
e.maybeRefreshAntigravityCreditsHint(ctx, auth, accessToken)
|
||||
}
|
||||
return accessToken, nil, false, nil
|
||||
}
|
||||
token := metaStringValue(updated.Metadata, "access_token")
|
||||
if strings.TrimSpace(token) == "" {
|
||||
return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing access token"}
|
||||
}
|
||||
if discoverProject && !refreshedLocal && !refreshedViaHome {
|
||||
e.maybeRefreshAntigravityCreditsHint(ctx, updated, token)
|
||||
}
|
||||
return token, updated, refreshedLocal, nil
|
||||
}
|
||||
|
||||
func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyauth.Auth, requestCtx context.Context) (*cliproxyauth.Auth, error) {
|
||||
@@ -154,6 +198,7 @@ func (e *AntigravityExecutor) refreshTokenWithOptions(ctx context.Context, auth
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
ctx = cliproxyexecutor.WithoutRequestProxyURL(ctx)
|
||||
refreshToken = strings.TrimSpace(refreshToken)
|
||||
|
||||
result, errRefresh, _ := antigravityRefreshGroup.Do(refreshToken, func() (interface{}, error) {
|
||||
@@ -345,7 +390,8 @@ func (e *AntigravityExecutor) fetchAntigravityProjectID(ctx context.Context, aut
|
||||
ctx = context.Background()
|
||||
}
|
||||
// Project discovery is required credential preparation, not a generation request.
|
||||
acquisitionCtx, cancelAcquisition := context.WithTimeout(ctx, antigravityCredentialAcquisitionTimeout)
|
||||
// Exclude execution-scoped request proxy overrides while preserving caller cancellation.
|
||||
acquisitionCtx, cancelAcquisition := context.WithTimeout(cliproxyexecutor.WithoutRequestProxyURL(ctx), antigravityCredentialAcquisitionTimeout)
|
||||
defer cancelAcquisition()
|
||||
httpClient := newAntigravityHTTPClient(acquisitionCtx, e.cfg, auth, 0)
|
||||
tracedClient := helps.WithAntigravityHTTPClientTrace(httpClient, auth, "project_discovery")
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
|
||||
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
||||
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
@@ -500,13 +501,7 @@ func (e *AntigravityExecutor) maybeRefreshAntigravityCreditsHint(ctx context.Con
|
||||
if !written {
|
||||
return
|
||||
}
|
||||
refreshCtx := context.Background()
|
||||
if ctx != nil {
|
||||
if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil {
|
||||
refreshCtx = context.WithValue(refreshCtx, "cliproxy.roundtripper", rt)
|
||||
}
|
||||
}
|
||||
refreshCtx, cancel := context.WithTimeout(refreshCtx, antigravityCreditsHintRefreshTimeout)
|
||||
refreshCtx, cancel := context.WithTimeout(detachedAntigravityCredentialContext(ctx), antigravityCreditsHintRefreshTimeout)
|
||||
authCopy := auth.Clone()
|
||||
go func(auth *cliproxyauth.Auth, token string) {
|
||||
defer cancel()
|
||||
@@ -572,17 +567,16 @@ func (e *AntigravityExecutor) queueAntigravityCreditsRefresh(ctx context.Context
|
||||
var refreshCtx context.Context
|
||||
var cancelRefresh context.CancelFunc
|
||||
if timeout > 0 {
|
||||
// Keep the existing independent warm-hint budget and transport selection.
|
||||
lifecycle = context.Background()
|
||||
if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil {
|
||||
lifecycle = context.WithValue(lifecycle, "cliproxy.roundtripper", rt)
|
||||
}
|
||||
// Keep the existing independent warm-hint budget and transport selection
|
||||
// while preserving non-cancellation context values and excluding
|
||||
// execution-scoped request proxy overrides.
|
||||
lifecycle = detachedAntigravityCredentialContext(ctx)
|
||||
refreshCtx, cancelRefresh = context.WithTimeout(lifecycle, timeout)
|
||||
} else {
|
||||
// Optional post-refresh work still follows the caller's lifecycle, but a
|
||||
// stalled upstream must not leak the goroutine or wedge state.task, so it
|
||||
// runs under the bounded warm-hint budget instead of an unbounded cancel.
|
||||
refreshCtx, cancelRefresh = context.WithTimeout(lifecycle, antigravityCreditsHintRefreshTimeout)
|
||||
refreshCtx, cancelRefresh = context.WithTimeout(cliproxyexecutor.WithoutRequestProxyURL(lifecycle), antigravityCreditsHintRefreshTimeout)
|
||||
}
|
||||
task := &antigravityCreditsRefreshTask{
|
||||
state: state,
|
||||
|
||||
1739
internal/runtime/executor/antigravity_refresh_issue7749_test.go
Normal file
1739
internal/runtime/executor/antigravity_refresh_issue7749_test.go
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1309,6 +1309,9 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req
|
||||
}
|
||||
preparedAuth, errPrepare := m.prepareRequestAuth(execCtx, executor, auth)
|
||||
if errPrepare != nil {
|
||||
if preparedAuth != nil {
|
||||
auth = preparedAuth
|
||||
}
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
return cliproxyexecutor.Response{}, errCtx
|
||||
@@ -1387,11 +1390,28 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req
|
||||
return cliproxyexecutor.Response{}, errIntercept
|
||||
}
|
||||
execReq = attachResolvedExecutionModelInfo(routing, execReq, auth, routeModel, upstreamModel, restoreExecutionModel)
|
||||
execCtx = withUpstreamAttemptProvider(syncMetadataSessionToContext(execCtx, execOpts.Metadata), provider)
|
||||
var activeAuth atomic.Pointer[Auth]
|
||||
activeAuth.Store(auth)
|
||||
syncActiveAuth := func() {
|
||||
if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != auth {
|
||||
auth = currentAuth
|
||||
}
|
||||
}
|
||||
refreshExecCtx := func(base context.Context) context.Context {
|
||||
return m.withExecutionAuthRefresh(base, executionAuthRefreshOptions{
|
||||
onAuthUpdated: func(updated *Auth) {
|
||||
if updated != nil {
|
||||
activeAuth.Store(updated.Clone())
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
execCtx = refreshExecCtx(withUpstreamAttemptProvider(syncMetadataSessionToContext(execCtx, execOpts.Metadata), provider))
|
||||
executionSeq := m.nextExecutionSeq()
|
||||
startExec := time.Now()
|
||||
var preRefreshExecErr error
|
||||
resp, errExec := executor.Execute(execCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec)
|
||||
durationExec := time.Since(startExec)
|
||||
if errExec != nil {
|
||||
@@ -1403,13 +1423,15 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req
|
||||
if refreshed, okRefresh := m.tryRefreshAfterUnauthorized(refreshCtx, auth, errExec, didRefreshOnUnauthorized, execOpts.Headers); okRefresh {
|
||||
preRefreshExecErr = errExec
|
||||
auth = refreshed
|
||||
activeAuth.Store(auth)
|
||||
publishSelectedAuthMetadata(execOpts.Metadata, auth)
|
||||
didRefreshOnUnauthorized = true
|
||||
execCtx = withUpstreamAttemptProvider(m.newUpstreamAttemptContext(execCtx), provider)
|
||||
execCtx = refreshExecCtx(withUpstreamAttemptProvider(m.newUpstreamAttemptContext(execCtx), provider))
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
executionSeq = m.nextExecutionSeq()
|
||||
startRetry := time.Now()
|
||||
resp, errExec = executor.Execute(execCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec)
|
||||
durationRetry := time.Since(startRetry)
|
||||
if errExec != nil {
|
||||
@@ -1591,6 +1613,9 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string,
|
||||
}
|
||||
preparedAuth, errPrepare := m.prepareRequestAuth(execCtx, executor, auth)
|
||||
if errPrepare != nil {
|
||||
if preparedAuth != nil {
|
||||
auth = preparedAuth
|
||||
}
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
return cliproxyexecutor.Response{}, errCtx
|
||||
@@ -1669,11 +1694,28 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string,
|
||||
return cliproxyexecutor.Response{}, errIntercept
|
||||
}
|
||||
execReq = attachResolvedExecutionModelInfo(routing, execReq, auth, routeModel, upstreamModel, restoreExecutionModel)
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
var activeAuth atomic.Pointer[Auth]
|
||||
activeAuth.Store(auth)
|
||||
syncActiveAuth := func() {
|
||||
if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != auth {
|
||||
auth = currentAuth
|
||||
}
|
||||
}
|
||||
refreshExecCtx := func(base context.Context) context.Context {
|
||||
return m.withExecutionAuthRefresh(base, executionAuthRefreshOptions{
|
||||
onAuthUpdated: func(updated *Auth) {
|
||||
if updated != nil {
|
||||
activeAuth.Store(updated.Clone())
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
execCtx = refreshExecCtx(syncMetadataSessionToContext(execCtx, execOpts.Metadata))
|
||||
executionSeq := m.nextExecutionSeq()
|
||||
startExec := time.Now()
|
||||
var preRefreshExecErr error
|
||||
resp, errExec := executor.CountTokens(execCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec)
|
||||
durationExec := time.Since(startExec)
|
||||
if errExec != nil {
|
||||
@@ -1685,13 +1727,15 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string,
|
||||
if refreshed, okRefresh := m.tryRefreshAfterUnauthorized(refreshCtx, auth, errExec, didRefreshOnUnauthorized, execOpts.Headers); okRefresh {
|
||||
preRefreshExecErr = errExec
|
||||
auth = refreshed
|
||||
activeAuth.Store(auth)
|
||||
publishSelectedAuthMetadata(execOpts.Metadata, auth)
|
||||
didRefreshOnUnauthorized = true
|
||||
execCtx = m.newUpstreamAttemptContext(execCtx)
|
||||
execCtx = refreshExecCtx(m.newUpstreamAttemptContext(execCtx))
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
executionSeq = m.nextExecutionSeq()
|
||||
startRetry := time.Now()
|
||||
resp, errExec = executor.CountTokens(execCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec)
|
||||
durationRetry := time.Since(startRetry)
|
||||
if errExec != nil {
|
||||
@@ -2035,6 +2079,9 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string
|
||||
preparedAuth, errPrepare = m.prepareRequestAuth(execCtx, executor, auth)
|
||||
}
|
||||
if errPrepare != nil {
|
||||
if preparedAuth != nil {
|
||||
auth = preparedAuth
|
||||
}
|
||||
errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare)
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
if selection != nil {
|
||||
@@ -3014,27 +3061,62 @@ func (m *Manager) prepareRequestAuthInternal(ctx context.Context, preparer Reque
|
||||
if !preparer.ShouldPrepareRequestAuth(target) {
|
||||
return target, nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
base := target.Clone()
|
||||
updated, errPrepare := preparer.PrepareRequestAuth(ctx, base.Clone())
|
||||
currentExpectedVersion := expectedVersion
|
||||
var latestCommitted *Auth
|
||||
prepOpts := executionAuthRefreshOptions{
|
||||
holdRefreshLock: true,
|
||||
expectedEpoch: expectedEpoch,
|
||||
onAuthUpdated: func(saved *Auth) {
|
||||
if saved != nil {
|
||||
base = saved.Clone()
|
||||
latestCommitted = saved.Clone()
|
||||
}
|
||||
},
|
||||
}
|
||||
if expectedVersion != 0 {
|
||||
prepOpts.expectedVersion = ¤tExpectedVersion
|
||||
}
|
||||
prepCtx := m.withExecutionAuthRefresh(ctx, prepOpts)
|
||||
updated, errPrepare := preparer.PrepareRequestAuth(prepCtx, base.Clone())
|
||||
if expectedVersion != 0 {
|
||||
currentAfter, okAfter := m.GetByID(id)
|
||||
if !okAfter || currentAfter == nil {
|
||||
return nil, errVerifyCredentialRemoved
|
||||
}
|
||||
if (expectedEpoch != 0 && currentAfter.RegistrationEpoch != expectedEpoch) || currentAfter.CredentialVersion != expectedVersion {
|
||||
if (expectedEpoch != 0 && currentAfter.RegistrationEpoch != expectedEpoch) || currentAfter.CredentialVersion != currentExpectedVersion {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
}
|
||||
if errPrepare != nil {
|
||||
if latestCommitted != nil {
|
||||
return latestCommitted, errPrepare
|
||||
}
|
||||
return auth, errPrepare
|
||||
}
|
||||
if updated == nil {
|
||||
if latestCommitted != nil {
|
||||
if errCtx := ctx.Err(); errCtx != nil {
|
||||
return latestCommitted, errCtx
|
||||
}
|
||||
return latestCommitted, nil
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
if latestCommitted != nil && preparedAuthMatchesBase(base, updated) {
|
||||
if errCtx := ctx.Err(); errCtx != nil {
|
||||
return latestCommitted, errCtx
|
||||
}
|
||||
return latestCommitted, nil
|
||||
}
|
||||
|
||||
commitCtx := context.WithoutCancel(ctx)
|
||||
if expectedVersion != 0 {
|
||||
saved, committed, baseSuperseded, errUpdate := m.updatePreparedAuthStrict(ctx, base, updated)
|
||||
saved, committed, baseSuperseded, errUpdate := m.updatePreparedAuthStrict(commitCtx, base, updated)
|
||||
if errUpdate != nil {
|
||||
if strings.Contains(errUpdate.Error(), "stale registration epoch") {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
@@ -3047,14 +3129,20 @@ func (m *Manager) prepareRequestAuthInternal(ctx context.Context, preparer Reque
|
||||
if !committed || baseSuperseded {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
if errCtx := ctx.Err(); errCtx != nil {
|
||||
return saved, errCtx
|
||||
}
|
||||
return saved, nil
|
||||
}
|
||||
|
||||
saved, errUpdate := m.UpdatePreparedAuth(ctx, base, updated)
|
||||
saved, errUpdate := m.UpdatePreparedAuth(commitCtx, base, updated)
|
||||
if errUpdate != nil {
|
||||
return nil, errUpdate
|
||||
}
|
||||
if saved != nil {
|
||||
if errCtx := ctx.Err(); errCtx != nil {
|
||||
return saved, errCtx
|
||||
}
|
||||
return saved, nil
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(auth.Provider), "meta") {
|
||||
@@ -3482,20 +3570,35 @@ func (m *Manager) InjectCredentials(req *http.Request, authID string) error {
|
||||
}
|
||||
m.mu.RLock()
|
||||
a := m.auths[authID]
|
||||
var authClone *Auth
|
||||
var exec ProviderExecutor
|
||||
if a != nil {
|
||||
authClone = a.Clone()
|
||||
exec, _ = m.executorLocked(executorKeyFromAuth(a))
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
if a == nil || exec == nil {
|
||||
if authClone == nil || exec == nil {
|
||||
return nil
|
||||
}
|
||||
if p, ok := exec.(RequestPreparer); ok && p != nil {
|
||||
return p.PrepareRequest(req, a)
|
||||
return m.prepareHTTPRequestWithExecutionAuthRefresh(req, authClone, p)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) prepareHTTPRequestWithExecutionAuthRefresh(req *http.Request, auth *Auth, preparer RequestPreparer) error {
|
||||
origCtx := req.Context()
|
||||
prepCtx := m.withExecutionAuthRefresh(origCtx, executionAuthRefreshOptions{})
|
||||
prepReq := req.WithContext(prepCtx)
|
||||
errPrep := preparer.PrepareRequest(prepReq, auth)
|
||||
finalCtx := origCtx
|
||||
if updatedCtx := prepReq.Context(); updatedCtx != prepCtx {
|
||||
finalCtx = context.WithValue(updatedCtx, executionAuthRefreshContextKey{}, nil)
|
||||
}
|
||||
*req = *prepReq.WithContext(finalCtx)
|
||||
return errPrep
|
||||
}
|
||||
|
||||
// PrepareHttpRequest injects provider credentials into the supplied HTTP request.
|
||||
func (m *Manager) PrepareHttpRequest(ctx context.Context, auth *Auth, req *http.Request) error {
|
||||
if m == nil {
|
||||
@@ -3522,7 +3625,7 @@ func (m *Manager) PrepareHttpRequest(ctx context.Context, auth *Auth, req *http.
|
||||
if !ok || preparer == nil {
|
||||
return &Error{Code: "not_supported", Message: "executor does not support http request preparation"}
|
||||
}
|
||||
return preparer.PrepareRequest(req, auth)
|
||||
return m.prepareHTTPRequestWithExecutionAuthRefresh(req, auth, preparer)
|
||||
}
|
||||
|
||||
// NewHttpRequest constructs a new HTTP request and injects provider credentials into it.
|
||||
@@ -3570,7 +3673,10 @@ func (m *Manager) HttpRequest(ctx context.Context, auth *Auth, req *http.Request
|
||||
if exec == nil {
|
||||
return nil, &Error{Code: "provider_not_found", Message: "executor not registered for provider: " + providerKey}
|
||||
}
|
||||
return exec.HttpRequest(ctx, auth, req)
|
||||
if ctx == nil {
|
||||
ctx = req.Context()
|
||||
}
|
||||
return exec.HttpRequest(m.withExecutionAuthRefresh(ctx, executionAuthRefreshOptions{}), auth, req)
|
||||
}
|
||||
|
||||
func ensureCanonicalSessionMetadata(metadata map[string]any, headers http.Header, payload []byte) map[string]any {
|
||||
@@ -3996,6 +4102,12 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth,
|
||||
latest, _ := m.GetByID(auth.ID)
|
||||
return latest, verifyCredentialSupersededError()
|
||||
}
|
||||
if preparedAuth != nil && preparedAuth.RegistrationEpoch == regEpoch {
|
||||
auth = preparedAuth
|
||||
accessToken = authAccessTokenForRequest(execCtx, auth, opts.Headers)
|
||||
credVersion = auth.CredentialVersion
|
||||
regEpoch = auth.RegistrationEpoch
|
||||
}
|
||||
if errCancel := verifyCancellationError(execCtx, auth, errPrepare); errCancel != nil {
|
||||
updated, _ := m.GetByID(auth.ID)
|
||||
return updated, errCancel
|
||||
@@ -4026,9 +4138,40 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth,
|
||||
}
|
||||
executor = executorForAuth(baseExecutor, auth)
|
||||
|
||||
var activeVerifyAuth atomic.Pointer[Auth]
|
||||
activeVerifyAuth.Store(auth)
|
||||
syncVerifyAuth := func() {
|
||||
if currentAuth := activeVerifyAuth.Load(); currentAuth != nil && currentAuth != auth {
|
||||
auth = currentAuth
|
||||
accessToken = authAccessTokenForRequest(execCtx, auth, opts.Headers)
|
||||
credVersion = auth.CredentialVersion
|
||||
regEpoch = auth.RegistrationEpoch
|
||||
}
|
||||
}
|
||||
verifyRefreshCtx := func(base context.Context) context.Context {
|
||||
return m.withExecutionAuthRefresh(base, executionAuthRefreshOptions{
|
||||
expectedEpoch: regEpoch,
|
||||
expectedVersion: &credVersion,
|
||||
onAuthUpdated: func(updated *Auth) {
|
||||
if updated != nil {
|
||||
activeVerifyAuth.Store(updated.Clone())
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
for {
|
||||
streamRes, errStream := executor.ExecuteStream(execCtx, auth, req, opts)
|
||||
activeVerifyAuth.Store(auth)
|
||||
streamRes, errStream := executor.ExecuteStream(verifyRefreshCtx(execCtx), auth, req, opts)
|
||||
syncVerifyAuth()
|
||||
if errStream != nil {
|
||||
if errors.Is(errStream, errVerifyCredentialRemoved) {
|
||||
return nil, verifyCredentialRemovedError()
|
||||
}
|
||||
if errors.Is(errStream, errVerifyCredentialSuperseded) {
|
||||
latest, _ := m.GetByID(auth.ID)
|
||||
return latest, verifyCredentialSupersededError()
|
||||
}
|
||||
if errCancel := verifyCancellationError(execCtx, auth, errStream); errCancel != nil {
|
||||
updated, _ := m.GetByID(auth.ID)
|
||||
return updated, errCancel
|
||||
@@ -4037,8 +4180,17 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth,
|
||||
if rerr != nil && rerr.HTTPStatus == http.StatusNotImplemented {
|
||||
opts.Stream = false
|
||||
for {
|
||||
resp, errExec := executor.Execute(execCtx, auth, req, opts)
|
||||
activeVerifyAuth.Store(auth)
|
||||
resp, errExec := executor.Execute(verifyRefreshCtx(execCtx), auth, req, opts)
|
||||
syncVerifyAuth()
|
||||
if errExec != nil {
|
||||
if errors.Is(errExec, errVerifyCredentialRemoved) {
|
||||
return nil, verifyCredentialRemovedError()
|
||||
}
|
||||
if errors.Is(errExec, errVerifyCredentialSuperseded) {
|
||||
latest, _ := m.GetByID(auth.ID)
|
||||
return latest, verifyCredentialSupersededError()
|
||||
}
|
||||
if errCancel := verifyCancellationError(execCtx, auth, errExec); errCancel != nil {
|
||||
updated, _ := m.GetByID(auth.ID)
|
||||
return updated, errCancel
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/MoeForge/moego/json"
|
||||
@@ -1920,6 +1921,9 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy
|
||||
creditsCtx = m.newUpstreamAttemptContext(creditsCtx)
|
||||
preparedAuth, errPrepare := m.prepareRequestAuth(creditsCtx, c.executor, c.auth)
|
||||
if errPrepare != nil {
|
||||
if preparedAuth != nil {
|
||||
c.auth = preparedAuth
|
||||
}
|
||||
if errAbort := m.handleAntigravityCreditsPrepareError(creditsCtx, c, routeModel, creditsOpts, errPrepare); errAbort != nil {
|
||||
return cliproxyexecutor.Response{}, false, errAbort
|
||||
}
|
||||
@@ -1942,9 +1946,20 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy
|
||||
}
|
||||
return cliproxyexecutor.Response{}, false, errIntercept
|
||||
}
|
||||
creditsCtx = syncMetadataSessionToContext(creditsCtx, execOpts.Metadata)
|
||||
var activeAuth atomic.Pointer[Auth]
|
||||
activeAuth.Store(c.auth)
|
||||
creditsCtx = m.withExecutionAuthRefresh(syncMetadataSessionToContext(creditsCtx, execOpts.Metadata), executionAuthRefreshOptions{
|
||||
onAuthUpdated: func(updated *Auth) {
|
||||
if updated != nil {
|
||||
activeAuth.Store(updated.Clone())
|
||||
}
|
||||
},
|
||||
})
|
||||
executionSeq := m.nextExecutionSeq()
|
||||
resp, errExec := c.executor.Execute(creditsCtx, c.auth, execReq, execOpts)
|
||||
if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != c.auth {
|
||||
c.auth = currentAuth
|
||||
}
|
||||
errExec = markUpstreamExecutionAttemptFromContext(creditsCtx, errExec)
|
||||
result := Result{AuthID: c.auth.ID, Provider: c.provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, CompletedResponse: errExec == nil && !resp.Incomplete && isCompletedExecutionPayload(resp.Payload), Options: execOpts, AccessToken: authAccessTokenForRequest(creditsCtx, c.auth, execOpts.Headers), RefreshToken: authRefreshToken(c.auth), CredentialVersion: c.auth.CredentialVersion, RegistrationEpoch: c.auth.RegistrationEpoch, ExecutionSeq: executionSeq}
|
||||
if errExec != nil {
|
||||
@@ -2030,6 +2045,9 @@ func (m *Manager) tryAntigravityCreditsExecuteStream(ctx context.Context, req cl
|
||||
creditsCtx = m.newUpstreamAttemptContext(creditsCtx)
|
||||
preparedAuth, errPrepare := m.prepareRequestAuth(creditsCtx, c.executor, c.auth)
|
||||
if errPrepare != nil {
|
||||
if preparedAuth != nil {
|
||||
c.auth = preparedAuth
|
||||
}
|
||||
if errAbort := m.handleAntigravityCreditsPrepareError(creditsCtx, c, routeModel, creditsOpts, errPrepare); errAbort != nil {
|
||||
return nil, false, errAbort
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/MoeForge/moego/ojson"
|
||||
@@ -392,7 +393,17 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c
|
||||
}
|
||||
return effectiveAuth.Clone(), AccessTokenSHA256(effectiveAuth)
|
||||
}
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
var activeAuth atomic.Pointer[Auth]
|
||||
activeAuth.Store(preparedAuth)
|
||||
execCtx = m.withExecutionAuthRefresh(syncMetadataSessionToContext(execCtx, execOpts.Metadata), executionAuthRefreshOptions{
|
||||
ephemeral: true,
|
||||
onAuthUpdated: func(updated *Auth) {
|
||||
if updated != nil {
|
||||
activeAuth.Store(updated.Clone())
|
||||
setEffectiveAuth(updated)
|
||||
}
|
||||
},
|
||||
})
|
||||
executorCtx := execCtx
|
||||
if countTokens {
|
||||
executorCtx = withAccessTokenFingerprintObserver(execCtx, setEffectiveAuth)
|
||||
@@ -406,6 +417,9 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c
|
||||
}
|
||||
startHomeExec := time.Now()
|
||||
response, errExecute = execute()
|
||||
if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != preparedAuth {
|
||||
preparedAuth = currentAuth
|
||||
}
|
||||
errExecute = markUpstreamExecutionAttemptFromContext(execCtx, errExecute)
|
||||
durationHomeExec := time.Since(startHomeExec)
|
||||
if errCtx := execCtx.Err(); errCtx != nil {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/MoeForge/moego/json"
|
||||
@@ -658,6 +659,14 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
executionSeq := m.nextExecutionSeq()
|
||||
accessToken := authAccessTokenForRequest(execCtx, auth, execOpts.Headers)
|
||||
var activeAuth atomic.Pointer[Auth]
|
||||
activeAuth.Store(auth)
|
||||
syncActiveAuth := func() {
|
||||
if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != auth {
|
||||
auth = currentAuth
|
||||
accessToken = authAccessTokenForRequest(execCtx, auth, execOpts.Headers)
|
||||
}
|
||||
}
|
||||
|
||||
var cancelAttempt context.CancelFunc
|
||||
var attemptCleaned bool
|
||||
@@ -667,6 +676,14 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi
|
||||
}
|
||||
var attemptCtx context.Context
|
||||
attemptCtx, cancelAttempt = context.WithCancel(parent)
|
||||
attemptCtx = m.withExecutionAuthRefresh(attemptCtx, executionAuthRefreshOptions{
|
||||
ephemeral: ephemeralResult,
|
||||
onAuthUpdated: func(updated *Auth) {
|
||||
if updated != nil {
|
||||
activeAuth.Store(updated.Clone())
|
||||
}
|
||||
},
|
||||
})
|
||||
attemptCleaned = false
|
||||
return attemptCtx
|
||||
}
|
||||
@@ -688,9 +705,11 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi
|
||||
}
|
||||
|
||||
var preRefreshStreamErr error
|
||||
activeAuth.Store(auth)
|
||||
attemptCtx := startAttempt(execCtx)
|
||||
startStream := time.Now()
|
||||
streamResult, errStream := executor.ExecuteStream(attemptCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
errStream = markUpstreamExecutionAttemptFromContext(attemptCtx, errStream)
|
||||
durationStream := time.Since(startStream)
|
||||
if errStream != nil {
|
||||
@@ -711,9 +730,11 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
executionSeq = m.nextExecutionSeq()
|
||||
accessToken = authAccessTokenForRequest(execCtx, auth, execOpts.Headers)
|
||||
activeAuth.Store(auth)
|
||||
attemptCtx = startAttempt(execCtx)
|
||||
startRetry := time.Now()
|
||||
streamResult, errStream = executor.ExecuteStream(attemptCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
errStream = markUpstreamExecutionAttemptFromContext(attemptCtx, errStream)
|
||||
durationRetry := time.Since(startRetry)
|
||||
if errStream != nil {
|
||||
@@ -814,9 +835,11 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi
|
||||
execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata)
|
||||
executionSeq = m.nextExecutionSeq()
|
||||
accessToken = authAccessTokenForRequest(execCtx, auth, execOpts.Headers)
|
||||
activeAuth.Store(auth)
|
||||
attemptCtx = startAttempt(execCtx)
|
||||
startRetry := time.Now()
|
||||
retryStream, retryErr := executor.ExecuteStream(attemptCtx, auth, execReq, execOpts)
|
||||
syncActiveAuth()
|
||||
retryErr = markUpstreamExecutionAttemptFromContext(attemptCtx, retryErr)
|
||||
retryStream, retryErr = validateStreamResult(retryStream, retryErr)
|
||||
retryErr = markUpstreamExecutionAttemptFromContext(attemptCtx, retryErr)
|
||||
|
||||
237
sdk/cliproxy/auth/execution_auth_refresh.go
Normal file
237
sdk/cliproxy/auth/execution_auth_refresh.go
Normal file
@@ -0,0 +1,237 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type executionAuthRefreshHandler func(ctx context.Context, auth *Auth, refresh func(context.Context, *Auth) (*Auth, error)) (*Auth, error)
|
||||
|
||||
type executionAuthRefreshContextKey struct{}
|
||||
|
||||
type executionAuthRefreshOptions struct {
|
||||
holdRefreshLock bool
|
||||
ephemeral bool
|
||||
expectedEpoch uint64
|
||||
expectedVersion *uint64
|
||||
onAuthUpdated func(*Auth)
|
||||
}
|
||||
|
||||
// RefreshExecutionAuth runs an executor's in-flight credential refresh through
|
||||
// the Manager refresh coordinator attached to ctx, if present.
|
||||
//
|
||||
// When managed by Manager:
|
||||
// - Refresh calls serialize under the per-credential refresh lock (unless the
|
||||
// caller already holds it during PrepareRequestAuth) and re-read the latest
|
||||
// registered credential snapshot before invoking refresh.
|
||||
// - If refresh returns (nil, nil), no refresh was needed (for example because
|
||||
// another request already refreshed the credential); the coordinator syncs
|
||||
// the caller's active auth state to the latest snapshot and returns it.
|
||||
// - If refresh returns a refreshed auth with err == nil, the coordinator
|
||||
// commits and persists it using context.WithoutCancel so client
|
||||
// cancellation never discards a rotated refresh token while preserving
|
||||
// RegistrationEpoch and CredentialVersion checks, and notifies the active
|
||||
// execution attempt so subsequent MarkResult / metadata records reflect the
|
||||
// refreshed snapshot.
|
||||
//
|
||||
// When no coordinator is attached to ctx (for example in direct unit tests or
|
||||
// unmanaged calls), RefreshExecutionAuth invokes refresh(ctx, auth) directly.
|
||||
func RefreshExecutionAuth(ctx context.Context, auth *Auth, refresh func(context.Context, *Auth) (*Auth, error)) (*Auth, error) {
|
||||
if auth == nil || refresh == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if ctx != nil {
|
||||
if handler, ok := ctx.Value(executionAuthRefreshContextKey{}).(executionAuthRefreshHandler); ok && handler != nil {
|
||||
return handler(ctx, auth, refresh)
|
||||
}
|
||||
}
|
||||
return refresh(ctx, auth)
|
||||
}
|
||||
|
||||
func (m *Manager) withExecutionAuthRefresh(ctx context.Context, opts executionAuthRefreshOptions) context.Context {
|
||||
if m == nil {
|
||||
return ctx
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
handler := func(callCtx context.Context, auth *Auth, refresh func(context.Context, *Auth) (*Auth, error)) (*Auth, error) {
|
||||
if auth == nil || refresh == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if callCtx == nil {
|
||||
callCtx = context.Background()
|
||||
}
|
||||
if errCtx := callCtx.Err(); errCtx != nil {
|
||||
return nil, errCtx
|
||||
}
|
||||
|
||||
id := strings.TrimSpace(auth.ID)
|
||||
if opts.ephemeral || id == "" || (m.HomeEnabled() && auth.RegistrationEpoch == 0) {
|
||||
updated, errRefresh := refresh(callCtx, auth)
|
||||
if errRefresh != nil {
|
||||
return nil, errRefresh
|
||||
}
|
||||
if updated != nil && opts.onAuthUpdated != nil {
|
||||
opts.onAuthUpdated(updated.Clone())
|
||||
}
|
||||
if errCtx := callCtx.Err(); errCtx != nil {
|
||||
return nil, errCtx
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
if !opts.holdRefreshLock {
|
||||
releaseRefresh, errLock := m.lockRefreshContext(callCtx, id)
|
||||
if errLock != nil {
|
||||
return nil, errLock
|
||||
}
|
||||
defer releaseRefresh()
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
current := m.auths[id]
|
||||
var latest *Auth
|
||||
if current != nil {
|
||||
latest = current.Clone()
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
strictVersion := opts.expectedVersion != nil && *opts.expectedVersion != 0
|
||||
if latest == nil {
|
||||
if strictVersion {
|
||||
return nil, errVerifyCredentialRemoved
|
||||
}
|
||||
if !m.HomeEnabled() && auth.RegistrationEpoch != 0 {
|
||||
return nil, fmt.Errorf("refresh %s auth: credential no longer registered", prepareProviderLabel(auth.Provider))
|
||||
}
|
||||
updated, errRefresh := refresh(callCtx, auth)
|
||||
if errRefresh != nil {
|
||||
return nil, errRefresh
|
||||
}
|
||||
if updated != nil && opts.onAuthUpdated != nil {
|
||||
opts.onAuthUpdated(updated.Clone())
|
||||
}
|
||||
if errCtx := callCtx.Err(); errCtx != nil {
|
||||
return nil, errCtx
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
if auth.RegistrationEpoch != 0 && latest.RegistrationEpoch != auth.RegistrationEpoch {
|
||||
if strictVersion {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
return nil, fmt.Errorf("refresh %s auth: stale registration epoch %d != %d", prepareProviderLabel(auth.Provider), auth.RegistrationEpoch, latest.RegistrationEpoch)
|
||||
}
|
||||
if opts.expectedEpoch != 0 && latest.RegistrationEpoch != opts.expectedEpoch {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
if strictVersion && latest.CredentialVersion != *opts.expectedVersion {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
|
||||
base := latest.Clone()
|
||||
updated, errRefresh := refresh(callCtx, base.Clone())
|
||||
if errRefresh != nil {
|
||||
return nil, errRefresh
|
||||
}
|
||||
if updated == nil {
|
||||
if opts.onAuthUpdated != nil {
|
||||
opts.onAuthUpdated(latest.Clone())
|
||||
}
|
||||
if errCtx := callCtx.Err(); errCtx != nil {
|
||||
return nil, errCtx
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if updated.Runtime == nil {
|
||||
updated.Runtime = base.Runtime
|
||||
}
|
||||
updated.LastRefreshedAt = now
|
||||
updated.NextRefreshAfter = time.Time{}
|
||||
updated.UpdatedAt = now
|
||||
applyPreservedRenewalState(base, updated, updateModeRefresh, now)
|
||||
if authHasUnchangedRejectedRefreshToken(updated) {
|
||||
if exp, okExp := updated.AccessTokenExpirationTime(); okExp && !exp.IsZero() && exp.After(now) {
|
||||
updated.NextRefreshAfter = exp
|
||||
}
|
||||
}
|
||||
applyPreservedRejectedTokens(base, updated, true)
|
||||
canServeWithAccessToken := !updated.RequiresSignIn || updated.HasValidAccessToken(now)
|
||||
if canServeWithAccessToken && (updated.RejectedAccessToken == "" || authAccessToken(updated) != updated.RejectedAccessToken) {
|
||||
updated.LastError = nil
|
||||
updated.StatusMessage = ""
|
||||
updated.Unavailable = false
|
||||
updated.RefreshFailures = 0
|
||||
if updated.Status == StatusError || updated.Status == "" {
|
||||
updated.Status = StatusActive
|
||||
}
|
||||
_ = clearUnauthorizedModelStates(updated, now)
|
||||
}
|
||||
if m.shouldRefresh(updated, now) {
|
||||
updated.NextRefreshAfter = now.Add(refreshIneffectiveBackoff)
|
||||
}
|
||||
|
||||
// A successful refresh may have rotated upstream tokens after caller cancellation.
|
||||
// Commit with context values intact while preserving epoch and version checks.
|
||||
saved, committed, baseSuperseded, errUpdate := m.updateRefreshedAuthWithStatus(context.WithoutCancel(callCtx), base, updated)
|
||||
if errUpdate != nil {
|
||||
log.WithFields(log.Fields{"auth_id": base.ID, "credential": base.ID, "provider": base.Provider}).Warnf("persist refreshed auth %s (%s) failed: %v", base.Provider, base.ID, errUpdate)
|
||||
if strictVersion && strings.Contains(errUpdate.Error(), "stale registration epoch") {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
return nil, errUpdate
|
||||
}
|
||||
if saved == nil {
|
||||
if strictVersion {
|
||||
return nil, errVerifyCredentialRemoved
|
||||
}
|
||||
return nil, fmt.Errorf("refresh %s auth: credential removed during refresh", prepareProviderLabel(base.Provider))
|
||||
}
|
||||
if strictVersion {
|
||||
if !committed || baseSuperseded {
|
||||
return nil, errVerifyCredentialSuperseded
|
||||
}
|
||||
*opts.expectedVersion = saved.CredentialVersion
|
||||
}
|
||||
if committed {
|
||||
supportedModels, regEpoch := registry.GetGlobalRegistry().GetModelsAndEpochForClient(id)
|
||||
projections := make([]registry.ClientModelProjection, 0, len(supportedModels))
|
||||
for _, sm := range supportedModels {
|
||||
if sm == nil || strings.TrimSpace(sm.ID) == "" {
|
||||
continue
|
||||
}
|
||||
projections = append(projections, m.clientModelProjectionForAuth(saved, sm.ID, now))
|
||||
}
|
||||
if len(projections) > 0 {
|
||||
registry.GetGlobalRegistry().ApplyClientModelProjections(id, regEpoch, saved.Generation, projections)
|
||||
}
|
||||
}
|
||||
if opts.onAuthUpdated != nil {
|
||||
opts.onAuthUpdated(saved.Clone())
|
||||
}
|
||||
if errCtx := callCtx.Err(); errCtx != nil {
|
||||
return nil, errCtx
|
||||
}
|
||||
return saved.Clone(), nil
|
||||
}
|
||||
return context.WithValue(ctx, executionAuthRefreshContextKey{}, executionAuthRefreshHandler(handler))
|
||||
}
|
||||
|
||||
func preparedAuthMatchesBase(base, updated *Auth) bool {
|
||||
if base == nil || updated == nil {
|
||||
return false
|
||||
}
|
||||
return base.ProxyURL == updated.ProxyURL &&
|
||||
reflect.DeepEqual(base.Metadata, updated.Metadata) &&
|
||||
reflect.DeepEqual(base.Attributes, updated.Attributes)
|
||||
}
|
||||
364
sdk/cliproxy/auth/execution_auth_refresh_test.go
Normal file
364
sdk/cliproxy/auth/execution_auth_refresh_test.go
Normal file
@@ -0,0 +1,364 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/MoeForge/moego/json"
|
||||
internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry"
|
||||
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
||||
)
|
||||
|
||||
type issue7749SameIDHomeDispatcher struct {
|
||||
homeAuth *Auth
|
||||
}
|
||||
|
||||
func (d *issue7749SameIDHomeDispatcher) RPopAuth(_ context.Context, _ string, _ string, _ http.Header, _ int) ([]byte, error) {
|
||||
return json.Marshal(homeAuthDispatchResponse{Auth: *d.homeAuth.Clone()})
|
||||
}
|
||||
|
||||
func (d *issue7749SameIDHomeDispatcher) HeartbeatOK() bool { return true }
|
||||
|
||||
func (d *issue7749SameIDHomeDispatcher) AbortAmbiguousDispatch() {}
|
||||
|
||||
type issue7749HomeRefreshExecutor struct {
|
||||
mu sync.Mutex
|
||||
seenTokens []string
|
||||
refreshCalls atomic.Int32
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) Identifier() string { return "antigravity" }
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) refreshIfExpiring(ctx context.Context, auth *Auth) (*Auth, error) {
|
||||
updated, err := RefreshExecutionAuth(ctx, auth, func(_ context.Context, latest *Auth) (*Auth, error) {
|
||||
if latest != nil && testStringValue(latest.Metadata["access_token"]) == "local-valid-token" {
|
||||
// Local token looks fresh; returning (nil, nil) would adopt the local credential if Home leaked into m.auths.
|
||||
return nil, nil
|
||||
}
|
||||
e.refreshCalls.Add(1)
|
||||
out := latest.Clone()
|
||||
if out.Metadata == nil {
|
||||
out.Metadata = map[string]any{}
|
||||
}
|
||||
out.Metadata["access_token"] = "home-refreshed-token"
|
||||
return out, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if updated != nil {
|
||||
return updated, nil
|
||||
}
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) recordToken(auth *Auth) {
|
||||
e.mu.Lock()
|
||||
e.seenTokens = append(e.seenTokens, testStringValue(auth.Metadata["access_token"]))
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) Execute(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
effective, err := e.refreshIfExpiring(ctx, auth)
|
||||
if err != nil {
|
||||
return cliproxyexecutor.Response{}, err
|
||||
}
|
||||
e.recordToken(effective)
|
||||
return cliproxyexecutor.Response{Payload: []byte("ok")}, nil
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) ExecuteStream(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) {
|
||||
effective, err := e.refreshIfExpiring(ctx, auth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.recordToken(effective)
|
||||
ch := make(chan cliproxyexecutor.StreamChunk, 1)
|
||||
ch <- cliproxyexecutor.StreamChunk{Payload: []byte("ok")}
|
||||
close(ch)
|
||||
return &cliproxyexecutor.StreamResult{Chunks: ch}, nil
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) CountTokens(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
effective, err := e.refreshIfExpiring(ctx, auth)
|
||||
if err != nil {
|
||||
return cliproxyexecutor.Response{}, err
|
||||
}
|
||||
e.recordToken(effective)
|
||||
return cliproxyexecutor.Response{Payload: []byte("1")}, nil
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) {
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
func (e *issue7749HomeRefreshExecutor) HttpRequest(_ context.Context, _ *Auth, _ *http.Request) (*http.Response, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestIssue7749HomeExecutionRefreshDoesNotUseSameIDLocalAuth(t *testing.T) {
|
||||
paths := []struct {
|
||||
name string
|
||||
run func(*Manager, context.Context) error
|
||||
}{
|
||||
{
|
||||
name: "Execute",
|
||||
run: func(m *Manager, ctx context.Context) error {
|
||||
_, err := m.Execute(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: "test-model"}, cliproxyexecutor.Options{})
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "CountTokens",
|
||||
run: func(m *Manager, ctx context.Context) error {
|
||||
_, err := m.ExecuteCount(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: "test-model"}, cliproxyexecutor.Options{})
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ExecuteStream",
|
||||
run: func(m *Manager, ctx context.Context) error {
|
||||
res, err := m.ExecuteStream(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: "test-model"}, cliproxyexecutor.Options{Stream: true})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res != nil && res.Chunks != nil {
|
||||
for range res.Chunks {
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range paths {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
exec := &issue7749HomeRefreshExecutor{}
|
||||
homeAuth := &Auth{
|
||||
ID: "same-id-7749",
|
||||
Provider: "antigravity",
|
||||
Status: StatusActive,
|
||||
Metadata: map[string]any{"access_token": "home-expiring-token", "source": "home"},
|
||||
}
|
||||
manager := NewManager(&requestPrepareStore{}, nil, nil)
|
||||
manager.SetConfig(&internalconfig.Config{Home: internalconfig.HomeConfig{Enabled: true}})
|
||||
manager.PublishHomeDispatch(&issue7749SameIDHomeDispatcher{homeAuth: homeAuth}, executionregistry.New(), 1)
|
||||
manager.RegisterExecutor(exec)
|
||||
|
||||
localAuth := &Auth{
|
||||
ID: "same-id-7749",
|
||||
Provider: "antigravity",
|
||||
Status: StatusActive,
|
||||
Metadata: map[string]any{"access_token": "local-valid-token", "source": "local"},
|
||||
}
|
||||
if _, errReg := manager.Register(WithSkipPersist(context.Background()), localAuth); errReg != nil {
|
||||
t.Fatalf("Register local auth: %v", errReg)
|
||||
}
|
||||
|
||||
if errRun := tc.run(manager, context.Background()); errRun != nil {
|
||||
t.Fatalf("%s error = %v", tc.name, errRun)
|
||||
}
|
||||
|
||||
exec.mu.Lock()
|
||||
tokens := append([]string(nil), exec.seenTokens...)
|
||||
exec.mu.Unlock()
|
||||
if len(tokens) != 1 || tokens[0] != "home-refreshed-token" {
|
||||
t.Fatalf("%s used tokens %v, want [home-refreshed-token]", tc.name, tokens)
|
||||
}
|
||||
if exec.refreshCalls.Load() != 1 {
|
||||
t.Fatalf("%s Home refresh calls = %d, want 1", tc.name, exec.refreshCalls.Load())
|
||||
}
|
||||
|
||||
current, ok := manager.GetByID("same-id-7749")
|
||||
if !ok || current == nil {
|
||||
t.Fatal("local auth disappeared")
|
||||
}
|
||||
if got := testStringValue(current.Metadata["access_token"]); got != "local-valid-token" {
|
||||
t.Fatalf("local auth access_token = %q, want unchanged local-valid-token", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type issue7749PrepAndHTTPExecutor struct {
|
||||
id string
|
||||
hostToSet string
|
||||
seenHTTPCtx context.Context
|
||||
seenReqCtx context.Context
|
||||
prepareFn func(req *http.Request, auth *Auth) error
|
||||
}
|
||||
|
||||
func (e *issue7749PrepAndHTTPExecutor) Identifier() string { return e.id }
|
||||
func (e *issue7749PrepAndHTTPExecutor) Execute(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
return cliproxyexecutor.Response{}, nil
|
||||
}
|
||||
func (e *issue7749PrepAndHTTPExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (e *issue7749PrepAndHTTPExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
return cliproxyexecutor.Response{}, nil
|
||||
}
|
||||
func (e *issue7749PrepAndHTTPExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) {
|
||||
return auth, nil
|
||||
}
|
||||
func (e *issue7749PrepAndHTTPExecutor) PrepareRequest(req *http.Request, auth *Auth) error {
|
||||
if e.prepareFn != nil {
|
||||
return e.prepareFn(req, auth)
|
||||
}
|
||||
if e.hostToSet != "" {
|
||||
req.Host = e.hostToSet
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer prepared-tok")
|
||||
return nil
|
||||
}
|
||||
func (e *issue7749PrepAndHTTPExecutor) HttpRequest(ctx context.Context, _ *Auth, req *http.Request) (*http.Response, error) {
|
||||
e.seenHTTPCtx = ctx
|
||||
e.seenReqCtx = req.Context()
|
||||
if ctx != nil && ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return &http.Response{StatusCode: http.StatusOK}, nil
|
||||
}
|
||||
|
||||
func TestIssue7749InjectCredentialsConcurrentWithMarkResultNoRace(t *testing.T) {
|
||||
exec := &issue7749PrepAndHTTPExecutor{id: "issue7749-race"}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(exec)
|
||||
|
||||
auth := &Auth{
|
||||
ID: "cred-race-7749",
|
||||
Provider: "issue7749-race",
|
||||
Status: StatusActive,
|
||||
Metadata: map[string]any{"access_token": "tok-1"},
|
||||
}
|
||||
if _, errReg := manager.Register(context.Background(), auth); errReg != nil {
|
||||
t.Fatalf("Register auth: %v", errReg)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 100; i++ {
|
||||
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://example.test/api", nil)
|
||||
_ = manager.InjectCredentials(req, "cred-race-7749")
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 100; i++ {
|
||||
manager.MarkResult(context.Background(), Result{
|
||||
AuthID: "cred-race-7749",
|
||||
Provider: "issue7749-race",
|
||||
Model: "model-" + string(rune('a'+(i%10))),
|
||||
Success: i%2 == 0,
|
||||
})
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestIssue7749ManagerHttpRequestNilContextPreservesRequestContext(t *testing.T) {
|
||||
type reqCtxKey struct{}
|
||||
|
||||
exec := &issue7749PrepAndHTTPExecutor{id: "issue7749-httpctx"}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(exec)
|
||||
|
||||
auth := &Auth{
|
||||
ID: "cred-httpctx-7749",
|
||||
Provider: "issue7749-httpctx",
|
||||
Status: StatusActive,
|
||||
}
|
||||
|
||||
reqCtx, cancel := context.WithCancel(context.WithValue(context.Background(), reqCtxKey{}, "req-marker-7749"))
|
||||
cancel()
|
||||
req, _ := http.NewRequestWithContext(reqCtx, http.MethodGet, "https://example.test/api", nil)
|
||||
|
||||
_, errHTTP := manager.HttpRequest(nil, auth, req)
|
||||
if !errors.Is(errHTTP, context.Canceled) {
|
||||
t.Fatalf("Manager.HttpRequest(nil, auth, canceledReq) error = %v, want context.Canceled", errHTTP)
|
||||
}
|
||||
if exec.seenHTTPCtx == nil || exec.seenHTTPCtx.Value(reqCtxKey{}) != "req-marker-7749" {
|
||||
t.Fatalf("executor HttpRequest ctx value = %v, want req-marker-7749 from req.Context()", exec.seenHTTPCtx)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssue7749PrepareRequestPreservesHostMutation(t *testing.T) {
|
||||
type origKey struct{}
|
||||
type preparerKey struct{}
|
||||
|
||||
exec := &issue7749PrepAndHTTPExecutor{
|
||||
id: "issue7749-host",
|
||||
hostToSet: "custom-host.example.test",
|
||||
prepareFn: func(req *http.Request, _ *Auth) error {
|
||||
req.Host = "custom-host.example.test"
|
||||
req.Header.Set("Authorization", "Bearer prepared-tok")
|
||||
*req = *req.WithContext(context.WithValue(req.Context(), preparerKey{}, "from-preparer"))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
manager := NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(exec)
|
||||
|
||||
auth := &Auth{
|
||||
ID: "cred-host-7749",
|
||||
Provider: "issue7749-host",
|
||||
Status: StatusActive,
|
||||
}
|
||||
registered, errReg := manager.Register(context.Background(), auth)
|
||||
if errReg != nil {
|
||||
t.Fatalf("Register auth: %v", errReg)
|
||||
}
|
||||
|
||||
t.Run("InjectCredentials", func(t *testing.T) {
|
||||
origCtx := context.WithValue(context.Background(), origKey{}, "keep-7749")
|
||||
req, _ := http.NewRequestWithContext(origCtx, http.MethodGet, "https://original.example.test/v1", nil)
|
||||
if errInj := manager.InjectCredentials(req, registered.ID); errInj != nil {
|
||||
t.Fatalf("InjectCredentials error = %v", errInj)
|
||||
}
|
||||
if req.Host != "custom-host.example.test" {
|
||||
t.Fatalf("req.Host = %q, want custom-host.example.test", req.Host)
|
||||
}
|
||||
if got := req.Header.Get("Authorization"); got != "Bearer prepared-tok" {
|
||||
t.Fatalf("Authorization = %q, want Bearer prepared-tok", got)
|
||||
}
|
||||
if req.Context().Value(origKey{}) != "keep-7749" {
|
||||
t.Fatal("InjectCredentials lost original req.Context value")
|
||||
}
|
||||
if got := req.Context().Value(preparerKey{}); got != "from-preparer" {
|
||||
t.Fatalf("InjectCredentials dropped preparer context value: got %v, want from-preparer", got)
|
||||
}
|
||||
if fn, ok := req.Context().Value(executionAuthRefreshContextKey{}).(executionAuthRefreshHandler); ok && fn != nil {
|
||||
t.Fatal("InjectCredentials leaked executionAuthRefreshContextKey onto request context")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PrepareHttpRequest", func(t *testing.T) {
|
||||
origCtx := context.WithValue(context.Background(), origKey{}, "keep-prep-7749")
|
||||
req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://original.example.test/v1", nil)
|
||||
if errPrep := manager.PrepareHttpRequest(origCtx, registered.Clone(), req); errPrep != nil {
|
||||
t.Fatalf("PrepareHttpRequest error = %v", errPrep)
|
||||
}
|
||||
if req.Host != "custom-host.example.test" {
|
||||
t.Fatalf("req.Host = %q, want custom-host.example.test", req.Host)
|
||||
}
|
||||
if got := req.Header.Get("Authorization"); got != "Bearer prepared-tok" {
|
||||
t.Fatalf("Authorization = %q, want Bearer prepared-tok", got)
|
||||
}
|
||||
if req.Context().Value(origKey{}) != "keep-prep-7749" {
|
||||
t.Fatal("PrepareHttpRequest lost caller ctx value")
|
||||
}
|
||||
if got := req.Context().Value(preparerKey{}); got != "from-preparer" {
|
||||
t.Fatalf("PrepareHttpRequest dropped preparer context value: got %v, want from-preparer", got)
|
||||
}
|
||||
if fn, ok := req.Context().Value(executionAuthRefreshContextKey{}).(executionAuthRefreshHandler); ok && fn != nil {
|
||||
t.Fatal("PrepareHttpRequest leaked executionAuthRefreshContextKey onto request context")
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user