mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-28 06:46:26 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fcbbcab0b | ||
|
|
2de0bf029d | ||
|
|
17d7bebf88 | ||
|
|
1432c7176b |
@@ -15,7 +15,7 @@
|
||||
"@fontsource/ibm-plex-mono": "5.3.0",
|
||||
"@fontsource/ibm-plex-sans": "5.3.0",
|
||||
"@fortawesome/free-solid-svg-icons": "7.3.1",
|
||||
"@perfect-design/ui": "0.3.10",
|
||||
"@perfect-design/ui": "0.3.11",
|
||||
"axios": "^1.20.0",
|
||||
"pinia": "^4.0.0",
|
||||
"vue": "^3.5.26",
|
||||
|
||||
Generated
+5
-5
@@ -23,8 +23,8 @@ importers:
|
||||
specifier: 7.3.1
|
||||
version: 7.3.1
|
||||
'@perfect-design/ui':
|
||||
specifier: 0.3.10
|
||||
version: 0.3.10([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))
|
||||
specifier: 0.3.11
|
||||
version: 0.3.11([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))
|
||||
axios:
|
||||
specifier: ^1.20.0
|
||||
version: 1.21.1([email protected]([email protected]))([email protected])
|
||||
@@ -353,8 +353,8 @@ packages:
|
||||
'@oxc-project/[email protected]':
|
||||
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
|
||||
|
||||
'@perfect-design/[email protected]0':
|
||||
resolution: {integrity: sha512-nFpY8dK6braHsRPVdX3bUCrkPNfwiUj2KfvUfLdFRFlfBRaqrkNGx2QkmNu/L0rdNe6JQj6Mvdrb+LnC/sFg8Q==}
|
||||
'@perfect-design/[email protected]1':
|
||||
resolution: {integrity: sha512-vu7liBjd6ZndJWio3gt1EHmOVi1VAcPQ/v+8xQRLvrIH9Bd43ZYsgsh+JITpBRmagYyAxPjo1zFU7ma/I6lVmg==}
|
||||
peerDependencies:
|
||||
pinia: ^3.0.0 || ^4.0.0
|
||||
tailwindcss: ^4.1.0
|
||||
@@ -1967,7 +1967,7 @@ snapshots:
|
||||
|
||||
'@oxc-project/[email protected]': {}
|
||||
|
||||
'@perfect-design/[email protected]0([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))':
|
||||
'@perfect-design/[email protected]1([email protected](@vue/[email protected])([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))':
|
||||
dependencies:
|
||||
pinia: 4.1.0(@vue/[email protected])([email protected])([email protected]([email protected]))
|
||||
reka-ui: 2.11.0([email protected]([email protected]))
|
||||
|
||||
@@ -50,7 +50,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.39.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 // indirect
|
||||
github.com/aws/smithy-go v1.28.9 // indirect
|
||||
github.com/aws/smithy-go v1.28.10 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
@@ -71,7 +71,7 @@ require (
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/gofiber/schema v1.10.0 // indirect
|
||||
github.com/gofiber/schema v1.10.2 // indirect
|
||||
github.com/gofiber/utils/v2 v2.6.5 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.4 // indirect
|
||||
@@ -100,7 +100,7 @@ require (
|
||||
github.com/moby/moby/client v0.6.3 // indirect
|
||||
github.com/moby/patternmatcher v0.6.1 // indirect
|
||||
github.com/moby/sys/sequential v0.7.0 // indirect
|
||||
github.com/moby/sys/user v0.5.0 // indirect
|
||||
github.com/moby/sys/user v0.5.1 // indirect
|
||||
github.com/moby/sys/userns v0.2.1 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/molecule-man/go-brrr v1.3.1 // indirect
|
||||
|
||||
@@ -42,8 +42,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5 h1:uIOBLMhef4N16WguadoHKuBy
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.5/go.mod h1:NwWmkFLtsTVyXQpbzPOlYLwEoANkdCFjJRtrNcbg/vY=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0 h1:my9Y6lxcqvPV5k4OTqnxr8XbiTDDRos1leEh050Z93U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.53.0/go.mod h1:MG6N8U9+lY4LqchrlHPqCOSr7hyxw70XU0Et2YR3eNA=
|
||||
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
|
||||
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
|
||||
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
@@ -105,8 +105,8 @@ github.com/goccy/go-json v0.12.0 h1:pD+oWouAiz4yruwXIt/iT+lOMeyhr1aTtxzaMP/RgVI=
|
||||
github.com/goccy/go-json v0.12.0/go.mod h1:3NdmfEkZlB7YI5UFw/qdFKq8XN1aiWR0YyRPWZNQltY=
|
||||
github.com/gofiber/fiber/v3 v3.7.0 h1:aF+GfB7nP9Dd0wVsv6wmr8675v66OGfjSyoDhPmvKEo=
|
||||
github.com/gofiber/fiber/v3 v3.7.0/go.mod h1:7dlbpUZ789TJg4q/VfdS1UWDtB6Fl/Smk6ZYZusMpAQ=
|
||||
github.com/gofiber/schema v1.10.0 h1:d/2/NpHOVD0f29aNvM3KSPmaEDLJZvxW5edtN4Ymd8U=
|
||||
github.com/gofiber/schema v1.10.0/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
|
||||
github.com/gofiber/schema v1.10.2 h1:mjqtglIvi/+NK3gJTra6wKOaBLZYx+tdNu7xtaCVPOg=
|
||||
github.com/gofiber/schema v1.10.2/go.mod h1:scfpXbReJ8y9xKlNnrwlewJ8nIGVZZmzoHZ4i5yGxG0=
|
||||
github.com/gofiber/utils/v2 v2.6.5 h1:rU+8ao6LKi3fKOA3sEjfLv1T+2C2IwomeVmEKaqkr4A=
|
||||
github.com/gofiber/utils/v2 v2.6.5/go.mod h1:OqPxdhDW7fPz0dupDanqf4e5O15IyFKy724y/EY9RI4=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -187,8 +187,8 @@ github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9Kou
|
||||
github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4=
|
||||
github.com/moby/sys/sequential v0.7.0 h1:ASQNGNROJSuOO6LL6bPHbKvuZu6NU8P4ldPWk31zj/8=
|
||||
github.com/moby/sys/sequential v0.7.0/go.mod h1:NfSTAp6V3fw4tmkD62PEcOKeZKquXT8VKCkf7aVR79o=
|
||||
github.com/moby/sys/user v0.5.0 h1:5+S4lyoavGyX1DGs68NW8xpx48T9+a7ogSUc0KjZg8Y=
|
||||
github.com/moby/sys/user v0.5.0/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
|
||||
github.com/moby/sys/user v0.5.1 h1:IMM/21OvpU2icUZczWBwLMf8iBEx1bOoiCQqcy1eKu0=
|
||||
github.com/moby/sys/user v0.5.1/go.mod h1:4mQzP5aTmaLjDLp/dc870oNkik6E9vjRtWYwI05gvow=
|
||||
github.com/moby/sys/userns v0.2.1 h1:4OvdM7BcPkASbuouHsbW3aeMJSFlYDldBRnXVZhaRk8=
|
||||
github.com/moby/sys/userns v0.2.1/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||
|
||||
@@ -184,6 +184,7 @@ type SecurityConfig struct {
|
||||
RescanConcurrency int `mapstructure:"rescan_concurrency" json:"rescan_concurrency"` // scans run in parallel per rescan cycle; <1 = 1
|
||||
ScanRetryInterval time.Duration `mapstructure:"scan_retry_interval" json:"scan_retry_interval"` // wait before retrying a scan that failed on infrastructure; 0 = 5m
|
||||
ScanWaitTimeout time.Duration `mapstructure:"scan_wait_timeout" json:"scan_wait_timeout"` // how long a first download waits for its scan; 0 = 30s
|
||||
MinFreeBytes int64 `mapstructure:"min_free_bytes" json:"min_free_bytes"` // defer scans while the temp dir has less free space; 0 = off
|
||||
FailClosed bool `mapstructure:"fail_closed" json:"fail_closed"` // refuse packages whose scan failed on infrastructure
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
ScanOnDownload bool `mapstructure:"scan_on_download" json:"scan_on_download"`
|
||||
@@ -236,8 +237,9 @@ type StaticConfig struct {
|
||||
|
||||
// GrypeConfig contains Grype scanner configuration
|
||||
type GrypeConfig struct {
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
Enabled bool `mapstructure:"enabled" json:"enabled"`
|
||||
Timeout time.Duration `mapstructure:"timeout" json:"timeout"`
|
||||
DBUpdateInterval time.Duration `mapstructure:"db_update_interval" json:"db_update_interval"` // must stay under grype's 120h max database age; 0 = 6h
|
||||
}
|
||||
|
||||
// GovulncheckConfig contains govulncheck scanner configuration
|
||||
@@ -424,8 +426,9 @@ func Default() *Config {
|
||||
BlockSuspicious: false,
|
||||
},
|
||||
Grype: GrypeConfig{
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
Enabled: false,
|
||||
Timeout: 5 * time.Minute,
|
||||
DBUpdateInterval: 6 * time.Hour,
|
||||
},
|
||||
Govulncheck: GovulncheckConfig{
|
||||
Enabled: false,
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type diskProbeScanner struct {
|
||||
stubScanner
|
||||
calls int
|
||||
}
|
||||
|
||||
func (c *diskProbeScanner) Scan(ctx context.Context, registry, packageName, version, path string) (*metadata.ScanResult, error) {
|
||||
c.calls++
|
||||
return c.stubScanner.Scan(ctx, registry, packageName, version, path)
|
||||
}
|
||||
|
||||
func diskGuardManager(t *testing.T, minFree int64, free uint64, freeErr error) (*Manager, *stubMetadataStore, *diskProbeScanner) {
|
||||
t.Helper()
|
||||
store := &stubMetadataStore{}
|
||||
mgr, err := New(config.SecurityConfig{Enabled: true, MinFreeBytes: minFree, ScanRetryInterval: time.Hour}, store)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(mgr.Stop)
|
||||
mgr.freeBytes = func(string) (uint64, error) { return free, freeErr }
|
||||
s := &diskProbeScanner{stubScanner: *stubResult("trivy", metadata.ScanStatusClean, nil)}
|
||||
mgr.RegisterScanner(s)
|
||||
return mgr, store, s
|
||||
}
|
||||
|
||||
func TestScanIsDeferredWhenDiskIsLow(t *testing.T) {
|
||||
mgr, store, s := diskGuardManager(t, 1<<30, 1<<20, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Zero(t, s.calls, "no scanner may run on a full disk")
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusError, store.savedResults[0].Status)
|
||||
assert.Equal(t, true, store.savedResults[0].Details[DetailInfrastructureError], "low disk is retried, not blamed on the package")
|
||||
}
|
||||
|
||||
func TestScanRunsWhenDiskHasRoom(t *testing.T) {
|
||||
mgr, store, s := diskGuardManager(t, 1<<30, 2<<30, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
require.Len(t, store.savedResults, 1)
|
||||
assert.Equal(t, metadata.ScanStatusClean, store.savedResults[0].Status)
|
||||
}
|
||||
|
||||
func TestDiskGuardOffByDefault(t *testing.T) {
|
||||
mgr, _, s := diskGuardManager(t, 0, 0, nil)
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
}
|
||||
|
||||
func TestDiskGuardMeasurementFailureDoesNotBlockScans(t *testing.T) {
|
||||
mgr, _, s := diskGuardManager(t, 1<<30, 0, errors.New("statfs failed"))
|
||||
|
||||
require.NoError(t, mgr.ScanPackage(context.Background(), "npm", "left-pad", "1.0.0", "/tmp/x"))
|
||||
|
||||
assert.Equal(t, 1, s.calls)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var errLowDiskSpace = stderrors.New("not enough free disk space to scan")
|
||||
|
||||
// checkDiskSpace refuses a scan while the temp dir, where scanners unpack packages, is short
|
||||
// of space. A failed measurement never blocks scans.
|
||||
func (m *Manager) checkDiskSpace() error {
|
||||
if m.config.MinFreeBytes <= 0 || m.freeBytes == nil {
|
||||
return nil
|
||||
}
|
||||
dir := os.TempDir()
|
||||
free, err := m.freeBytes(dir)
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("dir", dir).Msg("Cannot measure free disk space")
|
||||
return nil
|
||||
}
|
||||
if need := uint64(m.config.MinFreeBytes); free < need {
|
||||
return fmt.Errorf("%w: %d bytes free in %s, need %d", errLowDiskSpace, free, dir, need)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func diskFree(path string) (uint64, error) {
|
||||
var st syscall.Statfs_t
|
||||
if err := syscall.Statfs(path, &st); err != nil {
|
||||
return 0, fmt.Errorf("statfs %s: %w", path, err)
|
||||
}
|
||||
return st.Bavail * uint64(st.Bsize), nil // #nosec G115 -- block size is never negative
|
||||
}
|
||||
@@ -83,14 +83,21 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create temp dir: %w", err)
|
||||
}
|
||||
defer func() { _ = os.RemoveAll(tmpDir) }()
|
||||
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
|
||||
// scanned as a dependency of a wrapper module instead, and the wrapper imports its
|
||||
// packages because module-mode scanning only considers modules that provide an import.
|
||||
// Resolving the module reaches the module proxy.
|
||||
env := append(os.Environ(), "GOFLAGS=-mod=mod", "GOTOOLCHAIN=local", "GOWORK=off")
|
||||
// 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",
|
||||
"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 {
|
||||
return nil, fmt.Errorf("failed to write go.mod: %w", err)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
@@ -132,7 +133,7 @@ func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
|
||||
env, err := os.ReadFile(filepath.Join(rec, "env")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "-mod=mod|local\n", string(env))
|
||||
assert.Equal(t, "-mod=mod -modcacherw|local\n", string(env))
|
||||
|
||||
assert.Equal(t, []string{"-json", "-scan", "module"}, scannertest.Args(t, args))
|
||||
|
||||
@@ -144,6 +145,32 @@ func TestScanAuditsTheModuleItself(t *testing.T) {
|
||||
assert.NotContains(t, imports, "/internal", "internal packages cannot be imported")
|
||||
}
|
||||
|
||||
func TestScanRemovesTheModulesItDownloaded(t *testing.T) {
|
||||
rec := t.TempDir()
|
||||
// Like go, the fake leaves the module cache read-only unless GOFLAGS has -modcacherw.
|
||||
scannertest.Script(t, "go", fmt.Sprintf(`
|
||||
[ -n "$GOMODCACHE" ] || exit 1
|
||||
mkdir -p "$GOMODCACHE/example.com/[email protected]"
|
||||
touch "$GOMODCACHE/example.com/[email protected]/dep.go"
|
||||
case "$GOFLAGS" in *-modcacherw*) ;; *) chmod 0555 "$GOMODCACHE/example.com/[email protected]" ;; esac
|
||||
echo "$GOMODCACHE" > %q/go
|
||||
echo "github.com/google/uuid uuid 12 0 "`, rec))
|
||||
scannertest.Script(t, "govulncheck", fmt.Sprintf(`
|
||||
echo "$GOMODCACHE" > %q/govulncheck
|
||||
cat %q`, rec, abs(t, "google-uuid-v1.6.0.stream")))
|
||||
|
||||
res, err := New(config.GovulncheckConfig{}).Scan(context.Background(), "go", "github.com/google/uuid/@v/v1.6.0.zip", "v1.6.0", module(t))
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, metadata.ScanStatusClean, res.Status)
|
||||
listCache, err := os.ReadFile(filepath.Join(rec, "go")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
scanCache, err := os.ReadFile(filepath.Join(rec, "govulncheck")) // #nosec G304 -- test temp dir
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, string(listCache), string(scanCache), "govulncheck reads the modules go list downloaded")
|
||||
assert.NoDirExists(t, strings.TrimSpace(string(listCache)), "the scan keeps no downloaded modules")
|
||||
}
|
||||
|
||||
func TestScanCleanModule(t *testing.T) {
|
||||
scannertest.Script(t, "go", `echo "github.com/google/uuid uuid 12 0 "`)
|
||||
_, _ = fakeGovulncheck(t, abs(t, "google-uuid-v1.6.0.stream"), 0, "")
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultDBUpdateInterval = 6 * time.Hour
|
||||
// grype's own limits are 30s for the update check and 5m for the download.
|
||||
dbUpdateTimeout = 10 * time.Minute
|
||||
// Far past dbUpdateTimeout, so only a download whose grype process died is removed.
|
||||
abandonedAfter = time.Hour
|
||||
|
||||
downloadPrefix = "grype-db-download"
|
||||
// go-getter, which grype downloads through, stages the archive in the temp dir.
|
||||
getterPrefix = "getter"
|
||||
)
|
||||
|
||||
// RefreshDatabase updates the database every interval until stop closes. immediate runs
|
||||
// the first update at once; otherwise it waits one interval. interval 0 means 6h.
|
||||
func (s *Scanner) RefreshDatabase(stop <-chan struct{}, interval time.Duration, immediate bool) {
|
||||
if interval <= 0 {
|
||||
interval = defaultDBUpdateInterval
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go func() {
|
||||
<-stop
|
||||
cancel()
|
||||
}()
|
||||
|
||||
if immediate {
|
||||
s.refreshOnce(ctx)
|
||||
}
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
s.refreshOnce(ctx)
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scanner) refreshOnce(ctx context.Context) {
|
||||
if err := s.UpdateDatabase(ctx); err != nil {
|
||||
log.Error().Err(err).Str("scanner", ScannerName).Msg("Scheduled Grype database update failed")
|
||||
}
|
||||
}
|
||||
|
||||
// dbCacheDir mirrors grype's db.cache-dir default and its GRYPE_DB_CACHE_DIR override.
|
||||
func dbCacheDir() (string, error) {
|
||||
if dir := os.Getenv("GRYPE_DB_CACHE_DIR"); dir != "" {
|
||||
return dir, nil
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(home, ".cache", "grype", "db"), nil
|
||||
}
|
||||
|
||||
// removeAbandonedDownloads deletes database downloads last touched before cutoff. A grype
|
||||
// process killed mid-download never removes its staging dirs.
|
||||
func removeAbandonedDownloads(cutoff time.Time) {
|
||||
if dir, err := dbCacheDir(); err != nil {
|
||||
log.Warn().Err(err).Str("scanner", ScannerName).Msg("Cannot locate the Grype database cache")
|
||||
} else {
|
||||
removeStaleDirs(dir, downloadPrefix, cutoff)
|
||||
}
|
||||
removeStaleDirs(os.TempDir(), getterPrefix, cutoff)
|
||||
}
|
||||
|
||||
func removeStaleDirs(dir, prefix string, cutoff time.Time) {
|
||||
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 Grype downloads")
|
||||
}
|
||||
return
|
||||
}
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() || !strings.HasPrefix(e.Name(), prefix) {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil || !info.ModTime().Before(cutoff) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, e.Name())
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
log.Warn().Err(err).Str("path", path).Msg("Cannot remove abandoned Grype download")
|
||||
continue
|
||||
}
|
||||
log.Info().Str("path", path).Msg("Removed abandoned Grype download")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package grype
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scannertest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestScanDisablesDatabaseAutoUpdate(t *testing.T) {
|
||||
envFile := filepath.Join(t.TempDir(), "env")
|
||||
fix, err := filepath.Abs(fixture("purl-minimist-0.0.8.json"))
|
||||
require.NoError(t, err)
|
||||
scannertest.Script(t, "grype", "printf '%s' \"$GRYPE_DB_AUTO_UPDATE\" > '"+envFile+"'\ncat '"+fix+"'")
|
||||
|
||||
_, err = New(config.GrypeConfig{}).Scan(context.Background(), "npm", "minimist", "0.0.8", "/tmp/artifact")
|
||||
|
||||
require.NoError(t, err)
|
||||
got, err := os.ReadFile(envFile) // #nosec G304 -- test temp file
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "false", string(got), "a scan must never download the database itself")
|
||||
}
|
||||
|
||||
func mkdirAged(t *testing.T, path string, age time.Duration) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(path, 0o750))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(path, "archive"), []byte("x"), 0o600))
|
||||
when := time.Now().Add(-age)
|
||||
require.NoError(t, os.Chtimes(path, when, when))
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseRemovesAbandonedDownloads(t *testing.T) {
|
||||
cacheDir, tmpDir := t.TempDir(), t.TempDir()
|
||||
t.Setenv("GRYPE_DB_CACHE_DIR", cacheDir)
|
||||
t.Setenv("TMPDIR", tmpDir)
|
||||
scannertest.Fake(t, "grype", "", "", 0)
|
||||
|
||||
mkdirAged(t, filepath.Join(cacheDir, "grype-db-download111"), 2*time.Hour)
|
||||
mkdirAged(t, filepath.Join(cacheDir, "grype-db-download222"), time.Minute)
|
||||
mkdirAged(t, filepath.Join(cacheDir, "6"), 48*time.Hour)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "getter333"), 2*time.Hour)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "getter444"), time.Minute)
|
||||
mkdirAged(t, filepath.Join(tmpDir, "npm-audit-555"), 2*time.Hour)
|
||||
|
||||
require.NoError(t, New(config.GrypeConfig{}).UpdateDatabase(context.Background()))
|
||||
|
||||
assert.NoDirExists(t, filepath.Join(cacheDir, "grype-db-download111"))
|
||||
assert.NoDirExists(t, filepath.Join(tmpDir, "getter333"))
|
||||
assert.DirExists(t, filepath.Join(cacheDir, "grype-db-download222"), "a download in progress stays")
|
||||
assert.DirExists(t, filepath.Join(tmpDir, "getter444"), "a download in progress stays")
|
||||
assert.DirExists(t, filepath.Join(cacheDir, "6"), "the live database stays")
|
||||
assert.DirExists(t, filepath.Join(tmpDir, "npm-audit-555"), "other tools' temp dirs stay")
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseNeverOverlaps(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
lock, overlap := filepath.Join(dir, "lock"), filepath.Join(dir, "overlap")
|
||||
scannertest.Script(t, "grype",
|
||||
"mkdir '"+lock+"' 2>/dev/null || echo x >> '"+overlap+"'\nsleep 0.2\nrmdir '"+lock+"' 2>/dev/null\nexit 0")
|
||||
s := New(config.GrypeConfig{})
|
||||
|
||||
done := make(chan error, 4)
|
||||
for range 4 {
|
||||
go func() { done <- s.UpdateDatabase(context.Background()) }()
|
||||
}
|
||||
for range 4 {
|
||||
require.NoError(t, <-done)
|
||||
}
|
||||
|
||||
assert.NoFileExists(t, overlap, "two database downloads ran at once")
|
||||
}
|
||||
|
||||
func TestUpdateDatabaseOutlivesCallerCancel(t *testing.T) {
|
||||
marker := filepath.Join(t.TempDir(), "finished")
|
||||
scannertest.Script(t, "grype", "sleep 0.3\ntouch '"+marker+"'")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
|
||||
_ = New(config.GrypeConfig{}).UpdateDatabase(ctx)
|
||||
|
||||
assert.FileExists(t, marker, "a cancelled caller must not kill the download half way")
|
||||
}
|
||||
|
||||
func TestRefreshDatabaseRunsOnInterval(t *testing.T) {
|
||||
calls := filepath.Join(t.TempDir(), "calls")
|
||||
scannertest.Script(t, "grype", "echo \"$1 $2\" >> '"+calls+"'")
|
||||
stop := make(chan struct{})
|
||||
exited := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
New(config.GrypeConfig{}).RefreshDatabase(stop, 20*time.Millisecond, true)
|
||||
close(exited)
|
||||
}()
|
||||
|
||||
require.Eventually(t, func() bool {
|
||||
data, _ := os.ReadFile(calls) // #nosec G304 -- test temp file
|
||||
return strings.Count(string(data), "db update\n") >= 3
|
||||
}, 5*time.Second, 10*time.Millisecond)
|
||||
close(stop)
|
||||
select {
|
||||
case <-exited:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("refresh loop did not stop")
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,10 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
@@ -26,6 +28,7 @@ const ScannerName = "grype"
|
||||
type Scanner struct {
|
||||
version scanver.Cache
|
||||
config config.GrypeConfig
|
||||
dbMu sync.Mutex
|
||||
}
|
||||
|
||||
// New creates a new Grype scanner
|
||||
@@ -54,6 +57,8 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
|
||||
target = filePath
|
||||
}
|
||||
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")
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
output, err := cmd.Output()
|
||||
@@ -116,10 +121,17 @@ func (s *Scanner) Health(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateDatabase updates Grype's vulnerability database
|
||||
// UpdateDatabase updates Grype's vulnerability database. Calls are serialised, and the
|
||||
// download outlives a cancelled ctx so it never leaves a half-written database behind.
|
||||
func (s *Scanner) UpdateDatabase(ctx context.Context) error {
|
||||
log.Info().Str("scanner", ScannerName).Msg("Updating Grype database")
|
||||
s.dbMu.Lock()
|
||||
defer s.dbMu.Unlock()
|
||||
|
||||
log.Info().Str("scanner", ScannerName).Msg("Updating Grype database")
|
||||
removeAbandonedDownloads(time.Now().Add(-abandonedAfter))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dbUpdateTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "grype", "db", "update")
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
|
||||
+18
-2
@@ -99,6 +99,8 @@ type Manager struct {
|
||||
broadcaster events.Broadcaster
|
||||
retryTimers map[string]*time.Timer
|
||||
fileSource FileSource
|
||||
freeBytes func(path string) (uint64, error)
|
||||
stopCh chan struct{}
|
||||
inflight map[string]int
|
||||
scanners []Scanner
|
||||
config config.SecurityConfig
|
||||
@@ -113,10 +115,13 @@ func (m *Manager) Enabled() bool {
|
||||
return m.enabled
|
||||
}
|
||||
|
||||
// Stop cancels pending scan retries.
|
||||
// Stop cancels pending scan retries and background database refreshes.
|
||||
func (m *Manager) Stop() {
|
||||
m.stateMu.Lock()
|
||||
defer m.stateMu.Unlock()
|
||||
if !m.stopped && m.stopCh != nil {
|
||||
close(m.stopCh)
|
||||
}
|
||||
m.stopped = true
|
||||
for key, timer := range m.retryTimers {
|
||||
timer.Stop()
|
||||
@@ -212,6 +217,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
metadataStore: metadataStore,
|
||||
retryTimers: make(map[string]*time.Timer),
|
||||
inflight: make(map[string]int),
|
||||
freeBytes: diskFree,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
if !cfg.Enabled {
|
||||
@@ -252,6 +259,8 @@ func New(cfg config.SecurityConfig, metadataStore metadata.MetadataStore) (*Mana
|
||||
log.Warn().Err(err).Msg("Failed to update Grype database on startup")
|
||||
}
|
||||
}
|
||||
// Scans never update the database, so without this loop it ages past grype's limit.
|
||||
go grypeScanner.RefreshDatabase(manager.stopCh, cfg.Scanners.Grype.DBUpdateInterval, !cfg.UpdateDBOnStartup)
|
||||
}
|
||||
|
||||
// Initialize govulncheck scanner
|
||||
@@ -324,7 +333,14 @@ func (m *Manager) scan(ctx context.Context, registry, packageName, version strin
|
||||
scannerNames := make([]string, 0)
|
||||
var infraFailures, otherFailures int
|
||||
|
||||
for _, scanner := range m.scanners {
|
||||
scanners := m.scanners
|
||||
if err := m.checkDiskSpace(); err != nil {
|
||||
log.Warn().Err(err).Str("package", packageName).Msg("Deferring security scan")
|
||||
infraFailures++
|
||||
scanners = nil
|
||||
}
|
||||
|
||||
for _, scanner := range scanners {
|
||||
// Skip scanners that don't support this registry
|
||||
if !m.shouldRunScanner(scanner.Name(), registry) {
|
||||
log.Debug().
|
||||
|
||||
Reference in New Issue
Block a user