Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions internal/handler/cooldown_supported_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ import (

func TestCooldownSupportedCoversHandlers(t *testing.T) {
calls := regexp.MustCompile(`(?:IsAllowed|Evaluate)\("([a-z]+)"|withheld\(h\.proxy, "([a-z]+)"|IsAllowed\((helmMetadataEcosystem)`)
// Metadata rewrites moved out of the handlers (#501) check cooldown in
// internal/metadata.
files, err := filepath.Glob("*.go")
if err != nil {
t.Fatal(err)
}
extracted, err := filepath.Glob("../metadata/*/*.go")
if err != nil {
t.Fatal(err)
}
files = append(files, extracted...)
found := map[string]bool{}
for _, f := range files {
if strings.HasSuffix(f, "_test.go") {
Expand Down
134 changes: 15 additions & 119 deletions internal/handler/pub.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import (
"strings"
"time"

"github.com/Masterminds/semver/v3"
"github.com/git-pkgs/proxy/internal/database"
"github.com/git-pkgs/proxy/internal/metadata/pub"
"github.com/git-pkgs/proxy/internal/retention"
)

Expand Down Expand Up @@ -217,125 +217,21 @@ func (h *PubHandler) handlePackageMetadata(w http.ResponseWriter, r *http.Reques
_, _ = w.Write(rewritten)
}

// rewriteMetadata rewrites archive_url fields to point at this proxy.
// If cooldown is enabled, versions published too recently are filtered out.
// rewriteMetadata rewrites archive_url fields to point at this proxy and,
// with cooldown enabled, leaves out versions published too recently; see
// pub.Rewrite.
func (h *PubHandler) rewriteMetadata(name string, body []byte) ([]byte, error) {
var metadata map[string]any
if err := json.Unmarshal(body, &metadata); err != nil {
return nil, err
}

versions, ok := metadata["versions"].([]any)
if !ok {
return body, nil
}

packagePURL := canonicalPackagePURL("pub", name)
filtered := h.filterAndRewriteVersions(name, packagePURL, versions)
metadata["versions"] = filtered

h.updateLatestVersion(metadata, filtered)

return json.Marshal(metadata)
}

// filterAndRewriteVersions applies cooldown filtering and rewrites archive URLs
// for a package's version list.
func (h *PubHandler) filterAndRewriteVersions(name, packagePURL string, versions []any) []any {
filtered := versions[:0]
for _, vdata := range versions {
vmap, ok := vdata.(map[string]any)
if !ok {
continue
}

version, _ := vmap["version"].(string)
if version == "" {
continue
}

if h.shouldFilterVersion(packagePURL, name, version, vmap) {
continue
}

newURL := fmt.Sprintf("%s/pub/packages/%s/versions/%s.tar.gz", h.proxyURL, name, version)
vmap["archive_url"] = newURL
filtered = append(filtered, vdata)

h.proxy.Logger.Debug("rewrote archive URL",
"package", name, "version", version, "new", newURL)
}

return filtered
return pub.Rewrite(name, body, pub.Options{
ProxyURL: h.proxyURL,
Cooldown: h.proxy.cooldown(),
EvaluatedAt: time.Now(),
OnCooldownFilter: h.cooldownFiltered,
})
}

// shouldFilterVersion returns true if the version should be excluded due to cooldown.
func (h *PubHandler) shouldFilterVersion(packagePURL, name, version string, vmap map[string]any) bool {
if h.proxy.Cooldown == nil || !h.proxy.Cooldown.Enabled() {
return false
}

publishedStr, ok := vmap["published"].(string)
if !ok {
return false
}

publishedAt, err := time.Parse(time.RFC3339, publishedStr)
if err != nil {
return false
}

if !h.proxy.cooldown().IsAllowed("pub", packagePURL, publishedAt) {
h.proxy.Logger.Info("cooldown: filtering pub version",
"package", name, "version", version)
h.proxy.recordWithheld("pub", name, version, publishedAt)
return true
}

return false
}

// updateLatestVersion points latest at the kept entry for its version, so
// its archive_url is the proxy's too. When cooldown removed that version,
// latest becomes the newest stable version left, or the newest version left
// if all are prereleases, and is dropped when none is left.
func (h *PubHandler) updateLatestVersion(metadata map[string]any, filtered []any) {
latest, ok := metadata["latest"].(map[string]any)
if !ok {
return
}
latestVer, _ := latest["version"].(string)

var newest, newestStable *semver.Version
var newestEntry, newestStableEntry any
for _, vdata := range filtered {
vmap, ok := vdata.(map[string]any)
if !ok {
continue
}
version, _ := vmap["version"].(string)
if version == latestVer {
latest["archive_url"] = vmap["archive_url"]
return
}
parsed, err := semver.NewVersion(version)
if err != nil {
continue
}
if newest == nil || parsed.GreaterThan(newest) {
newest, newestEntry = parsed, vdata
}
if parsed.Prerelease() == "" && (newestStable == nil || parsed.GreaterThan(newestStable)) {
newestStable, newestStableEntry = parsed, vdata
}
}

switch {
case newestStableEntry != nil:
metadata["latest"] = newestStableEntry
case newestEntry != nil:
metadata["latest"] = newestEntry
default:
delete(metadata, "latest")
}
// cooldownFiltered logs a version a metadata rewrite held back and records
// it for the package page.
func (h *PubHandler) cooldownFiltered(name, version string, publishedAt time.Time) {
h.proxy.Logger.Info("cooldown: filtering pub version", "package", name, "version", version)
h.proxy.recordWithheld("pub", name, version, publishedAt)
}
44 changes: 44 additions & 0 deletions internal/metadata/pub/imports_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package pub

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/Masterminds/semver/v3",
"github.com/git-pkgs/cooldown",
"github.com/git-pkgs/proxy/internal/metadata/pub",
"github.com/git-pkgs/proxy/internal/packageurl",
"github.com/git-pkgs/purl",
"github.com/git-pkgs/vers",
"github.com/package-url/packageurl-go",
}
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)
}
}
}
149 changes: 149 additions & 0 deletions internal/metadata/pub/metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// Package pub transforms pub.dev package metadata without storage or
// network access.
package pub

