diff --git a/docs/configuration.md b/docs/configuration.md index a0bff49a..b907cf58 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1212,6 +1212,8 @@ This field has no environment variable, as with the other named upstream maps. Configure authentication for private upstream registries. The same authentication-aware client is used for metadata and artifact downloads, and credentials can reference environment variables using `${VAR_NAME}` syntax. +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. + 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/config/auth_validate_test.go b/internal/config/auth_validate_test.go new file mode 100644 index 00000000..013371de --- /dev/null +++ b/internal/config/auth_validate_test.go @@ -0,0 +1,135 @@ +package config + +import ( + "strings" + "testing" +) + +func TestValidateRejectsUnknownUpstreamAuthType(t *testing.T) { + for _, typ := range []string{"token", "", "bearer "} { + cfg := Default() + cfg.Upstream.Auth = map[string]AuthConfig{ + "https://registry.example.com/private": {Type: typ, Token: "t"}, + } + err := cfg.Validate() + if err == nil { + t.Fatalf("type %q: Validate() error = nil, want an unknown type error", typ) + } + for _, want := range []string{"upstream.auth", "https://registry.example.com/private", `"` + typ + `"`, "bearer, basic, header or ecr"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("type %q: Validate() error = %q, want it to contain %q", typ, err, want) + } + } + } +} + +func TestValidateAcceptsEveryUpstreamAuthType(t *testing.T) { + for _, typ := range []string{"bearer", "basic", "header", "ecr", "Bearer", "ECR"} { + cfg := Default() + cfg.Upstream.Auth = map[string]AuthConfig{ + "https://registry.example.com": {Type: typ}, + } + if err := cfg.Validate(); err != nil { + t.Errorf("type %q: Validate() error = %v", typ, err) + } + } +} + +func TestWarningsUpstreamAuthWithoutCredentials(t *testing.T) { + t.Setenv("AUTH_TEST_SET", "secret") + t.Setenv("AUTH_TEST_EMPTY", "") + + cfg := Default() + cfg.Upstream.Auth = map[string]AuthConfig{ + "https://ok-bearer.example.com": {Type: "bearer", Token: "${AUTH_TEST_SET}"}, + "https://ok-basic.example.com": {Type: "basic", Username: "u"}, + "https://ok-header.example.com": {Type: "header", HeaderName: "X-Key", HeaderValue: "${AUTH_TEST_SET}"}, + "https://ok-ecr.example.com": {Type: "ecr"}, + "https://no-token.example.com": {Type: "bearer", Token: "${AUTH_TEST_EMPTY}"}, + "https://no-user.example.com": {Type: "basic", Password: "p"}, + "https://no-name.example.com": {Type: "header", HeaderValue: "v"}, + "https://no-value.example.com": {Type: "header", HeaderName: "X-Key", HeaderValue: "${AUTH_TEST_EMPTY}"}, + "https://a-no-token.example.com/p": {Type: "Bearer"}, + } + + var got []string + for _, w := range cfg.Warnings() { + if strings.Contains(w, "upstream.auth") { + got = append(got, w) + } + } + want := []string{ + "https://a-no-token.example.com/p", + "https://no-name.example.com", + "https://no-token.example.com", + "https://no-user.example.com", + "https://no-value.example.com", + } + if len(got) != len(want) { + t.Fatalf("Warnings() = %q, want one for each of %q", got, want) + } + for i, scope := range want { + if !strings.Contains(got[i], `"`+scope+`"`) || !strings.Contains(got[i], "without credentials") { + t.Errorf("warning %d = %q, want it to name %q and say requests go out without credentials", i, got[i], scope) + } + if strings.Contains(got[i], "secret") { + t.Errorf("warning %d = %q leaks a credential", i, got[i]) + } + } +} + +// A scope can carry a credential of its own, which the messages naming the +// scope leave out. +func TestUpstreamAuthMessagesLeaveOutScopeCredentials(t *testing.T) { + const scope = "https://user:scope-pass@registry.example.com/private?api_key=scope-secret" + const shown = `"https://registry.example.com/private"` + + cfg := Default() + cfg.Upstream.Auth = map[string]AuthConfig{scope: {Type: "bearer"}} + var warning string + for _, w := range cfg.Warnings() { + if strings.Contains(w, "upstream.auth") { + warning = w + } + } + + cfg.Upstream.Auth = map[string]AuthConfig{scope: {Type: "token"}} + err := cfg.Validate() + if err == nil { + t.Fatal("Validate() error = nil, want an unknown type error") + } + + for name, message := range map[string]string{"warning": warning, "error": err.Error()} { + if !strings.Contains(message, shown) { + t.Errorf("%s = %q, want it to name %s", name, message, shown) + } + for _, secret := range []string{"scope-pass", "scope-secret", "user:", "api_key"} { + if strings.Contains(message, secret) { + t.Errorf("%s = %q, want it without %q", name, message, secret) + } + } + } +} + +// An invalid scope is named without its credentials too. +func TestInvalidUpstreamAuthScopeLeavesOutItsCredentials(t *testing.T) { + for scope, shown := range map[string]string{ + "https://user:scope-pass@/private?api_key=scope-secret": `"https:///private"`, + "https://user:scope-pass@host/%zz?api_key=scope-secret": `"(invalid URL)"`, + } { + cfg := Default() + cfg.Upstream.Auth = map[string]AuthConfig{scope: {Type: "bearer", Token: "t"}} + err := cfg.Validate() + if err == nil { + t.Fatalf("%s: Validate() error = nil, want an invalid URL error", shown) + } + if !strings.Contains(err.Error(), shown) { + t.Errorf("Validate() error = %q, want it to name %s", err, shown) + } + for _, secret := range []string{"scope-pass", "scope-secret", "user:", "api_key"} { + if strings.Contains(err.Error(), secret) { + t.Errorf("Validate() error = %q, want it without %q", err, secret) + } + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 837213c8..63dda7da 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -961,10 +961,8 @@ func (u *UpstreamConfig) AuthForURL(url string) *AuthConfig { // Validate checks upstream authentication URL scopes. func (u *UpstreamConfig) Validate() error { - for pattern := range u.Auth { - if _, err := parseAuthURL(pattern); err != nil { - return fmt.Errorf("invalid upstream.auth URL %q: %w", pattern, err) - } + if err := u.validateAuth(); err != nil { + return err } if err := validateNamedUpstreams("upstream.helm", u.Helm); err != nil { return err @@ -2341,6 +2339,45 @@ func (a *AuthConfig) Header() (name, value string) { } } +func (u *UpstreamConfig) validateAuth() error { + for pattern, auth := range u.Auth { + if _, err := parseAuthURL(pattern); err != nil { + return fmt.Errorf("invalid upstream.auth URL %q: %w", authScopeName(pattern), err) + } + switch strings.ToLower(auth.Type) { + case "bearer", "basic", "header", "ecr": + default: + return fmt.Errorf("invalid upstream.auth %q: unknown type %q, must be bearer, basic, header or ecr", authScopeName(pattern), auth.Type) + } + } + return nil +} + +// authScopeName returns an upstream.auth scope for a message, without the +// user information and query a scope can carry credentials in. +func authScopeName(pattern string) string { + parsed, err := url.Parse(pattern) + if err != nil { + return "(invalid URL)" + } + return (&url.URL{Scheme: parsed.Scheme, Host: parsed.Host, Path: parsed.Path, RawPath: parsed.RawPath}).String() +} + +// An ECR entry gets its credentials from AWS. +func (u *UpstreamConfig) authWithoutCredentials() []string { + var scopes []string + for pattern, auth := range u.Auth { + if strings.EqualFold(auth.Type, "ecr") { + continue + } + if name, value := auth.Header(); name == "" || value == "" { + scopes = append(scopes, authScopeName(pattern)) + } + } + slices.Sort(scopes) + return scopes +} + // expandEnv expands ${VAR_NAME} references in a string. func expandEnv(s string) string { return os.Expand(s, os.Getenv) diff --git a/internal/config/mirror.go b/internal/config/mirror.go index 3b56fd87..790dfe0d 100644 --- a/internal/config/mirror.go +++ b/internal/config/mirror.go @@ -144,6 +144,9 @@ func (c *Config) Warnings() []string { if c.Mirror.Refresh != nil && !c.CacheMetadata { warnings = append(warnings, "mirror.refresh without cache_metadata does not refresh Debian, Alpine or RPM packages: their indexes are found through the metadata cache") } + for _, scope := range c.Upstream.authWithoutCredentials() { + warnings = append(warnings, fmt.Sprintf("upstream.auth %q has nothing to send, so requests under it go out without credentials: its token, username, header name or header value is empty, after expanding ${VAR} references", scope)) + } return warnings }