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.
This commit is contained in:
yetone
2026-10-21 06:16:31 +08:00
parent f21dd99f5a
commit 0f044e9447
13 changed files with 389 additions and 36 deletions
+76 -5
View File
@@ -9,15 +9,23 @@
// 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"
@@ -29,32 +37,95 @@ 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 != "" {
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 false
return "", ""
}
t, _ := Token()
t, from := Token()
if t == "" {
return false
return "", ""
}
req.Header.Set("Authorization", "Bearer "+t)
return true
return t, from
}
// Refused is the error for a 401 from GitHub to a request that carried the
+184
View File
@@ -0,0 +1,184 @@
package ghtoken
import (
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// fakeAPI is GitHub's API answering 401 to every token but good, and
// answer (200 when nil) otherwise; it keeps the Authorization of each
// request.
type fakeAPI struct {
*httptest.Server
mu sync.Mutex
auth []string
good string
answer func(w http.ResponseWriter)
}
func newFakeAPI(t *testing.T) *fakeAPI {
f := &fakeAPI{}
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
a := r.Header.Get("Authorization")
f.mu.Lock()
f.auth = append(f.auth, a)
good, answer := f.good, f.answer
f.mu.Unlock()
if a != "" && a != "Bearer "+good {
w.WriteHeader(401)
fmt.Fprint(w, `{"message":"Bad credentials"}`)
return
}
if answer != nil {
answer(w)
return
}
fmt.Fprint(w, `{"ok":true}`)
}))
t.Cleanup(f.Close)
return f
}
func (f *fakeAPI) asked() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.auth...)
}
func (f *fakeAPI) get(t *testing.T) (*http.Response, bool, []byte) {
t.Helper()
req, _ := http.NewRequest("GET", f.URL+"/repos/o/r/commits", nil)
resp, token, err := Do(req, f.URL, http.DefaultClient.Do)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp, token, b
}
func setToken(t *testing.T, settingsTok, githubTok, ghTok string) {
t.Helper()
s := settings.Load()
s.GitHubToken = settingsTok
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
t.Setenv("GITHUB_TOKEN", githubTok)
t.Setenv("GH_TOKEN", ghTok)
}
// till on Discord: a stale GITHUB_TOKEN in the environment made the
// Plugins page say "GitHub refused GITHUB_TOKEN" while GitHub answered
// fine without it. The request is asked again without the token, and the
// anonymous answer is the one given back.
func TestEnvTokenRefusedAskedAgainWithout(t *testing.T) {
f := newFakeAPI(t)
setToken(t, "", "stale-env-retry", "")
resp, token, body := f.get(t)
if resp.StatusCode != 200 || token || string(body) != `{"ok":true}` {
t.Fatalf("got %d token=%v %s", resp.StatusCode, token, body)
}
if a := f.asked(); len(a) != 2 || a[0] != "Bearer stale-env-retry" || a[1] != "" {
t.Errorf("GitHub was asked with %q, want the token then none", a)
}
}
// Once refused, the environment's token isn't sent again: the next
// request goes without it at once, and Token says there is none.
func TestEnvTokenRefusedNotSentAgain(t *testing.T) {
f := newFakeAPI(t)
setToken(t, "", "stale-env-once", "")
f.get(t)
n := len(f.asked())
resp, token, _ := f.get(t)
if resp.StatusCode != 200 || token {
t.Fatalf("second request: %d token=%v", resp.StatusCode, token)
}
if a := f.asked()[n:]; len(a) != 1 || a[0] != "" {
t.Errorf("after the refusal GitHub was asked with %q, want one request without a token", a)
}
if tok, from := Token(); tok != "" || from != "" {
t.Errorf("Token() = %q from %q after its refusal", tok, from)
}
// GH_TOKEN, a different token, is still tried
t.Setenv("GH_TOKEN", "good-gh")
f.mu.Lock()
f.good = "good-gh"
f.mu.Unlock()
if _, token, _ := f.get(t); !token {
t.Error("GH_TOKEN wasn't sent after GITHUB_TOKEN was refused")
}
}
// The token set in Settings is the user's own choice: its refusal comes
// back as GitHub's 401, asked once, and Refused names it.
func TestSettingsTokenRefusedStaysAnError(t *testing.T) {
f := newFakeAPI(t)
setToken(t, "ghp_settings_bad", "", "")
resp, token, _ := f.get(t)
if resp.StatusCode != 401 || !token {
t.Fatalf("got %d token=%v, want 401 with the token", resp.StatusCode, token)
}
if a := f.asked(); len(a) != 1 || a[0] != "Bearer ghp_settings_bad" {
t.Errorf("GitHub was asked with %q", a)
}
err := Refused()
if !strings.Contains(err.Error(), "the GitHub token in Settings") || strings.Contains(err.Error(), "ghp_settings_bad") {
t.Errorf("Refused() = %v", err)
}
// and it is sent again next time: Settings' token is never dropped
f.get(t)
if a := f.asked(); len(a) != 2 || a[1] != "Bearer ghp_settings_bad" {
t.Errorf("Settings' token wasn't sent again: %q", a)
}
}
// The anonymous request, rate limited, is said as GitHub's limit for
// requests without a token, as before.
func TestEnvTokenRefusedThenAnonymousLimited(t *testing.T) {
f := newFakeAPI(t)
f.answer = func(w http.ResponseWriter) {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Reset", "1893553440")
w.WriteHeader(403)
fmt.Fprint(w, `{"message":"API rate limit exceeded for 1.2.3.4."}`)
}
setToken(t, "", "", "stale-env-limited")
resp, token, body := f.get(t)
e, ok := LimitedBy(resp, body, token)
if !ok || e.Token || e.Until.IsZero() {
t.Fatalf("LimitedBy = %+v %v (status %d)", e, ok, resp.StatusCode)
}
var l Limited
if err := error(e); !errors.As(err, &l) || !strings.Contains(err.Error(), "60 an hour") {
t.Errorf("limit said as %q", err)
}
}
// A request to another host never carries the token, and its 401 is left
// as it is.
func TestOtherHostUntouched(t *testing.T) {
f := newFakeAPI(t)
setToken(t, "", "env-other-host", "")
req, _ := http.NewRequest("GET", f.URL+"/x", nil)
resp, token, err := Do(req, "https://api.github.invalid", http.DefaultClient.Do)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if token || resp.StatusCode != 200 {
t.Errorf("got %d token=%v", resp.StatusCode, token)
}
if a := f.asked(); len(a) != 1 || a[0] != "" {
t.Errorf("another host was asked with %q", a)
}
}
+10
View File
@@ -0,0 +1,10 @@
package ghtoken
import (
"testing"
"github.com/yetone/magpie/internal/testenv"
)
// The tests run in a home of their own, so Settings is theirs.
func TestMain(m *testing.M) { testenv.Main(m) }
+8
View File
@@ -24,6 +24,14 @@ func GitHubToken() (token, from string) { return ghtoken.Token() }
// GitHub's API (githubAPI's host); it says whether it did.
func withGitHubToken(req *http.Request) bool { return ghtoken.Authorize(req, githubAPI) }
// doGitHub sends req with send, carrying the token as withGitHubToken
// does, and says whether the answer is to a request that carried it: an
// environment token GitHub refuses is dropped and req sent again without
// it (ghtoken.Do).
func doGitHub(req *http.Request, send func(*http.Request) (*http.Response, error)) (*http.Response, bool, error) {
return ghtoken.Do(req, githubAPI, send)
}
// errLimited is GitHub turning requests away for a while.
type errLimited = ghtoken.Limited
+30 -3
View File
@@ -201,8 +201,11 @@ func TestGitHubRateLimitSaid(t *testing.T) {
t.Errorf("secondary limit: %+v %+v", c, c.Limited)
}
// a token GitHub refuses says which one
// a token GitHub refuses says which one when it is Settings'
g.answer = func(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Authorization") == "" {
return false
}
w.WriteHeader(401)
fmt.Fprint(w, `{"message":"Bad credentials"}`)
return true
@@ -211,12 +214,36 @@ func TestGitHubRateLimitSaid(t *testing.T) {
if c.Limited != nil || c.Error != "GitHub refused the GitHub token in Settings → Network and sharing: it may have expired or been revoked" {
t.Errorf("refused: %+v", c)
}
// one from the environment (till on Discord: a stale GITHUB_TOKEN)
// is dropped: the check is asked again without it, and isn't sent
// again
setGitHubToken(t, "")
t.Setenv("GH_TOKEN", "bad")
t.Setenv("GH_TOKEN", "bad-env-skills")
g.mu.Lock()
n := len(g.apiAuth)
g.mu.Unlock()
c = check(t)["pdf"]
if !strings.Contains(c.Error, "GitHub refused GH_TOKEN") || strings.Contains(c.Error, "bad") {
if c.Error != "" || c.Limited != nil || c.Commit == "" {
t.Errorf("refused from the environment: %+v", c)
}
g.mu.Lock()
if a := g.apiAuth[n:]; len(a) < 2 || a[0] != "Bearer bad-env-skills" || a[1] != "" {
t.Errorf("refused from the environment: GitHub was asked with %q, want the token then none", a)
}
n = len(g.apiAuth)
g.mu.Unlock()
c = check(t)["pdf"]
if c.Error != "" || c.Commit == "" {
t.Errorf("refused from the environment, checked again: %+v", c)
}
g.mu.Lock()
defer g.mu.Unlock()
for _, a := range g.apiAuth[n:] {
if a != "" {
t.Errorf("the refused GH_TOKEN was sent again: %q", g.apiAuth[n:])
break
}
}
}
// A folder asked about again is asked with the ETag GitHub gave, and its
+1 -2
View File
@@ -284,9 +284,8 @@ func latestRTK() (string, error) {
}
req, _ = http.NewRequest("GET", rtkReleasesAPI, nil)
req.Header.Set("User-Agent", "magpie")
withGitHubToken(req)
req.Header.Set("Accept", "application/vnd.github+json")
resp, err := source.Do(c, req)
resp, _, err := doGitHub(req, func(r *http.Request) (*http.Response, error) { return source.Do(c, r) })
if err != nil {
return "", err
}
+1 -2
View File
@@ -162,7 +162,6 @@ func apiGet(u string) ([]byte, int, bool, error) {
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("User-Agent", "magpie")
req.Header.Set("Accept", "application/vnd.github+json")
token := withGitHubToken(req)
etags.Lock()
had, cached := etags.m[u]
etags.Unlock()
@@ -170,7 +169,7 @@ func apiGet(u string) ([]byte, int, bool, error) {
req.Header.Set("If-None-Match", had.etag)
}
c := &http.Client{Timeout: 20 * time.Second}
resp, err := source.Do(c, req)
resp, token, err := doGitHub(req, func(r *http.Request) (*http.Response, error) { return source.Do(c, r) })
if err != nil {
return nil, 0, token, fmt.Errorf("couldn't reach GitHub: %w", err)
}
+1 -3
View File
@@ -770,9 +770,7 @@ func fetch(src Source) (string, error) {
get := func(u string) (*http.Response, bool, error) {
req, _ := http.NewRequest("GET", u, nil)
req.Header.Set("User-Agent", "magpie")
token := withGitHubToken(req)
resp, err := source.DoOfficial(c, req)
return resp, token, err
return doGitHub(req, func(r *http.Request) (*http.Response, error) { return source.DoOfficial(c, r) })
}
if tooBig.has(src) {
return fetchSkillFiles(src)
+3 -2
View File
@@ -253,8 +253,9 @@ func fetchBlob(c *http.Client, src Source, path, sha, dst string, exec bool) err
if accept != "" {
req.Header.Set("Accept", accept)
}
token = withGitHubToken(req)
return source.DoOfficial(c, req)
resp, t, err := doGitHub(req, func(r *http.Request) (*http.Response, error) { return source.DoOfficial(c, r) })
token = t
return resp, err
}
resp, err := get(rawURL(src.Repo, src.Ref, path), "")
if err != nil {
+6 -7
View File
@@ -285,13 +285,12 @@ func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]by
}
// Bun's newest release is asked of GitHub's API: with the user's
// GitHub token, as every request magpie makes to it is (#1942)
ghtoken.Authorize(req, githubAPI)
var res *http.Response
if mirror {
res, err = source.Do(http.DefaultClient, req)
} else {
res, err = source.DoOfficial(http.DefaultClient, req)
}
res, _, err := ghtoken.Do(req, githubAPI, func(r *http.Request) (*http.Response, error) {
if mirror {
return source.Do(http.DefaultClient, r)
}
return source.DoOfficial(http.DefaultClient, r)
})
if err != nil {
return nil, err
}
+26
View File
@@ -93,6 +93,11 @@ func fakeGitHub(t *testing.T, up *atomic.Bool, asked *atomic.Int32) {
if h := holding.Load(); h != nil && q.URL.Path == h.path {
<-h.go_
}
if q.Header.Get("Authorization") == "Bearer "+staleToken {
w.WriteHeader(401)
w.Write([]byte(`{"message":"Bad credentials"}`))
return
}
if !up.Load() || q.URL.Path == "/raw/someone/flaky-entry/main/index.js" {
http.Error(w, "down", 503)
return
@@ -486,6 +491,27 @@ func TestPkgEntry(t *testing.T) {
// couldn't be read and why, not that none are tagged (till on Discord:
// on their desktop the section wasn't there, on their server it had many).
// One read before is kept and isn't counted.
// staleToken is a token fakeGitHub answers 401, as GitHub does an
// expired one.
const staleToken = "stale-till"
// till on Discord: a stale GITHUB_TOKEN in the environment, which GitHub
// refuses, left the Plugins page's GitHub section saying "GitHub refused
// GITHUB_TOKEN" while GitHub answered fine without it. The search is
// asked again without the token, and the list is GitHub's.
func TestTaggedReposStaleEnvTokenDropped(t *testing.T) {
var up atomic.Bool
var asked atomic.Int32
up.Store(true)
fakeGitHub(t, &up, &asked)
t.Setenv("GITHUB_TOKEN", staleToken)
t.Setenv("GH_TOKEN", "")
l, err := TaggedRepos(context.Background())
if err != nil || len(l) != 7 {
t.Fatalf("with a stale GITHUB_TOKEN: %v, %d repos", err, len(l))
}
}
func TestTaggedReposUnreadable(t *testing.T) {
var up atomic.Bool
var asked atomic.Int32
+37 -9
View File
@@ -30,7 +30,7 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) {
var mu sync.Mutex
var auth []string
var answer func(w http.ResponseWriter) bool
var answer func(w http.ResponseWriter, r *http.Request) bool
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
auth = append(auth, r.Header.Get("Authorization"))
@@ -40,7 +40,7 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) {
http.NotFound(w, r)
return
}
if a != nil && a(w) {
if a != nil && a(w, r) {
return
}
fmt.Fprint(w, `[{"sha":"abc1234def5678abc1234def5678abc1234def56"}]`)
@@ -109,7 +109,7 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) {
// 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 {
answer = func(w http.ResponseWriter, r *http.Request) bool {
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("X-RateLimit-Reset", fmt.Sprint(reset.Unix()))
w.WriteHeader(403)
@@ -132,7 +132,7 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) {
}
// a secondary limit: 429 with Retry-After
mu.Lock()
answer = func(w http.ResponseWriter) bool {
answer = func(w http.ResponseWriter, r *http.Request) bool {
w.Header().Set("Retry-After", "60")
w.WriteHeader(429)
return true
@@ -142,18 +142,46 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) {
t.Errorf("secondary limit: %+v %+v", c, c.Limited)
}
// a token GitHub refuses: which one, not the token
t.Setenv("GH_TOKEN", "bad-token")
// a token GitHub refuses (401), answering without one: the token in
// Settings is said, by where it is, not the token
mu.Lock()
answer = func(w http.ResponseWriter) bool {
answer = func(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Authorization") == "" {
return false
}
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)
setToken("ghp_settings_refused")
if c = check(); c.Limited != nil || !strings.Contains(c.Error, "GitHub refused the GitHub token in Settings") || strings.Contains(c.Error, "ghp_settings_refused") {
t.Errorf("Settings' token refused: %+v", c)
}
setToken("")
// one from the environment (till on Discord: a stale GITHUB_TOKEN) is
// dropped, and the check asked again without it
t.Setenv("GH_TOKEN", "bad-token")
mu.Lock()
n := len(auth)
mu.Unlock()
if c = check(); c.Status != "current" || c.Error != "" {
t.Errorf("GH_TOKEN refused: %+v", c)
}
mu.Lock()
if a := auth[n:]; len(a) != 2 || a[0] != "Bearer bad-token" || a[1] != "" {
t.Errorf("GH_TOKEN refused: GitHub was asked with %q, want the token then none", a)
}
n = len(auth)
mu.Unlock()
if c = check(); c.Status != "current" {
t.Errorf("GH_TOKEN refused, checked again: %+v", c)
}
mu.Lock()
if a := auth[n:]; len(a) != 1 || a[0] != "" {
t.Errorf("GH_TOKEN refused, checked again: GitHub was asked with %q, want none", a)
}
mu.Unlock()
// another host (raw files) never gets the token
var rawAuth string
+6 -3
View File
@@ -241,9 +241,12 @@ func fetchJSONFrom(ctx context.Context, u string, limit int64, do func(*http.Cli
req.Header.Set("Accept", "application/json")
// GitHub's API is asked with the user's GitHub token, as the
// library's skills are: without one it answers an address 60
// requests an hour, which a few git plugins' checks use up (#1942)
token := ghtoken.Authorize(req, githubAPI)
res, err := do(http.DefaultClient, req)
// requests an hour, which a few git plugins' checks use up (#1942);
// an environment token GitHub refuses is dropped for an anonymous
// request (till on Discord)
res, token, err := ghtoken.Do(req, githubAPI, func(r *http.Request) (*http.Response, error) {
return do(http.DefaultClient, r)
})
if err != nil {
return nil, err
}