From 62884e387ec38ece09345f560a84dc82b77bdfd9 Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Sun, 22 Nov 2026 10:57:54 +0100 Subject: [PATCH 1/2] Keep upstream.auth credentials off a redirect into their scope A redirect hop got the credentials of the scope its URL is in, so an upstream could redirect past generic_paths and a git upstream's repos. A hop now only gets credentials the request it started from was given. --- docs/configuration.md | 2 + internal/httpclient/redirect_auth_test.go | 151 ++++++++++++++++++++++ internal/httpclient/transport.go | 25 ++++ 3 files changed, 178 insertions(+) create mode 100644 internal/httpclient/redirect_auth_test.go diff --git a/docs/configuration.md b/docs/configuration.md index 991fb61d..50f51890 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1214,6 +1214,8 @@ Configure authentication for private upstream registries. The same authenticatio The `type` is `bearer`, `basic`, `header` or `ecr`; any other value fails the configuration check. An entry that ends up with nothing to send, such as a token whose `${VAR_NAME}` is unset, is still the match for its scope, so requests under it go out without credentials. The proxy logs a warning naming each such entry at startup, except an `ecr` entry: it gets its token from AWS when a request needs one, and a failed fetch is logged as an error then. +A redirect only gets an entry's credentials when the request it started from was given the same ones. A redirect from another upstream into a scope, or from one scope into another, goes out without them, so it can't reach past the routes `generic_paths` and a git upstream's `repos` allow. A redirect to a URL no entry covers is followed as before. + OCI registries that return a Bearer challenge from a `/v2/{repository}/…` endpoint are handled automatically. The proxy discovers the token realm from `WWW-Authenticate`, applies any configured credentials for the token URL, and reuses the token until shortly before it expires. The token is always requested for pull access to the repository being fetched (`repository:{repository}:pull`), whatever scope the challenge names. If the token URL redirects, the redirected request only carries credentials when the redirect target is configured with the same ones as the token URL, so a token URL that redirects to a token service with its own credentials needs those credentials configured for both. A token fetched with credentials configured for the token URL is only fetched for, and sent to, a registry that is trusted with it: one on the same host and port as the token service, one configured with the same credentials as the token URL, or Docker Hub (`registry-1.docker.io` and `index.docker.io` with `auth.docker.io`) and GitLab.com (`registry.gitlab.com` with `gitlab.com`). Sharing a parent domain is not enough, so `team-a.jfrog.io` is not trusted with tokens from `team-b.jfrog.io`. Any other host that answers with a challenge naming that token service gets its 401 back, so it cannot obtain a token minted from your credentials. Tokens from a token service with no configured credentials are anonymous and are fetched for any registry, as before. If your registry and its token service are on different hosts, such as a self-hosted GitLab with its registry on its own hostname, configure the same credentials for both URLs: diff --git a/internal/httpclient/redirect_auth_test.go b/internal/httpclient/redirect_auth_test.go new file mode 100644 index 00000000..8085ed4f --- /dev/null +++ b/internal/httpclient/redirect_auth_test.go @@ -0,0 +1,151 @@ +package httpclient + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" +) + +// redirectServers is a scoped server recording the Authorization it gets, +// and an origin. Both redirect a path containing /to/ to what follows it, on +// the scoped server. +type redirectServers struct { + scoped, origin *httptest.Server + mu sync.Mutex + got []string +} + +func newRedirectServers(t *testing.T) *redirectServers { + t.Helper() + s := &redirectServers{} + s.scoped = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, target, ok := strings.Cut(r.URL.Path, "/to/"); ok { + http.Redirect(w, r, s.scoped.URL+"/"+target, http.StatusFound) + return + } + s.mu.Lock() + s.got = append(s.got, r.Header.Get("Authorization")) + s.mu.Unlock() + _, _ = io.WriteString(w, "ok") + })) + t.Cleanup(s.scoped.Close) + s.origin = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + target, _ := strings.CutPrefix(r.URL.Path, "/to/") + http.Redirect(w, r, s.scoped.URL+"/"+target, http.StatusFound) + })) + t.Cleanup(s.origin.Close) + return s +} + +func (s *redirectServers) get(t *testing.T, authForURL AuthFunc, rawURL string) string { + t.Helper() + s.mu.Lock() + s.got = nil + s.mu.Unlock() + client := &http.Client{Transport: NewTransport(http.DefaultTransport, authForURL)} + resp, err := client.Get(rawURL) + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + s.mu.Lock() + defer s.mu.Unlock() + if len(s.got) != 1 { + t.Fatalf("scoped server got %d requests, want 1", len(s.got)) + } + return s.got[0] +} + +// TestTransportKeepsCredentialsOutOfARedirectIntoTheirScope checks a +// redirect hop only gets upstream.auth credentials that the request it +// started from was given too, so a redirect can't reach past the routes +// the client's request was checked against. +func TestTransportKeepsCredentialsOutOfARedirectIntoTheirScope(t *testing.T) { + s := newRedirectServers(t) + scopes := func(scopes map[string]string) AuthFunc { + return func(rawURL string) (string, string) { + best := "" + for prefix := range scopes { + if strings.HasPrefix(rawURL, prefix) && len(prefix) > len(best) { + best = prefix + } + } + if best == "" { + return "", "" + } + return "Authorization", scopes[best] + } + } + + for name, tc := range map[string]struct { + auth map[string]string + start string + want string + }{ + "from outside the scope": { + map[string]string{s.scoped.URL + "/private": "Bearer secret"}, s.origin.URL + "/to/private/x", "", + }, + "from another scope": { + map[string]string{s.scoped.URL + "/private": "Bearer secret", s.origin.URL: "Bearer other"}, s.origin.URL + "/to/private/x", "", + }, + "through the scope's host from outside it": { + map[string]string{s.scoped.URL + "/private": "Bearer secret"}, s.origin.URL + "/to/to/private/x", "", + }, + "through the scope from outside it": { + map[string]string{s.scoped.URL + "/private": "Bearer secret"}, s.origin.URL + "/to/private/to/private/x", "", + }, + "within the scope": { + map[string]string{s.scoped.URL + "/private": "Bearer secret"}, s.scoped.URL + "/private/to/private/y", "Bearer secret", + }, + "to a scope with the same credentials": { + map[string]string{s.scoped.URL + "/private": "Bearer secret", s.origin.URL: "Bearer secret"}, s.origin.URL + "/to/private/x", "Bearer secret", + }, + } { + t.Run(name, func(t *testing.T) { + if got := s.get(t, scopes(tc.auth), tc.start); got != tc.want { + t.Errorf("scoped server got Authorization %q, want %q", got, tc.want) + } + }) + } +} + +// TestTransportRedirectWithoutCredentialsStillGetsAToken checks a redirect +// hop that upstream.auth has nothing for is treated as before: it may still +// fetch an anonymous registry token. +func TestTransportRedirectWithoutCredentialsStillGetsAToken(t *testing.T) { + var registry *httptest.Server + registry = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/token" { + _, _ = io.WriteString(w, `{"token":"anonymous"}`) + return + } + if r.Header.Get("Authorization") != "Bearer anonymous" { + w.Header().Set("WWW-Authenticate", `Bearer realm="`+registry.URL+`/token"`) + w.WriteHeader(http.StatusUnauthorized) + } + })) + defer registry.Close() + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, registry.URL+"/v2/x/y/manifests/latest", http.StatusFound) + })) + defer origin.Close() + authForURL := func(rawURL string) (string, string) { + if strings.HasPrefix(rawURL, origin.URL) { + return "Authorization", "Bearer secret" + } + return "", "" + } + + client := &http.Client{Transport: NewTransport(http.DefaultTransport, authForURL)} + resp, err := client.Get(origin.URL + "/start") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Errorf("status = %d, want 200 with an anonymous token", resp.StatusCode) + } +} diff --git a/internal/httpclient/transport.go b/internal/httpclient/transport.go index ba79d49c..1f4e1e7f 100644 --- a/internal/httpclient/transport.go +++ b/internal/httpclient/transport.go @@ -81,6 +81,9 @@ func NewTransport(base http.RoundTripper, authForURL AuthFunc) *Transport { // RoundTrip implements http.RoundTripper. func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + if !t.redirectKeepsCredentials(req) { + return t.base.RoundTrip(req) + } hasExplicitAuthorization := req.Header.Get("Authorization") != "" outbound := cloneRequest(req) t.applyAuthentication(outbound, hasExplicitAuthorization) @@ -121,6 +124,28 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { return t.base.RoundTrip(retry) } +// redirectKeepsCredentials reports whether a request may get authentication +// added. A redirect hop upstream.auth has credentials for only may when it +// gives the request the redirects started from the same ones: that +// request's route was checked against generic_paths and git repos, and a +// redirect from an upstream must not reach past them with another scope's +// credentials. +func (t *Transport) redirectKeepsCredentials(req *http.Request) bool { + if t.authForURL == nil { + return true + } + name, value := t.authForURL(req.URL.String()) + if name == "" || value == "" { + return true + } + origin := req + for origin.Response != nil && origin.Response.Request != nil { + origin = origin.Response.Request + } + originName, originValue := t.authForURL(origin.URL.String()) + return sameHeader(name, value, originName, originValue) +} + // trustedWithToken reports whether a token from challenge's realm may be // fetched for, and sent to, the registry at requestURL. The challenge comes // from that registry, which can be any host the proxy fetches from, such as From 3f70542b292598d4529cfbeb4c26e3b6c8abf894 Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Sun, 22 Nov 2026 13:47:18 +0100 Subject: [PATCH 2/2] docs: a redirect between scopes with the same credentials keeps them --- docs/configuration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/configuration.md b/docs/configuration.md index 50f51890..cff025c5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1214,7 +1214,7 @@ Configure authentication for private upstream registries. The same authenticatio The `type` is `bearer`, `basic`, `header` or `ecr`; any other value fails the configuration check. An entry that ends up with nothing to send, such as a token whose `${VAR_NAME}` is unset, is still the match for its scope, so requests under it go out without credentials. The proxy logs a warning naming each such entry at startup, except an `ecr` entry: it gets its token from AWS when a request needs one, and a failed fetch is logged as an error then. -A redirect only gets an entry's credentials when the request it started from was given the same ones. A redirect from another upstream into a scope, or from one scope into another, goes out without them, so it can't reach past the routes `generic_paths` and a git upstream's `repos` allow. A redirect to a URL no entry covers is followed as before. +A redirect only gets an entry's credentials when the request it started from was given the same ones. A redirect from another upstream into a scope, or from one scope into another with different ones, goes out without them, so it can't reach past the routes `generic_paths` and a git upstream's `repos` allow. A redirect to a URL no entry covers is followed as before. OCI registries that return a Bearer challenge from a `/v2/{repository}/…` endpoint are handled automatically. The proxy discovers the token realm from `WWW-Authenticate`, applies any configured credentials for the token URL, and reuses the token until shortly before it expires. The token is always requested for pull access to the repository being fetched (`repository:{repository}:pull`), whatever scope the challenge names. If the token URL redirects, the redirected request only carries credentials when the redirect target is configured with the same ones as the token URL, so a token URL that redirects to a token service with its own credentials needs those credentials configured for both.