Files
magpie/internal/gateway/codex_reset_api_test.go
T
yetone 5ee5274bd9 quotas: a remote magpie's Codex reset is used from its card here (#3850)
prgrmrwy runs magpie on a home server and uses it from work through a
remote magpie (and DSH). The remote Codex card said "1 reset", but the
reset could only be used from the GUI of the computer that holds the
sign-in.

What changed:
- Gateway: POST /v1/magpie/quotas/codex-reset?user=<email>[&credit=<id>]
  (Server.codexReset) spends one of that account's resets with
  provider.SpendCodexReset. That is the Usage page's own code
  (UseCodexResetCard, then AwaitAllowance), moved out of
  internal/gui/usage.go so both use it. A reset can't be undone, so the
  route needs an enabled gateway key with full access, from loopback too.
  No key gets 401, and that covers every corsGuard exemption that has no
  key: Origin null, app schemes, *.localhost and a missing Origin. A
  read-only key gets 403 gateway_key_read_only (readOnlyGuard, which
  readOnlyRefused now lists, and again in the handler). A held key gets
  403 gateway_key_held, even one told quotas. The account must be named
  (400 otherwise). One ask runs per account at a time (409). When the
  reset is used, that card is read again.
- Remote client: UseRemoteCodexReset (remote_quotas.go) asks the remote
  with the provider's key. remoteJSON's status mapping is shared through
  remoteBody. A read-only key there is told as such, and a 404 as a
  remote too old. With no answer in time it says the reset may have been
  used, and it never asks again by itself. A remote Codex card now keeps
  its Resets; a GLM team's (byWindow) and every check-in are still
  dropped.
- GUI: "Use a reset" / "Use one..." show on a remote Codex card
  (codexResetCard). They open the same in-app confirmation sheet, with a
  line saying which computer's magpie uses it, and send the card's
  provider to /api/usage/codex-reset. The remote's errors are put in the
  user's words. New strings are in all 5 languages.
- DSH: no code here. Its provider plugin reads /v1/magpie/quotas/cards
  and can call the new route with a full key.
- resetOutcome (a reset's result in words) moved from app.js into
  resetask.js, the only place that says it, so the core's scripts stay
  in TestCoreScriptBudget's 1,533,802 with no raise (1,533,003 after;
  origin/main b967b1620 is 1,533,756).
