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
19 changes: 18 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
9 changes: 5 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand All @@ -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=
Expand All @@ -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=
Expand Down
18 changes: 17 additions & 1 deletion internal/config/auth_validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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", "")
Expand Down
48 changes: 41 additions & 7 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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"`
}

Expand Down Expand Up @@ -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 {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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
Expand All @@ -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 == "" {
Expand Down
57 changes: 57 additions & 0 deletions internal/server/codeartifact_auth.go
Original file line number Diff line number Diff line change
@@ -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)

Check failure on line 33 in internal/server/codeartifact_auth.go

View workflow job for this annotation

GitHub Actions / lint

Magic number: 3, in <argument> detected (mnd)
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
}
62 changes: 62 additions & 0 deletions internal/server/codeartifact_auth_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
8 changes: 7 additions & 1 deletion internal/server/ecr_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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,
},
}
}

Expand Down
3 changes: 3 additions & 0 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading