diff --git a/internal/ghtoken/ghtoken.go b/internal/ghtoken/ghtoken.go index 5c7dc32c7..a91da5182 100644 --- a/internal/ghtoken/ghtoken.go +++ b/internal/ghtoken/ghtoken.go @@ -10,11 +10,13 @@ // 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). +// A token GitHub refuses (401) is one that no longer reads: the request is +// asked again without it, and the token isn't sent again while magpie runs +// (till on Discord). For a token from the environment that is the whole of +// it. The token set in Settings is the user's own choice, so its refusal is +// also said (SettingsRefused): the checks go on without a token, not with +// the environment's, rather than failing whole, and Settings › Network and +// sharing says that token was refused and needs replacing (#3926). package ghtoken import ( @@ -37,10 +39,15 @@ 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. +// A token GitHub refused isn't one, wherever it came from. After an +// environment variable's, the next variable's is, or none; after the one +// set in Settings, none: the user chose that one over the environment's, +// and the page says requests go without a token till it is replaced. func Token() (token, from string) { if t := strings.TrimSpace(settings.Load().GitHubToken); t != "" { + if isRefused(t) { + return "", "" + } return t, "settings" } for _, k := range Env { @@ -51,14 +58,23 @@ func Token() (token, from string) { 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. +// refused holds the tokens GitHub answered 401, Settings' included, for as +// long as magpie runs: keyed by the token, so a variable or a Settings +// field set to another one is tried afresh. var refused = struct { sync.Mutex m map[string]bool }{m: map[string]bool{}} +// settingsRefused is the token set in Settings that GitHub refused, and +// when, for Settings to say that token needs replacing while the checks +// go on without one. +var settingsRefused struct { + sync.Mutex + t string + at time.Time +} + func isRefused(t string) bool { refused.Lock() defer refused.Unlock() @@ -71,16 +87,37 @@ func markRefused(t string) { refused.Unlock() } +func markSettingsRefused(t string) { + settingsRefused.Lock() + settingsRefused.t, settingsRefused.at = t, time.Now() + settingsRefused.Unlock() +} + +// SettingsRefused is when GitHub refused the token set in Settings, and +// whether it did. From then on the checks ask GitHub without a token until +// that field is changed or magpie restarts, so a stale token costs the user +// the 5,000 an hour it was for and not every check (#3926). +func SettingsRefused() (time.Time, bool) { + now := strings.TrimSpace(settings.Load().GitHubToken) + settingsRefused.Lock() + defer settingsRefused.Unlock() + if settingsRefused.t == "" || now != settingsRefused.t { + return time.Time{}, false + } + return settingsRefused.at, true +} + // 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(). +// GitHub refuses (401) a token, 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, so a check goes on with the 60 an hour rather than failing +// whole. A refusal of the token set in Settings is kept too +// (SettingsRefused), for the page to say which token to replace. 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 { + if err != nil || t == "" || resp.StatusCode != http.StatusUnauthorized { return resp, t != "" && err == nil, err } again := req.Clone(req.Context()) @@ -95,6 +132,9 @@ func Do(req *http.Request, api string, send func(*http.Request) (*http.Response, again.Body = b } markRefused(t) + if from == "settings" { + markSettingsRefused(t) + } io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) resp.Body.Close() again.Header.Del("Authorization") @@ -133,7 +173,7 @@ func authorize(req *http.Request, api string) (token, from string) { func Refused() error { _, from := Token() where := "the GitHub token in Settings → Network and sharing" - if from != "settings" { + if _, ok := SettingsRefused(); !ok && 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) diff --git a/internal/ghtoken/ghtoken_test.go b/internal/ghtoken/ghtoken_test.go index 3822814a2..9203e5c8c 100644 --- a/internal/ghtoken/ghtoken_test.go +++ b/internal/ghtoken/ghtoken_test.go @@ -119,26 +119,55 @@ func TestEnvTokenRefusedNotSentAgain(t *testing.T) { } } -// 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) { +// The token set in Settings is the user's own choice, so its refusal is +// said — and the check goes on: the request is asked again without it, the +// anonymous answer is the one given back, and the token isn't sent again +// while that field holds it (#3926). +func TestSettingsTokenRefusedAskedAgainWithout(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) + setToken(t, "ghp_settings_stale", "", "") + 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) != 1 || a[0] != "Bearer ghp_settings_bad" { - t.Errorf("GitHub was asked with %q", a) + if a := f.asked(); len(a) != 2 || a[0] != "Bearer ghp_settings_stale" || a[1] != "" { + t.Errorf("GitHub was asked with %q, want the token then none", a) + } + if _, ok := SettingsRefused(); !ok { + t.Error("SettingsRefused() says the Settings token was not refused") } err := Refused() - if !strings.Contains(err.Error(), "the GitHub token in Settings") || strings.Contains(err.Error(), "ghp_settings_bad") { + if !strings.Contains(err.Error(), "the GitHub token in Settings") || strings.Contains(err.Error(), "ghp_settings_stale") { t.Errorf("Refused() = %v", err) } - // and it is sent again next time: Settings' token is never dropped + // it isn't sent again: the next request goes without it at once + n := len(f.asked()) + if _, token, _ := f.get(t); token { + t.Error("the refused Settings token was sent again") + } + 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) + } +} + +// A token typed into Settings after one was refused is another token: it is +// sent, and the page stops saying the old one was refused. +func TestSettingsTokenReplacedAfterRefusalIsSent(t *testing.T) { + f := newFakeAPI(t) + setToken(t, "ghp_settings_old", "", "") 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) + f.mu.Lock() + f.good = "ghp_settings_new" + f.mu.Unlock() + setToken(t, "ghp_settings_new", "", "") + if _, token, _ := f.get(t); !token { + t.Error("the token typed after the refusal wasn't sent") + } + if _, ok := SettingsRefused(); ok { + t.Error("SettingsRefused() still says a token was refused after another was typed") } } @@ -182,3 +211,25 @@ func TestOtherHostUntouched(t *testing.T) { t.Errorf("another host was asked with %q", a) } } + +// A refused Settings token isn't swapped for the environment's: the user +// chose the one in Settings over it, and the page says requests go without +// a token, so they do (#3926). +func TestSettingsTokenRefusedGoesWithoutEnvToken(t *testing.T) { + f := newFakeAPI(t) + f.mu.Lock() + f.good = "ghp_env_good" + f.mu.Unlock() + setToken(t, "ghp_settings_gone", "ghp_env_good", "") + f.get(t) + n := len(f.asked()) + if _, token, _ := f.get(t); token { + t.Error("a token was sent after the Settings one was refused") + } + if a := f.asked()[n:]; len(a) != 1 || a[0] != "" { + t.Errorf("after the Settings token's refusal GitHub was asked with %q, want none", a) + } + if tok, from := Token(); tok != "" || from != "" { + t.Errorf("Token() = %q from %q, want none", tok, from) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index bab31b599..3d13c80c7 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -37,6 +37,7 @@ import ( "github.com/yetone/magpie/internal/fonts" "github.com/yetone/magpie/internal/fx" "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/lastgood" "github.com/yetone/magpie/internal/library" "github.com/yetone/magpie/internal/mcpauth" @@ -468,6 +469,9 @@ type settingsJSON struct { // is from ("settings", GITHUB_TOKEN or GH_TOKEN); never the token GitHubTokenMask string `json:"githubTokenMask,omitempty"` GitHubTokenFrom string `json:"githubTokenFrom,omitempty"` + // the token set in Settings was refused by GitHub (401): it is still + // shown, masked, while requests go without a token (#3926) + GitHubTokenRefused bool `json:"githubTokenRefused,omitempty"` // where other machines reach the gateway while it is shared LANURLs []string `json:"lanURLs,omitempty"` // LANURLs are a container's own addresses, not the host's: the page @@ -627,9 +631,14 @@ func settingsState() settingsJSON { s.LANKey = "" // the retained credential belongs on disk, not in UI state // the GitHub token, masked, and where the library's requests take one // from: Settings, or the environment variable named + own := strings.TrimSpace(s.GitHubToken) s.GitHubToken = "" if tok, from := library.GitHubToken(); tok != "" { s.GitHubTokenMask, s.GitHubTokenFrom = provider.Mask(tok), from + } else if _, refused := ghtoken.SettingsRefused(); refused && own != "" { + // a refused token set here is still the user's: shown as refused, + // not as if none were set, while requests go without one (#3926) + s.GitHubTokenMask, s.GitHubTokenFrom, s.GitHubTokenRefused = provider.Mask(own), "settings", true } if found, err := discoverTerminals(); err == nil { for _, app := range found.Apps { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 70a112170..f94bb175d 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -20552,11 +20552,8 @@ function proxyCheckText(c) { return [t("Works: through the proxy requests leave from {where}, {ms} ms; direct ones from {direct}", { where: where(via), ms: via.ms || 0, direct }), false]; } -// renderGitHubToken: the GitHub token the library's requests to GitHub's -// API carry (checking skills for updates, installing from a private -// repository), which raises GitHub's limit from -// 60 requests an hour to 5,000. The page is told a masked one only, and -// whether it is the one set here or GITHUB_TOKEN / GH_TOKEN's. +// renderGitHubToken: the token requests to GitHub's API carry, masked, +// and whether it is set here, GITHUB_TOKEN's / GH_TOKEN's, or refused. let githubTokenErr = "", githubTokenDraft = ""; function renderGitHubToken(s) { const box = $("#githubList"); @@ -20573,7 +20570,8 @@ function renderGitHubToken(s) { .catch((e) => { githubTokenErr = t(e.message); status(t(e.message), "err"); renderSettings(); }); const why = t("The library checks skills for updates with it: GitHub allows 5,000 requests an hour with a token, 60 without. It also installs skills from private repositories it can read; for public ones it needs no scopes."); if (s.githubTokenFrom === "settings") { - sub.textContent = sub.title = why; + sub.textContent = sub.title = s.githubTokenRefused ? t("GitHub refused this token: it may have expired or been revoked. Requests go without one (60 an hour) until it is replaced.") : why; + sub.classList.toggle("err", !!s.githubTokenRefused); const x = el("button", "text", t("Remove")); x.onclick = () => set(""); val.append(el("code", "", s.githubTokenMask || ""), x); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index be8cfb977..16da61afd 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3660,6 +3660,7 @@ const I18N = { "Coming soon": "即将上线", "{n} stars on GitHub": "GitHub 上 {n} 个 Star", "Unofficial, on GitHub": "非官方插件 · GitHub", + "GitHub refused this token: it may have expired or been revoked. Requests go without one (60 an hour) until it is replaced.": "GitHub 拒绝了这个令牌:它可能已过期或被撤销。在换成新令牌之前,请求改为不带令牌发出(每小时 60 次)。", "Looking on GitHub": "正在 GitHub 上查找", "Couldn't ask GitHub: {error}": "无法连接 GitHub:{error}", "GitHub didn't answer in time": "GitHub 响应超时", @@ -7658,6 +7659,7 @@ const I18N = { "Coming soon": "即將上線", "{n} stars on GitHub": "GitHub 上 {n} 個 Star", "Unofficial, on GitHub": "非官方外掛 · GitHub", + "GitHub refused this token: it may have expired or been revoked. Requests go without one (60 an hour) until it is replaced.": "GitHub 拒絕了這個令牌:它可能已過期或被撤銷。在換成新令牌之前,請求改為不帶令牌送出(每小時 60 次)。", "Looking on GitHub": "正在 GitHub 上尋找", "Couldn't ask GitHub: {error}": "無法連線 GitHub:{error}", "GitHub didn't answer in time": "GitHub 回應逾時", @@ -11678,6 +11680,7 @@ const I18N = { "Coming soon": "近日公開", "{n} stars on GitHub": "GitHub のスター {n}", "Unofficial, on GitHub": "非公式 · GitHub", + "GitHub refused this token: it may have expired or been revoked. Requests go without one (60 an hour) until it is replaced.": "GitHub がこのトークンを拒否しました。期限切れか取り消された可能性があります。差し替えるまで、リクエストはトークンなし(1 時間 60 回)で送られます。", "Looking on GitHub": "GitHub を検索中", "Couldn't ask GitHub: {error}": "GitHub に接続できませんでした:{error}", "GitHub didn't answer in time": "GitHub の応答がタイムアウトしました", @@ -15711,6 +15714,7 @@ const I18N = { "Coming soon": "Demnächst", "{n} stars on GitHub": "{n} Sterne auf GitHub", "Unofficial, on GitHub": "Inoffiziell, auf GitHub", + "GitHub refused this token: it may have expired or been revoked. Requests go without one (60 an hour) until it is replaced.": "GitHub hat diesen Token abgelehnt: Er ist vielleicht abgelaufen oder widerrufen. Bis er ersetzt ist, gehen Anfragen ohne Token (60 pro Stunde).", "Looking on GitHub": "Suche auf GitHub", "Couldn't ask GitHub: {error}": "GitHub nicht erreichbar: {error}", "GitHub didn't answer in time": "GitHub hat nicht rechtzeitig geantwortet", diff --git a/internal/gui/github_token_test.go b/internal/gui/github_token_test.go index 0321abd00..bf0b99c51 100644 --- a/internal/gui/github_token_test.go +++ b/internal/gui/github_token_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/settings" ) @@ -56,3 +57,50 @@ func TestGitHubTokenSetting(t *testing.T) { t.Errorf("from the environment: %s", body) } } + +// A Settings token GitHub refused is still shown in Settings, masked and +// said to be refused, not as if none were set, while requests go without +// one (#3926). +func TestGitHubTokenRefusedShown(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache")) + t.Setenv("GITHUB_TOKEN", "") + t.Setenv("GH_TOKEN", "") + state := func() string { + t.Helper() + rec := httptest.NewRecorder() + Handler(nil, nil).ServeHTTP(rec, httptest.NewRequest("GET", "/api/settings", nil)) + return rec.Body.String() + } + const tok = "ghp_refusedrefusedrefusedrefused4567" + s := settings.Load() + s.GitHubToken = tok + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if body := state(); strings.Contains(body, "githubTokenRefused") { + t.Fatalf("refused before GitHub was asked: %s", body) + } + gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "" { + w.WriteHeader(http.StatusUnauthorized) + } + })) + defer gh.Close() + req, _ := http.NewRequest("GET", gh.URL+"/repos/o/r", nil) + resp, _, err := ghtoken.Do(req, gh.URL, http.DefaultClient.Do) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("the request without the token got %d", resp.StatusCode) + } + body := state() + if strings.Contains(body, tok) || !strings.Contains(body, `"githubTokenRefused":true`) || !strings.Contains(body, `"githubTokenFrom":"settings"`) || !strings.Contains(body, `"githubTokenMask":"ghp_…4567"`) { + t.Errorf("after the refusal the page was told %s", body) + } +} diff --git a/internal/gui/tests/github-token-refused.test.cjs b/internal/gui/tests/github-token-refused.test.cjs new file mode 100644 index 000000000..d262b01fe --- /dev/null +++ b/internal/gui/tests/github-token-refused.test.cjs @@ -0,0 +1,82 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// #3926 (MYCF711): a GitHub token in Settings that GitHub refuses no longer +// fails every check; requests go without it. The page stays honest about +// it: Settings › Network and sharing still shows the token, masked, saying +// GitHub refused it and requests go without one, with Remove to replace +// it, rather than reading as no token set. English and Chinese, wide and +// 440px, Chromium and WebKit. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(process.env.MAGPIE_REFUSED_ASSETS || path.resolve(__dirname, "../assets")); +const W = { + en: { remove: "Remove", row: "GitHub refused this token: it may have expired or been revoked. Requests go without one (60 an hour) until it is replaced." }, + zh: { remove: "移除", row: "GitHub 拒绝了这个令牌:它可能已过期或被撤销。在换成新令牌之前,请求改为不带令牌发出(每小时 60 次)。" }, +}; + +function serve(lang, refused) { + const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], githubTokenMask: "ghp_…0123", githubTokenFrom: "settings", ...(refused ? { githubTokenRefused: true } : {}) }); + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() }); + if (url.pathname === "/api/settings") return json(settings()); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [] }); + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname.startsWith("/api/")) return json({}); + if (!/^\/[\w./-]*$/.test(url.pathname) || url.host !== "magpie.test") return r.fulfill({ status: 404, body: "" }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); } + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a refused Settings token is said in Settings", async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + for (const lang of Object.keys(W)) { + for (const width of [1000, 440]) { + await t.test(lang + " " + width, async () => { + const w = W[lang]; + for (const refused of [true, false]) { + const ctx = await browser.newContext({ viewport: { width, height: 860 } }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, refused)); + + // Settings: the token still shown, masked, and said refused + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=network"); + await settingsDrawn(page); + const row = page.locator("#githubList .row.github-token"); + await row.waitFor(); + assert.equal(await row.locator("code").innerText(), "ghp_…0123"); + assert.equal(await row.locator("button.text", { hasText: w.remove }).count(), 1); + const sub = row.locator(".sub"); + if (refused) { + assert.equal(await sub.innerText(), w.row); + assert.ok(await sub.evaluate((e) => e.classList.contains("err")), "said as an error"); + } else { + assert.notEqual(await sub.innerText(), w.row); + assert.ok(!(await sub.evaluate((e) => e.classList.contains("err")))); + } + + assert.ok(await sub.evaluate((e) => e.scrollWidth <= e.clientWidth + 1 || getComputedStyle(e).textOverflow === "ellipsis"), "the line fits"); + assert.deepEqual(errors, []); + await ctx.close(); + } + }); + } + } + }); +} diff --git a/internal/library/github_test.go b/internal/library/github_test.go index cd983e2b3..5c5dd54cd 100644 --- a/internal/library/github_test.go +++ b/internal/library/github_test.go @@ -9,6 +9,7 @@ import ( "testing" "time" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/settings" ) @@ -201,7 +202,8 @@ func TestGitHubRateLimitSaid(t *testing.T) { t.Errorf("secondary limit: %+v %+v", c, c.Limited) } - // a token GitHub refuses says which one when it is Settings' + // a token in Settings GitHub refuses: the check goes on without it, + // and Settings says it was refused (#3926) g.answer = func(w http.ResponseWriter, r *http.Request) bool { if r.Header.Get("Authorization") == "" { return false @@ -210,17 +212,28 @@ func TestGitHubRateLimitSaid(t *testing.T) { fmt.Fprint(w, `{"message":"Bad credentials"}`) return true } + g.mu.Lock() + n := len(g.apiAuth) + g.mu.Unlock() c = check(t)["pdf"] - if c.Limited != nil || c.Error != "GitHub refused the GitHub token in Settings → Network and sharing: it may have expired or been revoked" { + if c.Limited != nil || c.Error != "" || c.Commit == "" { t.Errorf("refused: %+v", c) } + g.mu.Lock() + if a := g.apiAuth[n:]; len(a) < 2 || !strings.HasPrefix(a[0], "Bearer ") || a[1] != "" { + t.Errorf("refused: GitHub was asked with %q, want the token then none", a) + } + g.mu.Unlock() + if _, ok := ghtoken.SettingsRefused(); !ok { + t.Error("the refused Settings token isn't said") + } // 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-env-skills") g.mu.Lock() - n := len(g.apiAuth) + n = len(g.apiAuth) g.mu.Unlock() c = check(t)["pdf"] if c.Error != "" || c.Limited != nil || c.Commit == "" { diff --git a/internal/plugin/github_token_test.go b/internal/plugin/github_token_test.go index 8d6a302f2..075e0c8a9 100644 --- a/internal/plugin/github_token_test.go +++ b/internal/plugin/github_token_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/yetone/magpie/internal/ghtoken" "github.com/yetone/magpie/internal/settings" ) @@ -142,8 +143,9 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) { t.Errorf("secondary limit: %+v %+v", c, c.Limited) } - // a token GitHub refuses (401), answering without one: the token in - // Settings is said, by where it is, not the token + // a token GitHub refuses (401): the check goes on without it rather + // than failing whole, and the anonymous answer is the one taken. The + // Settings says which token to replace (#3926). mu.Lock() answer = func(w http.ResponseWriter, r *http.Request) bool { if r.Header.Get("Authorization") == "" { @@ -153,11 +155,20 @@ func TestGitPluginCheckCarriesGitHubToken(t *testing.T) { fmt.Fprint(w, `{"message":"Bad credentials"}`) return true } + before := len(auth) mu.Unlock() 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") { + if c = check(); c.Limited != nil || c.Error != "" || c.Status != "current" { t.Errorf("Settings' token refused: %+v", c) } + mu.Lock() + if a := auth[before:]; len(a) != 2 || a[0] != "Bearer ghp_settings_refused" || a[1] != "" { + t.Errorf("Settings' token refused: GitHub was asked with %q, want the token then none", a) + } + mu.Unlock() + if _, ok := ghtoken.SettingsRefused(); !ok { + t.Error("ghtoken.SettingsRefused() says no token of Settings was refused") + } setToken("") // one from the environment (till on Discord: a stale GITHUB_TOKEN) is // dropped, and the check asked again without it