From 2513890327b7f0a54e447fe20c7f5385cce25619 Mon Sep 17 00:00:00 2001 From: PatrickNoFilter Date: Wed, 9 Sep 2026 12:35:39 +0700 Subject: [PATCH 1/3] fix(update): authenticate GitHub release checks Rebuild PatrickNoFilter's final change from Twigpine/zero#504 on current upstream main. Prefer ZERO_GITHUB_TOKEN, fall back to GITHUB_TOKEN, and limit credentials to HTTPS GitHub API requests with downgrade protection. Retain the original tests and update documentation. Original implementation, tests and documentation by PatrickNoFilter. Source-PR: https://github.com/Twigpine/zero/pull/504 Source-Head: 295b9d2a918957e846eab9c5d5a555befa99d175 Integration: two equivalent strings.Contains substitutions satisfy current advisory lint in the copied help test. Fixes #507 --- docs/UPDATE.md | 22 ++ internal/cli/app_test.go | 19 +- internal/cli/update.go | 7 + internal/update/auth_test.go | 417 +++++++++++++++++++++++++++++++++++ internal/update/update.go | 47 +++- 5 files changed, 508 insertions(+), 4 deletions(-) create mode 100644 internal/update/auth_test.go diff --git a/docs/UPDATE.md b/docs/UPDATE.md index 55e30595b4..ccdeea3a98 100644 --- a/docs/UPDATE.md +++ b/docs/UPDATE.md @@ -75,6 +75,28 @@ Installer scripts download the matching release asset for the local platform and verify its `.sha256` file. If Zero is already installed, run `zero upgrade` instead of reinstalling. +## Authentication + +Unauthenticated GitHub API requests are subject to strict +[rate limits](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api). +If you see `403 Forbidden` during update checks, set a GitHub personal access token: + +| Environment variable | Role | +|---|---| +| `ZERO_GITHUB_TOKEN` | Used for update checks (takes precedence) | +| `GITHUB_TOKEN` | Fallback when `ZERO_GITHUB_TOKEN` is not set | + +Note: `GITHUB_TOKEN` is also used by the GitHub Models provider +(`internal/providercatalog/catalog.go:150`); both recipients are GitHub so no +trust boundary is crossed, but a token set for the provider will also be sent +on update checks. + +Tokens are only sent when the request URL is `https://api.github.com`. Custom +endpoints (set via `--endpoint` or `ZERO_UPDATE_RELEASE_URL`) and plain HTTP +URLs never receive credentials. Redirects that downgrade to `http` are refused, +so the bearer token is never sent in cleartext (Go's standard library would +otherwise copy `Authorization` on same-host redirects based on host alone). + ## Windows recovery state (standalone installs) This section describes Windows only. On Linux and macOS a standalone update diff --git a/internal/cli/app_test.go b/internal/cli/app_test.go index bf1c40aa80..c12eb5017d 100644 --- a/internal/cli/app_test.go +++ b/internal/cli/app_test.go @@ -1596,11 +1596,28 @@ func TestRunUpdateHelpDocumentsCheckFlag(t *testing.T) { if exitCode != exitSuccess { t.Fatalf("expected exit code %d, got %d: %s", exitSuccess, exitCode, stderr.String()) } - for _, want := range []string{"--check", "--repo", "--endpoint", "--timeout", "--target"} { + for _, want := range []string{"--check", "--repo", "--endpoint", "--timeout", "--target", "ZERO_GITHUB_TOKEN", "ZERO_UPDATE_RELEASE_URL"} { if !strings.Contains(stdout.String(), want) { t.Fatalf("expected update help to document %s, got %q", want, stdout.String()) } } + // GITHUB_TOKEN must appear as a standalone token, not as a substring of ZERO_GITHUB_TOKEN. + out := stdout.String() + if idx := strings.Index(out, "GITHUB_TOKEN"); idx < 0 { + t.Fatalf("expected update help to document GITHUB_TOKEN, got %q", out) + } else if idx >= 5 && out[idx-5:idx] == "ZERO_" { + // Check after the ZERO_GITHUB_TOKEN occurrence too. + rest := out[idx+len("GITHUB_TOKEN"):] + if !strings.Contains(rest, "GITHUB_TOKEN") { + // Only ZERO_GITHUB_TOKEN matched; GITHUB_TOKEN is missing as a standalone entry. + // Find the first occurrence for the error message. + firstIdx := strings.Index(out, "ZERO_GITHUB_TOKEN") + after := out[firstIdx+len("ZERO_GITHUB_TOKEN"):] + if !strings.Contains(after, "GITHUB_TOKEN") { + t.Fatalf("expected update help to document GITHUB_TOKEN (standalone), got %q", out) + } + } + } if stderr.Len() != 0 { t.Fatalf("expected empty stderr, got %q", stderr.String()) } diff --git a/internal/cli/update.go b/internal/cli/update.go index 01851fe7f6..98695ecf69 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -207,6 +207,13 @@ Flags: --timeout Release check timeout (default 5s) --target Release target to verify with --check (for example windows-x64); not valid with --apply -h, --help Show this help + +Environment: + ZERO_GITHUB_TOKEN Token for update checks (takes precedence over GITHUB_TOKEN) + Only sent to https://api.github.com over HTTPS; never sent to custom endpoints + or on redirect to plain HTTP + GITHUB_TOKEN Fallback token for update checks + ZERO_UPDATE_RELEASE_URL Override the release API URL (same as --endpoint) `) return err } diff --git a/internal/update/auth_test.go b/internal/update/auth_test.go new file mode 100644 index 0000000000..d7aa56c29e --- /dev/null +++ b/internal/update/auth_test.go @@ -0,0 +1,417 @@ +package update + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// releaseJSON returns a minimal GitHub release JSON body. +func releaseJSON(tag string) string { + return fmt.Sprintf(`{"tag_name":"%s","html_url":"https://example.test/release","assets":[{"name":"%s-linux-x64.tar.gz","browser_download_url":"https://example.test/%s-linux-x64.tar.gz"}]}`, tag, tag, tag) +} + +// fakeTransport records the Authorization header from the first request it receives +// and returns a canned response. Used to verify auth is sent for GitHub URLs +// without needing a real TLS server. +type fakeTransport struct { + gotAuth string + statusCode int + body string +} + +func (ft *fakeTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ft.gotAuth = req.Header.Get("Authorization") + if ft.statusCode == 0 { + ft.statusCode = 200 + } + if ft.body == "" { + ft.body = releaseJSON("v0.2.0") + } + return &http.Response{ + StatusCode: ft.statusCode, + Body: io.NopCloser(strings.NewReader(ft.body)), + Header: make(http.Header), + Request: req, + }, nil +} + +func TestFetchReleaseSendsAuthToHttpsGithub(t *testing.T) { + ft := &fakeTransport{} + old := httpClient + httpClient = &http.Client{Transport: ft} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "zero_token") + t.Setenv(EnvGitHubToken, "github_fallback") + + _, err := fetchRelease(context.Background(), "https://api.github.com/repos/Gitlawb/zero/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if ft.gotAuth != "Bearer zero_token" { + t.Fatalf("expected Bearer zero_token, got %q", ft.gotAuth) + } +} + +func TestFetchReleaseSendsAuthCaseInsensitive(t *testing.T) { + ft := &fakeTransport{} + old := httpClient + httpClient = &http.Client{Transport: ft} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "zero_token") + t.Setenv(EnvGitHubToken, "") + + _, err := fetchRelease(context.Background(), "https://API.GITHUB.COM/repos/Gitlawb/zero/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if ft.gotAuth != "Bearer zero_token" { + t.Fatalf("expected Bearer zero_token, got %q", ft.gotAuth) + } +} + +func TestFetchReleaseFallsBackToGithubToken(t *testing.T) { + ft := &fakeTransport{} + old := httpClient + httpClient = &http.Client{Transport: ft} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvGitHubToken, "fallback_token") + t.Setenv(EnvUpdateToken, "") + + _, err := fetchRelease(context.Background(), "https://api.github.com/repos/Gitlawb/zero/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if ft.gotAuth != "Bearer fallback_token" { + t.Fatalf("expected Bearer fallback_token, got %q", ft.gotAuth) + } +} + +func TestFetchReleaseNoAuthToCustomEndpoint(t *testing.T) { + var gotAuth string + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, releaseJSON("v0.2.0")) + })) + defer srv.Close() + + old := httpClient + httpClient = srv.Client() + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "secret") + t.Setenv(EnvGitHubToken, "fallback") + + _, err := fetchRelease(context.Background(), srv.URL+"/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if gotAuth != "" { + t.Fatalf("expected no auth for non-GitHub endpoint, got %q", gotAuth) + } +} + +func TestFetchReleaseNoAuthToHttpGithub(t *testing.T) { + // Verify the scheme guard independently of the hostname guard: an http:// + // api.github.com request must not carry a token even when tokens are + // configured. Use the transport seam with the logical URL so the + // githubAPIToken precondition (https + api.github.com) is exercised. + calls := 0 + var firstAuth, firstURL string + tr := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + firstAuth = req.Header.Get("Authorization") + firstURL = req.URL.String() + } + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(releaseJSON("v0.2.0"))), + Header: make(http.Header), + Request: req, + }, nil + }) + + old := httpClient + httpClient = &http.Client{Transport: tr} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "secret") + t.Setenv(EnvGitHubToken, "fallback") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _, err := fetchRelease(ctx, "http://api.github.com/repos/Gitlawb/zero/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if calls != 1 { + t.Fatalf("expected 1 request, got %d", calls) + } + if firstAuth != "" { + t.Fatalf("auth should not be sent over HTTP even with tokens: got %q", firstAuth) + } + if firstURL != "http://api.github.com/repos/Gitlawb/zero/releases/latest" { + t.Fatalf("unexpected URL %q", firstURL) + } +} + +// roundTripperFunc adapts a function to http.RoundTripper. +type roundTripperFunc func(*http.Request) (*http.Response, error) + +func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req) +} + +func TestFetchReleaseNoAuthWhenTokensNotSet(t *testing.T) { + ft := &fakeTransport{} + old := httpClient + httpClient = &http.Client{Transport: ft} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "") + t.Setenv(EnvGitHubToken, "") + + _, err := fetchRelease(context.Background(), "https://api.github.com/repos/Gitlawb/zero/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if ft.gotAuth != "" { + t.Fatalf("expected no auth when no tokens set, got %q", ft.gotAuth) + } +} + +func TestFetchReleaseRefusesRedirectToHttp(t *testing.T) { + calls := 0 + var firstAuth, firstURL string + tr := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + firstAuth = req.Header.Get("Authorization") + firstURL = req.URL.String() + return &http.Response{ + StatusCode: 301, + Header: http.Header{"Location": []string{"http://api.github.com/repos/Gitlawb/zero/releases/latest"}}, + Body: io.NopCloser(strings.NewReader("")), + Request: req, + }, nil + } + t.Fatalf("HTTP downgrade destination should not be contacted: %s %s calls=%d", req.Method, req.URL.String(), calls) + return nil, fmt.Errorf("unexpected request to HTTP destination") + }) + + old := httpClient + httpClient = &http.Client{Transport: tr} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "secret") + t.Setenv(EnvGitHubToken, "") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _, err := fetchRelease(ctx, "https://api.github.com/repos/Gitlawb/zero/releases/latest") + if err == nil || !strings.Contains(err.Error(), "refusing redirect") { + t.Fatalf("expected redirect refusal error, got %v", err) + } + if calls != 1 { + t.Fatalf("expected 1 transport call, HTTP destination should not be contacted: got %d", calls) + } + if firstAuth != "Bearer secret" { + t.Fatalf("initial HTTPS request should carry Bearer token: got %q", firstAuth) + } + if firstURL != "https://api.github.com/repos/Gitlawb/zero/releases/latest" { + t.Fatalf("unexpected initial URL %q", firstURL) + } +} + +func TestFetchReleaseRejectsUserinfoHostTrick(t *testing.T) { + // Userinfo trick: "https://api.github.com@evil.example.com/..." — the Go + // URL parser treats "api.github.com" as userinfo, making Hostname() = + // "evil.example.com". githubAPIToken sees a non-GitHub host and returns "", + // so no auth is sent. + ft := &fakeTransport{} + old := httpClient + httpClient = &http.Client{Transport: ft} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "secret") + t.Setenv(EnvGitHubToken, "") + + _, _ = fetchRelease(context.Background(), "https://api.github.com@evil.example.com/repos/Gitlawb/zero/releases/latest") + if strings.HasPrefix(ft.gotAuth, "Bearer ") { + t.Fatalf("bearer auth should not be sent when userinfo tricks hostname, got %q", ft.gotAuth) + } +} + +// --- Redirect regression tests (jatmn review) --- + +func TestHTTPMirrorRedirectAllowedWithoutCredentials(t *testing.T) { + // Mirror server redirects HTTP→HTTP (no credentials on original request). + var gotAuth string + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, releaseJSON("v0.2.0")) + })) + defer mirror.Close() + + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, mirror.URL+"/releases/latest", http.StatusFound) + })) + defer origin.Close() + + old := httpClient + httpClient = origin.Client() + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "") + t.Setenv(EnvGitHubToken, "") + + _, err := fetchRelease(context.Background(), origin.URL+"/releases/latest") + if err != nil { + t.Fatalf("HTTP mirror redirect should succeed, got: %v", err) + } + if gotAuth != "" { + t.Fatalf("expected no auth on mirror, got %q", gotAuth) + } +} + +func TestHTTPMirrorRedirectAllowedWithDummyTokens(t *testing.T) { + // Mirror redirect works even with tokens set — tokens are not sent to non-GitHub hosts. + var gotAuth string + mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAuth = r.Header.Get("Authorization") + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, releaseJSON("v0.2.0")) + })) + defer mirror.Close() + + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, mirror.URL+"/releases/latest", http.StatusFound) + })) + defer origin.Close() + + old := httpClient + httpClient = origin.Client() + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "dummy_token") + t.Setenv(EnvGitHubToken, "dummy_fallback") + + _, err := fetchRelease(context.Background(), origin.URL+"/releases/latest") + if err != nil { + t.Fatalf("HTTP mirror redirect should succeed even with tokens, got: %v", err) + } + if gotAuth != "" { + t.Fatalf("expected no auth for non-GitHub mirror, got %q", gotAuth) + } +} + +func TestHTTPSDowngradeBlockedWhenCredentialsPresent(t *testing.T) { + calls := 0 + var firstAuth string + tr := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + calls++ + if calls == 1 { + firstAuth = req.Header.Get("Authorization") + return &http.Response{ + StatusCode: 301, + Header: http.Header{"Location": []string{"http://api.github.com/other"}}, + Body: io.NopCloser(strings.NewReader("")), + Request: req, + }, nil + } + t.Fatalf("HTTP downgrade destination should not be contacted: %s %s calls=%d", req.Method, req.URL.String(), calls) + return nil, fmt.Errorf("unexpected request") + }) + + old := httpClient + httpClient = &http.Client{Transport: tr} + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "secret") + t.Setenv(EnvGitHubToken, "fallback_should_not_be_used") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + _, err := fetchRelease(ctx, "https://api.github.com/repos/Gitlawb/zero/releases/latest") + if err == nil || !strings.Contains(err.Error(), "refusing redirect") { + t.Fatalf("expected redirect refusal, got %v", err) + } + if calls != 1 { + t.Fatalf("expected 1 call, got %d", calls) + } + if firstAuth != "Bearer secret" { + t.Fatalf("expected Bearer secret on first request, got %q", firstAuth) + } +} + +func TestHTTPSSameHostRedirectAllowed(t *testing.T) { + // HTTPS server redirects to same HTTPS host — should succeed. + var gotPath string + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + if r.URL.Path == "/repos/Gitlawb/zero/releases" { + http.Redirect(w, r, "/repos/Gitlawb/zero/releases/latest", http.StatusFound) + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, releaseJSON("v0.2.0")) + })) + defer srv.Close() + + old := httpClient + httpClient = srv.Client() + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "token123") + t.Setenv(EnvGitHubToken, "") + + _, err := fetchRelease(context.Background(), srv.URL+"/repos/Gitlawb/zero/releases") + if err != nil { + t.Fatalf("HTTPS→HTTPS same-host redirect should succeed, got: %v", err) + } + if gotPath != "/repos/Gitlawb/zero/releases/latest" { + t.Fatalf("expected final path /repos/Gitlawb/zero/releases/latest, got %q", gotPath) + } +} + +func TestRedirectLimitEnforced(t *testing.T) { + count := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + count++ + if count > 10 { + http.Error(w, "too many", http.StatusLoopDetected) + return + } + http.Redirect(w, r, "/loop", http.StatusFound) + })) + defer srv.Close() + + old := httpClient + httpClient = srv.Client() + t.Cleanup(func() { httpClient = old }) + + t.Setenv(EnvUpdateToken, "") + t.Setenv(EnvGitHubToken, "") + + _, err := fetchRelease(context.Background(), srv.URL+"/loop") + if err == nil { + t.Fatal("expected error for redirect loop") + } + if !strings.Contains(err.Error(), "10 redirects") { + t.Fatalf("expected redirect limit error, got: %v", err) + } +} diff --git a/internal/update/update.go b/internal/update/update.go index 8fa298dbce..a86000eaf5 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -3,6 +3,7 @@ package update import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/url" @@ -17,8 +18,19 @@ import ( const ( DefaultRepository = "Twigpine/zero" DefaultTimeout = 5 * time.Second + // EnvUpdateToken is read by fetchRelease to authenticate GitHub API + // requests. ZERO_GITHUB_TOKEN takes precedence over GITHUB_TOKEN. + EnvUpdateToken = "ZERO_GITHUB_TOKEN" + // EnvGitHubToken is the fallback token variable used for GitHub API requests. + EnvGitHubToken = "GITHUB_TOKEN" + // EnvUpdateReleaseURL overrides the release API endpoint. + EnvUpdateReleaseURL = "ZERO_UPDATE_RELEASE_URL" ) +// httpClient is the client used by fetchRelease. Overridden in tests to +// intercept requests without mutating the global http.DefaultClient. +var httpClient = http.DefaultClient + type Release struct { TagName string `json:"tag_name"` HTMLURL string `json:"html_url"` @@ -129,7 +141,7 @@ func Check(ctx context.Context, options Options) (Result, error) { currentVersion = "0.0.0" } repository := strings.TrimSpace(firstNonEmpty(options.Repository, DefaultRepository)) - endpoint, err := resolveEndpoint(firstNonEmpty(options.Endpoint, os.Getenv("ZERO_UPDATE_RELEASE_URL")), repository) + endpoint, err := resolveEndpoint(firstNonEmpty(options.Endpoint, os.Getenv(EnvUpdateReleaseURL)), repository) if err != nil { return Result{}, err } @@ -203,7 +215,7 @@ func upgradeSourceFlag(options Options) string { if endpoint := strings.TrimSpace(options.Endpoint); endpoint != "" { return "--endpoint " + shellQuote(endpoint) } - if strings.TrimSpace(os.Getenv("ZERO_UPDATE_RELEASE_URL")) != "" { + if strings.TrimSpace(os.Getenv(EnvUpdateReleaseURL)) != "" { return "" } if repository := strings.TrimSpace(options.Repository); repository != "" && repository != DefaultRepository { @@ -340,6 +352,16 @@ func upgradeGuidance(asset AssetCheck, sourceFlag string, installMethod InstallM return "Run `zero upgrade` to download, verify, and install the latest release." } +func githubAPIToken(u *url.URL) string { + if u.Scheme != "https" || !strings.EqualFold(u.Hostname(), "api.github.com") { + return "" + } + if token := os.Getenv(EnvUpdateToken); token != "" { + return token + } + return os.Getenv(EnvGitHubToken) +} + func fetchRelease(ctx context.Context, endpoint string) (release Release, err error) { if strings.HasPrefix(endpoint, "data:") { return fetchDataRelease(endpoint) @@ -350,7 +372,26 @@ func fetchRelease(ctx context.Context, endpoint string) (release Release, err er } request.Header.Set("Accept", "application/vnd.github+json") request.Header.Set("User-Agent", "zero/update") - response, err := http.DefaultClient.Do(request) + if token := githubAPIToken(request.URL); token != "" { + request.Header.Set("Authorization", "Bearer "+token) + } + client := &http.Client{ + Transport: httpClient.Transport, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return errors.New("stopped after 10 redirects") + } + if req.URL.Scheme != "https" { + for _, prev := range via { + if githubAPIToken(prev.URL) != "" { + return errors.New("refusing redirect to non-HTTPS URL") + } + } + } + return nil + }, + } + response, err := client.Do(request) if err != nil { return Release{}, err } From a993a3d78c40adba281ca675aa6ae885ae55ff39 Mon Sep 17 00:00:00 2001 From: jatmn Date: Mon, 9 Nov 2026 16:09:00 -0800 Subject: [PATCH 2/3] fix(update): normalize credentials and address review findings --- docs/UPDATE.md | 23 +++++----- internal/cli/app_test.go | 19 ++------- internal/cli/update.go | 6 +-- internal/update/auth_test.go | 81 ++++++++++++++++++++++++++++++++++++ internal/update/update.go | 6 +-- 5 files changed, 102 insertions(+), 33 deletions(-) diff --git a/docs/UPDATE.md b/docs/UPDATE.md index ccdeea3a98..f2c8bfab26 100644 --- a/docs/UPDATE.md +++ b/docs/UPDATE.md @@ -84,18 +84,21 @@ If you see `403 Forbidden` during update checks, set a GitHub personal access to | Environment variable | Role | |---|---| | `ZERO_GITHUB_TOKEN` | Used for update checks (takes precedence) | -| `GITHUB_TOKEN` | Fallback when `ZERO_GITHUB_TOKEN` is not set | +| `GITHUB_TOKEN` | Fallback when `ZERO_GITHUB_TOKEN` is empty after trimming | + +Surrounding whitespace is removed from both token values before use. Note: `GITHUB_TOKEN` is also used by the GitHub Models provider -(`internal/providercatalog/catalog.go:150`); both recipients are GitHub so no -trust boundary is crossed, but a token set for the provider will also be sent -on update checks. - -Tokens are only sent when the request URL is `https://api.github.com`. Custom -endpoints (set via `--endpoint` or `ZERO_UPDATE_RELEASE_URL`) and plain HTTP -URLs never receive credentials. Redirects that downgrade to `http` are refused, -so the bearer token is never sent in cleartext (Go's standard library would -otherwise copy `Authorization` on same-host redirects based on host alone). +(the `github` descriptor in `internal/providercatalog/catalog.go`); both +recipients are GitHub so no trust boundary is crossed, but a token set for +the provider will also be sent on update checks. + +Tokens are only sent to HTTPS URLs with the hostname `api.github.com`, including +URLs selected through `--endpoint` or `ZERO_UPDATE_RELEASE_URL`. Other hosts +and plain HTTP URLs never receive credentials. Redirects that downgrade to +`http` after a token-eligible GitHub API request are refused, so the bearer +token is never sent in cleartext (Go's standard library would otherwise copy +`Authorization` on same-host redirects based on host alone). ## Windows recovery state (standalone installs) diff --git a/internal/cli/app_test.go b/internal/cli/app_test.go index c12eb5017d..0de265d2b0 100644 --- a/internal/cli/app_test.go +++ b/internal/cli/app_test.go @@ -1601,22 +1601,9 @@ func TestRunUpdateHelpDocumentsCheckFlag(t *testing.T) { t.Fatalf("expected update help to document %s, got %q", want, stdout.String()) } } - // GITHUB_TOKEN must appear as a standalone token, not as a substring of ZERO_GITHUB_TOKEN. - out := stdout.String() - if idx := strings.Index(out, "GITHUB_TOKEN"); idx < 0 { - t.Fatalf("expected update help to document GITHUB_TOKEN, got %q", out) - } else if idx >= 5 && out[idx-5:idx] == "ZERO_" { - // Check after the ZERO_GITHUB_TOKEN occurrence too. - rest := out[idx+len("GITHUB_TOKEN"):] - if !strings.Contains(rest, "GITHUB_TOKEN") { - // Only ZERO_GITHUB_TOKEN matched; GITHUB_TOKEN is missing as a standalone entry. - // Find the first occurrence for the error message. - firstIdx := strings.Index(out, "ZERO_GITHUB_TOKEN") - after := out[firstIdx+len("ZERO_GITHUB_TOKEN"):] - if !strings.Contains(after, "GITHUB_TOKEN") { - t.Fatalf("expected update help to document GITHUB_TOKEN (standalone), got %q", out) - } - } + // The fallback entry must have its own line, apart from the precedence prose. + if !strings.Contains(stdout.String(), "\n GITHUB_TOKEN ") { + t.Fatalf("expected update help to document a standalone GITHUB_TOKEN entry, got %q", stdout.String()) } if stderr.Len() != 0 { t.Fatalf("expected empty stderr, got %q", stderr.String()) diff --git a/internal/cli/update.go b/internal/cli/update.go index 98695ecf69..2aecb8b78e 100644 --- a/internal/cli/update.go +++ b/internal/cli/update.go @@ -210,9 +210,9 @@ Flags: Environment: ZERO_GITHUB_TOKEN Token for update checks (takes precedence over GITHUB_TOKEN) - Only sent to https://api.github.com over HTTPS; never sent to custom endpoints - or on redirect to plain HTTP - GITHUB_TOKEN Fallback token for update checks + Only sent to HTTPS URLs on api.github.com, including endpoint overrides; + never sent to other hosts or plain HTTP + GITHUB_TOKEN Fallback token when ZERO_GITHUB_TOKEN is empty after trimming ZERO_UPDATE_RELEASE_URL Override the release API URL (same as --endpoint) `) return err diff --git a/internal/update/auth_test.go b/internal/update/auth_test.go index d7aa56c29e..70ce971156 100644 --- a/internal/update/auth_test.go +++ b/internal/update/auth_test.go @@ -95,6 +95,37 @@ func TestFetchReleaseFallsBackToGithubToken(t *testing.T) { } } +func TestFetchReleaseNormalizesTokens(t *testing.T) { + for _, tc := range []struct { + name string + updateToken string + githubToken string + wantAuth string + }{ + {"blank preferred falls back", " \t\n", "fallback_token", "Bearer fallback_token"}, + {"trim preferred", " \tzero_token\r\n", "fallback_token", "Bearer zero_token"}, + {"trim fallback", "", " \tfallback_token\r\n", "Bearer fallback_token"}, + {"both blank", " \t\n", "\r\n ", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + ft := &fakeTransport{} + old := httpClient + httpClient = &http.Client{Transport: ft} + t.Cleanup(func() { httpClient = old }) + t.Setenv(EnvUpdateToken, tc.updateToken) + t.Setenv(EnvGitHubToken, tc.githubToken) + + _, err := fetchRelease(context.Background(), "https://api.github.com/repos/Gitlawb/zero/releases/latest") + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if ft.gotAuth != tc.wantAuth { + t.Fatalf("Authorization = %q, want %q", ft.gotAuth, tc.wantAuth) + } + }) + } +} + func TestFetchReleaseNoAuthToCustomEndpoint(t *testing.T) { var gotAuth string srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -388,6 +419,56 @@ func TestHTTPSSameHostRedirectAllowed(t *testing.T) { } } +func TestFetchReleaseAuthenticatedHTTPSRedirects(t *testing.T) { + for _, tc := range []struct { + name string + location string + wantAuth string + }{ + {"same host", "https://api.github.com/redirected", "Bearer secret"}, + {"other host", "https://mirror.example.test/redirected", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + var urls, auth []string + tr := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + urls = append(urls, req.URL.String()) + auth = append(auth, req.Header.Get("Authorization")) + response := &http.Response{ + StatusCode: http.StatusOK, + Header: make(http.Header), + Body: io.NopCloser(strings.NewReader(releaseJSON("v0.2.0"))), + Request: req, + } + if len(urls) == 1 { + response.StatusCode = http.StatusFound + response.Header.Set("Location", tc.location) + } + return response, nil + }) + old := httpClient + httpClient = &http.Client{Transport: tr} + t.Cleanup(func() { httpClient = old }) + t.Setenv(EnvUpdateToken, "secret") + t.Setenv(EnvGitHubToken, "") + + const endpoint = "https://api.github.com/repos/Gitlawb/zero/releases/latest" + release, err := fetchRelease(context.Background(), endpoint) + if err != nil { + t.Fatalf("fetchRelease error: %v", err) + } + if len(urls) != 2 || urls[0] != endpoint || urls[1] != tc.location { + t.Fatalf("unexpected redirect route: %v", urls) + } + if auth[0] != "Bearer secret" || auth[1] != tc.wantAuth { + t.Fatalf("Authorization per hop = %q, want [%q %q]", auth, "Bearer secret", tc.wantAuth) + } + if release.TagName != "v0.2.0" { + t.Fatalf("release tag = %q, want v0.2.0", release.TagName) + } + }) + } +} + func TestRedirectLimitEnforced(t *testing.T) { count := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/update/update.go b/internal/update/update.go index a86000eaf5..7b44b2ea57 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -352,14 +352,12 @@ func upgradeGuidance(asset AssetCheck, sourceFlag string, installMethod InstallM return "Run `zero upgrade` to download, verify, and install the latest release." } +// githubAPIToken selects a trimmed token only for HTTPS GitHub API URLs. func githubAPIToken(u *url.URL) string { if u.Scheme != "https" || !strings.EqualFold(u.Hostname(), "api.github.com") { return "" } - if token := os.Getenv(EnvUpdateToken); token != "" { - return token - } - return os.Getenv(EnvGitHubToken) + return firstNonEmpty(os.Getenv(EnvUpdateToken), os.Getenv(EnvGitHubToken)) } func fetchRelease(ctx context.Context, endpoint string) (release Release, err error) { From 72f71e7e1abeed554d7b0b075b6c2706dbbcebd1 Mon Sep 17 00:00:00 2001 From: jatmn Date: Mon, 9 Nov 2026 16:18:23 -0800 Subject: [PATCH 3/3] fix(update): enforce exact-host credentials on redirects --- internal/update/auth_test.go | 1 + internal/update/update.go | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/internal/update/auth_test.go b/internal/update/auth_test.go index 70ce971156..9168f017cd 100644 --- a/internal/update/auth_test.go +++ b/internal/update/auth_test.go @@ -427,6 +427,7 @@ func TestFetchReleaseAuthenticatedHTTPSRedirects(t *testing.T) { }{ {"same host", "https://api.github.com/redirected", "Bearer secret"}, {"other host", "https://mirror.example.test/redirected", ""}, + {"subdomain", "https://sub.api.github.com/redirected", ""}, } { t.Run(tc.name, func(t *testing.T) { var urls, auth []string diff --git a/internal/update/update.go b/internal/update/update.go index 7b44b2ea57..82ef3a694b 100644 --- a/internal/update/update.go +++ b/internal/update/update.go @@ -386,6 +386,10 @@ func fetchRelease(ctx context.Context, endpoint string) (release Release, err er } } } + // net/http also forwards Authorization to subdomains; keep the exact-host boundary. + if req.URL.Scheme != "https" || !strings.EqualFold(req.URL.Hostname(), "api.github.com") { + req.Header.Del("Authorization") + } return nil }, }