Cause: a plugin hook that saves a sign-in through client.auth.set (a models list spending a rotating refresh token) wrote it into plugin-auth.json unconditionally. A listing that began before a sign-out, or before a failed move's putBack took the accounts back out of the plugin (plugin.Take), landed after it and wrote the account in again. TestMoveToPlugin's reset signs fakeco out, but a background listing set off by the step before spent a@fake's "rot-a" token again (rot-a+++++ seen in the file right after the sign-out), so the next Move saw a@fake as the plugin's own (movedAccount.Was), restored it on failure, and "the plugin kept an account of a failed move". TestMoveCutShort (#5119) fails the same way: the account Take removed came back through the same write. Not a leak between runs: the race is inside one run, and more runs only gave it more chances. It is a real bug for users too: signing out of a rotating-token account while its models are listed brought it back. Fix: inScope in host.js notes whether the account was signed in when the call began (had); auth.set skips the write under the file's lock when it was and is gone now, as renewLocked already does for renewals. Sign-in steps (signingIn) are not held to it, their account is new. Test: TestSignOutOutlastsRunningHook holds the fake plugin's models hook (new FAKE_MODELS_HOLD: marker file in, release file out) across a SignOut in a real host and checks the account stays gone, and that a hook not raced still keeps the token it saved. Run (all at this tree): - mote-run go test -count=30 -run 'TestMoveToPlugin$|TestMoveCutShort$' ./internal/provider: ok. Before the fix the same run on mote failed 3 TestMoveToPlugin + 9 TestMoveCutShort of 30 each; -count=15 of TestMoveToPlugin alone failed 2 to 4 of 15. - wsl-run go test -count=20 of the two plus the new test: ok. Before the fix: 4 + 17 of 20 failed on Linux. - mote-run go test -count=5 -run TestMoveToPlugin$: ok. - mote-run go test -count=5 TestSignOutOutlastsRunningHook: ok. - mote-run go test -timeout 45m ./internal/provider ./internal/plugin: ok (provider 171.6s, plugin 160.4s). - gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet of both packages: ok. Broken by hand: host.js reverted with the test kept: TestSignOutOutlastsRunningHook red 3 of 3 ("the hook signed the account in again"), and the provider tests red as above. Not tried: a real vendor's rotating-token plugin signed out mid-listing (the fake plugin's rot- sign-ins stand in for it); the full ./... suite runs after the push.
This commit is contained in:
@@ -203,6 +203,8 @@ An OAuth account keeps a short-lived access token beside its refresh token, and
|
||||
|
||||
A plugin's `auth.refresh` renews a sign-in only when something uses the account (a request, its models, its usage, its check-in) within its `refreshLead` of `expires`. An account left idle past its token's life lapsed, and for a vendor whose session dies with its token the user had to sign in again: OrcaTerm's WeChat token lives two hours, and its refresh after that answers `SESSION_EXPIRED` for good (#5080, orinsid, [magpie-community/plugins#675](https://github.com/magpie-community/plugins/issues/675)). So the magpie serving the gateway renews each such sign-in as it comes due (`KeepPluginsSignedIn` in [`plugin_keepalive.go`](../../internal/provider/plugin_keepalive.go), started beside `KeepPluginsListed`). It reads the due times from plugin-auth.json (`plugin.RenewAt`: `expires` less the lead the host reckons, `Provider.RenewLead`, listed with `Renews`), asks nothing and starts no host until one is due, and sleeps until the next, at most five minutes. A due sign-in is renewed through the host's own renewal (`keepSignedIn` → `renewal` in [`host.js`](../../internal/plugin/host.js)), the one a request makes: one at a time per account whoever asks, a request arriving meanwhile waiting for the same one, under the lock file every magpie process renews under, through the account's proxy. Only accounts switched on and not marked, of a plugin provider not switched off, hidden (`leftAlone`) or being moved, are kept. A renewal that fails marks nothing: it is held back a minute, doubled each time to half an hour, for that sign-in only; only the plugin's `signIn: "expired"` marks the account, as at a request. A plugin whose renewal costs the account something, or whose refresh token another client holds too, says `auth.keepAlive: false` and is renewed only when used. No plugin in magpie-community/plugins says so as of this change: their refreshes cost no quota, those that rotate a refresh token (Cline, Factory, Nous, SenseNova, CodeArts, Qoder, MiniMax) already rotate it at use, and the ones reading another app's sign-in (kimi-work's reference accounts, Raccoon's desktop) never refresh it. `TestKeepSignedInRenewsIdleSignIns` in [`plugin_keepalive_test.go`](../../internal/plugin/plugin_keepalive_test.go) runs the renewal fixture in a real host; `TestKeeperAsksOnlyWhatIsDue`, `TestKeeperBacksOffAFailedRenewal`, `TestKeeperHoldsWhatTheHostFindsNotDue` and `TestKeptSignInsAreTheOnesSwitchedOn` in [`plugin_keepalive_test.go`](../../internal/provider/plugin_keepalive_test.go) cover the loop and which accounts it keeps.
|
||||
|
||||
An account signed out while one of its hooks runs stays signed out. A hook that saves a sign-in through `client.auth.set` (a models list spending a rotating refresh token, as the fake plugin's `rot-` sign-ins do) saves nothing once the account it was called for is gone from plugin-auth.json: `inScope` in [`host.js`](../../internal/plugin/host.js) notes whether the account was signed in when the call began (`had`), and `auth.set` checks it under the file's lock, as `renewLocked` already did for a renewal. A sign-in's own steps (`signingIn`) are not held to it, since their account is new. Before this, a listing that started before a sign-out, or before a failed move took its accounts back out of the plugin (`putBack`), wrote the account in again, and the plugin kept an account of a move that failed (#5126, #5119). `TestSignOutOutlastsRunningHook` in [`signout_hook_test.go`](../../internal/plugin/signout_hook_test.go) holds the hook (`FAKE_MODELS_HOLD`) across the sign-out in a real host.
|
||||
|
||||
## A model's free and rate
|
||||
|
||||
magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true`, a $0 list price or the user counting its whole provider free (`Provider.CountFree`) (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)).
|
||||
|
||||
+17
-3
@@ -1103,8 +1103,18 @@ function freshKey(provider) {
|
||||
}
|
||||
}
|
||||
|
||||
function inScope(provider, key, fn) {
|
||||
return scope.run({ provider, key }, fn)
|
||||
// inScope runs fn for provider's account key. had is whether the account
|
||||
// was signed in as fn began: a hook's auth.set for one signed out while it
|
||||
// ran (a models list spending a rotating token) doesn't sign it in again.
|
||||
// A sign-in's steps (signIn) save whatever they are given.
|
||||
function inScope(provider, key, fn, signIn = false) {
|
||||
let had = false
|
||||
if (!signIn) {
|
||||
try {
|
||||
had = key in readAuth()
|
||||
} catch {}
|
||||
}
|
||||
return scope.run({ provider, key, had }, fn)
|
||||
}
|
||||
|
||||
function whoOf(a) {
|
||||
@@ -1197,7 +1207,11 @@ function makeClient() {
|
||||
// tokens over the old; nothing is merged. It goes to the
|
||||
// account the request is for.
|
||||
const key = keyFor(id)
|
||||
const s = scope.getStore()
|
||||
const had = s?.provider === id && s.had
|
||||
const kept = await changeAuth((all) => {
|
||||
// signed out while the hook ran: it stays signed out
|
||||
if (had && !(key in all)) return false
|
||||
if (JSON.stringify(all[key]) === JSON.stringify(body)) return false
|
||||
all[key] = body
|
||||
})
|
||||
@@ -2478,7 +2492,7 @@ function abortedSignIn() {
|
||||
// signingIn runs a plugin's sign-in step fn for key under proxy and
|
||||
// signal; it ends when signal aborts, whether fn does or not.
|
||||
function signingIn(signal, proxy, provider, key, fn) {
|
||||
const step = via.run(proxy, () => inScope(provider, key, () => signInSignal.run(signal, fn)))
|
||||
const step = via.run(proxy, () => inScope(provider, key, () => signInSignal.run(signal, fn), true))
|
||||
return signal ? bounded(Promise.resolve(step), signal) : step
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// An account signed out while one of its hooks runs stays signed out: the
|
||||
// hook's auth.set (a models list spending a rotating refresh token) lands
|
||||
// after the sign-out and must not sign it in again (#5126: a failed move's
|
||||
// account came back in the plugin this way). One not signed out keeps the
|
||||
// token the hook saved.
|
||||
func TestSignOutOutlastsRunningHook(t *testing.T) {
|
||||
sandbox(t)
|
||||
hold := filepath.Join(t.TempDir(), "hold")
|
||||
t.Setenv("FAKE_MODELS_HOLD", hold)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
abs, _ := filepath.Abs("testdata/fake/index.js")
|
||||
if _, err := Add(ctx, abs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(Settle)
|
||||
signIn := func() string {
|
||||
t.Helper()
|
||||
k, err := Import(ctx, "fakeco", map[string]any{"type": "oauth", "refresh": "rot-x", "access": "a", "expires": 9e15, "accountId": "x@fake"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
// the hook comes, and waits
|
||||
arrived := func() {
|
||||
t.Helper()
|
||||
for {
|
||||
if _, err := os.Stat(hold + ".in"); err == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatal("the models hook never came")
|
||||
case <-time.After(10 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
checked := func(key string) chan error {
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := Check(ctx, "fakeco", key)
|
||||
done <- err
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
// signed out while the hook holds the token it is about to save
|
||||
key := signIn()
|
||||
done := checked(key)
|
||||
arrived()
|
||||
if err := SignOut(ctx, "fakeco", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(hold, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-done
|
||||
if a := Auths("fakeco"); len(a) != 0 {
|
||||
t.Fatalf("the hook signed the account in again: %v", a)
|
||||
}
|
||||
|
||||
// not signed out: the token it spent is replaced by one it saved
|
||||
key = signIn()
|
||||
if err := <-checked(key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// (a listing the sign-in set off may spend it again too)
|
||||
if a := Auths("fakeco"); !strings.HasPrefix(fmt.Sprint(a[key]["refresh"]), "rot-x+") {
|
||||
t.Fatalf("the hook's renewed token wasn't kept: %v", a)
|
||||
}
|
||||
}
|
||||
+8
@@ -370,6 +370,14 @@ export const FakePlugin = async ({ client }) => ({
|
||||
// the vendor unreachable: the list kept, as Zed's plugin keeps it
|
||||
if (auth?.refresh === "r-unreachable") await fetch("http://127.0.0.1:9/models").catch(() => {})
|
||||
if (auth?.type === "oauth" && auth.refresh?.startsWith("rot-")) {
|
||||
// $FAKE_MODELS_HOLD: say the hook came ($FAKE_MODELS_HOLD.in), and
|
||||
// spend the token only once that file is there
|
||||
const hold = process.env.FAKE_MODELS_HOLD
|
||||
if (hold) {
|
||||
const fs = await import("node:fs")
|
||||
fs.writeFileSync(hold + ".in", "")
|
||||
while (!fs.existsSync(hold)) await new Promise((r) => setTimeout(r, 10))
|
||||
}
|
||||
await client.auth.set({ path: { id: ID }, body: { ...auth, refresh: auth.refresh + "+" } })
|
||||
}
|
||||
// fake-1 costs the plan nothing, as a WorkBuddy model of x0.00
|
||||
|
||||
Reference in New Issue
Block a user