diff --git a/internal/handler/cargo.go b/internal/handler/cargo.go index 19897194..16f4a730 100644 --- a/internal/handler/cargo.go +++ b/internal/handler/cargo.go @@ -1,8 +1,6 @@ package handler import ( - "bufio" - "bytes" "encoding/json" "errors" "fmt" @@ -11,16 +9,13 @@ import ( "strings" "time" + "github.com/git-pkgs/proxy/internal/metadata/cargo" "github.com/git-pkgs/proxy/internal/retention" ) const ( cargoUpstream = "https://index.crates.io" cargoDownloadBase = "https://static.crates.io/crates" - - cargoIndexLen1 = 1 - cargoIndexLen2 = 2 - cargoIndexLen3 = 3 ) // Crates are stored under pkg:cargo/{name}, with the name cargo puts in the @@ -92,7 +87,7 @@ type CargoConfig struct { // handleConfig returns the registry configuration. func (h *CargoHandler) handleConfig(w http.ResponseWriter, r *http.Request) { config := CargoConfig{ - DL: h.proxyURL + "/cargo/crates/{crate}/{version}/download", + DL: cargo.DownloadTemplate(h.proxyURL), } w.Header().Set(headerContentType, "application/json") @@ -135,61 +130,40 @@ func (h *CargoHandler) handleIndex(w http.ResponseWriter, r *http.Request) { h.applyCooldownFiltering(w, body) } -type crateIndexEntry struct { - Name string `json:"name"` - Version string `json:"vers"` - PublishTime string `json:"pubtime,omitempty"` -} - +// applyCooldownFiltering writes the index body with the versions the +// denylist names and those cooldown holds back left out (cargo.Filter). func (h *CargoHandler) applyCooldownFiltering(downstreamResponse http.ResponseWriter, body []byte) { - cooldownEnabled := h.proxy.Cooldown != nil && h.proxy.Cooldown.Enabled() - if !cooldownEnabled && h.proxy.Denylist == nil { - _, _ = downstreamResponse.Write(body) - return + out, err := cargo.Filter(body, h.filterOptions()) + _, _ = downstreamResponse.Write(out) + if err != nil { + h.proxy.Logger.Error("error reading index response", "error", err) } +} - scanner := bufio.NewScanner(strings.NewReader(string(body))) - // The response is already size-bounded by FetchOrCacheMetadata. Crate - // entries with many dependencies can exceed Scanner's default token limit. - scanner.Buffer(nil, len(body)+1) - - for scanner.Scan() { - line := scanner.Text() - - var crate crateIndexEntry - err := json.Unmarshal([]byte(line), &crate) - - if err != nil { - h.proxy.Logger.Error("failed to parse json entry in index", "error", err) - continue - } - - if h.proxy.versionDenied("cargo", crate.Name, crate.Version) { - continue - } - publishedAt, err := time.Parse(time.RFC3339, crate.PublishTime) - - if !cooldownEnabled || crate.PublishTime == "" || err != nil { - _, _ = downstreamResponse.Write([]byte(line + "\n")) - continue - } - - cratePURL := canonicalPackagePURL("cargo", crate.Name) - - if !h.proxy.cooldown().IsAllowed("cargo", cratePURL, publishedAt) { +// filterOptions are the policy the index filter applies. The callbacks log +// and record what it holds back. +func (h *CargoHandler) filterOptions() cargo.Options { + o := cargo.Options{ + EvaluatedAt: time.Now(), + OnWithheld: func(name, version string, publishedAt time.Time) { h.proxy.Logger.Info("cooldown: filtering cargo version", - "crate", crate.Name, "version", crate.Version, - "published", crate.PublishTime) - h.proxy.recordWithheld("cargo", crate.Name, crate.Version, publishedAt) - continue - } - - _, _ = downstreamResponse.Write([]byte(line + "\n")) + "crate", name, "version", version, + "published", publishedAt.Format(time.RFC3339)) + h.proxy.recordWithheld("cargo", name, version, publishedAt) + }, + OnInvalidEntry: func(err error) { + h.proxy.Logger.Error("failed to parse json entry in index", "error", err) + }, } - - if err := scanner.Err(); err != nil { - h.proxy.Logger.Error("error reading index response", "error", err) + if policy := h.proxy.cooldown(); policy != nil { + o.Cooldown = policy } + if h.proxy.Denylist != nil { + o.Denied = func(name, version string) bool { + return h.proxy.versionDenied("cargo", name, version) + } + } + return o } // publishTime reads a crate version's pubtime from the sparse index, sharing @@ -200,39 +174,15 @@ func (h *CargoHandler) publishTime(r *http.Request, name, version string) (time. upstreamURL := fmt.Sprintf("%s/%s", h.indexURL, h.buildIndexPath(name)) listed, err := readListed(r.Context(), h.proxy, "cargo", name, upstreamURL, "text/plain", "", func(res metadataResult) (listedTime, bool, error) { - for line := range bytes.SplitSeq(res.body, []byte("\n")) { - if len(bytes.TrimSpace(line)) == 0 { - continue - } - var entry crateIndexEntry - if err := json.Unmarshal(line, &entry); err != nil { - return listedTime{}, false, err - } - if entry.Version != version { - continue - } - published, err := time.Parse(time.RFC3339, entry.PublishTime) - return listedTime{published, err == nil}, true, nil - } - return listedTime{}, false, nil + published, ok, listed, err := cargo.PublishTime(res.body, version) + return listedTime{published, ok}, listed, err }) return listed.published, listed.ok, err } // buildIndexPath builds the sparse index path for a crate name. func (h *CargoHandler) buildIndexPath(name string) string { - name = strings.ToLower(name) - - switch len(name) { - case cargoIndexLen1: - return fmt.Sprintf("1/%s", name) - case cargoIndexLen2: - return fmt.Sprintf("2/%s", name) - case cargoIndexLen3: - return fmt.Sprintf("3/%c/%s", name[0], name) - default: - return fmt.Sprintf("%s/%s/%s", name[0:2], name[2:4], name) - } + return cargo.IndexPath(name) } // handleDownload serves a crate file, fetching and caching from upstream if needed. diff --git a/internal/handler/cooldown_supported_test.go b/internal/handler/cooldown_supported_test.go index 7187edeb..372d78d3 100644 --- a/internal/handler/cooldown_supported_test.go +++ b/internal/handler/cooldown_supported_test.go @@ -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") { diff --git a/internal/metadata/cargo/imports_test.go b/internal/metadata/cargo/imports_test.go new file mode 100644 index 00000000..f4fc9101 --- /dev/null +++ b/internal/metadata/cargo/imports_test.go @@ -0,0 +1,43 @@ +package cargo + +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/cargo", + "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) + } + } +} diff --git a/internal/metadata/cargo/metadata.go b/internal/metadata/cargo/metadata.go new file mode 100644 index 00000000..e1006220 --- /dev/null +++ b/internal/metadata/cargo/metadata.go @@ -0,0 +1,157 @@ +// Package cargo transforms Cargo sparse index metadata without storage or +// network access. +package cargo + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/packageurl" +) + +const ( + indexLen1 = 1 + indexLen2 = 2 + indexLen3 = 3 +) + +// 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 policy and callbacks for a filter. EvaluatedAt is +// used as given; the transformation never reads the clock. +type Options struct { + Cooldown CooldownPolicy + EvaluatedAt time.Time + // Denied reports whether the denylist names a version of a crate. + Denied func(name, version string) bool + // Optional callbacks report changes synchronously. OnWithheld is called + // for each version cooldown holds back, with its publish time; + // OnInvalidEntry for each index line that isn't a JSON entry, which is + // left out. + OnWithheld func(name, version string, publishedAt time.Time) + OnInvalidEntry func(err error) +} + +// Entry is the part of a sparse index line the proxy reads. +type Entry struct { + Name string `json:"name"` + Version string `json:"vers"` + PublishTime string `json:"pubtime,omitempty"` +} + +// Filters reports whether Filter would change anything under o: with +// neither an enabled cooldown nor a denylist, the index is served as is. +func (o Options) Filters() bool { + return o.cooldownEnabled() || o.Denied != nil +} + +func (o Options) cooldownEnabled() bool { + return o.Cooldown != nil && o.Cooldown.Enabled() +} + +// Filter leaves out of a sparse index the entries the denylist names and +// those cooldown holds back, by their pubtime. Entries without a readable +// pubtime are kept. Each kept line ends in a newline. Lines that aren't JSON +// entries are left out and reported to o.OnInvalidEntry. The error is one +// reading the index; the lines read before it are returned. +func Filter(body []byte, o Options) ([]byte, error) { + if !o.Filters() { + return body, nil + } + cooldownEnabled := o.cooldownEnabled() + out := make([]byte, 0, len(body)) + scanner := bufio.NewScanner(bytes.NewReader(body)) + // Entries with many dependencies can exceed Scanner's default token + // limit; no line is longer than the body. + scanner.Buffer(nil, len(body)+1) + for scanner.Scan() { + line := scanner.Bytes() + var entry Entry + if err := json.Unmarshal(line, &entry); err != nil { + if o.OnInvalidEntry != nil { + o.OnInvalidEntry(err) + } + continue + } + if o.Denied != nil && o.Denied(entry.Name, entry.Version) { + continue + } + if cooldownEnabled && o.withheld(entry) { + continue + } + out = append(out, line...) + out = append(out, '\n') + } + return out, scanner.Err() +} + +// withheld reports whether cooldown holds back entry, telling +// o.OnWithheld when it does. +func (o Options) withheld(entry Entry) bool { + // An entry without a pubtime, or with one that doesn't parse, is kept. + publishedAt, err := time.Parse(time.RFC3339, entry.PublishTime) + if err != nil { + return false + } + packagePURL := packageurl.MakeString("cargo", entry.Name, "") + if o.Cooldown.Evaluate("cargo", packagePURL, publishedAt, o.EvaluatedAt).Allowed { + return false + } + if o.OnWithheld != nil { + o.OnWithheld(entry.Name, entry.Version, publishedAt) + } + return true +} + +// PublishTime reads a version's pubtime from a sparse index. listed +// reports whether the index has the version at all; ok whether its pubtime +// is readable, which entries published before crates.io recorded pubtime +// aren't. A line that isn't a JSON entry is an error. +func PublishTime(body []byte, version string) (published time.Time, ok, listed bool, err error) { + for line := range bytes.SplitSeq(body, []byte("\n")) { + if len(bytes.TrimSpace(line)) == 0 { + continue + } + var entry Entry + if err := json.Unmarshal(line, &entry); err != nil { + return time.Time{}, false, false, err + } + if entry.Version != version { + continue + } + published, err := time.Parse(time.RFC3339, entry.PublishTime) + return published, err == nil, true, nil + } + return time.Time{}, false, false, nil +} + +// IndexPath is a crate's path in the sparse index, by the length of its +// lowercased name: 1/{name}, 2/{name}, 3/{a}/{name} or {ab}/{cd}/{name}. +func IndexPath(name string) string { + name = strings.ToLower(name) + switch len(name) { + case indexLen1: + return "1/" + name + case indexLen2: + return "2/" + name + case indexLen3: + return fmt.Sprintf("3/%c/%s", name[0], name) + default: + return fmt.Sprintf("%s/%s/%s", name[0:2], name[2:4], name) + } +} + +// DownloadTemplate is the config.json dl template that points crate +// downloads at the proxy. +func DownloadTemplate(proxyURL string) string { + return proxyURL + "/cargo/crates/{crate}/{version}/download" +} diff --git a/internal/metadata/cargo/metadata_test.go b/internal/metadata/cargo/metadata_test.go new file mode 100644 index 00000000..60079e30 --- /dev/null +++ b/internal/metadata/cargo/metadata_test.go @@ -0,0 +1,191 @@ +package cargo + +import ( + "reflect" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +var evaluatedAt = time.Date(2026, 6, 10, 12, 0, 0, 0, time.UTC) + +// policy holds back versions published less than three days before the +// time it is evaluated at, and records the PURLs it is asked about. +type policy struct { + disabled bool + purls []string + at []time.Time +} + +func (p *policy) Enabled() bool { return !p.disabled } + +func (p *policy) Evaluate(ecosystem, packagePURL string, publishedAt, at time.Time) cooldown.Decision { + p.purls = append(p.purls, ecosystem+" "+packagePURL) + p.at = append(p.at, at) + return cooldown.Decision{Allowed: !publishedAt.After(at.Add(-72 * time.Hour))} +} + +func line(name, version, pubtime string) string { + s := `{"name":"` + name + `","vers":"` + version + `","cksum":"ab"` + if pubtime != "" { + s += `,"pubtime":"` + pubtime + `"` + } + return s + `}` +} + +func TestFilterWithholdsByPubtimeAtEvaluatedAt(t *testing.T) { + old := evaluatedAt.Add(-96 * time.Hour).Format(time.RFC3339) + recent := evaluatedAt.Add(-time.Hour).Format(time.RFC3339) + body := line("serde", "1.0.0", old) + "\n" + + line("serde", "1.0.1", recent) + "\n" + + line("serde", "0.9.0", "") + "\n" + + line("serde", "0.9.1", "not a time") + p := &policy{} + var withheld []string + out, err := Filter([]byte(body), Options{ + Cooldown: p, EvaluatedAt: evaluatedAt, + OnWithheld: func(name, version string, publishedAt time.Time) { + withheld = append(withheld, name+"@"+version+" "+publishedAt.Format(time.RFC3339)) + }, + }) + if err != nil { + t.Fatal(err) + } + want := line("serde", "1.0.0", old) + "\n" + line("serde", "0.9.0", "") + "\n" + line("serde", "0.9.1", "not a time") + "\n" + if string(out) != want { + t.Errorf("Filter =\n%s\nwant\n%s", out, want) + } + if !reflect.DeepEqual(withheld, []string{"serde@1.0.1 " + recent}) { + t.Errorf("withheld = %v", withheld) + } + if !reflect.DeepEqual(p.purls, []string{"cargo pkg:cargo/serde", "cargo pkg:cargo/serde"}) { + t.Errorf("evaluated %v", p.purls) + } + for _, at := range p.at { + if !at.Equal(evaluatedAt) { + t.Errorf("evaluated at %v, want %v", at, evaluatedAt) + } + } +} + +func TestFilterDenylist(t *testing.T) { + body := line("demo", "1.0.0", "") + "\n" + line("demo", "2.0.0", "") + "\n" + for _, p := range []CooldownPolicy{nil, &policy{disabled: true}, &policy{}} { + out, err := Filter([]byte(body), Options{ + Cooldown: p, EvaluatedAt: evaluatedAt, + Denied: func(name, version string) bool { return name == "demo" && version == "1.0.0" }, + }) + if err != nil { + t.Fatal(err) + } + if string(out) != line("demo", "2.0.0", "")+"\n" { + t.Errorf("Filter = %q", out) + } + } +} + +func TestFilterDisabledCooldownKeepsRecentVersions(t *testing.T) { + recent := evaluatedAt.Add(-time.Hour).Format(time.RFC3339) + body := line("serde", "1.0.1", recent) + "\n" + p := &policy{disabled: true} + out, err := Filter([]byte(body), Options{Cooldown: p, EvaluatedAt: evaluatedAt, Denied: func(string, string) bool { return false }}) + if err != nil { + t.Fatal(err) + } + if string(out) != body { + t.Errorf("Filter = %q", out) + } + if len(p.purls) != 0 { + t.Errorf("disabled policy evaluated %v", p.purls) + } +} + +func TestFilterWithoutPolicyReturnsBodyAsIs(t *testing.T) { + body := []byte("not json\n\n" + line("serde", "1.0.0", "")) + for _, o := range []Options{{}, {Cooldown: &policy{disabled: true}}} { + if o.Filters() { + t.Errorf("%+v filters", o) + } + out, err := Filter(body, o) + if err != nil || string(out) != string(body) { + t.Errorf("Filter = %q, %v", out, err) + } + } + if !(Options{Cooldown: &policy{}}).Filters() || !(Options{Denied: func(string, string) bool { return false }}).Filters() { + t.Error("an enabled cooldown or a denylist should filter") + } +} + +func TestFilterLeavesOutInvalidEntries(t *testing.T) { + body := "not json\n\n" + line("serde", "1.0.0", "") + var invalid int + out, err := Filter([]byte(body), Options{ + Cooldown: &policy{}, + EvaluatedAt: evaluatedAt, + OnInvalidEntry: func(error) { invalid++ }, + }) + if err != nil { + t.Fatal(err) + } + if string(out) != line("serde", "1.0.0", "")+"\n" { + t.Errorf("Filter = %q", out) + } + if invalid != 2 { + t.Errorf("invalid entries reported = %d, want 2", invalid) + } + // Without the callback, invalid lines are still left out. + if out, _ := Filter([]byte(body), Options{Cooldown: &policy{}, EvaluatedAt: evaluatedAt}); string(out) != line("serde", "1.0.0", "")+"\n" { + t.Errorf("Filter = %q", out) + } +} + +func TestFilterKeepsLongEntries(t *testing.T) { + entry := `{"name":"demo","vers":"2.0.0","extra":"` + strings.Repeat("x", 70<<10) + `"}` + "\n" + out, err := Filter([]byte(entry), Options{Cooldown: &policy{}, EvaluatedAt: evaluatedAt}) + if err != nil || string(out) != entry { + t.Fatalf("long entry: err %v, %d bytes", err, len(out)) + } +} + +func TestPublishTime(t *testing.T) { + pub := "2026-01-02T03:04:05Z" + body := []byte(line("serde", "1.0.0", pub) + "\n\n" + line("serde", "0.9.0", "") + "\n") + published, ok, listed, err := PublishTime(body, "1.0.0") + if err != nil || !ok || !listed || published.Format(time.RFC3339) != pub { + t.Errorf("1.0.0: %v %v %v %v", published, ok, listed, err) + } + _, ok, listed, err = PublishTime(body, "0.9.0") + if err != nil || ok || !listed { + t.Errorf("0.9.0 without pubtime: ok %v listed %v err %v", ok, listed, err) + } + _, ok, listed, err = PublishTime(body, "2.0.0") + if err != nil || ok || listed { + t.Errorf("2.0.0 unlisted: ok %v listed %v err %v", ok, listed, err) + } + _, _, listed, err = PublishTime([]byte("not json\n"), "1.0.0") + if err == nil || listed { + t.Errorf("invalid line: listed %v err %v", listed, err) + } +} + +func TestIndexPath(t *testing.T) { + for name, want := range map[string]string{ + "a": "1/a", + "ab": "2/ab", + "abc": "3/a/abc", + "abcd": "ab/cd/abcd", + "Serde": "se/rd/serde", + } { + if got := IndexPath(name); got != want { + t.Errorf("IndexPath(%q) = %q, want %q", name, got, want) + } + } +} + +func TestDownloadTemplate(t *testing.T) { + if got := DownloadTemplate("http://proxy"); got != "http://proxy/cargo/crates/{crate}/{version}/download" { + t.Errorf("DownloadTemplate = %q", got) + } +}