Files
pipelines/internal/claudeaccounts/store_test.go
T
alan c490f71042 Claude account switcher: save and switch a chat's Claude login in place
Saved accounts live under <CLAUDE_CONFIG_DIR>/pipelines-accounts/<slug>/
(0700 dir, 0600 files). Switching changes what /login changes: the
claudeAiOauth entry of .credentials.json and oauthAccount of .claude.json
(atomic temp+rename, mode and other keys kept) and the org caches /login
drops, under Claude Code's own refresh, storage and config locks, so
running CLIs continue on the new account without a restart. The active
login's rotated tokens are written back to its slot first.

Server: claude_accounts / claude_account_save / _use / _remove, chat-scoped
and Claude-only; a switch moves the home's open chats to the new account's
quota (usage.account.switched_at), clearing a reached limit.
CLI: pipelines claude-account list|save|use|remove [--dir].
App: Claude account in the chat menu, and Switch to <account> on the
usage-limit and usage-warning banners, with a confirmation snack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:10:08 +00:00

357 lines
12 KiB
Go

package claudeaccounts
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
)
// fakeLogin writes a login the way Claude Code's /login leaves it: tokens in
// .credentials.json (beside an MCP OAuth entry it must keep) and the account
// in .claude.json among unrelated keys.
func fakeLogin(t *testing.T, dir, who, uuid, token string) {
t.Helper()
creds := map[string]any{
"claudeAiOauth": map[string]any{
"accessToken": "access-" + token, "refreshToken": "refresh-" + token,
"expiresAt": 1, "scopes": []string{"user:inference"}, "subscriptionType": "max",
"accountUuid": uuid, "organizationUuid": "org-" + uuid,
},
"mcpOAuth": map[string]any{"server": map[string]any{"accessToken": "mcp-secret"}},
}
writeJSON(t, filepath.Join(dir, ".credentials.json"), creds, false)
config := map[string]any{}
if data, err := os.ReadFile(filepath.Join(dir, ".claude.json")); err == nil {
if err := json.Unmarshal(data, &config); err != nil {
t.Fatal(err)
}
} else {
config = map[string]any{"numStartups": 4, "projects": map[string]any{"/x": map[string]any{"allowedTools": []any{}}}, "userID": "device"}
}
config["oauthAccount"] = map[string]any{"accountUuid": uuid, "emailAddress": who, "organizationUuid": "org-" + uuid, "organizationName": "Org " + uuid}
writeJSON(t, filepath.Join(dir, ".claude.json"), config, true)
}
func writeJSON(t *testing.T, path string, v any, indent bool) {
t.Helper()
var data []byte
var err error
if indent {
data, err = json.MarshalIndent(v, "", " ")
} else {
data, err = json.Marshal(v)
}
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
}
func readJSON(t *testing.T, path string) map[string]any {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var out map[string]any
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("%s: %v", path, err)
}
return out
}
func activeRefresh(t *testing.T, dir string) string {
t.Helper()
return readJSON(t, filepath.Join(dir, ".credentials.json"))["claudeAiOauth"].(map[string]any)["refreshToken"].(string)
}
func scratch(t *testing.T) (Store, string) {
t.Helper()
dir := t.TempDir()
return Store{ConfigDir: dir}, dir
}
func noTokens(t *testing.T, v any) {
t.Helper()
data, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"access-", "refresh-", "mcp-secret", "accessToken", "refreshToken"} {
if strings.Contains(string(data), secret) {
t.Fatalf("reply carries %q: %s", secret, data)
}
}
}
func TestSaveUseRotateBackAndRemove(t *testing.T) {
store, dir := scratch(t)
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
list, err := store.Save("")
if err != nil {
t.Fatal(err)
}
noTokens(t, list)
if len(list.Accounts) != 1 || list.Accounts[0].Name != "a@example.invalid" || !list.Accounts[0].Active || list.Active == nil || !list.Active.Saved {
t.Fatalf("after save a: %+v", list)
}
// A terminal /login switches to b; it is the active, unsaved login.
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
list, err = store.List()
if err != nil {
t.Fatal(err)
}
if list.Active == nil || list.Active.Email != "b@example.invalid" || list.Active.Saved || list.Accounts[0].Active {
t.Fatalf("list with unsaved b: %+v", list)
}
if _, err := store.Save("Work B"); err != nil {
t.Fatal(err)
}
// b's tokens rotate on refresh while it is active.
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b2")
list, err = store.Use("a@example.invalid")
if err != nil {
t.Fatal(err)
}
noTokens(t, list)
if list.Active == nil || list.Active.Email != "a@example.invalid" || activeRefresh(t, dir) != "refresh-a1" {
t.Fatalf("after use a: %+v refresh=%s", list, activeRefresh(t, dir))
}
config := readJSON(t, filepath.Join(dir, ".claude.json"))
if config["oauthAccount"].(map[string]any)["emailAddress"] != "a@example.invalid" || config["userID"] != "device" || config["numStartups"].(float64) != 4 || config["projects"] == nil {
t.Fatalf("config after use = %v", config)
}
creds := readJSON(t, filepath.Join(dir, ".credentials.json"))
if creds["mcpOAuth"] == nil {
t.Fatalf("other credentials dropped: %v", creds)
}
// The rotated b2 tokens were written back to b's slot, so switching back
// installs them, not the stale b1.
if _, err := store.Use("work b"); err != nil {
t.Fatal(err)
}
if got := activeRefresh(t, dir); got != "refresh-b2" {
t.Fatalf("switched back to %s, want the rotated refresh-b2", got)
}
list, err = store.Remove("Work B")
if err != nil {
t.Fatal(err)
}
if len(list.Accounts) != 1 || list.Active == nil || list.Active.Email != "b@example.invalid" || list.Active.Saved {
t.Fatalf("after remove: %+v", list)
}
if _, err := os.Stat(filepath.Join(dir, SlotsDir, "work-b")); !os.IsNotExist(err) {
t.Fatalf("slot still present: %v", err)
}
}
func TestUseKeepsAnUnsavedLogin(t *testing.T) {
store, dir := scratch(t)
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
if _, err := store.Save("a"); err != nil {
t.Fatal(err)
}
// A terminal /login to c, never saved, then a switch back to a.
fakeLogin(t, dir, "c@example.invalid", "uuid-c", "c1")
list, err := store.Use("a")
if err != nil {
t.Fatal(err)
}
if len(list.Accounts) != 2 || list.Accounts[1].Email != "c@example.invalid" || list.Accounts[1].Active {
t.Fatalf("the unsaved login was not kept: %+v", list.Accounts)
}
if _, err := store.Use("c@example.invalid"); err != nil || activeRefresh(t, dir) != "refresh-c1" {
t.Fatalf("switch back to the kept login: %v", err)
}
}
func TestPermissionsCachesAndFormat(t *testing.T) {
old := syscall.Umask(0o022)
defer syscall.Umask(old)
store, dir := scratch(t)
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
if _, err := store.Save("a"); err != nil {
t.Fatal(err)
}
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
if err := os.Chmod(filepath.Join(dir, ".claude.json"), 0o640); err != nil {
t.Fatal(err)
}
for _, cache := range orgCaches {
writeJSON(t, filepath.Join(dir, cache), map[string]any{}, false)
}
keep := filepath.Join(dir, "settings.json")
writeJSON(t, keep, map[string]any{}, false)
before, _ := os.Stat(filepath.Join(dir, ".credentials.json"))
time.Sleep(10 * time.Millisecond)
if _, err := store.Use("a"); err != nil {
t.Fatal(err)
}
for path, want := range map[string]os.FileMode{
filepath.Join(dir, SlotsDir): 0o700,
filepath.Join(dir, SlotsDir, "a"): 0o700,
filepath.Join(dir, SlotsDir, "a", "credentials.json"): 0o600,
filepath.Join(dir, SlotsDir, "a", "account.json"): 0o600,
filepath.Join(dir, SlotsDir, "a", "slot.json"): 0o600,
filepath.Join(dir, ".credentials.json"): 0o600,
filepath.Join(dir, ".claude.json"): 0o640,
} {
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != want {
t.Fatalf("%s mode %v, want %v", path, info.Mode().Perm(), want)
}
}
after, _ := os.Stat(filepath.Join(dir, ".credentials.json"))
if !after.ModTime().After(before.ModTime()) {
t.Fatal("credentials mtime did not move; running Claude Code would not reload")
}
for _, cache := range orgCaches {
if _, err := os.Stat(filepath.Join(dir, cache)); !os.IsNotExist(err) {
t.Fatalf("%s kept after a switch", cache)
}
}
if _, err := os.Stat(keep); err != nil {
t.Fatal("an unrelated file was removed")
}
data, _ := os.ReadFile(filepath.Join(dir, ".claude.json"))
if !strings.HasPrefix(string(data), "{\n \"") {
t.Fatalf(".claude.json lost Claude Code's indentation: %.40q", data)
}
entries, _ := os.ReadDir(dir)
for _, entry := range entries {
if strings.Contains(entry.Name(), ".pipelines-") || strings.HasSuffix(entry.Name(), ".lock") {
t.Fatalf("left behind %s", entry.Name())
}
}
}
func TestClaudeJSONKeyOrderAndValuesKept(t *testing.T) {
store, dir := scratch(t)
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
if _, err := store.Save(""); err != nil {
t.Fatal(err)
}
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
raw := "{\n \"zeta\": 1,\n \"oauthAccount\": " + string(mustRead(t, filepath.Join(dir, ".claude.json"), "oauthAccount")) +
",\n \"alpha\": {\n \"big\": 12345678901234567890,\n \"html\": \"<a&b>\"\n }\n}"
if err := os.WriteFile(filepath.Join(dir, ".claude.json"), []byte(raw), 0o600); err != nil {
t.Fatal(err)
}
if _, err := store.Use("a@example.invalid"); err != nil {
t.Fatal(err)
}
got := string(mustReadFile(t, filepath.Join(dir, ".claude.json")))
if !(strings.Index(got, "zeta") < strings.Index(got, "oauthAccount") && strings.Index(got, "oauthAccount") < strings.Index(got, "alpha")) {
t.Fatalf("key order changed: %s", got)
}
if !strings.Contains(got, "12345678901234567890") || !strings.Contains(got, `"<a&b>"`) {
t.Fatalf("values rewritten: %s", got)
}
}
func mustReadFile(t *testing.T, path string) []byte {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return data
}
func mustRead(t *testing.T, path, key string) json.RawMessage {
t.Helper()
obj, err := parseObject(mustReadFile(t, path))
if err != nil {
t.Fatal(err)
}
return obj.get(key)
}
func TestRefusals(t *testing.T) {
store, dir := scratch(t)
if _, err := store.Save(""); err != ErrNoLogin {
t.Fatalf("save while signed out: %v", err)
}
if _, err := (Store{ConfigDir: "relative"}).List(); err == nil {
t.Fatal("a relative config dir was accepted")
}
if _, err := (Store{ConfigDir: filepath.Join(dir, "missing")}).List(); err == nil {
t.Fatal("a missing config dir was accepted")
}
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
if _, err := store.Use("nobody"); err == nil || !strings.Contains(err.Error(), "no saved Claude account") {
t.Fatalf("use unknown: %v", err)
}
if _, err := store.Save("!!!"); err == nil {
t.Fatal("an unusable name was accepted")
}
if _, err := store.Save("shared"); err != nil {
t.Fatal(err)
}
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
if _, err := store.Save("Shared"); err == nil || !strings.Contains(err.Error(), "already names") {
t.Fatalf("a name of another account was overwritten: %v", err)
}
// A credentials file that is a symlink is not replaced.
if _, err := store.Save("b"); err != nil {
t.Fatal(err)
}
real := filepath.Join(dir, "real-creds.json")
if err := os.Rename(filepath.Join(dir, ".credentials.json"), real); err != nil {
t.Fatal(err)
}
if err := os.Symlink(real, filepath.Join(dir, ".credentials.json")); err != nil {
t.Fatal(err)
}
before := mustReadFile(t, filepath.Join(dir, ".claude.json"))
if _, err := store.Use("shared"); err == nil {
t.Fatal("a symlinked credentials file was replaced")
}
if string(mustReadFile(t, filepath.Join(dir, ".claude.json"))) != string(before) {
t.Fatal(".claude.json was left naming the other account after a failed switch")
}
}
func TestUseWaitsForAClaudeRefreshLock(t *testing.T) {
defer func(old time.Duration) { lockWait = old }(lockWait)
lockWait = 200 * time.Millisecond
store, dir := scratch(t)
fakeLogin(t, dir, "a@example.invalid", "uuid-a", "a1")
if _, err := store.Save(""); err != nil {
t.Fatal(err)
}
fakeLogin(t, dir, "b@example.invalid", "uuid-b", "b1")
lock := filepath.Join(dir, ".oauth_refresh.lock")
if err := os.Mkdir(lock, 0o700); err != nil {
t.Fatal(err)
}
if _, err := store.Use("a@example.invalid"); err != errLocked {
t.Fatalf("use under a live refresh lock: %v", err)
}
if activeRefresh(t, dir) != "refresh-b1" {
t.Fatal("switched while Claude Code held the refresh lock")
}
// An abandoned lock is taken over.
old := time.Now().Add(-2 * time.Minute)
if err := os.Chtimes(lock, old, old); err != nil {
t.Fatal(err)
}
if _, err := store.Use("a@example.invalid"); err != nil {
t.Fatal(err)
}
if activeRefresh(t, dir) != "refresh-a1" {
t.Fatal("did not switch after the stale lock")
}
}