mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-25 06:35:21 +00:00
fix(scanner): re-read the blob when a scan retry finds its file gone
This commit is contained in:
@@ -308,6 +308,8 @@ func (a *App) initializeComponents() error {
|
|||||||
}
|
}
|
||||||
bootCancel()
|
bootCancel()
|
||||||
|
|
||||||
|
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||||
|
|
||||||
// Initialize rescan worker if enabled
|
// Initialize rescan worker if enabled
|
||||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||||
|
|||||||
Vendored
+33
@@ -693,6 +693,39 @@ func (m *Manager) store(ctx context.Context, registry, name, version, releaseVer
|
|||||||
return pkg, nil
|
return pkg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ScanFile returns a local file holding a cached package, for a scan retry. Backends with a
|
||||||
|
// local path serve it directly; others are copied to a temp file that cleanup removes.
|
||||||
|
func (m *Manager) ScanFile(ctx context.Context, registry, name, version string) (string, func(), error) {
|
||||||
|
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
if local, ok := m.storage.(storage.LocalPathProvider); ok {
|
||||||
|
path, pathErr := local.GetLocalPath(ctx, pkg.StorageKey)
|
||||||
|
return path, func() {}, pathErr
|
||||||
|
}
|
||||||
|
rc, err := m.storage.Get(ctx, pkg.StorageKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
defer func() { _ = rc.Close() }()
|
||||||
|
tmp, err := os.CreateTemp(os.TempDir(), "gohoarder-rescan-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
cleanup := func() { _ = os.Remove(tmp.Name()) } // #nosec G104 -- cleanup
|
||||||
|
if _, err := io.Copy(tmp, rc); err != nil {
|
||||||
|
_ = tmp.Close() // #nosec G104 -- cleanup
|
||||||
|
cleanup()
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
if err := tmp.Close(); err != nil {
|
||||||
|
cleanup()
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
return tmp.Name(), cleanup, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Delete removes a package from cache
|
// Delete removes a package from cache
|
||||||
func (m *Manager) Delete(ctx context.Context, registry, name, version string) error {
|
func (m *Manager) Delete(ctx context.Context, registry, name, version string) error {
|
||||||
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
pkg, err := m.metadata.GetPackage(ctx, registry, name, version)
|
||||||
|
|||||||
Vendored
+92
@@ -0,0 +1,92 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||||
|
"github.com/lukaszraczylo/gohoarder/pkg/scanner/scanerr"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// scanMetadata lets the real scanner.Manager record results against the in-memory store.
|
||||||
|
type scanMetadata struct {
|
||||||
|
*memMetadata
|
||||||
|
}
|
||||||
|
|
||||||
|
func (scanMetadata) SaveScanResult(context.Context, *metadata.ScanResult) error { return nil }
|
||||||
|
func (scanMetadata) GetScanResult(context.Context, string, string, string) (*metadata.ScanResult, error) {
|
||||||
|
return nil, fmt.Errorf("no result")
|
||||||
|
}
|
||||||
|
|
||||||
|
// fileScanner fails on infrastructure once, then succeeds; it records what it could read.
|
||||||
|
type fileScanner struct {
|
||||||
|
seen chan string
|
||||||
|
mu sync.Mutex
|
||||||
|
n int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*fileScanner) Name() string { return "file-scanner" }
|
||||||
|
func (*fileScanner) Health(context.Context) error { return nil }
|
||||||
|
func (s *fileScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.n++
|
||||||
|
n := s.n
|
||||||
|
s.mu.Unlock()
|
||||||
|
body, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
s.seen <- "unreadable"
|
||||||
|
} else {
|
||||||
|
s.seen <- string(body)
|
||||||
|
}
|
||||||
|
if n == 1 {
|
||||||
|
return nil, fmt.Errorf("%w: scanner timed out", scanerr.ErrInfrastructure)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: "file-scanner", Status: metadata.ScanStatusClean}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// On a backend with no local path (S3, SMB) the scan source is a temp file removed after the
|
||||||
|
// first scan; a retry must read the blob again instead of scanning a path that is gone.
|
||||||
|
func TestScanRetryOnRemoteStorageReadsBlobAgain(t *testing.T) {
|
||||||
|
clock := newFakeClock()
|
||||||
|
store := newMemStorage() // no GetLocalPath, like S3 and SMB
|
||||||
|
meta := scanMetadata{newMemMetadata(clock)}
|
||||||
|
|
||||||
|
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true, ScanRetryInterval: 50 * time.Millisecond}, meta)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(scanMgr.Stop)
|
||||||
|
fs := &fileScanner{seen: make(chan string, 8)}
|
||||||
|
scanMgr.RegisterScanner(fs)
|
||||||
|
|
||||||
|
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour, ScanWaitTimeout: 200 * time.Millisecond})
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Cleanup(func() { _ = mgr.Close() })
|
||||||
|
scanMgr.SetFileSource(mgr.ScanFile)
|
||||||
|
|
||||||
|
entry, err := mgr.Get(context.Background(), "npm", "left-pad", "1.3.0", func(context.Context) (*FetchResult, error) {
|
||||||
|
return &FetchResult{Data: io.NopCloser(strings.NewReader("tarball-bytes"))}, nil
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, _ = io.Copy(io.Discard, entry.Data)
|
||||||
|
_ = entry.Data.Close()
|
||||||
|
|
||||||
|
for attempt := 1; attempt <= 2; attempt++ {
|
||||||
|
select {
|
||||||
|
case got := <-fs.seen:
|
||||||
|
require.Equal(t, "tarball-bytes", got, "scan attempt %d must read the blob", attempt)
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatalf("scan attempt %d never ran", attempt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-1
@@ -6,6 +6,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
stderrors "errors"
|
stderrors "errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -53,11 +54,23 @@ const (
|
|||||||
maxScanRetries = 6
|
maxScanRetries = 6
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// FileSource returns a readable local copy of a stored package for a retry, plus its cleanup.
|
||||||
|
type FileSource func(ctx context.Context, registry, packageName, version string) (path string, cleanup func(), err error)
|
||||||
|
|
||||||
|
// SetFileSource lets a retry re-read the stored blob when the file its first scan used is gone,
|
||||||
|
// as with remote storage whose scan source is a temp file removed after the first attempt.
|
||||||
|
func (m *Manager) SetFileSource(fs FileSource) {
|
||||||
|
m.stateMu.Lock()
|
||||||
|
m.fileSource = fs
|
||||||
|
m.stateMu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
// Manager manages multiple security scanners
|
// Manager manages multiple security scanners
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
metadataStore metadata.MetadataStore
|
metadataStore metadata.MetadataStore
|
||||||
broadcaster events.Broadcaster
|
broadcaster events.Broadcaster
|
||||||
retryTimers map[string]*time.Timer
|
retryTimers map[string]*time.Timer
|
||||||
|
fileSource FileSource
|
||||||
inflight map[string]int
|
inflight map[string]int
|
||||||
scanners []Scanner
|
scanners []Scanner
|
||||||
config config.SecurityConfig
|
config config.SecurityConfig
|
||||||
@@ -121,8 +134,21 @@ func (m *Manager) scheduleRetry(registry, packageName, version, filePath string,
|
|||||||
m.retryTimers[key] = time.AfterFunc(interval, func() {
|
m.retryTimers[key] = time.AfterFunc(interval, func() {
|
||||||
m.stateMu.Lock()
|
m.stateMu.Lock()
|
||||||
delete(m.retryTimers, key)
|
delete(m.retryTimers, key)
|
||||||
|
source := m.fileSource
|
||||||
m.stateMu.Unlock()
|
m.stateMu.Unlock()
|
||||||
if err := m.scan(context.Background(), registry, packageName, version, filePath, attempt); err != nil {
|
|
||||||
|
ctx := context.Background()
|
||||||
|
path := filePath
|
||||||
|
if _, statErr := os.Stat(filePath); statErr != nil && source != nil {
|
||||||
|
fresh, cleanup, err := source(ctx, registry, packageName, version)
|
||||||
|
if err != nil {
|
||||||
|
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry could not re-read package")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer cleanup()
|
||||||
|
path = fresh
|
||||||
|
}
|
||||||
|
if err := m.scan(ctx, registry, packageName, version, path, attempt); err != nil {
|
||||||
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry failed")
|
log.Warn().Err(err).Str("package", packageName).Int("attempt", attempt).Msg("Scan retry failed")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user