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
116 changes: 33 additions & 83 deletions internal/handler/cargo.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package handler

import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
Expand All @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
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
43 changes: 43 additions & 0 deletions internal/metadata/cargo/imports_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
157 changes: 157 additions & 0 deletions internal/metadata/cargo/metadata.go
Original file line number Diff line number Diff line change
@@ -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"
}
Loading
Loading