diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 183a6a73a..e675d63c1 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -182,6 +182,10 @@ The host loads every plugin side by side (`loadPlugins` in [`host.js`](../../int A 401 marks the account's sign-in by default (`notePluginSignIn` in [`plugins.go`](../../internal/provider/plugins.go)), and the gateway fails a 401 over to the provider's next account (`retryable` in [`fallback.go`](../../internal/gateway/fallback.go)), which a model the plan doesn't serve answers the same way. So a plugin that answered "this model isn't available to you" with 401 marked every account of the provider as needing a new sign-in, for credentials that were fine ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)). A 401 without `X-Magpie-Sign-In` whose body says the model isn't served (`provider.ModelUnserved`, the gateway's `unservedWords`, read decoded by `catalog.Words`) and nothing of a token, key, credential, session or sign-in (`signInWords`) is now read as `kept` (`modelOnly401`). Only the body's first 64KB is read, and the body goes on whole. The gateway still rests the account under its usual failure backoff for that answer; the guide asks for 403 or 404 for a model the account may not use, which `modelRefused` reads as the model refused. `TestPluginModel401KeepsSignIn` in [`plugin_signin_model_test.go`](../../internal/provider/plugin_signin_model_test.go) covers both kinds of 401. +## A 401 on an access token its refresh token renews + +An OAuth account keeps a short-lived access token beside its refresh token, and its plugin's loader (or magpie's `auth.refresh`) renews the access token when its stored `expires` comes. A vendor can turn an access token away before that: Copilot's API dropped the inference token of a slot that had carried no traffic, while its GitHub OAuth token still traded at `/copilot_internal/v2/token`, and the bare 401 marked the account "sign-in has expired — sign in again", whose row then offered only a new device flow ([magpie-community/plugins#618](https://github.com/magpie-community/plugins/issues/618), jinpy666). The host now judges a 401 its plugin said nothing of (no `X-Magpie-Sign-In`) against the sign-in as the request found it (`staleAccess` in [`host.js`](../../internal/plugin/host.js)): an OAuth sign-in with a refresh token whose access token is still the stored one and not due yet is made due (`expires` 1, under the auth lock, only while the access token is unchanged) and said `kept`, so the next request renews it and goes through, and the gateway fails this one over as it fails any 401. The account is still marked when the access token was renewed for this request and turned away, when it was due already and the plugin didn't renew it, when the account has no refresh token, and when the plugin says so (an error with `signIn: "expired"`, a refresh `auth.refresh` was refused). A sign-in that can't be read when the 401 comes (`readAuthState`'s `known` false) is unknown: `kept`, never marked. A marked account is still routed to (`pluginAlsoOn` leaves no account on out for its mark), so a slot marked before is renewed on its next request and cleared by the success. Copilot's plugin 0.1.1 says `expired` only for the token exchange's own 401 and `renewed` for a quota read GitHub answers, which clears a mark left from before. `TestPluginStaleAccessRenewsNotLapses` in [`plugin_stale_access_test.go`](../../internal/provider/plugin_stale_access_test.go) covers the idle account renewed, a renewed token turned away, a refused refresh, an unreadable sign-in and the marked account still routed. + ## 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)). diff --git a/internal/gateway/plugin_failover_test.go b/internal/gateway/plugin_failover_test.go index 65aa6d4ae..81b751f0a 100644 --- a/internal/gateway/plugin_failover_test.go +++ b/internal/gateway/plugin_failover_test.go @@ -171,6 +171,33 @@ func TestPluginFailover(t *testing.T) { t.Fatalf("%s: the next request tried %s again: %d %s (tried %v)", how, first, code, body, seen) } if how == "gone" { + // one 401 on an access token not due yet, with a + // refresh token beside it, makes the token due and + // keeps the sign-in (plugins#618): the account is + // marked when the token renewed for its next request + // is turned away too + for _, l := range provider.Logins("fakeco") { + if strings.HasPrefix(l.User, first+"@") && l.Lapsed != "" { + t.Fatalf("%s is marked for one 401 its refresh token can renew: %+v", first, l) + } + } + for again := 0; ; again++ { + restingUntil.Lock() + restingUntil.m = map[string]time.Time{} + restingUntil.Unlock() + sticks.Lock() + sticks.m = map[string]stick{} + sticks.Unlock() + mu.Lock() + tried = nil + mu.Unlock() + if _, _, seen := ask("fakeco/fake-1"); contains(seen, first) { + break + } + if again == 20 { + t.Fatalf("%s wasn't tried again", first) + } + } for _, l := range provider.Logins("fakeco") { if strings.HasPrefix(l.User, first+"@") && !strings.Contains(l.Lapsed, "sign-in has expired") { t.Fatalf("%s refused isn't marked: %+v", first, l) diff --git a/internal/plugin/host.js b/internal/plugin/host.js index ae87e1955..92a430497 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2699,9 +2699,43 @@ async function doFetch(id, record, params) { return via.run(params.proxy ?? "", () => inScope(params.provider, key, () => fetchAs(id, record, key, params))) } +// staleAccess is what a bare 401 says of the OAuth sign-in at key that +// had a refresh token when the request began (before): "kept" when the +// access token alone was turned away, so the next request renews it, and +// nothing, for the 401 to mark the account, when the refresh is what +// failed. An access token the vendor dropped before the expiry it was +// stored with (an idle account, another client trading the same refresh +// token: plugins#618) isn't the sign-in gone. So such a 401, with the +// access token the request began with still the stored one and not due +// yet, makes it due (expires 1) and keeps the sign-in: the plugin's +// loader, or magpie's auth.refresh, renews it on the next request. The +// account is marked when the token was renewed for this request and +// still turned away, or was due and the plugin didn't renew it; a +// refresh the vendor refuses says so itself (signIn "expired"). A +// sign-in that can't be read now is unknown: kept, not marked. +function staleAccess(key, before) { + const now = readAuthState() + if (!now.known) return "kept" + if (before?.type !== "oauth" || !before.refresh) return "" + const cur = now.all[key] + if (cur?.type !== "oauth" || cur.refresh !== before.refresh || cur.access !== before.access) return "" + const exp = Number(before.expires) + if (!Number.isFinite(exp) || exp <= Date.now()) return "" + changeAuth((all) => { + const a = all[key] + if (a?.type !== "oauth" || a.access !== before.access || a.refresh !== before.refresh) return false + all[key] = { ...a, expires: 1 } + }) + forgetAccount(key) + return "kept" +} + async function fetchAs(id, record, key, params) { const { controller: ctl, gate } = record const { provider, model, npm, url, method, headers, body, session } = params + // the sign-in as the request found it, before its loader or magpie + // renewed it: a 401 is judged against it (staleAccess) + const before = key ? readAuth()[key] : undefined try { const o = await options(provider, key) checkFetch(record) @@ -2755,6 +2789,10 @@ async function fetchAs(id, record, key, params) { transitionFetch(record, "streaming") const rh = {} res.headers.forEach((v, k) => (rh[k] = v)) + if (res.status === 401 && !("x-magpie-sign-in" in rh) && key) { + const said = staleAccess(key, before) + if (said) rh["x-magpie-sign-in"] = said + } const head = headCost(rh) if (head.entries > HEAD_ENTRIES || head.n > HEAD_MAX) { // the reply's head is past magpie's envelope: give the fetch up rather diff --git a/internal/provider/plugin_stale_access_test.go b/internal/provider/plugin_stale_access_test.go new file mode 100644 index 000000000..bfc021e6e --- /dev/null +++ b/internal/provider/plugin_stale_access_test.go @@ -0,0 +1,193 @@ +package provider + +import ( + "context" + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/testenv" +) + +// An idle OAuth account whose access token the vendor dropped before the +// expiry it was stored with, while its refresh token still renews, is not +// a sign-in gone (plugins#618, jinpy666: three Copilot slots, the two +// with no traffic said "sign-in has expired — sign in again" though their +// refresh tokens still traded at /copilot_internal/v2/token). The bare +// 401 makes the access due and keeps the account; the next request +// renews it through the plugin's loader and goes through. An account +// whose renewed token is turned away too is marked, and so is one whose +// plugin says its refresh was refused; a sign-in that can't be read when +// the 401 comes is unknown, not marked. A marked account is still one a +// request can be routed to, for the loader to renew on use. +func TestPluginStaleAccessRenewsNotLapses(t *testing.T) { + bun := testenv.Bun(t) + claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + var unreadable func() + testenv.FakeVendor(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + switch r.Header.Get("Authorization") { + case "Bearer fresh-r-ok", "Bearer fresh-r-unknown": + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"id":"x","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`) + return + case "Bearer a-unknown": + unreadable() + } + // the access token turned away, as Copilot's API answers one it + // no longer takes, whatever the stored expiry said + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + io.WriteString(w, `{"error":{"message":"unauthorized: token expired","code":"token_expired"}}`) + })) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + // the reporter's shape: access stored with an expiry still ahead, + // refresh good; "r-bad"'s renewed token is turned away too + accts := []struct{ user, refresh, access string }{ + {"idle@fake", "r-ok", "a"}, + {"bad@fake", "r-bad", "a"}, + {"revoked@fake", "r-revoked", "a"}, + {"unknown@fake", "r-unknown", "a-unknown"}, + {"first@fake", "r-first", "fresh-r-first"}, + } + keys := map[string]string{} + var rows []savedLogin + for _, a := range accts { + k, err := plugin.Import(ctx, "fakeco", map[string]any{"type": "oauth", "refresh": a.refresh, "access": a.access, "expires": float64(time.Now().Add(20 * time.Hour).UnixMilli()), "accountId": a.user}) + if err != nil { + t.Fatal(err) + } + keys[a.user] = k + rows = append(rows, savedLogin{Agent: "plugin:fakeco", User: a.user, Home: k, On: true}) + } + saveLogins(t, rows...) + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + authPath := plugin.AuthPath() + unreadable = func() { + for _, p := range []string{authPath, authPath + ".bak"} { + if err := os.WriteFile(p, []byte("{half"), 0o600); err != nil { + t.Error(err) + } + } + } + stored := func(user string) map[string]any { + t.Helper() + b, err := os.ReadFile(authPath) + if err != nil { + t.Fatal(err) + } + var all map[string]map[string]any + if err := json.Unmarshal(b, &all); err != nil { + t.Fatal(err) + } + return all[keys[user]] + } + lapsed := func(user string) bool { + for _, l := range pluginLogins(mustPlugin(t)) { + if l.User == user { + return l.Lapsed != "" + } + } + t.Fatalf("no row for %s", user) + return false + } + ask := func(user string) int { + t.Helper() + pp := mustPlugin(t) + req, _ := http.NewRequestWithContext(ctx, "POST", pluginBase+pp.ID+"/v1/chat/completions", strings.NewReader(`{"model":"fake-claude","messages":[{"role":"user","content":"hi"}]}`)) + resp, err := pluginFetch(pp, keys[user], req) + if err != nil { + return 0 + } + io.Copy(io.Discard, resp.Body) + resp.Body.Close() + if resp.Header.Get(SignInHeader) != "" { + t.Errorf("%s: %s went on to the client", user, SignInHeader) + } + return resp.StatusCode + } + + // idle: the first request meets the dropped token, the second renews + if got := ask("idle@fake"); got != http.StatusUnauthorized { + t.Fatalf("idle@fake's first request: %d", got) + } + if lapsed("idle@fake") { + t.Fatal("idle@fake was marked for a dropped access token its refresh token renews") + } + if a := stored("idle@fake"); a["refresh"] != "r-ok" || a["access"] != "a" || a["expires"] != float64(1) { + t.Fatalf("idle@fake isn't due for renewal: %v", a) + } + if got := ask("idle@fake"); got != http.StatusOK { + t.Fatalf("idle@fake's second request: %d", got) + } + if a := stored("idle@fake"); a["access"] != "fresh-r-ok" || a["refresh"] != "r-ok" { + t.Fatalf("idle@fake wasn't renewed: %v", a) + } + if lapsed("idle@fake") { + t.Fatal("idle@fake is marked after it renewed") + } + + // bad: renewed, and the renewed token turned away too + if got := ask("bad@fake"); got != http.StatusUnauthorized || lapsed("bad@fake") { + t.Fatalf("bad@fake's first request: %d, lapsed %v", got, lapsed("bad@fake")) + } + if got := ask("bad@fake"); got != http.StatusUnauthorized { + t.Fatalf("bad@fake's second request: %d", got) + } + if !lapsed("bad@fake") { + t.Fatal("bad@fake isn't marked though its renewed token was turned away") + } + // a lapsed account is still one to route to: the first of the + // provider, or one beside it + routed := slices.ContainsFunc(pluginAlsoOn(mustPlugin(t)), func(p Provider) bool { return p.Account != nil && p.Account.pluginKey == keys["bad@fake"] }) + for _, l := range pluginLogins(mustPlugin(t)) { + routed = routed || l.User == "bad@fake" && l.Active + } + if !routed { + t.Error("bad@fake left the accounts a request is routed to") + } + + // revoked: the plugin says its refresh was refused, and is believed + if got := ask("revoked@fake"); got != 0 { + t.Fatalf("revoked@fake's request went through: %d", got) + } + for deadline := time.Now().Add(10 * time.Second); !lapsed("revoked@fake"); time.Sleep(50 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("revoked@fake isn't marked though its plugin said its refresh was refused") + } + } + + // unknown: plugin-auth.json can't be read when the 401 comes + good, err := os.ReadFile(authPath) + if err != nil { + t.Fatal(err) + } + if got := ask("unknown@fake"); got != http.StatusUnauthorized { + t.Fatalf("unknown@fake's request: %d", got) + } + if err := os.WriteFile(authPath, good, 0o600); err != nil { + t.Fatal(err) + } + if lapsed("unknown@fake") { + t.Fatal("unknown@fake was marked while its sign-in couldn't be read") + } + if lapsed("first@fake") || lapsed("idle@fake") { + t.Fatal("an account no request failed was marked") + } +}