diff --git a/README.md b/README.md index c66cec8c0..d2ffaae95 100644 --- a/README.md +++ b/README.md @@ -1055,6 +1055,37 @@ credentials change before sending. Redirects are not followed. Backups without keys omit OTLP headers; restoring one preserves this machine's headers only when the collector endpoint is unchanged. +## Mirrors + +Mirror fallback is off by default. Set `MAGPIE_MIRRORS=on` to use it. When +it is on, the official source is tried first; a mirror is only tried after +a network error, HTTP 429, HTTP 5xx, or GitHub's rate-limit 403. The +defaults are `registry.npmmirror.com` for npm and `gh-proxy.com` for +GitHub. `MAGPIE_NPM_REGISTRY` and `MAGPIE_GITHUB_MIRROR` replace them. + +Only two downloads are checked against a checksum that does not come from +the mirror: Magpie's own update assets (their SHA-256 comes from the +unmirrored update feed) and Bun's zip. Bun's default version carries its +SHA-256s in the code, so it can be downloaded through a mirror even when +Bun's official `SHASUMS256.txt` is unreachable; a newer Bun still needs +that official file. Skill tarballs and the plugin-market registry always +use the official source. npm metadata, plugin README/search results and +version checks are not checksummed; a mirror can report a different +version. + +The official source and a mirror share one request budget, so a hanging +official source doesn't make the whole wait twice as long. + +Requests that carry credentials, such as an `Authorization`, `Cookie`, +API key, or URL userinfo/query token, never use a mirror; they go to the +official source alone. + +```sh +MAGPIE_MIRRORS=on \ +MAGPIE_NPM_REGISTRY=https://registry.example.com \ +MAGPIE_GITHUB_MIRROR=https://gh.example magpie serve +``` + ## Files - `~/.config/magpie/profiles.json` — saved profiles diff --git a/internal/agent/cliupdate.go b/internal/agent/cliupdate.go index e69f8fb16..eb1a89d70 100644 --- a/internal/agent/cliupdate.go +++ b/internal/agent/cliupdate.go @@ -27,6 +27,7 @@ import ( "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/source" ) // CLI is what magpie knows of an agent's command-line program. @@ -427,7 +428,7 @@ func npmLatest(pkg string) (string, error) { req, _ := http.NewRequest("GET", npmRegistry+pkg+"/latest", nil) req.Header.Set("User-Agent", "magpie") req.Header.Set("Accept", "application/json") - resp, err := c.Do(req) + resp, err := source.Do(c, req) if err != nil { return "", err } diff --git a/internal/library/rtk_upgrade.go b/internal/library/rtk_upgrade.go index 5519c43b4..53105bb2a 100644 --- a/internal/library/rtk_upgrade.go +++ b/internal/library/rtk_upgrade.go @@ -16,6 +16,7 @@ import ( "time" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/source" ) // rtk's version is kept up to date the way it was installed: Homebrew's @@ -70,7 +71,7 @@ func latestRTK() (string, error) { } req, _ := http.NewRequest("HEAD", rtkReleases, nil) req.Header.Set("User-Agent", "magpie") - if resp, err := c.Do(req); err == nil { + if resp, err := source.Do(c, req); err == nil { resp.Body.Close() if _, tag, ok := strings.Cut(resp.Header.Get("Location"), "/releases/tag/"); ok { if m := semver.FindStringSubmatch(tag); m != nil { @@ -82,7 +83,7 @@ func latestRTK() (string, error) { req.Header.Set("User-Agent", "magpie") withGitHubToken(req) req.Header.Set("Accept", "application/vnd.github+json") - resp, err := c.Do(req) + resp, err := source.Do(c, req) if err != nil { return "", err } diff --git a/internal/library/skillcheck.go b/internal/library/skillcheck.go index 31e8076d3..6eef98c1f 100644 --- a/internal/library/skillcheck.go +++ b/internal/library/skillcheck.go @@ -17,6 +17,8 @@ import ( "sync" "sync/atomic" "time" + + "github.com/yetone/magpie/internal/source" ) // ---- which skills GitHub has changed -------------------------------------- @@ -116,7 +118,7 @@ func lastCommit(src Source) (*commit, error) { req.Header.Set("If-None-Match", had.etag) } c := &http.Client{Timeout: 20 * time.Second} - resp, err := c.Do(req) + resp, err := source.Do(c, req) if err != nil { return nil, fmt.Errorf("couldn't reach GitHub: %w", err) } diff --git a/internal/library/skills.go b/internal/library/skills.go index b1550672e..b15c894a4 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -20,6 +20,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/source" "gopkg.in/yaml.v3" ) @@ -509,7 +510,7 @@ func fetch(src Source) (string, error) { req, _ := http.NewRequest("GET", tarballURL(src.Repo, src.Ref), nil) req.Header.Set("User-Agent", "magpie") c := &http.Client{Timeout: 2 * time.Minute} - resp, err := c.Do(req) + resp, err := source.DoOfficial(c, req) if err != nil { return "", fmt.Errorf("couldn't reach GitHub: %w", err) } diff --git a/internal/plugin/bun.go b/internal/plugin/bun.go index ef9ab5361..5514a6e8e 100644 --- a/internal/plugin/bun.go +++ b/internal/plugin/bun.go @@ -19,13 +19,32 @@ import ( "sync" "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/source" ) // BunVersion is the Bun magpie downloads to run plugins with the first // time one is needed, and the oldest it runs them on: newer releases are -// taken as they come (see CheckBun). +// taken as they come (see CheckBun). Update bunSums below when it changes. const BunVersion = "1.3.14" +// bunSums are the SHA-256s of BunVersion's builds, from Bun's own +// SHASUMS256.txt. They let the default Bun be downloaded through a mirror +// when Bun's GitHub release page can't be reached. +var bunSums = map[string]string{ + "bun-darwin-aarch64.zip": "d8b96221828ad6f97ac7ac0ab7e95872341af763001e8803e8267652c2652620", + "bun-darwin-x64.zip": "4183df3374623e5bab315c547cfa0974533cd457d86b73b639f7a87974cd6633", + "bun-linux-aarch64.zip": "a27ffb63a8310375836e0d6f668ae17fa8d8d18b88c37c821c65331973a19a3b", + "bun-linux-x64-baseline.zip": "a063908ae08b7852ca10939bbdc6ceed3ddabce8fb9402dce83d65d73b36e6c7", + "bun-windows-x64-baseline.zip": "538f9c846355d9e847b2671bc00c47da4229a0befb24df3282b739770f3b475f", +} + +func bunChecksum(version, target string) string { + if version != BunVersion { + return "" + } + return bunSums[target+".zip"] +} + // bunRelease is where Bun's releases are; a var for tests. var bunRelease = "https://github.com/oven-sh/bun/releases/download" @@ -98,20 +117,22 @@ func downloadBun(ctx context.Context, version, exe string) error { return err } base := bunRelease + "/bun-v" + version + "/" - sums, err := getURL(ctx, base+"SHASUMS256.txt", 1<<20) - if err != nil { - return err - } - want := "" - sc := bufio.NewScanner(strings.NewReader(string(sums))) - for sc.Scan() { - f := strings.Fields(sc.Text()) - if len(f) == 2 && f[1] == target+".zip" { - want = f[0] - } - } + want := bunChecksum(version, target) if want == "" { - return fmt.Errorf("%s.zip isn't in the release's checksums", target) + sums, err := getURLOfficial(ctx, base+"SHASUMS256.txt", 1<<20) + if err != nil { + return err + } + sc := bufio.NewScanner(strings.NewReader(string(sums))) + for sc.Scan() { + f := strings.Fields(sc.Text()) + if len(f) == 2 && f[1] == target+".zip" { + want = f[0] + } + } + if want == "" { + return fmt.Errorf("%s.zip isn't in the release's checksums", target) + } } z, err := getURL(ctx, base+target+".zip", 200<<20) if err != nil { @@ -156,11 +177,24 @@ func downloadBun(ctx context.Context, version, exe string) error { } func getURL(ctx context.Context, url string, limit int64) ([]byte, error) { + return getURLFrom(ctx, url, limit, true) +} + +func getURLOfficial(ctx context.Context, url string, limit int64) ([]byte, error) { + return getURLFrom(ctx, url, limit, false) +} + +func getURLFrom(ctx context.Context, url string, limit int64, mirror bool) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } - res, err := http.DefaultClient.Do(req) + var res *http.Response + if mirror { + res, err = source.Do(http.DefaultClient, req) + } else { + res, err = source.DoOfficial(http.DefaultClient, req) + } if err != nil { return nil, err } diff --git a/internal/plugin/bunupdate_test.go b/internal/plugin/bunupdate_test.go index c547c44f8..ff3e870a1 100644 --- a/internal/plugin/bunupdate_test.go +++ b/internal/plugin/bunupdate_test.go @@ -37,6 +37,15 @@ func bunReleases(t *testing.T, exe []byte) *atomic.Int32 { w.Write(exe) zw.Close() sum := sha256.Sum256(zb.Bytes()) + oldSum, hadSum := bunSums[target+".zip"] + bunSums[target+".zip"] = hex.EncodeToString(sum[:]) + t.Cleanup(func() { + if hadSum { + bunSums[target+".zip"] = oldSum + } else { + delete(bunSums, target+".zip") + } + }) var asked atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { @@ -78,6 +87,29 @@ func stubTry(t *testing.T, f func(exe, v string) error) { t.Cleanup(func() { tryBun = old }) } +// bunSums must be checked against Bun's official SHASUMS256.txt when +// BunVersion changes; this catches a missing or malformed value. +func TestBunDefaultSums(t *testing.T) { + for _, target := range []string{ + "bun-darwin-aarch64", + "bun-darwin-x64", + "bun-linux-aarch64", + "bun-linux-x64-baseline", + "bun-windows-x64-baseline", + } { + got := bunChecksum(BunVersion, target) + if len(got) != 64 { + t.Fatalf("%s checksum = %q", target, got) + } + if _, err := hex.DecodeString(got); err != nil { + t.Fatalf("%s checksum = %q: %v", target, got, err) + } + } + if got := bunChecksum("9.9.9", "bun-linux-x64-baseline"); got != "" { + t.Fatalf("a newer Bun used the built-in checksum: %q", got) + } +} + // A Bun out two days is taken: downloaded, its checksum checked, tried, // and run from then on; the one before it is kept to fall back on. func TestCheckBunTakesASettledRelease(t *testing.T) { @@ -207,3 +239,58 @@ func TestHostFallsBackWhenTheNewBunDies(t *testing.T) { t.Fatalf("in use %s, state %+v", BunInUse(), s) } } + +func TestDownloadBunDefaultSkipsOfficialSums(t *testing.T) { + target, err := bunTarget() + if err != nil { + t.Skip(err) + } + var zb bytes.Buffer + zw := zip.NewWriter(&zb) + h := &zip.FileHeader{Name: target + "/" + bunExe(), Method: zip.Deflate} + h.SetMode(0o755) + w, _ := zw.CreateHeader(h) + w.Write([]byte("bun")) + zw.Close() + sum := sha256.Sum256(zb.Bytes()) + + var sumsAsked atomic.Int32 + var zipAsked atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/SHASUMS256.txt"): + sumsAsked.Add(1) + http.Error(w, "must not ask", http.StatusInternalServerError) + case strings.HasSuffix(r.URL.Path, "/"+target+".zip"): + zipAsked.Add(1) + w.Write(zb.Bytes()) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + oldRelease := bunRelease + bunRelease = srv.URL + defer func() { bunRelease = oldRelease }() + + oldSum, hadSum := bunSums[target+".zip"] + bunSums[target+".zip"] = hex.EncodeToString(sum[:]) + defer func() { + if hadSum { + bunSums[target+".zip"] = oldSum + } else { + delete(bunSums, target+".zip") + } + }() + + exe := filepath.Join(t.TempDir(), bunExe()) + if err := downloadBun(context.Background(), BunVersion, exe); err != nil { + t.Fatal(err) + } + if sumsAsked.Load() != 0 { + t.Fatalf("SHASUMS256.txt asked %d times", sumsAsked.Load()) + } + if zipAsked.Load() != 1 { + t.Fatalf("zip asked %d times", zipAsked.Load()) + } +} diff --git a/internal/plugin/market.go b/internal/plugin/market.go index b72fdb909..fd6c3feab 100644 --- a/internal/plugin/market.go +++ b/internal/plugin/market.go @@ -16,6 +16,7 @@ import ( "time" "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/source" ) // The plugin market: the plugins magpie suggests, from the community @@ -168,7 +169,7 @@ func Market(ctx context.Context) []Listing { } if src != "off" { c, cancel := context.WithTimeout(ctx, 6*time.Second) - b, err := fetchJSON(c, src, 1<<20) + b, err := fetchJSONOfficial(c, src, 1<<20) cancel() if err == nil { if l, err := parseMarket(b); err == nil { @@ -192,13 +193,26 @@ func Market(ctx context.Context) []Listing { } func fetchJSON(ctx context.Context, u string, limit int64) ([]byte, error) { + return fetchJSONFrom(ctx, u, limit, true) +} + +func fetchJSONOfficial(ctx context.Context, u string, limit int64) ([]byte, error) { + return fetchJSONFrom(ctx, u, limit, false) +} + +func fetchJSONFrom(ctx context.Context, u string, limit int64, mirror bool) ([]byte, error) { req, err := http.NewRequestWithContext(ctx, "GET", u, nil) if err != nil { return nil, err } req.Header.Set("User-Agent", "magpie") req.Header.Set("Accept", "application/json") - res, err := http.DefaultClient.Do(req) + var res *http.Response + if mirror { + res, err = source.Do(http.DefaultClient, req) + } else { + res, err = source.DoOfficial(http.DefaultClient, req) + } if err != nil { return nil, err } @@ -411,7 +425,7 @@ func Search(ctx context.Context, q string) ([]Hit, error) { ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() v := url.Values{"text": {q + " opencode"}, "size": {"30"}} - b, err := fetchJSON(ctx, "https://registry.npmjs.org/-/v1/search?"+v.Encode(), 4<<20) + b, err := fetchJSON(ctx, npmRegistry+"/-/v1/search?"+v.Encode(), 4<<20) if err != nil { return nil, err } @@ -474,7 +488,7 @@ func Readme(ctx context.Context, name string) (Page, error) { } ctx, cancel := context.WithTimeout(ctx, 12*time.Second) defer cancel() - b, err := fetchJSON(ctx, "https://registry.npmjs.org/"+npmPath(name), 32<<20) + b, err := fetchJSON(ctx, npmRegistry+"/"+npmPath(name), 32<<20) if err != nil { return Page{}, err } diff --git a/internal/source/source.go b/internal/source/source.go new file mode 100644 index 000000000..46cccc8d2 --- /dev/null +++ b/internal/source/source.go @@ -0,0 +1,204 @@ +// Package source chooses where magpie reads from, with a mirror as a +// fallback when the official address can't be reached. The official source +// stays first; a mirror is only asked when it fails. +package source + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "os" + "strings" + "time" +) + +const ( + npmMirror = "https://registry.npmmirror.com" + githubMirror = "https://gh-proxy.com" +) + +// Enabled reports whether mirror fallback was turned on with +// MAGPIE_MIRRORS=on (or true, 1, cn). +func Enabled() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv("MAGPIE_MIRRORS"))) { + case "on", "true", "1", "cn": + return true + } + return false +} + +func npmBase() string { + if v := strings.TrimRight(strings.TrimSpace(os.Getenv("MAGPIE_NPM_REGISTRY")), "/"); v != "" { + return v + } + return npmMirror +} + +func githubBase() string { + if v := strings.TrimRight(strings.TrimSpace(os.Getenv("MAGPIE_GITHUB_MIRROR")), "/"); v != "" { + return v + } + return githubMirror +} + +// URLs is the official address followed by its mirrors, or just the +// official one when there is no mirror for it. +func URLs(raw string) []string { + if !Enabled() { + return []string{raw} + } + u, err := url.Parse(raw) + if err != nil { + return []string{raw} + } + switch strings.ToLower(u.Hostname()) { + case "registry.npmjs.org": + return distinct(raw, npmBase()+u.RequestURI()) + case "github.com", "api.github.com", "raw.githubusercontent.com", "codeload.github.com": + return distinct(raw, githubBase()+"/"+raw) + } + return []string{raw} +} + +func distinct(raw string, mirrors ...string) []string { + out := []string{raw} + for _, m := range mirrors { + if m != "" && m != raw { + out = append(out, m) + } + } + return out +} + +// Do sends req as usual and, when the official answer fails in a way a +// mirror could answer, tries its mirrors in order. A request that carries +// credentials is never sent to a mirror. +func Do(c *http.Client, req *http.Request) (*http.Response, error) { + if !mirrorable(req) { + return do(c, req, []string{req.URL.String()}) + } + return do(c, req, URLs(req.URL.String())) +} + +// mirrorable is whether req may be sent to a mirror. Credentials stay with +// the official source: a mirror must never see a token, cookie or key. +func mirrorable(req *http.Request) bool { + if req.URL == nil || req.URL.User != nil { + return false + } + for k := range req.URL.Query() { + k = strings.ToLower(k) + if strings.Contains(k, "token") || strings.Contains(k, "key") || + strings.Contains(k, "secret") || strings.Contains(k, "password") || + strings.Contains(k, "auth") { + return false + } + } + for _, h := range []string{ + "Authorization", + "Proxy-Authorization", + "Cookie", + "X-Api-Key", + "Api-Key", + "Private-Token", + } { + if req.Header.Get(h) != "" { + return false + } + } + return true +} + +// DoOfficial sends req to its official address alone. It is for a file +// whose checksum must come from the same trusted place as the file itself. +func DoOfficial(c *http.Client, req *http.Request) (*http.Response, error) { + return do(c, req, []string{req.URL.String()}) +} + +func do(c *http.Client, req *http.Request, urls []string) (*http.Response, error) { + var last error + for i, raw := range urls { + r := req.Clone(req.Context()) + if i > 0 { + u, err := url.Parse(raw) + if err != nil { + last = err + continue + } + r.URL = u + r.Host = "" + if r.Body != nil { + if r.GetBody == nil { + break + } + body, err := r.GetBody() + if err != nil { + last = err + break + } + r.Body = body + } + } + var cancel context.CancelFunc + var stop func() bool + if len(urls) > 1 { + ctx, cancelCandidate, stopCandidate := candidateContext(r.Context(), c, i < len(urls)-1) + if ctx != r.Context() { + r = r.WithContext(ctx) + cancel = cancelCandidate + stop = stopCandidate + } + } + resp, err := c.Do(r) + if err == nil && (!retryable(resp) || i == len(urls)-1) { + if stop != nil { + stop() + } + return resp, nil + } + if cancel != nil { + cancel() + } + if err == nil { + resp.Body.Close() + last = errors.Join(last, fmt.Errorf("%s: %s", raw, resp.Status)) + continue + } + last = errors.Join(last, fmt.Errorf("%s: %w", raw, err)) + } + if last == nil { + last = fmt.Errorf("no address for %s", req.URL) + } + return nil, last +} + +// candidateContext bounds a source's try to half of the request's +// remaining budget, so an official source that hangs doesn't make the +// next one's try double the whole wait. The last source keeps all of +// the time left. The timer only guards the wait for response headers; +// stop leaves the response's context alive for its body. +func candidateContext(ctx context.Context, c *http.Client, more bool) (context.Context, context.CancelFunc, func() bool) { + if !more { + return ctx, func() {}, func() bool { return false } + } + var d time.Duration + if deadline, ok := ctx.Deadline(); ok { + d = time.Until(deadline) / 2 + } else if c.Timeout > 0 { + d = c.Timeout / 2 + } + if d <= 0 { + return ctx, func() {}, func() bool { return false } + } + ctx, cancel := context.WithCancel(ctx) + timer := time.AfterFunc(d, cancel) + return ctx, cancel, timer.Stop +} + +func retryable(resp *http.Response) bool { + return resp.StatusCode == http.StatusTooManyRequests || + resp.StatusCode >= 500 || + (resp.StatusCode == http.StatusForbidden && resp.Header.Get("X-RateLimit-Remaining") == "0") +} diff --git a/internal/source/source_test.go b/internal/source/source_test.go new file mode 100644 index 000000000..d042b310b --- /dev/null +++ b/internal/source/source_test.go @@ -0,0 +1,295 @@ +package source + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestURLs(t *testing.T) { + t.Setenv("MAGPIE_MIRRORS", "on") + t.Setenv("MAGPIE_NPM_REGISTRY", "") + t.Setenv("MAGPIE_GITHUB_MIRROR", "") + + got := URLs("https://registry.npmjs.org/@scope/pkg/latest?x=1") + want := []string{ + "https://registry.npmjs.org/@scope/pkg/latest?x=1", + "https://registry.npmmirror.com/@scope/pkg/latest?x=1", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("npm URLs = %q, want %q", got, want) + } + + got = URLs("https://github.com/owner/repo/releases/download/v1/file") + want = []string{ + "https://github.com/owner/repo/releases/download/v1/file", + "https://gh-proxy.com/https://github.com/owner/repo/releases/download/v1/file", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("github URLs = %q, want %q", got, want) + } + + t.Setenv("MAGPIE_NPM_REGISTRY", "https://npm.example/") + t.Setenv("MAGPIE_GITHUB_MIRROR", "https://gh.example") + got = URLs("https://registry.npmjs.org/pkg") + if got[1] != "https://npm.example/pkg" { + t.Fatalf("npm mirror = %q", got[1]) + } + got = URLs("https://api.github.com/repos/o/r") + if got[1] != "https://gh.example/https://api.github.com/repos/o/r" { + t.Fatalf("github mirror = %q", got[1]) + } +} + +func TestURLsDefaultOff(t *testing.T) { + t.Setenv("MAGPIE_MIRRORS", "") + got := URLs("https://github.com/o/r") + if len(got) != 1 || got[0] != "https://github.com/o/r" { + t.Fatalf("URLs by default = %q", got) + } +} + +func TestURLsOff(t *testing.T) { + t.Setenv("MAGPIE_MIRRORS", "off") + got := URLs("https://github.com/o/r") + if len(got) != 1 || got[0] != "https://github.com/o/r" { + t.Fatalf("URLs with mirrors off = %q", got) + } +} + +func TestDoFallsBack(t *testing.T) { + var mirrorHits atomic.Int32 + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "down", http.StatusBadGateway) + })) + defer official.Close() + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mirrorHits.Add(1) + io.WriteString(w, "from mirror") + })) + defer mirror.Close() + + req, _ := http.NewRequest("GET", official.URL+"/thing", nil) + resp, err := do(http.DefaultClient, req, []string{official.URL + "/thing", mirror.URL + "/thing"}) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + if string(body) != "from mirror" || mirrorHits.Load() != 1 { + t.Fatalf("body %q, mirror hits %d", body, mirrorHits.Load()) + } +} + +func TestDoFallsBackOnRateLimit(t *testing.T) { + var mirrorHits atomic.Int32 + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-RateLimit-Remaining", "0") + http.Error(w, "limited", http.StatusForbidden) + })) + defer official.Close() + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mirrorHits.Add(1) + io.WriteString(w, "from mirror") + })) + defer mirror.Close() + + req, _ := http.NewRequest("GET", official.URL+"/thing", nil) + resp, err := do(http.DefaultClient, req, []string{official.URL + "/thing", mirror.URL + "/thing"}) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if mirrorHits.Load() != 1 { + t.Fatalf("mirror hits %d", mirrorHits.Load()) + } +} + +func TestCredentialsStayOfficial(t *testing.T) { + req, _ := http.NewRequest("GET", "https://api.github.com/repos/o/r", nil) + if !mirrorable(req) { + t.Fatal("a request without credentials can't use a mirror") + } + req.Header.Set("Authorization", "Bearer secret") + if mirrorable(req) { + t.Fatal("a request with Authorization can use a mirror") + } + req.Header.Del("Authorization") + req.Header.Set("Cookie", "session=secret") + if mirrorable(req) { + t.Fatal("a request with a cookie can use a mirror") + } + req.Header.Del("Cookie") + req.URL.User = url.UserPassword("user", "secret") + if mirrorable(req) { + t.Fatal("a request with URL userinfo can use a mirror") + } + req.URL.User = nil + q := req.URL.Query() + q.Set("access_token", "secret") + req.URL.RawQuery = q.Encode() + if mirrorable(req) { + t.Fatal("a request with an access_token can use a mirror") + } +} + +func TestDoOfficialSkipsMirror(t *testing.T) { + var mirrorHits atomic.Int32 + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "official") + })) + defer official.Close() + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mirrorHits.Add(1) + io.WriteString(w, "mirror") + })) + defer mirror.Close() + t.Setenv("MAGPIE_GITHUB_MIRROR", mirror.URL) + + req, _ := http.NewRequest("GET", official.URL+"/thing", nil) + resp, err := DoOfficial(http.DefaultClient, req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if mirrorHits.Load() != 0 { + t.Fatalf("mirror hits %d", mirrorHits.Load()) + } +} + +func TestDoJoinsErrors(t *testing.T) { + official := "http://127.0.0.1:1/thing" + mirror := "http://127.0.0.1:2/thing" + req, _ := http.NewRequest("GET", official, nil) + _, err := do(http.DefaultClient, req, []string{official, mirror}) + if err == nil { + t.Fatal("both sources failed but no error") + } + if !strings.Contains(err.Error(), official) || !strings.Contains(err.Error(), mirror) { + t.Fatalf("error %q doesn't name both sources", err) + } +} + +func TestDoKeepsAnAnswer(t *testing.T) { + var mirrorHits atomic.Int32 + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + defer official.Close() + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mirrorHits.Add(1) + })) + defer mirror.Close() + + req, _ := http.NewRequest("GET", official.URL+"/thing", nil) + resp, err := do(http.DefaultClient, req, []string{official.URL + "/thing", mirror.URL + "/thing"}) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusNotFound || mirrorHits.Load() != 0 { + t.Fatalf("status %d, mirror hits %d", resp.StatusCode, mirrorHits.Load()) + } +} + +func TestDoBodyOutlivesCandidateTimeout(t *testing.T) { + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "down", http.StatusBadGateway) + })) + defer official.Close() + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + time.Sleep(1200 * time.Millisecond) + io.WriteString(w, "slow mirror") + })) + defer mirror.Close() + + req, _ := http.NewRequest("GET", official.URL+"/thing", nil) + client := &http.Client{Timeout: 2 * time.Second} + resp, err := do(client, req, []string{official.URL + "/thing", mirror.URL + "/thing"}) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + if string(body) != "slow mirror" { + t.Fatalf("body = %q", body) + } +} + +type recordedTransport struct { + requests []string +} + +func (rt *recordedTransport) RoundTrip(req *http.Request) (*http.Response, error) { + rt.requests = append(rt.requests, req.URL.String()) + status := http.StatusBadGateway + if strings.HasPrefix(req.URL.String(), "https://gh.example/") { + status = http.StatusOK + } + return &http.Response{ + StatusCode: status, + Status: fmt.Sprintf("%d %s", status, http.StatusText(status)), + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader("")), + Request: req, + }, nil +} + +func TestDoKeepsCredentialsOfficial(t *testing.T) { + t.Setenv("MAGPIE_MIRRORS", "on") + t.Setenv("MAGPIE_GITHUB_MIRROR", "https://gh.example") + rt := &recordedTransport{} + req, _ := http.NewRequest("GET", "https://api.github.com/repos/o/r", nil) + req.Header.Set("Authorization", "Bearer secret") + resp, err := Do(&http.Client{Transport: rt}, req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if len(rt.requests) != 1 || rt.requests[0] != "https://api.github.com/repos/o/r" { + t.Fatalf("requests = %q", rt.requests) + } +} + +func TestDoLastSourceUsesRemainingBudget(t *testing.T) { + official := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(1100 * time.Millisecond) + http.Error(w, "slow official", http.StatusBadGateway) + })) + defer official.Close() + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + time.Sleep(700 * time.Millisecond) + io.WriteString(w, "slow mirror") + })) + defer mirror.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + req, _ := http.NewRequestWithContext(ctx, "GET", official.URL+"/thing", nil) + resp, err := do(http.DefaultClient, req, []string{official.URL + "/thing", mirror.URL + "/thing"}) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + if string(body) != "slow mirror" { + t.Fatalf("body = %q", body) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index eb8f1cfef..194ad0c27 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -31,6 +31,7 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" + "github.com/yetone/magpie/internal/source" ) // Site is magpie's home; its /api/latest is the update feed. @@ -82,7 +83,7 @@ func LatestIn(ctx context.Context, lang string) (*Release, error) { if err != nil { return nil, err } - res, err := client.Do(req) + res, err := source.Do(client, req) if err != nil { return nil, err } @@ -586,7 +587,7 @@ func fetch(ctx context.Context, a Asset, path string) error { if err != nil { return err } - res, err := client.Do(req) + res, err := source.Do(client, req) if err != nil { return err }