fix(pip-audit): audit the release from a pinned requirement

pip-audit takes a project directory as its positional argument and has
no --pyproject option, so every wheel and sdist scan failed. The scanner
now audits name==version from a requirements file with --no-deps and
--disable-pip.

It reads stdout only, lists each advisory once, and treats a skip_reason
as an error because pip-audit exits 0 for a package it could not audit.
This commit is contained in:
2026-11-23 18:07:27 +00:00
parent e37c797602
commit 3d6bda3a5f
6 changed files with 193 additions and 128 deletions
+47 -128
View File
@@ -3,17 +3,20 @@
package pipaudit
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"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"
)
@@ -64,47 +67,43 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
Str("version", version).
Msg("Starting pip-audit scan")
// Create a temporary directory
if !validName.MatchString(packageName) || !validVersion.MatchString(version) {
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("not a project name and version: %q %q", packageName, version), ""), nil
}
tmpDir, err := os.MkdirTemp("", "pip-audit-*")
if err != nil {
return nil, fmt.Errorf("failed to create temp dir: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
// Copy the wheel/tar.gz file to temp directory
tmpFile := filepath.Join(tmpDir, filepath.Base(filePath))
if err := s.copyInto(filePath, tmpDir, filepath.Base(tmpFile)); err != nil {
return nil, fmt.Errorf("failed to copy file: %w", err)
// pip-audit has no wheel or sdist input: its positional argument is a project directory. The
// release is audited by its pinned name and version. --no-deps and --disable-pip keep it to
// that release, with no resolution of its dependencies.
reqFile := filepath.Join(tmpDir, "requirements.txt")
if err := os.WriteFile(reqFile, []byte(packageName+"=="+version+"\n"), 0o600); err != nil {
return nil, fmt.Errorf("failed to write requirements: %w", err)
}
// Build the appropriate pip-audit invocation based on artifact type.
// `-r` expects requirements.txt — passing a wheel/tarball there is wrong.
// Wheels can be scanned directly via positional arg. Source distributions
// (tarballs) need to be extracted; if they contain a pyproject.toml we
// can scan that, otherwise we fail closed.
cmd, prepErr := s.buildAuditCmd(ctx, tmpDir, tmpFile)
if prepErr != nil {
log.Warn().
Err(prepErr).
Str("package", packageName).
Str("version", version).
Msg("pip-audit could not prepare input artifact, returning scan-error")
return s.scanErrorResult(registry, packageName, version, prepErr.Error()), nil
}
output, _ := cmd.CombinedOutput() // pip-audit returns non-zero when vulns found
cmd := exec.CommandContext(ctx, "pip-audit", "-r", reqFile, "--no-deps", "--disable-pip", "-f", "json") // #nosec G204 -- name and version are validated, file is in a controlled temp dir
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, _ := cmd.Output() // pip-audit exits non-zero when it finds vulnerabilities
// Parse pip-audit output
var auditResult PipAuditResult
if len(output) > 0 {
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Msg("Failed to parse pip-audit output")
// Parse failure → no signal → fail closed.
return s.scanErrorResult(registry, packageName, version,
fmt.Sprintf("failed to parse pip-audit output: %v", err)), nil
if err := json.Unmarshal(output, &auditResult); err != nil {
log.Warn().Err(err).Str("stderr", stderr.String()).Msg("Failed to parse pip-audit output")
return s.scanErrorResult(ctx, registry, packageName, version,
fmt.Sprintf("failed to parse pip-audit output: %v: %s", err, strings.TrimSpace(stderr.String())), stderr.String()), nil
}
for _, dep := range auditResult.Dependencies {
if dep.SkipReason != "" {
// pip-audit exits 0 for a package it could not audit; that is no verdict.
return s.scanErrorResult(ctx, registry, packageName, version, dep.SkipReason, ""), nil
}
}
// Convert to our format
result := s.convertResult(&auditResult, registry, packageName, version)
log.Info().
@@ -116,6 +115,11 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
return result, nil
}
var (
validName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
validVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.+!_-]*$`)
)
// Health checks if pip-audit is available
func (s *Scanner) Health(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "pip-audit", "--version")
@@ -125,98 +129,10 @@ func (s *Scanner) Health(ctx context.Context) error {
return nil
}
// copyInto copies src to name inside dir; name cannot escape dir.
func (s *Scanner) copyInto(src, dir, name string) error {
input, err := os.ReadFile(src) // #nosec G304 -- Source path is from scanner, controlled
if err != nil {
return err
}
root, err := os.OpenRoot(dir)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
return root.WriteFile(name, input, 0600)
}
// buildAuditCmd constructs the right pip-audit command for the input artifact.
//
// - .whl -> pip-audit <wheel> --format json
// - .tar.gz / .tgz / .zip (sdist) -> extract; if pyproject.toml exists
// run `pip-audit --pyproject <pyproject> --format json`; otherwise error.
//
// extractDir is used as a workspace for sdist extraction.
func (s *Scanner) buildAuditCmd(ctx context.Context, extractDir, artifact string) (*exec.Cmd, error) {
lower := strings.ToLower(artifact)
switch {
case strings.HasSuffix(lower, ".whl"):
// pip-audit can scan a wheel directly via positional argument.
return exec.CommandContext(ctx, "pip-audit", artifact, "--format", "json"), nil // #nosec G204 -- artifact path is in controlled tmp dir
case strings.HasSuffix(lower, ".tar.gz"),
strings.HasSuffix(lower, ".tgz"),
strings.HasSuffix(lower, ".zip"):
// Source distributions must be unpacked first.
sdistDir := filepath.Join(extractDir, "sdist")
if err := os.MkdirAll(sdistDir, 0o750); err != nil {
return nil, fmt.Errorf("create sdist dir: %w", err)
}
if err := s.extractSdist(artifact, sdistDir); err != nil {
return nil, fmt.Errorf("extract sdist: %w", err)
}
pyproject, err := findPyProject(sdistDir)
if err != nil {
return nil, fmt.Errorf("no pyproject.toml in sdist: %w", err)
}
return exec.CommandContext(ctx, "pip-audit", "--pyproject", pyproject, "--format", "json"), nil // #nosec G204 -- pyproject path under controlled tmp dir
default:
return nil, fmt.Errorf("unsupported pip artifact extension: %s", filepath.Base(artifact))
}
}
// extractSdist unpacks a Python source distribution into destDir.
func (s *Scanner) extractSdist(archive, destDir string) error {
lower := strings.ToLower(archive)
switch {
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
return exec.Command("tar", "-xzf", archive, "-C", destDir).Run()
case strings.HasSuffix(lower, ".zip"):
return exec.Command("unzip", "-q", archive, "-d", destDir).Run()
default:
return fmt.Errorf("unknown archive type: %s", archive)
}
}
// findPyProject returns the path to a pyproject.toml within root, walking
// one level deep (sdists typically extract to <pkg>-<ver>/).
func findPyProject(root string) (string, error) {
var found string
err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
if d.Name() == "pyproject.toml" {
found = path
return filepath.SkipAll
}
return nil
})
if err != nil {
return "", err
}
if found == "" {
return "", fmt.Errorf("pyproject.toml not found under %s", root)
}
return found, nil
}
// scanErrorResult returns a result marked scan-error so manager merge and
// CheckVulnerabilities can fail closed when this scanner could not run.
func (s *Scanner) scanErrorResult(registry, packageName, version, reason string) *metadata.ScanResult {
// scanErrorResult returns a scan-error result. 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,
@@ -227,21 +143,23 @@ 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),
}
}
// emptyResult returns an empty scan result
// convertResult converts pip-audit output to our ScanResult format
func (s *Scanner) convertResult(auditResult *PipAuditResult, registry, packageName, version string) *metadata.ScanResult {
vulnerabilities := make([]metadata.Vulnerability, 0)
severityCounts := make(map[string]int)
seen := make(map[string]bool)
for _, dep := range auditResult.Dependencies {
for _, vuln := range dep.Vulns {
// pip-audit lists an advisory once per alias.
if seen[vuln.ID] {
continue
}
seen[vuln.ID] = true
// Map pip-audit severity to our standard
severity := s.mapSeverity(vuln.ID)
normalizedSeverity := metadata.NormalizeSeverity(severity)
@@ -298,9 +216,10 @@ type PipAuditResult struct {
}
type PipDependency struct {
Name string `json:"name"`
Version string `json:"version"`
Vulns []PipVuln `json:"vulns"`
Name string `json:"name"`
Version string `json:"version"`
SkipReason string `json:"skip_reason"`
Vulns []PipVuln `json:"vulns"`
}
type PipVuln struct {
+142
View File
@@ -0,0 +1,142 @@
package pipaudit
import (
"context"
"os"
"path/filepath"
"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 `pip-audit -f json` output from pip-audit 2.10.1 (see FINDINGS GH-25); the
// example proxy credential in the requests 2.19.0 advisory text is replaced by a placeholder.
func fixture(name string) string { return filepath.Join("testdata", name) }
func ids(res *metadata.ScanResult) []string {
out := make([]string, 0, len(res.Vulnerabilities))
for _, v := range res.Vulnerabilities {
out = append(out, v.ID)
}
return out
}
// artifactNamed is a stand-in for the cached file: the scanner audits the release by name and version.
func artifactNamed(t *testing.T, name string) string {
t.Helper()
p := filepath.Join(t.TempDir(), name)
require.NoError(t, os.WriteFile(p, []byte("x"), 0o600))
return p
}
func TestScanAuditsTheReleaseFromARequirement(t *testing.T) {
// pip-audit has no wheel argument: its positional argument is a project directory, and it
// has no --pyproject flag. A wheel or sdist is audited by name and version.
for _, file := range []string{"requests-2.19.0-py2.py3-none-any.whl", "requests-2.19.0.tar.gz"} {
t.Run(file, func(t *testing.T) {
args := scannertest.Fake(t, "pip-audit", fixture("requests-2.19.0.json"), "WARNING:pip_audit._cli:--no-deps is supported\n", 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "requests", "2.19.0", artifactNamed(t, file))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusVulnerable, res.Status)
assert.ElementsMatch(t, []string{"PYSEC-2018-28", "PYSEC-2023-74", "PYSEC-2026-1872", "PYSEC-2026-1873", "PYSEC-2026-2275"}, ids(res),
"pip-audit lists an advisory once per alias; the result lists it once")
assert.Equal(t, 5, res.VulnerabilityCount)
got := scannertest.Args(t, args)
assert.Equal(t, []string{"-r"}, got[:1])
assert.Equal(t, []string{"--no-deps", "--disable-pip", "-f", "json"}, got[2:])
})
}
}
func TestScanWritesAPinnedRequirement(t *testing.T) {
dir := t.TempDir()
scannertest.Script(t, "pip-audit", `cat "$2" > `+filepath.Join(dir, "req")+`; cat `+mustAbs(t, "six-1.16.0.json"))
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "six", "1.16.0", artifactNamed(t, "six-1.16.0-py2.py3-none-any.whl"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
req, err := os.ReadFile(filepath.Join(dir, "req")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.Equal(t, "six==1.16.0\n", string(req))
}
func mustAbs(t *testing.T, name string) string {
t.Helper()
p, err := filepath.Abs(fixture(name))
require.NoError(t, err)
return p
}
func TestScanSeverityAndFix(t *testing.T) {
scannertest.Fake(t, "pip-audit", fixture("requests-2.32.0.json"), "", 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "requests", "2.32.0", artifactNamed(t, "requests-2.32.0.tar.gz"))
require.NoError(t, err)
fixed := map[string]string{}
for _, v := range res.Vulnerabilities {
fixed[v.ID] = v.FixedIn
assert.Equal(t, "MODERATE", v.Severity, "pip-audit reports no severity")
}
assert.Equal(t, map[string]string{"PYSEC-2026-1872": "2.32.4", "PYSEC-2026-2275": "2.33.0"}, fixed)
}
func TestScanPackageUnknownToPyPIIsAnError(t *testing.T) {
// pip-audit exits 0 with a skip_reason; reading that as clean would pass an unaudited package.
scannertest.Fake(t, "pip-audit", fixture("not-on-pypi.json"), "", 0)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "nopkg-zzz", "1.0", artifactNamed(t, "nopkg_zzz-1.0.tar.gz"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Contains(t, res.Details["error"], "not found on PyPI")
assert.Equal(t, false, res.Details[scanerr.DetailInfrastructure])
}
func TestScanFailuresAreErrorResultsWithACause(t *testing.T) {
cases := []struct {
name, stderr string
infra bool
}{
{"network", "ERROR: HTTPSConnectionPool: Max retries exceeded: ConnectionError ECONNREFUSED", true},
{"other", "ERROR:pip_audit._cli:boom", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
scannertest.Fake(t, "pip-audit", "", tc.stderr, 1)
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", "six", "1.16.0", artifactNamed(t, "six-1.16.0.tar.gz"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, tc.infra, res.Details[scanerr.DetailInfrastructure])
})
}
}
func TestScanRefusesNameAndVersionThatCouldBeOptions(t *testing.T) {
args := scannertest.Fake(t, "pip-audit", fixture("six-1.16.0.json"), "", 0)
for _, c := range [][2]string{{"--index-url=http://evil", "1.0"}, {"six", "1.0\n--index-url=x"}, {"", "1.0"}, {"six", ""}} {
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "pypi", c[0], c[1], artifactNamed(t, "x.whl"))
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status, "%q %q", c[0], c[1])
}
_, statErr := os.Stat(args)
assert.True(t, os.IsNotExist(statErr), "pip-audit never ran")
}
func TestScanSkipsOtherRegistries(t *testing.T) {
res, err := New(config.PipAuditConfig{}).Scan(context.Background(), "npm", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
}
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "nopkg-zzz", "skip_reason": "Dependency not found on PyPI and could not be audited: nopkg-zzz (1.0)"}], "fixes": []}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "requests", "version": "2.32.0", "vulns": [{"id": "PYSEC-2026-1872", "fix_versions": ["2.32.4"], "aliases": ["CVE-2024-47081", "GHSA-9hjg-9r4m-mvj7"], "description": "### Impact Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak .netrc credentials to third parties for specific maliciously-crafted URLs. ### Workarounds For older versions of Requests, use of the .netrc file can be disabled with `trust_env=False` on your Requests Session ([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)). ### References https://github.com/psf/requests/pull/6965 https://seclists.org/fulldisclosure/2025/Jun/2"}, {"id": "PYSEC-2026-2275", "fix_versions": ["2.33.0"], "aliases": ["CVE-2026-25645", "GHSA-gc5v-m9x4-r6x2"], "description": "### Impact The `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting files from zip archives into the system temporary directory. If the target file already exists, it is reused without validation. A local attacker with write access to the temp directory could pre-create a malicious file that would be loaded in place of the legitimate one. ### Affected usages **Standard usage of the Requests library is not affected by this vulnerability.** Only applications that call `extract_zipped_paths()` directly are impacted. ### Remediation Upgrade to at least Requests 2.33.0, where the library now extracts files to a non-deterministic location. If developers are unable to upgrade, they can set `TMPDIR` in their environment to a directory with restricted write access."}, {"id": "PYSEC-2026-1872", "fix_versions": ["2.32.4"], "aliases": ["CVE-2024-47081", "GHSA-9hjg-9r4m-mvj7"], "description": "### Impact Due to a URL parsing issue, Requests releases prior to 2.32.4 may leak .netrc credentials to third parties for specific maliciously-crafted URLs. ### Workarounds For older versions of Requests, use of the .netrc file can be disabled with `trust_env=False` on your Requests Session ([docs](https://requests.readthedocs.io/en/latest/api/#requests.Session.trust_env)). ### References https://github.com/psf/requests/pull/6965 https://seclists.org/fulldisclosure/2025/Jun/2"}, {"id": "PYSEC-2026-2275", "fix_versions": ["2.33.0"], "aliases": ["CVE-2026-25645", "GHSA-gc5v-m9x4-r6x2"], "description": "Requests is a HTTP library. Prior to version 2.33.0, the `requests.utils.extract_zipped_paths()` utility function uses a predictable filename when extracting files from zip archives into the system temporary directory. If the target file already exists, it is reused without validation. A local attacker with write access to the temp directory could pre-create a malicious file that would be loaded in place of the legitimate one. Standard usage of the Requests library is not affected by this vulnerability. Only applications that call `extract_zipped_paths()` directly are impacted. Starting in version 2.33.0, the library extracts files to a non-deterministic location. If developers are unable to upgrade, they can set `TMPDIR` in their environment to a directory with restricted write access."}]}], "fixes": []}
+1
View File
@@ -0,0 +1 @@
{"dependencies": [{"name": "six", "version": "1.16.0", "vulns": []}], "fixes": []}