fix(scanner): rescan packages on remote storage via ScanFile

This commit is contained in:
2026-11-23 14:26:35 +00:00
parent 9b4659218c
commit a84f080b79
5 changed files with 101 additions and 31 deletions
+2 -1
View File
@@ -61,7 +61,8 @@ Currency: `sh lean4/scripts/check_currency.sh origin/main`.
cannot be migrated: the raw key holds no id and the stored hash covers the whole raw key. Re-issue them to leave the
legacy path. Production holds none.
- **GH-20.** SQLite startup merges old duplicate rows (package rows add up, derived rows keep one) and creates the unique indexes.
- **GH-21.** `RescanWorker` still skips remote storage ("No local file path available"); that is a separate, unchanged behaviour.
- **GH-21.** `RescanWorker` reads each blob through the cache `ScanFile` source, so periodic rescans cover S3 and SMB as well as
local storage. A remote blob is copied to a temp file for the scan and removed after it. Test: `TestRescanWorkerScansRemoteStorage`.
- **GH-22.** Frontend nginx dropped the `Cookie` header on `/api/` and `/ws` (the backend reads none; keys travel in `Authorization` / `X-API-Key`).
The server read buffer is `server.read_buffer_size`, default 16384 (Fiber's default is 8192): a long Referer or `Authorization` no longer gets 431.
- **GH-17 cleanup.** The per-handler `Access-Control-*` lines in `pkg/app/handlers*.go` are removed; `apiOriginGuard` is the only CORS
+1 -1
View File
@@ -314,7 +314,7 @@ func (a *App) initializeComponents() error {
// Initialize rescan worker if enabled
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.storage, a.config.Security.RescanInterval)
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval)
}
// Initialize WebSocket server
+75
View File
@@ -0,0 +1,75 @@
package cache
import (
"context"
"os"
"strings"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
"github.com/stretchr/testify/require"
)
// listingMetadata adds the full listing the rescan worker walks.
type listingMetadata struct{ scanMetadata }
func (m listingMetadata) ListPackages(context.Context, *metadata.ListOptions) ([]*metadata.Package, error) {
return m.list(0, func(*metadata.Package) bool { return true }, func(a, b *metadata.Package) bool { return a.Name < b.Name }), nil
}
// bodyScanner reports the bytes it can read at the path it is given.
type bodyScanner struct{ seen chan string }
func (*bodyScanner) Name() string { return "body-scanner" }
func (*bodyScanner) Health(context.Context) error { return nil }
func (s *bodyScanner) Scan(_ context.Context, registry, name, version, path string) (*metadata.ScanResult, error) {
body, err := os.ReadFile(path)
if err != nil {
s.seen <- "unreadable"
return nil, err
}
s.seen <- string(body)
return &metadata.ScanResult{Registry: registry, PackageName: name, PackageVersion: version, Scanner: s.Name(), Status: metadata.ScanStatusClean}, nil
}
// A backend with no local path (S3, SMB) must still be rescanned: the worker reads the blob
// through the cache's file source instead of skipping the package.
func TestRescanWorkerScansRemoteStorage(t *testing.T) {
clock := newFakeClock()
store := newMemStorage() // no GetLocalPath, like S3 and SMB
meta := listingMetadata{scanMetadata{newMemMetadata(clock)}}
scanMgr, err := scanner.New(config.SecurityConfig{Enabled: true}, meta)
require.NoError(t, err)
t.Cleanup(scanMgr.Stop)
bs := &bodyScanner{seen: make(chan string, 8)}
scanMgr.RegisterScanner(bs)
mgr, err := New(store, meta, scanMgr, nil, Config{Now: clock.Now, CleanupInterval: 24 * time.Hour})
require.NoError(t, err)
t.Cleanup(func() { _ = mgr.Close() })
scanMgr.SetFileSource(mgr.ScanFile)
ctx := context.Background()
require.NoError(t, store.Put(ctx, "npm/left-pad/1.3.0", strings.NewReader("tarball-bytes"), nil))
require.NoError(t, meta.SavePackage(ctx, &metadata.Package{
Registry: "npm", Name: "left-pad", Version: "1.3.0", StorageKey: "npm/left-pad/1.3.0",
CachedAt: clock.Now(), LastAccessed: clock.Now(),
}))
worker := scanner.NewRescanWorker(scanMgr, meta, time.Hour)
runCtx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() { worker.Start(runCtx); close(done) }()
t.Cleanup(func() { cancel(); <-done })
select {
case got := <-bs.seen:
require.Equal(t, "tarball-bytes", got)
case <-time.After(5 * time.Second):
t.Fatal("rescan never scanned the remote-storage package")
}
}
+17 -29
View File
@@ -6,14 +6,12 @@ import (
"time"
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
"github.com/lukaszraczylo/gohoarder/pkg/storage"
"github.com/rs/zerolog/log"
)
// RescanWorker handles periodic re-scanning of cached packages
type RescanWorker struct {
metadataStore metadata.MetadataStore
storage storage.StorageBackend
manager *Manager
stopCh chan struct{}
stopOnce sync.Once
@@ -21,11 +19,10 @@ type RescanWorker struct {
}
// NewRescanWorker creates a new rescan worker
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, storageBackend storage.StorageBackend, interval time.Duration) *RescanWorker {
func NewRescanWorker(manager *Manager, metadataStore metadata.MetadataStore, interval time.Duration) *RescanWorker {
return &RescanWorker{
manager: manager,
metadataStore: metadataStore,
storage: storageBackend,
interval: interval,
stopCh: make(chan struct{}),
}
@@ -123,7 +120,6 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
Str("version", pkg.Version).
Msg("Package needs rescanning")
// Get file path from storage using the storage key from the package metadata
if pkg.StorageKey == "" {
log.Warn().
Str("registry", pkg.Registry).
@@ -134,7 +130,18 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
continue
}
filePath, err := w.getPackageFilePath(ctx, pkg.StorageKey)
source := w.manager.currentFileSource()
if source == nil {
log.Debug().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("No file source configured, skipping rescan")
skipped++
continue
}
filePath, cleanup, err := source(ctx, pkg.Registry, pkg.Name, pkg.Version)
if err != nil {
log.Warn().
Err(err).
@@ -142,23 +149,15 @@ func (w *RescanWorker) rescanPackages(ctx context.Context) {
Str("package", pkg.Name).
Str("version", pkg.Version).
Str("storage_key", pkg.StorageKey).
Msg("Failed to get package file path, skipping rescan")
Msg("Failed to read package file, skipping rescan")
failed++
continue
}
if filePath == "" {
log.Debug().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("No local file path available, skipping rescan")
skipped++
continue
}
// Perform the actual scan
if err := w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath); err != nil {
err = w.manager.ScanPackage(ctx, pkg.Registry, pkg.Name, pkg.Version, filePath)
cleanup()
if err != nil {
log.Error().
Err(err).
Str("registry", pkg.Registry).
@@ -210,14 +209,3 @@ func (w *RescanWorker) needsRescan(ctx context.Context, pkg *metadata.Package) (
return false, nil
}
// getPackageFilePath retrieves the local file path for a package from storage
func (w *RescanWorker) getPackageFilePath(ctx context.Context, storageKey string) (string, error) {
// Check if storage backend supports local paths
if localProvider, ok := w.storage.(storage.LocalPathProvider); ok {
return localProvider.GetLocalPath(ctx, storageKey)
}
// If storage doesn't support local paths (S3, SMB), we can't rescan
return "", nil
}
+6
View File
@@ -65,6 +65,12 @@ func (m *Manager) SetFileSource(fs FileSource) {
m.stateMu.Unlock()
}
func (m *Manager) currentFileSource() FileSource {
m.stateMu.Lock()
defer m.stateMu.Unlock()
return m.fileSource
}
// Manager manages multiple security scanners
type Manager struct {
metadataStore metadata.MetadataStore