Files
magpie/internal/ghtoken/ghtoken.go
T
yetone 0f044e9447 plugins: a GITHUB_TOKEN GitHub refuses is dropped for anonymous requests, not shown as an error (till on Discord)
till's Plugins page said "无法连接 GitHub: GitHub refused GITHUB_TOKEN
(no GitHub token is set in Settings → Network and sharing)". ghtoken.Token
falls back to the environment's GITHUB_TOKEN / GH_TOKEN, and a stale one
there made every GitHub read fail, though GitHub serves the same reads
without a token.

ghtoken.Do now sends a GitHub API request with the token. When the token
came from the environment and GitHub answers 401, it remembers that token
as refused for the rest of the process (Token() skips it, so GH_TOKEN is
still tried after a refused GITHUB_TOKEN, and Settings no longer shows it)
and asks once more without Authorization, returning that answer. A token
set in Settings is never dropped: its 401 is still Refused()'s error. An
anonymous rate limit after the drop is said by LimitedBy as before.

Every caller goes through it: plugin fetchJSONFrom (tagged-repo search,
git plugin checks, githubHead) and getURLFrom (Bun), and library apiGet,
skills fetch, skilltree fetchBlob and latestRTK via doGitHub.
internal/davsync/github.go stays strict: its token is the one the user gave
sync to write a private repo, outside ghtoken, and an anonymous retry can't
write there, so it would only hide why sync failed.

Tests (httptest only): ghtoken_test covers an env token refused then asked
again without, not sent again (and GH_TOKEN tried next), a Settings token
refused stays an error, an env token refused then an anonymous rate limit
is reported, and another host untouched. plugin TestTaggedReposStaleEnvTokenDropped
is till's case: TaggedRepos with GITHUB_TOKEN=stale-till lists 7 repos, no
error. github_token_test and library TestGitHubRateLimitSaid now expect the
env token dropped and the Settings token still refused.

Broken by hand, each red: (a) no anonymous retry: every new env test, the
plugin and library tests red, and TestTaggedReposStaleEnvTokenDropped shows
till's exact error; (b) no memory of the refusal: NotSentAgain, the plugin
and library tests red; (c) a Settings token also retried:
SettingsTokenRefusedStaysAnError, the plugin and library tests red.

