mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
fix(proxy): serve escaped npm scopes and unscanned packages
npm and pnpm request scoped packages as @scope%2fname. Fiber's adaptor answers 404 to an escaped slash, so a route middleware now rewrites the scope separator before the adaptor runs. With scanning off, the cache still waited 30 s for a scan result and then refused the package. A scanner that is off is now treated as absent. A scan that fails on infrastructure (timeout, network error, upstream 5xx) no longer blocks the package until its entry expires. The package is served and the scan is retried every scan_retry_interval. Set security.fail_closed to refuse such packages. The OSV api_url default and the docs named the host, which answers 404 to a query. They now name https://api.osv.dev/v1/query, and a bare host is completed with the query path.
This commit is contained in:
Vendored
+30
-7
@@ -84,6 +84,15 @@ type Config struct {
|
||||
EvictionThreshold float64 // Trigger eviction when usage > threshold (0.0-1.0)
|
||||
MaxConcurrent int // Max concurrent upstream fetches
|
||||
MaxPackageSize int64 // Maximum package size in bytes (0 = default 2GB)
|
||||
ScanWaitTimeout time.Duration // How long the first download waits for its scan (0 = 30s)
|
||||
FailClosed bool // Refuse a package whose scan did not finish in time
|
||||
}
|
||||
|
||||
const defaultScanWaitTimeout = 30 * time.Second
|
||||
|
||||
// scannerToggle is implemented by scanners that can be switched off.
|
||||
type scannerToggle interface {
|
||||
Enabled() bool
|
||||
}
|
||||
|
||||
// CacheEntry represents a cached package
|
||||
@@ -126,6 +135,12 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
return nil, errors.New(errors.ErrCodeInvalidConfig, "metadata store is required")
|
||||
}
|
||||
|
||||
// A scanner that is switched off never records a result, so waiting for
|
||||
// one would stall every first download until the wait times out.
|
||||
if toggle, ok := scanner.(scannerToggle); ok && !toggle.Enabled() {
|
||||
scanner = nil
|
||||
}
|
||||
|
||||
// Scanner is optional - can be nil if security scanning is disabled
|
||||
if scanner != nil {
|
||||
log.Info().Msg("Cache manager initialized with security scanning enabled")
|
||||
@@ -152,6 +167,10 @@ func New(storage storage.StorageBackend, metadata metadata.MetadataStore, scanne
|
||||
config.MaxConcurrent = 100
|
||||
}
|
||||
|
||||
if config.ScanWaitTimeout == 0 {
|
||||
config.ScanWaitTimeout = defaultScanWaitTimeout
|
||||
}
|
||||
|
||||
if config.MaxPackageSize == 0 {
|
||||
config.MaxPackageSize = 2 * 1024 * 1024 * 1024 // 2GB default
|
||||
}
|
||||
@@ -345,10 +364,10 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
|
||||
// Wait briefly for initial scan to complete if scanner is enabled
|
||||
// This prevents serving vulnerable packages on first request.
|
||||
// SECURITY: timeouts MUST fail closed — never serve unscanned content.
|
||||
// A wait that times out serves the package unless FailClosed is set; the
|
||||
// scan keeps running and records its result for later requests.
|
||||
if m.scanner != nil && !isMetadataEntry {
|
||||
// Wait up to 30 seconds for scan to complete
|
||||
scanCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
scanCtx, cancel := context.WithTimeout(ctx, m.config.ScanWaitTimeout)
|
||||
defer cancel()
|
||||
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
@@ -358,13 +377,17 @@ func (m *Manager) getOrFetch(ctx context.Context, registry, name, version string
|
||||
for {
|
||||
select {
|
||||
case <-scanCtx.Done():
|
||||
// Fail closed: do NOT serve unscanned packages on timeout/cancel.
|
||||
// Package remains cached; subsequent requests can retry once
|
||||
// the scan completes.
|
||||
if ctx.Err() == nil && !m.config.FailClosed {
|
||||
log.Warn().
|
||||
Str("package", name).
|
||||
Str("version", version).
|
||||
Msg("Scan wait timed out - serving package, scan continues in background")
|
||||
break scanWait
|
||||
}
|
||||
log.Warn().
|
||||
Str("package", name).
|
||||
Str("version", version).
|
||||
Msg("Scan timeout - refusing to serve unscanned package (fail-closed)")
|
||||
Msg("Scan wait ended - refusing to serve unscanned package (fail-closed)")
|
||||
return nil, errors.New(errors.ErrCodeServiceUnavailable, "package scan in progress, retry shortly")
|
||||
|
||||
case <-ticker.C:
|
||||
|
||||
Vendored
+84
@@ -0,0 +1,84 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/storage"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// stubScanner never records a scan result, like a scanner that is off or hung.
|
||||
type stubScanner struct {
|
||||
enabled bool
|
||||
}
|
||||
|
||||
func (s *stubScanner) Enabled() bool { return s.enabled }
|
||||
func (s *stubScanner) ScanPackage(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (s *stubScanner) CheckVulnerabilities(context.Context, string, string, string) (bool, string, error) {
|
||||
return false, "", nil
|
||||
}
|
||||
|
||||
func newMissManager(t *testing.T, sc ScannerInterface, cfg Config) *Manager {
|
||||
t.Helper()
|
||||
mockStorage := &MockStorageBackend{}
|
||||
mockMetadata := &MockMetadataStore{}
|
||||
|
||||
mockMetadata.On("GetPackage", mock.Anything, "npm", "lodash", "4.17.21").Return(nil, errors.New("not found")).Once()
|
||||
mockMetadata.On("GetPackage", mock.Anything, "npm", "lodash", "4.17.21").
|
||||
Return(&metadata.Package{Registry: "npm", Name: "lodash", Version: "4.17.21", StorageKey: "npm/lodash/4.17.21"}, nil)
|
||||
mockStorage.On("GetQuota", mock.Anything).Return(&storage.QuotaInfo{Used: 100, Available: 900, Limit: 1000}, nil)
|
||||
mockStorage.On("Put", mock.Anything, "npm/lodash/4.17.21", mock.Anything, mock.Anything).Return(nil)
|
||||
mockMetadata.On("SavePackage", mock.Anything, mock.Anything).Return(nil)
|
||||
mockStorage.On("Get", mock.Anything, "npm/lodash/4.17.21").Return(io.NopCloser(strings.NewReader("data")), nil)
|
||||
mockMetadata.On("UpdateDownloadCount", mock.Anything, "npm", "lodash", "4.17.21").Return(nil)
|
||||
|
||||
mockStorage.On("Close").Return(nil)
|
||||
mockMetadata.On("Close").Return(nil)
|
||||
|
||||
manager, err := New(mockStorage, mockMetadata, sc, nil, cfg)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = manager.Close() })
|
||||
return manager
|
||||
}
|
||||
|
||||
func fetchLodash(context.Context) (*FetchResult, error) {
|
||||
return &FetchResult{Data: io.NopCloser(strings.NewReader("data")), UpstreamURL: "https://registry.npmjs.org/lodash"}, nil
|
||||
}
|
||||
|
||||
// With scanning disabled the first download must not wait for a scan result.
|
||||
func TestGet_DisabledScannerServesWithoutWaiting(t *testing.T) {
|
||||
manager := newMissManager(t, &stubScanner{enabled: false}, Config{ScanWaitTimeout: 5 * time.Second})
|
||||
|
||||
start := time.Now()
|
||||
entry, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
assert.Less(t, time.Since(start), 2*time.Second, "disabled scanner must not delay the first download")
|
||||
}
|
||||
|
||||
// A scan that does not finish in time is an infrastructure problem: serve it
|
||||
// unless the operator chose fail-closed.
|
||||
func TestGet_ScanWaitTimeoutServesByDefault(t *testing.T) {
|
||||
manager := newMissManager(t, &stubScanner{enabled: true}, Config{ScanWaitTimeout: 200 * time.Millisecond})
|
||||
|
||||
entry, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, entry)
|
||||
}
|
||||
|
||||
func TestGet_ScanWaitTimeoutRefusesWhenFailClosed(t *testing.T) {
|
||||
manager := newMissManager(t, &stubScanner{enabled: true}, Config{ScanWaitTimeout: 200 * time.Millisecond, FailClosed: true})
|
||||
|
||||
_, err := manager.Get(context.Background(), "npm", "lodash", "4.17.21", fetchLodash)
|
||||
require.Error(t, err)
|
||||
}
|
||||
Reference in New Issue
Block a user