import (
"encoding/json"
"fmt"
"time"

"github.com/Masterminds/semver/v3"
"github.com/git-pkgs/cooldown"
"github.com/git-pkgs/proxy/internal/packageurl"
)

const ecosystem = "pub"

// 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
}

// Options supplies the public URL and policy for a rewrite. EvaluatedAt is
// used as given; the transformation never reads the clock.
type Options struct {
ProxyURL string
Cooldown CooldownPolicy
EvaluatedAt time.Time
// OnCooldownFilter is called synchronously for each version cooldown
// holds back, with its publish time.
OnCooldownFilter func(name, version string, publishedAt time.Time)
}

// ArchiveURL is where the proxy serves a version's archive.
func ArchiveURL(proxyURL, name, version string) string {
return fmt.Sprintf("%s/pub/packages/%s/versions/%s.tar.gz", proxyURL, name, version)
}

// Rewrite points each version's archive_url at the proxy and leaves out the
// versions cooldown holds back. A document without a versions list is
// returned unchanged. latest follows the versions kept (see updateLatest).
func Rewrite(name string, body []byte, o Options) ([]byte, error) {
var metadata map[string]any
if err := json.Unmarshal(body, &metadata); err != nil {
return nil, err
}

versions, ok := metadata["versions"].([]any)
if !ok {
return body, nil
}

kept := filterVersions(name, versions, o)
metadata["versions"] = kept
updateLatest(metadata, kept)

return json.Marshal(metadata)
}

// filterVersions keeps the entries with a version that cooldown doesn't
// hold back, with their archive_url pointing at the proxy.
func filterVersions(name string, versions []any, o Options) []any {
packagePURL := packageurl.MakeString(ecosystem, name, "")
kept := versions[:0]
for _, vdata := range versions {
vmap, ok := vdata.(map[string]any)
if !ok {
continue
}
version, _ := vmap["version"].(string)
if version == "" {
continue
}
if heldBack(packagePURL, name, version, vmap, o) {
continue
}
vmap["archive_url"] = ArchiveURL(o.ProxyURL, name, version)
kept = append(kept, vdata)
}
return kept
}

// heldBack reports whether cooldown holds a version back. A version without
// an RFC 3339 published time is let through.
func heldBack(packagePURL, name, version string, vmap map[string]any, o Options) bool {
if o.Cooldown == nil || !o.Cooldown.Enabled() {
return false
}
published, ok := vmap["published"].(string)
if !ok {
return false
}
publishedAt, err := time.Parse(time.RFC3339, published)
if err != nil {
return false
}
if o.Cooldown.Evaluate("pub", packagePURL, publishedAt, o.EvaluatedAt).Allowed {
return false
}
if o.OnCooldownFilter != nil {
o.OnCooldownFilter(name, version, publishedAt)
}
return true
}

// updateLatest points latest at the kept entry for its version, so its
// archive_url is the proxy's too. When cooldown removed that version,
// latest becomes the newest stable version left, or the newest version left
// if all are prereleases, and is dropped when none is left.
func updateLatest(metadata map[string]any, kept []any) {
latest, ok := metadata["latest"].(map[string]any)
if !ok {
return
}
latestVer, _ := latest["version"].(string)

var newest, newestStable *semver.Version
var newestEntry, newestStableEntry any
for _, vdata := range kept {
vmap, ok := vdata.(map[string]any)
if !ok {
continue
}
version, _ := vmap["version"].(string)
if version == latestVer {
latest["archive_url"] = vmap["archive_url"]
return
}
parsed, err := semver.NewVersion(version)
if err != nil {
continue
}
if newest == nil || parsed.GreaterThan(newest) {
newest, newestEntry = parsed, vdata
}
if parsed.Prerelease() == "" && (newestStable == nil || parsed.GreaterThan(newestStable)) {
newestStable, newestStableEntry = parsed, vdata
}
}

switch {
case newestStableEntry != nil:
metadata["latest"] = newestStableEntry
case newestEntry != nil:
metadata["latest"] = newestEntry
default:
delete(metadata, "latest")
}
}
Loading
Loading