mirror of
https://github.com/lukaszraczylo/gohoarder.git
synced 2026-11-26 06:37:07 +00:00
feat(security): add an admin-triggered rescan
POST /api/admin/rescan queues a background rescan of the cached artifacts with scope vulnerable or all. It ignores the active window and the age of the last scan, runs on the server context and uses the rescan worker concurrency. A second request while a run is active gets 409. GET /api/admin/rescan/status reports queued, done, failed and running. The System page gets a Rescan section with progress and a confirmation for the full rescan.
This commit is contained in:
+9
-1
@@ -56,6 +56,7 @@ type App struct {
|
||||
networkClient *network.Client
|
||||
scanManager *scanner.Manager
|
||||
rescanWorker *scanner.RescanWorker
|
||||
workerCtx context.Context
|
||||
analyticsEngine *analytics.Engine
|
||||
wsServer *websocket.Server
|
||||
prewarmWorker *prewarming.Worker
|
||||
@@ -323,7 +324,8 @@ func (a *App) initializeComponents() error {
|
||||
a.scanManager.SetFileSource(a.cache.ScanFile)
|
||||
|
||||
// Initialize rescan worker if enabled
|
||||
if a.config.Security.Enabled && a.config.Security.RescanInterval > 0 {
|
||||
// Built whenever scanning is on: an interval of 0 only turns off the periodic cycle, not admin rescans.
|
||||
if a.config.Security.Enabled {
|
||||
log.Info().Dur("interval", a.config.Security.RescanInterval).Msg("Initializing package rescan worker")
|
||||
a.rescanWorker = scanner.NewRescanWorker(a.scanManager, a.metadata, a.config.Security.RescanInterval,
|
||||
scanner.WithActiveWindow(a.config.Security.RescanActiveWindow),
|
||||
@@ -497,6 +499,10 @@ func (a *App) setupServer() error {
|
||||
a.app.Post("/api/admin/prewarming/trigger", a.requireAdmin, a.handlePrewarmingTrigger)
|
||||
a.app.Post("/api/admin/prewarming/package", a.requireAdmin, a.handlePrewarmingPackage)
|
||||
|
||||
// Admin endpoints (forced rescan)
|
||||
a.app.Post("/api/admin/rescan", a.requireAdmin, a.handleRescanTrigger)
|
||||
a.app.Get("/api/admin/rescan/status", a.requireAdmin, a.handleRescanStatus)
|
||||
|
||||
// Admin endpoints (API key management)
|
||||
a.app.Post("/api/admin/keys", a.requireAdmin, a.handleGenerateAPIKey)
|
||||
a.app.Get("/api/admin/keys", a.requireAdmin, a.handleListAPIKeys)
|
||||
@@ -625,6 +631,8 @@ func (a *App) setupServer() error {
|
||||
|
||||
// startWorkers starts the background loops that live as long as ctx.
|
||||
func (a *App) startWorkers(ctx context.Context) {
|
||||
a.workerCtx = ctx
|
||||
|
||||
// Without the event loop the broadcast channel fills after 256 events and websocket clients never register.
|
||||
a.wsServer.Start(ctx)
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/scanner"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
type rescanRequest struct {
|
||||
Scope scanner.RescanScope `json:"scope"`
|
||||
}
|
||||
|
||||
// jobContext is the context of work that outlives a request: it ends with the server.
|
||||
func (a *App) jobContext() context.Context {
|
||||
if a.workerCtx != nil {
|
||||
return a.workerCtx
|
||||
}
|
||||
return context.Background()
|
||||
}
|
||||
|
||||
func rescanStatusBody(a *App) fiber.Map {
|
||||
body := fiber.Map{"enabled": a.rescanWorker != nil, "running": false, "scope": "", "queued": 0, "done": 0, "failed": 0}
|
||||
if a.rescanWorker == nil {
|
||||
return body
|
||||
}
|
||||
st := a.rescanWorker.Status()
|
||||
body["running"], body["scope"] = st.Running, string(st.Scope)
|
||||
body["queued"], body["done"], body["failed"] = st.Queued, st.Done, st.Failed
|
||||
if !st.StartedAt.IsZero() {
|
||||
body["started_at"] = st.StartedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if !st.FinishedAt.IsZero() {
|
||||
body["finished_at"] = st.FinishedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// handleRescanTrigger queues a rescan of cached artifacts and answers 202 with the queued count.
|
||||
func (a *App) handleRescanTrigger(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
|
||||
var req rescanRequest
|
||||
if err := c.Bind().Body(&req); err != nil || !req.Scope.Valid() {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": `scope must be "vulnerable" or "all"`})
|
||||
}
|
||||
if a.rescanWorker == nil {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": scanner.ErrRescanDisabled.Error()})
|
||||
}
|
||||
|
||||
queued, err := a.rescanWorker.RescanNow(a.jobContext(), req.Scope)
|
||||
switch {
|
||||
case errors.Is(err, scanner.ErrRescanRunning):
|
||||
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"error": err.Error(), "status": rescanStatusBody(a)})
|
||||
case errors.Is(err, scanner.ErrRescanDisabled):
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
|
||||
case err != nil:
|
||||
log.Error().Err(err).Msg("Failed to queue rescan")
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "failed to queue rescan"})
|
||||
}
|
||||
|
||||
log.Info().Str("scope", string(req.Scope)).Int("queued", queued).Msg("Rescan queued via API")
|
||||
return c.Status(fiber.StatusAccepted).JSON(fiber.Map{"queued": queued, "scope": req.Scope})
|
||||
}
|
||||
|
||||
// handleRescanStatus reports the progress of the latest admin-triggered rescan.
|
||||
func (a *App) handleRescanStatus(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "application/json")
|
||||
return c.Status(fiber.StatusOK).JSON(rescanStatusBody(a))
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/config"
|
||||
"github.com/lukaszraczylo/gohoarder/pkg/metadata"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func rescanApp(t *testing.T) (*App, *fiber.App) {
|
||||
t.Helper()
|
||||
a := newTestApp(t, func(c *config.Config) {
|
||||
c.Security.Enabled = true
|
||||
c.Security.UpdateDBOnStartup = false
|
||||
c.Security.RescanInterval = 0
|
||||
disableAllScanners(c)
|
||||
})
|
||||
f := fiber.New()
|
||||
f.Post("/api/admin/rescan", a.handleRescanTrigger)
|
||||
f.Get("/api/admin/rescan/status", a.handleRescanStatus)
|
||||
return a, f
|
||||
}
|
||||
|
||||
func decodeBody(t *testing.T, resp *http.Response) map[string]any {
|
||||
t.Helper()
|
||||
var out map[string]any
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&out))
|
||||
return out
|
||||
}
|
||||
|
||||
func postRescan(t *testing.T, f *fiber.App, body string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/rescan", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := f.Test(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
return resp.StatusCode, decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func rescanStatus(t *testing.T, f *fiber.App) map[string]any {
|
||||
t.Helper()
|
||||
resp, err := f.Test(httptest.NewRequest(http.MethodGet, "/api/admin/rescan/status", nil))
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
return decodeBody(t, resp)
|
||||
}
|
||||
|
||||
func saveRescanPackage(t *testing.T, a *App, name, version string) {
|
||||
t.Helper()
|
||||
now := time.Now()
|
||||
require.NoError(t, a.metadata.SavePackage(context.Background(), &metadata.Package{
|
||||
Registry: "npm", Name: name, Version: version, StorageKey: "npm/" + name + "/" + version, Size: 1, CachedAt: now, LastAccessed: now,
|
||||
}))
|
||||
}
|
||||
|
||||
func TestRescanTriggerQueuesAndReportsProgress(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
saveRescanPackage(t, a, "left-pad", "1.3.0")
|
||||
saveRescanPackage(t, a, "left-pad", "metadata")
|
||||
|
||||
code, body := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
require.EqualValues(t, 1, body["queued"], "the metadata row is not queued")
|
||||
require.Equal(t, "all", body["scope"])
|
||||
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
st := rescanStatus(t, f)
|
||||
require.EqualValues(t, 1, st["queued"])
|
||||
require.EqualValues(t, 1, st["done"].(float64)+st["failed"].(float64), "the one artifact is processed")
|
||||
require.NotEmpty(t, st["finished_at"])
|
||||
}
|
||||
|
||||
func TestRescanTriggerRefusesASecondRunWhileActive(t *testing.T) {
|
||||
a, f := rescanApp(t)
|
||||
saveRescanPackage(t, a, "left-pad", "1.3.0")
|
||||
release, entered := make(chan struct{}), make(chan struct{}, 1)
|
||||
a.scanManager.SetFileSource(func(context.Context, string, string, string) (string, func(), error) {
|
||||
select {
|
||||
case entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
<-release
|
||||
return "", func() {}, context.Canceled
|
||||
})
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusAccepted, code)
|
||||
<-entered
|
||||
require.Equal(t, true, rescanStatus(t, f)["running"])
|
||||
|
||||
code, body := postRescan(t, f, `{"scope":"vulnerable"}`)
|
||||
require.Equal(t, http.StatusConflict, code)
|
||||
require.NotEmpty(t, body["error"])
|
||||
|
||||
close(release)
|
||||
require.Eventually(t, func() bool { return rescanStatus(t, f)["running"] == false }, 5*time.Second, 10*time.Millisecond)
|
||||
}
|
||||
|
||||
func TestRescanTriggerRejectsBadInput(t *testing.T) {
|
||||
_, f := rescanApp(t)
|
||||
for _, body := range []string{``, `{}`, `{"scope":"everything"}`, `not json`} {
|
||||
code, _ := postRescan(t, f, body)
|
||||
require.Equal(t, http.StatusBadRequest, code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRescanTriggerNeedsScanningOn(t *testing.T) {
|
||||
a := newTestApp(t, func(c *config.Config) { c.Security.Enabled = false })
|
||||
f := fiber.New()
|
||||
f.Post("/api/admin/rescan", a.handleRescanTrigger)
|
||||
f.Get("/api/admin/rescan/status", a.handleRescanStatus)
|
||||
|
||||
code, _ := postRescan(t, f, `{"scope":"all"}`)
|
||||
require.Equal(t, http.StatusBadRequest, code)
|
||||
require.Equal(t, false, rescanStatus(t, f)["enabled"])
|
||||
}
|
||||
|
||||
func TestRescanRoutesNeedAdmin(t *testing.T) {
|
||||
a, _ := rescanApp(t)
|
||||
for _, tc := range []struct{ method, path string }{
|
||||
{http.MethodPost, "/api/admin/rescan"},
|
||||
{http.MethodGet, "/api/admin/rescan/status"},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(`{"scope":"all"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := a.app.Test(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
require.Equal(t, http.StatusUnauthorized, resp.StatusCode, tc.path)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user