From 906ff8640da5fa0a0750b6bfcc8d8718ae74713e Mon Sep 17 00:00:00 2001 From: Simon Chrzanowski Date: Mon, 23 Nov 2026 17:13:39 +0100 Subject: [PATCH] Extract portable Maven metadata transformations The maven-metadata.xml cooldown filter moves out of internal/handler into internal/metadata/maven: parsing the version list, , and with their offsets, removing versions in cooldown in place, and the coordinate and version helpers. The package takes the cooldown policy, the time it is evaluated at and a publish-time lookup explicitly, and reports held-back versions through OnWithheld. Publish times still come from the handler, looked up only as far as the filter asks. Cooldown is checked with Evaluate at one EvaluatedAt. --- internal/handler/maven_cooldown.go | 234 ++++------------ internal/metadata/maven/imports_test.go | 43 +++ internal/metadata/maven/metadata.go | 269 +++++++++++++++++++ internal/metadata/maven/metadata_test.go | 322 +++++++++++++++++++++++ 4 files changed, 680 insertions(+), 188 deletions(-) create mode 100644 internal/metadata/maven/imports_test.go create mode 100644 internal/metadata/maven/metadata.go create mode 100644 internal/metadata/maven/metadata_test.go diff --git a/internal/handler/maven_cooldown.go b/internal/handler/maven_cooldown.go index beccb703..c439f803 100644 --- a/internal/handler/maven_cooldown.go +++ b/internal/handler/maven_cooldown.go @@ -8,17 +8,16 @@ import ( "crypto/sha256" "crypto/sha512" "encoding/hex" - "encoding/xml" - "errors" "fmt" "hash" "io" "net/http" "net/url" "path" - "slices" "strings" "time" + + "github.com/git-pkgs/proxy/internal/metadata/maven" ) // Maven cooldown measures a version by the Last-Modified header of its .pom. @@ -42,10 +41,9 @@ const errMavenCooldown = "version is in cooldown" const mavenTimeUserAgent = "git-pkgs-proxy/1.0" const ( - mavenMetadataFile = "maven-metadata.xml" - mavenSnapshot = "-SNAPSHOT" - // mavenLastUpdatedLayout is the UTC timestamp format of . - mavenLastUpdatedLayout = "20060102150405" + mavenMetadataFile = maven.MetadataFile + mavenSnapshot = maven.Snapshot + mavenLastUpdatedLayout = maven.LastUpdatedLayout ) // mavenChecksums are the checksum files served beside maven-metadata.xml. @@ -62,23 +60,19 @@ func (h *MavenHandler) cooldownEnabled() bool { } func mavenPackagePURL(group, artifact string) string { - return canonicalPackagePURL("maven", group+":"+artifact) + return maven.PackagePURL(group, artifact) } // mavenCoordinates returns the group and artifact of an artifact directory -// such as com/google/guava/guava. +// such as com/google/guava/guava; see maven.Coordinates. func mavenCoordinates(artifactDir string) (group, artifact string, ok bool) { - i := strings.LastIndex(artifactDir, "/") - if i <= 0 || i == len(artifactDir)-1 { - return "", "", false - } - return strings.ReplaceAll(artifactDir[:i], "/", "."), artifactDir[i+1:], true + return maven.Coordinates(artifactDir) } // usableMavenVersion reports whether version can be put in a URL path as -// one segment. Versions come from upstream metadata. +// one segment; see maven.UsableVersion. func usableMavenVersion(version string) bool { - return version != "" && version != "." && version != ".." && !strings.ContainsAny(version, "/\\?#%") + return maven.UsableVersion(version) } // mavenTimeKey returns the versions-table PURLs a version's time is stored @@ -292,190 +286,54 @@ func (h *MavenHandler) serveCooldownMetadata(w http.ResponseWriter, r *http.Requ // filterMetadata removes versions in cooldown from an artifact's // maven-metadata.xml and points and at the newest -// versions left. Metadata without a version list, such as a group's plugin -// list or a SNAPSHOT's build list, is returned unchanged. The document is -// edited in place rather than encoded again, so everything else in it stays -// as upstream sent it. +// versions left; see maven.Filter. Times come from the versions table or +// the .pom's Last-Modified (publishTime), looked up only as far as +// maven.Filter asks. func (h *MavenHandler) filterMetadata(ctx context.Context, source mavenSource, artifactDir string, body []byte) ([]byte, error) { - doc, err := parseMavenMetadata(body) - if err != nil { - return nil, err - } - group, artifact, ok := mavenCoordinates(artifactDir) - if !ok || len(doc.versions) == 0 { - return body, nil - } - packagePURL := mavenPackagePURL(group, artifact) - // No version can be newer than the metadata listing it. - if lastUpdated, err := time.Parse(mavenLastUpdatedLayout, doc.lastUpdated); err == nil && - h.proxy.cooldown().IsAllowed("maven", packagePURL, lastUpdated) { - return body, nil - } - - removed := map[string]bool{} - for i := len(doc.versions) - 1; i >= 0; i-- { - v := doc.versions[i].value - if strings.HasSuffix(v, mavenSnapshot) { - continue - } - published, err := h.publishTime(ctx, source, artifactDir, v) - if err != nil { - return nil, fmt.Errorf("reading time of %s: %w", v, err) - } - if published.IsZero() { - continue - } - if h.proxy.cooldown().IsAllowed("maven", packagePURL, published) { - break - } - h.proxy.Logger.Info("cooldown: filtering maven version", "group", group, "artifact", artifact, "version", v) - removed[v] = true - // A named repository's times are its own, under PURLs that name it, - // and the package page shows the default repository's. - if source.name == "" { - h.proxy.recordWithheld("maven", group+":"+artifact, v, published) - } - } - if len(removed) == 0 { - return body, nil - } - return doc.without(body, removed), nil + group, artifact, _ := mavenCoordinates(artifactDir) + return maven.Filter(artifactDir, body, maven.Options{ + Cooldown: h.proxy.cooldown(), + EvaluatedAt: time.Now(), + PublishTime: func(version string) (time.Time, error) { + return h.publishTime(ctx, source, artifactDir, version) + }, + OnWithheld: func(version string, published time.Time) { + h.proxy.Logger.Info("cooldown: filtering maven version", "group", group, "artifact", artifact, "version", version) + // A named repository's times are its own, under PURLs that name + // it, and the package page shows the default repository's. + if source.name == "" { + h.proxy.recordWithheld("maven", group+":"+artifact, version, published) + } + }, + }) } -// mavenElement is an element of maven-metadata.xml: its text and where it -// starts and ends in the document. +// mavenElement is a version element read by parseMavenMetadata. type mavenElement struct { - value string - start, end int + value string } +// mavenMetadata is a parsed maven-metadata.xml; see maven.Metadata. type mavenMetadata struct { - versions []mavenElement - latest, release *mavenElement - lastUpdated string + doc *maven.Metadata + versions []mavenElement } -// parseMavenMetadata reads the version list, , and -// of a maven-metadata.xml, with their offsets. +// parseMavenMetadata reads a maven-metadata.xml; see maven.ParseMetadata. func parseMavenMetadata(body []byte) (*mavenMetadata, error) { - dec := xml.NewDecoder(bytes.NewReader(body)) - // Versions are ASCII, so any declared charset can be read as bytes. - dec.CharsetReader = func(_ string, in io.Reader) (io.Reader, error) { return in, nil } - - doc := &mavenMetadata{} - var stack []string - var current *mavenElement - for { - offset := int(dec.InputOffset()) - tok, err := dec.Token() - if errors.Is(err, io.EOF) { - break - } - if err != nil { - return nil, fmt.Errorf("parsing maven metadata: %w", err) - } - switch t := tok.(type) { - case xml.StartElement: - stack = append(stack, t.Name.Local) - switch strings.Join(stack, "/") { - case "metadata/versioning/versions/version", - "metadata/versioning/latest", - "metadata/versioning/release", - "metadata/versioning/lastUpdated": - current = &mavenElement{start: offset} - } - case xml.CharData: - if current != nil { - current.value += string(t) - } - case xml.EndElement: - if current != nil { - current.value = strings.TrimSpace(current.value) - current.end = int(dec.InputOffset()) - switch t.Name.Local { - case "version": - doc.versions = append(doc.versions, *current) - case "latest": - doc.latest = current - case "release": - doc.release = current - case "lastUpdated": - doc.lastUpdated = current.value - } - current = nil - } - if len(stack) > 0 { - stack = stack[:len(stack)-1] - } - } - } - return doc, nil -} - -// without returns body with the removed versions taken out of the version -// list, and and set to the last versions left in list -// order, which is how the repository chose them. Either is dropped when no -// version is left for it. -func (doc *mavenMetadata) without(body []byte, removed map[string]bool) []byte { - type edit struct { - start, end int - text string - } - var edits []edit - drop := func(e mavenElement) { - edits = append(edits, edit{start: lineStart(body, e.start), end: e.end}) - } - var latest, release string - for _, v := range doc.versions { - if removed[v.value] { - drop(v) - continue - } - latest = v.value - if !strings.HasSuffix(v.value, mavenSnapshot) { - release = v.value - } - } - for _, field := range []struct { - el *mavenElement - name string - next string - }{{doc.latest, "latest", latest}, {doc.release, "release", release}} { - if field.el == nil || !removed[field.el.value] { - continue - } - if field.next == "" { - drop(*field.el) - continue - } - edits = append(edits, edit{field.el.start, field.el.end, "<" + field.name + ">" + field.next + ""}) + doc, err := maven.ParseMetadata(body) + if err != nil { + return nil, err } - - // Edits don't overlap; apply them in document order. - slices.SortFunc(edits, func(a, b edit) int { return a.start - b.start }) - out := make([]byte, 0, len(body)) - pos := 0 - for _, e := range edits { - out = append(out, body[pos:e.start]...) - out = append(out, e.text...) - pos = e.end + m := &mavenMetadata{doc: doc} + for _, v := range doc.Versions { + m.versions = append(m.versions, mavenElement{value: v.Value}) } - return append(out, body[pos:]...) + return m, nil } -// lineStart moves an element's start back over the indentation and line -// break before it, so removing the element removes its line. -func lineStart(body []byte, start int) int { - i := start - for i > 0 && (body[i-1] == ' ' || body[i-1] == '\t') { - i-- - } - if i > 0 && body[i-1] == '\n' { - i-- - if i > 0 && body[i-1] == '\r' { - i-- - } - return i - } - return start +// without returns body without the removed versions; see +// maven.Metadata.Without. +func (m *mavenMetadata) without(body []byte, removed map[string]bool) []byte { + return m.doc.Without(body, removed) } diff --git a/internal/metadata/maven/imports_test.go b/internal/metadata/maven/imports_test.go new file mode 100644 index 00000000..a749397b --- /dev/null +++ b/internal/metadata/maven/imports_test.go @@ -0,0 +1,43 @@ +package maven + +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/maven", + "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/maven/metadata.go b/internal/metadata/maven/metadata.go new file mode 100644 index 00000000..82fc9dc5 --- /dev/null +++ b/internal/metadata/maven/metadata.go @@ -0,0 +1,269 @@ +// Package maven transforms Maven repository metadata without storage or +// network access. +package maven + +import ( + "bytes" + "encoding/xml" + "errors" + "fmt" + "io" + "slices" + "strings" + "time" + + "github.com/git-pkgs/cooldown" + "github.com/git-pkgs/proxy/internal/packageurl" +) + +const ecosystem = "maven" + +const ( + // MetadataFile is the name of an artifact's version list. + MetadataFile = "maven-metadata.xml" + // Snapshot ends the versions cooldown leaves alone: their files change + // after publishing. + Snapshot = "-SNAPSHOT" + // LastUpdatedLayout is the UTC timestamp format of . + LastUpdatedLayout = "20060102150405" +) + +// 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 publish times for a filter. EvaluatedAt +// is used as given; the transformation never reads the clock. +type Options struct { + Cooldown CooldownPolicy + EvaluatedAt time.Time + // PublishTime returns a version's publish time, the zero time when it + // is unknown, which lets the version through. It is called from the + // newest version back, only as far as versions can be in cooldown, so + // a caller can look times up lazily. An error ends the filter. + PublishTime func(version string) (time.Time, error) + // OnWithheld is called synchronously for each version cooldown holds + // back, with its publish time. + OnWithheld func(version string, publishedAt time.Time) +} + +// PackagePURL is the package PURL cooldown is evaluated for. +func PackagePURL(group, artifact string) string { + return packageurl.MakeString(ecosystem, group+":"+artifact, "") +} + +// Coordinates returns the group and artifact of an artifact directory such +// as com/google/guava/guava. +func Coordinates(artifactDir string) (group, artifact string, ok bool) { + i := strings.LastIndex(artifactDir, "/") + if i <= 0 || i == len(artifactDir)-1 { + return "", "", false + } + return strings.ReplaceAll(artifactDir[:i], "/", "."), artifactDir[i+1:], true +} + +// UsableVersion reports whether version can be put in a URL path as one +// segment. Versions come from upstream metadata. +func UsableVersion(version string) bool { + return version != "" && version != "." && version != ".." && !strings.ContainsAny(version, "/\\?#%") +} + +// Filter removes versions in cooldown from an artifact's maven-metadata.xml +// and points and at the newest versions left. Metadata +// without a version list, such as a group's plugin list or a SNAPSHOT's +// build list, and metadata for a directory that isn't an artifact's, is +// returned unchanged, as is everything when no enabled policy is set. The +// document is edited in place rather than encoded again, so everything +// else in it stays as upstream sent it. +// +// No version can be newer than the metadata listing it, so when +// is out of cooldown no time is looked up. Otherwise versions +// are checked from the end of the list back to the first that is old +// enough; SNAPSHOT versions are skipped. +func Filter(artifactDir string, body []byte, o Options) ([]byte, error) { + doc, err := ParseMetadata(body) + if err != nil { + return nil, err + } + group, artifact, ok := Coordinates(artifactDir) + if !ok || len(doc.Versions) == 0 || o.Cooldown == nil || !o.Cooldown.Enabled() { + return body, nil + } + packagePURL := PackagePURL(group, artifact) + if lastUpdated, err := time.Parse(LastUpdatedLayout, doc.LastUpdated); err == nil && o.allowed(packagePURL, lastUpdated) { + return body, nil + } + + removed := map[string]bool{} + for i := len(doc.Versions) - 1; i >= 0; i-- { + v := doc.Versions[i].Value + if strings.HasSuffix(v, Snapshot) { + continue + } + var published time.Time + if o.PublishTime != nil { + if published, err = o.PublishTime(v); err != nil { + return nil, fmt.Errorf("reading time of %s: %w", v, err) + } + } + if published.IsZero() { + continue + } + if o.allowed(packagePURL, published) { + break + } + removed[v] = true + if o.OnWithheld != nil { + o.OnWithheld(v, published) + } + } + if len(removed) == 0 { + return body, nil + } + return doc.Without(body, removed), nil +} + +func (o Options) allowed(packagePURL string, published time.Time) bool { + return o.Cooldown.Evaluate(ecosystem, packagePURL, published, o.EvaluatedAt).Allowed +} + +// Element is an element of maven-metadata.xml: its text and where it +// starts and ends in the document. +type Element struct { + Value string + Start, End int +} + +// Metadata is what ParseMetadata reads from a maven-metadata.xml. +type Metadata struct { + Versions []Element + Latest, Release *Element + LastUpdated string +} + +// ParseMetadata reads the version list, , and +// of a maven-metadata.xml, with their offsets. +func ParseMetadata(body []byte) (*Metadata, error) { + dec := xml.NewDecoder(bytes.NewReader(body)) + // Versions are ASCII, so any declared charset can be read as bytes. + dec.CharsetReader = func(_ string, in io.Reader) (io.Reader, error) { return in, nil } + + doc := &Metadata{} + var stack []string + var current *Element + for { + offset := int(dec.InputOffset()) + tok, err := dec.Token() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, fmt.Errorf("parsing maven metadata: %w", err) + } + switch t := tok.(type) { + case xml.StartElement: + stack = append(stack, t.Name.Local) + switch strings.Join(stack, "/") { + case "metadata/versioning/versions/version", + "metadata/versioning/latest", + "metadata/versioning/release", + "metadata/versioning/lastUpdated": + current = &Element{Start: offset} + } + case xml.CharData: + if current != nil { + current.Value += string(t) + } + case xml.EndElement: + if current != nil { + current.Value = strings.TrimSpace(current.Value) + current.End = int(dec.InputOffset()) + switch t.Name.Local { + case "version": + doc.Versions = append(doc.Versions, *current) + case "latest": + doc.Latest = current + case "release": + doc.Release = current + case "lastUpdated": + doc.LastUpdated = current.Value + } + current = nil + } + if len(stack) > 0 { + stack = stack[:len(stack)-1] + } + } + } + return doc, nil +} + +// Without returns body with the removed versions taken out of the version +// list, and and set to the last versions left in list +// order, which is how the repository chose them. Either is dropped when no +// version is left for it. +func (doc *Metadata) Without(body []byte, removed map[string]bool) []byte { + type edit struct { + start, end int + text string + } + var edits []edit + drop := func(e Element) { + edits = append(edits, edit{start: lineStart(body, e.Start), end: e.End}) + } + var latest, release string + for _, v := range doc.Versions { + if removed[v.Value] { + drop(v) + continue + } + latest = v.Value + if !strings.HasSuffix(v.Value, Snapshot) { + release = v.Value + } + } + for _, field := range []struct { + el *Element + name string + next string + }{{doc.Latest, "latest", latest}, {doc.Release, "release", release}} { + if field.el == nil || !removed[field.el.Value] { + continue + } + if field.next == "" { + drop(*field.el) + continue + } + edits = append(edits, edit{field.el.Start, field.el.End, "<" + field.name + ">" + field.next + ""}) + } + + // Edits don't overlap; apply them in document order. + slices.SortFunc(edits, func(a, b edit) int { return a.start - b.start }) + out := make([]byte, 0, len(body)) + pos := 0 + for _, e := range edits { + out = append(out, body[pos:e.start]...) + out = append(out, e.text...) + pos = e.end + } + return append(out, body[pos:]...) +} + +// lineStart moves an element's start back over the indentation and line +// break before it, so removing the element removes its line. +func lineStart(body []byte, start int) int { + i := start + for i > 0 && (body[i-1] == ' ' || body[i-1] == '\t') { + i-- + } + if i > 0 && body[i-1] == '\n' { + i-- + if i > 0 && body[i-1] == '\r' { + i-- + } + return i + } + return start +} diff --git a/internal/metadata/maven/metadata_test.go b/internal/metadata/maven/metadata_test.go new file mode 100644 index 00000000..15f9af70 --- /dev/null +++ b/internal/metadata/maven/metadata_test.go @@ -0,0 +1,322 @@ +package maven + +import ( + "errors" + "slices" + "strings" + "testing" + "time" + + "github.com/git-pkgs/cooldown" +) + +var now = time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) + +// windowPolicy holds back versions published within window of evaluatedAt. +type windowPolicy struct { + window time.Duration + disabled bool + purls []string + at []time.Time +} + +func (p *windowPolicy) Enabled() bool { return !p.disabled } + +func (p *windowPolicy) Evaluate(eco, packagePURL string, publishedAt, evaluatedAt time.Time) cooldown.Decision { + if eco != "maven" { + panic("ecosystem " + eco) + } + p.purls = append(p.purls, packagePURL) + p.at = append(p.at, evaluatedAt) + available := publishedAt.Add(p.window) + return cooldown.Decision{Allowed: !evaluatedAt.Before(available), AvailableAt: available} +} + +func metadataDoc(lastUpdated time.Time, latest, release string, versions ...string) string { + var b strings.Builder + b.WriteString("\n\n com.example\n lib\n \n") + b.WriteString(" " + latest + "\n " + release + "\n \n") + for _, v := range versions { + b.WriteString(" " + v + "\n") + } + b.WriteString(" \n " + lastUpdated.UTC().Format(LastUpdatedLayout) + "\n \n\n") + return b.String() +} + +func versionsOf(t *testing.T, body []byte) (versions []string, latest, release string) { + t.Helper() + doc, err := ParseMetadata(body) + if err != nil { + t.Fatalf("parse: %v\n%s", err, body) + } + for _, v := range doc.Versions { + versions = append(versions, v.Value) + } + if doc.Latest != nil { + latest = doc.Latest.Value + } + if doc.Release != nil { + release = doc.Release.Value + } + return versions, latest, release +} + +type timeSource struct { + times map[string]time.Time + asked []string + errFor string +} + +func (s *timeSource) lookup(version string) (time.Time, error) { + s.asked = append(s.asked, version) + if version == s.errFor { + return time.Time{}, errors.New("rate limited") + } + return s.times[version], nil +} + +func TestFilterRemovesNewestVersionsInCooldown(t *testing.T) { + src := &timeSource{times: map[string]time.Time{ + "1.0": now.Add(-30 * 24 * time.Hour), + "1.1": now.Add(-10 * 24 * time.Hour), + "1.2": now.Add(-2 * 24 * time.Hour), + "1.3": now.Add(-time.Hour), + }} + policy := &windowPolicy{window: 3 * 24 * time.Hour} + var withheld []string + body := metadataDoc(now.Add(-time.Hour), "1.3", "1.3", "1.0", "1.1", "1.2", "1.3") + out, err := Filter("com/example/lib", []byte(body), Options{ + Cooldown: policy, + EvaluatedAt: now, + PublishTime: src.lookup, + OnWithheld: func(version string, published time.Time) { + if !published.Equal(src.times[version]) { + t.Errorf("OnWithheld(%s) published = %v", version, published) + } + withheld = append(withheld, version) + }, + }) + if err != nil { + t.Fatal(err) + } + versions, latest, release := versionsOf(t, out) + if !slices.Equal(versions, []string{"1.0", "1.1"}) || latest != "1.1" || release != "1.1" { + t.Errorf("versions %v latest %q release %q", versions, latest, release) + } + if !slices.Equal(withheld, []string{"1.3", "1.2"}) { + t.Errorf("withheld %v", withheld) + } + // Lookups stop at the first version old enough. + if !slices.Equal(src.asked, []string{"1.3", "1.2", "1.1"}) { + t.Errorf("asked %v", src.asked) + } + for _, purl := range policy.purls { + if purl != "pkg:maven/com.example/lib" { + t.Errorf("evaluated for %q", purl) + } + } + for _, at := range policy.at { + if !at.Equal(now) { + t.Errorf("evaluated at %v, want EvaluatedAt", at) + } + } + if strings.Contains(string(out), "1.2") || !strings.Contains(string(out), "com.example") { + t.Errorf("unexpected output:\n%s", out) + } +} + +func TestFilterSkipsLookupsWhenLastUpdatedIsOld(t *testing.T) { + src := &timeSource{} + body := metadataDoc(now.Add(-10*24*time.Hour), "1.1", "1.1", "1.0", "1.1") + out, err := Filter("com/example/lib", []byte(body), Options{ + Cooldown: &windowPolicy{window: 3 * 24 * time.Hour}, EvaluatedAt: now, PublishTime: src.lookup, + }) + if err != nil || string(out) != body { + t.Fatalf("got %q, %v", out, err) + } + if len(src.asked) != 0 { + t.Errorf("asked %v", src.asked) + } +} + +func TestFilterReadsTimesWhenLastUpdatedIsUnreadable(t *testing.T) { + src := &timeSource{times: map[string]time.Time{"1.1": now}} + body := strings.Replace(metadataDoc(now, "1.1", "1.1", "1.0", "1.1"), now.Format(LastUpdatedLayout), "soon", 1) + out, err := Filter("com/example/lib", []byte(body), Options{ + Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now, PublishTime: src.lookup, + }) + if err != nil { + t.Fatal(err) + } + if versions, _, _ := versionsOf(t, out); !slices.Equal(versions, []string{"1.0"}) { + t.Errorf("versions %v", versions) + } +} + +func TestFilterLeavesSnapshotsAndUnknownTimes(t *testing.T) { + src := &timeSource{times: map[string]time.Time{ + "1.0": now.Add(-time.Hour), + "2.0": now.Add(-time.Hour), + }} + body := metadataDoc(now, "2.1-SNAPSHOT", "2.0", "1.0", "1.1", "2.0", "2.1-SNAPSHOT") + out, err := Filter("com/example/lib", []byte(body), Options{ + Cooldown: &windowPolicy{window: 24 * time.Hour}, EvaluatedAt: now, PublishTime: src.lookup, + }) + if err != nil { + t.Fatal(err) + } + versions, latest, release := versionsOf(t, out) + if !slices.Equal(versions, []string{"1.1", "2.1-SNAPSHOT"}) { + t.Errorf("versions %v", versions) + } + if latest != "2.1-SNAPSHOT" || release != "1.1" { + t.Errorf("latest %q release %q", latest, release) + } + // 1.1 has no time and is let through without ending the walk. + if !slices.Equal(src.asked, []string{"2.0", "1.1", "1.0"}) { + t.Errorf("asked %v", src.asked) + } +} + +func TestFilterLookupError(t *testing.T) { + src := &timeSource{errFor: "1.1"} + body := metadataDoc(now, "1.1", "1.1", "1.0", "1.1") + _, err := Filter("com/example/lib", []byte(body), Options{ + Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now, PublishTime: src.lookup, + }) + if err == nil || !strings.Contains(err.Error(), "reading time of 1.1: rate limited") { + t.Fatalf("err = %v", err) + } +} + +func TestFilterUnchanged(t *testing.T) { + recent := metadataDoc(now, "1.0", "1.0", "1.0") + allNew := func(string) (time.Time, error) { return now, nil } + plugins := `x` + for _, tc := range []struct { + name, dir, body string + o Options + }{ + {"no policy", "com/example/lib", recent, Options{EvaluatedAt: now, PublishTime: allNew}}, + {"disabled policy", "com/example/lib", recent, Options{Cooldown: &windowPolicy{window: time.Hour, disabled: true}, EvaluatedAt: now, PublishTime: allNew}}, + {"not an artifact directory", "lib", recent, Options{Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now, PublishTime: allNew}}, + {"trailing slash", "com/example/", recent, Options{Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now, PublishTime: allNew}}, + {"no version list", "com/example", plugins, Options{Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now, PublishTime: allNew}}, + {"no time source", "com/example/lib", recent, Options{Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now}}, + {"all old enough", "com/example/lib", recent, Options{Cooldown: &windowPolicy{window: time.Hour}, EvaluatedAt: now.Add(2 * time.Hour), PublishTime: allNew}}, + } { + t.Run(tc.name, func(t *testing.T) { + out, err := Filter(tc.dir, []byte(tc.body), tc.o) + if err != nil || string(out) != tc.body { + t.Errorf("got %q, %v", out, err) + } + }) + } +} + +func TestFilterRefusesMalformedMetadata(t *testing.T) { + if _, err := Filter("com/example/lib", []byte(""), Options{}); err == nil { + t.Error("want an error") + } + if _, err := ParseMetadata([]byte("")); err == nil { + t.Error("want an error") + } +} + +func TestWithoutDropsLatestAndReleaseWhenNothingIsLeft(t *testing.T) { + in := "\r\n\r\n\t1\r\n\t1\r\n\t\r\n\t\t1\r\n\t\r\n\r\n" + doc, err := ParseMetadata([]byte(in)) + if err != nil { + t.Fatal(err) + } + got := string(doc.Without([]byte(in), map[string]bool{"1": true})) + want := "\r\n\r\n\t\r\n\t\r\n\r\n" + if got != want { + t.Errorf("got %q\nwant %q", got, want) + } +} + +func TestWithoutKeepsLatestAndReleaseNotRemoved(t *testing.T) { + in := `321234` + doc, err := ParseMetadata([]byte(in)) + if err != nil { + t.Fatal(err) + } + got := string(doc.Without([]byte(in), map[string]bool{"4": true})) + want := `32123` + if got != want { + t.Errorf("got %s\nwant %s", got, want) + } +} + +func TestParseMetadataIgnoresElementsElsewhere(t *testing.T) { + in := `9 1 20260101000000x` + doc, err := ParseMetadata([]byte(in)) + if err != nil { + t.Fatal(err) + } + if len(doc.Versions) != 1 || doc.Versions[0].Value != "1" || doc.Latest != nil || doc.LastUpdated != "20260101000000" { + t.Errorf("doc = %+v", doc) + } + if got := in[doc.Versions[0].Start:doc.Versions[0].End]; got != " 1 " { + t.Errorf("offsets cover %q", got) + } +} + +func TestParseMetadataReadsAnyCharset(t *testing.T) { + in := `1` + doc, err := ParseMetadata([]byte(in)) + if err != nil || len(doc.Versions) != 1 { + t.Fatalf("doc %+v, err %v", doc, err) + } +} + +func TestLineStart(t *testing.T) { + for _, tc := range []struct { + body string + start int + want int + }{ + {"a\n ", 4, 1}, + {"a\r\n\t", 4, 1}, + {"a ", 2, 2}, + {" ", 2, 2}, + {"\n", 1, 0}, + } { + if got := lineStart([]byte(tc.body), tc.start); got != tc.want { + t.Errorf("lineStart(%q, %d) = %d, want %d", tc.body, tc.start, got, tc.want) + } + } +} + +func TestCoordinates(t *testing.T) { + for _, tc := range []struct { + dir, group, artifact string + ok bool + }{ + {"com/google/guava/guava", "com.google.guava", "guava", true}, + {"junit/junit", "junit", "junit", true}, + {"guava", "", "", false}, + {"/guava", "", "", false}, + {"com/google/", "", "", false}, + } { + group, artifact, ok := Coordinates(tc.dir) + if group != tc.group || artifact != tc.artifact || ok != tc.ok { + t.Errorf("Coordinates(%q) = %q, %q, %v", tc.dir, group, artifact, ok) + } + } + if got := PackagePURL("com.google.guava", "guava"); got != "pkg:maven/com.google.guava/guava" { + t.Errorf("PackagePURL = %q", got) + } +} + +func TestUsableVersion(t *testing.T) { + for v, want := range map[string]bool{ + "1.0": true, "1.0-SNAPSHOT": true, "": false, ".": false, "..": false, + "1/2": false, `1\2`: false, "1?": false, "1#": false, "1%2F": false, + } { + if got := UsableVersion(v); got != want { + t.Errorf("UsableVersion(%q) = %v", v, got) + } + } +}