diff --git a/internal/handler/helm.go b/internal/handler/helm.go index 414e9a45..9365fb38 100644 --- a/internal/handler/helm.go +++ b/internal/handler/helm.go @@ -5,22 +5,20 @@ import ( "crypto/sha256" "encoding/hex" "errors" - "fmt" "net/http" - "net/url" - "path" "strings" "sync" "time" "gopkg.in/yaml.v3" + "github.com/git-pkgs/proxy/internal/metadata/helm" "github.com/git-pkgs/proxy/internal/retention" ) const ( helmMetadataEcosystem = "helm" - helmIndexFilename = "index.yaml" + helmIndexFilename = helm.IndexFilename helmIndexAccept = "application/x-yaml, text/yaml;q=0.9, */*;q=0.1" sha256HexLength = 64 ) @@ -237,47 +235,20 @@ func (h *HelmHandler) serveIndexError(w http.ResponseWriter, err error) { // rewriteIndex points the index's chart URLs at the proxy and drops releases // in cooldown. It also returns the releases it kept, by chart name and -// digest, which together with the index fix its output. +// digest, which together with the index fix its output; see helm.Rewrite. func (h *HelmHandler) rewriteIndex(repository, upstreamURL string, body []byte) ([]byte, []string, error) { - document, entries, err := parseHelmIndex(body) - if err != nil { - return nil, nil, err - } - - var kept []string - for i := 0; i < len(entries.Content); i += 2 { - chartName := entries.Content[i].Value - releases := entries.Content[i+1] - if releases.Kind != yaml.SequenceNode { - return nil, nil, fmt.Errorf("chart %q releases must be a sequence", chartName) - } - - filtered := make([]*yaml.Node, 0, len(releases.Content)) - for _, release := range releases.Content { - chart, err := h.parseChartRelease(chartName, upstreamURL, release) - if err != nil { - h.proxy.Logger.Warn("omitting malformed Helm chart release", - "repository", repository, "chart", chartName, "error", err) - continue - } - if h.chartOnCooldown(chartName, chart.created) { - continue - } - for _, download := range chart.downloads { - if download.oci { - download.node.Value = h.ociChartProxyURL(download.url) - } else { - download.node.Value = h.chartProxyURL(repository, chart.digest, download.filename) - } - } - filtered = append(filtered, release) - kept = append(kept, chartName+"@"+chart.digest) - } - releases.Content = filtered - } - - out, err := yaml.Marshal(document) - return out, kept, err + return helm.Rewrite(body, helm.Options{ + ProxyURL: h.proxyURL, + Repository: repository, + UpstreamURL: upstreamURL, + OCIRegistries: h.ociRegistries, + Cooldown: h.proxy.cooldown(), + EvaluatedAt: time.Now(), + OnMalformed: func(chart string, err error) { + h.proxy.Logger.Warn("omitting malformed Helm chart release", + "repository", repository, "chart", chart, "error", err) + }, + }) } // findChartDownload returns the upstream URL of a chart in the index. Parsing @@ -292,42 +263,25 @@ func (h *HelmHandler) findChartDownload(repository, upstreamURL string, index me } func (h *HelmHandler) findChartURL(charts *helmChartLookup, digest, filename string) (string, error) { - for _, chart := range charts.byDigest[digest] { - if h.chartOnCooldown(chart.name, chart.created) { + for _, chart := range charts.ByDigest[digest] { + if h.chartOnCooldown(chart.Name, chart.Created) { continue } - for _, download := range chart.downloads { - if download.filename == filename { - return download.url, nil + for _, download := range chart.Downloads { + if download.Filename == filename { + return download.URL, nil } } } return "", errHelmChartNotFound } -// helmChartLookup holds the HTTP chart downloads an index lists, by chart -// digest, in index order, and each release by chart name and version. -type helmChartLookup struct { - indexDigest string - byDigest map[string][]helmChartEntry - byRelease map[helmRelease]helmReleaseDownload -} - -type helmChartEntry struct { - name string - created time.Time - downloads []helmChartDownload -} - -type helmRelease struct{ chart, version string } - -// helmReleaseDownload is what helm downloads for a release: the first URL -// the index lists for it, checked against its digest. -type helmReleaseDownload struct { - digest string - created time.Time - first helmChartDownload -} +// helmChartLookup holds the HTTP chart downloads an index lists (see +// helm.Lookup), and helmRelease names a release in it. +type ( + helmChartLookup = helm.Lookup + helmRelease = helm.Release +) // chartLookup returns the charts the index lists, parsing it only when the // last lookup built for the repository came from other bytes. An index @@ -338,7 +292,7 @@ func (h *HelmHandler) chartLookup(repository, upstreamURL string, index metadata h.lookupMu.Lock() cached := h.lookups[key] h.lookupMu.Unlock() - if cached != nil && cached.indexDigest == index.digest { + if cached != nil && cached.IndexDigest == index.digest { return cached, nil } } @@ -348,7 +302,7 @@ func (h *HelmHandler) chartLookup(repository, upstreamURL string, index metadata return nil, err } if index.digest != "" { - lookup.indexDigest = index.digest + lookup.IndexDigest = index.digest h.lookupMu.Lock() if h.lookups == nil { h.lookups = make(map[string]*helmChartLookup) @@ -360,47 +314,7 @@ func (h *HelmHandler) chartLookup(repository, upstreamURL string, index metadata } func (h *HelmHandler) buildChartLookup(upstreamURL string, body []byte) (*helmChartLookup, error) { - _, entries, err := parseHelmIndex(body) - if err != nil { - return nil, err - } - - lookup := &helmChartLookup{byDigest: make(map[string][]helmChartEntry), byRelease: make(map[helmRelease]helmReleaseDownload)} - for i := 0; i < len(entries.Content); i += 2 { - chartName := entries.Content[i].Value - releases := entries.Content[i+1] - if releases.Kind != yaml.SequenceNode { - return nil, fmt.Errorf("chart %q releases must be a sequence", chartName) - } - for _, release := range releases.Content { - chart, err := h.parseChartRelease(chartName, upstreamURL, release) - if err != nil { - continue - } - entry := helmChartEntry{name: chartName, created: chart.created} - if version := helmMappingValue(release, "version"); version != nil && version.Value != "" { - // helm takes the first release listed for a version. - key := helmRelease{chartName, version.Value} - if _, listed := lookup.byRelease[key]; !listed { - first := chart.downloads[0] - lookup.byRelease[key] = helmReleaseDownload{ - digest: chart.digest, - created: chart.created, - first: helmChartDownload{url: first.url, filename: first.filename, oci: first.oci}, - } - } - } - for _, download := range chart.downloads { - if !download.oci { - // Drop the YAML node, so the lookup doesn't keep the - // parsed index alive. - entry.downloads = append(entry.downloads, helmChartDownload{url: download.url, filename: download.filename}) - } - } - lookup.byDigest[chart.digest] = append(lookup.byDigest[chart.digest], entry) - } - } - return lookup, nil + return helm.BuildLookup(upstreamURL, body) } // downloadChartLookup returns the charts the index lists, for a download @@ -419,31 +333,18 @@ func (h *HelmHandler) downloadChartLookup(r *http.Request, repository, upstreamU } return h.chartLookup(repository, upstreamURL, res) }, func(charts *helmChartLookup) bool { - return charts.lists(digest, filename) + return charts.Lists(digest, filename) }) } -// lists reports whether the index lists an HTTP download of filename with -// the digest. -func (c *helmChartLookup) lists(digest, filename string) bool { - for _, chart := range c.byDigest[digest] { - for _, download := range chart.downloads { - if download.filename == filename { - return true - } - } - } - return false -} - func (h *HelmHandler) withholdChart(w http.ResponseWriter, charts *helmChartLookup, digest, filename string) bool { withheld := false - for _, chart := range charts.byDigest[digest] { - for _, download := range chart.downloads { - if download.filename != filename { + for _, chart := range charts.ByDigest[digest] { + for _, download := range chart.Downloads { + if download.Filename != filename { continue } - if !h.chartOnCooldown(chart.name, chart.created) { + if !h.chartOnCooldown(chart.Name, chart.Created) { return false } withheld = true @@ -460,137 +361,24 @@ func (h *HelmHandler) chartOnCooldown(chartName string, created time.Time) bool !h.proxy.cooldown().IsAllowed(helmMetadataEcosystem, canonicalPackagePURL(helmMetadataEcosystem, chartName), created) } -type helmChartDownload struct { - node *yaml.Node - url string - filename string - oci bool -} - -type helmChartRelease struct { - created time.Time - digest string - downloads []helmChartDownload -} - var errHelmChartNotFound = errors.New("chart not found in Helm index") -func (h *HelmHandler) parseChartRelease(chartName, upstreamURL string, release *yaml.Node) (helmChartRelease, error) { - digestNode := helmMappingValue(release, "digest") - urlsNode := helmMappingValue(release, "urls") - if digestNode == nil || urlsNode == nil || urlsNode.Kind != yaml.SequenceNode || len(urlsNode.Content) == 0 { - return helmChartRelease{}, fmt.Errorf("chart %q has no digest or URLs", chartName) - } - digest, ok := normalizeHelmDigest(digestNode.Value) - if !ok { - return helmChartRelease{}, fmt.Errorf("chart %q has invalid digest", chartName) - } - - baseURL, err := url.Parse(upstreamURL + "/" + helmIndexFilename) - if err != nil { - return helmChartRelease{}, fmt.Errorf("parsing Helm repository URL: %w", err) - } - - chart := helmChartRelease{digest: digest} - if createdNode := helmMappingValue(release, "created"); createdNode != nil && createdNode.Value != "" { - chart.created, err = time.Parse(time.RFC3339Nano, createdNode.Value) - if err != nil { - return helmChartRelease{}, fmt.Errorf("chart %q has invalid creation time: %w", chartName, err) - } - } - - for _, urlNode := range urlsNode.Content { - download, err := parseHelmChartDownload(chartName, baseURL, urlNode) - if err != nil { - return helmChartRelease{}, err - } - chart.downloads = append(chart.downloads, download) - } - return chart, nil -} - -func parseHelmChartDownload(chartName string, baseURL *url.URL, node *yaml.Node) (helmChartDownload, error) { - if node.Kind != yaml.ScalarNode { - return helmChartDownload{}, fmt.Errorf("chart %q has invalid URL", chartName) - } - reference, err := url.Parse(node.Value) - if err != nil { - return helmChartDownload{}, fmt.Errorf("parsing chart %q URL: %w", chartName, err) - } - if reference.Scheme == "oci" { - if reference.Hostname() == "" || strings.Trim(reference.Path, "/") == "" || - reference.User != nil || reference.RawQuery != "" || reference.ForceQuery || reference.Fragment != "" || - containsPathTraversal(reference.Path) { - return helmChartDownload{}, fmt.Errorf("chart %q has invalid OCI reference", chartName) - } - return helmChartDownload{node: node, url: node.Value, oci: true}, nil - } - downloadURL := baseURL.ResolveReference(reference) - if (downloadURL.Scheme != "http" && downloadURL.Scheme != "https") || downloadURL.Host == "" { - return helmChartDownload{}, fmt.Errorf("chart %q URL must be HTTP(S) or OCI", chartName) - } - filename := path.Base(downloadURL.Path) - if filename == "." || filename == "/" || filename == "" || !strings.HasSuffix(filename, ".tgz") { - return helmChartDownload{}, fmt.Errorf("chart %q URL must point to a .tgz file", chartName) - } - return helmChartDownload{node: node, url: downloadURL.String(), filename: filename}, nil -} - func (h *HelmHandler) chartProxyURL(repository, digest, filename string) string { - return fmt.Sprintf("%s/helm/%s/charts/%s/%s", h.proxyURL, - url.PathEscape(repository), digest, url.PathEscape(filename)) + return helm.ChartProxyURL(h.proxyURL, repository, digest, filename) } func parseHelmIndex(body []byte) (*yaml.Node, *yaml.Node, error) { - var document yaml.Node - if err := yaml.Unmarshal(body, &document); err != nil { - return nil, nil, fmt.Errorf("parsing Helm index: %w", err) - } - entries, err := helmIndexEntries(&document) - if err != nil { - return nil, nil, err - } - return &document, entries, nil + return helm.ParseIndex(body) } func helmIndexEntries(document *yaml.Node) (*yaml.Node, error) { - if document == nil { - return nil, errors.New("helm index is empty") - } - if len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { - return nil, errors.New("helm index must be a mapping") - } - entries := helmMappingValue(document.Content[0], "entries") - if entries == nil || entries.Kind != yaml.MappingNode { - return nil, errors.New("helm index has no entries mapping") - } - if len(entries.Content)%2 != 0 { - return nil, errors.New("helm index entries mapping has an incomplete key-value pair") - } - return entries, nil + return helm.IndexEntries(document) } func helmMappingValue(mapping *yaml.Node, key string) *yaml.Node { - if mapping == nil || mapping.Kind != yaml.MappingNode { - return nil - } - for i := 0; i+1 < len(mapping.Content); i += 2 { - if mapping.Content[i].Value == key { - return mapping.Content[i+1] - } - } - return nil + return helm.MappingValue(mapping, key) } func normalizeHelmDigest(value string) (string, bool) { - digest := strings.TrimPrefix(strings.ToLower(value), "sha256:") - if len(digest) != sha256HexLength { - return "", false - } - for _, char := range digest { - if (char < '0' || char > '9') && (char < 'a' || char > 'f') { - return "", false - } - } - return digest, true + return helm.NormalizeDigest(value) } diff --git a/internal/handler/helm_mirror.go b/internal/handler/helm_mirror.go index fe2199dd..e7506b49 100644 --- a/internal/handler/helm_mirror.go +++ b/internal/handler/helm_mirror.go @@ -27,18 +27,18 @@ func (h *HelmHandler) MirrorChart(ctx context.Context, repository, chart, versio return nil, err } - release, ok := charts.byRelease[helmRelease{chart, version}] + release, ok := charts.ByRelease[helmRelease{Chart: chart, Version: version}] switch { case !ok: return nil, fmt.Errorf("%w: %s %s is not in the %s index", ErrUpstreamNotFound, chart, version, repository) - case release.first.oci: + case release.First.OCI: return nil, fmt.Errorf("%s %s is published as %s, which helm pulls through the container registry routes; mirror it as an image: %s", - chart, version, release.first.url, ociChartPURL(release.first.url, version)) - case h.chartOnCooldown(chart, release.created): + chart, version, release.First.URL, ociChartPURL(release.First.URL, version)) + case h.chartOnCooldown(chart, release.Created): return nil, fmt.Errorf("%s %s is in cooldown, so the index doesn't list it", chart, version) } - return h.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, helmMetadataEcosystem, repository, release.digest, - release.first.filename, release.first.url, "sha256:"+release.digest) + return h.proxy.GetOrFetchArtifactFromURLWithDigest(ctx, helmMetadataEcosystem, repository, release.Digest, + release.First.Filename, release.First.URL, "sha256:"+release.Digest) } func (h *HelmHandler) unknownRepositoryError(repository string) error { diff --git a/internal/handler/helm_oci.go b/internal/handler/helm_oci.go index 00392e84..4ca712c6 100644 --- a/internal/handler/helm_oci.go +++ b/internal/handler/helm_oci.go @@ -4,12 +4,13 @@ import ( "net/url" "slices" "strings" + + "github.com/git-pkgs/proxy/internal/metadata/helm" ) -type helmOCIRegistry struct { - host string - prefix string -} +// helmOCIRegistry is a registry whose chart references the index rewrite +// points at the /v2 routes. +type helmOCIRegistry = helm.OCIRegistry // NewHelmHandlerWithOCIRegistries also rewrites OCI references for configured // registries through the existing /v2 routes. Unmatched references stay intact. @@ -36,29 +37,9 @@ func (h *HelmHandler) addOCIRegistry(rawURL, prefix string) { strings.Trim(u.Path, "/") != "" || u.RawQuery != "" || u.Fragment != "" || u.User != nil { return } - h.ociRegistries = append(h.ociRegistries, helmOCIRegistry{host: u.Host, prefix: prefix}) + h.ociRegistries = append(h.ociRegistries, helmOCIRegistry{Host: u.Host, Prefix: prefix}) } func (h *HelmHandler) ociChartProxyURL(reference string) string { - u, err := url.Parse(reference) - if err != nil { - return reference - } - proxy, err := url.Parse(h.proxyURL) - // OCI clients place /v2 before the repository path, so a path-prefixed - // public HTTP base URL cannot be represented by simply prepending its path. - if err != nil || proxy.Host == "" || strings.Trim(proxy.Path, "/") != "" { - return reference - } - for _, registry := range h.ociRegistries { - if !strings.EqualFold(u.Host, registry.host) { - continue - } - if registry.prefix == "" && strings.HasPrefix(u.Path, "/upstream/") { - // This prefix is reserved by the named-registry router. - return reference - } - return "oci://" + proxy.Host + registry.prefix + u.EscapedPath() - } - return reference + return helm.OCIProxyReference(h.proxyURL, h.ociRegistries, reference) } diff --git a/internal/metadata/helm/imports_test.go b/internal/metadata/helm/imports_test.go new file mode 100644 index 00000000..d7f00c9f --- /dev/null +++ b/internal/metadata/helm/imports_test.go @@ -0,0 +1,44 @@ +package helm + +import ( + "os/exec" + "slices" + "strings" + "testing" +) + +// TestPortableImports keeps the package free of the proxy's infrastructure: +// no handler, database, storage, metrics, HTTP or logging, so it builds for +// targets such as WASI where those are not available. +func TestPortableImports(t *testing.T) { + goTool, err := exec.LookPath("go") + if err != nil { + t.Skip("go tool not found") + } + out, err := exec.Command(goTool, "list", "-deps", "-f", "{{.Standard}} {{.ImportPath}}", ".").Output() + if err != nil { + t.Fatalf("go list: %v", err) + } + allowed := []string{ + "github.com/git-pkgs/cooldown", + "github.com/git-pkgs/proxy/internal/metadata/helm", + "github.com/git-pkgs/proxy/internal/packageurl", + "github.com/git-pkgs/purl", + "github.com/git-pkgs/vers", + "github.com/package-url/packageurl-go", + "gopkg.in/yaml.v3", + } + forbiddenStd := []string{"database/sql", "log/slog", "net", "net/http"} + for line := range strings.Lines(string(out)) { + standard, path, _ := strings.Cut(strings.TrimSpace(line), " ") + if standard == "true" { + if slices.Contains(forbiddenStd, path) { + t.Errorf("imports %s", path) + } + continue + } + if !slices.Contains(allowed, path) { + t.Errorf("imports %s, which is not on the portable list", path) + } + } +} diff --git a/internal/metadata/helm/metadata.go b/internal/metadata/helm/metadata.go new file mode 100644 index 00000000..5decb335 --- /dev/null +++ b/internal/metadata/helm/metadata.go @@ -0,0 +1,400 @@ +// Package helm transforms Helm chart repository indexes without storage or +// network access. +package helm + +import ( + "errors" + "fmt" + "net/url" + "path" + "strings" + "time" + + "gopkg.in/yaml.v3" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/packageurl" +) + +const ( + ecosystem = "helm" + // IndexFilename is the name of a repository's index. + IndexFilename = "index.yaml" + sha256HexLength = 64 +) + +// CooldownPolicy evaluates version age at the caller's supplied time. +type CooldownPolicy interface { + Enabled() bool + Evaluate(ecosystem, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision +} + +// OCIRegistry is a registry whose chart references the proxy serves through +// its /v2 routes, under Prefix ("" for the default registry, else +// /upstream/{name}). +type OCIRegistry struct { + Host string + Prefix string +} + +// Options supplies the public URL, repository, policy and OCI registries +// for a rewrite. EvaluatedAt is used as given; the transformation never +// reads the clock. +type Options struct { + ProxyURL string + // Repository is the configured repository name the index is served + // under, and UpstreamURL the repository's upstream URL, which relative + // chart URLs resolve against. + Repository string + UpstreamURL string + // OCIRegistries are the registries whose OCI chart references point at + // the proxy; other references stay as they are. + OCIRegistries []OCIRegistry + Cooldown CooldownPolicy + EvaluatedAt time.Time + // OnMalformed is called synchronously for each release left out because + // it can't be read. + OnMalformed func(chart string, err error) +} + +// Rewrite points the index's chart URLs at the proxy and drops releases in +// cooldown or that can't be read. It also returns the releases it kept, as +// chart@digest, which together with the index fix its output. +func Rewrite(body []byte, o Options) ([]byte, []string, error) { + document, entries, err := ParseIndex(body) + if err != nil { + return nil, nil, err + } + + var kept []string + for i := 0; i < len(entries.Content); i += 2 { + chartName := entries.Content[i].Value + releases := entries.Content[i+1] + if releases.Kind != yaml.SequenceNode { + return nil, nil, fmt.Errorf("chart %q releases must be a sequence", chartName) + } + + filtered := make([]*yaml.Node, 0, len(releases.Content)) + for _, release := range releases.Content { + chart, err := parseRelease(chartName, o.UpstreamURL, release) + if err != nil { + if o.OnMalformed != nil { + o.OnMalformed(chartName, err) + } + continue + } + if inCooldown(o.Cooldown, chartName, chart.created, o.EvaluatedAt) { + continue + } + for _, download := range chart.downloads { + if download.OCI { + download.node.Value = OCIProxyReference(o.ProxyURL, o.OCIRegistries, download.URL) + } else { + download.node.Value = ChartProxyURL(o.ProxyURL, o.Repository, chart.digest, download.Filename) + } + } + filtered = append(filtered, release) + kept = append(kept, chartName+"@"+chart.digest) + } + releases.Content = filtered + } + + out, err := yaml.Marshal(document) + return out, kept, err +} + +// inCooldown reports whether policy holds back a chart release created at +// created, evaluated at evaluatedAt. A release without a creation time is +// let through. +func inCooldown(policy CooldownPolicy, chartName string, created, evaluatedAt time.Time) bool { + if created.IsZero() || policy == nil || !policy.Enabled() { + return false + } + return !policy.Evaluate(ecosystem, packageurl.MakeString(ecosystem, chartName, ""), created, evaluatedAt).Allowed +} + +// ChartProxyURL is where the proxy serves an HTTP chart download of the +// repository. +func ChartProxyURL(proxyURL, repository, digest, filename string) string { + return fmt.Sprintf("%s/helm/%s/charts/%s/%s", proxyURL, + url.PathEscape(repository), digest, url.PathEscape(filename)) +} + +// OCIProxyReference returns an OCI chart reference pointing at the proxy's +// /v2 routes when its registry is one of registries, and reference as it is +// otherwise or when proxyURL has a path, which OCI clients can't use. +func OCIProxyReference(proxyURL string, registries []OCIRegistry, reference string) string { + u, err := url.Parse(reference) + if err != nil { + return reference + } + proxy, err := url.Parse(proxyURL) + // OCI clients place /v2 before the repository path, so a path-prefixed + // public HTTP base URL cannot be represented by simply prepending its path. + if err != nil || proxy.Host == "" || strings.Trim(proxy.Path, "/") != "" { + return reference + } + for _, registry := range registries { + if !strings.EqualFold(u.Host, registry.Host) { + continue + } + if registry.Prefix == "" && strings.HasPrefix(u.Path, "/upstream/") { + // This prefix is reserved by the named-registry router. + return reference + } + return "oci://" + proxy.Host + registry.Prefix + u.EscapedPath() + } + return reference +} + +// Lookup holds the HTTP chart downloads an index lists, by chart digest, in +// index order, and each release by chart name and version. IndexDigest is +// left for the caller to record which index it was built from. +type Lookup struct { + IndexDigest string + ByDigest map[string][]Entry + ByRelease map[Release]ReleaseDownload +} + +// Entry is one release listed under a digest. +type Entry struct { + Name string + Created time.Time + Downloads []Download +} + +// Release names a chart release. +type Release struct{ Chart, Version string } + +// ReleaseDownload is what helm downloads for a release: the first URL the +// index lists for it, checked against its digest. +type ReleaseDownload struct { + Digest string + Created time.Time + First Download +} + +// Download is one URL a release lists: an HTTP download with its filename, +// or an OCI reference. +type Download struct { + URL string + Filename string + OCI bool +} + +// BuildLookup reads the charts an index lists, resolving relative URLs +// against upstreamURL. Releases that can't be read are left out. +func BuildLookup(upstreamURL string, body []byte) (*Lookup, error) { + _, entries, err := ParseIndex(body) + if err != nil { + return nil, err + } + + lookup := &Lookup{ByDigest: make(map[string][]Entry), ByRelease: make(map[Release]ReleaseDownload)} + for i := 0; i < len(entries.Content); i += 2 { + chartName := entries.Content[i].Value + releases := entries.Content[i+1] + if releases.Kind != yaml.SequenceNode { + return nil, fmt.Errorf("chart %q releases must be a sequence", chartName) + } + for _, release := range releases.Content { + chart, err := parseRelease(chartName, upstreamURL, release) + if err != nil { + continue + } + lookup.add(chartName, release, chart) + } + } + return lookup, nil +} + +func (l *Lookup) add(chartName string, release *yaml.Node, chart chartRelease) { + entry := Entry{Name: chartName, Created: chart.created} + if version := MappingValue(release, "version"); version != nil && version.Value != "" { + // helm takes the first release listed for a version. + key := Release{chartName, version.Value} + if _, listed := l.ByRelease[key]; !listed { + l.ByRelease[key] = ReleaseDownload{ + Digest: chart.digest, + Created: chart.created, + First: chart.downloads[0].Download, + } + } + } + for _, download := range chart.downloads { + if !download.OCI { + // Copy without the YAML node, so the lookup doesn't keep the + // parsed index alive. + entry.Downloads = append(entry.Downloads, download.Download) + } + } + l.ByDigest[chart.digest] = append(l.ByDigest[chart.digest], entry) +} + +// Lists reports whether the index lists an HTTP download of filename with +// the digest. +func (l *Lookup) Lists(digest, filename string) bool { + for _, chart := range l.ByDigest[digest] { + for _, download := range chart.Downloads { + if download.Filename == filename { + return true + } + } + } + return false +} + +// download is a Download with the index node its URL came from. +type download struct { + Download + node *yaml.Node +} + +type chartRelease struct { + created time.Time + digest string + downloads []download +} + +func parseRelease(chartName, upstreamURL string, release *yaml.Node) (chartRelease, error) { + digestNode := MappingValue(release, "digest") + urlsNode := MappingValue(release, "urls") + if digestNode == nil || urlsNode == nil || urlsNode.Kind != yaml.SequenceNode || len(urlsNode.Content) == 0 { + return chartRelease{}, fmt.Errorf("chart %q has no digest or URLs", chartName) + } + digest, ok := NormalizeDigest(digestNode.Value) + if !ok { + return chartRelease{}, fmt.Errorf("chart %q has invalid digest", chartName) + } + + baseURL, err := url.Parse(upstreamURL + "/" + IndexFilename) + if err != nil { + return chartRelease{}, fmt.Errorf("parsing Helm repository URL: %w", err) + } + + chart := chartRelease{digest: digest} + if createdNode := MappingValue(release, "created"); createdNode != nil && createdNode.Value != "" { + chart.created, err = time.Parse(time.RFC3339Nano, createdNode.Value) + if err != nil { + return chartRelease{}, fmt.Errorf("chart %q has invalid creation time: %w", chartName, err) + } + } + + for _, urlNode := range urlsNode.Content { + d, err := parseDownload(chartName, baseURL, urlNode) + if err != nil { + return chartRelease{}, err + } + chart.downloads = append(chart.downloads, d) + } + return chart, nil +} + +func parseDownload(chartName string, baseURL *url.URL, node *yaml.Node) (download, error) { + if node.Kind != yaml.ScalarNode { + return download{}, fmt.Errorf("chart %q has invalid URL", chartName) + } + reference, err := url.Parse(node.Value) + if err != nil { + return download{}, fmt.Errorf("parsing chart %q URL: %w", chartName, err) + } + if reference.Scheme == "oci" { + if reference.Hostname() == "" || strings.Trim(reference.Path, "/") == "" || + reference.User != nil || reference.RawQuery != "" || reference.ForceQuery || reference.Fragment != "" || + containsPathTraversal(reference.Path) { + return download{}, fmt.Errorf("chart %q has invalid OCI reference", chartName) + } + return download{Download: Download{URL: node.Value, OCI: true}, node: node}, nil + } + downloadURL := baseURL.ResolveReference(reference) + if (downloadURL.Scheme != "http" && downloadURL.Scheme != "https") || downloadURL.Host == "" { + return download{}, fmt.Errorf("chart %q URL must be HTTP(S) or OCI", chartName) + } + filename := path.Base(downloadURL.Path) + if filename == "." || filename == "/" || filename == "" || !strings.HasSuffix(filename, ".tgz") { + return download{}, fmt.Errorf("chart %q URL must point to a .tgz file", chartName) + } + return download{Download: Download{URL: downloadURL.String(), Filename: filename}, node: node}, nil +} + +// containsPathTraversal reports whether path, or its unescaped form, has a +// ".." segment, as the handler's check of the same name does. +func containsPathTraversal(p string) bool { + if hasDotDotSegment(p) { + return true + } + if decoded, err := url.PathUnescape(p); err == nil && decoded != p { + return hasDotDotSegment(decoded) + } + return false +} + +func hasDotDotSegment(p string) bool { + for segment := range strings.SplitSeq(strings.ReplaceAll(p, "\\", "/"), "/") { + if segment == ".." { + return true + } + } + return false +} + +// ParseIndex parses an index, returning the document and its entries +// mapping. +func ParseIndex(body []byte) (*yaml.Node, *yaml.Node, error) { + var document yaml.Node + if err := yaml.Unmarshal(body, &document); err != nil { + return nil, nil, fmt.Errorf("parsing Helm index: %w", err) + } + entries, err := IndexEntries(&document) + if err != nil { + return nil, nil, err + } + return &document, entries, nil +} + +// IndexEntries returns a parsed index's entries mapping. +func IndexEntries(document *yaml.Node) (*yaml.Node, error) { + if document == nil { + return nil, errors.New("helm index is empty") + } + if len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { + return nil, errors.New("helm index must be a mapping") + } + entries := MappingValue(document.Content[0], "entries") + if entries == nil || entries.Kind != yaml.MappingNode { + return nil, errors.New("helm index has no entries mapping") + } + if len(entries.Content)%2 != 0 { + return nil, errors.New("helm index entries mapping has an incomplete key-value pair") + } + return entries, nil +} + +// MappingValue returns the value under key in a YAML mapping, nil when +// mapping isn't one or has no such key. +func MappingValue(mapping *yaml.Node, key string) *yaml.Node { + if mapping == nil || mapping.Kind != yaml.MappingNode { + return nil + } + for i := 0; i+1 < len(mapping.Content); i += 2 { + if mapping.Content[i].Value == key { + return mapping.Content[i+1] + } + } + return nil +} + +// NormalizeDigest returns a chart digest as lowercase hex without its +// sha256: prefix, and whether it is one. +func NormalizeDigest(value string) (string, bool) { + digest := strings.TrimPrefix(strings.ToLower(value), "sha256:") + if len(digest) != sha256HexLength { + return "", false + } + for _, char := range digest { + if (char < '0' || char > '9') && (char < 'a' || char > 'f') { + return "", false + } + } + return digest, true +} diff --git a/internal/metadata/helm/metadata_test.go b/internal/metadata/helm/metadata_test.go new file mode 100644 index 00000000..c63c29ac --- /dev/null +++ b/internal/metadata/helm/metadata_test.go @@ -0,0 +1,282 @@ +package helm + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +// dayPolicy holds back releases younger than a day at the evaluation time. +type dayPolicy struct { + enabled bool + purls []string +} + +func (p *dayPolicy) Enabled() bool { return p.enabled } + +func (p *dayPolicy) Evaluate(eco, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision { + p.purls = append(p.purls, eco+" "+packagePURL) + return cooldown.Decision{Allowed: evaluatedAt.Sub(publishedAt) >= 24*time.Hour} +} + +var ( + digestA = strings.Repeat("a", 64) + digestB = strings.Repeat("b", 64) + digestC = strings.Repeat("c", 64) + now = time.Date(2026, 11, 23, 12, 0, 0, 0, time.UTC) +) + +const testIndex = `apiVersion: v1 +entries: + demo: + - version: 2.0.0 + created: "2026-11-23T06:00:00Z" + digest: sha256:` + "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB" + ` + urls: [demo-2.0.0.tgz] + - version: 1.0.0 + created: "2026-11-01T00:00:00Z" + digest: ` + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ` + urls: [charts/demo-1.0.0.tgz, "https://mirror.example/demo-1.0.0.tgz"] + - version: 0.9.0 + digest: ` + "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" + ` + urls: ["oci://ghcr.io/acme/demo:0.9.0"] + - version: 0.1.0 + digest: nope + urls: [demo-0.1.0.tgz] +` + +func rewrite(t *testing.T, o Options) (string, []string) { + t.Helper() + if o.ProxyURL == "" { + o.ProxyURL = "https://proxy.example" + } + if o.Repository == "" { + o.Repository = "my repo" + } + if o.UpstreamURL == "" { + o.UpstreamURL = "https://charts.example/sub" + } + out, kept, err := Rewrite([]byte(testIndex), o) + if err != nil { + t.Fatalf("Rewrite: %v", err) + } + return string(out), kept +} + +func TestRewritePointsURLsAtTheProxy(t *testing.T) { + var malformed []string + out, kept := rewrite(t, Options{ + OCIRegistries: []OCIRegistry{{Host: "ghcr.io", Prefix: "/upstream/gh"}}, + OnMalformed: func(chart string, err error) { malformed = append(malformed, chart+": "+err.Error()) }, + }) + for _, want := range []string{ + "https://proxy.example/helm/my%20repo/charts/" + digestB + "/demo-2.0.0.tgz", + "https://proxy.example/helm/my%20repo/charts/" + digestA + "/demo-1.0.0.tgz", + "oci://proxy.example/upstream/gh/acme/demo:0.9.0", + } { + if !strings.Contains(out, want) { + t.Errorf("output lacks %s:\n%s", want, out) + } + } + if strings.Contains(out, "charts.example") || strings.Contains(out, "mirror.example") || strings.Contains(out, "0.1.0") { + t.Errorf("output keeps an upstream URL or the malformed release:\n%s", out) + } + want := []string{"demo@" + digestB, "demo@" + digestA, "demo@" + digestC} + if !slices.Equal(kept, want) { + t.Errorf("kept = %v, want %v", kept, want) + } + if len(malformed) != 1 || !strings.Contains(malformed[0], "demo: chart \"demo\" has invalid digest") { + t.Errorf("malformed = %v, want the release with the bad digest", malformed) + } +} + +func TestRewriteCooldownAtEvaluatedAt(t *testing.T) { + policy := &dayPolicy{enabled: true} + out, kept := rewrite(t, Options{Cooldown: policy, EvaluatedAt: now}) + if strings.Contains(out, "2.0.0") { + t.Errorf("release created 6h before EvaluatedAt is listed:\n%s", out) + } + want := []string{"demo@" + digestA, "demo@" + digestC} + if !slices.Equal(kept, want) { + t.Errorf("kept = %v, want %v", kept, want) + } + // Releases without a creation time aren't evaluated. + if len(policy.purls) != 2 || policy.purls[0] != "helm pkg:helm/demo" { + t.Errorf("evaluated %v, want pkg:helm/demo twice", policy.purls) + } + + // A day later the release is out of cooldown. + _, kept = rewrite(t, Options{Cooldown: policy, EvaluatedAt: now.Add(24 * time.Hour)}) + if len(kept) != 3 { + t.Errorf("kept = %v a day later, want all three", kept) + } +} + +func TestRewriteWithoutCooldown(t *testing.T) { + for name, policy := range map[string]CooldownPolicy{"nil": nil, "disabled": &dayPolicy{}} { + _, kept := rewrite(t, Options{Cooldown: policy, EvaluatedAt: now}) + if len(kept) != 3 { + t.Errorf("%s policy: kept = %v, want all three", name, kept) + } + } +} + +func TestRewriteRefusesBadIndexes(t *testing.T) { + for name, body := range map[string]string{ + "not yaml": "entries: [", + "no entries": "apiVersion: v1\n", + "releases list": "entries:\n demo: {version: 1}\n", + } { + if _, _, err := Rewrite([]byte(body), Options{}); err == nil { + t.Errorf("%s: Rewrite accepted it", name) + } + if _, err := BuildLookup("https://charts.example", []byte(body)); err == nil { + t.Errorf("%s: BuildLookup accepted it", name) + } + } +} + +func TestBuildLookup(t *testing.T) { + lookup, err := BuildLookup("https://charts.example/sub", []byte(testIndex)) + if err != nil { + t.Fatal(err) + } + a := lookup.ByDigest[digestA] + if len(a) != 1 || a[0].Name != "demo" || !a[0].Created.Equal(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)) { + t.Fatalf("ByDigest[a] = %+v", a) + } + wantDownloads := []Download{ + {URL: "https://charts.example/sub/charts/demo-1.0.0.tgz", Filename: "demo-1.0.0.tgz"}, + {URL: "https://mirror.example/demo-1.0.0.tgz", Filename: "demo-1.0.0.tgz"}, + } + if !slices.Equal(a[0].Downloads, wantDownloads) { + t.Errorf("downloads = %+v, want %+v", a[0].Downloads, wantDownloads) + } + // OCI references aren't HTTP downloads, but the release is listed. + if c := lookup.ByDigest[digestC]; len(c) != 1 || len(c[0].Downloads) != 0 { + t.Errorf("ByDigest[c] = %+v, want one entry without downloads", c) + } + oci := lookup.ByRelease[Release{"demo", "0.9.0"}] + if !oci.First.OCI || oci.First.URL != "oci://ghcr.io/acme/demo:0.9.0" || oci.Digest != digestC { + t.Errorf("ByRelease 0.9.0 = %+v", oci) + } + one := lookup.ByRelease[Release{"demo", "1.0.0"}] + if one.First != wantDownloads[0] || one.Digest != digestA || !one.Created.Equal(a[0].Created) { + t.Errorf("ByRelease 1.0.0 = %+v", one) + } + if _, ok := lookup.ByRelease[Release{"demo", "0.1.0"}]; ok { + t.Error("the malformed release is listed") + } + if !lookup.Lists(digestA, "demo-1.0.0.tgz") || lookup.Lists(digestA, "demo-2.0.0.tgz") || lookup.Lists(digestC, "") { + t.Error("Lists doesn't match the HTTP downloads") + } +} + +func TestBuildLookupKeepsTheFirstReleaseOfAVersion(t *testing.T) { + index := "entries:\n demo:\n" + + " - {version: 1.0.0, digest: " + digestA + ", urls: [first.tgz]}\n" + + " - {version: 1.0.0, digest: " + digestB + ", urls: [second.tgz]}\n" + + " - {digest: " + digestC + ", urls: [unversioned.tgz]}\n" + + " - {version: \"\", digest: " + strings.Repeat("d", 64) + ", urls: [blank.tgz]}\n" + lookup, err := BuildLookup("https://charts.example", []byte(index)) + if err != nil { + t.Fatal(err) + } + if got := lookup.ByRelease[Release{"demo", "1.0.0"}]; got.Digest != digestA || got.First.Filename != "first.tgz" { + t.Errorf("ByRelease = %+v, want the first listed", got) + } + if len(lookup.ByRelease) != 1 || len(lookup.ByDigest[digestC]) != 1 || len(lookup.ByDigest[strings.Repeat("d", 64)]) != 1 { + t.Errorf("lookup = %+v", lookup) + } +} + +func TestParseReleaseRefusesBadDownloads(t *testing.T) { + for name, urls := range map[string]string{ + "no urls": "[]", + "not a tgz": "[demo.zip]", + "ftp": "[\"ftp://charts.example/demo.tgz\"]", + "nested": "[[demo.tgz]]", + "oci no path": "[\"oci://ghcr.io\"]", + "oci no host": "[\"oci:///acme/demo\"]", + "oci query": "[\"oci://ghcr.io/acme/demo?x=1\"]", + "oci forcequery": "[\"oci://ghcr.io/acme/demo?\"]", + "oci fragment": "[\"oci://ghcr.io/acme/demo#x\"]", + "oci userinfo": "[\"oci://u:p@ghcr.io/acme/demo\"]", + "oci traversal": "[\"oci://ghcr.io/acme/../demo\"]", + "oci encoded dot": "[\"oci://ghcr.io/acme/%2e%2e/demo\"]", + "bad url": "[\"https://charts.example/%zz.tgz\"]", + "trailing slash": "[\"https://charts.example/\"]", + "oci backslash": "[\"oci://ghcr.io/acme/..\\\\demo\"]", + } { + index := "entries:\n demo:\n - {digest: " + digestA + ", urls: " + urls + "}\n" + var got error + _, _, err := Rewrite([]byte(index), Options{UpstreamURL: "https://charts.example", OnMalformed: func(_ string, err error) { got = err }}) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if got == nil { + t.Errorf("%s: release accepted", name) + } + } + index := "entries:\n demo:\n - {digest: " + digestA + ", created: yesterday, urls: [demo.tgz]}\n" + var got error + if _, _, err := Rewrite([]byte(index), Options{UpstreamURL: "https://charts.example", OnMalformed: func(_ string, err error) { got = err }}); err != nil || got == nil { + t.Errorf("bad creation time: err %v, malformed %v", err, got) + } +} + +func TestOCIProxyReference(t *testing.T) { + registries := []OCIRegistry{{Host: "registry.example", Prefix: "/upstream/r"}, {Host: "docker.io"}} + for _, tc := range []struct{ proxy, ref, want string }{ + {"https://proxy.example", "oci://REGISTRY.example/acme/demo", "oci://proxy.example/upstream/r/acme/demo"}, + {"https://proxy.example", "oci://docker.io/acme/demo", "oci://proxy.example/acme/demo"}, + {"https://proxy.example", "oci://docker.io/upstream/x", "oci://docker.io/upstream/x"}, + {"https://proxy.example", "oci://other.example/acme/demo", "oci://other.example/acme/demo"}, + {"https://proxy.example/base", "oci://docker.io/acme/demo", "oci://docker.io/acme/demo"}, + {"", "oci://docker.io/acme/demo", "oci://docker.io/acme/demo"}, + {"https://proxy.example", "oci://docker.io/%zz", "oci://docker.io/%zz"}, + {"%zz", "oci://docker.io/acme/demo", "oci://docker.io/acme/demo"}, + } { + if got := OCIProxyReference(tc.proxy, registries, tc.ref); got != tc.want { + t.Errorf("OCIProxyReference(%q, %q) = %q, want %q", tc.proxy, tc.ref, got, tc.want) + } + } +} + +func TestNormalizeDigest(t *testing.T) { + if got, ok := NormalizeDigest("SHA256:" + strings.ToUpper(digestA)); !ok || got != digestA { + t.Errorf("NormalizeDigest = %q, %t", got, ok) + } + for _, bad := range []string{"", digestA[1:], digestA + "a", strings.Repeat("g", 64), strings.Repeat("/", 64)} { + if _, ok := NormalizeDigest(bad); ok { + t.Errorf("NormalizeDigest(%q) accepted", bad) + } + } +} + +func TestIndexEntries(t *testing.T) { + if _, err := IndexEntries(nil); err == nil { + t.Error("nil document accepted") + } + document, _, err := ParseIndex([]byte("entries:\n demo: []\n")) + if err != nil { + t.Fatal(err) + } + entries, _ := IndexEntries(document) + entries.Content = entries.Content[:1] + if _, err := IndexEntries(document); err == nil { + t.Error("incomplete mapping accepted") + } + if _, _, err := ParseIndex([]byte("- a\n")); err == nil { + t.Error("sequence document accepted") + } + if _, _, err := ParseIndex([]byte("entries: [a]\n")); err == nil { + t.Error("sequence entries accepted") + } + if MappingValue(nil, "x") != nil || MappingValue(entries, "missing") != nil { + t.Error("MappingValue found a missing key") + } +}