mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-12-06 07:34:00 +00:00
fix(scanner): remove scanner temp files after every scan
A scanner binary that its timeout kills cannot remove its own temp files. A killed trivy left its database download in the temp dir as trivy-<n> and getter<n>, up to 279 MB for each scan. Concurrent rescans filled the scanner temp dir, and the disk guard then refused all new scans. Each scanner run now gets a private dir in the temp dir, and the scanner binary gets this dir as TMPDIR. The scan removes the dir and its contents when the scan ends, also after a timeout or an error. Each new scan also removes abandoned dirs that are older than one hour. These dirs come from a process that stopped during a scan, or from a removal that failed.
This commit is contained in:
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -79,15 +80,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
fmt.Sprintf("not a module path and version: %q %q", module, version), ""), nil
|
||||
}
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "govulncheck-*")
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
tmpDir, err := os.MkdirTemp(wd.Path(), "govulncheck-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if rmErr := os.RemoveAll(tmpDir); rmErr != nil {
|
||||
log.Warn().Err(rmErr).Str("scanner", ScannerName).Str("dir", tmpDir).Msg("Cannot remove scan directory")
|
||||
}
|
||||
}()
|
||||
|
||||
// govulncheck never reports advisories against the main module of the tree it scans, so
|
||||
// scanning the module's own source reports a vulnerable module clean. The module is
|
||||
@@ -96,7 +97,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
// Resolving the module reaches the module proxy.
|
||||
// The dependency tree goes to a module cache inside tmpDir, so the scan keeps nothing on disk;
|
||||
// -modcacherw leaves that cache writable, or RemoveAll cannot delete it.
|
||||
env := append(os.Environ(), "GOFLAGS=-mod=mod -modcacherw", "GOTOOLCHAIN=local", "GOWORK=off",
|
||||
env := append(wd.Env(os.Environ()), "GOFLAGS=-mod=mod -modcacherw", "GOTOOLCHAIN=local", "GOWORK=off",
|
||||
"GOMODCACHE="+filepath.Join(tmpDir, "modcache"))
|
||||
goMod := fmt.Sprintf("module gohoarder.audit\n\nrequire %s %s\n", module, version)
|
||||
if err = os.WriteFile(filepath.Join(tmpDir, "go.mod"), []byte(goMod), 0o600); err != nil {
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/gomodule"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -56,9 +57,14 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
if target == "" {
|
||||
target = filePath
|
||||
}
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
cmd := exec.CommandContext(ctx, "grype", target, "-o", "json", "-q") // #nosec G204 -- target is a purl or the stored artifact path
|
||||
// Concurrent scans each downloading the database filled the disk; RefreshDatabase owns updates.
|
||||
cmd.Env = append(os.Environ(), "GRYPE_DB_AUTO_UPDATE=false")
|
||||
cmd.Env = append(wd.Env(os.Environ()), "GRYPE_DB_AUTO_UPDATE=false")
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, err := cmd.Output()
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package scanner_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/govulncheck"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/grype"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/npmaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/pipaudit"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/trivy"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type scanFunc func(ctx context.Context, registry, packageName, version, filePath string) (*metadata.ScanResult, error)
|
||||
|
||||
// A scanner binary killed by its timeout never removes its own temp files: a killed trivy
|
||||
// leaves its database download (trivy-<n>, getter<n>, up to 279 MB) in TMPDIR.
|
||||
func TestScanLeavesNothingInTheTempDir(t *testing.T) {
|
||||
const leave = `mkdir -p "$TMPDIR/trivy-1/db" "$TMPDIR/getter1" && echo x > "$TMPDIR/trivy-1/db/trivy.db"`
|
||||
cases := []struct {
|
||||
scan scanFunc
|
||||
name, bin, body string
|
||||
registry, pkg, ver string
|
||||
}{
|
||||
{name: "trivy timeout", bin: "trivy", body: leave + "\nexec sleep 5", registry: "pypi", pkg: "p", ver: "1",
|
||||
scan: trivy.New(config.TrivyConfig{Timeout: time.Second}).Scan},
|
||||
{name: "grype failure", bin: "grype", body: leave + "\nexit 1", registry: "npm", pkg: "p", ver: "1.0.0",
|
||||
scan: grype.New(config.GrypeConfig{}).Scan},
|
||||
{name: "npm audit failure", bin: "npm", body: leave + "\nexit 1", registry: "npm", pkg: "p", ver: "1.0.0",
|
||||
scan: npmaudit.New(config.NpmAuditConfig{}).Scan},
|
||||
{name: "pip-audit failure", bin: "pip-audit", body: leave + "\nexit 1", registry: "pypi", pkg: "requests", ver: "2.0.0",
|
||||
scan: pipaudit.New(config.PipAuditConfig{}).Scan},
|
||||
{name: "govulncheck go list failure", bin: "go", body: leave + "\nexit 1", registry: "go", pkg: "golang.org/x/text", ver: "v0.3.5",
|
||||
scan: govulncheck.New(config.GovulncheckConfig{}).Scan},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
scannertest.Script(t, tc.bin, tc.body)
|
||||
archive := filepath.Join(t.TempDir(), "p.tgz")
|
||||
require.NoError(t, os.WriteFile(archive, []byte("x"), 0o600))
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
|
||||
_, _ = tc.scan(context.Background(), tc.registry, tc.pkg, tc.ver, archive)
|
||||
|
||||
left, err := os.ReadDir(tmp)
|
||||
require.NoError(t, err)
|
||||
names := make([]string, 0, len(left))
|
||||
for _, e := range left {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
assert.Empty(t, names)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -69,11 +70,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
Str("version", version).
|
||||
Msg("Starting npm audit scan")
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "npm-audit-*")
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
tmpDir, err := os.MkdirTemp(wd.Path(), "npm-audit-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
|
||||
if err = writeWrapper(tmpDir, packageName, filePath); err != nil {
|
||||
return s.scanErrorResult(ctx, registry, packageName, version, fmt.Sprintf("prepare audit project: %v", err), ""), nil
|
||||
@@ -95,6 +100,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
"--no-fund",
|
||||
)
|
||||
installCmd.Dir = tmpDir
|
||||
installCmd.Env = wd.Env(os.Environ())
|
||||
if installOut, installErr := installCmd.CombinedOutput(); installErr != nil {
|
||||
log.Warn().
|
||||
Err(installErr).
|
||||
@@ -107,6 +113,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
|
||||
cmd := exec.CommandContext(ctx, "npm", "audit", "--omit=dev", "--json") // #nosec G204 -- fixed args
|
||||
cmd.Dir = tmpDir
|
||||
cmd.Env = installCmd.Env
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // npm audit exits non-zero when it finds vulnerabilities
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -74,11 +75,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
fmt.Sprintf("not a project name and version: %q %q", packageName, version), ""), nil
|
||||
}
|
||||
|
||||
tmpDir, err := os.MkdirTemp("", "pip-audit-*")
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
tmpDir, err := os.MkdirTemp(wd.Path(), "pip-audit-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
|
||||
// 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
|
||||
@@ -89,6 +94,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
}
|
||||
|
||||
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
|
||||
cmd.Env = wd.Env(os.Environ())
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, _ := cmd.Output() // pip-audit exits non-zero when it finds vulnerabilities
|
||||
|
||||
@@ -18,12 +18,12 @@ const maxExtractBytes int64 = 512 << 20
|
||||
var errTooLarge = errors.New("archive exceeds the extraction size limit")
|
||||
|
||||
// unpackNPM extracts an npm tarball into root/node_modules/<name>, the layout trivy's node-pkg
|
||||
// analyzer reads. It returns root, which the caller must remove.
|
||||
func unpackNPM(archive, name string) (root string, err error) {
|
||||
// analyzer reads. root is a new dir in parent.
|
||||
func unpackNPM(parent, archive, name string) (root string, err error) {
|
||||
if !validPackageName(name) {
|
||||
return "", fmt.Errorf("unsafe package name %q", name)
|
||||
}
|
||||
root, err = os.MkdirTemp("", "trivy-npm-*")
|
||||
root, err = os.MkdirTemp(parent, "trivy-npm-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
+24
-12
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanver"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/workdir"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -89,10 +90,13 @@ func (s *Scanner) Name() string {
|
||||
func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
||||
log.Info().Msg("Updating Trivy vulnerability database")
|
||||
|
||||
cmd := exec.CommandContext(ctx, "trivy", "image", "--download-db-only")
|
||||
if s.config.CacheDB != "" {
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("TRIVY_CACHE_DIR=%s", s.config.CacheDB))
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer wd.Remove()
|
||||
cmd := exec.CommandContext(ctx, "trivy", "image", "--download-db-only")
|
||||
cmd.Env = s.env(wd)
|
||||
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
@@ -112,16 +116,19 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
wd, err := workdir.New(ScannerName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer wd.Remove()
|
||||
|
||||
scanType := s.determineScanType(registry, filePath)
|
||||
target := filePath
|
||||
if registry == "npm" {
|
||||
// trivy does not unpack archives; the node-pkg analyzer needs an installed tree.
|
||||
root, err := unpackNPM(filePath, packageName)
|
||||
if err != nil {
|
||||
if target, err = unpackNPM(wd.Path(), filePath, packageName); err != nil {
|
||||
return nil, fmt.Errorf("prepare npm package for trivy: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(root) }()
|
||||
target = root
|
||||
}
|
||||
|
||||
args := []string{
|
||||
@@ -132,11 +139,7 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
|
||||
|
||||
// Set cache directory if configured
|
||||
if s.config.CacheDB != "" {
|
||||
cmd.Env = append(os.Environ(), fmt.Sprintf("TRIVY_CACHE_DIR=%s", s.config.CacheDB))
|
||||
}
|
||||
cmd.Env = s.env(wd)
|
||||
|
||||
// Execute scan
|
||||
output, err := cmd.Output()
|
||||
@@ -168,6 +171,15 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
return s.convertTrivyResult(&trivyResult, registry, packageName, version), nil
|
||||
}
|
||||
|
||||
// env runs trivy in wd, with the configured cache dir.
|
||||
func (s *Scanner) env(wd *workdir.Dir) []string {
|
||||
env := wd.Env(os.Environ())
|
||||
if s.config.CacheDB != "" {
|
||||
env = append(env, "TRIVY_CACHE_DIR="+s.config.CacheDB)
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
// determineScanType determines the appropriate Trivy scan type
|
||||
func (s *Scanner) determineScanType(registry, filePath string) string {
|
||||
// For now, use filesystem scan for packages
|
||||
|
||||
@@ -114,7 +114,7 @@ func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
root, err := unpackNPM(tgz(t, tt.entries...), "pkg")
|
||||
root, err := unpackNPM(t.TempDir(), tgz(t, tt.entries...), "pkg")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, root)
|
||||
})
|
||||
@@ -122,12 +122,11 @@ func TestExtractRejectsUnsafeArchives(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
|
||||
root, err := unpackNPM(tgz(t,
|
||||
root, err := unpackNPM(t.TempDir(), tgz(t,
|
||||
entry{name: "package/real.js", body: "x"},
|
||||
entry{name: "package/l", typeflag: tar.TypeSymlink, link: "real.js"},
|
||||
), "pkg")
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = os.RemoveAll(root) }()
|
||||
_, err = os.Lstat(filepath.Join(root, "node_modules", "pkg", "l"))
|
||||
assert.True(t, os.IsNotExist(err))
|
||||
assert.FileExists(t, filepath.Join(root, "node_modules", "pkg", "real.js"))
|
||||
@@ -136,7 +135,7 @@ func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
|
||||
func TestUnpackRejectsUnsafePackageNames(t *testing.T) {
|
||||
archive := tgz(t, entry{name: "package/package.json", body: "{}"})
|
||||
for _, name := range []string{"", "..", "../x", "/abs", "a/../../b", `a\b`} {
|
||||
_, err := unpackNPM(archive, name)
|
||||
_, err := unpackNPM(t.TempDir(), archive, name)
|
||||
assert.Error(t, err, name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Package workdir gives each scanner run a private temp dir. The scanner binary gets it as
|
||||
// TMPDIR, so the files it stages there, such as the database download of a trivy killed by
|
||||
// its timeout, are removed with the dir.
|
||||
package workdir
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
prefix = "gohoarder-scan-"
|
||||
// Far past every scanner timeout, so a sweep never takes the dir of a scan still running elsewhere.
|
||||
abandonedAfter = time.Hour
|
||||
)
|
||||
|
||||
var (
|
||||
liveMu sync.Mutex
|
||||
live = map[string]struct{}{}
|
||||
// One sweep at a time; concurrent scans skip it instead of queueing.
|
||||
sweeping sync.Mutex
|
||||
)
|
||||
|
||||
// Dir is the temp dir of one scanner run.
|
||||
type Dir struct {
|
||||
path string
|
||||
}
|
||||
|
||||
// New sweeps abandoned work dirs, then creates one for scanner.
|
||||
func New(scanner string) (*Dir, error) {
|
||||
sweep(time.Now().Add(-abandonedAfter))
|
||||
path, err := os.MkdirTemp("", prefix+scanner+"-*")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create scan work dir: %w", err)
|
||||
}
|
||||
liveMu.Lock()
|
||||
live[path] = struct{}{}
|
||||
liveMu.Unlock()
|
||||
return &Dir{path: path}, nil
|
||||
}
|
||||
|
||||
// Path returns the work dir.
|
||||
func (d *Dir) Path() string { return d.path }
|
||||
|
||||
// Env returns env with TMPDIR set to the work dir; exec uses the last value of a duplicate key.
|
||||
func (d *Dir) Env(env []string) []string {
|
||||
return append(env, "TMPDIR="+d.path)
|
||||
}
|
||||
|
||||
// Remove deletes the work dir and everything in it. A dir it cannot delete is left to a later sweep.
|
||||
func (d *Dir) Remove() {
|
||||
err := os.RemoveAll(d.path)
|
||||
liveMu.Lock()
|
||||
delete(live, d.path)
|
||||
liveMu.Unlock()
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("path", d.path).Msg("Cannot remove scan work dir")
|
||||
}
|
||||
}
|
||||
|
||||
// sweep removes work dirs last modified before cutoff that no scan in this process uses: those of
|
||||
// a process killed mid-scan, and those Remove could not delete.
|
||||
func sweep(cutoff time.Time) {
|
||||
if !sweeping.TryLock() {
|
||||
return
|
||||
}
|
||||
defer sweeping.Unlock()
|
||||
|
||||
dir := os.TempDir()
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if !errors.Is(err, fs.ErrNotExist) {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot list dir for abandoned scan work dirs")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() || !strings.HasPrefix(e.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, e.Name())
|
||||
liveMu.Lock()
|
||||
_, inUse := live[path]
|
||||
liveMu.Unlock()
|
||||
if inUse {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil || !info.ModTime().Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
log.Warn().Err(err).Str("path", path).Msg("Cannot remove abandoned scan work dir")
|
||||
continue
|
||||
}
|
||||
log.Info().Str("path", path).Msg("Removed abandoned scan work dir")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package workdir
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func entries(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
list, err := os.ReadDir(dir)
|
||||
require.NoError(t, err)
|
||||
names := make([]string, 0, len(list))
|
||||
for _, e := range list {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestRemoveDeletesWhatTheScannerLeft(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
|
||||
wd, err := New("trivy")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tmp, filepath.Dir(wd.Path()))
|
||||
assert.Equal(t, "TMPDIR="+wd.Path(), wd.Env([]string{"TMPDIR=/tmp"})[1])
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(wd.Path(), "trivy-1", "db"), 0o700))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(wd.Path(), "trivy-1", "db", "trivy.db"), []byte("x"), 0o600))
|
||||
|
||||
wd.Remove()
|
||||
|
||||
assert.Empty(t, entries(t, tmp))
|
||||
}
|
||||
|
||||
func TestSweepRemovesOnlyAbandonedDirs(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
old := time.Now().Add(-2 * abandonedAfter)
|
||||
mk := func(name string, mtime time.Time) {
|
||||
path := filepath.Join(tmp, name)
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(path, "x"), 0o700))
|
||||
require.NoError(t, os.Chtimes(path, mtime, mtime))
|
||||
}
|
||||
mk(prefix+"trivy-1", old)
|
||||
mk(prefix+"npm-audit-2", time.Now())
|
||||
mk("trivy-3", old)
|
||||
live, err := New("grype")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.Chtimes(live.Path(), old, old))
|
||||
|
||||
sweep(time.Now().Add(-abandonedAfter))
|
||||
|
||||
assert.ElementsMatch(t, []string{prefix + "npm-audit-2", "trivy-3", filepath.Base(live.Path())}, entries(t, tmp))
|
||||
live.Remove()
|
||||
}
|
||||
|
||||
func TestSweepRetriesADirWhoseRemoveFailed(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
wd, err := New("trivy")
|
||||
require.NoError(t, err)
|
||||
locked := filepath.Join(wd.Path(), "locked")
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(locked, "f"), 0o700))
|
||||
require.NoError(t, os.Chmod(locked, 0o500)) // #nosec G302 -- read-only on purpose
|
||||
t.Cleanup(func() { _ = os.Chmod(locked, 0o700) }) // #nosec G302 -- test dir
|
||||
|
||||
wd.Remove()
|
||||
require.NoError(t, os.Chmod(locked, 0o700)) // #nosec G302 -- test dir
|
||||
old := time.Now().Add(-2 * abandonedAfter)
|
||||
require.NoError(t, os.Chtimes(wd.Path(), old, old))
|
||||
sweep(time.Now().Add(-abandonedAfter))
|
||||
|
||||
assert.Empty(t, entries(t, tmp))
|
||||
}
|
||||
|
||||
func TestConcurrentScansLeaveNothing(t *testing.T) {
|
||||
tmp := t.TempDir()
|
||||
t.Setenv("TMPDIR", tmp)
|
||||
var wg sync.WaitGroup
|
||||
for range 16 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
wd, err := New("npm-audit")
|
||||
if !assert.NoError(t, err) {
|
||||
return
|
||||
}
|
||||
assert.NoError(t, os.WriteFile(filepath.Join(wd.Path(), "f"), []byte("x"), 0o600))
|
||||
wd.Remove()
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
assert.Empty(t, entries(t, tmp))
|
||||
}
|
||||
Reference in New Issue
Block a user