diff --git a/docs/configuration.md b/docs/configuration.md index 941f1070..565592ee 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1256,7 +1256,7 @@ 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. +The `type` is `bearer`, `basic`, `header`, `ecr` or `codeartifact`; 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` or `codeartifact` 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. @@ -1348,6 +1348,23 @@ upstream: type: ecr ``` +### AWS CodeArtifact + +CodeArtifact authorization tokens expire after at most 12 hours. The `codeartifact` auth type calls `codeartifact:GetAuthorizationToken` on demand, caches the token per domain, owner and region, refreshes it shortly before expiry, and sends it as a Bearer token. Use it with a package route to serve a private scope from CodeArtifact to clients that have no AWS credentials: + +```yaml +upstream: + npm_routes: + "@example/*": "https://example-123456789012.d.codeartifact.eu-west-1.amazonaws.com/npm/private/" + allow_private_hosts: + - "example-123456789012.d.codeartifact.eu-west-1.amazonaws.com" + auth: + "https://example-123456789012.d.codeartifact.eu-west-1.amazonaws.com": + type: codeartifact +``` + +The auth URL must be a repository endpoint host, `{domain}-{owner}.d.codeartifact.{region}.amazonaws.com`; the domain, owner and region are read from it, and `region` overrides the region. AWS credentials are resolved by the SDK's default chain, as for ECR. The IAM identity needs `codeartifact:GetAuthorizationToken` on the domain, `sts:GetServiceBearerToken` with the condition `sts:AWSServiceName` = `codeartifact.amazonaws.com`, and `codeartifact:ReadFromRepository` on the repository. + ### URL Matching Auth keys must be absolute URLs. Matching compares the scheme, host, effective port, and path-segment prefix, preventing credentials for `registry.example.com` from being sent to a lookalike host such as `registry.example.com.evil.test`. The longest matching scope wins, so you can configure different credentials for different paths: diff --git a/go.mod b/go.mod index 3902c9d1..2ec96652 100644 --- a/go.mod +++ b/go.mod @@ -5,12 +5,12 @@ go 1.27.4 require ( github.com/BurntSushi/toml v1.6.0 github.com/Masterminds/semver/v3 v3.5.0 - github.com/aws/aws-sdk-go-v2 v1.48.1 + github.com/aws/aws-sdk-go-v2 v1.49.0 github.com/aws/aws-sdk-go-v2/config v1.33.22 github.com/aws/aws-sdk-go-v2/service/ecr v1.69.1 github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.47.13 github.com/aws/aws-sdk-go-v2/service/s3 v1.116.1 - github.com/aws/smithy-go v1.28.10 + github.com/aws/smithy-go v1.28.11 github.com/git-pkgs/archives v0.11.0 github.com/git-pkgs/artifacts v0.2.1 github.com/git-pkgs/cooldown v0.3.1 @@ -62,9 +62,10 @@ require ( github.com/aws/aws-sdk-go-v2/credentials v1.21.4 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.10 // indirect github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.13 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.13 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 // indirect github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.13 // indirect + github.com/aws/aws-sdk-go-v2/service/codeartifact v1.48.9 // indirect github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.26 // indirect github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.14 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.13 // indirect diff --git a/go.sum b/go.sum index 44d4bdcc..c6c9c52d 100644 --- a/go.sum +++ b/go.sum @@ -60,6 +60,8 @@ github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7D github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk= github.com/aws/aws-sdk-go-v2 v1.48.1 h1:j6ro6IvbxUe8BCulc/6uWMrhmx6+i5HNIc1GZEJRT9k= github.com/aws/aws-sdk-go-v2 v1.48.1/go.mod h1:HP8Jzg1FDurJomtx40YM0eiLoJrwjjZ9X+4BNpy4OXc= +github.com/aws/aws-sdk-go-v2 v1.49.0 h1:nfIScsXPSCz+vXIKz49IjNPHmC4oT72SLPVc8P0OBbU= +github.com/aws/aws-sdk-go-v2 v1.49.0/go.mod h1:XwfdWCjuiyYPbYF4ObLoa5I25KjV0ry6d105smVjNKY= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.28 h1:/LppjvqoI0KYB6gDrG/b77okSNPrVJI7CJtK5ITYoZ0= github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.28/go.mod h1:E7HQl8N3fZeO2DT1X3xSleOe+gG0O2k7nMgrKWDCfHw= github.com/aws/aws-sdk-go-v2/config v1.33.22 h1:U4aevm9PINYwCsHE6WFmL2aCxtMM1XaB05v2nRAJzoI= @@ -72,10 +74,16 @@ github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16 h1:q9YuNkYR/7lxf github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.4.16/go.mod h1:3BSeJQF55QQI+dDFHx4WTIjTvX/Lvtk8Jaaf/SGAnBM= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.13 h1:ZFqKPVQYSIYOXVoG/YRGXYNPqcGslzu/N2J3kev/Djc= github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.13/go.mod h1:3guCF5FBy7MYWRVt7+gdRxPPTSIBQnImwEVW5BdnOCE= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15 h1:Y0fe1Hcly/OSHtSWzuQrXGt3RtRjso063UbwZgyCHyQ= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.15/go.mod h1:52lvlO6umU2TRGxZJfCtjOR6xnbJotZD11mmzhJLQzI= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.13 h1:0pHWAgLjLZWSc9GtdpMVFT7bvpUcm9xZYcaJ9bmyLGo= github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.13/go.mod h1:yVcS5ysT0fDsQKA6mqaI5QU1p9q5bj7NyM4bu91yNmU= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15 h1:g2qcH0dUfjjigOI+HQB3DLXDq/8c84uH1ii/SDkwatg= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.15/go.mod h1:yGE7vsxRwTs6YBSYcE1j/KNA7EmAGEgBX+TAH0AAvk0= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.13 h1:a6vUTTG7Vsf0LTCuy/GPJsLhz3L6YcS1WkwR5Nxyz8g= github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.13/go.mod h1:vlylLTRubgSLfSBOy7blRhV2CC1nVY1VDIgV5nlKi5Y= +github.com/aws/aws-sdk-go-v2/service/codeartifact v1.48.9 h1:Uhhyn38AjfoZ/946i4kf2aZIh1CZa9E4Y11hnxioVCI= +github.com/aws/aws-sdk-go-v2/service/codeartifact v1.48.9/go.mod h1:YVHFTC3Ki9AH5GW+erQA3fv5QRPoNfgEgnu8h7TmV0I= github.com/aws/aws-sdk-go-v2/service/ecr v1.69.1 h1:0MvfM6Sjf1adM0BNgBY4nQ9RnR4no5o9hS2vQDPEuXs= github.com/aws/aws-sdk-go-v2/service/ecr v1.69.1/go.mod h1:iAnMBmKm9/0+X29eLYrlzia7eWZIUCVG3bvhZAqGZwU= github.com/aws/aws-sdk-go-v2/service/ecrpublic v1.47.13 h1:O2czpZArzMtVdkUj805JHBj+MrY6JcmTEFJAoJL1v1I= @@ -100,6 +108,8 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.53.1 h1:v6vt91IoL7PWx0TjIETO5IWtjAVQ github.com/aws/aws-sdk-go-v2/service/sts v1.53.1/go.mod h1:HeFBzksjwXSkhBvH20Yp2xdgn+e3lHRiVACMMr0mzOU= github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE= github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/aws/smithy-go v1.28.11 h1:2aArhkXe0dFld6IFMlaVy47SbSdU/ZGbDaE7X2DjZkI= +github.com/aws/smithy-go v1.28.11/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= diff --git a/internal/config/auth_validate_test.go b/internal/config/auth_validate_test.go index 013371de..1c38b965 100644 --- a/internal/config/auth_validate_test.go +++ b/internal/config/auth_validate_test.go @@ -15,7 +15,7 @@ func TestValidateRejectsUnknownUpstreamAuthType(t *testing.T) { 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"} { + for _, want := range []string{"upstream.auth", "https://registry.example.com/private", `"` + typ + `"`, "bearer, basic, header, ecr or codeartifact"} { if !strings.Contains(err.Error(), want) { t.Errorf("type %q: Validate() error = %q, want it to contain %q", typ, err, want) } @@ -35,6 +35,22 @@ func TestValidateAcceptsEveryUpstreamAuthType(t *testing.T) { } } +func TestValidateCodeArtifactAuthNeedsRepositoryHost(t *testing.T) { + for url, ok := range map[string]bool{ + "https://acme-123456789012.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/": true, + "https://registry.example.com": false, + "https://acme-1234.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/": false, + "http://acme-123456789012.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/": false, + "https://acme-123456789012.d.codeartifact.eu-north-1.example.com/npm/repo/": false, + } { + cfg := Default() + cfg.Upstream.Auth = map[string]AuthConfig{url: {Type: "CodeArtifact"}} + if err := cfg.Validate(); (err == nil) != ok { + t.Errorf("%s: Validate() error = %v, want ok = %v", url, err, ok) + } + } +} + func TestWarningsUpstreamAuthWithoutCredentials(t *testing.T) { t.Setenv("AUTH_TEST_SET", "secret") t.Setenv("AUTH_TEST_EMPTY", "") diff --git a/internal/config/config.go b/internal/config/config.go index 9d8d88a1..e1142a05 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1497,7 +1497,8 @@ func authURLPort(value *url.URL) string { // AuthConfig configures authentication for an upstream registry. type AuthConfig struct { - // Type is the authentication type: "bearer", "basic", "header", or "ecr". + // Type is the authentication type: "bearer", "basic", "header", "ecr" or + // "codeartifact". Type string `json:"type" yaml:"type"` // Token is used for bearer authentication. @@ -1518,9 +1519,10 @@ type AuthConfig struct { // Can reference environment variables with ${VAR_NAME} syntax. HeaderValue string `json:"header_value" yaml:"header_value"` - // Region is the AWS region for ECR authentication (for type "ecr"). - // If empty, the region is inferred from private ECR registry URLs before - // falling back to the AWS SDK default region chain. + // Region is the AWS region for types "ecr" and "codeartifact". + // If empty, the region is inferred from private ECR registry and + // CodeArtifact repository URLs before falling back to the AWS SDK default + // region chain. Region string `json:"region" yaml:"region"` } @@ -2507,8 +2509,12 @@ func (u *UpstreamConfig) validateAuth() error { } switch strings.ToLower(auth.Type) { case "bearer", "basic", "header", "ecr": + case "codeartifact": + if _, _, _, ok := CodeArtifactEndpoint(pattern); !ok { + return fmt.Errorf("invalid upstream.auth %q: type codeartifact needs an https://{domain}-{owner}.d.codeartifact.{region}.amazonaws.com URL", authScopeName(pattern)) + } default: - return fmt.Errorf("invalid upstream.auth %q: unknown type %q, must be bearer, basic, header or ecr", authScopeName(pattern), auth.Type) + return fmt.Errorf("invalid upstream.auth %q: unknown type %q, must be bearer, basic, header, ecr or codeartifact", authScopeName(pattern), auth.Type) } } return nil @@ -2524,11 +2530,39 @@ func authScopeName(pattern string) string { return (&url.URL{Scheme: parsed.Scheme, Host: parsed.Host, Path: parsed.Path, RawPath: parsed.RawPath}).String() } -// An ECR entry gets its credentials from AWS. +// CodeArtifactEndpoint parses a CodeArtifact repository host, +// https://{domain}-{owner}.d.codeartifact.{region}.amazonaws.com. Plain http +// is rejected so the token is never sent in cleartext. +func CodeArtifactEndpoint(rawURL string) (domain, owner, region string, ok bool) { + parsed, err := url.Parse(rawURL) + if err != nil || !strings.EqualFold(parsed.Scheme, "https") { + return "", "", "", false + } + + labels := strings.Split(strings.ToLower(parsed.Hostname()), ".") + if len(labels) < 6 || labels[1] != "d" || labels[2] != "codeartifact" { + return "", "", "", false + } + if suffix := strings.Join(labels[4:], "."); suffix != "amazonaws.com" && suffix != "amazonaws.com.cn" { + return "", "", "", false + } + + i := strings.LastIndexByte(labels[0], '-') + if i < 1 { + return "", "", "", false + } + domain, owner, region = labels[0][:i], labels[0][i+1:], labels[3] + if len(owner) != 12 || strings.Trim(owner, "0123456789") != "" || region == "" { + return "", "", "", false + } + return domain, owner, region, true +} + +// ECR and CodeArtifact entries get their credentials from AWS. func (u *UpstreamConfig) authWithoutCredentials() []string { var scopes []string for pattern, auth := range u.Auth { - if strings.EqualFold(auth.Type, "ecr") { + if strings.EqualFold(auth.Type, "ecr") || strings.EqualFold(auth.Type, "codeartifact") { continue } if name, value := auth.Header(); name == "" || value == "" { diff --git a/internal/server/codeartifact_auth.go b/internal/server/codeartifact_auth.go new file mode 100644 index 00000000..acd8cb29 --- /dev/null +++ b/internal/server/codeartifact_auth.go @@ -0,0 +1,57 @@ +package server + +import ( + "context" + "strings" + "time" + + awsconfig "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/codeartifact" + "github.com/git-pkgs/proxy/internal/config" +) + +// codeArtifactHeader returns the CodeArtifact token for rawURL as Bearer. +// Tokens are cached per domain, owner and region. +func (e *ecrTokens) codeArtifactHeader(rawURL, region string) (name, value string) { + domain, owner, hostRegion, ok := config.CodeArtifactEndpoint(rawURL) + if !ok { + return "", "" + } + if region == "" { + region = hostRegion + } + + name, value = e.codeArtifact.header(domain + "/" + owner + "/" + region) + if value == "" { + return name, value + } + return name, "Bearer " + strings.TrimPrefix(value, "Basic ") +} + +// fetchCodeArtifactToken gets a token for the domain/owner/region key. +func fetchCodeArtifactToken(ctx context.Context, key string) (string, time.Time, error) { + parts := strings.SplitN(key, "/", 3) + domain, owner, region := parts[0], parts[1], parts[2] + + cfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(region)) + if err != nil { + return "", time.Time{}, err + } + + out, err := codeartifact.NewFromConfig(cfg).GetAuthorizationToken(ctx, &codeartifact.GetAuthorizationTokenInput{ + Domain: &domain, + DomainOwner: &owner, + }) + if err != nil { + return "", time.Time{}, err + } + if out.AuthorizationToken == nil { + return "", time.Time{}, nil + } + + expiresAt := time.Now().Add(ecrDefaultTokenLifetime) + if out.Expiration != nil { + expiresAt = *out.Expiration + } + return *out.AuthorizationToken, expiresAt, nil +} diff --git a/internal/server/codeartifact_auth_test.go b/internal/server/codeartifact_auth_test.go new file mode 100644 index 00000000..4c6d5e58 --- /dev/null +++ b/internal/server/codeartifact_auth_test.go @@ -0,0 +1,62 @@ +package server + +import ( + "context" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/config" +) + +func TestCodeArtifactEndpoint(t *testing.T) { + tests := []struct { + url string + domain, owner, region string + ok bool + }{ + {"https://my-domain-123456789012.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/", "my-domain", "123456789012", "eu-north-1", true}, + {"https://acme-123456789012.d.codeartifact.cn-north-1.amazonaws.com.cn/npm/repo/", "acme", "123456789012", "cn-north-1", true}, + {"https://acme-1234.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/", "", "", "", false}, + {"https://acme-123456789012.d.codeartifact.eu-north-1.example.com/npm/repo/", "", "", "", false}, + {"https://123456789012.d.codeartifact.eu-north-1.amazonaws.com/", "", "", "", false}, + {"https://registry.npmjs.org/", "", "", "", false}, + {"http://acme-123456789012.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/", "", "", "", false}, + } + for _, tt := range tests { + domain, owner, region, ok := config.CodeArtifactEndpoint(tt.url) + if domain != tt.domain || owner != tt.owner || region != tt.region || ok != tt.ok { + t.Errorf("CodeArtifactEndpoint(%q) = %q, %q, %q, %v", tt.url, domain, owner, region, ok) + } + } +} + +func TestAuthForURLCodeArtifact(t *testing.T) { + const repo = "https://acme-123456789012.d.codeartifact.eu-north-1.amazonaws.com/npm/repo/" + + e := testECRTokens() + calls := 0 + e.codeArtifact.getToken = func(_ context.Context, key string) (string, time.Time, error) { + calls++ + if key != "acme/123456789012/eu-north-1" { + t.Errorf("key = %q", key) + } + return "ca-token", time.Now().Add(time.Hour), nil + } + + s := &Server{ + ecr: e, + cfg: &config.Config{Upstream: config.UpstreamConfig{ + Auth: map[string]config.AuthConfig{repo: {Type: "codeartifact"}}, + }}, + } + + for range 2 { + name, value := s.authForURL(repo + "@acme/pkg/-/pkg-1.0.0.tgz") + if name != "Authorization" || value != "Bearer ca-token" { + t.Fatalf("authForURL() = %q, %q", name, value) + } + } + if calls != 1 { + t.Errorf("token fetched %d times, want 1", calls) + } +} diff --git a/internal/server/ecr_auth.go b/internal/server/ecr_auth.go index 33db1512..62422226 100644 --- a/internal/server/ecr_auth.go +++ b/internal/server/ecr_auth.go @@ -37,7 +37,8 @@ type ecrTokens struct { // in tests. getToken func(ctx context.Context, region string) (string, time.Time, error) - public *ecrTokens // ECR Public, cached apart from the regions + public *ecrTokens // ECR Public, cached apart from the regions + codeArtifact *ecrTokens // CodeArtifact, keyed by domain/owner/region } type ecrToken struct { @@ -56,6 +57,11 @@ func newECRTokens(logger *slog.Logger) *ecrTokens { cache: make(map[string]ecrToken), getToken: fetchECRPublicToken, }, + codeArtifact: &ecrTokens{ + logger: logger.With("service", "codeartifact"), + cache: make(map[string]ecrToken), + getToken: fetchCodeArtifactToken, + }, } } diff --git a/internal/server/server.go b/internal/server/server.go index 310fec2c..b6ef2dde 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -971,6 +971,9 @@ func (s *Server) authForURL(url string) (headerName, headerValue string) { if auth == nil { return "", "" } + if strings.EqualFold(auth.Type, "codeartifact") { + return s.ecr.codeArtifactHeader(url, auth.Region) + } if strings.EqualFold(auth.Type, "ecr") { if ecrPublic(url) { return s.ecr.publicHeader(url)