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/handler/gem.go b/internal/handler/gem.go index 3e7ce4c2..c2137800 100644 --- a/internal/handler/gem.go +++ b/internal/handler/gem.go @@ -1,14 +1,12 @@ package handler import ( - "bytes" - "encoding/json" "fmt" "net/http" - "regexp" "strings" "time" + "github.com/git-pkgs/proxy/internal/metadata/gem" "github.com/git-pkgs/proxy/internal/retention" ) @@ -87,60 +85,9 @@ func (h *GemHandler) handleDownload(w http.ResponseWriter, r *http.Request) { } // GemFilenameIdentity returns the name and version a gem file is cached -// under, read from its filename. A platform build's version keeps its -// platform. -// e.g., "rails-7.1.0.gem" -> ("rails", "7.1.0") -// e.g., "aws-sdk-s3-1.142.0.gem" -> ("aws-sdk-s3", "1.142.0") -// e.g., "sorbet-static-0.5.11002-universal-darwin-22.gem" -> ("sorbet-static", "0.5.11002-universal-darwin-22") -// e.g., "devise-2fa-1.0.0.gem" -> ("devise-2fa", "1.0.0") -// -// A gem file is named {name}-{version}[-{platform}]. RubyGems writes a -// version as dot-separated alphanumeric segments starting with a digit, -// turning any "-" into ".pre.", and a platform starts with a letter (its -// CPU, or java), though it can end in a number (universal-java-17), so -// splitting at the last "-" would cut the platform. The version -// starts at the first "-" that leaves such a version and platform, -// so a name with a "-" segment of its own, such as devise-2fa, is -// kept whole. A filename no split fits is split at the first "-". -// -// Trying every "-" costs time quadratic in the filename's length, so -// a filename longer than maxGemFilenameLength is refused. +// under, read from its filename (see gem.FilenameIdentity). func GemFilenameIdentity(filename string) (name, version string) { - if len(filename) > maxGemFilenameLength { - return "", "" - } - base := strings.TrimSuffix(filename, ".gem") - first := -1 - for i := 0; i+1 < len(base); i++ { - if base[i] != '-' || base[i+1] < '0' || base[i+1] > '9' { - continue - } - if first < 0 { - first = i - } - if gemVersionAndPlatform(base[i+1:]) { - return base[:i], base[i+1:] - } - } - if first < 0 { - return "", "" - } - return base[:first], base[first+1:] -} - -// maxGemFilenameLength bounds the gem filenames GemFilenameIdentity accepts. -// Real gem filenames are a small fraction of this. -const maxGemFilenameLength = 512 - -var ( - gemVersionPattern = regexp.MustCompile(`^[0-9]+(\.[0-9A-Za-z]+)*$`) - gemPlatformPattern = regexp.MustCompile(`^[A-Za-z][0-9A-Za-z_]*(-[0-9A-Za-z_]+)*$`) -) - -// gemVersionAndPlatform reports whether s reads as {version}[-{platform}]. -func gemVersionAndPlatform(s string) bool { - version, platform, hasPlatform := strings.Cut(s, "-") - return gemVersionPattern.MatchString(version) && (!hasPlatform || gemPlatformPattern.MatchString(platform)) + return gem.FilenameIdentity(filename) } // handleCompactIndex serves the compact index for a gem, filtering versions @@ -184,9 +131,7 @@ func (h *GemHandler) handleCompactIndex(w http.ResponseWriter, r *http.Request) if err != nil { return nil, nil, err } - out, kept := h.filterIndex(body, name, func(version string) bool { - return docs.withheld(h.proxy, "gem", name, version) - }) + out, kept := h.filterIndex(body, name, docs) return out, kept, nil }) if err != nil { @@ -227,83 +172,36 @@ func (h *GemHandler) indexVersions(doc metadataResult) ([]string, error) { if err != nil { return nil, err } - var versions []string - for rest := body; len(rest) > 0; { - line, tail, _ := bytes.Cut(rest, []byte("\n")) - rest = tail - if version := gemIndexLineVersion(line); gemIndexListsVersion(version) { - versions = append(versions, string(version)) - } - } - return versions, nil -} - -// gemIndexLineVersion returns the version a compact index line starts with. -func gemIndexLineVersion(line []byte) []byte { - if spaceIdx := bytes.IndexByte(line, ' '); spaceIdx > 0 { - return line[:spaceIdx] - } - return line + return gem.IndexVersions(body), nil } -// gemIndexListsVersion reports whether a compact index line's first field -// is a version, rather than the "---" that starts the file or an empty line. -func gemIndexListsVersion(field []byte) bool { - return len(field) > 0 && string(field) != "---" +// filterIndex returns the compact index without the lines of the versions +// cooldown holds back, by the publish times in docs, and the versions it +// kept; see gem.FilterIndex. +func (h *GemHandler) filterIndex(body []byte, name string, docs timedDocuments) ([]byte, []string) { + return gem.FilterIndex(name, body, gem.Options{ + Cooldown: h.proxy.cooldown(), + EvaluatedAt: h.proxy.clock(), + Published: docs.published, + WithholdUnknown: docs.withholdUnknown, + OnWithheld: h.cooldownFiltered, + }) } -// filterIndex returns the compact index without the lines of versions -// withheld reports, and the versions it kept. -func (h *GemHandler) filterIndex(body []byte, name string, withheld func(string) bool) ([]byte, []string) { - var kept []string - var out bytes.Buffer - out.Grow(len(body)) - for rest := body; len(rest) > 0; { - line, tail, _ := bytes.Cut(rest, []byte("\n")) - rest = tail - - version := gemIndexLineVersion(line) - if gemIndexListsVersion(version) { - if withheld(string(version)) { - h.proxy.Logger.Info("cooldown: filtering gem version", - "gem", name, "version", string(version)) - continue - } - kept = append(kept, string(version)) - } - out.Write(line) - out.WriteByte('\n') - } - return out.Bytes(), kept +// cooldownFiltered logs a version a compact index was served without and +// records it for the package page. +func (h *GemHandler) cooldownFiltered(name, version string, publishedAt time.Time) { + h.proxy.Logger.Info("cooldown: filtering gem version", "gem", name, "version", version) + h.proxy.recordWithheld("gem", name, version, publishedAt) } -// gemVersion represents a version entry from the RubyGems versions API. -type gemVersion struct { - Number string `json:"number"` - Platform string `json:"platform"` - CreatedAt string `json:"created_at"` -} +// gemVersion is a version entry from the RubyGems versions API. +type gemVersion = gem.Version // parseGemVersions reads the publish times from a versions API response, // keyed by version as the compact index writes it. func parseGemVersions(body []byte) (publishTimes, error) { - var versions []gemVersion - if err := json.Unmarshal(body, &versions); err != nil { - return nil, err - } - times := make(publishTimes, len(versions)) - for _, v := range versions { - versionStr := v.Number - if v.Platform != "" && v.Platform != "ruby" { - versionStr = v.Number + "-" + v.Platform - } - createdAt, err := time.Parse(time.RFC3339, v.CreatedAt) - if err != nil { - createdAt = time.Time{} - } - times[versionStr] = createdAt - } - return times, nil + return gem.PublishTimes(body) } func (h *GemHandler) publishTime(r *http.Request, name, version string) (time.Time, bool, bool, error) { diff --git a/internal/metadata/gem/filename.go b/internal/metadata/gem/filename.go new file mode 100644 index 00000000..efd61df9 --- /dev/null +++ b/internal/metadata/gem/filename.go @@ -0,0 +1,63 @@ +package gem + +import ( + "regexp" + "strings" +) + +// maxFilenameLength bounds the gem filenames FilenameIdentity accepts. +// Real gem filenames are a small fraction of this. +const maxFilenameLength = 512 + +var ( + versionPattern = regexp.MustCompile(`^[0-9]+(\.[0-9A-Za-z]+)*$`) + platformPattern = regexp.MustCompile(`^[A-Za-z][0-9A-Za-z_]*(-[0-9A-Za-z_]+)*$`) +) + +// FilenameIdentity returns the name and version a gem file is cached +// under, read from its filename. A platform build's version keeps its +// platform. +// e.g., "rails-7.1.0.gem" -> ("rails", "7.1.0") +// e.g., "aws-sdk-s3-1.142.0.gem" -> ("aws-sdk-s3", "1.142.0") +// e.g., "sorbet-static-0.5.11002-universal-darwin-22.gem" -> ("sorbet-static", "0.5.11002-universal-darwin-22") +// e.g., "devise-2fa-1.0.0.gem" -> ("devise-2fa", "1.0.0") +// +// A gem file is named {name}-{version}[-{platform}]. RubyGems writes a +// version as dot-separated alphanumeric segments starting with a digit, +// turning any "-" into ".pre.", and a platform starts with a letter (its +// CPU, or java), though it can end in a number (universal-java-17), so +// splitting at the last "-" would cut the platform. The version +// starts at the first "-" that leaves such a version and platform, +// so a name with a "-" segment of its own, such as devise-2fa, is +// kept whole. A filename no split fits is split at the first "-". +// +// Trying every "-" costs time quadratic in the filename's length, so +// a filename longer than 512 bytes is refused. +func FilenameIdentity(filename string) (name, version string) { + if len(filename) > maxFilenameLength { + return "", "" + } + base := strings.TrimSuffix(filename, ".gem") + first := -1 + for i := 0; i+1 < len(base); i++ { + if base[i] != '-' || base[i+1] < '0' || base[i+1] > '9' { + continue + } + if first < 0 { + first = i + } + if versionAndPlatform(base[i+1:]) { + return base[:i], base[i+1:] + } + } + if first < 0 { + return "", "" + } + return base[:first], base[first+1:] +} + +// versionAndPlatform reports whether s reads as {version}[-{platform}]. +func versionAndPlatform(s string) bool { + version, platform, hasPlatform := strings.Cut(s, "-") + return versionPattern.MatchString(version) && (!hasPlatform || platformPattern.MatchString(platform)) +} diff --git a/internal/metadata/gem/imports_test.go b/internal/metadata/gem/imports_test.go new file mode 100644 index 00000000..199c2c44 --- /dev/null +++ b/internal/metadata/gem/imports_test.go @@ -0,0 +1,43 @@ +package gem + +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/gem", + "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/gem/metadata.go b/internal/metadata/gem/metadata.go new file mode 100644 index 00000000..3fa1f43c --- /dev/null +++ b/internal/metadata/gem/metadata.go @@ -0,0 +1,147 @@ +// Package gem transforms RubyGems metadata without storage or network +// access. +package gem + +import ( + "bytes" + "encoding/json" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/packageurl" +) + +const ecosystem = "gem" + +// 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 the publish times for a filter. The +// compact index carries no times, so the caller reads them from the +// versions API (see PublishTimes). EvaluatedAt is used as given; the +// transformation never reads the clock. +type Options struct { + Cooldown CooldownPolicy + EvaluatedAt time.Time + // Published maps each version, as the compact index writes it, to its + // publish time. A version with the zero time is kept. + Published map[string]time.Time + // WithholdUnknown holds back the versions Published doesn't have, for + // a caller whose times may be older than the index. They are kept + // otherwise. + WithholdUnknown bool + // OnWithheld is called synchronously for each version cooldown holds + // back, with its publish time: the zero time for a version held back + // because Published doesn't have it. + OnWithheld func(name, version string, publishedAt time.Time) +} + +// IndexVersions lists the versions in a compact index (/info/{name}), as +// the versions API names them. +func IndexVersions(index []byte) []string { + var versions []string + for rest := index; len(rest) > 0; { + line, tail, _ := bytes.Cut(rest, []byte("\n")) + rest = tail + if version := lineVersion(line); listsVersion(version) { + versions = append(versions, string(version)) + } + } + return versions +} + +// FilterIndex returns the compact index of the gem name without the lines +// of the versions cooldown holds back, and the versions it kept. Without an +// enabled policy every version is kept. +func FilterIndex(name string, index []byte, o Options) ([]byte, []string) { + packagePURL := packageurl.MakeString(ecosystem, name, "") + var kept []string + var out bytes.Buffer + out.Grow(len(index)) + for rest := index; len(rest) > 0; { + line, tail, _ := bytes.Cut(rest, []byte("\n")) + rest = tail + + version := lineVersion(line) + if listsVersion(version) { + if o.withheld(packagePURL, name, string(version)) { + continue + } + kept = append(kept, string(version)) + } + out.Write(line) + out.WriteByte('\n') + } + return out.Bytes(), kept +} + +// withheld reports whether cooldown holds a version back, telling +// o.OnWithheld when it does. +func (o Options) withheld(packagePURL, name, version string) bool { + if o.Cooldown == nil || !o.Cooldown.Enabled() { + return false + } + publishedAt, known := o.Published[version] + switch { + case !known: + if !o.WithholdUnknown { + return false + } + case publishedAt.IsZero(): + return false + case o.Cooldown.Evaluate("gem", packagePURL, publishedAt, o.EvaluatedAt).Allowed: + return false + } + if o.OnWithheld != nil { + o.OnWithheld(name, version, publishedAt) + } + return true +} + +// lineVersion returns the version a compact index line starts with. +func lineVersion(line []byte) []byte { + if spaceIdx := bytes.IndexByte(line, ' '); spaceIdx > 0 { + return line[:spaceIdx] + } + return line +} + +// listsVersion reports whether a compact index line's first field is a +// version, rather than the "---" that starts the file or an empty line. +func listsVersion(field []byte) bool { + return len(field) > 0 && string(field) != "---" +} + +// Version is a version entry from the RubyGems versions API. +type Version struct { + Number string `json:"number"` + Platform string `json:"platform"` + CreatedAt string `json:"created_at"` +} + +// PublishTimes reads the publish times from a versions API response +// (/api/v1/versions/{name}.json), keyed by version as the compact index +// writes it: a platform build's version carries its platform. A time that +// doesn't parse is the zero time. +func PublishTimes(versionsJSON []byte) (map[string]time.Time, error) { + var versions []Version + if err := json.Unmarshal(versionsJSON, &versions); err != nil { + return nil, err + } + times := make(map[string]time.Time, len(versions)) + for _, v := range versions { + version := v.Number + if v.Platform != "" && v.Platform != "ruby" { + version = v.Number + "-" + v.Platform + } + createdAt, err := time.Parse(time.RFC3339, v.CreatedAt) + if err != nil { + createdAt = time.Time{} + } + times[version] = createdAt + } + return times, nil +} diff --git a/internal/metadata/gem/metadata_test.go b/internal/metadata/gem/metadata_test.go new file mode 100644 index 00000000..83ae113b --- /dev/null +++ b/internal/metadata/gem/metadata_test.go @@ -0,0 +1,232 @@ +package gem + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +const index = "---\n" + + "1 |checksum:zzz\n" + + "1.0.0 |checksum:aaa\n" + + "1.1.0 dep:>= 1|checksum:bbb\n" + + "\n" + + "2.0.0-x86_64-linux |checksum:ccc\n" + + "2.0.0" + +func TestIndexVersions(t *testing.T) { + got := IndexVersions([]byte(index)) + want := []string{"1", "1.0.0", "1.1.0", "2.0.0-x86_64-linux", "2.0.0"} + if !slices.Equal(got, want) { + t.Errorf("IndexVersions = %q, want %q", got, want) + } + if got := IndexVersions(nil); got != nil { + t.Errorf("IndexVersions(nil) = %q, want nil", got) + } +} + +// windowPolicy holds a version back until window has passed since it was +// published, as judged at the evaluation time it is given. +type windowPolicy struct { + disabled bool + window time.Duration + evaluated []time.Time + purls []string +} + +func (p *windowPolicy) Enabled() bool { return !p.disabled } + +func (p *windowPolicy) Evaluate(ecosystem, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision { + p.evaluated = append(p.evaluated, evaluatedAt) + p.purls = append(p.purls, ecosystem+" "+packagePURL) + availableAt := publishedAt.Add(p.window) + return cooldown.Decision{Allowed: !evaluatedAt.Before(availableAt), AvailableAt: availableAt} +} + +var now = time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) + +// published gives every version in index a time: 1.1.0 and the platform +// build of 2.0.0 an hour ago, the others a month ago. +func published() map[string]time.Time { + old, recent := now.AddDate(0, -1, 0), now.Add(-time.Hour) + return map[string]time.Time{ + "1": old, + "1.0.0": old, + "1.1.0": recent, + "2.0.0-x86_64-linux": recent, + "2.0.0": old, + } +} + +type withheldVersion struct { + name, version string + publishedAt time.Time +} + +func TestFilterIndex(t *testing.T) { + policy := &windowPolicy{window: 72 * time.Hour} + var reported []withheldVersion + out, kept := FilterIndex("demo", []byte(index), Options{ + Cooldown: policy, + EvaluatedAt: now, + Published: published(), + OnWithheld: func(name, version string, publishedAt time.Time) { + reported = append(reported, withheldVersion{name, version, publishedAt}) + }, + }) + + wantOut := "---\n1 |checksum:zzz\n1.0.0 |checksum:aaa\n\n2.0.0\n" + if string(out) != wantOut { + t.Errorf("FilterIndex output = %q, want %q", out, wantOut) + } + if want := []string{"1", "1.0.0", "2.0.0"}; !slices.Equal(kept, want) { + t.Errorf("kept = %q, want %q", kept, want) + } + recent := now.Add(-time.Hour) + want := []withheldVersion{{"demo", "1.1.0", recent}, {"demo", "2.0.0-x86_64-linux", recent}} + if !slices.Equal(reported, want) { + t.Errorf("OnWithheld got %v, want %v", reported, want) + } + if len(policy.purls) != 5 || slices.ContainsFunc(policy.purls, func(p string) bool { return p != "gem pkg:gem/demo" }) { + t.Errorf("policy asked about %q, want gem pkg:gem/demo for each of the 5 versions", policy.purls) + } + if slices.ContainsFunc(policy.evaluated, func(at time.Time) bool { return !at.Equal(now) }) { + t.Errorf("policy evaluated at %v, want only %v", policy.evaluated, now) + } +} + +func TestFilterIndexWithholdsNothing(t *testing.T) { + tests := map[string]Options{ + "no policy": {Published: published(), WithholdUnknown: true}, + "policy disabled": {Cooldown: &windowPolicy{disabled: true, window: 72 * time.Hour}, EvaluatedAt: now, WithholdUnknown: true}, + "all old enough": {Cooldown: &windowPolicy{window: 30 * time.Minute}, EvaluatedAt: now, Published: published()}, + } + for name, o := range tests { + t.Run(name, func(t *testing.T) { + o.OnWithheld = func(_, version string, _ time.Time) { t.Errorf("withheld %s", version) } + out, kept := FilterIndex("demo", []byte(index), o) + if string(out) != index+"\n" { + t.Errorf("FilterIndex output = %q, want the index with a final newline", out) + } + if len(kept) != 5 { + t.Errorf("kept = %q, want 5 versions", kept) + } + }) + } +} + +// A version the times don't have is kept, unless the caller says its times +// are too old to trust: then it is held back, with no publish time to +// report. +func TestFilterIndexVersionWithoutTime(t *testing.T) { + times := published() + delete(times, "1.0.0") + o := Options{Cooldown: &windowPolicy{window: 30 * time.Minute}, EvaluatedAt: now, Published: times} + + if _, kept := FilterIndex("demo", []byte(index), o); !slices.Contains(kept, "1.0.0") { + t.Errorf("kept = %q, want 1.0.0 in it", kept) + } + + var reported []withheldVersion + o.WithholdUnknown = true + o.OnWithheld = func(name, version string, publishedAt time.Time) { + reported = append(reported, withheldVersion{name, version, publishedAt}) + } + out, kept := FilterIndex("demo", []byte(index), o) + if slices.Contains(kept, "1.0.0") || strings.Contains(string(out), "1.0.0 ") { + t.Errorf("kept = %q, output = %q; want 1.0.0 held back", kept, out) + } + if want := []withheldVersion{{"demo", "1.0.0", time.Time{}}}; !slices.Equal(reported, want) { + t.Errorf("OnWithheld got %v, want %v", reported, want) + } +} + +// A version whose time didn't parse is kept, whatever WithholdUnknown says. +func TestFilterIndexKeepsVersionWithZeroTime(t *testing.T) { + times := published() + times["1.1.0"] = time.Time{} + policy := &windowPolicy{window: 72 * time.Hour} + _, kept := FilterIndex("demo", []byte(index), Options{ + Cooldown: policy, EvaluatedAt: now, Published: times, WithholdUnknown: true, + }) + if want := []string{"1", "1.0.0", "1.1.0", "2.0.0"}; !slices.Equal(kept, want) { + t.Errorf("kept = %q, want %q", kept, want) + } + if len(policy.evaluated) != 4 { + t.Errorf("policy evaluated %d versions, want 4: not the one without a time", len(policy.evaluated)) + } +} + +func TestFilterIndexWithoutOnWithheld(t *testing.T) { + out, kept := FilterIndex("demo", []byte("1.0.0 |x\n"), Options{ + Cooldown: &windowPolicy{window: 72 * time.Hour}, + EvaluatedAt: now, + Published: map[string]time.Time{"1.0.0": now}, + }) + if string(out) != "" || kept != nil { + t.Errorf("FilterIndex = %q, %q; want nothing kept", out, kept) + } +} + +func TestPublishTimes(t *testing.T) { + body := `[ + {"number":"1.0.0","platform":"ruby","created_at":"2024-01-02T03:04:05Z"}, + {"number":"2.0.0","platform":"x86_64-linux","created_at":"2024-02-03T04:05:06.000Z"}, + {"number":"3.0.0","platform":"","created_at":"not a time"} + ]` + times, err := PublishTimes([]byte(body)) + if err != nil { + t.Fatal(err) + } + want := map[string]time.Time{ + "1.0.0": time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC), + "2.0.0-x86_64-linux": time.Date(2024, 2, 3, 4, 5, 6, 0, time.UTC), + "3.0.0": {}, + } + if len(times) != len(want) { + t.Fatalf("PublishTimes = %v, want %v", times, want) + } + for v, w := range want { + if got, ok := times[v]; !ok || !got.Equal(w) { + t.Errorf("PublishTimes[%q] = %v (%v), want %v", v, got, ok, w) + } + } + if _, err := PublishTimes([]byte("{")); err == nil { + t.Error("PublishTimes accepted invalid JSON") + } +} + +func TestFilenameIdentity(t *testing.T) { + tests := []struct{ filename, name, version string }{ + {"rails-7.1.0.gem", "rails", "7.1.0"}, + {"aws-sdk-s3-1.142.0.gem", "aws-sdk-s3", "1.142.0"}, + {"sorbet-static-0.5.11002-universal-darwin-22.gem", "sorbet-static", "0.5.11002-universal-darwin-22"}, + {"devise-2fa-1.0.0.gem", "devise-2fa", "1.0.0"}, + {"jruby-launcher-1.1.19-java.gem", "jruby-launcher", "1.1.19-java"}, + {"nokogiri-1.16.0-universal-java-17.gem", "nokogiri", "1.16.0-universal-java-17"}, + {"foo-1.0.0.pre.1.gem", "foo", "1.0.0.pre.1"}, + {"odd-1-+.gem", "odd", "1-+"}, + {"a-1-2-+.gem", "a", "1-2-+"}, + {"noversion.gem", "", ""}, + {"x" + strings.Repeat("-1", 300) + ".gem", "", ""}, + } + for _, tt := range tests { + name, version := FilenameIdentity(tt.filename) + if name != tt.name || version != tt.version { + t.Errorf("FilenameIdentity(%q) = (%q, %q), want (%q, %q)", tt.filename, name, version, tt.name, tt.version) + } + } +} + +func TestFilenameIdentityLengthBound(t *testing.T) { + name := strings.Repeat("a", maxFilenameLength-len("-1.0.gem")) + if n, v := FilenameIdentity(name + "-1.0.gem"); n != name || v != "1.0" { + t.Errorf("FilenameIdentity at the bound = (%q, %q)", n, v) + } + if n, v := FilenameIdentity(name + "a-1.0.gem"); n != "" || v != "" { + t.Errorf("FilenameIdentity past the bound = (%q, %q), want empty", n, v) + } +} diff --git a/internal/mirror/files.go b/internal/mirror/files.go index 92cb50a0..90b10ddc 100644 --- a/internal/mirror/files.go +++ b/internal/mirror/files.go @@ -10,6 +10,7 @@ import ( "github.com/git-pkgs/proxy/internal/database" "github.com/git-pkgs/proxy/internal/handler" + "github.com/git-pkgs/proxy/internal/metadata/gem" "github.com/git-pkgs/proxy/internal/metadata/pypi" "github.com/git-pkgs/registries" ) @@ -51,12 +52,12 @@ var fileEcosystems = map[string]fileEcosystem{ return map[string]string{"platform": gemArtifactPlatform(file)} }, cacheKey: func(_ PackageVersion, file registries.Artifact) (string, string, string, bool) { - name, version := handler.GemFilenameIdentity(file.Filename) + name, version := gem.FilenameIdentity(file.Filename) return name, version, file.Filename, name != "" }, variants: func(file registries.Artifact) []string { return []string{gemArtifactPlatform(file)} }, cachedVariants: func(cacheFilename string) []string { - _, version := handler.GemFilenameIdentity(cacheFilename) + _, version := gem.FilenameIdentity(cacheFilename) _, platform := gemVersionPlatform(version) return []string{platform} },