Run on the commit before the rebase (base 9b04c4e20):
- gofmt -l: clean. go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows: clean.
- set -o pipefail; go test -timeout 45m ./... at load ~30: 62 packages ok.
  agent, gateway and library ran past 45m while still progressing; gui
  failed TestSetAnswersWhileDevinAndProvidersHang (set took 10.26s, #1375)
  and TestMainWindowCorners (measuring killed, #1936/#2645); provider failed
  TestPluginPicksComeBackWithTheirList (#3051, fixed on main in c922225f1).
- Each rerun alone at load 21-56: library ok 809.7s, provider ok 308.8s,
  gui ok 159.5s, agent ok 1673.3s, gateway ok 780.4s.

After rebasing onto a3ebed202 (main moved 8 commits): gofmt -l clean; go vet
darwin, linux -tags nogui, windows clean; go test -count=1 at load ~57:
ghtoken ok 2.9s, plugin ok 277.6s, library ok 144.2s.
2026-10-21 06:16:31 +08:00

179 lines
6.1 KiB
Go

// Package ghtoken has magpie's requests to GitHub's REST API carry the
// user's GitHub token, and says plainly when GitHub turns them away.
//
// GitHub's API answers an address 60 requests an hour without a token,
// which a check of a few repositories, or a network shared with others,
// uses up; with a token it answers 5,000 an hour. The token is the one set
// in Settings (GitHubToken), else GITHUB_TOKEN or GH_TOKEN from the
// environment. It goes to GitHub's API's host alone, never to codeload, raw
// files or a mirror (source.Do sends no request with Authorization to one),
// and is never written to a log or an error. The library's skills and the
// Plugins page's git plugins both ask GitHub through here (#1942).
//
// A token from the environment that GitHub refuses (401) is one the user
// may not know is there, often stale: the request is asked again without
// it, and the token isn't sent again while magpie runs (till on Discord).
// The token set in Settings is the user's own choice, so a refusal of it
// is said (Refused).
package ghtoken
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/settings"
)
// Env names the environment variables a token is taken from when Settings
// has none, in the order they are looked at.
var Env = []string{"GITHUB_TOKEN", "GH_TOKEN"}
// Token is the token requests to GitHub's API carry, and where it came
// from: "settings", the environment variable's name, or "" for none.
// An environment variable's token GitHub refused isn't one: the next
// variable's is, or none.
func Token() (token, from string) {
if t := strings.TrimSpace(settings.Load().GitHubToken); t != "" {
return t, "settings"
}
for _, k := range Env {
if t := strings.TrimSpace(os.Getenv(k)); t != "" && !isRefused(t) {
return t, k
}
}
return "", ""
}
// refused holds the environment's tokens GitHub answered 401, for as long
// as magpie runs: keyed by the token, so a variable set to another one is
// tried afresh.
var refused = struct {
sync.Mutex
m map[string]bool
}{m: map[string]bool{}}
func isRefused(t string) bool {
refused.Lock()
defer refused.Unlock()
return refused.m[t]
}
func markRefused(t string) {
refused.Lock()
refused.m[t] = true
refused.Unlock()
}
// Do sends req with send, carrying the token as Authorize does, and says
// whether the answer given back is to a request that carried it. When
// GitHub refuses (401) a token from the environment, that token is
// dropped for the rest of the run and req is sent again without it: the
// anonymous answer is the one given back. A refused token from Settings
// is answered as GitHub answered, for the caller to say Refused().
func Do(req *http.Request, api string, send func(*http.Request) (*http.Response, error)) (*http.Response, bool, error) {
t, from := authorize(req, api)
resp, err := send(req)
if err != nil || t == "" || from == "settings" || resp.StatusCode != http.StatusUnauthorized {
return resp, t != "" && err == nil, err
}
again := req.Clone(req.Context())
if req.Body != nil && req.Body != http.NoBody {
if req.GetBody == nil {
return resp, true, nil
}
b, err := req.GetBody()
if err != nil {
return resp, true, nil
}
again.Body = b
}
markRefused(t)
io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
again.Header.Del("Authorization")
resp, err = send(again)
return resp, false, err
}
// Authorize has req carry the token, if there is one and req goes to the
// host of api (GitHub's API's base URL, which tests move); it says whether
// it did.
//
// Do is Authorize with an environment token GitHub refuses dropped for an
// anonymous request; a caller sends through it rather than this.
func Authorize(req *http.Request, api string) bool {
t, _ := authorize(req, api)
return t != ""
}
// authorize is Authorize, saying which token req carries and where it came
// from, or "" for none.
func authorize(req *http.Request, api string) (token, from string) {
u, err := url.Parse(api)
if err != nil || u.Host == "" || req.URL == nil || req.URL.Host == "" || !strings.EqualFold(req.URL.Host, u.Host) {
return "", ""
}
t, from := Token()
if t == "" {
return "", ""
}
req.Header.Set("Authorization", "Bearer "+t)
return t, from
}
// Refused is the error for a 401 from GitHub to a request that carried the
// token: which token it was, never the token itself.
func Refused() error {
_, from := Token()
where := "the GitHub token in Settings → Network and sharing"
if from != "settings" {
where = from + " (no GitHub token is set in Settings → Network and sharing)"
}
return fmt.Errorf("GitHub refused %s: it may have expired or been revoked", where)
}
// Limited is GitHub turning requests away for a while: until when (zero
// when GitHub didn't say), and whether the requests carried a token.
type Limited struct {
Until time.Time
Token bool
}
func (e Limited) Error() string {
when := "for a while"
if !e.Until.IsZero() {
when = "until " + e.Until.Local().Format("15:04")
}
if e.Token {
return "GitHub's rate limit for your GitHub token is used up " + when + "; try again then"
}
return "GitHub's rate limit for requests without a token (60 an hour) is used up " + when +
". Add a GitHub token in Settings → Network and sharing to raise it to 5,000 an hour"
}
// LimitedBy is the Limited a refusal of GitHub's says, or false when it
// isn't one: 429, or 403 with the limit spent or a secondary limit's
// Retry-After or message. A 403 for anything else (a token without access)
// isn't one.
func LimitedBy(resp *http.Response, body []byte, token bool) (Limited, bool) {
msg := strings.ToLower(string(body))
if resp.StatusCode != 429 && (resp.StatusCode != 403 || resp.Header.Get("X-RateLimit-Remaining") != "0" &&
resp.Header.Get("Retry-After") == "" && !strings.Contains(msg, "rate limit")) {
return Limited{}, false
}
e := Limited{Token: token}
if n, err := strconv.ParseInt(resp.Header.Get("X-RateLimit-Reset"), 10, 64); err == nil && n > 0 {
e.Until = time.Unix(n, 0)
} else if s, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil && s > 0 {
e.Until = time.Now().Add(time.Duration(s) * time.Second)
}
return e, true
}