Skip to content

Commit

Permalink
fix match sort ordering for different locations (#1944)
Browse files Browse the repository at this point in the history
* introduce failing test: inconsistent location sorting

Signed-off-by: Dan Luhring <dluhring@chainguard.dev>

* fix: inconsistent matches sort ordering

Signed-off-by: Dan Luhring <dluhring@chainguard.dev>

---------

Signed-off-by: Dan Luhring <dluhring@chainguard.dev>
  • Loading branch information
luhring committed Jun 14, 2024
1 parent f994fe6 commit f599a66
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
29 changes: 23 additions & 6 deletions grype/match/matches_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package match
import (
"testing"

"github.com/anchore/syft/syft/file"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -104,20 +105,36 @@ func TestMatchesSortMixedDimensions(t *testing.T) {
},
},
Package: pkg.Package{
ID: pkg.ID(uuid.NewString()),
Name: "package-d",
Version: "2.0.0",
Type: syftPkg.RpmPkg,
ID: pkg.ID(uuid.NewString()),
Name: "package-d",
Version: "2.0.0",
Type: syftPkg.RpmPkg,
Locations: file.NewLocationSet(file.NewLocation("/some/first-path")),
},
}
ninth := Match{
Vulnerability: vulnerability.Vulnerability{
ID: "CVE-2020-0020",
Fix: vulnerability.Fix{
Versions: []string{"3.0.0"},
},
},
Package: pkg.Package{
ID: pkg.ID(uuid.NewString()),
Name: "package-d",
Version: "2.0.0",
Type: syftPkg.RpmPkg,
Locations: file.NewLocationSet(file.NewLocation("/some/other-path")),
},
}

input := []Match{
// shuffle vulnerability id, package name, package version, and package type
fifth, eighth, third, seventh, first, sixth, second, fourth,
ninth, fifth, eighth, third, seventh, first, sixth, second, fourth,
}
matches := NewMatches(input...)

assertMatchOrder(t, []Match{first, second, third, fourth, fifth, sixth, seventh, eighth}, matches.Sorted())
assertMatchOrder(t, []Match{first, second, third, fourth, fifth, sixth, seventh, eighth, ninth}, matches.Sorted())

}

Expand Down
15 changes: 15 additions & 0 deletions grype/match/sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ func (m ByElements) Less(i, j int) bool {
sort.Strings(fixVersions2)
fixStr1 := strings.Join(fixVersions1, ",")
fixStr2 := strings.Join(fixVersions2, ",")

if fixStr1 == fixStr2 {
loc1 := m[i].Package.Locations.ToSlice()
loc2 := m[j].Package.Locations.ToSlice()
var locStr1 string
for _, location := range loc1 {
locStr1 += location.String()
}
var locStr2 string
for _, location := range loc2 {
locStr2 += location.String()
}

return locStr1 < locStr2
}
return fixStr1 < fixStr2
}
return m[i].Package.Type < m[j].Package.Type
Expand Down

0 comments on commit f599a66

Please sign in to comment.