- Docs: reference.md (remote quotas, gateway keys), gateway-routing.md
  (read-only list, the route's admission), providers-accounts.md.

What was run (rebased on origin/main b967b1620, then on 2e4735f8f):
- mote, at the head before the rebase and the resetOutcome move:
  go test -count=1 -timeout 45m ./internal/provider ./internal/gateway
  ./internal/gui at load ~300-450. provider ok. gateway: only
  TestCompactionOverByteCapEveryTime (#4862). gui: TestCoreScriptBudget
  (this change, 158 bytes over; fixed by the move), TestMainWindowCorners
  (#3949) and TestGatewaySkewOfAnotherIsSaidNotQuit/own_build (#5053,
  passes alone here and at b967b1620).
- mote, same run: 155 GUI files (reset|quota|usage-|panel-|i18n|budget|
  remote|gui-|old-webkit|core-script|script-size), 1856 of 1904 pass.
- WSL (magpie-desktop), the 9 red files alone, at this change and at
  origin/main b967b1620: this change 147 pass / 43 fail, main 146 / 44;
  every test red here is red on main too: codex-auto-reset webkit de
  (#4790), remote-magpie (#4398), usage-agents-hide (#3414), usage-fold
  (#3415, #4790), usage-heatmap (#4718), usage-ledger (#5048).
  codex-reset-lead (#5054) and panel-routing-providers (#5055) were red
  only under mote's load and pass alone on both.
- mote, at this head: TestCoreScriptBudget and
  TestGatewaySkewOfAnotherIsSaidNotQuit ok.
- WSL, at this head: account-every-reset, codex-resets-used, i18n-keys,
  providers-reset-use, remote-codex-reset, reset-each-title,
  reset-pick-card, reset-providers, quota-used-no-reset: 99 of 102 pass.
  The 3 reds are providers-reset-use's 420px Windows cases ("a click
  moved the page", #4873); that file alone is red on origin/main
  b967b1620 too (3 of 40 there, 2 of 40 here).
- WSL, rebased on 2e4735f8f (main had changed internal/gateway): the new
  tests and the read-only, CORS, LAN-guard, held-key, remote-magpie and
  UseCodexResetCard tests in ./internal/gateway ./internal/provider ok;
  core scripts 1,532,960 under 1,533,802; gofmt clean.
- Earlier on mote: TestCodexResetNeedsAFullKey,
  TestRemoteCodexResetThroughTheGateway, TestRemoteCodexResetAnswers, the
  read-only, CORS, LAN-guard, held-key and remote-magpie tests ok;
  remote-codex-reset and reset-pick-card 20 of 20 (chromium and webkit,
  5 languages, 900/390/440px). gofmt clean; go vet darwin, windows ok,
  linux for provider and gateway.

Broken by hand:
- With the handler's key check turned off, TestCodexResetNeedsAFullKey
  went red: "this computer, no key: 200 {code: reset}" and a reset was
  spent.
- With codexResetCard put back to provider === "codex",
  remote-codex-reset.test.cjs went red ("one Use, on the remote Codex
  card"). On the old code the route doesn't exist, so the full-key case
  gets 404.

Not tried:
- A real Codex reset spent between two real magpies: none was spent, to
  keep the owner's resets. The ChatGPT backend is the fake from
  codex_autoreset_test.
- DSH's plugin calling the route.
- GOOS=linux vet of internal/gui: it needs gtk4/webkitgtk, which neither
  mote nor magpie-desktop has. Its change is usage.go only, and that was
  vetted on darwin and windows.

Thanks to prgrmrwy for the report and the proposal.
2026-11-03 17:12:25 +08:00

174 lines
6.9 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// #3850 (prgrmrwy): magpie runs on a home server, and the office's remote
// magpie card (or DSH's, reading the cards) said "1 reset" with no way to
// use it but walking to the server. POST /v1/magpie/quotas/codex-reset
// spends it there, through the Usage page's own code. A reset can't be
// undone, so only a gateway key with full access spends one: never a
// request with no key, from this computer or a page or app the gateway
// lets in on loopback without one, nor a read-only key or a held one.
func TestCodexResetNeedsAFullKey(t *testing.T) {
codexSignedIn(t)
t.Setenv("MAGPIE_ADDR", "")
b := newResetBackend(t, "acct-1")
keys, secrets := newCaller(t, "Full", "Read only", "Held")
if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("limit-key", access.Change{Key: keys[2].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil {
t.Fatal(err)
}
h := lanGuard(New().Handler())
path := provider.RemoteCodexResetPath + "?user=" + url.QueryEscape("me@example.com")
do := func(path, from, host, origin, secret string) (int, string) {
t.Helper()
r := httptest.NewRequest("POST", path, nil)
r.RemoteAddr = from
r.Host = host
if origin != "" {
r.Header.Set("Origin", origin)
r.Header.Set("Sec-Fetch-Site", "cross-site")
r.Header.Set("Sec-Fetch-Mode", "cors")
r.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/27.2 Safari/605.1.15")
}
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w.Code, w.Body.String()
}
const loop, lan, gw = "127.0.0.1:50123", "192.168.1.9:5000", "127.0.0.1:3425"
refused := []struct {
why string
from, host, origin, secret string
}{
{"this computer, no key", loop, gw, "", ""},
{"a sandboxed frame (Origin null), no key", loop, gw, "null", ""},
{"an app's scheme, no key", loop, gw, "tauri://localhost", ""},
{"a *.localhost page, no key", loop, gw, "http://evil.localhost:8080", ""},
{"a rebound page (its own Host), no key", loop, "evil.example:3425", "", ""},
{"a foreign page, no key", loop, gw, "https://evil.example", ""},
{"a foreign page with the full key", loop, gw, "https://evil.example", secrets[0]},
{"another machine, no key", lan, gw, "", ""},
{"another machine, a wrong key", lan, gw, "", "sk-magpie-wrong"},
{"a read-only key", lan, gw, "", secrets[1]},
{"a read-only key, this computer", loop, gw, "", secrets[1]},
{"a held key", lan, gw, "", secrets[2]},
}
for _, c := range refused {
if code, body := do(path, c.from, c.host, c.origin, c.secret); code < 400 || code == http.StatusNotFound || strings.Contains(body, `"code":"reset"`) {
t.Errorf("%s: %d %s", c.why, code, body)
}
if _, spent := b.seen(); spent != "" {
t.Fatalf("%s spent a reset of %s", c.why, spent)
}
}
if code, body := do(provider.RemoteCodexResetPath, lan, gw, "", secrets[0]); code != http.StatusBadRequest || !strings.Contains(body, "name the Codex account") {
t.Fatalf("no account named: %d %s", code, body)
}
if code, body := do(path, lan, gw, "", secrets[1]); code != http.StatusForbidden || !strings.Contains(body, ReadOnlyCode) {
t.Fatalf("read-only key: %d %s", code, body)
}
if code, body := do(path, lan, gw, "", secrets[2]); code != http.StatusForbidden || !strings.Contains(body, provider.KeyHeldCode) {
t.Fatalf("held key: %d %s", code, body)
}
if _, spent := b.seen(); spent != "" {
t.Fatalf("spent before the full key asked: %s", spent)
}
// the full key, from another machine: one reset, of the account named
code, body := do(path, lan, gw, "", secrets[0])
var out provider.ResetOutcome
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.Code != "reset" || out.Windows != 2 {
t.Fatalf("full key: %d %s", code, body)
}
if _, spent := b.seen(); spent != "acct-1" {
t.Fatalf("spent %q, want acct-1 once", spent)
}
// none left: said so, nothing more spent
code, body = do(path, loop, gw, "", secrets[0])
if code != 200 || json.Unmarshal([]byte(body), &out) != nil || out.Code != "no_credit" {
t.Fatalf("none left: %d %s", code, body)
}
if _, spent := b.seen(); spent != "acct-1" {
t.Fatalf("spent %q after none was left", spent)
}
}
// The office's magpie spends the home server's reset through its remote
// magpie provider (#3850): the card here keeps the remote's resets, and
// using one asks the remote with the provider's key. A read-only key there
// says so in words the card can show.
func TestRemoteCodexResetThroughTheGateway(t *testing.T) {
codexSignedIn(t)
t.Setenv("MAGPIE_ADDR", "")
provider.ForgetRemoteCardsForTest()
t.Cleanup(provider.ForgetRemoteCardsForTest)
b := newResetBackend(t, "acct-1")
keys, secrets := newCaller(t, "Office", "Viewer")
if _, err := access.Update("access-key", access.Change{Key: keys[1].ID, ReadOnly: true}); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(lanGuard(New().Handler()))
defer srv.Close()
ctx := context.Background()
save := func(secret string) {
t.Helper()
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: secret, Chat: srv.URL}); err != nil {
t.Fatal(err)
}
provider.ForgetRemoteCardsForTest()
}
save(secrets[1])
if _, err := provider.UseRemoteCodexReset(ctx, "office/codex", "me@example.com", ""); err == nil || !strings.Contains(err.Error(), "read-only") {
t.Fatalf("read-only key: %v", err)
}
if _, err := provider.UseRemoteCodexReset(ctx, "office/codex", "", ""); err == nil {
t.Fatal("no account named was asked")
}
if _, err := provider.UseRemoteCodexReset(ctx, "office/bal", "me@example.com", ""); err == nil {
t.Fatal("a card not Codex's was asked")
}
if _, spent := b.seen(); spent != "" {
t.Fatalf("spent %q before a full key asked", spent)
}
save(secrets[0])
// the remote's card, read there, carries its reset here
provider.RefreshUsage(ctx, "office", "")
var card *provider.SubscriptionQuota
for _, q := range provider.RemoteCards(ctx) {
if q.Provider == "office/codex" {
card = &q
}
}
if card == nil || card.Resets == nil || card.Resets.Count != 1 || card.User != "me@example.com" || card.Checkins {
t.Fatalf("office/codex: %+v", card)
}
out, err := provider.UseRemoteCodexReset(ctx, "office/codex", card.User, "")
if err != nil || out.Code != "reset" {
t.Fatalf("full key: %+v %v", out, err)
}
if _, spent := b.seen(); spent != "acct-1" {
t.Fatalf("spent %q, want acct-1 once", spent)
}
// read again after: the card shows none left
for _, q := range provider.RemoteCards(ctx) {
if q.Provider == "office/codex" && q.Resets != nil && q.Resets.Count != 0 {
t.Fatalf("after the reset: %+v", q.Resets)
}
}
}