Compare commits

...
4 Commits
Author SHA1 Message Date
lukaszraczylo 916e2b0aa5 fix(proxy): keep package names that start with the registry name
The app mounts each handler behind http.StripPrefix. The npm and PyPI
handlers trimmed the registry prefix a second time. A request for
npm-run-all reached upstream as -run-all, and the npm package itself
became an empty path. PyPI trimmed /simple without a segment check.
2026-11-24 00:22:49 +00:00
lukaszraczylo 30ebfaae3e chore(deploy): add rescan and scan-wait keys to the example configs
The Helm chart and the Kubernetes configmap listed only rescan_interval.
They now also set rescan_active_window, rescan_concurrency,
rescan_on_access and scan_wait_timeout. The values match the effective
code defaults, so a deploy behaves as before.
2026-11-24 00:20:01 +00:00
lukaszraczylo 3a7ffab4d5 fix(prewarming): start the worker and cache through the proxy path
The pre-warm worker was never started, and its fetch discarded the
response body, so nothing reached the cache. startWorkers now calls
Start. The worker hands each package to a Fetcher. ProxyFetcher calls
the npm, Go and PyPI handlers in-process, resolves the latest version,
and downloads the artifact. The cache and the scan queue then treat it
like a client request.

Pre-warming stays off unless prewarming.enabled is set. Stop is safe on
a worker that never started, and a second Start does nothing.
2026-11-24 00:19:36 +00:00
lukaszraczylo 22f2a8dfb9 fix(trivy): unpack npm tarballs before scanning
Trivy does not read archives, so a bare npm tarball always scanned clean.
The scanner now extracts the tarball into node_modules/<name> in a temp
dir and runs trivy rootfs on it, so the node-pkg analyzer sees the
package.json. Extraction rejects absolute paths, parent segments and
links that leave the tree, and caps the unpacked size at 512 MiB. The
temp dir is removed after the scan.

