From 5cd8122c9075d9befb95cd5c6199242740054d5c Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Sun, 22 Nov 2026 19:54:30 +0100 Subject: [PATCH] Add an upstreams page to the web UI /ui/upstreams lists, per ecosystem, the upstream URLs the config sets, the proxy path clients reach each one at, the config key, and the type of the upstream.auth entry that applies. Maps the proxy fills with a default when empty, such as upstream.apk and upstream.go_sumdbs, show that default. URLs are shown without userinfo, query and fragment, and no credentials are shown. The arch, freebsd and go_sumdbs defaults move into exported helpers, like APKRepositories, so the page and the handlers share them. --- README.md | 1 + internal/handler/arch.go | 20 +- internal/handler/freebsd.go | 20 +- internal/handler/go_sumdb.go | 18 +- internal/server/server.go | 1 + internal/server/templates/layout/header.html | 1 + .../server/templates/pages/upstreams.html | 30 +++ internal/server/upstreams_ui.go | 187 ++++++++++++++++++ internal/server/upstreams_ui_test.go | 152 ++++++++++++++ 9 files changed, 412 insertions(+), 18 deletions(-) create mode 100644 internal/server/templates/pages/upstreams.html create mode 100644 internal/server/upstreams_ui.go create mode 100644 internal/server/upstreams_ui_test.go diff --git a/README.md b/README.md index 961ce67e..833bc687 100644 --- a/README.md +++ b/README.md @@ -1649,6 +1649,7 @@ The proxy serves a web UI under `/ui`. No separate frontend build is needed -- t - **Dashboard** (`/ui/`) -- cache stats, popular packages, recently cached artifacts, and vulnerability overview. - **Analytics** (`/ui/analytics`) -- accumulated download size as a ring broken down by ecosystem with the total in the middle, the cache size, artifact, package and version counts, a per-ecosystem table, the vulnerability overview, and a Runtime card mirroring every counter `/metrics` exposes. See [Analytics](#analytics). - **Install guide** (`/ui/install`) -- per-ecosystem configuration instructions, so you don't have to look them up here. +- **Upstreams** (`/ui/upstreams`) -- the upstream URLs each ecosystem's requests go to, as configured, with the proxy path clients use, the config key and, where an `upstream.auth` entry applies, its type. Credentials, and a URL's userinfo, query and fragment, are never shown. Like the rest of `/ui`, it names hosts the proxy reaches, so restrict `/ui` if those are internal. - **Package browser** (`/ui/packages`) -- browse all cached packages with filtering by ecosystem and sorting by hits, size, name, or vulnerability count. - **Search** (`/ui/search?q=...`) -- search cached packages by name. - **Package detail** (`/ui/package/{ecosystem}/{name}`) -- metadata, license, vulnerabilities, and version list for a package. You can select two versions to compare. diff --git a/internal/handler/arch.go b/internal/handler/arch.go index f3d6cf93..1bcbd6ee 100644 --- a/internal/handler/arch.go +++ b/internal/handler/arch.go @@ -45,15 +45,23 @@ func NewArchHandler(proxy *Proxy, proxyURL string, repositories map[string]strin h := &ArchHandler{ proxy: proxy, proxyURL: strings.TrimSuffix(proxyURL, "/"), - repositories: make(map[string]string, len(repositories)), + repositories: ArchRepositories(repositories), } - for name, repositoryURL := range repositories { - h.repositories[name] = strings.TrimSuffix(repositoryURL, "/") + return h +} + +// ArchRepositories returns the upstream.arch repositories by name without +// trailing slashes, or the Arch Linux GeoIP mirror as "archlinux" when none +// are configured. +func ArchRepositories(configured map[string]string) map[string]string { + repositories := make(map[string]string, len(configured)) + for name, repositoryURL := range configured { + repositories[name] = strings.TrimSuffix(repositoryURL, "/") } - if len(h.repositories) == 0 { - h.repositories[defaultArchRepositoryName] = defaultArchUpstream + if len(repositories) == 0 { + repositories[defaultArchRepositoryName] = defaultArchUpstream } - return h + return repositories } // Routes returns the HTTP handler for pacman requests. diff --git a/internal/handler/freebsd.go b/internal/handler/freebsd.go index aceffa4f..9cf9ce7c 100644 --- a/internal/handler/freebsd.go +++ b/internal/handler/freebsd.go @@ -67,15 +67,23 @@ func NewFreeBSDHandler(proxy *Proxy, proxyURL string, repositories map[string]st h := &FreeBSDHandler{ proxy: proxy, proxyURL: strings.TrimSuffix(proxyURL, "/"), - repositories: make(map[string]string, len(repositories)), + repositories: FreeBSDRepositories(repositories), } - for name, repositoryURL := range repositories { - h.repositories[name] = strings.TrimSuffix(repositoryURL, "/") + return h +} + +// FreeBSDRepositories returns the upstream.freebsd repositories by name +// without trailing slashes, or the official FreeBSD mirror as "freebsd" +// when none are configured. +func FreeBSDRepositories(configured map[string]string) map[string]string { + repositories := make(map[string]string, len(configured)) + for name, repositoryURL := range configured { + repositories[name] = strings.TrimSuffix(repositoryURL, "/") } - if len(h.repositories) == 0 { - h.repositories[defaultFreeBSDRepositoryName] = defaultFreeBSDUpstream + if len(repositories) == 0 { + repositories[defaultFreeBSDRepositoryName] = defaultFreeBSDUpstream } - return h + return repositories } // Routes returns the HTTP handler for pkg requests. diff --git a/internal/handler/go_sumdb.go b/internal/handler/go_sumdb.go index 1c4c128e..bb2ba355 100644 --- a/internal/handler/go_sumdb.go +++ b/internal/handler/go_sumdb.go @@ -100,14 +100,20 @@ func (p *goSumDBProbes) recordFailure(name string, start time.Time) { // clients have no route to the database of their own. func (h *GoHandler) SetSumDBs(sumDBs map[string]string, offline bool) { h.sumDBOffline = offline - if len(sumDBs) == 0 { - h.sumDBs = map[string]string{defaultGoSumDBName: defaultGoSumDBURL} - return + h.sumDBs = GoSumDBs(sumDBs) +} + +// GoSumDBs returns the upstream.go_sumdbs checksum databases by name without +// trailing slashes, or sum.golang.org when none are configured. +func GoSumDBs(configured map[string]string) map[string]string { + if len(configured) == 0 { + return map[string]string{defaultGoSumDBName: defaultGoSumDBURL} } - h.sumDBs = make(map[string]string, len(sumDBs)) - for name, sumDBURL := range sumDBs { - h.sumDBs[name] = strings.TrimSuffix(sumDBURL, "/") + sumDBs := make(map[string]string, len(configured)) + for name, sumDBURL := range configured { + sumDBs[name] = strings.TrimSuffix(sumDBURL, "/") } + return sumDBs } // handleSumDB serves checksum database requests that the go command sends diff --git a/internal/server/server.go b/internal/server/server.go index 297adeae..2061b080 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -380,6 +380,7 @@ func (s *Server) serve(listener net.Listener) error { ui.Get("/", s.handleRoot) ui.Get("/analytics", s.handleAnalytics) ui.Get("/install", s.handleInstall) + ui.Get("/upstreams", s.handleUpstreams) ui.Get("/search", s.handleSearch) ui.Get("/packages", s.handlePackagesList) ui.Get("/package/{ecosystem}/*", s.handlePackagePath) diff --git a/internal/server/templates/layout/header.html b/internal/server/templates/layout/header.html index a5740103..bb3d790d 100644 --- a/internal/server/templates/layout/header.html +++ b/internal/server/templates/layout/header.html @@ -58,6 +58,7 @@ {{if .Projects}}Projects{{end}} Analytics Install +Upstreams Health API {{end}} diff --git a/internal/server/templates/pages/upstreams.html b/internal/server/templates/pages/upstreams.html new file mode 100644 index 00000000..faacfa92 --- /dev/null +++ b/internal/server/templates/pages/upstreams.html @@ -0,0 +1,30 @@ +{{define "title"}}Upstreams - git-pkgs proxy{{end}} + +{{define "content"}} +
+

Upstreams

+

Where each ecosystem's requests go, as configured. Credentials are never shown; Auth names the type of the upstream.auth entry that applies.

+
+ +
+ {{range .Ecosystems}} +
+

{{.Name}}

+
+ {{range .Upstreams}} +
+
+
{{.URL}}
+
{{.Path}}
+
+
+ {{.Setting}}{{if .Name}} ยท {{.Name}}{{end}} + {{if .Auth}}auth: {{.Auth}}{{end}} +
+
+ {{end}} +
+
+ {{end}} +
+{{end}} diff --git a/internal/server/upstreams_ui.go b/internal/server/upstreams_ui.go new file mode 100644 index 00000000..a6eb4bb2 --- /dev/null +++ b/internal/server/upstreams_ui.go @@ -0,0 +1,187 @@ +package server + +import ( + "net/http" + "net/url" + "sort" + "strings" + + "github.com/git-pkgs/proxy/internal/config" + "github.com/git-pkgs/proxy/internal/handler" +) + +// UpstreamsData is the upstreams page: the upstream URLs each ecosystem's +// requests go to, as configured. +type UpstreamsData struct { + Layout + Ecosystems []UpstreamEcosystem +} + +// UpstreamEcosystem is one ecosystem on the upstreams page. +type UpstreamEcosystem struct { + Name string + Upstreams []UpstreamRow +} + +// UpstreamRow is one configured upstream URL. It carries no credentials: +// URL has no userinfo, query or fragment, and Auth names only the type of +// the upstream.auth entry that applies to it. +type UpstreamRow struct { + // Setting is the config key that sets URL, such as upstream.apk, and + // Name the entry's key in it for a map. + Setting, Name string + // Path is where clients reach the upstream through the proxy. + Path string + URL string + // Auth is the type of the upstream.auth entry for URL, empty when none + // applies. + Auth string +} + +func (s *Server) handleUpstreams(w http.ResponseWriter, r *http.Request) { + data := UpstreamsData{ + Layout: s.layoutFor(r), + Ecosystems: upstreamEcosystems(s.cfg.BaseURL, &s.cfg.Upstream), + } + if err := s.templates.Render(w, "upstreams", data); err != nil { + s.logger.Error("failed to render upstreams", "error", err) + } +} + +// upstreamSetting is one config key on the upstreams page: a single URL +// or, with named set, a map of them. path is where it is served, with +// {name} for a map entry's key. +type upstreamSetting struct { + key string + path string + url string + named map[string]string +} + +// upstreamEcosystems lists the upstream URLs u configures, per ecosystem. +// A map the proxy fills with a default when it is empty, such as +// upstream.apk, lists that default. +func upstreamEcosystems(baseURL string, u *config.UpstreamConfig) []UpstreamEcosystem { + git := make(map[string]string, len(u.Git)) + for name, upstream := range u.Git { + git[name] = upstream.URL + } + single := func(key, path, url string) upstreamSetting { return upstreamSetting{key: key, path: path, url: url} } + named := func(key, path string, m map[string]string) upstreamSetting { + return upstreamSetting{key: key, path: path, named: m} + } + groups := []struct { + name string + settings []upstreamSetting + }{ + {"npm", []upstreamSetting{single("upstream.npm", "/npm/", u.NPM), named("upstream.npm_routes", "/npm/", u.NPMRoutes)}}, + {"Cargo", []upstreamSetting{single("upstream.cargo", "/cargo/", u.Cargo), single("upstream.cargo_download", "/cargo/", u.CargoDownload)}}, + {"RubyGems", []upstreamSetting{single("upstream.gem", "/gem/", u.Gem)}}, + {"Go", []upstreamSetting{ + single("upstream.go", "/go/", u.Go), + named("upstream.go_sumdbs", "/go/sumdb/{name}/", handler.GoSumDBs(u.GoSumDBs)), + single("upstream.go_vulndb", "/go/vulndb/", u.GoVulnDB), + }}, + {"Hex", []upstreamSetting{single("upstream.hex", "/hex/", u.Hex), single("upstream.hex_api", "/hex/", u.HexAPI)}}, + {"pub.dev", []upstreamSetting{single("upstream.pub", "/pub/", u.Pub)}}, + {"PyPI", []upstreamSetting{single("upstream.pypi", "/pypi/", u.PyPI), single("upstream.pypi_download", "/pypi/", u.PyPIDownload)}}, + {"Maven", []upstreamSetting{ + single("upstream.maven", "/maven/", u.Maven), + named("upstream.maven_repositories", "/maven/{name}/", u.MavenRepositories), + single("upstream.gradle_plugin_portal", "/maven/", u.GradlePluginPortal), + }}, + {"NuGet", []upstreamSetting{single("upstream.nuget", "/nuget/", u.NuGet), single("upstream.nuget_search", "/nuget/", u.NuGetSearch)}}, + {"Composer", []upstreamSetting{ + single("upstream.composer", "/composer/", u.Composer), + single("upstream.composer_repository", "/composer/", u.ComposerRepository), + named("upstream.composer_routes", "/composer/", u.ComposerRoutes), + }}, + {"Conan", []upstreamSetting{single("upstream.conan", "/conan/", u.Conan)}}, + {"Chef", []upstreamSetting{single("upstream.chef", "/chef/", u.Chef)}}, + {"Conda", []upstreamSetting{single("upstream.conda", "/conda/", u.Conda)}}, + {"CRAN", []upstreamSetting{single("upstream.cran", "/cran/", u.CRAN)}}, + {"Julia", []upstreamSetting{single("upstream.julia", "/julia/", u.Julia)}}, + {"Swift", []upstreamSetting{single("upstream.swift", "/swift/", u.Swift)}}, + {"Homebrew", []upstreamSetting{ + single("upstream.homebrew_api", "/homebrew/", u.HomebrewAPI), + single("upstream.homebrew_artifact", "/homebrew/", u.HomebrewArtifact), + }}, + {"OCI", []upstreamSetting{single("upstream.oci_default", "/v2/", u.OCIDefault), named("upstream.oci", "/v2/upstream/{name}/", u.OCI)}}, + {"Helm", []upstreamSetting{named("upstream.helm", "/helm/{name}/", u.Helm)}}, + {"Alpine", []upstreamSetting{named("upstream.apk", "/apk/{name}/", handler.APKRepositories(u.APK))}}, + {"Arch Linux", []upstreamSetting{named("upstream.arch", "/arch/{name}/", handler.ArchRepositories(u.Arch))}}, + {"FreeBSD", []upstreamSetting{named("upstream.freebsd", "/freebsd/{name}/", handler.FreeBSDRepositories(u.FreeBSD))}}, + {"Terraform", []upstreamSetting{named("upstream.terraform", "/terraform/providers/{name}/", terraformRegistries(u.Terraform))}}, + {"Debian", []upstreamSetting{single("upstream.debian", "/debian/", u.Debian), named("upstream.debian_repositories", "/debian/{name}/", u.DebianRepositories)}}, + {"RPM", []upstreamSetting{single("upstream.rpm", "/rpm/", u.RPM)}}, + {"Generic", []upstreamSetting{named("upstream.generic", "/generic/{name}/", u.Generic)}}, + {"Git", []upstreamSetting{named("upstream.git", "/git/{name}/", git)}}, + } + base := strings.TrimSuffix(baseURL, "/") + ecosystems := make([]UpstreamEcosystem, 0, len(groups)) + for _, group := range groups { + var rows []UpstreamRow + for _, setting := range group.settings { + rows = append(rows, setting.rows(base, u)...) + } + if len(rows) > 0 { + ecosystems = append(ecosystems, UpstreamEcosystem{Name: group.name, Upstreams: rows}) + } + } + return ecosystems +} + +// rows lists the setting's URLs, map entries sorted by name, leaving out +// empty ones. +func (s upstreamSetting) rows(base string, u *config.UpstreamConfig) []UpstreamRow { + row := func(name, rawURL string) UpstreamRow { + r := UpstreamRow{ + Setting: s.key, + Name: name, + Path: base + strings.ReplaceAll(s.path, "{name}", name), + URL: displayURL(rawURL), + } + if auth := u.AuthForURL(rawURL); auth != nil { + r.Auth = strings.ToLower(auth.Type) + } + return r + } + if s.named == nil { + if s.url == "" { + return nil + } + return []UpstreamRow{row("", s.url)} + } + names := make([]string, 0, len(s.named)) + for name := range s.named { + names = append(names, name) + } + sort.Strings(names) + rows := make([]UpstreamRow, 0, len(names)) + for _, name := range names { + rows = append(rows, row(name, s.named[name])) + } + return rows +} + +// terraformRegistries is upstream.terraform as the provider mirror uses +// it: the default registries when empty. +func terraformRegistries(configured map[string]string) map[string]string { + if len(configured) == 0 { + return handler.DefaultTerraformRegistries + } + return configured +} + +// displayURL is rawURL without its userinfo, query and fragment, where +// credentials can sit. A URL that doesn't parse is not shown at all. +func displayURL(rawURL string) string { + u, err := url.Parse(rawURL) + if err != nil || u.Host == "" { + return "(not a valid URL)" + } + u.User = nil + u.RawQuery, u.ForceQuery = "", false + u.Fragment, u.RawFragment = "", "" + return strings.TrimSuffix(u.String(), "/") +} diff --git a/internal/server/upstreams_ui_test.go b/internal/server/upstreams_ui_test.go new file mode 100644 index 00000000..e89a3a2d --- /dev/null +++ b/internal/server/upstreams_ui_test.go @@ -0,0 +1,152 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/git-pkgs/proxy/internal/config" +) + +func TestUpstreamsPage(t *testing.T) { + cfg, _ := startGitTestServer(t, func(cfg *config.Config) { + cfg.Upstream.Debian = "https://deb.example.org/debian" + cfg.Upstream.DebianRepositories = map[string]string{"security": "https://security.example.org/debian-security"} + cfg.Upstream.Helm = map[string]string{"charts": "https://charts.example.org"} + cfg.Upstream.Auth = map[string]config.AuthConfig{ + "https://charts.example.org": {Type: "bearer", Token: "chart-token-secret"}, + } + }) + + if _, body := request(t, http.MethodGet, cfg.BaseURL+"/ui/", "", nil); !strings.Contains(body, `href="/ui/upstreams"`) { + t.Error("navigation doesn't link the upstreams page") + } + status, body := request(t, http.MethodGet, cfg.BaseURL+"/ui/upstreams", "", nil) + if status != http.StatusOK { + t.Fatalf("status %d\n%s", status, body) + } + for _, want := range []string{ + "https://deb.example.org/debian", + cfg.BaseURL + "/debian/", + "https://security.example.org/debian-security", + cfg.BaseURL + "/debian/security/", + "https://charts.example.org", + cfg.BaseURL + "/helm/charts/", + "https://registry.npmjs.org", + cfg.BaseURL + "/npm/", + // upstream.apk is empty, so the page lists the mirror the proxy uses. + "https://dl-cdn.alpinelinux.org/alpine", + cfg.BaseURL + "/apk/alpine/", + // So is the checksum database with upstream.go_sumdbs empty. + cfg.BaseURL + "/go/sumdb/sum.golang.org/", + } { + if !strings.Contains(body, want) { + t.Errorf("page doesn't show %q", want) + } + } + if strings.Contains(body, "chart-token-secret") { + t.Error("page shows the upstream token") + } +} + +func TestUpstreamEcosystems(t *testing.T) { + u := config.Default().Upstream + u.NPM = "https://user:url-password@npm.example.org/registry?token=query-secret#frag" + u.Generic = map[string]string{"files": "https://files.example.org/base"} + u.Git = map[string]config.GitUpstream{"github": {URL: "https://github.com"}} + u.GoSumDBs = map[string]string{"sum.example.org": "https://sum.example.org"} + u.Auth = map[string]config.AuthConfig{ + "https://npm.example.org": {Type: "basic", Username: "basic-user", Password: "basic-secret"}, + "https://files.example.org": {Type: "header", HeaderName: "X-Api-Key", HeaderValue: "header-secret"}, + } + ecosystems := upstreamEcosystems("http://proxy.test/", &u) + + rows := map[string]UpstreamRow{} + for _, e := range ecosystems { + for _, row := range e.Upstreams { + rows[row.Setting+" "+row.Name] = row + } + } + for key, want := range map[string]UpstreamRow{ + "upstream.npm ": {Setting: "upstream.npm", Path: "http://proxy.test/npm/", URL: "https://npm.example.org/registry", Auth: "basic"}, + "upstream.generic files": {Setting: "upstream.generic", Name: "files", Path: "http://proxy.test/generic/files/", URL: "https://files.example.org/base", Auth: "header"}, + "upstream.git github": {Setting: "upstream.git", Name: "github", Path: "http://proxy.test/git/github/", URL: "https://github.com"}, + "upstream.go_sumdbs sum.example.org": {Setting: "upstream.go_sumdbs", Name: "sum.example.org", Path: "http://proxy.test/go/sumdb/sum.example.org/", URL: "https://sum.example.org"}, + "upstream.arch archlinux": {Setting: "upstream.arch", Name: "archlinux", Path: "http://proxy.test/arch/archlinux/", URL: "https://geo.mirror.pkgbuild.com"}, + "upstream.freebsd freebsd": {Setting: "upstream.freebsd", Name: "freebsd", Path: "http://proxy.test/freebsd/freebsd/", URL: "https://pkg.freebsd.org"}, + "upstream.cargo_download ": {Setting: "upstream.cargo_download", Path: "http://proxy.test/cargo/", URL: "https://static.crates.io/crates"}, + } { + if got := rows[key]; got != want { + t.Errorf("%s = %+v, want %+v", key, got, want) + } + } + if _, ok := rows["upstream.go_sumdbs sum.golang.org"]; ok { + t.Error("lists the default checksum database although upstream.go_sumdbs replaces it") + } + if _, ok := rows["upstream.helm "]; ok { + t.Error("lists an empty upstream.helm") + } + if got := rows["upstream.terraform registry.opentofu.org"].URL; got != "https://registry.opentofu.org" { + t.Errorf("default Terraform registry = %q", got) + } + for _, e := range ecosystems { + if len(e.Upstreams) == 0 { + t.Errorf("lists %s without upstreams", e.Name) + } + } +} + +func TestUpstreamEcosystemsSortNames(t *testing.T) { + u := config.Default().Upstream + u.Generic = map[string]string{} + for _, name := range []string{"d", "b", "e", "a", "c", "f", "h", "g"} { + u.Generic[name] = "https://" + name + ".example.org" + } + for _, e := range upstreamEcosystems("http://proxy.test", &u) { + if e.Name != "Generic" { + continue + } + var names []string + for _, row := range e.Upstreams { + names = append(names, row.Name) + } + if got := strings.Join(names, ""); got != "abcdefgh" { + t.Errorf("generic upstreams in order %q", got) + } + } +} + +func TestUpstreamsPageShowsNoSecrets(t *testing.T) { + u := config.Default().Upstream + u.NPM = "https://user:url-password@npm.example.org?token=query-secret#frag-secret" + u.Generic = map[string]string{"files": "https://files.example.org"} + u.Auth = map[string]config.AuthConfig{ + "https://npm.example.org": {Type: "basic", Username: "basic-user", Password: "basic-secret"}, + "https://files.example.org": {Type: "header", HeaderName: "X-Api-Key", HeaderValue: "header-secret"}, + "https://pypi.org": {Type: "bearer", Token: "bearer-secret"}, + } + w := httptest.NewRecorder() + if err := (&Templates{}).Render(w, "upstreams", UpstreamsData{Ecosystems: upstreamEcosystems("http://proxy.test", &u)}); err != nil { + t.Fatal(err) + } + body := w.Body.String() + for _, secret := range []string{"url-password", "user@", "query-secret", "frag-secret", "basic-user", "basic-secret", "X-Api-Key", "header-secret", "bearer-secret"} { + if strings.Contains(body, secret) { + t.Errorf("page shows %q", secret) + } + } + for _, want := range []string{"https://npm.example.org", "basic", "header", "bearer"} { + if !strings.Contains(body, want) { + t.Errorf("page doesn't show %q", want) + } + } +} + +func TestDisplayURLHidesWhatItCannotParse(t *testing.T) { + for _, raw := range []string{"https://user:pw@[::1", "not a url with secret", ""} { + if got := displayURL(raw); strings.Contains(got, "secret") || strings.Contains(got, "pw") { + t.Errorf("displayURL(%q) = %q", raw, got) + } + } +}