mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-11-29 05:12:44 +08:00
fix(auth): reconcile disabled-era and orphaned unavailable flags
- Clear disabled-era Unavailable state when re-enabling credentials via management handlers, lifecycle transitions, post-save delta merges, and concurrent refresh merges while preserving unresolved sign-in or token-rejection errors. - Reconcile unexplained StatusActive Unavailable flags with no cooldown deadline or auth error consistently across routing selection, scheduling, model projection, and management cooldown views. - Add regression tests covering disabled re-enable flows, concurrent persist/refresh races, SIWC diagnostic 401 preservation, and orphaned unavailable reconciliation. Closes: #8523
This commit is contained in:
@@ -643,6 +643,13 @@ func reconcileAuthFileCooldownState(auth *coreauth.Auth, now time.Time) (unavail
|
||||
return false, status, statusMessage, time.Time{}
|
||||
}
|
||||
|
||||
// Match selector.isAuthBlockedForModelForRequest: an enabled active credential
|
||||
// with no cooldown deadline, no error status/message, and no unresolved auth
|
||||
// or token failure must not be reported as permanently unavailable.
|
||||
if !hasActiveCredCooldown && !hasActiveModelCooldown && coreauth.IsOrphanedAuthUnavailable(auth, now) {
|
||||
return false, coreauth.StatusActive, "", time.Time{}
|
||||
}
|
||||
|
||||
// If nextRetry is in the past, do not expose a past retry deadline.
|
||||
if !nextRetry.IsZero() && !nextRetry.After(now) {
|
||||
nextRetry = time.Time{}
|
||||
|
||||
@@ -244,13 +244,18 @@ func applyAuthDisabledState(auth *coreauth.Auth, disabled bool) {
|
||||
if auth == nil {
|
||||
return
|
||||
}
|
||||
wasDisabled := auth.Disabled || auth.Status == coreauth.StatusDisabled
|
||||
auth.Disabled = disabled
|
||||
if disabled {
|
||||
auth.Status = coreauth.StatusDisabled
|
||||
auth.StatusMessage = "disabled via management API"
|
||||
} else {
|
||||
} else if wasDisabled {
|
||||
auth.Status = coreauth.StatusActive
|
||||
auth.StatusMessage = ""
|
||||
auth.Unavailable = false
|
||||
auth.LastError = nil
|
||||
} else if auth.Status == "" {
|
||||
auth.Status = coreauth.StatusActive
|
||||
}
|
||||
auth.UpdatedAt = time.Now()
|
||||
if auth.Metadata == nil {
|
||||
@@ -847,6 +852,7 @@ func syncAuthFileDisabledState(auth *coreauth.Auth) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
wasDisabled := auth.Disabled || auth.Status == coreauth.StatusDisabled
|
||||
auth.Disabled = disabled
|
||||
if disabled {
|
||||
auth.Status = coreauth.StatusDisabled
|
||||
@@ -855,8 +861,14 @@ func syncAuthFileDisabledState(auth *coreauth.Auth) {
|
||||
}
|
||||
return
|
||||
}
|
||||
auth.Status = coreauth.StatusActive
|
||||
auth.StatusMessage = ""
|
||||
if wasDisabled {
|
||||
auth.Status = coreauth.StatusActive
|
||||
auth.StatusMessage = ""
|
||||
auth.Unavailable = false
|
||||
auth.LastError = nil
|
||||
} else if auth.Status == "" {
|
||||
auth.Status = coreauth.StatusActive
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) removeAuth(ctx context.Context, id string) {
|
||||
|
||||
314
internal/api/handlers/management/auth_files_issue8523_test.go
Normal file
314
internal/api/handlers/management/auth_files_issue8523_test.go
Normal file
@@ -0,0 +1,314 @@
|
||||
package management
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
||||
)
|
||||
|
||||
func TestPatchAuthFileStatusReenableClearsUnavailableAndRestoresSelectability_Issue8523(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
|
||||
authDir := t.TempDir()
|
||||
fileName := "codex-issue8523-status.json"
|
||||
filePath := filepath.Join(authDir, fileName)
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
if errWrite := os.WriteFile(filePath, []byte("{\"type\":\"codex\",\"access_token\":\"tok\",\"expired\":\""+validExp+"\",\"disabled\":false}"), 0o600); errWrite != nil {
|
||||
t.Fatalf("write auth file: %v", errWrite)
|
||||
}
|
||||
|
||||
reg := registry.GetGlobalRegistry()
|
||||
model := "issue8523-mgmt-gpt-6-luna"
|
||||
t.Cleanup(func() { reg.UnregisterClient(fileName) })
|
||||
|
||||
manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil)
|
||||
auth := &coreauth.Auth{
|
||||
ID: fileName,
|
||||
FileName: fileName,
|
||||
Provider: "codex",
|
||||
Status: coreauth.StatusActive,
|
||||
Attributes: map[string]string{
|
||||
"path": filePath,
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "tok",
|
||||
"expired": validExp,
|
||||
"disabled": false,
|
||||
},
|
||||
}
|
||||
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
|
||||
t.Fatalf("register auth: %v", errRegister)
|
||||
}
|
||||
reg.RegisterClient(fileName, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
|
||||
// Serve a successful request so ModelStates is non-empty before disable.
|
||||
manager.MarkResult(context.Background(), coreauth.Result{
|
||||
AuthID: fileName,
|
||||
Provider: "codex",
|
||||
Model: model,
|
||||
Success: true,
|
||||
})
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
||||
h.SetPostAuthPersistHook(func(ctx context.Context, a *coreauth.Auth) error {
|
||||
if a == nil || a.ID == "" {
|
||||
return nil
|
||||
}
|
||||
if a.Disabled {
|
||||
reg.UnregisterClient(a.ID)
|
||||
} else {
|
||||
reg.RegisterClient(a.ID, a.Provider, []*registry.ModelInfo{{ID: model}})
|
||||
}
|
||||
manager.ReconcileRegistryModelStates(ctx, a.ID)
|
||||
return nil
|
||||
})
|
||||
|
||||
// Disable via PatchAuthFileStatus.
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/v8/management/credentials/status", strings.NewReader("{\"name\":\""+fileName+"\",\"disabled\":true}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
h.PatchAuthFileStatus(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("disable status = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Re-enable via PatchAuthFileStatus.
|
||||
rec = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(rec)
|
||||
req = httptest.NewRequest(http.MethodPatch, "/v8/management/credentials/status", strings.NewReader("{\"name\":\""+fileName+"\",\"disabled\":false}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
h.PatchAuthFileStatus(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("re-enable status = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
got, ok := manager.GetByID(fileName)
|
||||
if !ok || got == nil {
|
||||
t.Fatal("auth missing after re-enable")
|
||||
}
|
||||
if got.Unavailable {
|
||||
t.Fatalf("re-enabled auth stuck with Unavailable=true (status=%q)", got.Status)
|
||||
}
|
||||
if !coreauth.IsAuthAvailableForModel(got, model, time.Now()) {
|
||||
t.Fatal("IsAuthAvailableForModel = false after re-enable, want true")
|
||||
}
|
||||
|
||||
unavailable, status, _, _ := reconcileAuthFileCooldownState(got, time.Now().UTC())
|
||||
if unavailable || status != coreauth.StatusActive {
|
||||
t.Fatalf("reconcileAuthFileCooldownState = (unavailable=%v, status=%q), want (false, active)", unavailable, status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAuthFileFieldsReenableClearsUnavailable_Issue8523(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
|
||||
authDir := t.TempDir()
|
||||
fileName := "codex-issue8523-fields.json"
|
||||
filePath := filepath.Join(authDir, fileName)
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
if errWrite := os.WriteFile(filePath, []byte("{\"type\":\"codex\",\"access_token\":\"tok\",\"expired\":\""+validExp+"\",\"disabled\":false}"), 0o600); errWrite != nil {
|
||||
t.Fatalf("write auth file: %v", errWrite)
|
||||
}
|
||||
|
||||
reg := registry.GetGlobalRegistry()
|
||||
model := "issue8523-fields-gpt-6-luna"
|
||||
t.Cleanup(func() { reg.UnregisterClient(fileName) })
|
||||
|
||||
manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil)
|
||||
if _, errRegister := manager.Register(context.Background(), &coreauth.Auth{
|
||||
ID: fileName,
|
||||
FileName: fileName,
|
||||
Provider: "codex",
|
||||
Status: coreauth.StatusActive,
|
||||
Attributes: map[string]string{
|
||||
"path": filePath,
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "tok",
|
||||
"expired": validExp,
|
||||
"disabled": false,
|
||||
},
|
||||
}); errRegister != nil {
|
||||
t.Fatalf("register auth: %v", errRegister)
|
||||
}
|
||||
reg.RegisterClient(fileName, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
manager.MarkResult(context.Background(), coreauth.Result{
|
||||
AuthID: fileName,
|
||||
Provider: "codex",
|
||||
Model: model,
|
||||
Success: true,
|
||||
})
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
||||
h.SetPostAuthPersistHook(func(ctx context.Context, a *coreauth.Auth) error {
|
||||
if a == nil || a.ID == "" {
|
||||
return nil
|
||||
}
|
||||
if a.Disabled {
|
||||
reg.UnregisterClient(a.ID)
|
||||
} else {
|
||||
reg.RegisterClient(a.ID, a.Provider, []*registry.ModelInfo{{ID: model}})
|
||||
}
|
||||
manager.ReconcileRegistryModelStates(ctx, a.ID)
|
||||
return nil
|
||||
})
|
||||
|
||||
// Disable via PatchAuthFileFields.
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/v8/management/credentials/fields", strings.NewReader("{\"name\":\""+fileName+"\",\"disabled\":true}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
h.PatchAuthFileFields(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("fields disable status = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Re-enable via PatchAuthFileFields.
|
||||
rec = httptest.NewRecorder()
|
||||
c, _ = gin.CreateTestContext(rec)
|
||||
req = httptest.NewRequest(http.MethodPatch, "/v8/management/credentials/fields", strings.NewReader("{\"name\":\""+fileName+"\",\"disabled\":false}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
h.PatchAuthFileFields(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("fields re-enable status = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(fileName)
|
||||
if got.Unavailable {
|
||||
t.Fatalf("re-enabled auth via PatchAuthFileFields stuck with Unavailable=true")
|
||||
}
|
||||
if !coreauth.IsAuthAvailableForModel(got, model, time.Now()) {
|
||||
t.Fatal("IsAuthAvailableForModel = false after PatchAuthFileFields re-enable, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchAuthFileStatusEnableNoOpDoesNotClearActiveCooldown_Issue8523(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
|
||||
authDir := t.TempDir()
|
||||
fileName := "codex-issue8523-cooling.json"
|
||||
filePath := filepath.Join(authDir, fileName)
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
if errWrite := os.WriteFile(filePath, []byte("{\"type\":\"codex\",\"access_token\":\"tok\",\"expired\":\""+validExp+"\",\"disabled\":false}"), 0o600); errWrite != nil {
|
||||
t.Fatalf("write auth file: %v", errWrite)
|
||||
}
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
retryAt := time.Now().Add(15 * time.Minute)
|
||||
if _, errRegister := manager.Register(context.Background(), &coreauth.Auth{
|
||||
ID: fileName,
|
||||
FileName: fileName,
|
||||
Provider: "codex",
|
||||
Status: coreauth.StatusError,
|
||||
StatusMessage: "quota exhausted",
|
||||
Unavailable: true,
|
||||
NextRetryAfter: retryAt,
|
||||
Quota: coreauth.QuotaState{
|
||||
Exceeded: true,
|
||||
Reason: "credential_quota",
|
||||
NextRecoverAt: retryAt,
|
||||
},
|
||||
Attributes: map[string]string{
|
||||
"path": filePath,
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "tok",
|
||||
"expired": validExp,
|
||||
"disabled": false,
|
||||
},
|
||||
}); errRegister != nil {
|
||||
t.Fatalf("register auth: %v", errRegister)
|
||||
}
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/v8/management/credentials/status", strings.NewReader("{\"name\":\""+fileName+"\",\"disabled\":false}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
c.Request = req
|
||||
h.PatchAuthFileStatus(c)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(fileName)
|
||||
if !got.Unavailable || !got.NextRetryAfter.After(time.Now()) || got.Status != coreauth.StatusError {
|
||||
t.Fatalf("no-op disabled=false cleared active cooldown: unavailable=%v status=%q nextRetry=%v",
|
||||
got.Unavailable, got.Status, got.NextRetryAfter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrphanedUnavailableManagementViewConsistentWithoutResetOrEdit_Issue8523(t *testing.T) {
|
||||
t.Setenv("MANAGEMENT_PASSWORD", "")
|
||||
|
||||
authDir := t.TempDir()
|
||||
fileName := "codex-issue8523-orphaned-view.json"
|
||||
filePath := filepath.Join(authDir, fileName)
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
if errWrite := os.WriteFile(filePath, []byte("{\"type\":\"codex\",\"access_token\":\"tok\",\"expired\":\""+validExp+"\",\"disabled\":false}"), 0o600); errWrite != nil {
|
||||
t.Fatalf("write auth file: %v", errWrite)
|
||||
}
|
||||
|
||||
manager := coreauth.NewManager(nil, &coreauth.RoundRobinSelector{}, nil)
|
||||
cfg := &config.Config{AuthDir: authDir}
|
||||
manager.SetConfig(cfg)
|
||||
|
||||
// Register directly in the contradictory stuck state without any edit, toggle, or reset.
|
||||
if _, errRegister := manager.Register(context.Background(), &coreauth.Auth{
|
||||
ID: fileName,
|
||||
FileName: fileName,
|
||||
Provider: "codex",
|
||||
Status: coreauth.StatusActive,
|
||||
Unavailable: true,
|
||||
Attributes: map[string]string{
|
||||
"path": filePath,
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "tok",
|
||||
"expired": validExp,
|
||||
"disabled": false,
|
||||
},
|
||||
}); errRegister != nil {
|
||||
t.Fatalf("register auth: %v", errRegister)
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(fileName)
|
||||
if !coreauth.IsAuthAvailableForModel(got, "gpt-6-luna", time.Now()) {
|
||||
t.Fatal("IsAuthAvailableForModel = false for orphaned active auth, want true")
|
||||
}
|
||||
|
||||
unavailable, status, statusMsg, nextRetry := reconcileAuthFileCooldownState(got, time.Now().UTC())
|
||||
if unavailable || status != coreauth.StatusActive || statusMsg != "" || !nextRetry.IsZero() {
|
||||
t.Fatalf("reconcileAuthFileCooldownState = (unavailable=%v, status=%q, msg=%q, next=%v), want (false, active, empty, zero)",
|
||||
unavailable, status, statusMsg, nextRetry)
|
||||
}
|
||||
|
||||
h := NewHandlerWithoutConfigFilePath(cfg, manager)
|
||||
payload := requestAuthFilesCooldowns(t, h, "?name="+fileName)
|
||||
if len(payload.Files) != 1 {
|
||||
t.Fatalf("expected 1 file, got %d", len(payload.Files))
|
||||
}
|
||||
if payload.Files[0].Unavailable || payload.Files[0].Status != string(coreauth.StatusActive) {
|
||||
t.Fatalf("management list reported contradictory state: unavailable=%v status=%q",
|
||||
payload.Files[0].Unavailable, payload.Files[0].Status)
|
||||
}
|
||||
}
|
||||
700
sdk/cliproxy/auth/conductor_issue8523_test.go
Normal file
700
sdk/cliproxy/auth/conductor_issue8523_test.go
Normal file
@@ -0,0 +1,700 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
|
||||
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
||||
)
|
||||
|
||||
func TestReenableDisabledAuthClearsUnavailableAndRestoresRouting_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
reg := registry.GetGlobalRegistry()
|
||||
model := "issue8523-gpt-6-luna"
|
||||
highID := "issue8523-codex-high.json"
|
||||
lowID := "issue8523-codex-low.json"
|
||||
|
||||
t.Cleanup(func() {
|
||||
reg.UnregisterClient(highID)
|
||||
reg.UnregisterClient(lowID)
|
||||
})
|
||||
|
||||
manager := NewManager(nil, &RoundRobinSelector{}, nil)
|
||||
manager.RegisterExecutor(&issue7756DummyExecutor{id: "codex"})
|
||||
now := time.Now().UTC()
|
||||
validExp := now.Add(time.Hour).Format(time.RFC3339)
|
||||
|
||||
highAuth := &Auth{
|
||||
ID: highID,
|
||||
FileName: highID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Attributes: map[string]string{
|
||||
"priority": "8",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-high-token",
|
||||
"expired": validExp,
|
||||
},
|
||||
}
|
||||
lowAuth := &Auth{
|
||||
ID: lowID,
|
||||
FileName: lowID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Attributes: map[string]string{
|
||||
"priority": "0",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-low-token",
|
||||
"expired": validExp,
|
||||
},
|
||||
}
|
||||
|
||||
if _, errReg := manager.Register(ctx, highAuth); errReg != nil {
|
||||
t.Fatalf("Register(high) error = %v", errReg)
|
||||
}
|
||||
if _, errReg := manager.Register(ctx, lowAuth); errReg != nil {
|
||||
t.Fatalf("Register(low) error = %v", errReg)
|
||||
}
|
||||
reg.RegisterClient(highID, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
reg.RegisterClient(lowID, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
manager.RefreshSchedulerEntry(highID)
|
||||
manager.RefreshSchedulerEntry(lowID)
|
||||
|
||||
// Record a successful execution so ModelStates is populated while Failed stays 0.
|
||||
manager.MarkResult(ctx, Result{
|
||||
AuthID: highID,
|
||||
Provider: "codex",
|
||||
Model: model,
|
||||
Success: true,
|
||||
})
|
||||
|
||||
// Disable high-priority credential and unregister its models, then reconcile.
|
||||
if _, committed, errMod := manager.Modify(ctx, highID, 0, func(current *Auth) error {
|
||||
current.Disabled = true
|
||||
current.Status = StatusDisabled
|
||||
current.StatusMessage = "disabled via management API"
|
||||
return nil
|
||||
}); errMod != nil || !committed {
|
||||
t.Fatalf("Modify(disable) committed=%v err=%v", committed, errMod)
|
||||
}
|
||||
reg.UnregisterClient(highID)
|
||||
manager.ReconcileRegistryModelStates(ctx, highID)
|
||||
|
||||
disabledSnap, okDisabled := manager.GetByID(highID)
|
||||
if !okDisabled || disabledSnap == nil {
|
||||
t.Fatal("high auth missing after disable")
|
||||
}
|
||||
if !disabledSnap.Disabled || !disabledSnap.Unavailable || len(disabledSnap.ModelStates) != 0 {
|
||||
t.Fatalf("unexpected disabled precondition: disabled=%v unavailable=%v modelStates=%d",
|
||||
disabledSnap.Disabled, disabledSnap.Unavailable, len(disabledSnap.ModelStates))
|
||||
}
|
||||
|
||||
// Re-enable via Modify without manually touching Unavailable (mirrors Management API).
|
||||
if _, committed, errMod := manager.Modify(ctx, highID, 0, func(current *Auth) error {
|
||||
current.Disabled = false
|
||||
current.Status = StatusActive
|
||||
current.StatusMessage = ""
|
||||
return nil
|
||||
}); errMod != nil || !committed {
|
||||
t.Fatalf("Modify(re-enable) committed=%v err=%v", committed, errMod)
|
||||
}
|
||||
reg.RegisterClient(highID, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
manager.ReconcileRegistryModelStates(ctx, highID)
|
||||
manager.RefreshSchedulerEntry(highID)
|
||||
|
||||
got, ok := manager.GetByID(highID)
|
||||
if !ok || got == nil {
|
||||
t.Fatal("high auth missing after re-enable")
|
||||
}
|
||||
if got.Unavailable {
|
||||
t.Fatalf("re-enabled auth stuck with Unavailable=true (status=%q nextRetry=%v quota=%+v)",
|
||||
got.Status, got.NextRetryAfter, got.Quota)
|
||||
}
|
||||
if got.Status != StatusActive {
|
||||
t.Fatalf("re-enabled auth Status = %q, want %q", got.Status, StatusActive)
|
||||
}
|
||||
if !IsAuthAvailableForModel(got, model, time.Now()) {
|
||||
t.Fatalf("IsAuthAvailableForModel = false after re-enable, want true")
|
||||
}
|
||||
|
||||
picked, _, errPick := manager.pickNext(ctx, "codex", model, cliproxyexecutor.Options{}, nil)
|
||||
if errPick != nil {
|
||||
t.Fatalf("pickNext error = %v", errPick)
|
||||
}
|
||||
if picked == nil || picked.ID != highID {
|
||||
pickedID := ""
|
||||
if picked != nil {
|
||||
pickedID = picked.ID
|
||||
}
|
||||
t.Fatalf("pickNext selected %q, want re-enabled high-priority auth %q", pickedID, highID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReenableDisabledAuthWithLateInFlightSuccessClearsUnavailable_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
manager := NewManager(nil, nil, nil)
|
||||
authID := "issue8523-late-success.json"
|
||||
model := "issue8523-model"
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: authID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-token",
|
||||
"expired": validExp,
|
||||
},
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register error = %v", errReg)
|
||||
}
|
||||
|
||||
// Disable credential, then receive a late in-flight success while disabled.
|
||||
if _, _, errMod := manager.Modify(ctx, authID, 0, func(current *Auth) error {
|
||||
current.Disabled = true
|
||||
current.Status = StatusDisabled
|
||||
return nil
|
||||
}); errMod != nil {
|
||||
t.Fatalf("Modify(disable) error = %v", errMod)
|
||||
}
|
||||
manager.MarkResult(ctx, Result{
|
||||
AuthID: authID,
|
||||
Provider: "codex",
|
||||
Model: model,
|
||||
Success: true,
|
||||
})
|
||||
|
||||
// Re-enable credential.
|
||||
if _, _, errMod := manager.Modify(ctx, authID, 0, func(current *Auth) error {
|
||||
current.Disabled = false
|
||||
current.Status = StatusActive
|
||||
current.StatusMessage = ""
|
||||
return nil
|
||||
}); errMod != nil {
|
||||
t.Fatalf("Modify(re-enable) error = %v", errMod)
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(authID)
|
||||
if got.Unavailable {
|
||||
t.Fatalf("auth.Unavailable = true after re-enable following late disabled success, want false")
|
||||
}
|
||||
if !IsAuthAvailableForModel(got, model, time.Now()) {
|
||||
t.Fatalf("IsAuthAvailableForModel = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReenableDisabledAuthWithRequiresSignInAndExpiredTokenStaysError_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
manager := NewManager(nil, nil, nil)
|
||||
authID := "issue8523-requires-signin.json"
|
||||
expiredAt := time.Now().UTC().Add(-time.Hour).Format(time.RFC3339)
|
||||
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: authID,
|
||||
Provider: "codex",
|
||||
Disabled: true,
|
||||
Status: StatusDisabled,
|
||||
Unavailable: true,
|
||||
RequiresSignIn: true,
|
||||
RefreshError: &Error{Code: "invalid_grant", Message: "refresh token invalid", HTTPStatus: http.StatusUnauthorized},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "expired-token",
|
||||
"refresh_token": "rejected-refresh",
|
||||
"expired": expiredAt,
|
||||
},
|
||||
RejectedRefreshToken: "rejected-refresh",
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register error = %v", errReg)
|
||||
}
|
||||
|
||||
// Re-enable without replacing tokens: must NOT become status=active + unavailable=true or falsely available.
|
||||
if _, _, errMod := manager.Modify(ctx, authID, 0, func(current *Auth) error {
|
||||
current.Disabled = false
|
||||
current.Status = StatusActive
|
||||
current.StatusMessage = ""
|
||||
return nil
|
||||
}); errMod != nil {
|
||||
t.Fatalf("Modify(re-enable) error = %v", errMod)
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(authID)
|
||||
if !got.Unavailable {
|
||||
t.Fatal("auth.Unavailable = false, want true when RequiresSignIn and token is expired")
|
||||
}
|
||||
if got.Status != StatusError {
|
||||
t.Fatalf("auth.Status = %q, want %q (must not expose status=active while unavailable)", got.Status, StatusError)
|
||||
}
|
||||
if got.StatusMessage == "" {
|
||||
t.Fatal("auth.StatusMessage is empty, want explicit error reason")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSnapshotReloadHealsOrphanedUnavailableWithoutCooldown_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
manager := NewManager(nil, nil, nil)
|
||||
authID := "issue8523-file-reload.json"
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
|
||||
tmpDir := t.TempDir()
|
||||
filePath := filepath.Join(tmpDir, authID)
|
||||
raw := []byte("{\"type\":\"codex\",\"access_token\":\"valid-token\",\"expired\":\"" + validExp + "\",\"priority\":2}")
|
||||
if errWrite := os.WriteFile(filePath, raw, 0o600); errWrite != nil {
|
||||
t.Fatalf("WriteFile error = %v", errWrite)
|
||||
}
|
||||
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: authID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Unavailable: true, // Orphaned unavailable with zero deadlines and active status.
|
||||
Attributes: map[string]string{
|
||||
AttributePath: filePath,
|
||||
"priority": "0",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-token",
|
||||
"expired": validExp,
|
||||
"priority": 0,
|
||||
},
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register error = %v", errReg)
|
||||
}
|
||||
|
||||
reloaded := &Auth{
|
||||
ID: authID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Attributes: map[string]string{
|
||||
AttributePath: filePath,
|
||||
"priority": "2",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-token",
|
||||
"expired": validExp,
|
||||
"priority": 2,
|
||||
},
|
||||
}
|
||||
reloaded.BindFileSnapshot(filePath, raw)
|
||||
|
||||
updated, errUpdate := manager.Update(ctx, reloaded)
|
||||
if errUpdate != nil {
|
||||
t.Fatalf("Update error = %v", errUpdate)
|
||||
}
|
||||
if updated.Unavailable {
|
||||
t.Fatalf("file reload preserved orphaned Unavailable=true with zero cooldown deadline")
|
||||
}
|
||||
if !IsAuthAvailableForModel(updated, "gpt-6-luna", time.Now()) {
|
||||
t.Fatalf("IsAuthAvailableForModel = false after file reload, want true")
|
||||
}
|
||||
|
||||
// Negative case: an active timed cooldown must still be preserved across a priority edit.
|
||||
activeRetry := time.Now().Add(10 * time.Minute)
|
||||
if _, _, errMod := manager.Modify(ctx, authID, 0, func(current *Auth) error {
|
||||
current.Unavailable = true
|
||||
current.Status = StatusError
|
||||
current.StatusMessage = "quota exhausted"
|
||||
current.NextRetryAfter = activeRetry
|
||||
current.Quota = QuotaState{Exceeded: true, Reason: "credential_quota", NextRecoverAt: activeRetry}
|
||||
return nil
|
||||
}); errMod != nil {
|
||||
t.Fatalf("Modify(cooldown) error = %v", errMod)
|
||||
}
|
||||
|
||||
reloaded2 := reloaded.Clone()
|
||||
reloaded2.Attributes["priority"] = "3"
|
||||
reloaded2.Metadata["priority"] = 3
|
||||
reloaded2.BindFileSnapshot(filePath, raw)
|
||||
updated2, errUpdate2 := manager.Update(ctx, reloaded2)
|
||||
if errUpdate2 != nil {
|
||||
t.Fatalf("Update(with active cooldown) error = %v", errUpdate2)
|
||||
}
|
||||
if !updated2.Unavailable || !updated2.NextRetryAfter.After(time.Now()) {
|
||||
t.Fatalf("active cooldown was lost on file reload: unavailable=%v nextRetry=%v", updated2.Unavailable, updated2.NextRetryAfter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeRefreshedAuthConcurrentReenableClearsUnavailable_Issue8523(t *testing.T) {
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
base := &Auth{
|
||||
ID: "issue8523-merge",
|
||||
Provider: "codex",
|
||||
Disabled: true,
|
||||
Status: StatusDisabled,
|
||||
Unavailable: true,
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "old-token",
|
||||
"expired": validExp,
|
||||
"disabled": true,
|
||||
},
|
||||
}
|
||||
// User concurrently re-enabled before refresh committed, carrying Unavailable=true.
|
||||
current := base.Clone()
|
||||
current.Disabled = false
|
||||
current.Status = StatusActive
|
||||
current.StatusMessage = ""
|
||||
current.Metadata["disabled"] = false
|
||||
|
||||
// Refresh succeeded against disabled base (retaining StatusDisabled).
|
||||
updated := base.Clone()
|
||||
updated.Metadata["access_token"] = "new-token"
|
||||
|
||||
merged := MergeRefreshedAuth(base, current, updated)
|
||||
if merged == nil {
|
||||
t.Fatal("MergeRefreshedAuth returned nil")
|
||||
}
|
||||
if merged.Disabled || merged.Status != StatusActive {
|
||||
t.Fatalf("merged disabled=%v status=%q, want false / %q", merged.Disabled, merged.Status, StatusActive)
|
||||
}
|
||||
if merged.Unavailable {
|
||||
t.Fatalf("merged.Unavailable = true after concurrent re-enable during refresh, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrphanedUnavailableIsRoutableWithoutResetOrEdit_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
reg := registry.GetGlobalRegistry()
|
||||
model := "issue8523-orphaned-direct-gpt-6-luna"
|
||||
highID := "issue8523-orphaned-high.json"
|
||||
lowID := "issue8523-orphaned-low.json"
|
||||
t.Cleanup(func() {
|
||||
reg.UnregisterClient(highID)
|
||||
reg.UnregisterClient(lowID)
|
||||
})
|
||||
|
||||
manager := NewManager(nil, &RoundRobinSelector{}, nil)
|
||||
manager.RegisterExecutor(&issue7756DummyExecutor{id: "codex"})
|
||||
now := time.Now().UTC()
|
||||
validExp := now.Add(time.Hour).Format(time.RFC3339)
|
||||
|
||||
// Register high-priority auth directly in the contradictory stuck state:
|
||||
// enabled, StatusActive, empty StatusMessage, nil LastError, empty ModelStates,
|
||||
// zero NextRetryAfter, Quota.Exceeded=false, valid token, but Unavailable=true.
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: highID,
|
||||
FileName: highID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Unavailable: true,
|
||||
Attributes: map[string]string{"priority": "8"},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-high-token",
|
||||
"expired": validExp,
|
||||
},
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register(high) error = %v", errReg)
|
||||
}
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: lowID,
|
||||
FileName: lowID,
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Attributes: map[string]string{"priority": "0"},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-low-token",
|
||||
"expired": validExp,
|
||||
},
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register(low) error = %v", errReg)
|
||||
}
|
||||
reg.RegisterClient(highID, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
reg.RegisterClient(lowID, "codex", []*registry.ModelInfo{{ID: model}})
|
||||
manager.RefreshSchedulerEntry(highID)
|
||||
manager.RefreshSchedulerEntry(lowID)
|
||||
|
||||
highSnap, _ := manager.GetByID(highID)
|
||||
if !IsAuthAvailableForModel(highSnap, model, time.Now()) {
|
||||
t.Fatal("IsAuthAvailableForModel = false for orphaned active auth without reset/edit, want true")
|
||||
}
|
||||
proj := manager.clientModelProjectionForAuth(highSnap, model, time.Now())
|
||||
if proj.Suspended {
|
||||
t.Fatalf("clientModelProjectionForAuth suspended orphaned active auth: %+v", proj)
|
||||
}
|
||||
|
||||
// Without editing files, toggling disabled, or calling ResetQuota, routing must select highID.
|
||||
picked, _, errPick := manager.pickNext(ctx, "codex", model, cliproxyexecutor.Options{}, nil)
|
||||
if errPick != nil {
|
||||
t.Fatalf("pickNext error = %v", errPick)
|
||||
}
|
||||
if picked == nil || picked.ID != highID {
|
||||
pickedID := ""
|
||||
if picked != nil {
|
||||
pickedID = picked.ID
|
||||
}
|
||||
t.Fatalf("pickNext selected %q, want %q without requiring file edit or cooldown reset", pickedID, highID)
|
||||
}
|
||||
}
|
||||
|
||||
type issue8523BlockingStore struct {
|
||||
mu sync.Mutex
|
||||
blockNext bool
|
||||
saveStarted chan struct{}
|
||||
releaseSave chan struct{}
|
||||
}
|
||||
|
||||
func (s *issue8523BlockingStore) List(context.Context) ([]*Auth, error) { return nil, nil }
|
||||
|
||||
func (s *issue8523BlockingStore) Save(_ context.Context, auth *Auth) (string, error) {
|
||||
s.mu.Lock()
|
||||
shouldBlock := s.blockNext
|
||||
if shouldBlock {
|
||||
s.blockNext = false
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if shouldBlock {
|
||||
close(s.saveStarted)
|
||||
<-s.releaseSave
|
||||
}
|
||||
if auth == nil {
|
||||
return "", nil
|
||||
}
|
||||
return auth.ID, nil
|
||||
}
|
||||
|
||||
func (s *issue8523BlockingStore) Delete(context.Context, string) error { return nil }
|
||||
|
||||
type issue8523FailingRefreshExecutor struct {
|
||||
issue7756DummyExecutor
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *issue8523FailingRefreshExecutor) Refresh(context.Context, *Auth) (*Auth, error) {
|
||||
return nil, e.err
|
||||
}
|
||||
|
||||
func TestReenableNotOverwrittenByConcurrentDisabledRefreshFailureDuringPersist_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &issue8523BlockingStore{
|
||||
saveStarted: make(chan struct{}),
|
||||
releaseSave: make(chan struct{}),
|
||||
}
|
||||
manager := NewManager(store, &RoundRobinSelector{}, nil)
|
||||
manager.RegisterExecutor(&issue8523FailingRefreshExecutor{
|
||||
issue7756DummyExecutor: issue7756DummyExecutor{id: "codex"},
|
||||
err: &Error{Code: "upstream_503", Message: "temporary refresh failure", HTTPStatus: http.StatusServiceUnavailable},
|
||||
})
|
||||
|
||||
authID := "issue8523-persist-race.json"
|
||||
validExp := time.Now().UTC().Add(time.Hour).Format(time.RFC3339)
|
||||
|
||||
// Start with disabled=true, unavailable=false so a concurrent refresh failure
|
||||
// during persistLocked flips existing.Unavailable false->true while existing.Status stays disabled.
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: authID,
|
||||
Provider: "codex",
|
||||
Disabled: true,
|
||||
Status: StatusDisabled,
|
||||
Unavailable: false,
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-token",
|
||||
"refresh_token": "refresh-tok",
|
||||
"expired": validExp,
|
||||
"disabled": true,
|
||||
},
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register error = %v", errReg)
|
||||
}
|
||||
|
||||
store.mu.Lock()
|
||||
store.blockNext = true
|
||||
store.mu.Unlock()
|
||||
|
||||
modifyDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, _, errMod := manager.Modify(ctx, authID, 0, func(current *Auth) error {
|
||||
current.Disabled = false
|
||||
current.Status = StatusActive
|
||||
current.StatusMessage = ""
|
||||
current.Unavailable = false
|
||||
current.LastError = nil
|
||||
current.Metadata["disabled"] = false
|
||||
return nil
|
||||
})
|
||||
modifyDone <- errMod
|
||||
}()
|
||||
|
||||
// Wait until Modify has entered persistLocked and released m.mu.
|
||||
<-store.saveStarted
|
||||
|
||||
// Run a transient refresh failure while existing in m.auths is still disabled.
|
||||
manager.refreshAuth(ctx, authID)
|
||||
|
||||
// Verify existing in m.auths was flipped to Unavailable=true while still disabled.
|
||||
midSnap, _ := manager.GetByID(authID)
|
||||
if !midSnap.Disabled || !midSnap.Unavailable {
|
||||
t.Fatalf("expected concurrent refresh to mark still-disabled auth Unavailable=true, got disabled=%v unavailable=%v",
|
||||
midSnap.Disabled, midSnap.Unavailable)
|
||||
}
|
||||
|
||||
// Unblock Store.Save so Modify runs post-save mergeAuthSaveDelta and publishes.
|
||||
close(store.releaseSave)
|
||||
if errMod := <-modifyDone; errMod != nil {
|
||||
t.Fatalf("Modify(re-enable) error = %v", errMod)
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(authID)
|
||||
if got.Disabled || got.Status != StatusActive {
|
||||
t.Fatalf("final auth disabled=%v status=%q, want false / %q", got.Disabled, got.Status, StatusActive)
|
||||
}
|
||||
if got.Unavailable {
|
||||
t.Fatalf("post-save delta merge re-introduced Unavailable=true on re-enabled active auth (lastErr=%+v)", got.LastError)
|
||||
}
|
||||
if !IsAuthAvailableForModel(got, "gpt-6-luna", time.Now()) {
|
||||
t.Fatal("IsAuthAvailableForModel = false after re-enable race, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReenableDisabledSIWCUnknownDiagnostic401PreservesOuterRouting_Issue8523(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
manager := NewManager(nil, nil, nil)
|
||||
authID := "issue8523-siwc-diagnostic-401.json"
|
||||
now := time.Now().UTC()
|
||||
validOuterExp := now.Add(time.Hour).Format(time.RFC3339)
|
||||
expiredSIWCExp := now.Add(-time.Hour).Format(time.RFC3339)
|
||||
|
||||
// Disabled Codex SIWC auth whose disabled-era refresh left both
|
||||
// RefreshError.Code=refresh_outcome_unknown and a diagnostic HTTP 401 LastError.
|
||||
if _, errReg := manager.Register(ctx, &Auth{
|
||||
ID: authID,
|
||||
Provider: "codex",
|
||||
Disabled: true,
|
||||
Status: StatusDisabled,
|
||||
Unavailable: true,
|
||||
RequiresSignIn: true,
|
||||
RejectedSIWCRefreshToken: "siwc-refresh",
|
||||
RefreshError: &Error{
|
||||
Code: "refresh_outcome_unknown",
|
||||
Message: "siwc refresh transport diagnostic",
|
||||
HTTPStatus: http.StatusUnauthorized,
|
||||
},
|
||||
LastError: &Error{
|
||||
Code: "unauthorized",
|
||||
Message: "siwc refresh transport diagnostic",
|
||||
HTTPStatus: http.StatusUnauthorized,
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "outer-valid-token",
|
||||
"refresh_token": "outer-refresh",
|
||||
"expired": validOuterExp,
|
||||
"use_siwc": true,
|
||||
"disabled": true,
|
||||
"siwc": map[string]any{
|
||||
"access_token": "siwc-expired-token",
|
||||
"refresh_token": "siwc-refresh",
|
||||
"client_id": "siwc-client",
|
||||
"expires_at": expiredSIWCExp,
|
||||
},
|
||||
},
|
||||
}); errReg != nil {
|
||||
t.Fatalf("Register error = %v", errReg)
|
||||
}
|
||||
|
||||
// Re-enable via Modify (mirrors Management API re-enable).
|
||||
if _, _, errMod := manager.Modify(ctx, authID, 0, func(current *Auth) error {
|
||||
current.Disabled = false
|
||||
current.Status = StatusActive
|
||||
current.StatusMessage = ""
|
||||
current.Unavailable = false
|
||||
current.LastError = nil
|
||||
current.Metadata["disabled"] = false
|
||||
return nil
|
||||
}); errMod != nil {
|
||||
t.Fatalf("Modify(re-enable) error = %v", errMod)
|
||||
}
|
||||
|
||||
got, _ := manager.GetByID(authID)
|
||||
if !got.Unavailable || got.Status != StatusError {
|
||||
t.Fatalf("re-enabled SIWC auth = (unavailable=%v, status=%q), want (true, error)", got.Unavailable, got.Status)
|
||||
}
|
||||
if got.LastError == nil || got.LastError.Code != "refresh_outcome_unknown" || got.LastError.HTTPStatus == http.StatusUnauthorized {
|
||||
t.Fatalf("re-enabled SIWC auth escalated diagnostic 401: LastError=%+v", got.LastError)
|
||||
}
|
||||
if hasUnauthorizedAuthFailure(got) {
|
||||
t.Fatal("hasUnauthorizedAuthFailure = true, want false so valid outer token remains routable")
|
||||
}
|
||||
|
||||
// SIWC requests (default headers) must stay blocked because SIWC token is expired.
|
||||
if blocked, _, _ := isAuthBlockedForModelForRequest(ctx, got, "gpt-6-luna", now); !blocked {
|
||||
t.Fatal("SIWC request was not blocked while SIWC token is expired")
|
||||
}
|
||||
// Native Codex requests (using healthy outer token) must remain routable.
|
||||
nativeHeaders := http.Header{"User-Agent": {"codex_cli_rs/1.0.0"}}
|
||||
if blocked, _, _ := isAuthBlockedForModelForRequest(ctx, got, "gpt-6-luna", now, nativeHeaders); blocked {
|
||||
t.Fatal("native Codex request with valid outer token was blocked after re-enable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrphanedUnavailablePredicateRejectsExpiredTokenAndFutureQuotaRecoverAt_Issue8523(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
manager := NewManager(nil, &RoundRobinSelector{}, nil)
|
||||
model := "issue8523-negative-guard-model"
|
||||
|
||||
t.Run("expired access token without RequiresSignIn stays unavailable", func(t *testing.T) {
|
||||
expiredAuth := &Auth{
|
||||
ID: "issue8523-expired-no-signin.json",
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Unavailable: true,
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "expired-token",
|
||||
"expired": now.Add(-time.Minute).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
if IsOrphanedAuthUnavailable(expiredAuth, now) {
|
||||
t.Fatal("IsOrphanedAuthUnavailable = true for expired access token, want false")
|
||||
}
|
||||
if IsAuthAvailableForModel(expiredAuth, model, now) {
|
||||
t.Fatal("IsAuthAvailableForModel = true for expired access token, want false")
|
||||
}
|
||||
if proj := manager.clientModelProjectionForAuth(expiredAuth, model, now); !proj.Suspended {
|
||||
t.Fatalf("clientModelProjectionForAuth.Suspended = false for expired access token, want true (%+v)", proj)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("future Quota.NextRecoverAt without Quota.Exceeded stays unavailable", func(t *testing.T) {
|
||||
recoverAt := now.Add(10 * time.Minute)
|
||||
recoveringAuth := &Auth{
|
||||
ID: "issue8523-future-recover-at.json",
|
||||
Provider: "codex",
|
||||
Status: StatusActive,
|
||||
Unavailable: true,
|
||||
Quota: QuotaState{
|
||||
Exceeded: false,
|
||||
NextRecoverAt: recoverAt,
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"type": "codex",
|
||||
"access_token": "valid-token",
|
||||
"expired": now.Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
if IsOrphanedAuthUnavailable(recoveringAuth, now) {
|
||||
t.Fatal("IsOrphanedAuthUnavailable = true with future Quota.NextRecoverAt, want false")
|
||||
}
|
||||
if IsAuthAvailableForModel(recoveringAuth, model, now) {
|
||||
t.Fatal("IsAuthAvailableForModel = true with future Quota.NextRecoverAt, want false")
|
||||
}
|
||||
if proj := manager.clientModelProjectionForAuth(recoveringAuth, model, now); !proj.Suspended {
|
||||
t.Fatalf("clientModelProjectionForAuth.Suspended = false with future Quota.NextRecoverAt, want true (%+v)", proj)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -714,6 +714,9 @@ func (m *Manager) updateInternalLockedWithOptions(ctx context.Context, base, aut
|
||||
auth.Status = existing.Status
|
||||
}
|
||||
}
|
||||
if isFileSnapshot && reconcileOrphanedAuthUnavailable(auth, now) {
|
||||
cooldownStateChanged = true
|
||||
}
|
||||
} else {
|
||||
applyPreservedRejectedTokens(existing, auth, mode == updateModeRefresh)
|
||||
applyPreservedRenewalState(existing, auth, mode, now)
|
||||
@@ -731,6 +734,11 @@ func (m *Manager) updateInternalLockedWithOptions(ctx context.Context, base, aut
|
||||
}
|
||||
}
|
||||
}
|
||||
if (existing.Disabled || existing.Status == StatusDisabled) && !auth.Disabled && auth.Status != StatusDisabled {
|
||||
if reconcileReenabledAuthState(auth, existing, now) {
|
||||
cooldownStateChanged = true
|
||||
}
|
||||
}
|
||||
}
|
||||
auth.UpdatedAt = now
|
||||
cooldownStateChanged = m.migrateAuthAliasModelStatesLocked(auth, nil, now, false) || cooldownStateChanged
|
||||
@@ -812,6 +820,15 @@ func (m *Manager) updateInternalLockedWithOptions(ctx context.Context, base, aut
|
||||
}
|
||||
}
|
||||
}
|
||||
if (existingBeforeSave.Disabled || existingBeforeSave.Status == StatusDisabled) && !auth.Disabled && auth.Status != StatusDisabled {
|
||||
if reconcileReenabledAuthState(auth, existing, now) {
|
||||
cooldownStateChanged = true
|
||||
}
|
||||
} else if isFileSnapshot && !auth.Disabled && auth.Status != StatusDisabled {
|
||||
if reconcileOrphanedAuthUnavailable(auth, now) {
|
||||
cooldownStateChanged = true
|
||||
}
|
||||
}
|
||||
if existing.Generation >= auth.Generation {
|
||||
auth.Generation = existing.Generation + 1
|
||||
}
|
||||
@@ -838,6 +855,142 @@ func (m *Manager) updateInternalLockedWithOptions(ctx context.Context, base, aut
|
||||
return auth.Clone(), true, baseSuperseded, cooldownStateChanged, nil
|
||||
}
|
||||
|
||||
// reconcileReenabledAuthState reconciles availability and status when a
|
||||
// credential transitions from disabled back to enabled. It clears disabled-era
|
||||
// unavailability and disabled model states while keeping unresolved sign-in or
|
||||
// rejected-token failures explicitly marked as StatusError.
|
||||
func reconcileReenabledAuthState(auth, existing *Auth, now time.Time) bool {
|
||||
if auth == nil || auth.Disabled || auth.Status == StatusDisabled {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
for _, state := range auth.ModelStates {
|
||||
if state == nil || state.Status != StatusDisabled {
|
||||
continue
|
||||
}
|
||||
resetModelState(state, now)
|
||||
changed = true
|
||||
}
|
||||
requiresSignInBlocked := auth.RequiresSignIn && !auth.HasValidAccessToken(now)
|
||||
rejectedAccessBlocked := hasRejectedActiveAccessToken(auth)
|
||||
if requiresSignInBlocked || rejectedAccessBlocked || hasUnauthorizedAuthFailure(auth) {
|
||||
auth.Unavailable = true
|
||||
auth.Status = StatusError
|
||||
if auth.StatusMessage == "" || strings.HasPrefix(strings.ToLower(strings.TrimSpace(auth.StatusMessage)), "disabled") {
|
||||
if existing != nil && existing.StatusMessage != "" && !strings.HasPrefix(strings.ToLower(strings.TrimSpace(existing.StatusMessage)), "disabled") {
|
||||
auth.StatusMessage = existing.StatusMessage
|
||||
} else {
|
||||
auth.StatusMessage = "unauthorized (refresh token invalid)"
|
||||
}
|
||||
}
|
||||
if auth.RefreshError != nil && auth.RefreshError.Code == "refresh_outcome_unknown" {
|
||||
// Use refreshAccessError so a diagnostic 401 from an unknown SIWC refresh
|
||||
// does not escalate into a terminal unauthorized block for valid outer tokens.
|
||||
auth.LastError = refreshAccessError(auth, auth.RefreshError.Message, rejectedAccessBlocked, hasUnauthorizedAuthFailure(existing))
|
||||
if auth.LastError != nil && auth.LastError.Code == "refresh_outcome_unknown" {
|
||||
auth.StatusMessage = auth.LastError.Message
|
||||
}
|
||||
} else if auth.LastError == nil {
|
||||
if auth.RefreshError != nil {
|
||||
auth.LastError = refreshAccessError(auth, auth.RefreshError.Message, rejectedAccessBlocked, hasUnauthorizedAuthFailure(existing))
|
||||
} else if existing != nil && existing.LastError != nil && !isTOSViolationResultError(existing.LastError) {
|
||||
auth.LastError = cloneError(existing.LastError)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
prevUnavailable := auth.Unavailable
|
||||
if len(auth.ModelStates) > 0 {
|
||||
updateAggregatedAvailability(auth, now)
|
||||
} else if auth.Unavailable &&
|
||||
!auth.NextRetryAfter.After(now) &&
|
||||
!(auth.Quota.Exceeded && auth.Quota.NextRecoverAt.After(now)) &&
|
||||
!auth.credentialRetryAfter.After(now) &&
|
||||
!effectiveAuthForceUntil(auth).After(now) {
|
||||
auth.Unavailable = false
|
||||
auth.NextRetryAfter = time.Time{}
|
||||
applyCooldownFields(&auth.Quota, QuotaState{})
|
||||
}
|
||||
if auth.Unavailable != prevUnavailable {
|
||||
changed = true
|
||||
}
|
||||
if !auth.Unavailable && !hasModelError(auth, now) && !effectiveAuthForceUntil(auth).After(now) {
|
||||
auth.Status = StatusActive
|
||||
auth.StatusMessage = ""
|
||||
auth.LastError = nil
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
func hasRejectedActiveAccessToken(auth *Auth) bool {
|
||||
if auth == nil {
|
||||
return false
|
||||
}
|
||||
if IsCodexUseSIWC(auth) {
|
||||
token := authSIWCTokenField(auth, "access_token")
|
||||
return (auth.RejectedSIWCAccessToken != "" && token == auth.RejectedSIWCAccessToken) ||
|
||||
(auth.RejectedAccessToken != "" && token == auth.RejectedAccessToken)
|
||||
}
|
||||
token := authOuterAccessToken(auth)
|
||||
return auth.RejectedAccessToken != "" && token == auth.RejectedAccessToken
|
||||
}
|
||||
|
||||
// IsOrphanedAuthUnavailable reports whether auth carries an unexplained
|
||||
// auth-level Unavailable=true flag with StatusActive, empty error details,
|
||||
// no quota exhaustion, no retry/cooldown deadline, no model errors, and no
|
||||
// unresolved sign-in or token-rejection block.
|
||||
func IsOrphanedAuthUnavailable(auth *Auth, now time.Time) bool {
|
||||
return isOrphanedAuthUnavailable(auth, now)
|
||||
}
|
||||
|
||||
func isOrphanedAuthUnavailable(auth *Auth, now time.Time) bool {
|
||||
if auth == nil || !auth.Unavailable || auth.Disabled || auth.Status == StatusDisabled {
|
||||
return false
|
||||
}
|
||||
if auth.Status != StatusActive {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(auth.StatusMessage) != "" || auth.LastError != nil {
|
||||
return false
|
||||
}
|
||||
if auth.Quota.Exceeded || !auth.Quota.NextRecoverAt.IsZero() || !auth.NextRetryAfter.IsZero() {
|
||||
return false
|
||||
}
|
||||
if auth.credentialRetryAfter.After(now) || effectiveAuthForceUntil(auth).After(now) {
|
||||
return false
|
||||
}
|
||||
if exp, ok := auth.AccessTokenExpirationTime(); ok && !exp.IsZero() && !exp.After(now) {
|
||||
return false
|
||||
}
|
||||
if hasUnauthorizedAuthFailure(auth) || (auth.RequiresSignIn && !auth.HasValidAccessToken(now)) {
|
||||
return false
|
||||
}
|
||||
if hasRejectedActiveAccessToken(auth) {
|
||||
return false
|
||||
}
|
||||
if hasModelError(auth, now) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// reconcileOrphanedAuthUnavailable clears a stale auth.Unavailable flag carried
|
||||
// across file-snapshot reloads when an enabled credential has StatusActive, no
|
||||
// active cooldown deadline, no model errors, and no unresolved auth/token block.
|
||||
func reconcileOrphanedAuthUnavailable(auth *Auth, now time.Time) bool {
|
||||
if !isOrphanedAuthUnavailable(auth, now) {
|
||||
return false
|
||||
}
|
||||
if len(auth.ModelStates) > 0 {
|
||||
updateAggregatedAvailability(auth, now)
|
||||
return !auth.Unavailable
|
||||
}
|
||||
auth.Unavailable = false
|
||||
auth.NextRetryAfter = time.Time{}
|
||||
applyCooldownFields(&auth.Quota, QuotaState{})
|
||||
return true
|
||||
}
|
||||
|
||||
func equalErrorPtr(a, b *Error) bool {
|
||||
if a == nil && b == nil {
|
||||
return true
|
||||
|
||||
@@ -397,7 +397,8 @@ func (m *Manager) clientModelProjectionForAuth(auth *Auth, routeModel string, no
|
||||
// cooldown (isAuthBlockedForModel); the projection must agree with it.
|
||||
// When states exist, unmatched models stay schedulable by design, so the
|
||||
// credential-wide fields must not suspend them here either.
|
||||
if blocked, _, retryAfter := availabilityBlock(auth.Unavailable, auth.Quota.Exceeded, auth.NextRetryAfter, auth.Quota.NextRecoverAt, now); blocked {
|
||||
effectiveUnavailable := auth.Unavailable && !isOrphanedAuthUnavailable(auth, now)
|
||||
if blocked, _, retryAfter := availabilityBlock(effectiveUnavailable, auth.Quota.Exceeded, auth.NextRetryAfter, auth.Quota.NextRecoverAt, now); blocked {
|
||||
isSuspended = true
|
||||
if retryAfter.IsZero() {
|
||||
openEnded = true
|
||||
|
||||
@@ -142,7 +142,7 @@ func MergeRefreshedAuth(base, current, updated *Auth) *Auth {
|
||||
merged.Unavailable = current.Unavailable
|
||||
merged.Status = current.Status
|
||||
merged.StatusMessage = current.StatusMessage
|
||||
} else if (updated.Status == StatusActive || updated.Status == "") && (!merged.RequiresSignIn || merged.HasValidAccessToken(time.Now())) && (merged.RejectedAccessToken == "" || authAccessToken(merged) != merged.RejectedAccessToken) {
|
||||
} else if (updated.Status == StatusActive || updated.Status == "" || (baseDisabled && !currentDisabled && updated.Status == StatusDisabled)) && (!merged.RequiresSignIn || merged.HasValidAccessToken(time.Now())) && (merged.RejectedAccessToken == "" || authAccessToken(merged) != merged.RejectedAccessToken) {
|
||||
// Successful refresh clears previous auth error and restores active
|
||||
merged.Status = StatusActive
|
||||
merged.Unavailable = false
|
||||
|
||||
@@ -1039,13 +1039,14 @@ func isCredentialBlocked(auth *Auth, supportedModelCount int, now time.Time) boo
|
||||
if !auth.credentialRetryAfter.IsZero() && auth.credentialRetryAfter.After(now) {
|
||||
return true
|
||||
}
|
||||
effectiveUnavailable := auth.Unavailable && !isOrphanedAuthUnavailable(auth, now)
|
||||
if len(auth.ModelStates) == 0 {
|
||||
return auth.Unavailable || auth.Quota.Exceeded || (!auth.NextRetryAfter.IsZero() && auth.NextRetryAfter.After(now))
|
||||
return effectiveUnavailable || auth.Quota.Exceeded || (!auth.NextRetryAfter.IsZero() && auth.NextRetryAfter.After(now))
|
||||
}
|
||||
if supportedModelCount > 0 && len(auth.ModelStates) < supportedModelCount {
|
||||
return false
|
||||
}
|
||||
return auth.Unavailable
|
||||
return effectiveUnavailable
|
||||
}
|
||||
|
||||
// upsertAuthResultLocked updates one auth in-place after a request execution result,
|
||||
|
||||
@@ -1329,6 +1329,9 @@ func isAuthBlockedForModelForRequest(ctx context.Context, auth *Auth, model stri
|
||||
return true, blockReasonOther, credNext
|
||||
}
|
||||
unavailable := codexRefreshUnavailableForRequest(ctx, auth, now, clientHeaders...)
|
||||
if unavailable && isOrphanedAuthUnavailable(auth, now) {
|
||||
unavailable = false
|
||||
}
|
||||
if model != "" {
|
||||
if len(auth.ModelStates) > 0 {
|
||||
modelKey := canonicalModelLookupKey(model)
|
||||
@@ -1508,6 +1511,9 @@ func isAuthBlockedByQuotaOrAuthForModelForRequest(ctx context.Context, auth *Aut
|
||||
}
|
||||
quota := auth.Quota
|
||||
unavailable := codexRefreshUnavailableForRequest(ctx, auth, now, clientHeaders...)
|
||||
if unavailable && isOrphanedAuthUnavailable(auth, now) {
|
||||
unavailable = false
|
||||
}
|
||||
if len(auth.ModelStates) > 0 && auth.Quota.Reason != "credential_quota" && !unavailable {
|
||||
quota.Exceeded = false
|
||||
}
|
||||
|
||||
@@ -151,6 +151,7 @@ func TestSessionAffinityFallbackOnlyReceivesHighestAvailablePriority(t *testing.
|
||||
assertPick("cold binding", opts, high.ID)
|
||||
assertPick("no-session fallback", cliproxyexecutor.Options{}, high.ID)
|
||||
|
||||
high.Status = StatusError
|
||||
high.Unavailable = true
|
||||
assertPick("fallback after bound auth became unavailable", opts, low.ID)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user