mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(npm-audit): audit the package through a wrapper project
npm 11 prints via as an array and metadata.dependencies as an object, so the parser failed on every report. It now reads both shapes of via and lists each advisory once. The lockfile step resolved devDependencies, which took 28 seconds for dayjs and reported 142 findings in its development tree. The tarball is now the only dependency of a wrapper project, audited with --omit=dev. This also audits the package itself, which npm audit skips for a root.
This commit is contained in:
+151
-107
@@ -3,16 +3,20 @@
|
||||
package npmaudit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -63,71 +67,60 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
Str("version", version).
|
||||
Msg("Starting npm audit scan")
|
||||
|
||||
// Create a temporary directory
|
||||
tmpDir, err := os.MkdirTemp("", "npm-audit-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
|
||||
// Extract the .tgz file
|
||||
if err := s.extractTgz(filePath, tmpDir); err != nil {
|
||||
return nil, fmt.Errorf("failed to extract tgz: %w", err)
|
||||
if err = writeWrapper(tmpDir, packageName, filePath); err != nil {
|
||||
return s.scanErrorResult(ctx, registry, packageName, version, fmt.Sprintf("prepare audit project: %v", err), ""), nil
|
||||
}
|
||||
|
||||
// Find the package directory (usually "package/")
|
||||
packageDir := filepath.Join(tmpDir, "package")
|
||||
if _, err := os.Stat(packageDir); os.IsNotExist(err) {
|
||||
// Try the tmpDir itself
|
||||
packageDir = tmpDir
|
||||
}
|
||||
|
||||
// npm tarballs ship only package.json — there is no lockfile. We must
|
||||
// generate one before `npm audit` can resolve the dependency tree.
|
||||
// NOTE: this performs network egress (npm registry lookups for
|
||||
// transitive deps). Acceptable here because the scanner runs server-
|
||||
// side and the operator already trusts upstream resolution to cache
|
||||
// the package; we use --ignore-scripts to avoid running install hooks.
|
||||
// npm audit needs a lockfile and a tarball ships none. The tarball is installed into a
|
||||
// wrapper project, so its own advisories are audited with its production dependencies, and
|
||||
// its devDependencies are never resolved. This step reaches the npm registry.
|
||||
log.Info().
|
||||
Str("scanner", ScannerName).
|
||||
Str("package", packageName).
|
||||
Msg("Generating package-lock.json for npm audit (network egress)")
|
||||
|
||||
installCmd := exec.CommandContext(ctx, "npm", "install",
|
||||
installCmd := exec.CommandContext(ctx, "npm", "install", // #nosec G204 -- fixed args
|
||||
"--package-lock-only",
|
||||
"--omit=dev",
|
||||
"--ignore-scripts",
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
)
|
||||
installCmd.Dir = packageDir
|
||||
if installOut, err := installCmd.CombinedOutput(); err != nil {
|
||||
installCmd.Dir = tmpDir
|
||||
if installOut, installErr := installCmd.CombinedOutput(); installErr != nil {
|
||||
log.Warn().
|
||||
Err(err).
|
||||
Err(installErr).
|
||||
Str("package", packageName).
|
||||
Str("output", string(installOut)).
|
||||
Msg("npm install --package-lock-only failed; returning scan-error")
|
||||
return s.scanErrorResult(registry, packageName, version,
|
||||
fmt.Sprintf("npm install --package-lock-only failed: %v", err)), nil
|
||||
return s.scanErrorResult(ctx, registry, packageName, version,
|
||||
fmt.Sprintf("npm install --package-lock-only failed: %v", installErr), string(installOut)), nil
|
||||
}
|
||||
|
||||
// Run npm audit against the freshly generated lockfile.
|
||||
cmd := exec.CommandContext(ctx, "npm", "audit", "--json")
|
||||
cmd.Dir = packageDir
|
||||
output, _ := cmd.CombinedOutput() // npm audit returns non-zero when vulns found
|
||||
cmd := exec.CommandContext(ctx, "npm", "audit", "--omit=dev", "--json") // #nosec G204 -- fixed args
|
||||
cmd.Dir = tmpDir
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // npm audit exits non-zero when it finds vulnerabilities
|
||||
|
||||
// Parse npm audit output
|
||||
var auditResult NpmAuditResult
|
||||
if len(output) > 0 {
|
||||
if err := json.Unmarshal(output, &auditResult); err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to parse npm audit output")
|
||||
// Parse failure means we couldn't determine vulnerability state — fail closed.
|
||||
return s.scanErrorResult(registry, packageName, version,
|
||||
fmt.Sprintf("failed to parse npm audit output: %v", err)), nil
|
||||
}
|
||||
auditResult, err := parse(output)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Msg("Failed to parse npm audit output")
|
||||
return s.scanErrorResult(ctx, registry, packageName, version,
|
||||
fmt.Sprintf("failed to parse npm audit output: %v", err), stderr.String()), nil
|
||||
}
|
||||
if auditResult.Error != nil {
|
||||
return s.scanErrorResult(ctx, registry, packageName, version,
|
||||
fmt.Sprintf("npm audit failed: %s %s", auditResult.Error.Code, auditResult.Error.Summary), stderr.String()), nil
|
||||
}
|
||||
|
||||
// Convert to our format
|
||||
result := s.convertResult(&auditResult, registry, packageName, version)
|
||||
result := s.convertResult(auditResult, registry, packageName, version)
|
||||
|
||||
log.Info().
|
||||
Str("scanner", ScannerName).
|
||||
@@ -138,6 +131,44 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// wrapperTarball is the archive's name inside the wrapper project.
|
||||
const wrapperTarball = "artifact.tgz"
|
||||
|
||||
// writeWrapper makes dir a project whose only dependency is the archive.
|
||||
func writeWrapper(dir, packageName, archive string) error {
|
||||
src, err := os.Open(archive) // #nosec G304 -- path from the cache, not user input
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = src.Close() }()
|
||||
root, err := os.OpenRoot(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = root.Close() }()
|
||||
dst, err := root.Create(wrapperTarball)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = io.Copy(dst, src); err != nil {
|
||||
_ = dst.Close()
|
||||
return err
|
||||
}
|
||||
if err = dst.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
manifest, err := json.Marshal(map[string]interface{}{
|
||||
"name": "gohoarder-audit",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"dependencies": map[string]string{packageName: "file:./" + wrapperTarball},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return root.WriteFile("package.json", manifest, 0o600)
|
||||
}
|
||||
|
||||
// Health checks if npm is available
|
||||
func (s *Scanner) Health(ctx context.Context) error {
|
||||
cmd := exec.CommandContext(ctx, "npm", "--version")
|
||||
@@ -147,18 +178,11 @@ func (s *Scanner) Health(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// extractTgz extracts a .tgz file
|
||||
func (s *Scanner) extractTgz(tgzPath, destDir string) error {
|
||||
cmd := exec.Command("tar", "-xzf", tgzPath, "-C", destDir)
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// emptyResult returns an empty scan result
|
||||
|
||||
// scanErrorResult returns a result marked as scan-error so the manager merge
|
||||
// and CheckVulnerabilities can fail closed. Use this when the scan could not
|
||||
// complete and we therefore have no signal about vulnerabilities.
|
||||
func (s *Scanner) scanErrorResult(registry, packageName, version, reason string) *metadata.ScanResult {
|
||||
// scanErrorResult returns a result marked scan-error. The manager leaves it out of the merge
|
||||
// and counts it as an infrastructure failure when the context ended or the tool output shows
|
||||
// the network was unreachable.
|
||||
func (s *Scanner) scanErrorResult(ctx context.Context, registry, packageName, version, reason, toolOutput string) *metadata.ScanResult {
|
||||
infra := ctx.Err() != nil || scanerr.NetworkFailure(toolOutput)
|
||||
return &metadata.ScanResult{
|
||||
ID: uuid.New().String(),
|
||||
Registry: registry,
|
||||
@@ -169,9 +193,7 @@ func (s *Scanner) scanErrorResult(registry, packageName, version, reason string)
|
||||
Status: metadata.ScanStatusError,
|
||||
VulnerabilityCount: 0,
|
||||
Vulnerabilities: []metadata.Vulnerability{},
|
||||
Details: map[string]interface{}{
|
||||
"error": reason,
|
||||
},
|
||||
Details: scanerr.ErrorDetails(reason, infra),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,37 +202,35 @@ func (s *Scanner) convertResult(auditResult *NpmAuditResult, registry, packageNa
|
||||
vulnerabilities := make([]metadata.Vulnerability, 0)
|
||||
severityCounts := make(map[string]int)
|
||||
|
||||
// Process vulnerabilities from the audit result
|
||||
for _, vuln := range auditResult.Vulnerabilities {
|
||||
// Normalize severity
|
||||
normalizedSeverity := metadata.NormalizeSeverity(vuln.Severity)
|
||||
severityCounts[normalizedSeverity]++
|
||||
|
||||
// Get references
|
||||
refs := make([]string, 0)
|
||||
if vuln.URL != "" {
|
||||
refs = append(refs, vuln.URL)
|
||||
}
|
||||
for _, ref := range vuln.References {
|
||||
if ref.URL != "" {
|
||||
refs = append(refs, ref.URL)
|
||||
// Each advisory is listed once, under the package it affects. A string in `via` only says
|
||||
// that the package is affected through another one, whose own entry lists the advisory.
|
||||
seen := make(map[int]bool)
|
||||
names := make([]string, 0, len(auditResult.Vulnerabilities))
|
||||
for name := range auditResult.Vulnerabilities {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
for _, via := range auditResult.Vulnerabilities[name].Via {
|
||||
adv := via.Advisory
|
||||
if adv == nil || seen[adv.Source] {
|
||||
continue
|
||||
}
|
||||
seen[adv.Source] = true
|
||||
normalizedSeverity := metadata.NormalizeSeverity(adv.Severity)
|
||||
severityCounts[normalizedSeverity]++
|
||||
refs := make([]string, 0, 1)
|
||||
if adv.URL != "" {
|
||||
refs = append(refs, adv.URL)
|
||||
}
|
||||
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
|
||||
ID: advisoryID(adv),
|
||||
Severity: normalizedSeverity,
|
||||
Title: adv.Title,
|
||||
Description: fmt.Sprintf("%s: %s (affected %s)", adv.Name, adv.Title, adv.Range),
|
||||
References: refs,
|
||||
})
|
||||
}
|
||||
|
||||
// Get fixed version
|
||||
fixedIn := ""
|
||||
if vuln.FixAvailable != nil {
|
||||
fixedIn = fmt.Sprintf("%v", vuln.FixAvailable)
|
||||
}
|
||||
|
||||
vulnerabilities = append(vulnerabilities, metadata.Vulnerability{
|
||||
ID: vuln.Via,
|
||||
Severity: normalizedSeverity,
|
||||
Title: vuln.Name,
|
||||
Description: vuln.Name,
|
||||
References: refs,
|
||||
FixedIn: fixedIn,
|
||||
})
|
||||
}
|
||||
|
||||
status := metadata.ScanStatusClean
|
||||
@@ -234,38 +254,62 @@ func (s *Scanner) convertResult(auditResult *NpmAuditResult, registry, packageNa
|
||||
}
|
||||
}
|
||||
|
||||
// NpmAuditResult represents npm audit JSON output
|
||||
// advisoryID is the GHSA id from the advisory URL, or the npm advisory number.
|
||||
func advisoryID(adv *NpmAdvisory) string {
|
||||
if i := strings.LastIndex(adv.URL, "/"); i >= 0 && i+1 < len(adv.URL) {
|
||||
return adv.URL[i+1:]
|
||||
}
|
||||
return fmt.Sprintf("npm:%d", adv.Source)
|
||||
}
|
||||
|
||||
func parse(output []byte) (*NpmAuditResult, error) {
|
||||
var res NpmAuditResult
|
||||
if err := json.Unmarshal(output, &res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// NpmAuditResult represents `npm audit --json` output (auditReportVersion 2), or its error document.
|
||||
type NpmAuditResult struct {
|
||||
Vulnerabilities map[string]NpmVulnerability `json:"vulnerabilities"`
|
||||
Metadata NpmAuditMetadata `json:"metadata"`
|
||||
AuditReportVersion int `json:"auditReportVersion"`
|
||||
Vulnerabilities map[string]NpmVulnerability `json:"vulnerabilities"`
|
||||
Error *NpmAuditError `json:"error"`
|
||||
}
|
||||
|
||||
// NpmAuditError is the document npm prints in place of a report, e.g. ENOLOCK.
|
||||
type NpmAuditError struct {
|
||||
Code string `json:"code"`
|
||||
Summary string `json:"summary"`
|
||||
}
|
||||
|
||||
// NpmVulnerability is one affected package.
|
||||
type NpmVulnerability struct {
|
||||
Name string `json:"name"`
|
||||
Severity string `json:"severity"`
|
||||
Via string `json:"via"`
|
||||
Effects []string `json:"effects"`
|
||||
Range string `json:"range"`
|
||||
FixAvailable interface{} `json:"fixAvailable"`
|
||||
URL string `json:"url"`
|
||||
References []NpmReference `json:"references"`
|
||||
Name string `json:"name"`
|
||||
Severity string `json:"severity"`
|
||||
Via []NpmVia `json:"via"`
|
||||
}
|
||||
|
||||
type NpmReference struct {
|
||||
URL string `json:"url"`
|
||||
// NpmVia is a package name (affected through that package) or an advisory.
|
||||
type NpmVia struct {
|
||||
Advisory *NpmAdvisory
|
||||
Package string
|
||||
}
|
||||
|
||||
type NpmAuditMetadata struct {
|
||||
Vulnerabilities NpmVulnCounts `json:"vulnerabilities"`
|
||||
Dependencies int `json:"dependencies"`
|
||||
// UnmarshalJSON accepts both shapes of an element of `via`.
|
||||
func (v *NpmVia) UnmarshalJSON(data []byte) error {
|
||||
if len(data) > 0 && data[0] == '"' {
|
||||
return json.Unmarshal(data, &v.Package)
|
||||
}
|
||||
v.Advisory = &NpmAdvisory{}
|
||||
return json.Unmarshal(data, v.Advisory)
|
||||
}
|
||||
|
||||
type NpmVulnCounts struct {
|
||||
Info int `json:"info"`
|
||||
Low int `json:"low"`
|
||||
Moderate int `json:"moderate"`
|
||||
High int `json:"high"`
|
||||
Critical int `json:"critical"`
|
||||
Total int `json:"total"`
|
||||
// NpmAdvisory is a security advisory attached to a package.
|
||||
type NpmAdvisory struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Severity string `json:"severity"`
|
||||
Range string `json:"range"`
|
||||
Source int `json:"source"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
package npmaudit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The fixtures are real `npm audit --json` output from npm 11.12.1 (see FINDINGS GH-25).
|
||||
func fixture(name string) string { return filepath.Join("testdata", name) }
|
||||
|
||||
func readFixture(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(fixture(name))
|
||||
require.NoError(t, err)
|
||||
return data
|
||||
}
|
||||
|
||||
func severities(res *metadata.ScanResult) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, v := range res.Vulnerabilities {
|
||||
out[v.ID] = v.Severity
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestParseKeepsBothViaShapes(t *testing.T) {
|
||||
// `via` is an array of package names for a transitive finding and an array of advisory
|
||||
// objects for a direct one; mkdirp-0.5.1.json has both, the dev-tree file many of each.
|
||||
for _, name := range []string{"dayjs-1.11.13.json", "minimist-0.0.8.json", "mkdirp-0.5.1.json", "request-2.88.2.json", "mkdirp-0.5.1-dev-tree.json"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, err := parse(readFixture(t, name))
|
||||
require.NoError(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertMapsAdvisories(t *testing.T) {
|
||||
cases := []struct {
|
||||
want map[string]string
|
||||
fixture string
|
||||
}{
|
||||
{fixture: "dayjs-1.11.13.json", want: map[string]string{}},
|
||||
{fixture: "minimist-0.0.8.json", want: map[string]string{"GHSA-vh95-rmgr-6w4m": "MODERATE", "GHSA-xvch-5gv4-984h": "CRITICAL"}},
|
||||
// mkdirp has no advisory of its own: its entry only points at minimist.
|
||||
{fixture: "mkdirp-0.5.1.json", want: map[string]string{"GHSA-vh95-rmgr-6w4m": "MODERATE", "GHSA-xvch-5gv4-984h": "CRITICAL"}},
|
||||
{fixture: "request-2.88.2.json", want: map[string]string{
|
||||
"GHSA-fjxv-7rqg-78g4": "CRITICAL", "GHSA-hmw2-7cc7-3qxx": "HIGH", "GHSA-6rw7-vpxm-498p": "MODERATE",
|
||||
"GHSA-4mjr-xmp4-gh2g": "MODERATE", "GHSA-p8p7-x288-28g6": "MODERATE", "GHSA-72xf-g2v4-qvf3": "MODERATE",
|
||||
"GHSA-w5hq-g745-h8pq": "MODERATE",
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.fixture, func(t *testing.T) {
|
||||
audit, err := parse(readFixture(t, tc.fixture))
|
||||
require.NoError(t, err)
|
||||
|
||||
res := New(config.NpmAuditConfig{}).convertResult(audit, "npm", "p", "1")
|
||||
|
||||
assert.Equal(t, tc.want, severities(res))
|
||||
assert.Equal(t, len(tc.want), res.VulnerabilityCount)
|
||||
if len(tc.want) == 0 {
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
} else {
|
||||
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertCarriesTitleAndReference(t *testing.T) {
|
||||
audit, err := parse(readFixture(t, "minimist-0.0.8.json"))
|
||||
require.NoError(t, err)
|
||||
|
||||
res := New(config.NpmAuditConfig{}).convertResult(audit, "npm", "minimist", "0.0.8")
|
||||
|
||||
ids := make([]string, 0)
|
||||
for _, v := range res.Vulnerabilities {
|
||||
ids = append(ids, v.ID)
|
||||
assert.Equal(t, "Prototype Pollution in minimist", v.Title)
|
||||
assert.Equal(t, []string{"https://github.com/advisories/" + v.ID}, v.References)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
assert.Equal(t, []string{"GHSA-vh95-rmgr-6w4m", "GHSA-xvch-5gv4-984h"}, ids)
|
||||
}
|
||||
|
||||
// npmScript fakes npm: `install` exits installExit, `audit` prints stdout and exits 1.
|
||||
func npmScript(t *testing.T, auditFixture string, installExit int, installStderr string) (recDir string) {
|
||||
t.Helper()
|
||||
recDir = t.TempDir()
|
||||
audit := "cat " + fmt.Sprintf("%q", mustAbs(t, auditFixture))
|
||||
if auditFixture == "" {
|
||||
audit = "printf '%s' 'not json'"
|
||||
}
|
||||
scannertest.Script(t, "npm", fmt.Sprintf(`
|
||||
case "$1" in
|
||||
install) cat package.json > %[1]q/package.json; echo "$@" > %[1]q/install; printf '%%s' %[2]q >&2; exit %[3]d ;;
|
||||
audit) echo "$@" > %[1]q/audit; %[4]s; exit 1 ;;
|
||||
esac`, recDir, installStderr, installExit, audit))
|
||||
return recDir
|
||||
}
|
||||
|
||||
func mustAbs(t *testing.T, name string) string {
|
||||
t.Helper()
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
abs, err := filepath.Abs(fixture(name))
|
||||
require.NoError(t, err)
|
||||
return abs
|
||||
}
|
||||
|
||||
func artifact(t *testing.T) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(t.TempDir(), "pkg.tgz")
|
||||
require.NoError(t, os.WriteFile(p, []byte("tgz"), 0o600))
|
||||
return p
|
||||
}
|
||||
|
||||
func TestScanAuditsThePackageItselfWithoutItsDevTree(t *testing.T) {
|
||||
rec := npmScript(t, "minimist-0.0.8.json", 0, "")
|
||||
|
||||
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "minimist", "0.0.8", artifact(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
|
||||
assert.Len(t, res.Vulnerabilities, 2)
|
||||
|
||||
pkgJSON, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
var wrapper struct {
|
||||
Dependencies map[string]string `json:"dependencies"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(pkgJSON, &wrapper))
|
||||
assert.Equal(t, map[string]string{"minimist": "file:./artifact.tgz"}, wrapper.Dependencies,
|
||||
"the tarball is a dependency of a wrapper project, so its own advisories are audited and its devDependencies are never resolved")
|
||||
|
||||
audit, err := os.ReadFile(filepath.Join(rec, "audit")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(audit), "--omit=dev")
|
||||
}
|
||||
|
||||
func TestScanCleanPackage(t *testing.T) {
|
||||
npmScript(t, "dayjs-1.11.13.json", 0, "")
|
||||
|
||||
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "dayjs", "1.11.13", artifact(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
}
|
||||
|
||||
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
fixture string
|
||||
installOut string
|
||||
installRC int
|
||||
infra bool
|
||||
}{
|
||||
{"network down", "", "npm error code ENOTFOUND", 1, true},
|
||||
{"unresolvable tree", "", "npm error code ERESOLVE", 1, false},
|
||||
{"unparseable audit", "", "", 0, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
npmScript(t, tc.fixture, tc.installRC, tc.installOut)
|
||||
|
||||
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "p", "1", artifact(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
||||
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanAuditErrorDocumentIsAnErrorResult(t *testing.T) {
|
||||
doc := filepath.Join(t.TempDir(), "enolock.json")
|
||||
require.NoError(t, os.WriteFile(doc, []byte(`{"error":{"code":"ENOLOCK","summary":"This command requires an existing lockfile.","detail":""}}`), 0o600))
|
||||
scannertest.Script(t, "npm", fmt.Sprintf(`case "$1" in audit) cat %q; exit 1 ;; esac`, doc))
|
||||
|
||||
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "npm", "p", "1", artifact(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusError, res.Status)
|
||||
assert.Contains(t, res.Details["error"], "ENOLOCK")
|
||||
}
|
||||
|
||||
func TestScanSkipsOtherRegistries(t *testing.T) {
|
||||
res, err := New(config.NpmAuditConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"auditReportVersion": 2,
|
||||
"vulnerabilities": {},
|
||||
"metadata": {
|
||||
"vulnerabilities": {
|
||||
"info": 0,
|
||||
"low": 0,
|
||||
"moderate": 0,
|
||||
"high": 0,
|
||||
"critical": 0,
|
||||
"total": 0
|
||||
},
|
||||
"dependencies": {
|
||||
"prod": 2,
|
||||
"dev": 0,
|
||||
"optional": 0,
|
||||
"peer": 0,
|
||||
"peerOptional": 0,
|
||||
"total": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"auditReportVersion": 2,
|
||||
"vulnerabilities": {
|
||||
"minimist": {
|
||||
"name": "minimist",
|
||||
"severity": "critical",
|
||||
"isDirect": true,
|
||||
"via": [
|
||||
{
|
||||
"source": 1096466,
|
||||
"name": "minimist",
|
||||
"dependency": "minimist",
|
||||
"title": "Prototype Pollution in minimist",
|
||||
"url": "https://github.com/advisories/GHSA-vh95-rmgr-6w4m",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-1321"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 5.6,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L"
|
||||
},
|
||||
"range": "<0.2.1"
|
||||
},
|
||||
{
|
||||
"source": 1097677,
|
||||
"name": "minimist",
|
||||
"dependency": "minimist",
|
||||
"title": "Prototype Pollution in minimist",
|
||||
"url": "https://github.com/advisories/GHSA-xvch-5gv4-984h",
|
||||
"severity": "critical",
|
||||
"cwe": [
|
||||
"CWE-1321"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 9.8,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
|
||||
},
|
||||
"range": "<0.2.4"
|
||||
}
|
||||
],
|
||||
"effects": [],
|
||||
"range": "<=0.2.3",
|
||||
"nodes": [
|
||||
"node_modules/minimist"
|
||||
],
|
||||
"fixAvailable": false
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"vulnerabilities": {
|
||||
"info": 0,
|
||||
"low": 0,
|
||||
"moderate": 0,
|
||||
"high": 0,
|
||||
"critical": 1,
|
||||
"total": 1
|
||||
},
|
||||
"dependencies": {
|
||||
"prod": 2,
|
||||
"dev": 0,
|
||||
"optional": 0,
|
||||
"peer": 0,
|
||||
"peerOptional": 0,
|
||||
"total": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+84
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"auditReportVersion": 2,
|
||||
"vulnerabilities": {
|
||||
"minimist": {
|
||||
"name": "minimist",
|
||||
"severity": "critical",
|
||||
"isDirect": false,
|
||||
"via": [
|
||||
{
|
||||
"source": 1096466,
|
||||
"name": "minimist",
|
||||
"dependency": "minimist",
|
||||
"title": "Prototype Pollution in minimist",
|
||||
"url": "https://github.com/advisories/GHSA-vh95-rmgr-6w4m",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-1321"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 5.6,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:L"
|
||||
},
|
||||
"range": "<0.2.1"
|
||||
},
|
||||
{
|
||||
"source": 1097677,
|
||||
"name": "minimist",
|
||||
"dependency": "minimist",
|
||||
"title": "Prototype Pollution in minimist",
|
||||
"url": "https://github.com/advisories/GHSA-xvch-5gv4-984h",
|
||||
"severity": "critical",
|
||||
"cwe": [
|
||||
"CWE-1321"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 9.8,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
|
||||
},
|
||||
"range": "<0.2.4"
|
||||
}
|
||||
],
|
||||
"effects": [
|
||||
"mkdirp"
|
||||
],
|
||||
"range": "<=0.2.3",
|
||||
"nodes": [
|
||||
"node_modules/minimist"
|
||||
],
|
||||
"fixAvailable": false
|
||||
},
|
||||
"mkdirp": {
|
||||
"name": "mkdirp",
|
||||
"severity": "critical",
|
||||
"isDirect": true,
|
||||
"via": [
|
||||
"minimist"
|
||||
],
|
||||
"effects": [],
|
||||
"range": "0.4.1 - 0.5.1",
|
||||
"nodes": [
|
||||
"node_modules/mkdirp"
|
||||
],
|
||||
"fixAvailable": false
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"vulnerabilities": {
|
||||
"info": 0,
|
||||
"low": 0,
|
||||
"moderate": 0,
|
||||
"high": 0,
|
||||
"critical": 2,
|
||||
"total": 2
|
||||
},
|
||||
"dependencies": {
|
||||
"prod": 3,
|
||||
"dev": 0,
|
||||
"optional": 0,
|
||||
"peer": 0,
|
||||
"peerOptional": 0,
|
||||
"total": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
{
|
||||
"auditReportVersion": 2,
|
||||
"vulnerabilities": {
|
||||
"form-data": {
|
||||
"name": "form-data",
|
||||
"severity": "critical",
|
||||
"isDirect": false,
|
||||
"via": [
|
||||
{
|
||||
"source": 1109540,
|
||||
"name": "form-data",
|
||||
"dependency": "form-data",
|
||||
"title": "form-data uses unsafe random function in form-data for choosing boundary",
|
||||
"url": "https://github.com/advisories/GHSA-fjxv-7rqg-78g4",
|
||||
"severity": "critical",
|
||||
"cwe": [
|
||||
"CWE-330"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 0,
|
||||
"vectorString": null
|
||||
},
|
||||
"range": "<2.5.4"
|
||||
},
|
||||
{
|
||||
"source": 1120745,
|
||||
"name": "form-data",
|
||||
"dependency": "form-data",
|
||||
"title": "form-data: CRLF injection in form-data via unescaped multipart field names and filenames",
|
||||
"url": "https://github.com/advisories/GHSA-hmw2-7cc7-3qxx",
|
||||
"severity": "high",
|
||||
"cwe": [
|
||||
"CWE-93"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 7.5,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N"
|
||||
},
|
||||
"range": "<2.5.6"
|
||||
}
|
||||
],
|
||||
"effects": [
|
||||
"request"
|
||||
],
|
||||
"range": "<=2.5.5",
|
||||
"nodes": [
|
||||
"node_modules/form-data"
|
||||
],
|
||||
"fixAvailable": false
|
||||
},
|
||||
"qs": {
|
||||
"name": "qs",
|
||||
"severity": "moderate",
|
||||
"isDirect": false,
|
||||
"via": [
|
||||
{
|
||||
"source": 1113719,
|
||||
"name": "qs",
|
||||
"dependency": "qs",
|
||||
"title": "qs's arrayLimit bypass in its bracket notation allows DoS via memory exhaustion",
|
||||
"url": "https://github.com/advisories/GHSA-6rw7-vpxm-498p",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-20"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 3.7,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L"
|
||||
},
|
||||
"range": "<6.14.1"
|
||||
},
|
||||
{
|
||||
"source": 1158507,
|
||||
"name": "qs",
|
||||
"dependency": "qs",
|
||||
"title": "qs: Denial of Service via Attacker Controlled isBuffer",
|
||||
"url": "https://github.com/advisories/GHSA-4mjr-xmp4-gh2g",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-248",
|
||||
"CWE-703"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 5.3,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L"
|
||||
},
|
||||
"range": ">=2.2.5 <6.16.0"
|
||||
}
|
||||
],
|
||||
"effects": [
|
||||
"request"
|
||||
],
|
||||
"range": "<=6.15.4",
|
||||
"nodes": [
|
||||
"node_modules/qs"
|
||||
],
|
||||
"fixAvailable": false
|
||||
},
|
||||
"request": {
|
||||
"name": "request",
|
||||
"severity": "critical",
|
||||
"isDirect": true,
|
||||
"via": [
|
||||
{
|
||||
"source": 1096727,
|
||||
"name": "request",
|
||||
"dependency": "request",
|
||||
"title": "Server-Side Request Forgery in Request",
|
||||
"url": "https://github.com/advisories/GHSA-p8p7-x288-28g6",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-918"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 6.1,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"
|
||||
},
|
||||
"range": "<=2.88.2"
|
||||
},
|
||||
"form-data",
|
||||
"qs",
|
||||
"tough-cookie",
|
||||
"uuid"
|
||||
],
|
||||
"effects": [],
|
||||
"range": "*",
|
||||
"nodes": [
|
||||
"node_modules/request"
|
||||
],
|
||||
"fixAvailable": false
|
||||
},
|
||||
"tough-cookie": {
|
||||
"name": "tough-cookie",
|
||||
"severity": "moderate",
|
||||
"isDirect": false,
|
||||
"via": [
|
||||
{
|
||||
"source": 1097682,
|
||||
"name": "tough-cookie",
|
||||
"dependency": "tough-cookie",
|
||||
"title": "tough-cookie Prototype Pollution vulnerability",
|
||||
"url": "https://github.com/advisories/GHSA-72xf-g2v4-qvf3",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-1321"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 6.5,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N"
|
||||
},
|
||||
"range": "<4.1.3"
|
||||
}
|
||||
],
|
||||
"effects": [
|
||||
"request"
|
||||
],
|
||||
"range": "<4.1.3",
|
||||
"nodes": [
|
||||
"node_modules/tough-cookie"
|
||||
],
|
||||
"fixAvailable": false
|
||||
},
|
||||
"uuid": {
|
||||
"name": "uuid",
|
||||
"severity": "moderate",
|
||||
"isDirect": false,
|
||||
"via": [
|
||||
{
|
||||
"source": 1119441,
|
||||
"name": "uuid",
|
||||
"dependency": "uuid",
|
||||
"title": "uuid: Missing buffer bounds check in v3/v5/v6 when buf is provided",
|
||||
"url": "https://github.com/advisories/GHSA-w5hq-g745-h8pq",
|
||||
"severity": "moderate",
|
||||
"cwe": [
|
||||
"CWE-787",
|
||||
"CWE-1285"
|
||||
],
|
||||
"cvss": {
|
||||
"score": 7.5,
|
||||
"vectorString": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N"
|
||||
},
|
||||
"range": "<11.1.1"
|
||||
}
|
||||
],
|
||||
"effects": [
|
||||
"request"
|
||||
],
|
||||
"range": "<11.1.1",
|
||||
"nodes": [
|
||||
"node_modules/uuid"
|
||||
],
|
||||
"fixAvailable": false
|
||||
}
|
||||
},
|
||||
"metadata": {
|
||||
"vulnerabilities": {
|
||||
"info": 0,
|
||||
"low": 0,
|
||||
"moderate": 3,
|
||||
"high": 0,
|
||||
"critical": 2,
|
||||
"total": 5
|
||||
},
|
||||
"dependencies": {
|
||||
"prod": 48,
|
||||
"dev": 0,
|
||||
"optional": 0,
|
||||
"peer": 0,
|
||||
"peerOptional": 0,
|
||||
"total": 47
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user