Files
magpie/internal/plugin/github_token_test.go
T
yetone 431707944e plugin, library: Check for updates asks GitHub with the GitHub token from Settings, and says when GitHub's rate limit is used up (#1942, bingqilinweimaotai)
What changed: a plugin installed from GitHub (github:owner/repo) is
checked by asking GitHub's API for its branch's commit (githubHead,
through fetchJSON). That request went without a token, so a token saved
in Settings → Network and sharing did nothing for it: the check stayed
at GitHub's 60 requests an hour for the whole address, which a shared
proxy exit uses up, and the row said only "<url>: 403 Forbidden".

- The token lookup, where a token may go and how a rate limit is told
  move from internal/library into a new internal/ghtoken, shared by the
  library and the plugin package (plugin can't import library).
  The order is unchanged: Settings, then GITHUB_TOKEN, then GH_TOKEN.
- plugin's fetchJSON has a request to GitHub's API's host (githubAPI)
  carry it, which covers the git plugins' check and the Plugins page's
  topic search. Raw files, npm and every other host never get it, and
  source.Do already sends nothing with Authorization to a mirror.
- An answer from GitHub's API that is a rate limit (429, or 403 with
  X-RateLimit-Remaining 0, Retry-After or a rate-limit message) is a
  ghtoken.Limited: the check's row has Why "limited" and Limited {until,
  token} for the page, as the library's skill check already had. A 401
  to a request with a token names which token was refused, never the
  token.

What was run:
- TestGitPluginCheckCarriesGitHubToken (new, internal/plugin): asks with
  no token / GH_TOKEN / GITHUB_TOKEN / Settings in that order of
  precedence, a 403 rate limit with and without a token, a 429 with
  Retry-After, a refused GH_TOKEN, and a raw-file host that must get no
  Authorization. Broken by hand twice: with fetchJSON's Authorize removed
  it fails "GH_TOKEN: GitHub's API was asked with Authorization "", want
  "Bearer gh-env"" (and the other two sources); with the limit check
  removed it fails with Why "registry", Limited nil, "403 Forbidden".
- go test -tags nogui -count=1 ./internal/library ./internal/plugin
  (temp HOME, pinned caches): ok, the library's TestGitHubToken*,
  TestGitHubRateLimitSaid among them.
- gofmt -l clean; go vet -tags nogui on darwin, GOOS=linux and
  GOOS=windows for internal/plugin, library, ghtoken, gui: clean.
- Not tried against the real api.github.com (tests stay off the network).
2026-10-13 15:19:53 +08:00

172 lines
5.3 KiB
Go