PyPI wheels and Go module zips share the archive problem and need their
own extractors. This commit does not change them.
2026-11-24 00:16:07 +00:00
15 changed files with 1016 additions and 96 deletions
@@ -32,6 +32,10 @@ data:
severity_threshold: medium
block_on_vulnerability: false
rescan_interval: 24h
rescan_active_window: 0s
rescan_concurrency: 1
rescan_on_access: false
scan_wait_timeout: 30s
handlers:
npm:
+4
View File
@@ -89,6 +89,10 @@ data:
block_on_severity: {{ .Values.security.blockOnSeverity | quote }}
scan_on_download: {{ .Values.security.scanOnDownload }}
rescan_interval: {{ .Values.security.rescanInterval | quote }}
rescan_active_window: {{ .Values.security.rescanActiveWindow | quote }}
rescan_concurrency: {{ .Values.security.rescanConcurrency }}
rescan_on_access: {{ .Values.security.rescanOnAccess }}
scan_wait_timeout: {{ .Values.security.scanWaitTimeout | quote }}
update_db_on_startup: {{ .Values.security.updateDbOnStartup }}
block_thresholds:
critical: {{ .Values.security.blockThresholds.critical }}
+4
View File
@@ -395,6 +395,10 @@ security:
blockOnSeverity: "high" # none, low, medium, high, critical
scanOnDownload: true
rescanInterval: "24h"
rescanActiveWindow: "0s" # rescan only packages requested within this window; 0 = all
rescanConcurrency: 1 # scans run in parallel per rescan cycle
rescanOnAccess: false # rescan a stale cache hit before serving it
scanWaitTimeout: "30s" # how long a first download waits for its scan
updateDbOnStartup: false
blockThresholds:
+16 -6
View File
@@ -60,6 +60,7 @@ type App struct {
analyticsEngine *analytics.Engine
wsServer *websocket.Server
prewarmWorker *prewarming.Worker
prewarmFetcher *prewarming.ProxyFetcher
cdnMiddleware *cdn.Middleware
}
@@ -348,14 +349,14 @@ func (a *App) initializeComponents() error {
// Initialize pre-warming worker. Operator-controlled via cfg.Prewarming;
// defaults are baked into config.Default() so unset fields stay sane.
log.Info().Msg("Initializing pre-warming worker")
a.prewarmFetcher = prewarming.NewProxyFetcher()
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{
Enabled: a.config.Prewarming.Enabled,
Interval: a.config.Prewarming.Interval,
MaxConcurrent: a.config.Prewarming.MaxConcurrent,
TopPackages: a.config.Prewarming.TopPackages,
CacheManager: a.cache,
Analytics: a.analyticsEngine,
NetworkClient: a.networkClient,
Popularity: a.analyticsEngine,
Fetcher: a.prewarmFetcher,
})
// Initialize CDN middleware
@@ -536,7 +537,9 @@ func (a *App) setupServer() error {
SumDBURL: sumDB,
CredStore: credStore,
})
goProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/go", goProxyHandler))
goProxyMounted := http.StripPrefix("/go", goProxyHandler)
a.prewarmFetcher.Mount("go", goProxyMounted)
goProxyWithCDN := a.cdnMiddleware.Handler(goProxyMounted)
if authEnabled {
a.app.All("/go/*", mwAuth, adaptor.HTTPHandler(goProxyWithCDN))
} else {
@@ -552,7 +555,9 @@ func (a *App) setupServer() error {
npmProxyHandler := npm.New(a.cache, a.networkClient, npm.Config{
Upstream: npmUpstream,
})
npmProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/npm", npmProxyHandler))
npmProxyMounted := http.StripPrefix("/npm", npmProxyHandler)
a.prewarmFetcher.Mount("npm", npmProxyMounted)
npmProxyWithCDN := a.cdnMiddleware.Handler(npmProxyMounted)
a.app.Use("/npm", func(c fiber.Ctx) error {
if canonical := npm.CanonicalPath(c.Path()); canonical != c.Path() {
c.Path(canonical)
@@ -574,7 +579,9 @@ func (a *App) setupServer() error {
pypiProxyHandler := pypi.New(a.cache, a.networkClient, pypi.Config{
Upstream: pypiUpstream,
})
pypiProxyWithCDN := a.cdnMiddleware.Handler(http.StripPrefix("/pypi", pypiProxyHandler))
pypiProxyMounted := http.StripPrefix("/pypi", pypiProxyHandler)
a.prewarmFetcher.Mount("pypi", pypiProxyMounted)
pypiProxyWithCDN := a.cdnMiddleware.Handler(pypiProxyMounted)
if authEnabled {
a.app.All("/pypi/*", mwAuth, adaptor.HTTPHandler(pypiProxyWithCDN))
} else {
@@ -631,6 +638,9 @@ func (a *App) startWorkers(ctx context.Context) {
if a.rescanWorker != nil {
go a.rescanWorker.Start(ctx)
}
// Start is a no-op unless prewarming.enabled is set.
a.prewarmWorker.Start(ctx)
}
func (a *App) Run() error {
+33
View File
@@ -12,6 +12,7 @@ import (
"net/url"
"os"
"os/exec"
"slices"
"strconv"
"strings"
"testing"
@@ -316,3 +317,35 @@ func TestNPMMetadataTTLOverrideReachesCache(t *testing.T) {
}
t.Fatalf("no npm metadata entry with an expiry among %d packages", len(pkgs))
}
// The mount already strips the registry prefix, so a package named after the registry must keep its name.
func TestPackagesNamedAfterTheRegistryKeepTheirName(t *testing.T) {
var npmSeen, pypiSeen []string
npmUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
npmSeen = append(npmSeen, r.URL.Path)
_, _ = w.Write([]byte(`{"name":"x","versions":{}}`))
}))
t.Cleanup(npmUp.Close)
pypiUp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
pypiSeen = append(pypiSeen, r.URL.Path)
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(`<html><body></body></html>`))
}))
t.Cleanup(pypiUp.Close)
a := newTestApp(t, func(c *config.Config) {
c.Handlers.NPM.UpstreamRegistry = npmUp.URL
c.Handlers.PyPI.SimpleAPIURL = pypiUp.URL + "/simple"
})
for _, target := range []string{"/npm/npm-run-all", "/npm/npm", "/pypi/simple/pypi-a/", "/pypi/pypi-b/"} {
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
t.Fatalf("GET %s: status = %d, body %q", target, code, body)
}
}
if want := []string{"/npm-run-all", "/npm"}; !slices.Equal(npmSeen, want) {
t.Errorf("npm upstream paths = %v, want %v", npmSeen, want)
}
if want := []string{"/simple/pypi-a/", "/simple/pypi-b/"}; !slices.Equal(pypiSeen, want) {
t.Errorf("pypi upstream paths = %v, want %v", pypiSeen, want)
}
}
+46
View File
@@ -4,6 +4,10 @@ import (
"context"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
"github.com/lukaszraczylo/gohoarder/pkg/config"
"github.com/lukaszraczylo/gohoarder/pkg/prewarming"
)
// TestWorkersDrainTheBroadcastChannel pins that the app starts the websocket
@@ -36,3 +40,45 @@ func TestWorkersDrainTheBroadcastChannel(t *testing.T) {
t.Fatalf("dropped %d of %d events; the broadcast loop is not draining the channel", dropped, bursts*burstLen)
}
}
type recordingFetcher struct{ got chan prewarming.PackageInfo }
func (f recordingFetcher) Fetch(_ context.Context, pkg prewarming.PackageInfo) error {
f.got <- pkg
return nil
}
type fixedPopularity struct{}
func (fixedPopularity) GetTopPackages(int) []analytics.PopularPackage {
return []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}}
}
func (fixedPopularity) GetTrendingPackages(int) []analytics.PopularPackage { return nil }
// TestEnabledPrewarmWorkerStartsWithTheApp pins that startWorkers starts the pre-warm loop.
func TestEnabledPrewarmWorkerStartsWithTheApp(t *testing.T) {
a := newTestApp(t, nil)
f := recordingFetcher{got: make(chan prewarming.PackageInfo, 4)}
a.prewarmWorker = prewarming.NewWorker(prewarming.Config{Enabled: true, Fetcher: f, Popularity: fixedPopularity{}})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a.startWorkers(ctx)
defer a.prewarmWorker.Stop()
select {
case pkg := <-f.got:
if pkg.Name != "lodash" {
t.Fatalf("pre-warmed %q, want lodash", pkg.Name)
}
case <-time.After(10 * time.Second):
t.Fatal("pre-warm worker never ran after startWorkers")
}
}
func TestPrewarmingStaysOffByDefault(t *testing.T) {
if config.Default().Prewarming.Enabled {
t.Fatal("prewarming.enabled must default to false")
}
}
+266
View File
@@ -0,0 +1,266 @@
package prewarming
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html"
"net/http"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"github.com/lukaszraczylo/gohoarder/pkg/proxy/pypi"
)
const (
registryNPM = "npm"
registryPyPI = "pypi"
registryGo = "go"
// proxyHost is only a placeholder: the handlers are called in-process and never dial it.
proxyHost = "gohoarder.invalid"
maxMetadataBytes = 64 << 20
)
var (
hrefPattern = regexp.MustCompile(`href="([^"]+)"`)
numericSemVer = regexp.MustCompile(`^\d+(\.\d+)*$`)
distSuffixes = []string{".whl", ".tar.gz", ".zip", ".egg"}
)
// ProxyFetcher pre-warms through the registry handlers in-process, so artifacts are cached,
// scanned and policy-checked exactly like a client request.
type ProxyFetcher struct {
handlers map[string]http.Handler
}
// NewProxyFetcher returns a fetcher with no registries mounted.
func NewProxyFetcher() *ProxyFetcher {
return &ProxyFetcher{handlers: make(map[string]http.Handler)}
}
// Mount registers the handler serving a registry; it must already strip the "/<registry>" prefix
// the way the HTTP server mounts it. Mount before the worker starts.
func (f *ProxyFetcher) Mount(registry string, h http.Handler) {
f.handlers[registry] = h
}
// Fetch resolves the version when it is empty or LatestVersion, then downloads the artifact.
func (f *ProxyFetcher) Fetch(ctx context.Context, pkg PackageInfo) error {
h, ok := f.handlers[pkg.Registry]
if !ok {
return fmt.Errorf("registry %q is not mounted", pkg.Registry)
}
if !safeName(pkg.Name) {
return fmt.Errorf("unsafe package name %q", pkg.Name)
}
latest := pkg.Version == "" || pkg.Version == LatestVersion
switch pkg.Registry {
case registryNPM:
return f.fetchNPM(ctx, h, pkg.Name, pkg.Version, latest)
case registryGo:
return f.fetchGo(ctx, h, pkg.Name, pkg.Version, latest)
case registryPyPI:
return f.fetchPyPI(ctx, h, pkg.Name, pkg.Version, latest)
default:
return fmt.Errorf("unsupported registry %q", pkg.Registry)
}
}
func safeName(name string) bool {
return name != "" && !strings.ContainsAny(name, "?#\\") && !strings.Contains(name, "..") && !strings.HasPrefix(name, "/")
}
func (f *ProxyFetcher) fetchNPM(ctx context.Context, h http.Handler, name, version string, latest bool) error {
if latest {
body, err := call(ctx, h, "/npm/"+name, "", true)
if err != nil {
return fmt.Errorf("npm metadata: %w", err)
}
var meta struct {
DistTags map[string]string `json:"dist-tags"`
}
if err := json.Unmarshal(body, &meta); err != nil {
return fmt.Errorf("npm metadata: %w", err)
}
if version = meta.DistTags["latest"]; version == "" {
return fmt.Errorf("npm %s has no latest dist-tag", name)
}
}
bare := name[strings.LastIndex(name, "/")+1:]
_, err := call(ctx, h, "/npm/"+name+"/-/"+bare+"-"+version+".tgz", "", false)
return err
}
func (f *ProxyFetcher) fetchGo(ctx context.Context, h http.Handler, name, version string, latest bool) error {
if latest {
body, err := call(ctx, h, "/go/"+name+"/@latest", "", true)
if err != nil {
return fmt.Errorf("go latest: %w", err)
}
var info struct{ Version string }
if err := json.Unmarshal(body, &info); err != nil {
return fmt.Errorf("go latest: %w", err)
}
if version = info.Version; version == "" {
return fmt.Errorf("go %s has no latest version", name)
}
}
_, err := call(ctx, h, "/go/"+name+"/@v/"+version+".zip", "", false)
return err
}
func (f *ProxyFetcher) fetchPyPI(ctx context.Context, h http.Handler, name, version string, latest bool) error {
page, err := call(ctx, h, "/pypi/simple/"+name+"/", "text/html", true)
if err != nil {
return fmt.Errorf("pypi package page: %w", err)
}
link, err := pickPyPIFile(page, version, latest)
if err != nil {
return fmt.Errorf("pypi %s: %w", name, err)
}
if !strings.HasPrefix(link.Path, "/pypi/") {
return fmt.Errorf("pypi %s: link %q is not a proxy path", name, link.Path)
}
_, err = call(ctx, h, link.Path, "", false, link.RawQuery)
return err
}
type distFile struct {
link *url.URL
version string
}
// pickPyPIFile chooses one distribution: the wanted version or the highest plain release,
// preferring a wheel over an sdist.
func pickPyPIFile(page []byte, version string, latest bool) (*url.URL, error) {
var wheel, sdist *distFile
for _, m := range hrefPattern.FindAllSubmatch(page, -1) {
u, err := url.Parse(html.UnescapeString(string(m[1])))
if err != nil {
continue
}
file := path.Base(u.Path)
if !hasDistSuffix(file) {
continue
}
cand := &distFile{link: u, version: pypi.ReleaseVersion(file)}
if latest {
if !numericSemVer.MatchString(cand.version) {
continue
}
} else if cand.version != version {
continue
}
if strings.HasSuffix(file, ".whl") {
wheel = better(wheel, cand, latest)
} else {
sdist = better(sdist, cand, latest)
}
}
for _, c := range []*distFile{wheel, sdist} {
if c != nil {
return c.link, nil
}
}
if latest {
return nil, fmt.Errorf("no plain release file listed")
}
return nil, fmt.Errorf("no file listed for version %q", version)
}
func better(cur, cand *distFile, latest bool) *distFile {
if cur == nil || (latest && compareVersions(cand.version, cur.version) > 0) {
return cand
}
return cur
}
func hasDistSuffix(file string) bool {
for _, s := range distSuffixes {
if strings.HasSuffix(file, s) {
return true
}
}
return false
}
func compareVersions(a, b string) int {
as, bs := strings.Split(a, "."), strings.Split(b, ".")
for i := 0; i < len(as) || i < len(bs); i++ {
var x, y int
if i < len(as) {
x, _ = strconv.Atoi(as[i])
}
if i < len(bs) {
y, _ = strconv.Atoi(bs[i])
}
if x != y {
if x > y {
return 1
}
return -1
}
}
return 0
}
// call serves a GET through h. It keeps the body only when capture is set and fails on non-200.
func call(ctx context.Context, h http.Handler, p, accept string, capture bool, rawQuery ...string) ([]byte, error) {
u := url.URL{Scheme: "http", Host: proxyHost, Path: p}
if len(rawQuery) > 0 {
u.RawQuery = rawQuery[0]
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return nil, err
}
if accept != "" {
req.Header.Set("Accept", accept)
}
w := &sink{header: make(http.Header), capture: capture}
h.ServeHTTP(w, req)
if w.status == 0 {
w.status = http.StatusOK
}
if w.status != http.StatusOK {
return nil, fmt.Errorf("GET %s: status %d", p, w.status)
}
if w.overflow {
return nil, fmt.Errorf("GET %s: response over %d bytes", p, maxMetadataBytes)
}
return w.buf.Bytes(), nil
}
// sink is a ResponseWriter that discards artifact bytes so a pre-warm never holds one in memory.
type sink struct {
header http.Header
buf bytes.Buffer
status int
capture bool
overflow bool
}
func (s *sink) Header() http.Header { return s.header }
func (s *sink) WriteHeader(code int) {
if s.status == 0 {
s.status = code
}
}
func (s *sink) Write(b []byte) (int, error) {
s.WriteHeader(http.StatusOK)
if s.capture {
if s.buf.Len()+len(b) > maxMetadataBytes {
s.overflow = true
} else {
s.buf.Write(b)
}
}
return len(b), nil
}
+129
View File
@@ -0,0 +1,129 @@
package prewarming
import (
"context"
"net/http"
"strings"
"sync"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type routes struct {
resp map[string]string
hits []string
mu sync.Mutex
}
func (r *routes) ServeHTTP(w http.ResponseWriter, req *http.Request) {
key := req.URL.RequestURI()
r.mu.Lock()
r.hits = append(r.hits, key)
r.mu.Unlock()
body, ok := r.resp[key]
if !ok {
http.NotFound(w, req)
return
}
_, _ = w.Write([]byte(body))
}
func fetcherFor(registry string, resp map[string]string) (*ProxyFetcher, *routes) {
rt := &routes{resp: resp}
f := NewProxyFetcher()
f.Mount(registry, rt)
return f, rt
}
func TestFetchNPMLatestDownloadsTheTarball(t *testing.T) {
f, rt := fetcherFor("npm", map[string]string{
"/npm/@scope/pkg": `{"dist-tags":{"latest":"2.1.0"}}`,
"/npm/@scope/pkg/-/pkg-2.1.0.tgz": "tarball",
})
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "@scope/pkg", Version: LatestVersion}))
assert.Equal(t, []string{"/npm/@scope/pkg", "/npm/@scope/pkg/-/pkg-2.1.0.tgz"}, rt.hits)
}
func TestFetchNPMExplicitVersionSkipsMetadata(t *testing.T) {
f, rt := fetcherFor("npm", map[string]string{"/npm/lodash/-/lodash-4.17.21.tgz": "x"})
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "lodash", Version: "4.17.21"}))
assert.Equal(t, []string{"/npm/lodash/-/lodash-4.17.21.tgz"}, rt.hits)
}
func TestFetchGoLatestDownloadsTheZip(t *testing.T) {
f, rt := fetcherFor("go", map[string]string{
"/go/example.com/m/@latest": `{"Version":"v1.2.3","Time":"2026-01-01T00:00:00Z"}`,
"/go/example.com/m/@v/v1.2.3.zip": "zip",
})
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "go", Name: "example.com/m", Version: LatestVersion}))
assert.Equal(t, []string{"/go/example.com/m/@latest", "/go/example.com/m/@v/v1.2.3.zip"}, rt.hits)
}
const pypiPage = `<html><body>
<a href="http://h/pypi/req/req-2.9.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fa">a</a>
<a href="http://h/pypi/req/req-2.31.0.tar.gz?original_url=https%3A%2F%2Ffiles%2Fb">b</a>
<a href="http://h/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&amp;x=1">c</a>
<a href="http://h/pypi/req/req-3.0.0rc1-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fd">d</a>
<a href="http://h/pypi/req/req-2.31.0-py3-none-any.whl.metadata?original_url=m">m</a>
</body></html>`
func TestFetchPyPILatestPicksHighestPlainReleaseWheel(t *testing.T) {
f, rt := fetcherFor("pypi", map[string]string{
"/pypi/simple/req/": pypiPage,
"/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1": "whl",
})
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: LatestVersion}))
require.Len(t, rt.hits, 2)
assert.Equal(t, "/pypi/req/req-2.31.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fc&x=1", rt.hits[1])
}
func TestFetchPyPIExplicitVersionAndMissingVersion(t *testing.T) {
f, rt := fetcherFor("pypi", map[string]string{
"/pypi/simple/req/": pypiPage,
"/pypi/req/req-2.9.0-py3-none-any.whl?original_url=https%3A%2F%2Ffiles%2Fa": "whl",
})
require.NoError(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: "2.9.0"}))
assert.Contains(t, rt.hits[1], "req-2.9.0")
require.ErrorContains(t, f.Fetch(context.Background(), PackageInfo{Registry: "pypi", Name: "req", Version: "9.9.9"}), "no file listed")
}
func TestFetchRejectsBadInput(t *testing.T) {
f, rt := fetcherFor("npm", map[string]string{})
ctx := context.Background()
require.ErrorContains(t, f.Fetch(ctx, PackageInfo{Registry: "cargo", Name: "x"}), "not mounted")
for _, name := range []string{"", "../etc", "a?b", "/abs", "a#b"} {
assert.ErrorContains(t, f.Fetch(ctx, PackageInfo{Registry: "npm", Name: name}), "unsafe package name", name)
}
assert.Empty(t, rt.hits)
}
func TestFetchReportsUpstreamFailure(t *testing.T) {
f, _ := fetcherFor("npm", map[string]string{})
err := f.Fetch(context.Background(), PackageInfo{Registry: "npm", Name: "ghost", Version: LatestVersion})
require.Error(t, err)
assert.Contains(t, err.Error(), "404")
}
func TestSinkDiscardsArtifactBytes(t *testing.T) {
big := strings.Repeat("a", 1<<20)
h := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte(big)) })
body, err := call(context.Background(), h, "/x", "", false)
require.NoError(t, err)
assert.Empty(t, body)
}
+70 -81
View File
@@ -8,11 +8,28 @@ import (
"time"
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
"github.com/lukaszraczylo/gohoarder/pkg/cache"
"github.com/lukaszraczylo/gohoarder/pkg/network"
"github.com/rs/zerolog/log"
)
// LatestVersion asks the Fetcher to resolve the newest release itself.
const LatestVersion = "latest"
const (
fetchTimeout = 5 * time.Minute
trendingPackages = 50
)
// Fetcher pulls an artifact through the proxy path, so it is cached and scanned like a client request.
type Fetcher interface {
Fetch(ctx context.Context, pkg PackageInfo) error
}
// Popularity ranks packages by recent demand.
type Popularity interface {
GetTopPackages(limit int) []analytics.PopularPackage
GetTrendingPackages(limit int) []analytics.PopularPackage
}
// PackageInfo represents a package to pre-warm
type PackageInfo struct {
Registry string
@@ -23,21 +40,21 @@ type PackageInfo struct {
// Worker handles background pre-warming of popular packages
type Worker struct {
cache *cache.Manager
analytics *analytics.Engine
client *network.Client
stopChan chan struct{}
popularity Popularity
fetcher Fetcher
cancel context.CancelFunc
wg sync.WaitGroup
mu sync.Mutex
interval time.Duration
maxConcurrent int
topPackages int
enabled bool
}
// Config holds pre-warming worker configuration
type Config struct {
CacheManager *cache.Manager
Analytics *analytics.Engine
NetworkClient *network.Client
Popularity Popularity
Fetcher Fetcher
Interval time.Duration
MaxConcurrent int
TopPackages int
@@ -57,13 +74,12 @@ func NewWorker(cfg Config) *Worker {
}
worker := &Worker{
cache: cfg.CacheManager,
analytics: cfg.Analytics,
client: cfg.NetworkClient,
popularity: cfg.Popularity,
fetcher: cfg.Fetcher,
interval: cfg.Interval,
maxConcurrent: cfg.MaxConcurrent,
topPackages: cfg.TopPackages,
enabled: cfg.Enabled,
stopChan: make(chan struct{}),
}
if cfg.Enabled {
@@ -78,15 +94,26 @@ func NewWorker(cfg Config) *Worker {
return worker
}
// Start begins the pre-warming worker
// Start begins the pre-warming worker; it is a no-op when disabled or already started.
func (w *Worker) Start(ctx context.Context) {
if !w.enabled {
log.Debug().Msg("Pre-warming worker is disabled, not starting")
return
}
if w.fetcher == nil || w.popularity == nil {
log.Warn().Msg("Pre-warming worker has no fetcher or popularity source, not starting")
return
}
w.mu.Lock()
defer w.mu.Unlock()
if w.cancel != nil {
return
}
runCtx, cancel := context.WithCancel(ctx)
w.cancel = cancel
w.wg.Add(1)
go w.run(ctx)
go w.run(runCtx)
log.Info().Msg("Pre-warming worker started")
}
@@ -97,15 +124,11 @@ func (w *Worker) run(ctx context.Context) {
ticker := time.NewTicker(w.interval)
defer ticker.Stop()
// Run immediately on start
w.prewarmPopularPackages(ctx)
for {
select {
case <-ctx.Done():
log.Info().Msg("Pre-warming worker stopping due to context cancellation")
return
case <-w.stopChan:
log.Info().Msg("Pre-warming worker stopped")
return
case <-ticker.C:
@@ -119,14 +142,14 @@ func (w *Worker) prewarmPopularPackages(ctx context.Context) {
log.Info().Msg("Starting pre-warming cycle")
// Get popular packages from analytics
popularPackages := w.analytics.GetTopPackages(100)
popularPackages := w.popularity.GetTopPackages(w.topPackages)
if len(popularPackages) == 0 {
log.Debug().Msg("No popular packages found for pre-warming")
return
}
// Get trending packages for additional candidates
trendingPackages := w.analytics.GetTrendingPackages(50)
trendingPackages := w.popularity.GetTrendingPackages(trendingPackages)
// Combine and deduplicate
packages := w.combinePackages(popularPackages, trendingPackages)
@@ -141,7 +164,7 @@ func (w *Worker) prewarmPopularPackages(ctx context.Context) {
workChan <- PackageInfo{
Registry: pkg.Registry,
Name: pkg.Name,
Version: "latest", // Pre-warm latest version
Version: LatestVersion,
Priority: int(pkg.Downloads),
}
}
@@ -168,13 +191,13 @@ func (w *Worker) processPackages(ctx context.Context, workerID int, workChan <-c
case <-ctx.Done():
return
default:
w.prewarmPackage(ctx, pkg, workerID)
_ = w.prewarmPackage(ctx, pkg, workerID) // logged inside
}
}
}
// prewarmPackage fetches and caches a single package
func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID int) {
// prewarmPackage fetches a single package through the proxy path
func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID int) error {
log.Debug().
Int("worker", workerID).
Str("registry", pkg.Registry).
@@ -182,60 +205,24 @@ func (w *Worker) prewarmPackage(ctx context.Context, pkg PackageInfo, workerID i
Str("version", pkg.Version).
Msg("Pre-warming package")
// Build URL based on registry
url := w.buildPackageURL(pkg)
if url == "" {
log.Warn().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Msg("Cannot build URL for registry")
return
}
// Fetch package from upstream
reqCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
reqCtx, cancel := context.WithTimeout(ctx, fetchTimeout)
defer cancel()
body, statusCode, err := w.client.Get(reqCtx, url, nil)
if err != nil {
if err := w.fetcher.Fetch(reqCtx, pkg); err != nil {
log.Error().
Err(err).
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Msg("Failed to fetch package for pre-warming")
return
}
defer func() { _ = body.Close() }() // #nosec G104 -- Cleanup, error not critical
if statusCode != 200 {
log.Warn().
Int("status", statusCode).
Str("package", pkg.Name).
Msg("Non-200 response for package")
return
Msg("Failed to pre-warm package")
return err
}
// Cache the package
// In a real implementation, this would read the response body and store it
log.Info().
Str("registry", pkg.Registry).
Str("package", pkg.Name).
Str("version", pkg.Version).
Msg("Successfully pre-warmed package")
}
// buildPackageURL builds the upstream URL for a package
func (w *Worker) buildPackageURL(pkg PackageInfo) string {
// This is simplified - in reality, each registry has different URL patterns
switch pkg.Registry {
case "npm":
return "https://registry.npmjs.org/" + pkg.Name
case "pypi":
return "https://pypi.org/simple/" + pkg.Name + "/"
case "go":
// Go modules use different URL patterns
return "https://proxy.golang.org/" + pkg.Name + "/@latest"
default:
return ""
}
Msg("Pre-warmed package")
return nil
}
// combinePackages merges popular and trending packages, removing duplicates
@@ -262,22 +249,25 @@ func (w *Worker) combinePackages(popular, trending []analytics.PopularPackage) [
return result
}
// Stop gracefully stops the pre-warming worker
// Stop stops the worker and waits for it; it is safe on a nil, disabled or never-started worker.
func (w *Worker) Stop() {
if !w.enabled {
if w == nil {
return
}
log.Info().Msg("Stopping pre-warming worker")
close(w.stopChan)
w.mu.Lock()
cancel := w.cancel
w.mu.Unlock()
if cancel != nil {
log.Info().Msg("Stopping pre-warming worker")
cancel()
}
w.wg.Wait()
log.Info().Msg("Pre-warming worker stopped")
}
// TriggerPrewarm manually triggers a pre-warming cycle
func (w *Worker) TriggerPrewarm(ctx context.Context) {
if !w.enabled {
log.Warn().Msg("Cannot trigger pre-warm: worker is disabled")
if !w.enabled || w.fetcher == nil || w.popularity == nil {
log.Warn().Msg("Cannot trigger pre-warm: worker is disabled or unconfigured")
return
}
@@ -287,8 +277,8 @@ func (w *Worker) TriggerPrewarm(ctx context.Context) {
// PrewarmPackage pre-warms a specific package
func (w *Worker) PrewarmPackage(ctx context.Context, registry, name, version string) error {
if !w.enabled {
log.Warn().Msg("Pre-warming worker is disabled")
if !w.enabled || w.fetcher == nil {
log.Warn().Msg("Pre-warming worker is disabled or unconfigured")
return nil
}
@@ -299,8 +289,7 @@ func (w *Worker) PrewarmPackage(ctx context.Context, registry, name, version str
Priority: 100,
}
w.prewarmPackage(ctx, pkg, 0)
return nil
return w.prewarmPackage(ctx, pkg, 0)
}
// GetStatus returns the current status of the pre-warming worker
+134
View File
@@ -0,0 +1,134 @@
package prewarming
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/lukaszraczylo/gohoarder/pkg/analytics"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type fakeFetcher struct {
err error
got map[string]PackageInfo
calls chan PackageInfo
mu sync.Mutex
}
func newFakeFetcher() *fakeFetcher {
return &fakeFetcher{got: map[string]PackageInfo{}, calls: make(chan PackageInfo, 64)}
}
func (f *fakeFetcher) Fetch(_ context.Context, pkg PackageInfo) error {
f.mu.Lock()
f.got[pkg.Registry+":"+pkg.Name] = pkg
f.mu.Unlock()
f.calls <- pkg
return f.err
}
type fakePopularity struct {
top, trending []analytics.PopularPackage
topLimit int
}
func (p *fakePopularity) GetTopPackages(limit int) []analytics.PopularPackage {
p.topLimit = limit
return p.top
}
func (p *fakePopularity) GetTrendingPackages(int) []analytics.PopularPackage { return p.trending }
func samplePopularity() *fakePopularity {
return &fakePopularity{
top: []analytics.PopularPackage{{Registry: "npm", Name: "lodash", Downloads: 9}, {Registry: "go", Name: "example.com/m", Downloads: 3}},
trending: []analytics.PopularPackage{{Registry: "npm", Name: "lodash"}, {Registry: "pypi", Name: "requests"}},
}
}
func TestCycleFetchesEachPopularPackageOnceAsLatest(t *testing.T) {
f, pop := newFakeFetcher(), samplePopularity()
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: pop, MaxConcurrent: 2, TopPackages: 7})
w.prewarmPopularPackages(context.Background())
assert.Len(t, f.got, 3, "lodash appears in both lists and must be fetched once")
for _, p := range f.got {
assert.Equal(t, LatestVersion, p.Version)
}
assert.Equal(t, 7, pop.topLimit)
}
func TestFetchFailureDoesNotStopTheCycle(t *testing.T) {
f := newFakeFetcher()
f.err = errors.New("upstream down")
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity(), MaxConcurrent: 1})
w.prewarmPopularPackages(context.Background())
assert.Len(t, f.got, 3)
}
func TestStartRunsACycleAndStopEndsIt(t *testing.T) {
f := newFakeFetcher()
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity(), Interval: time.Hour})
w.Start(context.Background())
w.Start(context.Background()) // second start must not spawn a second loop
select {
case <-f.calls:
case <-time.After(5 * time.Second):
t.Fatal("Start never ran a pre-warm cycle")
}
done := make(chan struct{})
go func() { w.Stop(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("Stop did not return")
}
w.Stop() // idempotent
}
func TestDisabledWorkerNeverFetches(t *testing.T) {
f := newFakeFetcher()
w := NewWorker(Config{Enabled: false, Fetcher: f, Popularity: samplePopularity()})
w.Start(context.Background())
w.TriggerPrewarm(context.Background())
require.NoError(t, w.PrewarmPackage(context.Background(), "npm", "lodash", "4.17.21"))
w.Stop()
assert.Empty(t, f.calls)
}
func TestStopIsSafeWithoutStart(t *testing.T) {
assert.NotPanics(t, func() {
NewWorker(Config{Enabled: true, Fetcher: newFakeFetcher(), Popularity: samplePopularity()}).Stop()
NewWorker(Config{}).Stop()
(*Worker)(nil).Stop()
})
}
func TestStartWithoutFetcherDoesNotRun(t *testing.T) {
w := NewWorker(Config{Enabled: true, Popularity: samplePopularity()})
w.Start(context.Background())
w.Stop()
assert.Nil(t, w.cancel)
}
func TestPrewarmPackagePassesExplicitVersionAndReturnsError(t *testing.T) {
f := newFakeFetcher()
f.err = errors.New("boom")
w := NewWorker(Config{Enabled: true, Fetcher: f, Popularity: samplePopularity()})
err := w.PrewarmPackage(context.Background(), "npm", "lodash", "4.17.21")
require.ErrorContains(t, err, "boom")
assert.Equal(t, "4.17.21", f.got["npm:lodash"].Version)
}
+1 -1
View File
@@ -58,7 +58,7 @@ func New(cacheManager *cache.Manager, client *network.Client, config Config) *Ha
// ServeHTTP handles NPM registry requests
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := strings.TrimPrefix(r.URL.Path, "/npm")
path := r.URL.Path
log.Debug().Str("path", path).Str("method", r.Method).Msg("NPM proxy request")
+5 -3
View File
@@ -111,9 +111,11 @@ func New(cacheManager *cache.Manager, client *network.Client, config Config) *Ha
// ServeHTTP handles PyPI Simple API requests
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := strings.TrimPrefix(r.URL.Path, "/pypi")
// Also trim /simple prefix since upstream already includes it
path = strings.TrimPrefix(path, "/simple")
path := r.URL.Path
// Upstream already includes /simple; trim it only as a whole segment so a package such as simple-x keeps its name.
if path == "/simple" || strings.HasPrefix(path, "/simple/") {
path = path[len("/simple"):]
}
log.Debug().Str("path", path).Str("method", r.Method).Msg("PyPI proxy request")
+164
View File
@@ -0,0 +1,164 @@
package trivy
import (
"archive/tar"
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
)
// maxExtractBytes caps the unpacked size so a compressed bomb cannot fill the disk.
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) {
if !validPackageName(name) {
return "", fmt.Errorf("unsafe package name %q", name)
}
root, err = os.MkdirTemp("", "trivy-npm-*")
if err != nil {
return "", err
}
defer func() {
if err != nil {
_ = os.RemoveAll(root)
root = ""
}
}()
dest := filepath.Join(root, "node_modules", filepath.FromSlash(name))
if err = os.MkdirAll(dest, 0o750); err != nil {
return root, err
}
err = extractTarball(archive, dest)
return root, err
}
func validPackageName(name string) bool {
if name == "" || strings.Contains(name, "\\") || !filepath.IsLocal(name) {
return false
}
for _, seg := range strings.Split(name, "/") {
if seg == ".." || seg == "." || seg == "" {
return false
}
}
return true
}
// extractTarball unpacks a .tgz into dest, dropping the top-level directory. Links are never
// created; escaping ones are rejected outright.
func extractTarball(archive, dest string) error {
f, err := os.Open(archive) // #nosec G304 -- path from the cache, not user input
if err != nil {
return err
}
defer func() { _ = f.Close() }()
gz, err := gzip.NewReader(f)
if err != nil {
return fmt.Errorf("open gzip: %w", err)
}
defer func() { _ = gz.Close() }()
tr := tar.NewReader(gz)
var total int64
for {
hdr, err := tr.Next()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return fmt.Errorf("read tar: %w", err)
}
rel, err := entryPath(hdr.Name)
if err != nil {
return err
}
switch hdr.Typeflag {
case tar.TypeDir:
if rel == "" {
continue
}
if err := os.MkdirAll(filepath.Join(dest, rel), 0o750); err != nil {
return err
}
case tar.TypeReg:
if rel == "" {
continue
}
n, err := writeEntry(filepath.Join(dest, rel), tr, maxExtractBytes-total)
if err != nil {
return err
}
total += n
case tar.TypeSymlink, tar.TypeLink:
if err := checkLink(hdr); err != nil {
return err
}
}
}
}
// entryPath validates a tar entry name and strips its first segment.
func entryPath(name string) (string, error) {
clean := strings.ReplaceAll(name, "\\", "/")
if strings.HasPrefix(clean, "/") {
return "", fmt.Errorf("absolute path in archive: %q", name)
}
for _, seg := range strings.Split(clean, "/") {
if seg == ".." {
return "", fmt.Errorf("path traversal in archive: %q", name)
}
}
segs := strings.Split(path.Clean(clean), "/")
if len(segs) < 2 {
return "", nil
}
rel := filepath.FromSlash(strings.Join(segs[1:], "/"))
if !filepath.IsLocal(rel) {
return "", fmt.Errorf("unsafe path in archive: %q", name)
}
return rel, nil
}
func checkLink(hdr *tar.Header) error {
target := strings.ReplaceAll(hdr.Linkname, "\\", "/")
if strings.HasPrefix(target, "/") {
return fmt.Errorf("absolute link target in archive: %q -> %q", hdr.Name, hdr.Linkname)
}
base := path.Dir(hdr.Name)
if hdr.Typeflag == tar.TypeLink {
base = "."
}
joined := path.Join(base, target)
if joined == ".." || strings.HasPrefix(joined, "../") {
return fmt.Errorf("link escapes the archive: %q -> %q", hdr.Name, hdr.Linkname)
}
return nil
}
// writeEntry copies at most limit bytes and fails when the entry is larger.
func writeEntry(dst string, r io.Reader, limit int64) (int64, error) {
if err := os.MkdirAll(filepath.Dir(dst), 0o750); err != nil {
return 0, err
}
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) // #nosec G304 -- dst validated by entryPath
if err != nil {
return 0, err
}
n, err := io.Copy(out, io.LimitReader(r, limit+1))
if cerr := out.Close(); err == nil {
err = cerr
}
if err == nil && n > limit {
err = errTooLarge
}
return n, err
}
+12 -4
View File
@@ -110,15 +110,23 @@ func (s *Scanner) Scan(ctx context.Context, registry, packageName, version strin
defer cancel()
}
// Determine scan type based on registry
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 {
return nil, fmt.Errorf("prepare npm package for trivy: %w", err)
}
defer func() { _ = os.RemoveAll(root) }()
target = root
}
// Build Trivy command
args := []string{
scanType,
"--format", "json",
"--quiet",
filePath,
target,
}
cmd := exec.CommandContext(ctx, "trivy", args...) // #nosec G204 -- trivy command with controlled arguments
@@ -166,7 +174,7 @@ func (s *Scanner) determineScanType(registry, filePath string) string {
switch registry {
case "npm":
return "fs" // Filesystem scan for npm packages
return "rootfs" // rootfs enables the node-pkg analyzer; fs reads lockfiles only
case "pypi":
return "fs" // Filesystem scan for Python packages
case "go":
+128 -1
View File
@@ -1,7 +1,14 @@
package trivy
import (
"archive/tar"
"bytes"
"compress/gzip"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -16,9 +23,129 @@ import (
func TestScanTimeoutIsAnInfrastructureErrorResult(t *testing.T) {
scannertest.Script(t, "trivy", "exec sleep 5")
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "npm", "p", "1", "/x")
res, err := New(config.TrivyConfig{Timeout: 100 * time.Millisecond}).Scan(context.Background(), "pypi", "p", "1", "/x")
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusError, res.Status)
assert.Equal(t, true, res.Details[scanerr.DetailInfrastructure])
}
type entry struct {
name, body, link string
typeflag byte
}
func tgz(t *testing.T, entries ...entry) string {
t.Helper()
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
for _, e := range entries {
tf := e.typeflag
if tf == 0 {
tf = tar.TypeReg
}
hdr := &tar.Header{Name: e.name, Typeflag: tf, Mode: 0o644, Linkname: e.link}
if tf == tar.TypeReg {
hdr.Size = int64(len(e.body))
}
require.NoError(t, tw.WriteHeader(hdr))
if tf == tar.TypeReg {
_, err := tw.Write([]byte(e.body))
require.NoError(t, err)
}
}
require.NoError(t, tw.Close())
require.NoError(t, gz.Close())
p := filepath.Join(t.TempDir(), "p.tgz")
require.NoError(t, os.WriteFile(p, buf.Bytes(), 0o600))
return p
}
func TestNPMScanRunsRootfsOnUnpackedTree(t *testing.T) {
rec := t.TempDir()
scannertest.Script(t, "trivy", fmt.Sprintf(`
printf '%%s\n' "$@" > %[1]q/args
for last; do :; done
cp "$last/node_modules/@scope/pkg/package.json" %[1]q/package.json
echo "$last" > %[1]q/root
echo '{"Results":[]}'`, rec))
archive := tgz(t,
entry{name: "package/", typeflag: tar.TypeDir},
entry{name: "package/package.json", body: `{"name":"@scope/pkg"}`},
entry{name: "package/lib/index.js", body: "x"},
)
res, err := New(config.TrivyConfig{}).Scan(context.Background(), "npm", "@scope/pkg", "1.0.0", archive)
require.NoError(t, err)
assert.Equal(t, metadata.ScanStatusClean, res.Status)
args, err := os.ReadFile(filepath.Join(rec, "args")) // #nosec G304 -- test temp dir
require.NoError(t, err)
root, err := os.ReadFile(filepath.Join(rec, "root")) // #nosec G304 -- test temp dir
require.NoError(t, err)
lines := strings.Split(strings.TrimSpace(string(args)), "\n")
assert.Equal(t, []string{"rootfs", "--format", "json", "--quiet", strings.TrimSpace(string(root))}, lines)
pkg, err := os.ReadFile(filepath.Join(rec, "package.json")) // #nosec G304 -- test temp dir
require.NoError(t, err)
assert.JSONEq(t, `{"name":"@scope/pkg"}`, string(pkg))
_, err = os.Stat(strings.TrimSpace(string(root))) // #nosec G304 G703 -- path from the test fake
assert.True(t, os.IsNotExist(err), "temp tree must be removed")
}
func TestNonNPMScansTheFileWithFS(t *testing.T) {
argsFile := scannertest.Fake(t, "trivy", "", "", 0)
_, err := New(config.TrivyConfig{}).Scan(context.Background(), "pypi", "p", "1", "/x/p.whl")
require.Error(t, err) // empty output is not JSON
assert.Equal(t, []string{"fs", "--format", "json", "--quiet", "/x/p.whl"}, scannertest.Args(t, argsFile))
}
func TestExtractRejectsUnsafeArchives(t *testing.T) {
tests := []struct {
name string
entries []entry
}{
{"parent traversal", []entry{{name: "package/../../evil", body: "x"}}},
{"leading traversal", []entry{{name: "../evil", body: "x"}}},
{"absolute path", []entry{{name: "/etc/evil", body: "x"}}},
{"symlink to absolute", []entry{{name: "package/l", typeflag: tar.TypeSymlink, link: "/etc/passwd"}}},
{"symlink out of tree", []entry{{name: "package/l", typeflag: tar.TypeSymlink, link: "../../x"}}},
{"hardlink out of tree", []entry{{name: "package/l", typeflag: tar.TypeLink, link: "../x"}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
root, err := unpackNPM(tgz(t, tt.entries...), "pkg")
require.Error(t, err)
assert.Empty(t, root)
})
}
}
func TestExtractSkipsInTreeLinksWithoutCreatingThem(t *testing.T) {
root, err := unpackNPM(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"))
}
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)
assert.Error(t, err, name)
}
}
func TestExtractEnforcesSizeCap(t *testing.T) {
dest := t.TempDir()
_, err := writeEntry(filepath.Join(dest, "big"), strings.NewReader(strings.Repeat("a", 11)), 10)
require.ErrorIs(t, err, errTooLarge)
n, err := writeEntry(filepath.Join(dest, "ok"), strings.NewReader(strings.Repeat("a", 10)), 10)
require.NoError(t, err)
assert.EqualValues(t, 10, n)
}