From e3f1ee7a4ec25df9ed318eaf129236134268a251 Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Sun, 22 Nov 2026 19:55:35 +0100 Subject: [PATCH] Add disabled_ecosystems to turn ecosystems off Every built-in package route is served by default, and there was no way to turn one off. disabled_ecosystems (PROXY_DISABLED_ECOSYSTEMS) takes ecosystem keys such as pypi or oci, with the aliases scanning accepts. A turned-off ecosystem's routes answer 404 without reaching upstream, also under cooldown profiles; it is left off the install page; proxy mirror, mirror API jobs and schedules fail its packages; and its change feed isn't followed. Cached data stays. Unknown names fail validation. --- cmd/proxy/main.go | 1 + cmd/proxy/mirror_test.go | 15 ++ config.example.yaml | 4 + docs/configuration.md | 12 ++ internal/config/config.go | 10 + internal/config/disabled_ecosystems.go | 49 +++++ internal/config/disabled_ecosystems_test.go | 74 ++++++++ internal/mirror/mirror.go | 9 + internal/mirror/mirror_test.go | 50 +++++ internal/server/change_feeds.go | 13 +- internal/server/dashboard.go | 10 + internal/server/disabled_ecosystems_test.go | 193 ++++++++++++++++++++ internal/server/mirror_versions.go | 1 + internal/server/server.go | 83 ++++++--- 14 files changed, 495 insertions(+), 29 deletions(-) create mode 100644 internal/config/disabled_ecosystems.go create mode 100644 internal/config/disabled_ecosystems_test.go create mode 100644 internal/server/disabled_ecosystems_test.go diff --git a/cmd/proxy/main.go b/cmd/proxy/main.go index 7c51732f..b7d6edaf 100644 --- a/cmd/proxy/main.go +++ b/cmd/proxy/main.go @@ -631,6 +631,7 @@ 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) } diff --git a/cmd/proxy/mirror_test.go b/cmd/proxy/mirror_test.go index bd39de9b..d1d0f176 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,14 @@ 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") + } +} 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 991fb61d..2a1c31f2 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 and `mirror.schedules` fail its packages with an error saying it is turned off, 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/mirror.go b/internal/mirror/mirror.go index 50305084..c483b368 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 m.Disabled != nil && m.Disabled(pv.Ecosystem) { + m.recordFailure(tracker, pv, fmt.Errorf("%s is turned off on this proxy", pv.Ecosystem)) + return + } if isImageEcosystem(pv.Ecosystem) && m.Images != nil { m.mirrorImage(ctx, pv, tracker) return diff --git a/internal/mirror/mirror_test.go b/internal/mirror/mirror_test.go index 68526878..9aea19b2 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,52 @@ 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") +} 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..36613dcb --- /dev/null +++ b/internal/server/disabled_ecosystems_test.go @@ -0,0 +1,193 @@ +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) + } +} 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 297adeae..667af1fc 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -561,32 +561,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, []ecosystemRoute{ + {"npm", "/npm", npmHandler.Routes()}, + {"cargo", "/cargo", cargoHandler.Routes()}, + {"gem", "/gem", gemHandler.Routes()}, + {"golang", "/go", goHandler.Routes()}, + {"hex", "/hex", hexHandler.Routes()}, + {"pub", "/pub", pubHandler.Routes()}, + {"pypi", "/pypi", pypiHandler.Routes()}, + {"maven", "/maven", mavenHandler.Routes()}, + {"gradle", "/gradle", gradleHandler.Routes()}, + {"nuget", "/nuget", nugetHandler.Routes()}, + {"composer", "/composer", composerHandler.Routes()}, + {"conan", "/conan", conanHandler.Routes()}, + {"chef", "/chef", chefHandler.Routes()}, + {"conda", "/conda", condaHandler.Routes()}, + {"cran", "/cran", cranHandler.Routes()}, + {"julia", "/julia", juliaHandler.Routes()}, + {"swift", "/swift", swiftHandler.Routes()}, + {"homebrew", "/homebrew", homebrewHandler.Routes()}, + {"oci", "/v2", containerHandler.Routes()}, + {"helm", "/helm", helmHandler.Routes()}, + {"alpine", "/apk", apkHandler.Routes()}, + {"arch", "/arch", archHandler.Routes()}, + {"freebsd", "/freebsd", freebsdHandler.Routes()}, + {"terraform", "/terraform", terraformHandler.Routes()}, + {"deb", "/debian", debianHandler.Routes()}, + {"rpm", "/rpm", rpmHandler.Routes()}, + }) if s.git == nil { return nil } @@ -596,6 +598,33 @@ func (s *Server) mountProtocolHandlersAt(r chi.Router, proxy *handler.Proxy, bas return gitHandler } +// ecosystemRoute is an ecosystem's handler, mounted at prefix. +type ecosystemRoute struct { + key string + prefix string + handler http.Handler +} + +// mountEcosystems mounts each route, or for an ecosystem disabled_ecosystems +// turns off, a handler that answers 404 without reaching its upstream. +func (s *Server) mountEcosystems(r chi.Router, routes []ecosystemRoute) { + for _, route := range routes { + if s.cfg.EcosystemDisabled(route.key) { + r.Mount(route.prefix, ecosystemTurnedOff(route.key)) + continue + } + r.Mount(route.prefix, http.StripPrefix(route.prefix, route.handler)) + } +} + +// 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. @@ -1007,7 +1036,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 {