package plugin
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
// bingqilinweimaotai (#1942): a GitHub token saved in Settings did nothing
// for Check for updates of a plugin installed from GitHub, which kept
// asking GitHub's API without one, 60 an hour for a whole shared address.
// The check asks with the token from Settings, else GITHUB_TOKEN, else
// GH_TOKEN; a used-up rate limit says so, with when it lifts, and a token
// GitHub refuses says which one; raw files on another host never get it.
func TestGitPluginCheckCarriesGitHubToken(t *testing.T) {
dir := t.TempDir()
t.Setenv("HOME", dir)
t.Setenv("USERPROFILE", dir)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
var mu sync.Mutex
var auth []string
var answer func(w http.ResponseWriter) bool
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
auth = append(auth, r.Header.Get("Authorization"))
a := answer
mu.Unlock()
if r.URL.Path != "/repos/me/opencode-x-auth/commits" {
http.NotFound(w, r)
return
}
if a != nil && a(w) {
return
}
fmt.Fprint(w, `[{"sha":"abc1234def5678abc1234def5678abc1234def56"}]`)
}))
t.Cleanup(api.Close)
was := githubAPI
githubAPI = api.URL
t.Cleanup(func() { githubAPI = was })
lastAuth := func() string {
mu.Lock()
defer mu.Unlock()
if len(auth) == 0 {
return "(not asked)"
}
return auth[len(auth)-1]
}
setToken := func(tok string) {
s := settings.Load()
s.GitHubToken = tok
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
}
// a plugin bun installed from github:me/opencode-x-auth at abc1234
const spec = "github:me/opencode-x-auth"
if err := save(List{Plugins: []Entry{{Spec: spec}}}); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(Dir(), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(Dir(), "package.json"), []byte(`{"dependencies":{"opencode-x-auth":"`+spec+`"}}`), 0o644); err != nil {
t.Fatal(err)
}
installedAt(t, "opencode-x-auth", "0.1.0")
if err := os.WriteFile(filepath.Join(Target(spec), ".bun-tag"), []byte("me-opencode-x-auth-abc1234\n"), 0o644); err != nil {
t.Fatal(err)
}
check := func() VersionCheck {
t.Helper()
cs := CheckNow(context.Background()).Plugins
if len(cs) != 1 {
t.Fatalf("checked %+v", cs)
}
return cs[0]
}
for _, c := range []struct{ name, setting, github, gh, want string }{
{"none", "", "", "", ""},
{"GH_TOKEN", "", "", "gh-env", "Bearer gh-env"},
{"GITHUB_TOKEN", "", "github-env", "gh-env", "Bearer github-env"},
{"settings", "ghp_settings", "github-env", "gh-env", "Bearer ghp_settings"},
} {
t.Setenv("GITHUB_TOKEN", c.github)
t.Setenv("GH_TOKEN", c.gh)
setToken(c.setting)
if got := check(); got.Status != "current" {
t.Errorf("%s: %+v", c.name, got)
}
if a := lastAuth(); a != c.want {
t.Errorf("%s: GitHub's API was asked with Authorization %q, want %q", c.name, a, c.want)
}
}
// the rate limit used up: said, with when it lifts, the token never
reset := time.Date(2030, 1, 2, 3, 4, 0, 0, time.UTC)
mu.Lock()
answer = func(w http.ResponseWriter) bool {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Reset", fmt.Sprint(reset.Unix()))
w.WriteHeader(403)
fmt.Fprint(w, `{"message":"API rate limit exceeded for 1.2.3.4."}`)
return true
}
mu.Unlock()
c := check()
if c.Status != "unknown" || c.Why != "limited" || c.Limited == nil || !c.Limited.Token || c.Limited.Until != "2030-01-02T03:04:00Z" {
t.Fatalf("limited, with a token: %+v %+v", c, c.Limited)
}
if !strings.Contains(c.Error, "rate limit for your GitHub token") || strings.Contains(c.Error, "ghp_settings") {
t.Errorf("limited, with a token: %q", c.Error)
}
setToken("")
t.Setenv("GITHUB_TOKEN", "")
t.Setenv("GH_TOKEN", "")
if c = check(); c.Limited == nil || c.Limited.Token || !strings.Contains(c.Error, "Add a GitHub token in Settings") {
t.Errorf("limited, without a token: %+v %+v", c, c.Limited)
}
// a secondary limit: 429 with Retry-After
mu.Lock()
answer = func(w http.ResponseWriter) bool {
w.Header().Set("Retry-After", "60")
w.WriteHeader(429)
return true
}
mu.Unlock()
if c = check(); c.Why != "limited" || c.Limited == nil || c.Limited.Until == "" {
t.Errorf("secondary limit: %+v %+v", c, c.Limited)
}
// a token GitHub refuses: which one, not the token
t.Setenv("GH_TOKEN", "bad-token")
mu.Lock()
answer = func(w http.ResponseWriter) bool {
w.WriteHeader(401)
fmt.Fprint(w, `{"message":"Bad credentials"}`)
return true
}
mu.Unlock()
if c = check(); c.Limited != nil || !strings.Contains(c.Error, "GitHub refused GH_TOKEN") || strings.Contains(c.Error, "bad-token") {
t.Errorf("refused: %+v", c)
}
// another host (raw files) never gets the token
var rawAuth string
raw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rawAuth = r.Header.Get("Authorization")
fmt.Fprint(w, `{}`)
}))
t.Cleanup(raw.Close)
if _, err := fetchJSON(context.Background(), raw.URL+"/me/opencode-x-auth/HEAD/package.json", 1<<10); err != nil {
t.Fatal(err)
}
if rawAuth != "" {
t.Errorf("a host other than GitHub's API was sent Authorization %q", rawAuth)
}
}