Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.

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:
Expand Down
151 changes: 151 additions & 0 deletions internal/httpclient/redirect_auth_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
25 changes: 25 additions & 0 deletions internal/httpclient/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading