diff --git a/cmd/proxy/main.go b/cmd/proxy/main.go index 7c51732f..b760953a 100644 --- a/cmd/proxy/main.go +++ b/cmd/proxy/main.go @@ -568,12 +568,7 @@ func runMirror() { } m := newCommandMirror(cfg, proxy, images, db, store, logger, *concurrency) - switch s := source.(type) { - case *mirror.PURLSource: - s.Versions = m.Versions - case *mirror.SBOMSource: - s.Versions = m.Versions - } + useMirrorListing(source, m) ctx, cancel := context.WithCancel(context.Background()) go func() { @@ -631,12 +626,25 @@ func newCommandMirror(cfg *config.Config, proxy *handler.Proxy, images *handler. m.Bottles = handler.NewHomebrewHandler(proxy, cfg.Upstream.HomebrewAPI) m.Charts = handler.NewHelmHandler(proxy, cfg.BaseURL, cfg.Upstream.Helm) server.UseMirrorUpstreams(m, cfg.Upstream, proxy.HTTPClient) + m.Disabled = cfg.EcosystemDisabled if cfg.Scanning.Enabled { refuseUnscannedMirroring(m) } return m } +// useMirrorListing has source list versions with m's lister and leave +// out the ecosystems m turns off, which are known only once the config is +// loaded. +func useMirrorListing(source mirror.Source, m *mirror.Mirror) { + switch s := source.(type) { + case *mirror.PURLSource: + s.Versions, s.Disabled = m.Versions, m.Disabled + case *mirror.SBOMSource: + s.Versions, s.Disabled = m.Versions, m.Disabled + } +} + // useCommandGit opens the git cache for the pkg:git items of proxy mirror, // when upstream.git is configured, and returns the function that closes it. // Where it can't be opened, such as while the running server holds diff --git a/cmd/proxy/mirror_test.go b/cmd/proxy/mirror_test.go index bd39de9b..75c1d5e8 100644 --- a/cmd/proxy/mirror_test.go +++ b/cmd/proxy/mirror_test.go @@ -2,14 +2,18 @@ package main import ( "errors" + "io" + "log/slog" "os" "os/exec" "path/filepath" "strings" "testing" + "github.com/git-pkgs/proxy/internal/config" "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/mirror" + "github.com/git-pkgs/proxy/internal/server" ) // mirrorTestEnv carries the mirror command's arguments into the helper @@ -212,3 +216,28 @@ func TestMirrorFailureProcess(*testing.T) { } main() } + +func TestCommandMirrorRefusesDisabledEcosystems(t *testing.T) { + cfg := config.Default() + cfg.DisabledEcosystems = []string{"pypi"} + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + proxy, images := server.NewMirrorProxy(cfg, nil, nil, logger) + m := newCommandMirror(cfg, proxy, images, nil, nil, logger, 1) + if m.Disabled == nil || !m.Disabled("pypi") || m.Disabled("npm") { + t.Errorf("Disabled doesn't follow disabled_ecosystems") + } +} + +func TestCommandSourcesFollowTheMirror(t *testing.T) { + m := &mirror.Mirror{Disabled: func(ecosystem string) bool { return ecosystem == "pypi" }} + purls := &mirror.PURLSource{} + sbom := &mirror.SBOMSource{} + for _, source := range []mirror.Source{purls, sbom} { + useMirrorListing(source, m) + } + for name, disabled := range map[string]func(string) bool{"purls": purls.Disabled, "sbom": sbom.Disabled} { + if disabled == nil || !disabled("pypi") || disabled("npm") { + t.Errorf("%s source Disabled doesn't follow the mirror's", name) + } + } +} diff --git a/config.example.yaml b/config.example.yaml index db7d4448..c1183073 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -28,6 +28,10 @@ base_url: "http://localhost:8080" # restrict /api/cache, /api/git and /ui at the ingress first. # cache_delete: false +# Ecosystems to turn off: their routes answer 404, mirroring refuses their +# packages, and they are left off the install page. Cached data stays. +# disabled_ecosystems: [pypi, cargo] + # Largest upstream artifact to fetch (e.g. "2GB"). Larger ones are refused # and not cached. Default: unlimited. # artifact_max_size: "" diff --git a/docs/configuration.md b/docs/configuration.md index 5deb5637..287e8816 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -392,6 +392,18 @@ upstream: token: "${SUPERMARKET_TOKEN}" ``` +### Turning ecosystems off + +Every built-in package route is served by default. `disabled_ecosystems` (`PROXY_DISABLED_ECOSYSTEMS`, a comma-separated list) turns ecosystems off by key: + +```yaml +disabled_ecosystems: [pypi, cargo, oci] +``` + +A turned-off ecosystem's routes answer every request with 404, including routes under a [cooldown profile](#cooldown-profiles), and never reach its upstream. It is left off the install page, `proxy mirror`, mirror API jobs, `mirror.schedules` and `mirror.refresh` fail its packages with an error saying it is turned off, without asking its upstream for versions or indexes, and its change feed isn't followed. What is already cached for it stays, and is still shown in the dashboard and evicted as before. + +The keys are `alpine`, `arch`, `cargo`, `chef`, `composer`, `conan`, `conda`, `cran`, `deb`, `freebsd`, `gem`, `golang`, `gradle` (the build cache), `helm`, `hex`, `homebrew`, `julia`, `maven`, `npm`, `nuget`, `oci`, `pub`, `pypi`, `rpm`, `swift` and `terraform`, case-insensitive; `apk`, `debian`, `docker`, `go`, `brew`, `packagist` and `rubygems` are accepted for the same ecosystems. Any other name stops the proxy at startup. `oci` is everything under `/v2/`, so it also stops Homebrew bottle downloads and Helm charts pulled over OCI. `git` and `generic` serve only what `upstream.git` and `upstream.generic` configure, so they are turned off by leaving those out. + ### Private package routes Clients that use the proxy as their only registry can still install private packages. A package route sends every package whose name matches a pattern to a private registry, and never to the default upstream: diff --git a/internal/config/config.go b/internal/config/config.go index 63dda7da..4624bee0 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -149,6 +149,11 @@ type Config struct { // Upstream configures upstream registry URLs (optional overrides). Upstream UpstreamConfig `json:"upstream" yaml:"upstream"` + // DisabledEcosystems turns ecosystems off by key (npm, pypi, oci, ...): + // their routes answer 404, they are left off the install page, and + // mirroring refuses their packages. What is cached for them stays. + DisabledEcosystems []string `json:"disabled_ecosystems" yaml:"disabled_ecosystems"` + // Cooldown configures version age filtering to mitigate supply chain attacks. Cooldown CooldownConfig `json:"cooldown" yaml:"cooldown"` @@ -1615,6 +1620,7 @@ func (c *Config) LoadFromEnv() { setEnvString(&c.Log.Level, "PROXY_LOG_LEVEL") setEnvString(&c.Log.Format, "PROXY_LOG_FORMAT") setEnvString(&c.AccessLog.Path, "PROXY_ACCESS_LOG_PATH") + setEnvStringSlice(&c.DisabledEcosystems, "PROXY_DISABLED_ECOSYSTEMS") setEnvStringSlice(&c.Upstream.AllowPrivateHosts, "PROXY_UPSTREAM_ALLOW_PRIVATE_HOSTS") c.setEnvBool(&c.Upstream.AllowLoopback, "PROXY_UPSTREAM_ALLOW_LOOPBACK") setEnvString(&c.Upstream.NPM, "PROXY_UPSTREAM_NPM") @@ -1837,6 +1843,10 @@ func (c *Config) validateComponents() error { return err } + if err := c.validateDisabledEcosystems(); err != nil { + return err + } + if err := c.Health.Validate(); err != nil { return err } diff --git a/internal/config/disabled_ecosystems.go b/internal/config/disabled_ecosystems.go new file mode 100644 index 00000000..eaf0bf25 --- /dev/null +++ b/internal/config/disabled_ecosystems.go @@ -0,0 +1,49 @@ +package config + +import ( + "fmt" + "slices" + "strings" +) + +// DisableableEcosystems are the ecosystem keys disabled_ecosystems accepts: +// the ones served by default. git and generic serve only what upstream.git +// and upstream.generic configure, so they are turned off by leaving those +// out. +var DisableableEcosystems = []string{ + "alpine", "arch", "cargo", "chef", "composer", "conan", "conda", "cran", "deb", + "freebsd", "gem", "golang", "gradle", "helm", "hex", "homebrew", "julia", "maven", + "npm", "nuget", "oci", "pub", "pypi", "rpm", "swift", "terraform", +} + +// normalizeEcosystem resolves case and the aliases scanning accepts, plus +// brew for homebrew. +func normalizeEcosystem(name string) string { + key := NormalizeScannerEcosystem(name) + if key == "brew" { + return "homebrew" + } + return key +} + +// validateDisabledEcosystems normalizes disabled_ecosystems in place and +// rejects names it doesn't accept. +func (c *Config) validateDisabledEcosystems() error { + for i, name := range c.DisabledEcosystems { + key := normalizeEcosystem(name) + if !slices.Contains(DisableableEcosystems, key) { + return fmt.Errorf("invalid disabled_ecosystems entry %q (valid: %s)", name, strings.Join(DisableableEcosystems, ", ")) + } + c.DisabledEcosystems[i] = key + } + return nil +} + +// EcosystemDisabled reports whether disabled_ecosystems turns off the +// ecosystem, given by its key or an alias such as apk, go or docker. +func (c *Config) EcosystemDisabled(name string) bool { + key := normalizeEcosystem(name) + return slices.ContainsFunc(c.DisabledEcosystems, func(entry string) bool { + return normalizeEcosystem(entry) == key + }) +} diff --git a/internal/config/disabled_ecosystems_test.go b/internal/config/disabled_ecosystems_test.go new file mode 100644 index 00000000..4ae4a1a5 --- /dev/null +++ b/internal/config/disabled_ecosystems_test.go @@ -0,0 +1,74 @@ +package config + +import ( + "slices" + "strings" + "testing" +) + +func TestDisabledEcosystemsDefaultToNone(t *testing.T) { + cfg := Default() + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + for _, key := range DisableableEcosystems { + if cfg.EcosystemDisabled(key) { + t.Errorf("%s is disabled by default", key) + } + } +} + +func TestDisabledEcosystemsAreNormalized(t *testing.T) { + cfg := Default() + cfg.DisabledEcosystems = []string{"PyPI", " apk ", "go", "docker", "debian", "brew", "rubygems"} + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + want := []string{"pypi", "alpine", "golang", "oci", "deb", "homebrew", "gem"} + if !slices.Equal(cfg.DisabledEcosystems, want) { + t.Errorf("DisabledEcosystems = %v, want %v", cfg.DisabledEcosystems, want) + } + for _, name := range []string{"pypi", "PyPI", "alpine", "apk", "golang", "go", "oci", "docker", "deb", "homebrew", "brew", "gem"} { + if !cfg.EcosystemDisabled(name) { + t.Errorf("EcosystemDisabled(%q) = false, want true", name) + } + } + for _, name := range []string{"npm", "cargo", "maven"} { + if cfg.EcosystemDisabled(name) { + t.Errorf("EcosystemDisabled(%q) = true, want false", name) + } + } +} + +func TestDisabledEcosystemsRejectUnknownNames(t *testing.T) { + for _, name := range []string{"pipy", "git", "generic", ""} { + cfg := Default() + cfg.DisabledEcosystems = []string{"npm", name} + err := cfg.Validate() + if err == nil { + t.Errorf("%q: Validate accepted it", name) + continue + } + if !strings.Contains(err.Error(), "disabled_ecosystems") { + t.Errorf("%q: error %q doesn't name the setting", name, err) + } + } +} + +func TestDisabledEcosystemsFromEnv(t *testing.T) { + t.Setenv("PROXY_DISABLED_ECOSYSTEMS", "pypi, cargo") + cfg := Default() + cfg.LoadFromEnv() + if !slices.Equal(cfg.DisabledEcosystems, []string{"pypi", "cargo"}) { + t.Errorf("DisabledEcosystems = %v, want [pypi cargo]", cfg.DisabledEcosystems) + } +} + +// Entries are matched by key before Validate has normalized them too. +func TestEcosystemDisabledBeforeValidate(t *testing.T) { + cfg := Default() + cfg.DisabledEcosystems = []string{"PyPI", "apk"} + if !cfg.EcosystemDisabled("pypi") || !cfg.EcosystemDisabled("alpine") || cfg.EcosystemDisabled("npm") { + t.Errorf("EcosystemDisabled doesn't match unnormalized entries") + } +} diff --git a/internal/mirror/job.go b/internal/mirror/job.go index 841c7c9b..a42bbc0c 100644 --- a/internal/mirror/job.go +++ b/internal/mirror/job.go @@ -211,9 +211,9 @@ func (js *JobStore) sourceFromRequest(req JobRequest) (Source, error) { //nolint case len(req.PURLs) > 0 && len(req.SBOM) > 0: return nil, fmt.Errorf("request must include only one of purls or sbom") case len(req.PURLs) > 0: - return &PURLSource{PURLs: req.PURLs, Versions: js.mirror.Versions, Latest: req.Latest, Platforms: req.Platforms}, nil + return &PURLSource{PURLs: req.PURLs, Versions: js.mirror.Versions, Latest: req.Latest, Platforms: req.Platforms, Disabled: js.mirror.Disabled}, nil case len(req.SBOM) > 0: - return &SBOMSource{Data: req.SBOM, Versions: js.mirror.Versions, Latest: req.Latest, Platforms: req.Platforms}, nil + return &SBOMSource{Data: req.SBOM, Versions: js.mirror.Versions, Latest: req.Latest, Platforms: req.Platforms, Disabled: js.mirror.Disabled}, nil case req.Registry != "": return nil, fmt.Errorf("registry mirroring is not yet implemented; use purls instead") default: diff --git a/internal/mirror/mirror.go b/internal/mirror/mirror.go index 50305084..57c7d9f1 100644 --- a/internal/mirror/mirror.go +++ b/internal/mirror/mirror.go @@ -64,6 +64,11 @@ type Mirror struct { DebianUpstream string DebianRepositories map[string]string + // Disabled reports whether disabled_ecosystems turns off an item's + // ecosystem, given as the PURL type. Such items fail without being + // fetched. Nil turns none off. + Disabled func(ecosystem string) bool + // RefusePackages, when set, fails every item Images does not take with // this reason instead of fetching it, so nothing is cached. RefusePackages string @@ -258,6 +263,10 @@ func (m *Mirror) mirrorRecovered(ctx context.Context, item PackageVersion, track } func (m *Mirror) mirrorOne(ctx context.Context, pv PackageVersion, tracker *progressTracker) { + if err := m.turnedOff(pv.Ecosystem); err != nil { + m.recordFailure(tracker, pv, err) + return + } if isImageEcosystem(pv.Ecosystem) && m.Images != nil { m.mirrorImage(ctx, pv, tracker) return @@ -330,6 +339,14 @@ func (m *Mirror) mirrorOne(ctx context.Context, pv PackageVersion, tracker *prog m.recordResult(tracker, pv, result) } +// turnedOff returns an error when disabled_ecosystems turns off ecosystem. +func (m *Mirror) turnedOff(ecosystem string) error { + if m.Disabled != nil && m.Disabled(ecosystem) { + return fmt.Errorf("%s is turned off on this proxy", ecosystem) + } + return nil +} + // recordFailure counts and logs a package that could not be mirrored. func (m *Mirror) recordFailure(tracker *progressTracker, pv PackageVersion, err error) { tracker.failed.Add(1) diff --git a/internal/mirror/mirror_test.go b/internal/mirror/mirror_test.go index 68526878..3f3d40df 100644 --- a/internal/mirror/mirror_test.go +++ b/internal/mirror/mirror_test.go @@ -9,6 +9,7 @@ import ( "os" "strings" "sync" + "sync/atomic" "testing" "time" @@ -350,3 +351,157 @@ func TestMirrorRefusePackagesLeavesImagesToImages(t *testing.T) { t.Errorf("errors = %+v, want the image refusal", progress.Errors) } } + +// A turned-off ecosystem's items fail without being fetched, images and +// Homebrew included, and the others are mirrored as before. +func TestMirrorRunRefusesDisabledEcosystems(t *testing.T) { + m := setupTestMirror(t, 1) + fetcher := &recordingFetcher{} + m.proxy.Fetcher = fetcher + images := &recordingImages{} + m.Images = images + m.Disabled = func(ecosystem string) bool { return ecosystem == "npm" || ecosystem == "docker" || ecosystem == "brew" } + + source := &PURLSource{PURLs: []string{"pkg:npm/lodash@4.17.21", "pkg:docker/library/alpine@3.20", "pkg:brew/wget@1.24.5", "pkg:cargo/serde@1.0.0"}} + progress, err := m.Run(context.Background(), source) + if err != nil { + t.Fatalf("Run: %v", err) + } + refused := map[string]bool{} + for _, e := range progress.Errors { + if strings.Contains(e.Error, "turned off") { + refused[e.Ecosystem] = true + } + } + for _, eco := range []string{"npm", "docker", "brew"} { + if !refused[eco] { + t.Errorf("%s item wasn't refused as turned off: %+v", eco, progress.Errors) + } + } + if refused["cargo"] { + t.Errorf("cargo item was refused") + } + for _, u := range fetcher.fetched() { + if strings.Contains(u, "lodash") { + t.Errorf("turned-off npm item was fetched: %s", u) + } + } + if images.calls.Load() != 0 { + t.Errorf("turned-off image was handed to Images") + } + if len(fetcher.fetched()) == 0 { + t.Errorf("cargo item wasn't fetched") + } +} + +type recordingImages struct{ calls atomic.Int32 } + +func (r *recordingImages) MirrorImage(context.Context, handler.ImageRef, []handler.Platform) (handler.ImageResult, error) { + r.calls.Add(1) + return handler.ImageResult{}, errors.New("not mirrored") +} + +// An unversioned PURL of a turned-off ecosystem isn't listed from its +// upstream: it yields one item that fails, and a lister error can't abort +// the job for the enabled ecosystems. +func TestMirrorRunDoesNotListDisabledEcosystems(t *testing.T) { + disabled := func(ecosystem string) bool { return ecosystem == "npm" } + bom := map[string]any{ + "bomFormat": "CycloneDX", + "specVersion": "1.4", + "components": []map[string]any{ + {"type": "library", "name": "lodash", "purl": "pkg:npm/lodash"}, + {"type": "library", "name": "serde", "version": "1.0.0", "purl": "pkg:cargo/serde@1.0.0"}, + }, + } + sources := map[string]func(VersionLister) Source{ + "purls": func(versions VersionLister) Source { + return &PURLSource{PURLs: []string{"pkg:npm/lodash", "pkg:cargo/serde@1.0.0"}, Versions: versions, Disabled: disabled} + }, + "sbom": func(versions VersionLister) Source { + return &SBOMSource{Data: marshalJSON(t, bom), Versions: versions, Disabled: disabled} + }, + } + for name, source := range sources { + t.Run(name, func(t *testing.T) { + m := setupTestMirror(t, 1) + fetcher := &recordingFetcher{} + m.proxy.Fetcher = fetcher + m.Disabled = disabled + versions := &failingVersions{} + + progress, err := m.Run(context.Background(), source(versions)) + if err != nil { + t.Fatalf("Run: %v", err) + } + if n := versions.calls.Load(); n != 0 { + t.Errorf("versions listed %d times, want none", n) + } + var refused int + for _, e := range progress.Errors { + if e.Ecosystem == "npm" && strings.Contains(e.Error, "turned off") { + refused++ + } + } + if refused != 1 { + t.Errorf("npm refusals = %d, want 1: %+v", refused, progress.Errors) + } + fetchedSerde := false + for _, u := range fetcher.fetched() { + fetchedSerde = fetchedSerde || strings.Contains(u, "serde") + } + if !fetchedSerde { + t.Errorf("enabled cargo item wasn't fetched: %v", fetcher.fetched()) + } + }) + } +} + +type failingVersions struct{ calls atomic.Int32 } + +func (f *failingVersions) ListVersions(context.Context, string, string) ([]string, error) { + f.calls.Add(1) + return nil, errors.New("upstream unreachable") +} + +// Mirror API jobs and schedules hand the mirror's Disabled to their +// sources, so their unversioned PURLs of a turned-off ecosystem aren't +// listed either. +func TestJobsAndSchedulesDoNotListDisabledEcosystems(t *testing.T) { + newMirror := func(t *testing.T) (*Mirror, *failingVersions) { + m := setupTestMirror(t, 1) + m.proxy.Fetcher = &recordingFetcher{} + m.Disabled = func(ecosystem string) bool { return ecosystem == "npm" } + versions := &failingVersions{} + m.Versions = versions + return m, versions + } + bom := marshalJSON(t, map[string]any{ + "bomFormat": "CycloneDX", + "specVersion": "1.4", + "components": []map[string]any{{"type": "library", "name": "lodash", "purl": "pkg:npm/lodash"}}, + }) + for name, req := range map[string]JobRequest{"purls": {PURLs: []string{"pkg:npm/lodash"}}, "sbom": {SBOM: bom}} { + t.Run("job "+name, func(t *testing.T) { + m, versions := newMirror(t) + source, err := NewJobStore(context.Background(), m).sourceFromRequest(req) + if err != nil { + t.Fatalf("sourceFromRequest: %v", err) + } + if _, err := m.Run(context.Background(), source); err != nil { + t.Fatalf("Run: %v", err) + } + if n := versions.calls.Load(); n != 0 { + t.Errorf("versions listed %d times, want none", n) + } + }) + } + t.Run("schedule", func(t *testing.T) { + m, versions := newMirror(t) + schedule := Schedule{PURLs: []string{"pkg:npm/lodash"}, Interval: time.Hour} + NewScheduler(m, []Schedule{schedule}, m.logger).run(context.Background(), 0, schedule) + if n := versions.calls.Load(); n != 0 { + t.Errorf("versions listed %d times, want none", n) + } + }) +} diff --git a/internal/mirror/refresh.go b/internal/mirror/refresh.go index 9715d2a3..41125c8a 100644 --- a/internal/mirror/refresh.go +++ b/internal/mirror/refresh.go @@ -55,7 +55,8 @@ func (m *Mirror) releaseLister() ReleaseLister { //nolint:ireturn // any lister // Refresh mirrors, for each of the most used packages, the newest release // of each major line it has a version cached on, as clients would be served // it: releases within cooldown or on the denylist are left out. Packages it -// can't list are counted as failed. +// can't list, and those of an ecosystem disabled_ecosystems turns off, are +// counted as failed. func (m *Mirror) Refresh(ctx context.Context, r Refresh) (*Progress, error) { ctx = handler.MirrorFetch(ctx) cutoff := time.Now().Add(-r.Since) @@ -88,11 +89,7 @@ func (m *Mirror) Refresh(ctx context.Context, r Refresh) (*Progress, error) { } for _, group := range byEcosystem(packages) { if ix, ok := osIndexes[group[0].Ecosystem]; ok { - items, errs := m.indexRefreshItems(ctx, ix, group, cutoff) - for _, err := range errs { - m.recordFailure(tracker, PackageVersion{Ecosystem: ix.ecosystem}, err) - } - if !run(items) { + if !run(m.indexRefreshGroup(ctx, ix, group, cutoff, tracker)) { break } continue @@ -117,6 +114,23 @@ func (m *Mirror) Refresh(ctx context.Context, r Refresh) (*Progress, error) { return &p, nil } +// indexRefreshGroup returns the versions to mirror for the used packages of +// an OS ecosystem and records the indexes it couldn't read. A turned-off +// ecosystem fails without its indexes being read. +func (m *Mirror) indexRefreshGroup(ctx context.Context, ix osIndex, group []database.UsedPackage, cutoff time.Time, tracker *progressTracker) []PackageVersion { + if err := m.turnedOff(ix.ecosystem); err != nil { + for _, pkg := range group { + m.recordFailure(tracker, PackageVersion{Ecosystem: pkg.Ecosystem, Name: pkg.Name}, err) + } + return nil + } + items, errs := m.indexRefreshItems(ctx, ix, group, cutoff) + for _, err := range errs { + m.recordFailure(tracker, PackageVersion{Ecosystem: ix.ecosystem}, err) + } + return items +} + // byEcosystem splits packages, ordered by ecosystem, into one group per // ecosystem. func byEcosystem(packages []database.UsedPackage) [][]database.UsedPackage { @@ -137,6 +151,9 @@ func (m *Mirror) refreshItems(ctx context.Context, pkg database.UsedPackage) ([] return nil, err } ecosystem, name, _ := mirrorTarget(p) + if err := m.turnedOff(ecosystem); err != nil { + return nil, err + } if !refreshable(ecosystem) { return nil, nil } diff --git a/internal/mirror/refresh_disabled_test.go b/internal/mirror/refresh_disabled_test.go new file mode 100644 index 00000000..2cd35806 --- /dev/null +++ b/internal/mirror/refresh_disabled_test.go @@ -0,0 +1,136 @@ +package mirror + +import ( + "context" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/registries" +) + +// countingReleases counts the listings it answers. +type countingReleases struct { + stubReleases + calls atomic.Int32 +} + +func (c *countingReleases) ListReleases(ctx context.Context, ecosystem, name string) ([]registries.Version, error) { + c.calls.Add(1) + return c.stubReleases.ListReleases(ctx, ecosystem, name) +} + +func (c *countingReleases) ListVersions(ctx context.Context, ecosystem, name string) ([]string, error) { + c.calls.Add(1) + return c.stubReleases.ListVersions(ctx, ecosystem, name) +} + +// countingTransport counts the requests it passes on. +type countingTransport struct { + next http.RoundTripper + calls atomic.Int32 +} + +func (c *countingTransport) RoundTrip(r *http.Request) (*http.Response, error) { + c.calls.Add(1) + return c.next.RoundTrip(r) +} + +func turnedOffFailures(p *Progress, ecosystem, name string) int { + n := 0 + for _, e := range p.Errors { + if e.Ecosystem == ecosystem && e.Name == name && strings.Contains(e.Error, "turned off") { + n++ + } + } + return n +} + +func TestRefreshDoesNotListReleasesOfDisabledEcosystems(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "tarball") + cacheNPM(t, m, "lodash", "4.17.20") + lister := &countingReleases{stubReleases: stubReleases{"npm/lodash": oldReleases("4.17.20", "4.17.21")}} + m.Versions = lister + m.Disabled = func(ecosystem string) bool { return ecosystem == "npm" } + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if n := lister.calls.Load(); n != 0 { + t.Errorf("listed releases %d times for a turned-off ecosystem", n) + } + if len(fetcher.fetched()) != 0 { + t.Errorf("fetched %v for a turned-off ecosystem", fetcher.fetched()) + } + if progress.Failed != 1 || turnedOffFailures(progress, "npm", "lodash") != 1 { + t.Errorf("progress = %+v, want lodash failed as turned off", progress) + } +} + +// A turned-off ecosystem a refresh never lists releases for, such as +// images, still fails its packages instead of skipping them silently. +func TestRefreshFailsDisabledUnrefreshableEcosystems(t *testing.T) { + m, fetcher := setupRefreshMirror(t, "file") + packagePURL := "pkg:docker/library/alpine" + versionPURL := packagePURL + "@3.20" + const filename = "alpine-3.20.tar" + for _, err := range []error{ + m.db.UpsertPackage(&database.Package{PURL: packagePURL, Ecosystem: "docker", Name: "library/alpine"}), + m.db.UpsertVersion(&database.Version{PURL: versionPURL, PackagePURL: packagePURL}), + m.db.UpsertArtifact(&database.Artifact{VersionPURL: versionPURL, Filename: filename, UpstreamURL: "https://registry.example/" + filename}), + m.db.MarkArtifactCached(versionPURL, filename, "docker/"+filename, "sha256:00", 1, "application/octet-stream"), + m.db.RecordArtifactHit(versionPURL, filename), + } { + if err != nil { + t.Fatalf("caching library/alpine: %v", err) + } + } + lister := &countingReleases{} + m.Versions = lister + m.Disabled = func(ecosystem string) bool { return ecosystem == "docker" } + fetcher.reset() + + progress, err := m.Refresh(context.Background(), Refresh{Top: 10, Since: 24 * time.Hour}) + if err != nil { + t.Fatalf("Refresh: %v", err) + } + if n := lister.calls.Load(); n != 0 { + t.Errorf("listed releases %d times for a turned-off ecosystem", n) + } + if len(fetcher.fetched()) != 0 { + t.Errorf("fetched %v for a turned-off ecosystem", fetcher.fetched()) + } + if progress.Failed != 1 || turnedOffFailures(progress, "docker", "library/alpine") != 1 { + t.Errorf("progress = %+v, want library/alpine failed as turned off", progress) + } +} + +func TestRefreshDoesNotReadIndexesOfDisabledEcosystems(t *testing.T) { + m, fetcher, idx := setupIndexRefresh(t) + dir := "/alpine/v3.20/main/aarch64" + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.0-r0\nA:aarch64\n\n")) + clientFetchesCurl(t, m, "alpine", idx.URL+dir+"/APKINDEX.tar.gz", + "alpine", "8.9.0-r0", "edge/v3.20/main/aarch64/curl-8.9.0-r0.apk", idx.URL+dir+"/curl-8.9.0-r0.apk") + idx.set(dir+"/APKINDEX.tar.gz", apkIndexArchive(t, "P:curl\nV:8.9.1-r0\nA:aarch64\n\n")) + + transport := &countingTransport{next: idx.Client().Transport} + m.proxy.HTTPClient = &http.Client{Transport: transport} + m.Disabled = func(ecosystem string) bool { return ecosystem == "alpine" } + fetcher.reset() + + progress := refreshOnce(t, m) + if n := transport.calls.Load(); n != 0 { + t.Errorf("read %d index documents for a turned-off ecosystem", n) + } + if len(fetcher.fetched()) != 0 { + t.Errorf("fetched %v for a turned-off ecosystem", fetcher.fetched()) + } + if progress.Failed != 1 || turnedOffFailures(progress, "alpine", "curl") != 1 { + t.Errorf("progress = %+v, want curl failed as turned off", progress) + } +} diff --git a/internal/mirror/schedule.go b/internal/mirror/schedule.go index 244fd89b..9e3cdc33 100644 --- a/internal/mirror/schedule.go +++ b/internal/mirror/schedule.go @@ -109,7 +109,7 @@ func (s *Scheduler) run(ctx context.Context, index int, schedule Schedule) { if schedule.Refresh != nil { progress, err = s.mirror.Refresh(ctx, *schedule.Refresh) } else { - progress, err = s.mirror.Run(ctx, &PURLSource{PURLs: schedule.PURLs, Versions: s.mirror.Versions, Platforms: schedule.Platforms}) + progress, err = s.mirror.Run(ctx, &PURLSource{PURLs: schedule.PURLs, Versions: s.mirror.Versions, Platforms: schedule.Platforms, Disabled: s.mirror.Disabled}) } if ctx.Err() != nil { if s.Claim != nil && s.Release != nil { diff --git a/internal/mirror/source.go b/internal/mirror/source.go index 5409a86a..363078fc 100644 --- a/internal/mirror/source.go +++ b/internal/mirror/source.go @@ -61,6 +61,10 @@ type PURLSource struct { Latest bool // Platforms limit which platforms of container images are mirrored. Platforms []string + // Disabled reports whether disabled_ecosystems turns off an ecosystem. + // Its unversioned PURLs aren't listed from the upstream: each yields + // one item, which Mirror refuses. + Disabled func(ecosystem string) bool } func (s *PURLSource) Enumerate(ctx context.Context, fn func(PackageVersion) error) error { @@ -107,6 +111,12 @@ func (s *PURLSource) enumeratePURL(ctx context.Context, versions VersionLister, return fn(pv) } + // A turned-off ecosystem's upstream isn't asked for versions; the one + // unversioned item fails in Mirror. + if s.Disabled != nil && s.Disabled(ecosystem) { + return fn(PackageVersion{Ecosystem: ecosystem, Name: name, Namespace: namespace, Qualifiers: qualifiers}) + } + // Unversioned: enumerate all versions, or the newest listed, err := s.listVersions(ctx, versions, ecosystem, name) if err != nil { @@ -181,6 +191,10 @@ type SBOMSource struct { Latest bool // Platforms limit which platforms of container images are mirrored. Platforms []string + // Disabled reports whether disabled_ecosystems turns off an ecosystem. + // Its unversioned PURLs aren't listed from the upstream: each yields + // one item, which Mirror refuses. + Disabled func(ecosystem string) bool } func (s *SBOMSource) Enumerate(ctx context.Context, fn func(PackageVersion) error) error { @@ -192,7 +206,7 @@ func (s *SBOMSource) Enumerate(ctx context.Context, fn func(PackageVersion) erro return fmt.Errorf("parsing SBOM: %w", err) } - inner := &PURLSource{PURLs: purls, Versions: s.Versions, Latest: s.Latest, Platforms: s.Platforms} + inner := &PURLSource{PURLs: purls, Versions: s.Versions, Latest: s.Latest, Platforms: s.Platforms, Disabled: s.Disabled} return inner.Enumerate(ctx, fn) } diff --git a/internal/server/change_feeds.go b/internal/server/change_feeds.go index 556650f2..63b7f528 100644 --- a/internal/server/change_feeds.go +++ b/internal/server/change_feeds.go @@ -24,10 +24,11 @@ const changeFeedMaxBackoff = 15 * time.Minute func (s *Server) startChangeFeeds(ctx context.Context, httpClient *http.Client, metadataTTL time.Duration) { c := changes.WithClient(client.NewClient(client.WithHTTPClient(httpClient))) var feeds []changes.Feed - if s.cfg.Upstream.NPMChangeFeed { + npm, composer := s.changeFeedsOn() + if npm { feeds = append(feeds, changes.NewNPM(c)) } - if s.cfg.Upstream.ComposerChangeFeed { + if composer { feeds = append(feeds, changes.NewPackagist(c, changes.WithURL(changes.PackagistFeedURL(s.cfg.Upstream.Composer)))) } if len(feeds) == 0 { @@ -43,6 +44,14 @@ func (s *Server) startChangeFeeds(ctx context.Context, httpClient *http.Client, } } +// changeFeedsOn reports which change feeds to follow: those the +// configuration turns on, unless disabled_ecosystems turns their ecosystem +// off. +func (s *Server) changeFeedsOn() (npm, composer bool) { + return s.cfg.Upstream.NPMChangeFeed && !s.cfg.EcosystemDisabled("npm"), + s.cfg.Upstream.ComposerChangeFeed && !s.cfg.EcosystemDisabled("composer") +} + // followChangeFeed reads feed every interval until ctx ends and expires the // cached metadata it lists. After a failed read it waits twice as long as // before, up to changeFeedMaxBackoff. The position in the feed is kept in diff --git a/internal/server/dashboard.go b/internal/server/dashboard.go index a3d4fa91..07d888bc 100644 --- a/internal/server/dashboard.go +++ b/internal/server/dashboard.go @@ -2,9 +2,11 @@ package server import ( "html/template" + "slices" "sort" "strings" + "github.com/git-pkgs/proxy/internal/config" "github.com/git-pkgs/proxy/internal/database" ) @@ -270,6 +272,14 @@ func buildEcosystemFilters(counts map[string]int64) []EcosystemFilter { return filters } +// installRegistries is getRegistryConfigs without the ecosystems +// disabled_ecosystems turns off. +func installRegistries(cfg *config.Config) []RegistryConfig { + return slices.DeleteFunc(getRegistryConfigs(cfg.BaseURL), func(r RegistryConfig) bool { + return cfg.EcosystemDisabled(r.ID) + }) +} + func getRegistryConfigs(baseURL string) []RegistryConfig { swiftInsecureFlag := "" if strings.HasPrefix(strings.ToLower(baseURL), "http://") { diff --git a/internal/server/disabled_ecosystems_test.go b/internal/server/disabled_ecosystems_test.go new file mode 100644 index 00000000..a514bb1e --- /dev/null +++ b/internal/server/disabled_ecosystems_test.go @@ -0,0 +1,206 @@ +package server + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/database" + "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/proxy/internal/storage" + "github.com/git-pkgs/registries/fetch" + "github.com/go-chi/chi/v5" +) + +// ecosystemPaths is a request under each disableable ecosystem's route. +var ecosystemPaths = map[string]string{ + "alpine": "/apk/alpine/v3.22/main/x86_64/APKINDEX.tar.gz", + "arch": "/arch/archlinux/core/os/x86_64/core.db", + "cargo": "/cargo/config.json", + "chef": "/chef/api/v1/cookbooks/nginx", + "composer": "/composer/packages.json", + "conan": "/conan/v2/ping", + "conda": "/conda/conda-forge/noarch/repodata.json", + "cran": "/cran/src/contrib/PACKAGES", + "deb": "/debian/dists/bookworm/InRelease", + "freebsd": "/freebsd/freebsd/FreeBSD:14:amd64/quarterly/meta.conf", + "gem": "/gem/specs.4.8.gz", + "golang": "/go/github.com/x/y/@v/list", + "gradle": "/gradle/cache/abc", + "helm": "/helm/bitnami/index.yaml", + "hex": "/hex/names", + "homebrew": "/homebrew/api/formula.jws.json", + "julia": "/julia/registries", + "maven": "/maven/org/x/y/maven-metadata.xml", + "npm": "/npm/lodash", + "nuget": "/nuget/v3/index.json", + "oci": "/v2/", + "pub": "/pub/api/packages/http", + "pypi": "/pypi/simple/requests/", + "rpm": "/rpm/releases/43/Everything/x86_64/os/repodata/repomd.xml", + "swift": "/swift/apple/swift-argument-parser", + "terraform": "/terraform/providers/registry.terraform.io/hashicorp/aws/index.json", +} + +func newDisabledRouter(t *testing.T, client *http.Client, disabled ...string) *chi.Mux { + t.Helper() + db, err := database.Create(t.TempDir() + "/test.db") + if err != nil { + t.Fatalf("creating database: %v", err) + } + t.Cleanup(func() { _ = db.Close() }) + store, err := storage.OpenBucket(context.Background(), "file://"+t.TempDir()) + if err != nil { + t.Fatalf("opening storage: %v", err) + } + fetcher := fetch.NewFetcher(fetch.WithHTTPClient(client), fetch.WithMaxRetries(0)) + t.Cleanup(func() { _ = fetcher.Close() }) + proxy := handler.NewProxy(db, store, fetcher, fetch.NewResolver(), slog.New(slog.NewTextHandler(io.Discard, nil))) + proxy.HTTPClient = client + + cfg := config.Default() + cfg.BaseURL = "http://proxy.example" + cfg.DisabledEcosystems = disabled + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + s := &Server{cfg: cfg} + r := chi.NewRouter() + s.mountProtocolHandlers(r, proxy) + return r +} + +func isDisabledResponse(w *httptest.ResponseRecorder) bool { + return w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "turned off") +} + +// Every disableable ecosystem's route answers 404 without contacting +// upstream when it is turned off, and only then. +func TestDisabledEcosystemRoutesAnswer404(t *testing.T) { + for _, key := range config.DisableableEcosystems { + path, ok := ecosystemPaths[key] + if !ok { + t.Errorf("%s: no request path in the test", key) + continue + } + t.Run(key, func(t *testing.T) { + transport := &countingTransport{} + r := newDisabledRouter(t, &http.Client{Transport: transport}, key) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if !isDisabledResponse(w) { + t.Errorf("GET %s: status %d, body %q; want the turned-off 404", path, w.Code, w.Body.String()) + } + if n := transport.hits.Load(); n != 0 { + t.Errorf("upstream was contacted %d times", n) + } + + enabled := newDisabledRouter(t, &http.Client{Transport: &countingTransport{}}) + w = httptest.NewRecorder() + enabled.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if isDisabledResponse(w) { + t.Errorf("GET %s answers turned off with nothing disabled", path) + } + }) + } +} + +// Turning one ecosystem off leaves the others served. +func TestDisabledEcosystemLeavesOthers(t *testing.T) { + r := newDisabledRouter(t, &http.Client{Transport: &countingTransport{}}, "pypi") + for key, path := range ecosystemPaths { + if key == "pypi" { + continue + } + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil)) + if isDisabledResponse(w) { + t.Errorf("GET %s answers turned off with only pypi disabled", path) + } + } +} + +// The install page leaves out turned-off ecosystems, and each of its +// entries names an ecosystem disabled_ecosystems accepts. +func TestInstallPageLeavesOutDisabledEcosystems(t *testing.T) { + cfg := config.Default() + cfg.BaseURL = "http://proxy.example" + all := installRegistries(cfg) + if len(all) != len(getRegistryConfigs(cfg.BaseURL)) { + t.Fatalf("installRegistries left out entries with nothing disabled") + } + for _, reg := range all { + cfg := config.Default() + cfg.BaseURL = "http://proxy.example" + cfg.DisabledEcosystems = []string{reg.ID} + if err := cfg.Validate(); err != nil { + t.Errorf("%s: %v", reg.ID, err) + continue + } + got := installRegistries(cfg) + if len(got) != len(all)-1 || slices.ContainsFunc(got, func(r RegistryConfig) bool { return r.ID == reg.ID }) { + t.Errorf("disabling %s: install page lists %d of %d entries", reg.ID, len(got), len(all)) + } + } +} + +// Mirror jobs and schedules refuse what disabled_ecosystems turns off, +// given as PURL types. +func TestServerMirrorRefusesDisabledEcosystems(t *testing.T) { + cfg := config.Default() + cfg.DisabledEcosystems = []string{"oci", "npm"} + if err := cfg.Validate(); err != nil { + t.Fatalf("Validate: %v", err) + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + proxy, _ := NewMirrorProxy(cfg, nil, nil, logger) + s := &Server{cfg: cfg, logger: logger, ecr: newECRTokens(logger)} + + m := s.newMirror(proxy, 1) + if m.Disabled == nil { + t.Fatal("Disabled is nil") + } + for eco, want := range map[string]bool{"npm": true, "docker": true, "oci": true, "cargo": false} { + if got := m.Disabled(eco); got != want { + t.Errorf("Disabled(%q) = %t, want %t", eco, got, want) + } + } +} + +// A change feed isn't followed for a turned-off ecosystem. +func TestChangeFeedsSkipDisabledEcosystems(t *testing.T) { + cfg := config.Default() + cfg.Upstream.NPMChangeFeed = true + cfg.Upstream.ComposerChangeFeed = true + s := &Server{cfg: cfg} + if npm, composer := s.changeFeedsOn(); !npm || !composer { + t.Fatalf("changeFeedsOn = %t, %t with nothing disabled; want both", npm, composer) + } + cfg.DisabledEcosystems = []string{"npm"} + if npm, composer := s.changeFeedsOn(); npm || !composer { + t.Errorf("changeFeedsOn = %t, %t with npm disabled; want composer only", npm, composer) + } + cfg.DisabledEcosystems = []string{"composer"} + if npm, composer := s.changeFeedsOn(); !npm || composer { + t.Errorf("changeFeedsOn = %t, %t with composer disabled; want npm only", npm, composer) + } +} + +// Every mounted ecosystem can be turned off: a route added without a key +// disabled_ecosystems accepts fails here. +func TestEcosystemRoutesCanBeTurnedOff(t *testing.T) { + if len(ecosystemMounts) == 0 { + t.Fatal("no ecosystem routes") + } + for _, mount := range ecosystemMounts { + if !slices.Contains(config.DisableableEcosystems, mount.key) { + t.Errorf("route %s has key %q, which disabled_ecosystems doesn't accept", mount.prefix, mount.key) + } + } +} diff --git a/internal/server/mirror_versions.go b/internal/server/mirror_versions.go index bf756745..8ce974c8 100644 --- a/internal/server/mirror_versions.go +++ b/internal/server/mirror_versions.go @@ -36,6 +36,7 @@ func (s *Server) newMirror(proxy *handler.Proxy, workers int) *mirror.Mirror { m.Git = handler.NewGitHandler(proxy, s.git, s.cfg.Upstream) } UseMirrorUpstreams(m, s.cfg.Upstream, proxy.HTTPClient) + m.Disabled = s.cfg.EcosystemDisabled return m } diff --git a/internal/server/server.go b/internal/server/server.go index 2061b080..d5300854 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -562,32 +562,34 @@ func (s *Server) mountProtocolHandlersAt(r chi.Router, proxy *handler.Proxy, bas r.With(sandboxUpstreamContent, rejectDotSegments). Mount("/generic", http.StripPrefix("/generic", genericHandler.Routes())) r = r.With(sandboxUpstreamContent, rejectQueryInPath, rejectDotSegments) - r.Mount("/npm", http.StripPrefix("/npm", npmHandler.Routes())) - r.Mount("/cargo", http.StripPrefix("/cargo", cargoHandler.Routes())) - r.Mount("/gem", http.StripPrefix("/gem", gemHandler.Routes())) - r.Mount("/go", http.StripPrefix("/go", goHandler.Routes())) - r.Mount("/hex", http.StripPrefix("/hex", hexHandler.Routes())) - r.Mount("/pub", http.StripPrefix("/pub", pubHandler.Routes())) - r.Mount("/pypi", http.StripPrefix("/pypi", pypiHandler.Routes())) - r.Mount("/maven", http.StripPrefix("/maven", mavenHandler.Routes())) - r.Mount("/gradle", http.StripPrefix("/gradle", gradleHandler.Routes())) - r.Mount("/nuget", http.StripPrefix("/nuget", nugetHandler.Routes())) - r.Mount("/composer", http.StripPrefix("/composer", composerHandler.Routes())) - r.Mount("/conan", http.StripPrefix("/conan", conanHandler.Routes())) - r.Mount("/chef", http.StripPrefix("/chef", chefHandler.Routes())) - r.Mount("/conda", http.StripPrefix("/conda", condaHandler.Routes())) - r.Mount("/cran", http.StripPrefix("/cran", cranHandler.Routes())) - r.Mount("/julia", http.StripPrefix("/julia", juliaHandler.Routes())) - r.Mount("/swift", http.StripPrefix("/swift", swiftHandler.Routes())) - r.Mount("/homebrew", http.StripPrefix("/homebrew", homebrewHandler.Routes())) - r.Mount("/v2", http.StripPrefix("/v2", containerHandler.Routes())) - r.Mount("/helm", http.StripPrefix("/helm", helmHandler.Routes())) - r.Mount("/apk", http.StripPrefix("/apk", apkHandler.Routes())) - r.Mount("/arch", http.StripPrefix("/arch", archHandler.Routes())) - r.Mount("/freebsd", http.StripPrefix("/freebsd", freebsdHandler.Routes())) - r.Mount("/terraform", http.StripPrefix("/terraform", terraformHandler.Routes())) - r.Mount("/debian", http.StripPrefix("/debian", debianHandler.Routes())) - r.Mount("/rpm", http.StripPrefix("/rpm", rpmHandler.Routes())) + s.mountEcosystems(r, map[string]http.Handler{ + "npm": npmHandler.Routes(), + "cargo": cargoHandler.Routes(), + "gem": gemHandler.Routes(), + "golang": goHandler.Routes(), + "hex": hexHandler.Routes(), + "pub": pubHandler.Routes(), + "pypi": pypiHandler.Routes(), + "maven": mavenHandler.Routes(), + "gradle": gradleHandler.Routes(), + "nuget": nugetHandler.Routes(), + "composer": composerHandler.Routes(), + "conan": conanHandler.Routes(), + "chef": chefHandler.Routes(), + "conda": condaHandler.Routes(), + "cran": cranHandler.Routes(), + "julia": juliaHandler.Routes(), + "swift": swiftHandler.Routes(), + "homebrew": homebrewHandler.Routes(), + "oci": containerHandler.Routes(), + "helm": helmHandler.Routes(), + "alpine": apkHandler.Routes(), + "arch": archHandler.Routes(), + "freebsd": freebsdHandler.Routes(), + "terraform": terraformHandler.Routes(), + "deb": debianHandler.Routes(), + "rpm": rpmHandler.Routes(), + }) if s.git == nil { return nil } @@ -597,6 +599,71 @@ func (s *Server) mountProtocolHandlersAt(r chi.Router, proxy *handler.Proxy, bas return gitHandler } +// ecosystemMount is where an ecosystem's handler is mounted, by the key +// disabled_ecosystems turns it off with. +type ecosystemMount struct { + key string + prefix string +} + +// ecosystemMounts are the ecosystem routes, in mount order. +var ecosystemMounts = []ecosystemMount{ + {"npm", "/npm"}, + {"cargo", "/cargo"}, + {"gem", "/gem"}, + {"golang", "/go"}, + {"hex", "/hex"}, + {"pub", "/pub"}, + {"pypi", "/pypi"}, + {"maven", "/maven"}, + {"gradle", "/gradle"}, + {"nuget", "/nuget"}, + {"composer", "/composer"}, + {"conan", "/conan"}, + {"chef", "/chef"}, + {"conda", "/conda"}, + {"cran", "/cran"}, + {"julia", "/julia"}, + {"swift", "/swift"}, + {"homebrew", "/homebrew"}, + {"oci", "/v2"}, + {"helm", "/helm"}, + {"alpine", "/apk"}, + {"arch", "/arch"}, + {"freebsd", "/freebsd"}, + {"terraform", "/terraform"}, + {"deb", "/debian"}, + {"rpm", "/rpm"}, +} + +// mountEcosystems mounts each of ecosystemMounts with its handler from +// handlers, or for an ecosystem disabled_ecosystems turns off, a handler +// that answers 404 without reaching its upstream. +func (s *Server) mountEcosystems(r chi.Router, handlers map[string]http.Handler) { + if len(handlers) != len(ecosystemMounts) { + panic(fmt.Sprintf("%d ecosystem handlers for %d routes", len(handlers), len(ecosystemMounts))) + } + for _, mount := range ecosystemMounts { + h, ok := handlers[mount.key] + if !ok { + panic("no handler for ecosystem route " + mount.key) + } + if s.cfg.EcosystemDisabled(mount.key) { + r.Mount(mount.prefix, ecosystemTurnedOff(mount.key)) + continue + } + r.Mount(mount.prefix, http.StripPrefix(mount.prefix, h)) + } +} + +// ecosystemTurnedOff answers every request with 404, so clients treat the +// ecosystem as absent rather than failing. +func ecosystemTurnedOff(key string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, key+" is turned off on this proxy", http.StatusNotFound) + }) +} + // configureScanning builds the scanner group from cfg and wires it into // proxy, returning the group so the caller can decide whether to mount the // internal scan-fetch route. @@ -1008,7 +1075,7 @@ func (s *Server) handleInstall(w http.ResponseWriter, r *http.Request) { }{ Layout: s.layoutFor(r), BaseURL: s.cfg.BaseURL, - Registries: getRegistryConfigs(s.cfg.BaseURL), + Registries: installRegistries(s.cfg), } if err := s.templates.Render(w, "install", data); err != nil {