mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
perf(api): serve package lists and stats in constant queries
The dashboard waited seconds for /api/packages and /api/stats. Both handlers ran queries per package, so the cost grew with the cache. Baseline, measured live through a port-forward (median of 5): - /api/packages: 3033 ms, 594 items, limit ignored - /api/packages?limit=50&offset=0: 2813 ms - /api/stats: 3813 ms - /api/stats/timeseries?period=1day: 12 ms Baseline queries per request, counted on SQLite with 20 and 120 rows: - /api/packages: 141 and 841 queries (7 per package) - /api/stats: 103 and 603 queries (5 per package) Both handlers now run a constant number of queries: 4 for the full list, 6 for a page, 6 for stats. The query-count tests fail on the old code. - /api/packages pages (registry, name) groups with page, page_size, registry, q, sort and order, and returns total_groups. Without page and page_size it returns every package, so old clients keep working. - A batched scan lookup replaces the per-package GetScanResult and CheckVulnerabilities calls. ScanDecisions returns the same verdicts as CheckVulnerabilities, proven by a policy and bypass matrix test. - The silent 1000-row cap is gone from the list and the Go delete. - /api/stats sums per registry with GROUP BY and judges blocked packages in one batch. - Migration 202611240001 adds scan_results (package_id, scanned_at) on SQLite, PostgreSQL and MySQL. The existing (registry_id, name, version) index already serves the group lookups.
This commit is contained in:
+141
-164
@@ -1,12 +1,14 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/internal/version"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/websocket"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
@@ -56,156 +58,141 @@ func packageSummary(pkg *metadata.Package) map[string]interface{} {
|
||||
return summary
|
||||
}
|
||||
|
||||
// handleListPackages returns list of cached packages
|
||||
// Pagination limits of GET /api/packages.
|
||||
const (
|
||||
defaultPageSize = 25
|
||||
maxPageSize = 200
|
||||
)
|
||||
|
||||
// listParams are the parsed query parameters of GET /api/packages.
|
||||
type listParams struct {
|
||||
opts metadata.GroupListOptions
|
||||
paged bool
|
||||
}
|
||||
|
||||
// parseListParams reads page, page_size, registry, q, sort and order. Without
|
||||
// page or page_size the list is unpaginated, as it was before paging existed.
|
||||
func parseListParams(c fiber.Ctx) listParams {
|
||||
p := listParams{opts: metadata.GroupListOptions{
|
||||
Registry: c.Query("registry"),
|
||||
Query: c.Query("q"),
|
||||
SortBy: metadata.GroupSortName,
|
||||
}}
|
||||
switch sortBy := c.Query("sort"); sortBy {
|
||||
case metadata.GroupSortName, metadata.GroupSortCachedAt, metadata.GroupSortDownloads, metadata.GroupSortSize:
|
||||
p.opts.SortBy = sortBy
|
||||
p.opts.SortDesc = sortBy != metadata.GroupSortName
|
||||
}
|
||||
switch c.Query("order") {
|
||||
case "asc":
|
||||
p.opts.SortDesc = false
|
||||
case "desc":
|
||||
p.opts.SortDesc = true
|
||||
}
|
||||
if c.Query("page") != "" || c.Query("page_size") != "" {
|
||||
p.paged = true
|
||||
p.opts.Page = max(fiber.Query[int](c, "page", 1), 1)
|
||||
p.opts.PageSize = fiber.Query[int](c, "page_size", defaultPageSize)
|
||||
if p.opts.PageSize < 1 {
|
||||
p.opts.PageSize = defaultPageSize
|
||||
}
|
||||
p.opts.PageSize = min(p.opts.PageSize, maxPageSize)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// scanDecisions judges scanned packages, falling back to plain summaries without a scan manager.
|
||||
func (a *App) scanDecisions(ctx context.Context, ids []string) ([]scanner.ScanDecision, error) {
|
||||
if a.scanManager != nil {
|
||||
return a.scanManager.ScanDecisions(ctx, ids)
|
||||
}
|
||||
summaries, err := a.metadata.GetScanSummaries(ctx, ids, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]scanner.ScanDecision, len(summaries))
|
||||
for i, s := range summaries {
|
||||
out[i] = scanner.ScanDecision{Summary: s}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vulnerabilityInfo is the per-row scan block of the list payload.
|
||||
func vulnerabilityInfo(pkg *metadata.Package, decisions map[string]scanner.ScanDecision) map[string]interface{} {
|
||||
if !pkg.SecurityScanned {
|
||||
return map[string]interface{}{"scanned": false, "status": "not_scanned", "isBlocked": false}
|
||||
}
|
||||
d, ok := decisions[pkg.ID]
|
||||
if !ok || !d.Summary.HasScan {
|
||||
return map[string]interface{}{"scanned": false, "status": "pending", "isBlocked": false}
|
||||
}
|
||||
sum := d.Summary
|
||||
return map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": sum.Status,
|
||||
"scannedAt": sum.ScannedAt.Format(time.RFC3339),
|
||||
"counts": map[string]int{
|
||||
"critical": sum.Critical,
|
||||
"high": sum.High,
|
||||
"moderate": sum.Moderate,
|
||||
"low": sum.Low,
|
||||
},
|
||||
"total": sum.Total,
|
||||
"isBlocked": d.Blocked,
|
||||
}
|
||||
}
|
||||
|
||||
// handleListPackages returns cached packages, one page of groups when page or
|
||||
// page_size is given and every group otherwise.
|
||||
func (a *App) handleListPackages(c fiber.Ctx) error {
|
||||
ctx := c.Context()
|
||||
params := parseListParams(c)
|
||||
|
||||
// Get packages from metadata store
|
||||
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
|
||||
Limit: 1000, // Get more to account for duplicates
|
||||
Offset: 0,
|
||||
})
|
||||
page, err := a.metadata.ListPackageGroups(ctx, params.opts)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
|
||||
}
|
||||
|
||||
log.Debug().Int("total_packages_from_db", len(allPackages)).Msg("Retrieved packages from database")
|
||||
|
||||
// Filter, clean, and deduplicate packages
|
||||
// Map stores both cleaned package and original name for scan lookups
|
||||
type packageEntry struct {
|
||||
pkg *metadata.Package
|
||||
originalName string
|
||||
response := fiber.Map{
|
||||
"total": len(page.Packages),
|
||||
"total_groups": page.TotalGroups,
|
||||
}
|
||||
seen := make(map[string]*packageEntry)
|
||||
skippedCount := 0
|
||||
for _, pkg := range allPackages {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
skippedCount++
|
||||
log.Debug().
|
||||
Str("name", pkg.Name).
|
||||
Str("version", pkg.Version).
|
||||
Str("registry", pkg.Registry).
|
||||
Msg("Skipping metadata entry")
|
||||
continue
|
||||
if params.paged {
|
||||
response["page"] = params.opts.Page
|
||||
response["page_size"] = params.opts.PageSize
|
||||
}
|
||||
|
||||
if !a.config.Security.Enabled {
|
||||
response["packages"] = page.Packages
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
var scannedIDs []string
|
||||
for _, pkg := range page.Packages {
|
||||
if pkg.SecurityScanned {
|
||||
scannedIDs = append(scannedIDs, pkg.ID)
|
||||
}
|
||||
|
||||
// Clean the package name (remove /@v/version.ext suffix)
|
||||
originalName := pkg.Name
|
||||
cleanName := pkg.Name
|
||||
if idx := strings.Index(cleanName, "/@v/"); idx != -1 {
|
||||
cleanName = cleanName[:idx]
|
||||
}
|
||||
decisions := map[string]scanner.ScanDecision{}
|
||||
if len(scannedIDs) > 0 {
|
||||
list, err := a.scanDecisions(ctx, scannedIDs)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to load scan summaries")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to list packages"})
|
||||
}
|
||||
|
||||
// Create deduplication key
|
||||
key := cleanName + "@" + pkg.Version
|
||||
|
||||
// Keep the entry with the largest size (typically .zip files)
|
||||
if existing, ok := seen[key]; !ok || pkg.Size > existing.pkg.Size {
|
||||
// Create a copy with cleaned name
|
||||
cleanPkg := *pkg
|
||||
cleanPkg.Name = cleanName
|
||||
seen[key] = &packageEntry{
|
||||
pkg: &cleanPkg,
|
||||
originalName: originalName,
|
||||
}
|
||||
for _, d := range list {
|
||||
decisions[d.Summary.PackageID] = d
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().
|
||||
Int("skipped_metadata", skippedCount).
|
||||
Int("unique_packages", len(seen)).
|
||||
Msg("Filtered and deduplicated packages")
|
||||
|
||||
// Convert map to slice, keeping track of original names
|
||||
type packageWithOriginalName struct {
|
||||
pkg *metadata.Package
|
||||
originalName string
|
||||
enhanced := make([]map[string]interface{}, 0, len(page.Packages))
|
||||
for _, pkg := range page.Packages {
|
||||
pkgMap := packageSummary(pkg)
|
||||
pkgMap["vulnerabilities"] = vulnerabilityInfo(pkg, decisions)
|
||||
enhanced = append(enhanced, pkgMap)
|
||||
}
|
||||
packagesWithNames := make([]packageWithOriginalName, 0, len(seen))
|
||||
for _, entry := range seen {
|
||||
packagesWithNames = append(packagesWithNames, packageWithOriginalName{
|
||||
pkg: entry.pkg,
|
||||
originalName: entry.originalName,
|
||||
})
|
||||
}
|
||||
|
||||
// Enhance packages with vulnerability information if security scanning is enabled
|
||||
var response map[string]interface{}
|
||||
if a.config.Security.Enabled {
|
||||
enhancedPackages := make([]map[string]interface{}, 0, len(packagesWithNames))
|
||||
for _, entry := range packagesWithNames {
|
||||
pkg := entry.pkg
|
||||
pkgMap := packageSummary(pkg)
|
||||
|
||||
// Add vulnerability info if scanned
|
||||
if pkg.SecurityScanned {
|
||||
// Use original name for scan result lookup (handles Go packages with /@v/ suffix)
|
||||
scanResult, err := a.metadata.GetScanResult(ctx, pkg.Registry, entry.originalName, pkg.Version)
|
||||
if err == nil && scanResult != nil {
|
||||
// Count vulnerabilities by severity
|
||||
severityCounts := make(map[string]int)
|
||||
for _, vuln := range scanResult.Vulnerabilities {
|
||||
severityCounts[metadata.NormalizeSeverity(vuln.Severity)]++
|
||||
}
|
||||
|
||||
// Check if package should be blocked based on thresholds
|
||||
isBlocked := false
|
||||
if a.scanManager != nil {
|
||||
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, entry.originalName, pkg.Version)
|
||||
isBlocked = blocked
|
||||
}
|
||||
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": true,
|
||||
"status": scanResult.Status,
|
||||
"scannedAt": scanResult.ScannedAt.Format(time.RFC3339),
|
||||
"counts": map[string]int{
|
||||
"critical": severityCounts["CRITICAL"],
|
||||
"high": severityCounts["HIGH"],
|
||||
"moderate": severityCounts["MODERATE"],
|
||||
"low": severityCounts["LOW"],
|
||||
},
|
||||
"total": scanResult.VulnerabilityCount,
|
||||
"isBlocked": isBlocked,
|
||||
}
|
||||
} else {
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": false,
|
||||
"status": "pending",
|
||||
"isBlocked": false,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pkgMap["vulnerabilities"] = map[string]interface{}{
|
||||
"scanned": false,
|
||||
"status": "not_scanned",
|
||||
"isBlocked": false,
|
||||
}
|
||||
}
|
||||
|
||||
enhancedPackages = append(enhancedPackages, pkgMap)
|
||||
}
|
||||
|
||||
response = map[string]interface{}{
|
||||
"packages": enhancedPackages,
|
||||
"total": len(enhancedPackages),
|
||||
}
|
||||
} else {
|
||||
// Non-enhanced mode - just return the packages
|
||||
packages := make([]*metadata.Package, 0, len(packagesWithNames))
|
||||
for _, entry := range packagesWithNames {
|
||||
packages = append(packages, entry.pkg)
|
||||
}
|
||||
response = map[string]interface{}{
|
||||
"packages": packages,
|
||||
"total": len(packages),
|
||||
}
|
||||
}
|
||||
|
||||
// Success response
|
||||
response["packages"] = enhanced
|
||||
return c.Status(fiber.StatusOK).JSON(response)
|
||||
}
|
||||
|
||||
@@ -236,7 +223,8 @@ func (a *App) handleDeletePackage(c fiber.Ctx) error {
|
||||
if registry == "go" {
|
||||
// List all packages matching the base name and version
|
||||
allPackages, err := a.metadata.ListPackages(ctx, &metadata.ListOptions{
|
||||
Limit: 1000,
|
||||
Registry: registry,
|
||||
NamePrefix: name,
|
||||
})
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages for deletion")
|
||||
@@ -363,39 +351,28 @@ func (a *App) handleStats(c fiber.Ctx) error {
|
||||
cacheStats = &metadata.Stats{}
|
||||
}
|
||||
|
||||
// Get all packages to calculate per-registry breakdown
|
||||
packages, err := a.metadata.ListPackages(ctx, nil)
|
||||
registryStats := make(map[string]map[string]interface{})
|
||||
byRegistry, err := a.metadata.GetRegistryStats(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list packages")
|
||||
packages = []*metadata.Package{}
|
||||
log.Error().Err(err).Msg("Failed to get registry stats")
|
||||
}
|
||||
for _, rs := range byRegistry {
|
||||
registryStats[rs.Registry] = map[string]interface{}{
|
||||
"count": int(rs.Count),
|
||||
"size": rs.Size,
|
||||
"downloads": rs.Downloads,
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate per-registry breakdown and blocked packages count
|
||||
registryStats := make(map[string]map[string]interface{})
|
||||
// Blocked packages need the blocking policy, so judge every scanned package in one batch.
|
||||
blockedCount := int64(0)
|
||||
|
||||
for _, pkg := range packages {
|
||||
// Skip metadata entries (npm metadata pages, pypi pages, etc.)
|
||||
if pkg.Version == "list" || pkg.Version == "latest" || pkg.Version == "metadata" || pkg.Version == "page" {
|
||||
continue
|
||||
if a.config.Security.Enabled && a.scanManager != nil {
|
||||
decisions, err := a.scanManager.ScanDecisions(ctx, nil)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to judge scanned packages")
|
||||
}
|
||||
|
||||
// Track per-registry stats
|
||||
if _, ok := registryStats[pkg.Registry]; !ok {
|
||||
registryStats[pkg.Registry] = map[string]interface{}{
|
||||
"count": 0,
|
||||
"size": int64(0),
|
||||
"downloads": int64(0),
|
||||
}
|
||||
}
|
||||
registryStats[pkg.Registry]["count"] = registryStats[pkg.Registry]["count"].(int) + 1
|
||||
registryStats[pkg.Registry]["size"] = registryStats[pkg.Registry]["size"].(int64) + pkg.Size
|
||||
registryStats[pkg.Registry]["downloads"] = registryStats[pkg.Registry]["downloads"].(int64) + int64(pkg.DownloadCount)
|
||||
|
||||
// Check if package is blocked (only if security scanning is enabled and package is scanned)
|
||||
if a.config.Security.Enabled && a.scanManager != nil && pkg.SecurityScanned {
|
||||
blocked, _, _ := a.scanManager.CheckVulnerabilities(ctx, pkg.Registry, pkg.Name, pkg.Version)
|
||||
if blocked {
|
||||
for _, d := range decisions {
|
||||
if d.Blocked && !metadata.IsMetadataVersion(d.Summary.Version) {
|
||||
blockedCount++
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
)
|
||||
|
||||
type listResponse struct {
|
||||
Packages []struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
Registry string `json:"registry"`
|
||||
Vulnerabilities struct {
|
||||
Status string `json:"status"`
|
||||
IsBlocked bool `json:"isBlocked"`
|
||||
Total int `json:"total"`
|
||||
Counts struct {
|
||||
Critical int `json:"critical"`
|
||||
} `json:"counts"`
|
||||
} `json:"vulnerabilities"`
|
||||
} `json:"packages"`
|
||||
Total int `json:"total"`
|
||||
TotalGroups int `json:"total_groups"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
func getList(t *testing.T, a *App, target string) listResponse {
|
||||
t.Helper()
|
||||
code, _, body := doRequest(t, a, target, nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
var out listResponse
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatalf("decode %s: %v", body, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestListPackagesPagesGroupsAndAttachesScans(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60)
|
||||
|
||||
page := getList(t, a, "/api/packages?page=2&page_size=25")
|
||||
if page.TotalGroups != 60 || page.Page != 2 || page.PageSize != 25 {
|
||||
t.Fatalf("paging fields = %+v", page)
|
||||
}
|
||||
if len(page.Packages) != 25 || page.Total != 25 {
|
||||
t.Fatalf("page 2 holds %d rows (total %d), want 25", len(page.Packages), page.Total)
|
||||
}
|
||||
if first := page.Packages[0].Name; first != "pkg-025" {
|
||||
t.Errorf("page 2 starts at %q, want pkg-025 (name order)", first)
|
||||
}
|
||||
|
||||
last := getList(t, a, "/api/packages?page=3&page_size=25")
|
||||
if len(last.Packages) != 10 {
|
||||
t.Errorf("last page holds %d rows, want 10", len(last.Packages))
|
||||
}
|
||||
|
||||
found := getList(t, a, "/api/packages?q=PKG-005&page_size=10")
|
||||
if found.TotalGroups != 1 || len(found.Packages) != 1 {
|
||||
t.Fatalf("search pkg-005 = %+v", found)
|
||||
}
|
||||
v := found.Packages[0].Vulnerabilities
|
||||
if v.Status != "vulnerable" || !v.IsBlocked || v.Total != 1 || v.Counts.Critical != 1 {
|
||||
t.Errorf("pkg-005 scan block = %+v, want vulnerable, blocked, one critical", v)
|
||||
}
|
||||
|
||||
clean := getList(t, a, "/api/packages?q=pkg-006&page_size=10")
|
||||
if cv := clean.Packages[0].Vulnerabilities; cv.Status != "clean" || cv.IsBlocked {
|
||||
t.Errorf("pkg-006 scan block = %+v, want clean and not blocked", cv)
|
||||
}
|
||||
|
||||
if none := getList(t, a, "/api/packages?registry=pypi&page_size=10"); none.TotalGroups != 0 || len(none.Packages) != 0 {
|
||||
t.Errorf("pypi filter = %+v, want empty", none)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListPackagesRecentFirst(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 30)
|
||||
recent := getList(t, a, "/api/packages?sort=cached_at&order=desc&page=1&page_size=3")
|
||||
got := []string{recent.Packages[0].Name, recent.Packages[1].Name, recent.Packages[2].Name}
|
||||
want := []string{"pkg-000", "pkg-001", "pkg-002"} // seedScanned caches pkg-N N minutes ago
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("recent = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The unpaginated list used to stop at 1000 rows without saying so.
|
||||
func TestListPackagesUnpaginatedHasNoCap(t *testing.T) {
|
||||
a := newTestApp(t, nil)
|
||||
ctx := context.Background()
|
||||
const rows = 1005
|
||||
now := time.Now()
|
||||
for i := 0; i < rows; i++ {
|
||||
name := fmt.Sprintf("bulk-%04d", i)
|
||||
if err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}); err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
}
|
||||
all := getList(t, a, "/api/packages")
|
||||
if len(all.Packages) != rows || all.Total != rows || all.TotalGroups != rows {
|
||||
t.Fatalf("unpaginated list = %d rows, total %d, groups %d; want %d", len(all.Packages), all.Total, all.TotalGroups, rows)
|
||||
}
|
||||
if capped := getList(t, a, "/api/packages?page_size=100000"); capped.PageSize != maxPageSize || len(capped.Packages) != maxPageSize {
|
||||
t.Errorf("page_size clamp: size %d, rows %d, want %d", capped.PageSize, len(capped.Packages), maxPageSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsFromAggregates(t *testing.T) {
|
||||
a, _ := newScanningApp(t)
|
||||
seedScanned(t, a, 0, 60)
|
||||
code, _, body := doRequest(t, a, "/api/stats", nil)
|
||||
if code != 200 {
|
||||
t.Fatalf("GET /api/stats = %d %s", code, body)
|
||||
}
|
||||
var out struct {
|
||||
Stats map[string]float64 `json:"stats"`
|
||||
Registries map[string]map[string]float64 `json:"registries"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Stats["total_packages"] != 60 || out.Stats["scanned_packages"] != 60 || out.Stats["vulnerable_packages"] != 12 {
|
||||
t.Errorf("stats = %v", out.Stats)
|
||||
}
|
||||
if out.Stats["blocked_packages"] != 12 {
|
||||
t.Errorf("blocked_packages = %v, want the 12 critical packages", out.Stats["blocked_packages"])
|
||||
}
|
||||
if npm := out.Registries["npm"]; npm["count"] != 60 || npm["size"] != 6000 {
|
||||
t.Errorf("npm registry = %v, want 60 rows and 6000 bytes", npm)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lukaszraczylo/gohoarder/internal/dbcount"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata/gormstore"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// seedScanned stores n scanned npm packages, every fifth with a critical finding.
|
||||
func seedScanned(t *testing.T, a *App, from, n int) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
for i := from; i < from+n; i++ {
|
||||
name := fmt.Sprintf("pkg-%03d", i)
|
||||
err := a.metadata.SavePackage(ctx, &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: "1.0.0", StorageKey: "npm/" + name + "/1.0.0",
|
||||
Size: 100, CachedAt: now.Add(-time.Duration(i) * time.Minute), LastAccessed: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("SavePackage: %v", err)
|
||||
}
|
||||
res := &metadata.ScanResult{
|
||||
Registry: "npm", PackageName: name, PackageVersion: "1.0.0", Scanner: "test",
|
||||
Status: metadata.ScanStatusClean, ScannedAt: now,
|
||||
}
|
||||
if i%5 == 0 {
|
||||
res.Status = metadata.ScanStatusVulnerable
|
||||
res.VulnerabilityCount = 1
|
||||
res.Vulnerabilities = []metadata.Vulnerability{{ID: fmt.Sprintf("CVE-2026-%04d", i), Severity: "critical"}}
|
||||
}
|
||||
if err := a.metadata.SaveScanResult(ctx, res); err != nil {
|
||||
t.Fatalf("SaveScanResult: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newScanningApp(t *testing.T) (*App, *dbcount.Counter) {
|
||||
t.Helper()
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.Scanners.Static.Enabled = false
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
})
|
||||
store, ok := a.metadata.(*gormstore.GORMStoreV2)
|
||||
if !ok {
|
||||
t.Fatalf("metadata store is %T, want *gormstore.GORMStoreV2", a.metadata)
|
||||
}
|
||||
var counter *dbcount.Counter
|
||||
store.WrapDB(func(db *gorm.DB) *gorm.DB {
|
||||
counted, c := dbcount.Attach(db)
|
||||
counter = c
|
||||
return counted
|
||||
})
|
||||
return a, counter
|
||||
}
|
||||
|
||||
// queriesFor reports how many SQL statements one GET runs.
|
||||
func queriesFor(t *testing.T, a *App, c *dbcount.Counter, target string) int {
|
||||
t.Helper()
|
||||
c.Reset()
|
||||
if code, _, body := doRequest(t, a, target, nil); code != http.StatusOK {
|
||||
t.Fatalf("GET %s = %d %s", target, code, body)
|
||||
}
|
||||
return c.Count()
|
||||
}
|
||||
|
||||
// The dashboard endpoints must cost the same number of statements for 20 rows and for 120.
|
||||
func TestDashboardEndpointsQueryCountIsConstant(t *testing.T) {
|
||||
a, counter := newScanningApp(t)
|
||||
targets := []string{"/api/packages", "/api/packages?page=1&page_size=25", "/api/stats"}
|
||||
|
||||
seedScanned(t, a, 0, 20)
|
||||
small := map[string]int{}
|
||||
for _, target := range targets {
|
||||
small[target] = queriesFor(t, a, counter, target)
|
||||
}
|
||||
|
||||
seedScanned(t, a, 20, 100)
|
||||
for _, target := range targets {
|
||||
large := queriesFor(t, a, counter, target)
|
||||
t.Logf("%-40s 20 rows: %3d queries, 120 rows: %3d queries", target, small[target], large)
|
||||
if large != small[target] {
|
||||
t.Errorf("%s: %d queries for 20 rows but %d for 120 rows; the count must not grow with rows", target, small[target], large)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user