diff --git a/internal/ghtoken/ghtoken.go b/internal/ghtoken/ghtoken.go new file mode 100644 index 000000000..396aee59d --- /dev/null +++ b/internal/ghtoken/ghtoken.go @@ -0,0 +1,107 @@ +// 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). +package ghtoken + +import ( + "fmt" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "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. +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 != "" { + return t, k + } + } + return "", "" +} + +// 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. +func Authorize(req *http.Request, api string) bool { + 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 + } + t, _ := Token() + if t == "" { + return false + } + req.Header.Set("Authorization", "Bearer "+t) + return true +} + +// 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 +} diff --git a/internal/library/github.go b/internal/library/github.go index b92837261..d8554f815 100644 --- a/internal/library/github.go +++ b/internal/library/github.go @@ -2,102 +2,32 @@ package library import ( "net/http" - "net/url" - "os" - "strconv" - "strings" "sync" - "time" - "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/ghtoken" ) // ---- asking GitHub's API with the user's token ---------------------------- // -// GitHub's REST API answers an address 60 requests an hour without a token, -// which a check of a few repositories' skills, 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 alone (githubAPI's host), never to -// codeload or anywhere else, and is never written to a log or an error. +// The token, where it may go and what a rate limit says are ghtoken's, +// shared with the Plugins page's checks of git plugins (#1942). // GitHubTokenEnv names the environment variables a token is taken from when // Settings has none, in the order they are looked at. -var GitHubTokenEnv = []string{"GITHUB_TOKEN", "GH_TOKEN"} +var GitHubTokenEnv = ghtoken.Env // GitHubToken is the token requests to GitHub's API carry, and where it // came from: "settings", the environment variable's name, or "" for none. -func GitHubToken() (token, from string) { - if t := strings.TrimSpace(settings.Load().GitHubToken); t != "" { - return t, "settings" - } - for _, k := range GitHubTokenEnv { - if t := strings.TrimSpace(os.Getenv(k)); t != "" { - return t, k - } - } - return "", "" -} - -// githubAPIHost is the host a token may be sent to: GitHub's API's. -func githubAPIHost() string { - u, err := url.Parse(githubAPI) - if err != nil { - return "" - } - return u.Host -} +func GitHubToken() (token, from string) { return ghtoken.Token() } // withGitHubToken has req carry the token, if there is one and req goes to -// GitHub's API; it says whether it did. -func withGitHubToken(req *http.Request) bool { - if req.URL == nil || req.URL.Host == "" || !strings.EqualFold(req.URL.Host, githubAPIHost()) { - return false - } - t, _ := GitHubToken() - if t == "" { - return false - } - req.Header.Set("Authorization", "Bearer "+t) - return true -} +// GitHub's API (githubAPI's host); it says whether it did. +func withGitHubToken(req *http.Request) bool { return ghtoken.Authorize(req, githubAPI) } -// errLimited is GitHub turning requests away for a while: the API allows -// an address 60 an hour without a token, 5,000 with one. -type errLimited struct { - until time.Time - token bool // the requests carried a token -} +// errLimited is GitHub turning requests away for a while. +type errLimited = ghtoken.Limited -func (e errLimited) 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 errLimited 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. -func limitedBy(resp *http.Response, body []byte, token bool) (errLimited, 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 errLimited{}, false - } - e := errLimited{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 -} +var limitedBy = ghtoken.LimitedBy // etags are GitHub's answers kept by URL, for the next request for one to // ask if it changed: a 304 doesn't count against the rate limit. diff --git a/internal/library/skillcheck.go b/internal/library/skillcheck.go index 365f83aa3..3db9d16d8 100644 --- a/internal/library/skillcheck.go +++ b/internal/library/skillcheck.go @@ -19,6 +19,7 @@ import ( "sync/atomic" "time" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/source" ) @@ -53,10 +54,10 @@ type Limited struct { Token bool `json:"token,omitempty"` } -func (e errLimited) view() *Limited { - l := &Limited{Token: e.token} - if !e.until.IsZero() { - l.Until = e.until.UTC().Format(time.RFC3339) +func limitedView(e errLimited) *Limited { + l := &Limited{Token: e.Token} + if !e.Until.IsZero() { + l.Until = e.Until.UTC().Format(time.RFC3339) } return l } @@ -133,12 +134,7 @@ func lastCommit(src Source) (*commit, error) { } switch { case code == 401 && token: - _, from := GitHubToken() - 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 nil, fmt.Errorf("GitHub refused %s: it may have expired or been revoked", where) + return nil, ghtoken.Refused() case code == 404, code == 422: if src.Ref != "" { return nil, fmt.Errorf("GitHub has no %s at %s any more", src.Repo, src.Ref) @@ -372,7 +368,7 @@ func checkSkill(s *Skill, f *fetcher, asked map[string]*commit, limited *atomic. last := asked[key] if last == nil { if e := limited.Load(); e != nil { - c.Error, c.Limited = e.Error(), e.view() + c.Error, c.Limited = e.Error(), limitedView(*e) return c, "", "" } var err error @@ -381,7 +377,7 @@ func checkSkill(s *Skill, f *fetcher, asked map[string]*commit, limited *atomic. var e errLimited if errors.As(err, &e) { limited.Store(&e) - c.Limited = e.view() + c.Limited = limitedView(e) } c.Error = err.Error() return c, "", "" diff --git a/internal/library/skillcheck_test.go b/internal/library/skillcheck_test.go index 8a0c7fe55..2aa05a8db 100644 --- a/internal/library/skillcheck_test.go +++ b/internal/library/skillcheck_test.go @@ -157,7 +157,7 @@ func TestCheckSkills(t *testing.T) { clear(asked) got = check(t) for _, n := range []string{"pdf", "docx", "x", "y"} { - if c := got[n]; c.Status != "unknown" || c.Error != (errLimited{until: time.Unix(2000000000, 0)}).Error() { + if c := got[n]; c.Status != "unknown" || c.Error != (errLimited{Until: time.Unix(2000000000, 0)}).Error() { t.Errorf("%s: %+v", n, c) } } diff --git a/internal/plugin/github_token_test.go b/internal/plugin/github_token_test.go new file mode 100644 index 000000000..298f0b65d --- /dev/null +++ b/internal/plugin/github_token_test.go @@ -0,0 +1,171 @@ +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) + } +} diff --git a/internal/plugin/market.go b/internal/plugin/market.go index 2a4c6ffce..f489411ba 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -17,6 +17,7 @@ import ( "time" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/source" ) @@ -237,6 +238,10 @@ func fetchJSONFrom(ctx context.Context, u string, limit int64, do func(*http.Cli } req.Header.Set("User-Agent", "magpie") 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) if err != nil { return nil, err @@ -245,6 +250,15 @@ func fetchJSONFrom(ctx context.Context, u string, limit int64, do func(*http.Cli if res.StatusCode == http.StatusNotFound { return nil, errNotFound } + if res.StatusCode != http.StatusOK && sameHost(u, githubAPI) { + body, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) + if e, ok := ghtoken.LimitedBy(res, body, token); ok { + return nil, e + } + if res.StatusCode == http.StatusUnauthorized && token { + return nil, ghtoken.Refused() + } + } if res.StatusCode != http.StatusOK { return nil, &statusError{URL: u, Code: res.StatusCode, Status: res.Status} } @@ -253,6 +267,13 @@ func fetchJSONFrom(ctx context.Context, u string, limit int64, do func(*http.Cli var errNotFound = errors.New("not found") +// sameHost is whether u is on base's host. +func sameHost(u, base string) bool { + a, err1 := url.Parse(u) + b, err2 := url.Parse(base) + return err1 == nil && err2 == nil && a.Host != "" && strings.EqualFold(a.Host, b.Host) +} + // statusError is a server's answer other than 200 or 404. type statusError struct { URL string diff --git a/internal/plugin/updates.go b/internal/plugin/updates.go index 8ef984b6c..e865c94bd 100644 --- a/internal/plugin/updates.go +++ b/internal/plugin/updates.go @@ -22,6 +22,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/steady" "github.com/yetone/magpie/internal/update" @@ -268,12 +269,23 @@ type VersionCheck struct { // (it has no such package) Why string `json:"why,omitempty"` Error string `json:"error,omitempty"` + // Limited is set when a git one's repository couldn't be asked + // because GitHub's rate limit was used up, for the page to say so in + // its own words, as the library's skills do (#1942) + Limited *GitHubLimit `json:"limited,omitempty"` // Auto is whether magpie updates it by itself (the community's, // unpinned, switched on), so an update found would come anyway Auto bool `json:"auto"` Off bool `json:"off"` } +// GitHubLimit is GitHub's rate limit used up: until when (RFC 3339, "" +// when GitHub didn't say), and whether the request carried a GitHub token. +type GitHubLimit struct { + Until string `json:"until,omitempty"` + Token bool `json:"token,omitempty"` +} + // VersionChecks is what a check asked now found. type VersionChecks struct { At time.Time `json:"at"` @@ -321,6 +333,13 @@ func CheckNow(ctx context.Context) VersionChecks { cancel() if err != nil { c.Status, c.Why, c.Error = "unknown", whyNot(err), err.Error() + var l ghtoken.Limited + if errors.As(err, &l) { + c.Limited = &GitHubLimit{Token: l.Token} + if !l.Until.IsZero() { + c.Limited.Until = l.Until.UTC().Format(time.RFC3339) + } + } return } c.Head, c.Status = short(head), "current" @@ -403,7 +422,7 @@ func whyNot(err error) string { switch { case errors.Is(err, errNotFound): return "missing" - case errors.As(err, &se) && se.Code == http.StatusTooManyRequests: + case errors.As(err, &se) && se.Code == http.StatusTooManyRequests, errors.As(err, new(ghtoken.Limited)): return "limited" case errors.As(err, &se): return "registry"