mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(grype): parse file sources and scan packages by purl
grype 0.121 prints source.target as a string for file, directory and purl sources. The parser expected an object and failed every scan. A bare npm, PyPI or Go archive holds nothing grype can catalog, so a scan of the archive read minimist 0.0.8 as clean. The scanner now passes a purl for these registries and falls back to the file for others.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
// Package gomodule maps a Go cache key to a module path.
|
||||
package gomodule
|
||||
|
||||
import "strings"
|
||||
|
||||
// Path returns the module path of a cache key "module/@v/version.zip", with the module proxy's
|
||||
// case encoding ("!a" is "A") reversed. A name without "/@v/" is taken as the module path.
|
||||
func Path(cacheKey string) string {
|
||||
module, _, _ := strings.Cut(cacheKey, "/@v/")
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(module); i++ {
|
||||
if module[i] == '!' && i+1 < len(module) {
|
||||
i++
|
||||
b.WriteString(strings.ToUpper(string(module[i])))
|
||||
continue
|
||||
}
|
||||
b.WriteByte(module[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package gomodule
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestPath(t *testing.T) {
|
||||
assert.Equal(t, "golang.org/x/text", Path("golang.org/x/text/@v/v0.3.5.zip"))
|
||||
assert.Equal(t, "github.com/Azure/go-x", Path("github.com/!azure/go-x/@v/v1.2.3.zip"))
|
||||
assert.Equal(t, "github.com/a/b/v2", Path("github.com/a/b/v2"))
|
||||
}
|
||||
+46
-16
@@ -3,14 +3,17 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -44,25 +47,25 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
Str("file", filePath).
|
||||
Msg("Starting Grype scan")
|
||||
|
||||
// Run grype scan
|
||||
cmd := exec.CommandContext(ctx, "grype", filePath, "-o", "json", "-q")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
// Grype returns non-zero exit code when vulnerabilities are found
|
||||
// Only treat it as error if we got no output
|
||||
if len(output) == 0 {
|
||||
return nil, fmt.Errorf("grype scan failed: %w (output: %s)", err, string(output))
|
||||
}
|
||||
target := purl(registry, packageName, version)
|
||||
if target == "" {
|
||||
target = filePath
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, "grype", target, "-o", "json", "-q") // #nosec G204 -- target is a purl or the stored artifact path
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, err := cmd.Output()
|
||||
if err != nil && len(output) == 0 {
|
||||
return nil, fmt.Errorf("grype scan failed: %w (stderr: %s)", err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
|
||||
// Parse Grype JSON output
|
||||
var grypeResult GrypeResult
|
||||
if err := json.Unmarshal(output, &grypeResult); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse grype output: %w", err)
|
||||
grypeResult, err := parse(output)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Convert to our format
|
||||
result := s.convertGrypeResult(&grypeResult, registry, packageName, version)
|
||||
result := s.convertGrypeResult(grypeResult, registry, packageName, version)
|
||||
|
||||
log.Info().
|
||||
Str("scanner", ScannerName).
|
||||
@@ -73,6 +76,33 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// purl names the package for grype. A bare npm, PyPI or Go archive has no lockfile or installed
|
||||
// metadata, so grype catalogs nothing in it and reports clean; a purl is matched against the
|
||||
// database directly. Empty means no purl can be built.
|
||||
func purl(registry, name, version string) string {
|
||||
if name == "" || version == "" {
|
||||
return ""
|
||||
}
|
||||
version = strings.ReplaceAll(version, "+", "%2B")
|
||||
switch registry {
|
||||
case "npm":
|
||||
return "pkg:npm/" + strings.Replace(name, "@", "%40", 1) + "@" + version
|
||||
case "go":
|
||||
return "pkg:golang/" + gomodule.Path(name) + "@" + version
|
||||
case "pypi":
|
||||
return "pkg:pypi/" + strings.ToLower(strings.NewReplacer("_", "-", ".", "-").Replace(name)) + "@" + version
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parse(output []byte) (*GrypeResult, error) {
|
||||
var res GrypeResult
|
||||
if err := json.Unmarshal(output, &res); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse grype output: %w", err)
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// Health checks if Grype is available
|
||||
func (s *Scanner) Health(ctx context.Context) error {
|
||||
cmd := exec.CommandContext(ctx, "grype", "version")
|
||||
@@ -166,8 +196,8 @@ type GrypeDescriptor struct {
|
||||
}
|
||||
|
||||
type GrypeSource struct {
|
||||
Target map[string]interface{} `json:"target"`
|
||||
Type string `json:"type"`
|
||||
Type string `json:"type"`
|
||||
Target json.RawMessage `json:"target"` // a string for file, directory and purl sources, an object for images
|
||||
}
|
||||
|
||||
type GrypeMatch struct {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The fixtures are real `grype -o json -q` output from grype 0.121.2 (see FINDINGS GH-25).
|
||||
func fixture(name string) string { return filepath.Join("testdata", name) }
|
||||
|
||||
func TestParseFileScanTargetIsAString(t *testing.T) {
|
||||
data, err := os.ReadFile(fixture("file-minimist-0.0.8.json"))
|
||||
require.NoError(t, err)
|
||||
|
||||
res, err := parse(data)
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "file", res.Source.Type)
|
||||
}
|
||||
|
||||
func TestScanMapsRealOutput(t *testing.T) {
|
||||
cases := []struct {
|
||||
wantSeverities map[string]string
|
||||
wantFixedIn map[string]string
|
||||
name, fixture, registry, pkg, version string
|
||||
wantPurl string
|
||||
wantStatus metadata.ScanStatus
|
||||
}{
|
||||
{
|
||||
name: "npm vulnerable", fixture: "purl-minimist-0.0.8.json", registry: "npm", pkg: "minimist", version: "0.0.8",
|
||||
wantPurl: "pkg:npm/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
|
||||
wantSeverities: map[string]string{"GHSA-xvch-5gv4-984h": "CRITICAL", "GHSA-vh95-rmgr-6w4m": "MODERATE"},
|
||||
wantFixedIn: map[string]string{"GHSA-xvch-5gv4-984h": "0.2.4"},
|
||||
},
|
||||
{
|
||||
name: "npm clean", fixture: "purl-dayjs-1.11.13.json", registry: "npm", pkg: "dayjs", version: "1.11.13",
|
||||
wantPurl: "pkg:npm/[email protected]", wantStatus: metadata.ScanStatusClean,
|
||||
},
|
||||
{
|
||||
name: "go vulnerable", fixture: "purl-go-text-0.3.5.json", registry: "go", pkg: "golang.org/x/text/@v/v0.3.5.zip", version: "v0.3.5",
|
||||
wantPurl: "pkg:golang/golang.org/x/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
|
||||
wantSeverities: map[string]string{"GHSA-69ch-w2m2-3vjp": "HIGH", "GO-2026-6629": "HIGH"},
|
||||
},
|
||||
{
|
||||
name: "pypi vulnerable", fixture: "purl-pypi-requests-2.19.0.json", registry: "pypi", pkg: "requests", version: "2.19.0",
|
||||
wantPurl: "pkg:pypi/[email protected]", wantStatus: metadata.ScanStatusVulnerable,
|
||||
wantSeverities: map[string]string{"GHSA-x84v-xcm2-53pg": "HIGH", "GHSA-j8r2-6x86-q33q": "MODERATE"},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
args := scannertest.Fake(t, "grype", fixture(tc.fixture), "", 0)
|
||||
|
||||
res, err := New(config.GrypeConfig{}).Scan(context.Background(), tc.registry, tc.pkg, tc.version, "/tmp/artifact")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.wantStatus, res.Status)
|
||||
assert.Equal(t, tc.wantPurl, scannertest.Args(t, args)[0], "the package is scanned by purl, not by its archive")
|
||||
got := map[string]string{}
|
||||
fixed := map[string]string{}
|
||||
for _, v := range res.Vulnerabilities {
|
||||
got[v.ID] = v.Severity
|
||||
fixed[v.ID] = v.FixedIn
|
||||
}
|
||||
for id, sev := range tc.wantSeverities {
|
||||
assert.Equal(t, sev, got[id], id)
|
||||
}
|
||||
for id, f := range tc.wantFixedIn {
|
||||
assert.Equal(t, f, fixed[id], id)
|
||||
}
|
||||
assert.Equal(t, len(res.Vulnerabilities), res.VulnerabilityCount)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanFallsBackToFileForUnknownRegistry(t *testing.T) {
|
||||
args := scannertest.Fake(t, "grype", fixture("file-minimist-0.0.8.json"), "", 0)
|
||||
|
||||
res, err := New(config.GrypeConfig{}).Scan(context.Background(), "docker", "x", "1", "/tmp/artifact.tar")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
assert.Equal(t, "/tmp/artifact.tar", scannertest.Args(t, args)[0])
|
||||
}
|
||||
|
||||
func TestScanIgnoresStderrNoise(t *testing.T) {
|
||||
scannertest.Fake(t, "grype", fixture("purl-dayjs-1.11.13.json"), "[0000] WARN something\n", 0)
|
||||
|
||||
res, err := New(config.GrypeConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", "/tmp/a.tgz")
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
}
|
||||
|
||||
func TestScanFailureWithoutOutputIsAnError(t *testing.T) {
|
||||
scannertest.Fake(t, "grype", "", "failed to load vulnerability db", 1)
|
||||
|
||||
_, err := New(config.GrypeConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", "/tmp/a.tgz")
|
||||
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "failed to load vulnerability db")
|
||||
}
|
||||
|
||||
func TestPurl(t *testing.T) {
|
||||
cases := []struct{ registry, name, version, want string }{
|
||||
{"npm", "left-pad", "1.3.0", "pkg:npm/[email protected]"},
|
||||
{"npm", "@babel/traverse", "7.0.0", "pkg:npm/%40babel/[email protected]"},
|
||||
{"go", "github.com/!azure/go-x/@v/v1.2.3.zip", "v1.2.3", "pkg:golang/github.com/Azure/[email protected]"},
|
||||
{"go", "github.com/a/b/v2/@v/v2.0.0+incompatible.zip", "v2.0.0+incompatible", "pkg:golang/github.com/a/b/[email protected]%2Bincompatible"},
|
||||
{"pypi", "Zope.Interface_x", "5.0", "pkg:pypi/[email protected]"},
|
||||
{"npm", "", "1", ""},
|
||||
{"npm", "x", "", ""},
|
||||
{"docker", "x", "1", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
assert.Equal(t, tc.want, purl(tc.registry, tc.name, tc.version), "%s %s", tc.registry, tc.name)
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user