provider: a magpie run from a terminal that only lists accounts no longer writes logins.json, and every change to it is made under a lock the gateway holds too, so a token the gateway just refreshed is never written back over (#1674, FaintGhost)
Every CLI command that reached Logins() (magpie ls, providers, sessions,
usage) ran rememberLogins, whose 30-second throttle (loginsSeenAt) lives
in the process, so in a new process it never held: each run moved Seen on
for the signed-in Codex and Claude accounts and wrote logins.json back.
loginsMu was an in-process mutex, so that read-modify-write could
interleave with the gateway's renewSavedLogin: the CLI reads, the gateway
writes a refreshed sign-in, the CLI writes what it read. Codex/OpenAI
refresh tokens are single use, so the account would be signed out.
- rememberLogins writes nothing when the only change is Seen and the saved
Seen is less than seenEvery (10 minutes) old (onlySeenMoved, comparing
with what was read, IDs and order normalised as writeLogins writes them;
sortLogins is split out of writeLogins for that).
- internal/filelock (new): davsync's TryLock/Unlock (flock; LockFileEx on
Windows) moved here and davsync uses it; Lock(path, wait) and
filelock.Mutex, a sync.Mutex that also holds the OS lock on a lock file.
A lock another magpie holds is waited for up to filelock.Wait (10s),
then gone on without, as before, so a stuck magpie never hangs others.
- loginsMu is a filelock.Mutex on logins.json.lock, so all 107 existing
Lock sites (every writeLogins is under one) are cross-process with no
change at the call sites. Taking it calls filememo.Look (new), so the
read under it isn't a parse filememo.Hold kept from before another
magpie's write. savedTokenMu holds logins.json.renew.lock the same way:
two magpies never refresh one saved account at once.
- Siblings: caller-keys.json (access.mu: magpie keys from the CLI vs the
window; a lost revoke would bring a key back) and mcp-signins.json
(mcpauth.fileMu, plus mcp-signins.json.renew.lock around renew, since
library's MCP check renews from the CLI too) get the same lock.
plugin-auth.json already has one (plugin-auth.json.lock, shared with
host.js). Not covered: providers.json (33 store sites with no
in-process lock either; user-entered keys, nothing refreshed there),
migrations.json/settings.json (no credentials), and the agents' own
files (~/.codex/auth.json etc.: the agent itself writes them without
any lock of ours, so a magpie-only lock can't make them safe).
Tests:
- TestReadOnlyRunLeavesLogins: Codex and Claude signed in, Seen a minute
old, file time set back; three "new processes" of Logins("")/codex/
claude/All() leave logins.json's bytes and mtime as they were. Seen an
hour old is written; Codex's own refresh is written at once.
- TestLoginsKeepAnotherMagpiesWrite: between this process's read and write
(beforeLoginsWrite hook) a second test process (TestLoginsOtherMagpie,
os.Args[0] -test.run) renews the saved work@ account's refresh token;
both the renewed token and this process's change are in the file.
- TestLoginsReadAfreshUnderLock: with filememo.Hold held, a write
filememo never heard of is seen by a read under loginsMu.
- TestLockAcrossProcesses (filelock): a holder subprocess makes Lock wait
and give up after its wait; killed, the lock is free; a Mutex holds it.
Broken by hand: onlySeenMoved bypassed -> TestReadOnlyRunLeavesLogins
FAIL "a run that only listed the accounts wrote logins.json"; the file
lock taken out of filelock.Mutex.Lock -> TestLoginsKeepAnotherMagpiesWrite
FAIL "the other magpie's renewed sign-in was written over"; Locked hook
emptied -> TestLoginsReadAfreshUnderLock FAIL. Each restored, green.
Ran: gofmt -l (nothing); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
nogui, GOOS=windows go build; go test -tags nogui -count=1 ./... under a
temp HOME with pinned caches: all ok but internal/provider, whose
TestReadOnlyRunLeavesLogins failed at that point from its own fixture
(two rewrites of one size given the same mtime read as unchanged by
filememo); fixed in the test, then internal/provider, access, mcpauth,
filememo, filelock and davsync -count=1 all ok, and the three new provider
tests -race -count=10 ok.
Not tried: the reporter's Linux arm64 box with a real systemd gateway and
real Codex accounts; Windows (LockFileEx path) only vetted and built, not
run on the Windows box.
This commit is contained in:
@@ -118,6 +118,7 @@ Account discovery can be turned off (#1535): Settings → Privacy → *Subscript
|
||||
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
|
||||
- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `lastgood.Keep` ([lastgood.go](../../internal/lastgood/lastgood.go)) keeps the file there now: as `logins.json.bak`, its last good generation, when it reads, or copied aside as `logins.json.bad-<time>` (`-2`, `-3`… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.
|
||||
- A Windows machine that went down mid-write left `logins.json` and `plugin-auth.json` at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through `steady.WriteFile` (or `edit.WriteAtomic`), which flushes the temp file before renaming it in, and the plugin host's `writeDurable` does the same. A file that is there but doesn't read on a cold start is read from its `.bak` (`lastgood.Read`/`Fallback`): `logins.json`, `providers.json`, `migrations.json`, `settings.json`, `profiles.json`, `plugins.json`, `plugin-auth.json` and `mcp-signins.json`. `caller-keys.json` is flushed the same way but never read from a `.bak`: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in `/api/state`'s `recovered`, which the window tells once (`recoveredOnce`). The `.bak` lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good `.bak` the file is unknown, never empty: a sign-out leaves `plugin-auth.json` or `mcp-signins.json` as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.
|
||||
- The gateway and a magpie run from a terminal change the same files (#1674). `loginsMu` is a [`filelock.Mutex`](../../internal/filelock/filelock.go): besides the mutex it holds an OS lock on `logins.json.lock` (flock, `LockFileEx` on Windows), and taking it has `logins.json` read afresh (`filememo.Look`), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over. `savedTokenMu` holds `logins.json.renew.lock` the same way, so two magpies never spend one refresh token. `caller-keys.json` (`access`) and `mcp-signins.json` (`mcpauth`, with `mcp-signins.json.renew.lock` around a renewal) are changed under such locks too; `plugin-auth.json` already was, under `plugin-auth.json.lock`, which `host.js` takes too. A lock another magpie holds is waited for up to `filelock.Wait` (10s), then gone on without, as before there was one. `rememberLogins` writes nothing when only `Seen` would move on and the saved one is less than `seenEvery` (10 minutes) old, so a run that only lists accounts (`magpie ls`, `providers`, `sessions`, `usage`) leaves `logins.json` as it is. [`logins_lock_test.go`](../../internal/provider/logins_lock_test.go) covers both, the second with another test process writing between this one's read and write.
|
||||
- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.
|
||||
- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.
|
||||
- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
@@ -140,7 +141,10 @@ func WithIdentity(ctx context.Context, who Identity) context.Context {
|
||||
}
|
||||
func Caller(ctx context.Context) Identity { who, _ := ctx.Value(contextKey{}).(Identity); return who }
|
||||
|
||||
var mu sync.Mutex
|
||||
// mu is held for every read of caller-keys.json a change is made from,
|
||||
// and the write, across magpies too (#1674): a key revoked with magpie
|
||||
// keys while the window adds one is never written back.
|
||||
var mu = filelock.Mutex{Path: func() string { return Path() + ".lock" }}
|
||||
|
||||
func Path() string { return filepath.Join(settings.Dir(), "caller-keys.json") }
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
@@ -28,13 +29,13 @@ func lock(ctx context.Context) (unlock func(), err error) {
|
||||
return func() {}, nil // no lock to be had here: sync as before there was one
|
||||
}
|
||||
for {
|
||||
got, err := tryLock(f)
|
||||
got, err := filelock.TryLock(f)
|
||||
if err != nil { // a file system without locks, as an NFS home with no lockd
|
||||
f.Close()
|
||||
return func() {}, nil
|
||||
}
|
||||
if got {
|
||||
return func() { unlockFile(f); f.Close() }, nil
|
||||
return func() { filelock.Unlock(f); f.Close() }, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
//go:build !windows
|
||||
|
||||
package davsync
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// tryLock takes f's lock when no other magpie holds it.
|
||||
func tryLock(f *os.File) (bool, error) {
|
||||
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if errors.Is(err, syscall.EWOULDBLOCK) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func unlockFile(f *os.File) { syscall.Flock(int(f.Fd()), syscall.LOCK_UN) }
|
||||
@@ -0,0 +1,82 @@
|
||||
// Package filelock keeps a change to a file one at a time across the
|
||||
// magpies on a computer: the gateway that runs all day, and each magpie
|
||||
// run from a terminal or a script meanwhile.
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Wait is how long Mutex waits for another magpie to let go, before it
|
||||
// goes on without the lock, as it did before there was one: a magpie
|
||||
// stuck holding it (or two magpies each waiting on a lock the other
|
||||
// holds) never hangs every other.
|
||||
const Wait = 10 * time.Second
|
||||
|
||||
// Lock takes the lock on the file at path, made if it isn't there, waiting
|
||||
// up to wait for another process to let it go. The system holds it on the
|
||||
// file and lets it go when the process holding it ends, however it ends,
|
||||
// so none is ever left behind; the file stays, since taken away one
|
||||
// process could hold the lock on it while another took one on a new file.
|
||||
// held is false when it went on without the lock: on a file system
|
||||
// without locks, or after wait.
|
||||
func Lock(path string, wait time.Duration) (unlock func(), held bool) {
|
||||
os.MkdirAll(filepath.Dir(path), 0o700)
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return func() {}, false // no lock to be had here: no file to change either
|
||||
}
|
||||
start := time.Now()
|
||||
for {
|
||||
got, err := TryLock(f)
|
||||
if err != nil { // a file system without locks, as an NFS home with no lockd
|
||||
f.Close()
|
||||
return func() {}, false
|
||||
}
|
||||
if got {
|
||||
return func() { Unlock(f); f.Close() }, true
|
||||
}
|
||||
if time.Since(start) > wait {
|
||||
f.Close()
|
||||
log.Printf("%s: another magpie held it for %v; going on without it", path, wait)
|
||||
return func() {}, false
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// Mutex is a sync.Mutex that also holds the lock on the file Path names
|
||||
// while it is held, so a read, change and write of a file under it is
|
||||
// one at a time across magpies too, not only within this one. Every
|
||||
// read of the file a change is made from is to be made after Lock.
|
||||
type Mutex struct {
|
||||
mu sync.Mutex
|
||||
// Path is the lock file: the file guarded, with ".lock".
|
||||
Path func() string
|
||||
// Locked, when set, is called once both locks are held: to have the
|
||||
// file guarded read afresh, not from what was parsed of it before
|
||||
// another magpie wrote it.
|
||||
Locked func()
|
||||
unlock func()
|
||||
}
|
||||
|
||||
func (m *Mutex) Lock() {
|
||||
m.mu.Lock()
|
||||
m.unlock, _ = Lock(m.Path(), Wait)
|
||||
if m.Locked != nil {
|
||||
m.Locked()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Mutex) Unlock() {
|
||||
unlock := m.unlock
|
||||
m.unlock = nil
|
||||
if unlock != nil {
|
||||
unlock()
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestLockHolder is the other magpie of TestLockAcrossProcesses: it takes
|
||||
// the lock, says so, and holds it until it is killed.
|
||||
func TestLockHolder(t *testing.T) {
|
||||
path := os.Getenv("MAGPIE_FILELOCK_HOLD")
|
||||
if path == "" {
|
||||
t.Skip("run by TestLockAcrossProcesses")
|
||||
}
|
||||
if _, held := Lock(path, time.Second); !held {
|
||||
t.Fatal("not held")
|
||||
}
|
||||
os.Stdout.WriteString("locked\n")
|
||||
time.Sleep(time.Minute)
|
||||
}
|
||||
|
||||
// Another magpie holding the lock is waited for, up to the wait and no
|
||||
// longer; once it ends, however it ends, the lock is free again; and a
|
||||
// Mutex holds it while it is held itself.
|
||||
func TestLockAcrossProcesses(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "f.json.lock")
|
||||
holder := exec.Command(os.Args[0], "-test.run=^TestLockHolder$", "-test.count=1")
|
||||
holder.Env = append(os.Environ(), "MAGPIE_FILELOCK_HOLD="+path)
|
||||
out, _ := holder.StdoutPipe()
|
||||
if err := holder.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { holder.Process.Kill(); holder.Wait() })
|
||||
if line, _ := bufio.NewReader(out).ReadString('\n'); line != "locked\n" {
|
||||
t.Fatalf("the other magpie: %q", line)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
unlock, held := Lock(path, 300*time.Millisecond)
|
||||
unlock()
|
||||
if held || time.Since(start) < 300*time.Millisecond {
|
||||
t.Fatalf("held %v after %v, while another magpie held it", held, time.Since(start))
|
||||
}
|
||||
|
||||
holder.Process.Kill()
|
||||
holder.Wait()
|
||||
unlock, held = Lock(path, 5*time.Second)
|
||||
if !held {
|
||||
t.Fatal("not held after the other magpie ended")
|
||||
}
|
||||
unlock()
|
||||
|
||||
m := Mutex{Path: func() string { return path }}
|
||||
m.Lock()
|
||||
if unlock, held := Lock(path, 50*time.Millisecond); held {
|
||||
unlock()
|
||||
t.Fatal("taken while a Mutex held it")
|
||||
}
|
||||
m.Unlock()
|
||||
unlock, held = Lock(path, time.Second)
|
||||
if !held {
|
||||
t.Fatal("not free after the Mutex let go")
|
||||
}
|
||||
unlock()
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build !windows
|
||||
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// TryLock takes f's lock when no other process (or other descriptor of
|
||||
// the file) holds it.
|
||||
func TryLock(f *os.File) (bool, error) {
|
||||
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if errors.Is(err, syscall.EWOULDBLOCK) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
// Unlock lets f's lock go.
|
||||
func Unlock(f *os.File) { syscall.Flock(int(f.Fd()), syscall.LOCK_UN) }
|
||||
@@ -1,4 +1,4 @@
|
||||
package davsync
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// tryLock takes f's lock when no other magpie holds it.
|
||||
func tryLock(f *os.File) (bool, error) {
|
||||
// TryLock takes f's lock when no other process (or other handle of the
|
||||
// file) holds it.
|
||||
func TryLock(f *os.File) (bool, error) {
|
||||
err := windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, new(windows.Overlapped))
|
||||
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
|
||||
return false, nil
|
||||
@@ -16,6 +17,7 @@ func tryLock(f *os.File) (bool, error) {
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func unlockFile(f *os.File) {
|
||||
// Unlock lets f's lock go.
|
||||
func Unlock(f *os.File) {
|
||||
windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, new(windows.Overlapped))
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// The tests run in a home of their own, never the user's real files.
|
||||
func TestMain(m *testing.M) { testenv.Main(m) }
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -73,6 +74,20 @@ func Forget() {
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// Look has the file at path looked at on its next read, even while a
|
||||
// request holds what was read (Hold): another magpie may have written it,
|
||||
// which Forget, moved on by this one's writes alone, can't know of.
|
||||
func Look(path string) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for k, e := range seen {
|
||||
if strings.HasSuffix(k, "\x00"+path) && !e.checked.IsZero() {
|
||||
e.checked = time.Time{}
|
||||
seen[k] = e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Read is parse of the file at path, from what it gave last time when the
|
||||
// file has the same size and time as then (and, written just now, the same
|
||||
// bytes). kind tells apart two parses of
|
||||
|
||||
@@ -36,6 +36,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
@@ -103,7 +104,10 @@ type Record struct {
|
||||
Dead bool `json:"dead,omitempty"`
|
||||
}
|
||||
|
||||
var fileMu sync.Mutex
|
||||
// fileMu is held for a change to mcp-signins.json read afresh under it,
|
||||
// across magpies too (#1674): the gateway renews a sign-in while a magpie
|
||||
// run from a terminal checks or renames a server.
|
||||
var fileMu = filelock.Mutex{Path: func() string { return path() + ".lock" }}
|
||||
|
||||
func path() string { return filepath.Join(settings.Dir(), "mcp-signins.json") }
|
||||
|
||||
@@ -286,6 +290,10 @@ func renew(ctx context.Context, name string, still func(Record) bool) (string, e
|
||||
mu := lockOf(name)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
// one renewal at a time across magpies as well: a server that rotates
|
||||
// its refresh tokens takes each once
|
||||
unlock, _ := filelock.Lock(path()+".renew.lock", filelock.Wait)
|
||||
defer unlock()
|
||||
r, ok := Get(name)
|
||||
if !ok {
|
||||
return "", ErrNotSignedIn
|
||||
|
||||
+84
-24
@@ -27,6 +27,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
@@ -119,7 +120,15 @@ type savedLogin struct {
|
||||
}
|
||||
|
||||
var (
|
||||
loginsMu sync.Mutex
|
||||
// loginsMu is held for every read of logins.json a change is made
|
||||
// from, and the write: in this magpie, and across magpies (#1674), so
|
||||
// a refresh the gateway writes is never written back over with what a
|
||||
// magpie run from a terminal read before it. Taken, it has logins.json
|
||||
// read afresh.
|
||||
loginsMu = filelock.Mutex{
|
||||
Path: func() string { return loginsPath() + ".lock" },
|
||||
Locked: func() { filememo.Look(loginsPath()) },
|
||||
}
|
||||
loginsSeenAt time.Time
|
||||
)
|
||||
|
||||
@@ -232,6 +241,37 @@ func writeLogins(ls []savedLogin) error {
|
||||
for i := range ls {
|
||||
ls[i].ID = loginID(ls[i])
|
||||
}
|
||||
sortLogins(ls)
|
||||
// a Copilot account renamed on read is written under its new name
|
||||
// once its settings have moved to it; until they can, under its old
|
||||
disk := renameSettled(ls)
|
||||
b, err := json.MarshalIndent(disk, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer Changed() // an account added, switched or gone: All builds anew
|
||||
beforeLoginsWrite()
|
||||
// the file there now is kept first: as its last good generation, or
|
||||
// copied aside when it doesn't read, never written over unkept
|
||||
if err := lastgood.Keep(loginsPath(), validLogins, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writePrivate(loginsPath(), append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
lastLoginsMu.Lock()
|
||||
lastLogins, loginsKnown = slices.Clone(ls), true
|
||||
lastLoginsMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// beforeLoginsWrite is called as logins.json is about to be written: for a
|
||||
// test to have another magpie write it then.
|
||||
var beforeLoginsWrite = func() {}
|
||||
|
||||
// sortLogins puts accounts in the order logins.json keeps them: by agent,
|
||||
// then the order the user gave, then by name.
|
||||
func sortLogins(ls []savedLogin) {
|
||||
sort.SliceStable(ls, func(i, j int) bool {
|
||||
if ls[i].Agent != ls[j].Agent {
|
||||
return ls[i].Agent < ls[j].Agent
|
||||
@@ -247,26 +287,6 @@ func writeLogins(ls []savedLogin) error {
|
||||
}
|
||||
return strings.ToLower(ls[i].User) < strings.ToLower(ls[j].User)
|
||||
})
|
||||
// a Copilot account renamed on read is written under its new name
|
||||
// once its settings have moved to it; until they can, under its old
|
||||
disk := renameSettled(ls)
|
||||
b, err := json.MarshalIndent(disk, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer Changed() // an account added, switched or gone: All builds anew
|
||||
// the file there now is kept first: as its last good generation, or
|
||||
// copied aside when it doesn't read, never written over unkept
|
||||
if err := lastgood.Keep(loginsPath(), validLogins, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writePrivate(loginsPath(), append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
lastLoginsMu.Lock()
|
||||
lastLogins, loginsKnown = slices.Clone(ls), true
|
||||
lastLoginsMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// writePrivate replaces a file readable by the user alone, atomically, so
|
||||
@@ -674,7 +694,9 @@ func rememberLogins(force bool) {
|
||||
return
|
||||
}
|
||||
loginsSeenAt = time.Now()
|
||||
ls := readLogins()
|
||||
was := readLogins()
|
||||
ls := slices.Clone(was)
|
||||
now := time.Now().UTC().Truncate(time.Second)
|
||||
changed := false
|
||||
for _, agent := range loginAgents {
|
||||
if accountRemoved(agent) {
|
||||
@@ -687,7 +709,7 @@ func rememberLogins(force bool) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
l.Seen = time.Now().UTC().Truncate(time.Second)
|
||||
l.Seen = now
|
||||
if agent == "claude" {
|
||||
for i := range ls {
|
||||
ls[i].Held = false
|
||||
@@ -697,11 +719,49 @@ func rememberLogins(force bool) {
|
||||
ls = upsertLogin(ls, l)
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
// every magpie run from a terminal is a new process, which the 30
|
||||
// seconds above don't hold for: one that would only move Seen on, and
|
||||
// that recently, writes nothing (#1674)
|
||||
if changed && !onlySeenMoved(was, ls, now) {
|
||||
_ = writeLogins(ls)
|
||||
}
|
||||
}
|
||||
|
||||
// seenEvery is how often an account still signed in has the time it was
|
||||
// last seen written, when nothing else of it changed.
|
||||
const seenEvery = 10 * time.Minute
|
||||
|
||||
// onlySeenMoved says next is was with nothing changed but the times
|
||||
// accounts were last seen, each of them less than seenEvery before now.
|
||||
func onlySeenMoved(was, next []savedLogin, now time.Time) bool {
|
||||
if len(was) != len(next) {
|
||||
return false
|
||||
}
|
||||
norm := func(ls []savedLogin) []savedLogin {
|
||||
out := slices.Clone(ls)
|
||||
for i := range out {
|
||||
out[i].ID = loginID(out[i])
|
||||
}
|
||||
sortLogins(out)
|
||||
return out
|
||||
}
|
||||
a, b := norm(was), norm(next)
|
||||
for i := range b {
|
||||
if a[i].ID != b[i].ID {
|
||||
return false
|
||||
}
|
||||
if !b[i].Seen.Equal(a[i].Seen) {
|
||||
if a[i].Seen.IsZero() || now.Sub(a[i].Seen) >= seenEvery || b[i].Seen.Before(a[i].Seen) {
|
||||
return false
|
||||
}
|
||||
b[i].Seen = a[i].Seen
|
||||
}
|
||||
}
|
||||
ja, err1 := json.Marshal(a)
|
||||
jb, err2 := json.Marshal(b)
|
||||
return err1 == nil && err2 == nil && bytes.Equal(ja, jb)
|
||||
}
|
||||
|
||||
// Logins lists the remembered accounts of an agent ("" for every one),
|
||||
// the active one flagged.
|
||||
func Logins(agent string) []Login {
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
)
|
||||
|
||||
// newProcess is what a magpie run from a terminal starts with: nothing
|
||||
// remembered of when the accounts were last looked at.
|
||||
func newProcess() {
|
||||
loginsMu.Lock()
|
||||
loginsSeenAt = time.Time{}
|
||||
loginsMu.Unlock()
|
||||
}
|
||||
|
||||
var seenAgoCalls int
|
||||
|
||||
// seenAgo puts every account's Seen in logins.json back by d, and the
|
||||
// file's time back an hour, so a write after it shows.
|
||||
func seenAgo(t *testing.T, d time.Duration) (raw []byte, mod time.Time) {
|
||||
t.Helper()
|
||||
var ls []map[string]any
|
||||
b, err := os.ReadFile(loginsPath())
|
||||
if err != nil || json.Unmarshal(b, &ls) != nil || len(ls) == 0 {
|
||||
t.Fatalf("logins.json: %v %s", err, b)
|
||||
}
|
||||
for _, l := range ls {
|
||||
l["seen"] = time.Now().Add(-d).UTC().Truncate(time.Second)
|
||||
}
|
||||
writeFile(t, loginsPath(), ls)
|
||||
// a time of its own each call, as another magpie's write has: the
|
||||
// same size at the same time would read as the file unchanged
|
||||
seenAgoCalls++
|
||||
mod = time.Now().Add(-time.Hour - time.Duration(seenAgoCalls)*time.Minute).Truncate(time.Second)
|
||||
if err := os.Chtimes(loginsPath(), mod, mod); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ = os.ReadFile(loginsPath())
|
||||
return raw, mod
|
||||
}
|
||||
|
||||
func loginsUnchanged(t *testing.T, raw []byte, mod time.Time) bool {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile(loginsPath())
|
||||
fi, ferr := os.Stat(loginsPath())
|
||||
if err != nil || ferr != nil {
|
||||
t.Fatal(err, ferr)
|
||||
}
|
||||
return bytes.Equal(b, raw) && fi.ModTime().Equal(mod)
|
||||
}
|
||||
|
||||
// A magpie run from a terminal that only lists accounts (magpie ls,
|
||||
// providers, sessions, usage) writes nothing to logins.json (#1674,
|
||||
// FaintGhost): each is a new process, so the 30 seconds between looks
|
||||
// never held, and every run wrote the file back with Seen moved on, over
|
||||
// whatever the gateway had written meanwhile.
|
||||
func TestReadOnlyRunLeavesLogins(t *testing.T) {
|
||||
home := signIn(t)
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", "")
|
||||
noAnthropic(t)
|
||||
claudeSignIn(t, home, time.Now().Add(time.Hour))
|
||||
writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{"oauthAccount": map[string]any{"emailAddress": "own@example.com"}})
|
||||
rememberLogins(true)
|
||||
if ls := Logins(""); len(ls) < 2 {
|
||||
t.Fatalf("listed: %+v", ls)
|
||||
}
|
||||
|
||||
raw, mod := seenAgo(t, time.Minute)
|
||||
for range 3 {
|
||||
newProcess()
|
||||
Logins("")
|
||||
Logins("codex")
|
||||
Logins("claude")
|
||||
All()
|
||||
}
|
||||
if !loginsUnchanged(t, raw, mod) {
|
||||
b, _ := os.ReadFile(loginsPath())
|
||||
t.Fatalf("a run that only listed the accounts wrote logins.json:\nwas %s\nnow %s", raw, b)
|
||||
}
|
||||
|
||||
// seen long enough ago, it is written: the time still moves on
|
||||
raw, mod = seenAgo(t, time.Hour)
|
||||
newProcess()
|
||||
Logins("")
|
||||
if loginsUnchanged(t, raw, mod) {
|
||||
t.Fatal("an account last seen an hour ago wasn't written as seen now")
|
||||
}
|
||||
|
||||
// a change besides the time is written at once: Codex refreshed its own
|
||||
raw, mod = seenAgo(t, time.Minute)
|
||||
codexSignIn(t, home, "me@example.com", "r-refreshed")
|
||||
newProcess()
|
||||
Logins("")
|
||||
if loginsUnchanged(t, raw, mod) {
|
||||
t.Fatal("Codex's refreshed sign-in wasn't saved")
|
||||
}
|
||||
if b, _ := os.ReadFile(loginsPath()); !bytes.Contains(b, []byte("r-refreshed")) {
|
||||
t.Fatalf("logins.json: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginsOtherMagpie is the gateway of TestLoginsKeepAnotherMagpiesWrite:
|
||||
// it renews the saved account's sign-in, as renewSavedLogin writes it.
|
||||
func TestLoginsOtherMagpie(t *testing.T) {
|
||||
if os.Getenv("MAGPIE_LOGINS_WRITER") == "" {
|
||||
t.Skip("run by TestLoginsKeepAnotherMagpiesWrite")
|
||||
}
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
ls := readLogins()
|
||||
found := false
|
||||
for i := range ls {
|
||||
if ls[i].User == "work@example.com" {
|
||||
ls[i].Auth = []byte(strings.ReplaceAll(string(ls[i].Auth), "r-work", "r-rotated"))
|
||||
ls[i].Renewed = time.Now().UTC().Truncate(time.Second)
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("no saved work@example.com in %+v", ls)
|
||||
}
|
||||
if err := writeLogins(ls); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The gateway renews a saved account's sign-in while a magpie run from a
|
||||
// terminal is between reading logins.json and writing it back (#1674): the
|
||||
// renewed sign-in stays. Codex's refresh tokens are spent by use, so the
|
||||
// old one written back would sign the account out.
|
||||
func TestLoginsKeepAnotherMagpiesWrite(t *testing.T) {
|
||||
home := signIn(t)
|
||||
codexSignIn(t, home, "work@example.com", "r-work")
|
||||
rememberLogins(true)
|
||||
codexSignIn(t, home, "me@example.com", "r-me")
|
||||
rememberLogins(true)
|
||||
if b, _ := os.ReadFile(loginsPath()); !bytes.Contains(b, []byte("r-work")) {
|
||||
t.Fatalf("work@example.com not saved: %s", b)
|
||||
}
|
||||
|
||||
// Codex refreshed its own sign-in: this magpie has a change to write
|
||||
codexSignIn(t, home, "me@example.com", "r-me-2")
|
||||
newProcess()
|
||||
var other *exec.Cmd
|
||||
otherDone := make(chan error, 1)
|
||||
beforeLoginsWrite = func() {
|
||||
beforeLoginsWrite = func() {}
|
||||
other = exec.Command(os.Args[0], "-test.run=^TestLoginsOtherMagpie$", "-test.count=1")
|
||||
other.Env = append(os.Environ(), "MAGPIE_LOGINS_WRITER=1")
|
||||
var out bytes.Buffer
|
||||
other.Stdout, other.Stderr = &out, &out
|
||||
if err := other.Start(); err != nil {
|
||||
t.Error(err)
|
||||
otherDone <- err
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
err := other.Wait()
|
||||
if err != nil {
|
||||
t.Logf("the other magpie: %v\n%s", err, out.Bytes())
|
||||
}
|
||||
otherDone <- err
|
||||
}()
|
||||
// the other magpie writes now if it can; with the lock held here
|
||||
// it waits for this one's write instead
|
||||
select {
|
||||
case err := <-otherDone:
|
||||
otherDone <- err
|
||||
case <-time.After(2 * time.Second):
|
||||
}
|
||||
}
|
||||
t.Cleanup(func() { beforeLoginsWrite = func() {} })
|
||||
rememberLogins(false)
|
||||
if other == nil {
|
||||
t.Fatal("this magpie wrote nothing")
|
||||
}
|
||||
if err := <-otherDone; err != nil {
|
||||
t.Fatal("the other magpie failed")
|
||||
}
|
||||
|
||||
b, _ := os.ReadFile(loginsPath())
|
||||
if !bytes.Contains(b, []byte("r-rotated")) || bytes.Contains(b, []byte(`r-work"`)) {
|
||||
t.Fatalf("the other magpie's renewed sign-in was written over:\n%s", b)
|
||||
}
|
||||
if !bytes.Contains(b, []byte("r-me-2")) {
|
||||
t.Fatalf("this magpie's change was lost:\n%s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// A change is made from logins.json as it is on the disk, not as this
|
||||
// magpie parsed it before another wrote it: the GUI's state holds what
|
||||
// was read for a second (filememo.Hold), and taking loginsMu looks again.
|
||||
func TestLoginsReadAfreshUnderLock(t *testing.T) {
|
||||
home := signIn(t)
|
||||
codexSignIn(t, home, "work@example.com", "r-work")
|
||||
rememberLogins(true)
|
||||
old := time.Now().Add(-time.Hour)
|
||||
os.Chtimes(loginsPath(), old, old)
|
||||
release := filememo.Hold()
|
||||
defer release()
|
||||
readLogins()
|
||||
|
||||
// another magpie's write, which this one's filememo.Forget never hears of
|
||||
b, _ := os.ReadFile(loginsPath())
|
||||
if err := os.WriteFile(loginsPath(), bytes.ReplaceAll(b, []byte("r-work"), []byte("r-rotated")), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loginsMu.Lock()
|
||||
ls := readLogins()
|
||||
loginsMu.Unlock()
|
||||
if len(ls) != 1 || !bytes.Contains(ls[0].Auth, []byte("r-rotated")) {
|
||||
t.Fatalf("read under the lock: %+v", ls)
|
||||
}
|
||||
}
|
||||
@@ -14,13 +14,16 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filelock"
|
||||
)
|
||||
|
||||
// savedTokenMu keeps two requests from refreshing one saved account at
|
||||
// once: the second would spend a refresh token the first just rotated.
|
||||
var savedTokenMu sync.Mutex
|
||||
// once: the second would spend a refresh token the first just rotated. It
|
||||
// holds across magpies too (#1674): the gateway's refresh and one by a
|
||||
// magpie run from a terminal would each spend the same refresh token.
|
||||
var savedTokenMu = filelock.Mutex{Path: func() string { return loginsPath() + ".renew.lock" }}
|
||||
|
||||
// SetLoginOn puts a saved account in use beside the agent's own, or takes
|
||||
// it out. The account the agent is signed in to is always in use.
|
||||
|
||||
Reference in New Issue
Block a user