diff --git a/internal/api/handlers/management/auth_files_fields.go b/internal/api/handlers/management/auth_files_fields.go index a5b5558f57..698ed934a6 100644 --- a/internal/api/handlers/management/auth_files_fields.go +++ b/internal/api/handlers/management/auth_files_fields.go @@ -17,6 +17,7 @@ import ( "github.com/gin-gonic/gin" claudeauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude" "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" + xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/clienterror" "github.com/router-for-me/CLIProxyAPI/v8/internal/credentialweight" "github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer" @@ -1013,6 +1014,38 @@ func (h *Handler) saveTokenRecord(ctx context.Context, record *coreauth.Auth) (s if legacyClaudeCredential != nil { coreauth.MergeExistingAuthMetadata(record, legacyClaudeCredential.Metadata) } + legacyXAICredential, errLegacyXAI := xaiauth.FindMatchingLegacyCredential(ctx, store, record) + if errLegacyXAI != nil { + return "", errLegacyXAI + } + adoptXAICredential := legacyXAICredential != nil && + strings.EqualFold(strings.TrimSpace(record.Provider), "xai") && + metadataStringValue(record.Metadata, "email") == "" && + metadataStringValue(record.Metadata, "sub") != "" && + metadataStringValue(legacyXAICredential.Metadata, "email") != "" + if adoptXAICredential { + // The upstream stopped returning the email; keep the account on its + // richer email-named credential (richest-known name wins) so the next + // login that returns the email finds the same file again. Renaming is + // limited to stores that resolve the save path from the record name; + // every built-in backend (file, git, Postgres, object) exposes the + // SetBaseDir capability, so unknown stores keep the ordinary + // migration instead of risking a rename they cannot honor. + if _, isFileNameStore := store.(interface{ SetBaseDir(string) }); !isFileNameStore { + adoptXAICredential = false + } else if disabled, hasDisabled := record.Metadata["disabled"].(bool); hasDisabled && disabled { + // The destination file deliberately disables this credential; renaming + // would leave it disabled while the richer file gets deleted, losing + // the operator's opt-out and the saved credential on re-login. + adoptXAICredential = false + } + } + if legacyXAICredential != nil { + coreauth.MergeExistingAuthMetadata(record, legacyXAICredential.Metadata) + } + if adoptXAICredential { + adoptLegacyXAIFileName(record, legacyXAICredential) + } if h.postAuthHook != nil { if err := h.postAuthHook(ctx, record); err != nil { return "", fmt.Errorf("post-auth hook failed: %w", err) @@ -1034,6 +1067,18 @@ func (h *Handler) saveTokenRecord(ctx context.Context, record *coreauth.Auth) (s return savedPath, fmt.Errorf("canonical Claude credential saved but legacy credential cleanup failed: %w", errDelete) } } + if legacyXAICredential != nil && !adoptXAICredential { + if strings.TrimSpace(savedPath) == "" { + return "", fmt.Errorf("canonical xAI credential was not persisted; legacy credential retained") + } + legacyID := strings.TrimSpace(legacyXAICredential.ID) + if legacyID == "" { + legacyID = strings.TrimSpace(legacyXAICredential.FileName) + } + if errDelete := store.Delete(ctx, legacyID); errDelete != nil { + return savedPath, fmt.Errorf("canonical xAI credential saved but legacy credential cleanup failed: %w", errDelete) + } + } if h.postAuthPersistHook != nil { persistedRecord := record if data, errRead := os.ReadFile(savedPath); errRead == nil && len(data) > 0 { @@ -1072,3 +1117,40 @@ func (h *Handler) saveTokenRecord(ctx context.Context, record *coreauth.Auth) (s } return savedPath, nil } + +func metadataStringValue(metadata map[string]any, key string) string { + value, _ := metadata[key].(string) + return strings.TrimSpace(value) +} + +// adoptLegacyXAIFileName points a subject-only xAI record at the existing +// email-named credential so the save refreshes that file in place. The token +// storage email is backfilled because SaveTokenToFile merges the record +// metadata over the serialized storage and would otherwise drop the email. +// Path attributes pointing at the superseded subject-named file are cleared +// so the store resolves the adopted name. +func adoptLegacyXAIFileName(record, legacy *coreauth.Auth) { + legacyFileName := strings.TrimSpace(legacy.FileName) + if legacyFileName == "" { + legacyFileName = strings.TrimSpace(legacy.ID) + } + if legacyFileName == "" { + return + } + oldBaseName := filepath.Base(strings.TrimSpace(record.FileName)) + if oldBaseName == "" || oldBaseName == "." { + oldBaseName = filepath.Base(strings.TrimSpace(record.ID)) + } + record.ID = legacyFileName + record.FileName = legacyFileName + if storage, ok := record.Storage.(*xaiauth.TokenStorage); ok && storage != nil { + if email := metadataStringValue(legacy.Metadata, "email"); email != "" { + storage.Email = email + } + } + for key, value := range record.Attributes { + if strings.TrimSpace(value) != "" && strings.EqualFold(filepath.Base(strings.TrimSpace(value)), oldBaseName) { + delete(record.Attributes, key) + } + } +} diff --git a/internal/api/handlers/management/auth_files_relogin_preserve_test.go b/internal/api/handlers/management/auth_files_relogin_preserve_test.go index bc34d77a5c..4f670dccb1 100644 --- a/internal/api/handlers/management/auth_files_relogin_preserve_test.go +++ b/internal/api/handlers/management/auth_files_relogin_preserve_test.go @@ -14,6 +14,7 @@ import ( "github.com/gin-gonic/gin" "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude" "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/codex" + "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" @@ -254,6 +255,213 @@ func TestSaveTokenRecord_MigratesMatchingLegacyClaudeCredential(t *testing.T) { } } +func TestSaveTokenRecord_MigratesMatchingLegacyXAICredential(t *testing.T) { + authDir := t.TempDir() + legacyFileName := "xai-a-b@example.com.json" + targetFileName := xai.CredentialFileName("a+b@example.com", "sub-first") + legacyPath := filepath.Join(authDir, legacyFileName) + targetPath := filepath.Join(authDir, targetFileName) + + existing := map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "old-token", + "refresh_token": "old-refresh", + "prefix": "team", + "proxy_url": "http://127.0.0.1:8080", + "disabled": true, + "weight": float64(5), + } + raw, errMarshal := json.Marshal(existing) + if errMarshal != nil { + t.Fatalf("marshal legacy credential: %v", errMarshal) + } + if errWrite := os.WriteFile(legacyPath, raw, 0o600); errWrite != nil { + t.Fatalf("write legacy credential: %v", errWrite) + } + + tokenStorage := &xai.TokenStorage{ + AccessToken: "new-token", + RefreshToken: "new-refresh", + Email: "a+b@example.com", + Subject: "sub-first", + Expire: "2026-12-31T23:59:59Z", + } + record := &coreauth.Auth{ + ID: targetFileName, + Provider: "xai", + FileName: targetFileName, + Storage: tokenStorage, + Metadata: map[string]any{ + "email": tokenStorage.Email, + "sub": tokenStorage.Subject, + }, + } + + h := NewHandler(&config.Config{AuthDir: authDir}, "", nil) + savedPath, errSave := h.saveTokenRecord(context.Background(), record) + if errSave != nil { + t.Fatalf("saveTokenRecord error: %v", errSave) + } + if savedPath != targetPath { + t.Fatalf("savedPath = %s, want %s", savedPath, targetPath) + } + if _, errStat := os.Stat(legacyPath); !os.IsNotExist(errStat) { + t.Fatalf("legacy credential still exists or stat failed: %v", errStat) + } + + savedRaw, errRead := os.ReadFile(targetPath) + if errRead != nil { + t.Fatalf("read migrated credential: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal migrated credential: %v", errUnmarshal) + } + for key, want := range map[string]any{ + "access_token": "new-token", + "refresh_token": "new-refresh", + "prefix": "team", + "proxy_url": "http://127.0.0.1:8080", + "disabled": true, + "weight": float64(5), + } { + if got := saved[key]; got != want { + t.Errorf("%s = %#v, want %#v", key, got, want) + } + } +} + +func TestSaveTokenRecord_ReloginKeepsCanonicalXAICredential(t *testing.T) { + authDir := t.TempDir() + targetFileName := xai.CredentialFileName("a+b@example.com", "sub-first") + targetPath := filepath.Join(authDir, targetFileName) + + existing := map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "old-token", + "refresh_token": "old-refresh", + "prefix": "team", + } + raw, errMarshal := json.Marshal(existing) + if errMarshal != nil { + t.Fatalf("marshal canonical credential: %v", errMarshal) + } + if errWrite := os.WriteFile(targetPath, raw, 0o600); errWrite != nil { + t.Fatalf("write canonical credential: %v", errWrite) + } + + tokenStorage := &xai.TokenStorage{ + AccessToken: "new-token", + RefreshToken: "new-refresh", + Email: "a+b@example.com", + Subject: "sub-first", + Expire: "2026-12-31T23:59:59Z", + } + record := &coreauth.Auth{ + ID: targetFileName, + Provider: "xai", + FileName: targetFileName, + Storage: tokenStorage, + Metadata: map[string]any{ + "email": tokenStorage.Email, + "sub": tokenStorage.Subject, + }, + } + + h := NewHandler(&config.Config{AuthDir: authDir}, "", nil) + savedPath, errSave := h.saveTokenRecord(context.Background(), record) + if errSave != nil { + t.Fatalf("saveTokenRecord error: %v", errSave) + } + if savedPath != targetPath { + t.Fatalf("savedPath = %s, want %s", savedPath, targetPath) + } + savedRaw, errRead := os.ReadFile(targetPath) + if errRead != nil { + t.Fatalf("canonical credential was deleted by re-login: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal canonical credential: %v", errUnmarshal) + } + if saved["access_token"] != "new-token" || saved["prefix"] != "team" { + t.Fatalf("saved credential = %#v, want new token with preserved prefix", saved) + } +} + +func TestSaveTokenRecord_SubjectOnlyReloginKeepsEmailCredential(t *testing.T) { + authDir := t.TempDir() + emailFileName := xai.CredentialFileName("a+b@example.com", "sub-first") + emailPath := filepath.Join(authDir, emailFileName) + + existing := map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "old-token", + "refresh_token": "old-refresh", + "prefix": "team", + "weight": float64(5), + } + raw, errMarshal := json.Marshal(existing) + if errMarshal != nil { + t.Fatalf("marshal canonical credential: %v", errMarshal) + } + if errWrite := os.WriteFile(emailPath, raw, 0o600); errWrite != nil { + t.Fatalf("write canonical credential: %v", errWrite) + } + + // The upstream stops returning an email, so the record is named after + // the subject; its identity keys omit the missing email. + tokenStorage := &xai.TokenStorage{ + AccessToken: "new-token", + RefreshToken: "new-refresh", + Subject: "sub-first", + Expire: "2026-12-31T23:59:59Z", + } + subjectFileName := xai.CredentialFileName("", tokenStorage.Subject) + record := &coreauth.Auth{ + ID: subjectFileName, + Provider: "xai", + FileName: subjectFileName, + Storage: tokenStorage, + Metadata: map[string]any{ + "sub": tokenStorage.Subject, + }, + } + + h := NewHandler(&config.Config{AuthDir: authDir}, "", nil) + savedPath, errSave := h.saveTokenRecord(context.Background(), record) + if errSave != nil { + t.Fatalf("saveTokenRecord error: %v", errSave) + } + if savedPath != emailPath { + t.Fatalf("savedPath = %s, want canonical email credential %s", savedPath, emailPath) + } + savedRaw, errRead := os.ReadFile(emailPath) + if errRead != nil { + t.Fatalf("read canonical credential: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal canonical credential: %v", errUnmarshal) + } + if saved["access_token"] != "new-token" || saved["prefix"] != "team" || saved["weight"] != float64(5) || saved["email"] != "a+b@example.com" { + t.Fatalf("saved credential = %#v, want new token with preserved settings and email", saved) + } + entries, errReadDir := os.ReadDir(authDir) + if errReadDir != nil { + t.Fatalf("ReadDir error: %v", errReadDir) + } + if len(entries) != 1 { + t.Fatalf("auth dir holds %d files, want the single canonical credential", len(entries)) + } +} + func TestPatchAuthFileFields_DeletesPluginFields(t *testing.T) { gin.SetMode(gin.TestMode) authDir := t.TempDir() diff --git a/internal/auth/xai/filename.go b/internal/auth/xai/filename.go new file mode 100644 index 0000000000..c1b6f96d8e --- /dev/null +++ b/internal/auth/xai/filename.go @@ -0,0 +1,219 @@ +package xai + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +// CredentialFileName returns the filename used to persist xAI OAuth credentials. +// It keeps a readable account name and appends a hash of the original identity +// so distinct emails that sanitize identically cannot overwrite each other. +func CredentialFileName(email, subject string) string { + cleanEmail := strings.TrimSpace(email) + if cleanEmail != "" { + // Emails are case-insensitive, so normalize case to keep the same + // account on the same file regardless of the case returned upstream. + // The hash covers the normalized email only so the filename stays + // stable even when a later login stops returning a subject. + normalizedEmail := strings.ToLower(cleanEmail) + sanitized := sanitizeFileSegment(normalizedEmail) + if sanitized == "" { + sanitized = "account" + } + // Leave room for the prefix, identity hash and extension on common filesystems. + if len(sanitized) > 120 { + sanitized = sanitized[:120] + } + digest := sha256.Sum256([]byte("email\x00" + normalizedEmail)) + return fmt.Sprintf("xai-%s-%s.json", sanitized, hex.EncodeToString(digest[:8])) + } + cleanSubject := strings.TrimSpace(subject) + if cleanSubject != "" { + sanitized := sanitizeFileSegment(cleanSubject) + if sanitized == "" { + sanitized = "account" + } + if len(sanitized) > 120 { + sanitized = sanitized[:120] + } + digest := sha256.Sum256([]byte("subject\x00" + cleanSubject)) + return fmt.Sprintf("xai-%s-%s.json", sanitized, hex.EncodeToString(digest[:8])) + } + return fmt.Sprintf("xai-%d.json", time.Now().UnixMilli()) +} + +func sanitizeFileSegment(value string) string { + value = strings.TrimSpace(value) + if value == "" { + return "" + } + var b strings.Builder + for _, r := range value { + switch { + case r >= 'a' && r <= 'z': + b.WriteRune(r) + case r >= 'A' && r <= 'Z': + b.WriteRune(r) + case r >= '0' && r <= '9': + b.WriteRune(r) + case r == '@' || r == '.' || r == '_' || r == '-': + b.WriteRune(r) + default: + b.WriteRune('-') + } + } + return strings.Trim(b.String(), "-") +} + +// legacyCredentialFileName reconstructs the pre-hash filename format so a +// credential saved before the hash suffix was introduced can be migrated. +func legacyCredentialFileName(email, subject string) string { + if sanitized := sanitizeFileSegment(email); sanitized != "" { + return fmt.Sprintf("xai-%s.json", sanitized) + } + if sanitized := sanitizeFileSegment(subject); sanitized != "" { + return fmt.Sprintf("xai-%s.json", sanitized) + } + return "" +} + +// FindMatchingLegacyCredential locates a prior filename for the same xAI +// identity as target. A candidate's recognized names are derived from every +// subset of its stored identity, covering the pre-hash format as well as +// hashed names from logins that saw only the email or only the subject. +// The target's own canonical filename is never a predecessor, so an ordinary +// re-login does not match the destination file itself. A legacy filename +// alone is ambiguous because distinct accounts could sanitize to it, so a +// candidate is only returned when its stored identity affirmatively matches +// the target identity. +func FindMatchingLegacyCredential(ctx context.Context, store coreauth.Store, target *coreauth.Auth) (*coreauth.Auth, error) { + if store == nil || !isHashedCredentialTarget(target) { + return nil, nil + } + + records, errList := store.List(ctx) + if errList != nil { + if errors.Is(errList, os.ErrNotExist) { + return nil, nil + } + return nil, fmt.Errorf("list xAI credentials for legacy migration: %w", errList) + } + + targetEmail := metadataString(target.Metadata, "email") + targetSubject := metadataString(target.Metadata, "sub") + // A nonempty identity always yields a hashed filename even when the + // pre-hash sanitization would have produced an empty segment, so do not + // require a legacy name here; isHashedCredentialTarget already verified + // that at least one identity field is present. + targetFileName := strings.TrimSpace(target.FileName) + if targetFileName == "" { + targetFileName = strings.TrimSpace(target.ID) + } + targetBaseName := filepath.Base(targetFileName) + + for _, candidate := range records { + if candidate == nil || !strings.EqualFold(strings.TrimSpace(candidate.Provider), "xai") { + continue + } + if !identityMatches(targetEmail, targetSubject, candidate) { + continue + } + candidateFileName := strings.TrimSpace(candidate.FileName) + if candidateFileName == "" { + candidateFileName = strings.TrimSpace(candidate.ID) + } + candidateBaseName := filepath.Base(candidateFileName) + // Only root-level generated files participate in migration. Login + // always writes flat names, and a nested relative ID would not + // resolve against the auth directory on cleanup. + if candidateBaseName != candidateFileName { + continue + } + // Never match the destination file itself: callers delete the returned + // predecessor after saving, which would erase the fresh credential. + if strings.EqualFold(candidateBaseName, targetBaseName) { + continue + } + candidateEmail := metadataString(candidate.Metadata, "email") + candidateSubject := metadataString(candidate.Metadata, "sub") + if isRecognizedPredecessor(candidateBaseName, candidateEmail, candidateSubject) { + return candidate, nil + } + } + + return nil, nil +} + +// isRecognizedPredecessor reports whether baseName is a filename the login +// flow itself would have produced from some subset of the stored identity: +// the pre-hash name, or a hashed name derived from either identity field. +// A file named when only the subject was known stays recognizable after a +// later login backfills the email into its stored metadata. +func isRecognizedPredecessor(baseName, email, subject string) bool { + if email == "" && subject == "" { + return false + } + if strings.EqualFold(baseName, CredentialFileName(email, subject)) { + return true + } + if email != "" && strings.EqualFold(baseName, CredentialFileName(email, "")) { + return true + } + if subject != "" && strings.EqualFold(baseName, CredentialFileName("", subject)) { + return true + } + if legacyName := legacyCredentialFileName(email, subject); legacyName != "" && strings.EqualFold(baseName, legacyName) { + return true + } + if subject != "" { + if legacyName := legacyCredentialFileName("", subject); legacyName != "" && strings.EqualFold(baseName, legacyName) { + return true + } + } + return false +} + +func isHashedCredentialTarget(target *coreauth.Auth) bool { + if target == nil || !strings.EqualFold(strings.TrimSpace(target.Provider), "xai") { + return false + } + email := metadataString(target.Metadata, "email") + subject := metadataString(target.Metadata, "sub") + if email == "" && subject == "" { + return false + } + targetFileName := strings.TrimSpace(target.FileName) + if targetFileName == "" { + targetFileName = strings.TrimSpace(target.ID) + } + return strings.EqualFold(filepath.Base(targetFileName), CredentialFileName(email, subject)) +} + +// identityMatches reports whether a candidate credential is provably the +// same account as the target: at least one stored identity field must match +// affirmatively and no stored identity field may conflict. Emails compare +// case-insensitively; subjects are case-sensitive identifiers and must match +// exactly. +func identityMatches(targetEmail, targetSubject string, candidate *coreauth.Auth) bool { + candidateEmail := metadataString(candidate.Metadata, "email") + candidateSubject := metadataString(candidate.Metadata, "sub") + emailMatches := targetEmail != "" && candidateEmail != "" && strings.EqualFold(targetEmail, candidateEmail) + emailConflicts := targetEmail != "" && candidateEmail != "" && !strings.EqualFold(targetEmail, candidateEmail) + subjectMatches := targetSubject != "" && candidateSubject != "" && targetSubject == candidateSubject + subjectConflicts := targetSubject != "" && candidateSubject != "" && targetSubject != candidateSubject + return (emailMatches || subjectMatches) && !emailConflicts && !subjectConflicts +} + +func metadataString(metadata map[string]any, key string) string { + value, _ := metadata[key].(string) + return strings.TrimSpace(value) +} diff --git a/internal/auth/xai/filename_test.go b/internal/auth/xai/filename_test.go new file mode 100644 index 0000000000..4f16afe636 --- /dev/null +++ b/internal/auth/xai/filename_test.go @@ -0,0 +1,273 @@ +package xai + +import ( + "context" + "path/filepath" + "strings" + "testing" + + coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +type credentialListStore struct { + records []*coreauth.Auth +} + +func (s *credentialListStore) List(context.Context) ([]*coreauth.Auth, error) { + return s.records, nil +} + +func (*credentialListStore) Save(context.Context, *coreauth.Auth) (string, error) { + panic("unexpected Save call") +} + +func (*credentialListStore) Delete(context.Context, string) error { + panic("unexpected Delete call") +} + +func TestCredentialFileNameSeparatesCollidingEmails(t *testing.T) { + plus := CredentialFileName("a+b@example.com", "sub-first") + hyphen := CredentialFileName("a-b@example.com", "sub-second") + if plus == hyphen { + t.Fatalf("CredentialFileName(a+b@example.com) = %q collides with CredentialFileName(a-b@example.com)", plus) + } + for _, name := range []string{plus, hyphen} { + if !strings.HasPrefix(name, "xai-") || !strings.HasSuffix(name, ".json") || !filepath.IsLocal(name) { + t.Fatalf("CredentialFileName() = %q, want local xai-*.json filename", name) + } + } +} + +func TestCredentialFileNameStableForSameAccount(t *testing.T) { + first := CredentialFileName("User+Work@example.com", "sub-1") + second := CredentialFileName(" user+work@example.com ", "sub-1") + if first != second { + t.Fatalf("re-login changed account file: %q != %q", first, second) + } +} + +func TestCredentialFileNameStableWhenSubjectAvailabilityChanges(t *testing.T) { + withoutSubject := CredentialFileName("user@example.com", "") + withSubject := CredentialFileName("user@example.com", "sub-1") + if withoutSubject != withSubject { + t.Fatalf("subject availability changed account file: %q != %q", withoutSubject, withSubject) + } +} + +func TestCredentialFileNameSeparatesSubjects(t *testing.T) { + if got := CredentialFileName("", "sub one"); got == CredentialFileName("", "sub-one") { + t.Fatalf("subject-only filenames collide: %q", got) + } +} + +func TestCredentialFileNameLongEmailFitsFilesystem(t *testing.T) { + name := CredentialFileName(strings.Repeat("a", 300)+"@example.com", "sub-1") + if len(name) > 255 || !filepath.IsLocal(name) { + t.Fatalf("filename %q (len %d) cannot be saved on common filesystems", name, len(name)) + } + shortTail := CredentialFileName(strings.Repeat("a", 300)+"b@example.com", "sub-1") + if name == shortTail { + t.Fatalf("long emails differing past truncation point collide: %q", name) + } +} + +func TestFindMatchingLegacyCredential(t *testing.T) { + const collidingLegacyFileName = "xai-a-b@example.com.json" + + tests := []struct { + name string + targetEmail string + targetSubject string + legacyEmail string + legacySubject string + // legacyFileName overrides the default colliding legacy filename so a + // fixture can carry the exact predecessor name it claims to exercise. + legacyFileName string + wantMatch bool + }{ + { + name: "same account migrates from legacy filename", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + legacyFileName: collidingLegacyFileName, + wantMatch: true, + }, + { + name: "colliding account does not claim the other account file", + targetEmail: "a-b@example.com", + targetSubject: "sub-second", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + legacyFileName: collidingLegacyFileName, + }, + { + name: "conflicting subject blocks migration", + targetEmail: "a+b@example.com", + targetSubject: "sub-other", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + legacyFileName: collidingLegacyFileName, + }, + { + name: "conflicting email blocks migration", + targetEmail: "a-b@example.com", + targetSubject: "sub-shared", + legacyEmail: "a+b@example.com", + legacySubject: "sub-shared", + legacyFileName: collidingLegacyFileName, + }, + { + name: "matching email with missing stored subject migrates", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacyFileName: collidingLegacyFileName, + wantMatch: true, + }, + { + name: "legacy file without stored identity stays unclaimed", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyFileName: collidingLegacyFileName, + }, + { + name: "disjoint identity fields stay unclaimed", + targetEmail: "a+b@example.com", + legacySubject: "sub-first", + legacyFileName: "xai-sub-first.json", + }, + { + name: "matching subject migrates from pre-hash subject filename", + targetSubject: "sub-first", + legacySubject: "sub-first", + legacyFileName: "xai-sub-first.json", + wantMatch: true, + }, + { + name: "pre-hash subject filename differing only by case stays unclaimed", + targetSubject: "abc", + legacySubject: "ABC", + legacyFileName: "xai-ABC.json", + }, + { + name: "email gained later migrates hashed subject-only predecessor", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacySubject: "sub-first", + wantMatch: true, + }, + { + name: "email gained later migrates pre-hash subject-only predecessor", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacySubject: "sub-first", + legacyFileName: "xai-sub-first.json", + wantMatch: true, + }, + { + name: "email lost later selects email-hashed predecessor", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + wantMatch: true, + }, + { + name: "canonical destination file is not its own predecessor", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + // Default fixture name is the hashed name, identical to the + // target's own destination on an ordinary re-login. + }, + { + name: "custom-named credential is never claimed", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + // Same stored identity, but the file was renamed or imported; + // migration must not merge or delete a file it does not own. + legacyFileName: "my-xai.json", + }, + { + name: "subject-named file with backfilled email stays reconcilable", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + // Hashed subject-only name; the stored identity gained the email + // when an earlier migration merged it into this file. + legacyFileName: CredentialFileName("", "sub-first"), + wantMatch: true, + }, + { + name: "pre-hash subject-named file with backfilled email stays reconcilable", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + legacyFileName: "xai-sub-first.json", + wantMatch: true, + }, + { + name: "subject-only file named by foreign identity stays unclaimed", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + // The filename was derived from a different subject than the stored + // identity, so the file is not one the login flow produced for it. + legacyFileName: CredentialFileName("", "sub-other"), + }, + { + name: "nested credential is never claimed", + targetEmail: "a+b@example.com", + targetSubject: "sub-first", + legacyEmail: "a+b@example.com", + legacySubject: "sub-first", + legacyFileName: "team/" + collidingLegacyFileName, + }, + { + name: "unsanitizable subject still reconciles by identity", + targetSubject: "+++", + legacyEmail: "a+b@example.com", + legacySubject: "+++", + wantMatch: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + targetFileName := CredentialFileName(tt.targetEmail, tt.targetSubject) + target := &coreauth.Auth{ + ID: targetFileName, + FileName: targetFileName, + Provider: "xai", + Metadata: map[string]any{"email": tt.targetEmail, "sub": tt.targetSubject}, + } + legacyFileName := tt.legacyFileName + if legacyFileName == "" { + // Default to the predecessor filename the stored identity itself + // would have produced; fixtures that need the ambiguous + // colliding name set legacyFileName explicitly. + legacyFileName = CredentialFileName(tt.legacyEmail, tt.legacySubject) + } + legacy := &coreauth.Auth{ + ID: legacyFileName, + FileName: legacyFileName, + Provider: "xai", + Metadata: map[string]any{"email": tt.legacyEmail, "sub": tt.legacySubject}, + } + got, err := FindMatchingLegacyCredential(context.Background(), &credentialListStore{records: []*coreauth.Auth{legacy}}, target) + if err != nil { + t.Fatalf("FindMatchingLegacyCredential() error = %v", err) + } + if (got != nil) != tt.wantMatch { + t.Fatalf("FindMatchingLegacyCredential() match = %v, want %v", got != nil, tt.wantMatch) + } + }) + } +} diff --git a/internal/auth/xai/token.go b/internal/auth/xai/token.go index 100d3322a9..6fe82cec90 100644 --- a/internal/auth/xai/token.go +++ b/internal/auth/xai/token.go @@ -5,8 +5,6 @@ import ( "fmt" "os" "path/filepath" - "strings" - "time" "github.com/router-for-me/CLIProxyAPI/v8/internal/misc" log "github.com/sirupsen/logrus" @@ -68,39 +66,3 @@ func (ts *TokenStorage) SaveTokenToFile(authFilePath string) error { } return nil } - -// CredentialFileName returns the filename used for xAI credentials. -func CredentialFileName(email, subject string) string { - email = sanitizeFileSegment(email) - if email != "" { - return fmt.Sprintf("xai-%s.json", email) - } - subject = sanitizeFileSegment(subject) - if subject != "" { - return fmt.Sprintf("xai-%s.json", subject) - } - return fmt.Sprintf("xai-%d.json", time.Now().UnixMilli()) -} - -func sanitizeFileSegment(value string) string { - value = strings.TrimSpace(value) - if value == "" { - return "" - } - var b strings.Builder - for _, r := range value { - switch { - case r >= 'a' && r <= 'z': - b.WriteRune(r) - case r >= 'A' && r <= 'Z': - b.WriteRune(r) - case r >= '0' && r <= '9': - b.WriteRune(r) - case r == '@' || r == '.' || r == '_' || r == '-': - b.WriteRune(r) - default: - b.WriteRune('-') - } - } - return strings.Trim(b.String(), "-") -} diff --git a/internal/store/xai_filename_adoption_test.go b/internal/store/xai_filename_adoption_test.go new file mode 100644 index 0000000000..31e2f662fa --- /dev/null +++ b/internal/store/xai_filename_adoption_test.go @@ -0,0 +1,167 @@ +package store + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + git "github.com/go-git/go-git/v6" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" +) + +// TestFileNameStoresExposeBaseDirCapability pins the capability marker the +// login flows use to decide whether renaming onto a richer credential file +// is safe: every built-in backend resolves the save path from the record +// name and must keep exposing SetBaseDir. +func TestFileNameStoresExposeBaseDirCapability(t *testing.T) { + stores := map[string]cliproxyauth.Store{ + "git": &GitTokenStore{}, + "postgres": &PostgresStore{}, + "object": &ObjectTokenStore{}, + } + for name, store := range stores { + if _, ok := store.(interface{ SetBaseDir(string) }); !ok { + t.Errorf("%s store does not expose SetBaseDir; xAI filename adoption would be disabled for it", name) + } + } +} + +// TestGitTokenStoreSaveResolvesFromRecordFileName proves the behavior the +// adoption rename relies on outside FileTokenStore: when a record's name is +// changed before Save, the new file lands at the adopted (email) name and +// not at the superseded (subject) name it carried before the rename. +func TestGitTokenStoreSaveResolvesFromRecordFileName(t *testing.T) { + root := t.TempDir() + remoteDir := filepath.Join(root, "remote.git") + if _, errInit := git.PlainInit(remoteDir, true); errInit != nil { + t.Fatalf("PlainInit error: %v", errInit) + } + store := NewGitTokenStore(remoteDir, "", "", "") + authDir := filepath.Join(root, "work", "auths") + store.SetBaseDir(authDir) + if errEnsure := store.EnsureRepository(); errEnsure != nil { + t.Fatalf("EnsureRepository error: %v", errEnsure) + } + + const emailFileName = "xai-user@example.com-0123456789abcdef.json" + const subjectFileName = "xai-sub-1-fedcba9876543210.json" + record := &cliproxyauth.Auth{ + ID: subjectFileName, + FileName: subjectFileName, + Provider: "xai", + Metadata: map[string]any{ + "type": "xai", + "sub": "sub-1", + "access_token": "token-1", + }, + } + // Simulate the login-flow adoption rename onto the richer email file. + record.ID = emailFileName + record.FileName = emailFileName + record.Metadata["email"] = "user@example.com" + + savedPath, errSave := store.Save(context.Background(), record) + if errSave != nil { + t.Fatalf("Save error: %v", errSave) + } + if want := filepath.Join(authDir, emailFileName); savedPath != want { + t.Fatalf("savedPath = %s, want adopted email path %s", savedPath, want) + } + if _, errStat := os.Stat(savedPath); errStat != nil { + t.Fatalf("saved credential missing at %s: %v", savedPath, errStat) + } + if _, errStat := os.Stat(filepath.Join(authDir, subjectFileName)); !os.IsNotExist(errStat) { + t.Fatalf("superseded subject file should not exist: %v", errStat) + } +} + +// TestRemoteStoresSaveResolvesFromRecordFileName proves the same rename +// behavior for the Postgres and object backends: the remote key follows the +// resolved local path, so an adopted email filename is what reaches the +// remote store. +func TestRemoteStoresSaveResolvesFromRecordFileName(t *testing.T) { + const emailFileName = "xai-user@example.com-0123456789abcdef.json" + const subjectFileName = "xai-sub-1-fedcba9876543210.json" + + tests := []struct { + name string + build func(authDir string, onRemoteWrite func(id string, data []byte) error) cliproxyauth.Store + wantRemoteID string + }{ + { + name: "postgres", + build: func(authDir string, onRemoteWrite func(id string, data []byte) error) cliproxyauth.Store { + return &PostgresStore{ + authDir: authDir, + cfg: PostgresStoreConfig{AuthTable: "auth_tokens"}, + persistAuthFn: func(_ context.Context, relID string, data []byte) error { + return onRemoteWrite(relID, data) + }, + } + }, + wantRemoteID: emailFileName, + }, + { + name: "object", + build: func(authDir string, onRemoteWrite func(id string, data []byte) error) cliproxyauth.Store { + return &ObjectTokenStore{ + authDir: authDir, + cfg: ObjectStoreConfig{Bucket: "bucket"}, + putObjectFn: func(_ context.Context, key string, data []byte, _ string) error { + return onRemoteWrite(key, data) + }, + } + }, + wantRemoteID: "auths/" + emailFileName, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + authDir := filepath.Join(t.TempDir(), "auths") + if errMkdir := os.MkdirAll(authDir, 0o700); errMkdir != nil { + t.Fatal(errMkdir) + } + remoteSaved := make(map[string]string) + store := tt.build(authDir, func(id string, data []byte) error { + remoteSaved[id] = string(data) + return nil + }) + + record := &cliproxyauth.Auth{ + ID: subjectFileName, + FileName: subjectFileName, + Provider: "xai", + Metadata: map[string]any{ + "type": "xai", + "sub": "sub-1", + "access_token": "token-1", + }, + } + // Simulate the login-flow adoption rename onto the email file. + record.ID = emailFileName + record.FileName = emailFileName + record.Metadata["email"] = "user@example.com" + + savedPath, errSave := store.Save(context.Background(), record) + if errSave != nil { + t.Fatalf("Save error: %v", errSave) + } + if want := filepath.Join(authDir, emailFileName); savedPath != want { + t.Fatalf("savedPath = %s, want adopted email path %s", savedPath, want) + } + remotePayload, ok := remoteSaved[tt.wantRemoteID] + if !ok { + t.Fatalf("remote records = %v, want key %q", remoteSaved, tt.wantRemoteID) + } + if !strings.Contains(remotePayload, `"access_token":"token-1"`) { + t.Fatalf("remote payload = %s, want refreshed token", remotePayload) + } + if _, errStat := os.Stat(filepath.Join(authDir, subjectFileName)); !os.IsNotExist(errStat) { + t.Fatalf("superseded subject file should not exist: %v", errStat) + } + }) + } +} diff --git a/sdk/auth/manager.go b/sdk/auth/manager.go index 403426a8bd..4cbefd98e8 100644 --- a/sdk/auth/manager.go +++ b/sdk/auth/manager.go @@ -9,6 +9,7 @@ import ( "strings" claudeauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude" + xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" ) @@ -94,6 +95,38 @@ func (m *Manager) Login(ctx context.Context, provider string, cfg *config.Config if legacyClaudeCredential != nil { coreauth.MergeExistingAuthMetadata(record, legacyClaudeCredential.Metadata) } + legacyXAICredential, errLegacyXAI := xaiauth.FindMatchingLegacyCredential(ctx, m.store, record) + if errLegacyXAI != nil { + return record, "", errLegacyXAI + } + adoptXAICredential := legacyXAICredential != nil && record != nil && + strings.EqualFold(strings.TrimSpace(record.Provider), "xai") && + metadataStringValue(record.Metadata, "email") == "" && + metadataStringValue(record.Metadata, "sub") != "" && + metadataStringValue(legacyXAICredential.Metadata, "email") != "" + if adoptXAICredential { + // The upstream stopped returning the email; keep the account on its + // richer email-named credential (richest-known name wins) so the next + // login that returns the email finds the same file again. Renaming is + // limited to stores that resolve the save path from the record name; + // every built-in backend (file, git, Postgres, object) exposes the + // SetBaseDir capability, so unknown stores keep the ordinary + // migration instead of risking a rename they cannot honor. + if _, isFileNameStore := m.store.(interface{ SetBaseDir(string) }); !isFileNameStore { + adoptXAICredential = false + } else if disabled, hasDisabled := record.Metadata["disabled"].(bool); hasDisabled && disabled { + // The destination file deliberately disables this credential; renaming + // would leave it disabled while the richer file gets deleted, losing + // the operator's opt-out and the saved credential on re-login. + adoptXAICredential = false + } + } + if legacyXAICredential != nil { + coreauth.MergeExistingAuthMetadata(record, legacyXAICredential.Metadata) + } + if adoptXAICredential { + adoptLegacyXAIFileName(record, legacyXAICredential) + } savedPath, err := m.store.Save(coreauth.WithAuthCreationIntent(ctx), record) if err != nil { @@ -111,5 +144,54 @@ func (m *Manager) Login(ctx context.Context, provider string, cfg *config.Config return record, savedPath, fmt.Errorf("cliproxy auth: canonical Claude credential saved but legacy credential cleanup failed: %w", errDelete) } } + if legacyXAICredential != nil && !adoptXAICredential { + if strings.TrimSpace(savedPath) == "" { + return record, "", fmt.Errorf("cliproxy auth: canonical xAI credential was not persisted; legacy credential retained") + } + legacyID := strings.TrimSpace(legacyXAICredential.ID) + if legacyID == "" { + legacyID = strings.TrimSpace(legacyXAICredential.FileName) + } + if errDelete := m.store.Delete(ctx, legacyID); errDelete != nil { + return record, savedPath, fmt.Errorf("cliproxy auth: canonical xAI credential saved but legacy credential cleanup failed: %w", errDelete) + } + } return record, savedPath, nil } + +func metadataStringValue(metadata map[string]any, key string) string { + value, _ := metadata[key].(string) + return strings.TrimSpace(value) +} + +// adoptLegacyXAIFileName points a subject-only xAI record at the existing +// email-named credential so the save refreshes that file in place. The token +// storage email is backfilled because SaveTokenToFile merges the record +// metadata over the serialized storage and would otherwise drop the email. +// Path attributes pointing at the superseded subject-named file are cleared +// so the store resolves the adopted name. +func adoptLegacyXAIFileName(record, legacy *coreauth.Auth) { + legacyFileName := strings.TrimSpace(legacy.FileName) + if legacyFileName == "" { + legacyFileName = strings.TrimSpace(legacy.ID) + } + if legacyFileName == "" { + return + } + oldBaseName := filepath.Base(strings.TrimSpace(record.FileName)) + if oldBaseName == "" || oldBaseName == "." { + oldBaseName = filepath.Base(strings.TrimSpace(record.ID)) + } + record.ID = legacyFileName + record.FileName = legacyFileName + if storage, ok := record.Storage.(*xaiauth.TokenStorage); ok && storage != nil { + if email := metadataStringValue(legacy.Metadata, "email"); email != "" { + storage.Email = email + } + } + for key, value := range record.Attributes { + if strings.TrimSpace(value) != "" && strings.EqualFold(filepath.Base(strings.TrimSpace(value)), oldBaseName) { + delete(record.Attributes, key) + } + } +} diff --git a/sdk/auth/manager_test.go b/sdk/auth/manager_test.go index 21cf6b358a..5c42d114f3 100644 --- a/sdk/auth/manager_test.go +++ b/sdk/auth/manager_test.go @@ -9,6 +9,7 @@ import ( "time" claudeauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude" + xaiauth "github.com/router-for-me/CLIProxyAPI/v8/internal/auth/xai" "github.com/router-for-me/CLIProxyAPI/v8/internal/config" coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" ) @@ -193,6 +194,185 @@ func TestManagerLogin_MigratesMatchingLegacyClaudeCredential(t *testing.T) { } } +func TestManagerLogin_ReloginKeepsCanonicalXAICredential(t *testing.T) { + authDir := t.TempDir() + targetFileName := xaiauth.CredentialFileName("a+b@example.com", "sub-first") + targetPath := filepath.Join(authDir, targetFileName) + + existing := map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "old-token", + "prefix": "team", + } + raw, errMarshal := json.Marshal(existing) + if errMarshal != nil { + t.Fatalf("marshal canonical credential: %v", errMarshal) + } + if errWrite := os.WriteFile(targetPath, raw, 0o600); errWrite != nil { + t.Fatalf("write canonical credential: %v", errWrite) + } + + newRecord := &coreauth.Auth{ + ID: targetFileName, + FileName: targetFileName, + Provider: "xai", + Storage: &xaiauth.TokenStorage{ + Type: "xai", + Email: "a+b@example.com", + Subject: "sub-first", + AccessToken: "new-token", + }, + Metadata: map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "new-token", + }, + } + + store := NewFileTokenStore() + store.SetBaseDir(authDir) + mgr := NewManager(store, &dummyAuthenticator{provider: "xai", record: newRecord}) + + _, savedPath, errLogin := mgr.Login(context.Background(), "xai", &config.Config{AuthDir: authDir}, nil) + if errLogin != nil { + t.Fatalf("Login error: %v", errLogin) + } + if savedPath != targetPath { + t.Fatalf("savedPath = %s, want %s", savedPath, targetPath) + } + savedRaw, errRead := os.ReadFile(targetPath) + if errRead != nil { + t.Fatalf("canonical credential was deleted by re-login: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal canonical credential: %v", errUnmarshal) + } + if saved["access_token"] != "new-token" || saved["prefix"] != "team" { + t.Fatalf("saved credential = %#v, want new token with preserved prefix", saved) + } +} + +func TestManagerLogin_SubjectOnlyReloginKeepsEmailCredential(t *testing.T) { + authDir := t.TempDir() + emailFileName := xaiauth.CredentialFileName("a+b@example.com", "sub-first") + emailPath := filepath.Join(authDir, emailFileName) + + existing := map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "old-token", + "prefix": "team", + "weight": float64(5), + } + raw, errMarshal := json.Marshal(existing) + if errMarshal != nil { + t.Fatalf("marshal canonical credential: %v", errMarshal) + } + if errWrite := os.WriteFile(emailPath, raw, 0o600); errWrite != nil { + t.Fatalf("write canonical credential: %v", errWrite) + } + + // The upstream stops returning an email, so the authenticator names the + // record after the subject; its identity keys omit the missing email. + subjectFileName := xaiauth.CredentialFileName("", "sub-first") + newRecord := &coreauth.Auth{ + ID: subjectFileName, + FileName: subjectFileName, + Provider: "xai", + Storage: &xaiauth.TokenStorage{ + Type: "xai", + Subject: "sub-first", + AccessToken: "new-token", + }, + Metadata: map[string]any{ + "type": "xai", + "sub": "sub-first", + "access_token": "new-token", + }, + } + + store := NewFileTokenStore() + store.SetBaseDir(authDir) + mgr := NewManager(store, &dummyAuthenticator{provider: "xai", record: newRecord}) + + _, savedPath, errLogin := mgr.Login(context.Background(), "xai", &config.Config{AuthDir: authDir}, nil) + if errLogin != nil { + t.Fatalf("Login error: %v", errLogin) + } + if savedPath != emailPath { + t.Fatalf("savedPath = %s, want canonical email credential %s", savedPath, emailPath) + } + savedRaw, errRead := os.ReadFile(emailPath) + if errRead != nil { + t.Fatalf("read canonical credential: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal canonical credential: %v", errUnmarshal) + } + if saved["access_token"] != "new-token" || saved["prefix"] != "team" || saved["weight"] != float64(5) || saved["email"] != "a+b@example.com" { + t.Fatalf("saved credential = %#v, want new token with preserved settings and email", saved) + } + entries, errReadDir := os.ReadDir(authDir) + if errReadDir != nil { + t.Fatalf("ReadDir error: %v", errReadDir) + } + if len(entries) != 1 { + t.Fatalf("auth dir holds %d files, want the single canonical credential", len(entries)) + } + + // Return leg: the upstream returns the email again, and that login must + // land on the same canonical file with settings intact, completing the + // email+subject -> subject-only -> email+subject round trip. + returnRecord := &coreauth.Auth{ + ID: emailFileName, + FileName: emailFileName, + Provider: "xai", + Storage: &xaiauth.TokenStorage{ + Type: "xai", + Email: "a+b@example.com", + Subject: "sub-first", + AccessToken: "round-trip-token", + }, + Metadata: map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "round-trip-token", + }, + } + returnMgr := NewManager(store, &dummyAuthenticator{provider: "xai", record: returnRecord}) + _, savedPath, errLogin = returnMgr.Login(context.Background(), "xai", &config.Config{AuthDir: authDir}, nil) + if errLogin != nil { + t.Fatalf("return Login error: %v", errLogin) + } + if savedPath != emailPath { + t.Fatalf("return savedPath = %s, want canonical email credential %s", savedPath, emailPath) + } + savedRaw, errRead = os.ReadFile(emailPath) + if errRead != nil { + t.Fatalf("read round-trip credential: %v", errRead) + } + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal round-trip credential: %v", errUnmarshal) + } + if saved["access_token"] != "round-trip-token" || saved["prefix"] != "team" || saved["weight"] != float64(5) || saved["email"] != "a+b@example.com" { + t.Fatalf("round-trip credential = %#v, want newest token with preserved settings and email", saved) + } + entries, errReadDir = os.ReadDir(authDir) + if errReadDir != nil { + t.Fatalf("ReadDir error: %v", errReadDir) + } + if len(entries) != 1 { + t.Fatalf("auth dir holds %d files after round trip, want the single canonical credential", len(entries)) + } +} + func TestManagerLogin_DoesNotMigrateLegacyClaudeCredentialFromDifferentOrganization(t *testing.T) { authDir := t.TempDir() legacyFileName := "claude-user@example.com.json" @@ -315,3 +495,82 @@ func TestManagerLogin_MultipleOrganizationsSharingEmailCoexist(t *testing.T) { t.Fatalf("store.List returned %d records, want 2 distinct organization records", len(records)) } } + +func TestManagerLogin_MigratesMatchingLegacyXAICredential(t *testing.T) { + authDir := t.TempDir() + legacyFileName := "xai-a-b@example.com.json" + targetFileName := xaiauth.CredentialFileName("a+b@example.com", "sub-first") + legacyPath := filepath.Join(authDir, legacyFileName) + targetPath := filepath.Join(authDir, targetFileName) + + existing := map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "old-token", + "prefix": "team", + "proxy_url": "http://127.0.0.1:8080", + "disabled": true, + "weight": float64(5), + } + raw, errMarshal := json.Marshal(existing) + if errMarshal != nil { + t.Fatalf("marshal legacy credential: %v", errMarshal) + } + if errWrite := os.WriteFile(legacyPath, raw, 0o600); errWrite != nil { + t.Fatalf("write legacy credential: %v", errWrite) + } + + newRecord := &coreauth.Auth{ + ID: targetFileName, + FileName: targetFileName, + Provider: "xai", + Storage: &xaiauth.TokenStorage{ + Type: "xai", + Email: "a+b@example.com", + Subject: "sub-first", + AccessToken: "new-token", + }, + Metadata: map[string]any{ + "type": "xai", + "email": "a+b@example.com", + "sub": "sub-first", + "access_token": "new-token", + }, + } + + store := NewFileTokenStore() + store.SetBaseDir(authDir) + mgr := NewManager(store, &dummyAuthenticator{provider: "xai", record: newRecord}) + + _, savedPath, errLogin := mgr.Login(context.Background(), "xai", &config.Config{AuthDir: authDir}, nil) + if errLogin != nil { + t.Fatalf("Login error: %v", errLogin) + } + if savedPath != targetPath { + t.Fatalf("savedPath = %s, want %s", savedPath, targetPath) + } + if _, errStat := os.Stat(legacyPath); !os.IsNotExist(errStat) { + t.Fatalf("legacy credential still exists or stat failed: %v", errStat) + } + + savedRaw, errRead := os.ReadFile(targetPath) + if errRead != nil { + t.Fatalf("read migrated credential: %v", errRead) + } + var saved map[string]any + if errUnmarshal := json.Unmarshal(savedRaw, &saved); errUnmarshal != nil { + t.Fatalf("unmarshal migrated credential: %v", errUnmarshal) + } + for key, want := range map[string]any{ + "access_token": "new-token", + "prefix": "team", + "proxy_url": "http://127.0.0.1:8080", + "disabled": true, + "weight": float64(5), + } { + if got := saved[key]; got != want { + t.Errorf("%s = %#v, want %#v", key, got, want) + } + } +}