Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cmd/bluntcode/cli_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ func resolveScan(ctx context.Context, db *database.DB, identifier string) (core.
return core.Scan{}, fmt.Errorf("could not resolve scan or workspace for %q: %w", identifier, err)
}

scans, err := db.Scans(ctx, work.ID)
// Only the newest scan is wanted; read one page instead of full history.
scans, _, err := db.ScansPage(ctx, work.ID, 1, 1, database.ScansPageFilter{})
if err != nil {
return core.Scan{}, fmt.Errorf("load scans for workspace %s: %w", work.Name, err)
}
Expand Down
7 changes: 3 additions & 4 deletions cmd/bluntcode/history_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,13 @@ func runHistoryList(ctx context.Context, app *cliCore, args []string, stdout, st
fmt.Fprintf(stderr, "bluntcode history: %v\n", err)
return 1
}
scansList, err := app.db.Scans(ctx, work.ID)
// Fetch only the page that will be printed — history is unbounded and
// the truncating load-all pattern was the whole complaint here.
scansList, _, err := app.db.ScansPage(ctx, work.ID, 1, limit, database.ScansPageFilter{})
if err != nil {
fmt.Fprintf(stderr, "bluntcode history: %v\n", err)
return 1
}
if len(scansList) > limit {
scansList = scansList[:limit]
}

if *jsonOut {
_ = writeJSONOutput(stdout, scansList)
Expand Down
8 changes: 5 additions & 3 deletions cmd/bluntcode/stats_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ func runStats(args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stderr, "bluntcode stats: %v\n", err)
return 1
}
scansList, _ := app.db.Scans(ctx, work.ID)
// Only the total count is needed; a one-row page returns it without
// loading the workspace's full scan history.
_, totalScans, _ := app.db.ScansPage(ctx, work.ID, 1, 1, database.ScansPageFilter{})
snaps, _ := app.db.RecentCompletedSeverityCounts(ctx, work.ID, 1)

type wsStats struct {
Expand All @@ -65,7 +67,7 @@ func runStats(args []string, stdout, stderr io.Writer) int {
res := wsStats{
WorkspaceName: work.Name,
WorkspacePath: work.RootPath,
TotalScans: len(scansList),
TotalScans: totalScans,
}
if len(snaps) > 0 {
res.LatestCounts = &snaps[0]
Expand All @@ -78,7 +80,7 @@ func runStats(args []string, stdout, stderr io.Writer) int {

fmt.Fprintf(stdout, "Stats for workspace: %s\n", work.Name)
fmt.Fprintf(stdout, " Root Path: %s\n", work.RootPath)
fmt.Fprintf(stdout, " Total Scans: %d\n", len(scansList))
fmt.Fprintf(stdout, " Total Scans: %d\n", totalScans)
if len(snaps) > 0 {
s := snaps[0]
fmt.Fprintf(stdout, " Latest Scan: %s (Critical: %d, High: %d, Medium: %d, Low: %d, Info: %d)\n",
Expand Down
9 changes: 6 additions & 3 deletions cmd/bluntcode/workspace_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"bluntcode/internal/core"
"bluntcode/internal/database"
"bluntcode/internal/discovery"
)

Expand Down Expand Up @@ -237,7 +238,9 @@ func runWorkspaceShow(ctx context.Context, app *cliCore, args []string, stdout,
}

tags, _ := app.db.GetWorkspaceTags(ctx, work.ID)
scans, _ := app.db.Scans(ctx, work.ID)
// One bounded page carries both numbers this view needs: total via the
// count column, latest via the single row — no full-history load.
scans, total, _ := app.db.ScansPage(ctx, work.ID, 1, 1, database.ScansPageFilter{})

type workspaceDetail struct {
core.Workspace
Expand All @@ -249,7 +252,7 @@ func runWorkspaceShow(ctx context.Context, app *cliCore, args []string, stdout,
detail := workspaceDetail{
Workspace: work,
Tags: tags,
TotalScans: len(scans),
TotalScans: total,
}
if len(scans) > 0 {
detail.LatestScan = &scans[0]
Expand All @@ -271,7 +274,7 @@ func runWorkspaceShow(ctx context.Context, app *cliCore, args []string, stdout,
} else {
fmt.Fprintf(stdout, " Last Scanned: -\n")
}
fmt.Fprintf(stdout, " Total Scans: %d\n", len(scans))
fmt.Fprintf(stdout, " Total Scans: %d\n", total)
if len(tags) > 0 {
fmt.Fprintf(stdout, " Tags: %s\n", strings.Join(tags, ", "))
}
Expand Down
6 changes: 5 additions & 1 deletion internal/api/report_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@ func (s *Server) reportModel(ctx context.Context, scan core.Scan, work core.Work
selectedPaths = scan.Snapshot.SelectedFiles
}
if previousID, previousErr := s.db.PreviousCompletedScanID(ctx, scan.WorkspaceID, scan.ID); previousErr == nil {
previous, previousFindingsErr := s.db.Findings(ctx, previousID)
// The comparison only reads fingerprint + analyzer + path of the
// previous scan's findings; loading full rows doubled the decode
// (metadata_json unmarshal and ORDER BY included) for fields the
// renderers never touch.
previous, previousFindingsErr := s.db.FindingIdentities(ctx, previousID)
succeeded, succeededErr := s.db.SuccessfulAnalyzerIDs(ctx, scan.ID)
if previousFindingsErr == nil && succeededErr == nil {
comparison = scans.Compare(findings, scans.FilterSuppressed(previous, suppressed), scans.NewComparisonCoverage(succeeded, selectedPaths))
Expand Down
42 changes: 34 additions & 8 deletions internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ func (s *Server) routes() {
s.mux.HandleFunc("PUT /api/v1/workspaces/{id}/rules", s.putRules)
s.mux.HandleFunc("GET /api/v1/workspaces/{id}/suppressions", s.getSuppressions)
s.mux.HandleFunc("POST /api/v1/workspaces/{id}/suppressions", s.addSuppression)
s.mux.HandleFunc("GET /api/v1/workspaces/{id}/suppressions.csv", s.suppressionsCSV)
s.mux.Handle("GET /api/v1/workspaces/{id}/suppressions.csv", exportDeadline(http.HandlerFunc(s.suppressionsCSV)))
s.mux.HandleFunc("POST /api/v1/workspaces/{id}/suppressions/import", s.importSuppressions)
s.mux.HandleFunc("DELETE /api/v1/workspaces/{id}/suppressions/{fingerprint}", s.removeSuppression)
s.mux.HandleFunc("GET /api/v1/workspaces/{id}/trends", s.workspaceTrends)
Expand All @@ -199,19 +199,22 @@ func (s *Server) routes() {
s.mux.HandleFunc("POST /api/v1/scans/{id}/cancel", s.cancelScan)
s.mux.HandleFunc("GET /api/v1/scans/{id}/events", s.scanEvents)
s.mux.HandleFunc("GET /api/v1/scans/{id}/findings", s.findings)
s.mux.HandleFunc("GET /api/v1/scans/{id}/findings.csv", s.findingsCSV)
s.mux.HandleFunc("GET /api/v1/scans/{id}/findings.json", s.findingsJSON)
// Export routes get a per-handler write deadline: a stalled reader holds
// the handler goroutine — and, with MaxOpenConns(1), its DB slot — forever
// otherwise. SSE and the JSON API stay deadline-free by design.
s.mux.Handle("GET /api/v1/scans/{id}/findings.csv", exportDeadline(http.HandlerFunc(s.findingsCSV)))
s.mux.Handle("GET /api/v1/scans/{id}/findings.json", exportDeadline(http.HandlerFunc(s.findingsJSON)))
// report.json is the same versioned document under the report.* naming
// the other full-report exports use.
s.mux.HandleFunc("GET /api/v1/scans/{id}/report.json", s.findingsJSON)
s.mux.HandleFunc("GET /api/v1/scans/{id}/findings.jsonl", s.findingsJSONL)
s.mux.Handle("GET /api/v1/scans/{id}/report.json", exportDeadline(http.HandlerFunc(s.findingsJSON)))
s.mux.Handle("GET /api/v1/scans/{id}/findings.jsonl", exportDeadline(http.HandlerFunc(s.findingsJSONL)))
s.mux.HandleFunc("GET /api/v1/scans/{id}/fixed", s.fixedFindings)
s.mux.HandleFunc("GET /api/v1/scans/{id}/compare", s.scanCompare)
s.mux.HandleFunc("GET /api/v1/scans/{id}/findings/{findingID}/preview", s.findingPreview)
s.mux.HandleFunc("GET /api/v1/scans/{id}/report", s.report)
s.mux.HandleFunc("GET /api/v1/scans/{id}/report.md", s.reportMarkdown)
s.mux.HandleFunc("GET /api/v1/scans/{id}/report.sarif", s.reportSARIF)
s.mux.HandleFunc("GET /api/v1/scans/{id}/report.html", s.reportHTML)
s.mux.Handle("GET /api/v1/scans/{id}/report.md", exportDeadline(http.HandlerFunc(s.reportMarkdown)))
s.mux.Handle("GET /api/v1/scans/{id}/report.sarif", exportDeadline(http.HandlerFunc(s.reportSARIF)))
s.mux.Handle("GET /api/v1/scans/{id}/report.html", exportDeadline(http.HandlerFunc(s.reportHTML)))
s.mux.HandleFunc("GET /api/v1/analyzers", s.listAnalyzers)
s.mux.HandleFunc("GET /api/v1/tools", s.listTools)
s.mux.HandleFunc("POST /api/v1/tools/{id}/install", s.installTool)
Expand All @@ -220,6 +223,29 @@ func (s *Server) routes() {
s.mux.HandleFunc("DELETE /api/v1/tools/{id}", s.uninstallTool)
s.mux.HandleFunc("POST /api/v1/tools/{id}/uninstall", s.uninstallTool)
}

// exportWriteBound caps how long an export handler may write to one client.
// Generous for a local API: it exists to reap stalled readers, not to time
// honest downloads.
const exportWriteBound = 5 * time.Minute

// exportDeadline wraps a heavy, non-streaming handler with an absolute write
// deadline. ReadTimeout already bounds the body read; this bounds the writes
// so a stalled reader can't hold the connection — and its DB slot — forever.
// Not usable for SSE or other long-lived streams.
func exportDeadline(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ErrUnsupported writers (httptest recorders, non-HTTP/1 transports)
// simply can't take a deadline — serve them without one. Any other
// failure means the server accepted a socket it cannot bound.
if err := http.NewResponseController(w).SetWriteDeadline(time.Now().Add(exportWriteBound)); err != nil && !errors.Is(err, errors.ErrUnsupported) {
http.Error(w, "write deadline failed", http.StatusInternalServerError)
return
}
next.ServeHTTP(w, r)
})
}

func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
Expand Down
13 changes: 12 additions & 1 deletion internal/api/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,18 @@ func (s *Server) updateApply(w http.ResponseWriter, r *http.Request) {
return
}
s.log.Info("update staged", "dir", dir, "version", staged.Assets.Version, "signed", staged.Signed)
writeJSON(w, http.StatusOK, map[string]any{"started": true, "staged_at": dir, "version": staged.Assets.Version, "signed": staged.Signed})
if !staged.Signed {
// No release signing key is compiled in (self-built binary): the only
// integrity check was a SHA-256 fetched from the same release as the
// payload — a compromised release ships both files and both check out.
// Stay loud instead of silently downgrading the security model.
s.log.Warn("update verification was CHECKSUM-ONLY: no release signing key is compiled in, so the downloaded archive was not signature-verified")
}
resp := map[string]any{"started": true, "staged_at": dir, "version": staged.Assets.Version, "signed": staged.Signed}
if !staged.Signed {
resp["warning"] = "This build has no release signing key compiled in; the update was verified by checksum only, not by signature."
}
writeJSON(w, http.StatusOK, resp)
}

// launchUpdateProcess starts the detached updater. Package-level so tests can
Expand Down
3 changes: 3 additions & 0 deletions internal/database/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,9 @@ func durationMS(started, finished *time.Time) *int64 {
return &ms
}

// Scans loads a workspace's ENTIRE scan history — unbounded by design, so it
// stays for tests and full dumps only. Callers that need a count, the latest
// scan, or a page must use ScansPage so growth can't hurt them.
func (d *DB) Scans(ctx context.Context, workspaceID string) ([]core.Scan, error) {
rows, err := d.SQL.QueryContext(ctx, `SELECT `+scanSelectColumns("")+` FROM scans WHERE workspace_id=? ORDER BY started_at DESC, id DESC`, workspaceID)
if err != nil {
Expand Down
117 changes: 109 additions & 8 deletions internal/scans/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,33 @@ type Service struct {
statusMu sync.Mutex
statusCache []AnalyzerStatus
statusCachedAt time.Time
// queue holds scans accepted while every slot was busy, FIFO. Their rows
// exist in state 'queued'; drainQueue starts the head whenever a run
// finishes and frees a slot. Each entry's cancels[] wrapper cancels it
// out of the queue as well, so Cancel and Shutdown need no second path.
queue []queuedScan
}

// queuedScan is everything run() needs, captured at accept time.
type queuedScan struct {
scan core.Scan
work core.Workspace
files []core.FileEntry
opts ScanOptions
deselect func(string) bool
ctx context.Context
}

// MaxConcurrentScans bounds how many scans may run at once. Per-scan worker
// pools already parallelize analyzers inside a scan; without this cap,
// stacked CLI/UI starts would multiply whole analyzer trees on one machine.
const MaxConcurrentScans = 3

// MaxScanQueue bounds how many scans may wait queued behind a full slot set.
// Beyond it the API still answers 503 — an unbounded queue is a memory leak
// and a UX lie (a scan scheduled hours out is worse than an honest refusal).
const MaxScanQueue = 32

// ErrTooManyScans reports that MaxConcurrentScans scans are already running;
// the API surfaces it as 503 and the CLI as an operational failure (exit 3).
var ErrTooManyScans = errors.New("scan capacity reached: too many concurrent scans")
Expand Down Expand Up @@ -102,12 +122,18 @@ func (s *Service) start(ctx context.Context, work core.Workspace, profile string
s.mu.Unlock()
return core.Scan{}, ErrShuttingDown
}
if s.active >= MaxConcurrentScans {
// At capacity the scan no longer fails outright: it joins the FIFO queue
// and run() starts it as soon as a slot frees. Only a queue that itself
// is full is still a hard ErrTooManyScans.
atCapacity := s.active >= MaxConcurrentScans
if atCapacity && len(s.queue) >= MaxScanQueue {
s.mu.Unlock()
return core.Scan{}, ErrTooManyScans
}
s.active++
s.runs.Add(1)
if !atCapacity {
s.active++
s.runs.Add(1)
}
s.mu.Unlock()
snapshot := s.snapshot(ctx, work, profile, files, excludes, extras.skipCounts, extras.dependencyInputs)
if profile == analyzers.ProfilePentest && opts.TargetURL != "" {
Expand All @@ -123,13 +149,33 @@ func (s *Service) start(ctx context.Context, work core.Workspace, profile string
}
scan, err := s.db.CreateScanWithFiles(ctx, core.Scan{WorkspaceID: work.ID, Profile: profile, State: "queued", CandidateFileCount: len(files), SelectedFileCount: snapshot.SelectedFileCount, Snapshot: snapshot}, files)
if err != nil {
s.mu.Lock()
s.active--
s.mu.Unlock()
s.runs.Done()
if !atCapacity {
s.mu.Lock()
s.active--
s.mu.Unlock()
s.runs.Done()
}
return core.Scan{}, err
}
deselect := s.selectionDeselected(ctx, work.ID)
runCtx, cancel := context.WithCancel(context.Background())
if atCapacity {
s.mu.Lock()
entry := queuedScan{scan: scan, work: work, files: files, opts: opts, deselect: deselect, ctx: runCtx}
s.queue = append(s.queue, entry)
// Cancel and Shutdown find queued scans through cancels[] like any
// other: the wrapper cancels the stored ctx and drops the entry.
s.cancels[scan.ID] = func() { cancel(); s.dequeue(scan.ID) }
closing := s.closing
s.mu.Unlock()
if closing {
cancel()
}
// A slot may have freed while the snapshot and row write ran: pull the
// queue head now instead of stranding it until the next finish.
s.drainQueue()
return scan, nil
}
s.mu.Lock()
s.cancels[scan.ID] = cancel
closing := s.closing
Expand All @@ -140,10 +186,64 @@ func (s *Service) start(ctx context.Context, work core.Workspace, profile string
if closing {
cancel()
}
go s.run(runCtx, scan, work, files, opts, s.selectionDeselected(ctx, work.ID))
go s.run(runCtx, scan, work, files, opts, deselect)
return scan, nil
}

// dequeue drops a queued (never started) scan: it can no longer be drained,
// its cancels entry is released, and its row ends as cancelled instead of
// sitting in 'queued' until restart reconciliation marks it interrupted.
func (s *Service) dequeue(scanID string) {
s.mu.Lock()
deleted := false
for i, entry := range s.queue {
if entry.scan.ID == scanID {
s.queue = append(s.queue[:i], s.queue[i+1:]...)
deleted = true
break
}
}
if deleted {
delete(s.cancels, scanID)
}
s.mu.Unlock()
if deleted {
s.finishCancelled(scanID)
}
}

// drainQueue starts the oldest queued scan when a run freed a slot. Runs in
// the finishing goroutine's cleanup, before runs.Done(), so the new run's
// runs.Add can never race Shutdown's Wait into a negative count. Entries
// whose ctx was cancelled before they drained are skipped — dequeue usually
// already removed them, this is only the belt to that path's suspenders.
func (s *Service) drainQueue() {
for {
s.mu.Lock()
if s.closing || s.active >= MaxConcurrentScans || len(s.queue) == 0 {
s.mu.Unlock()
return
}
entry := s.queue[0]
s.queue = s.queue[1:]
if entry.ctx.Err() != nil {
// Cancel raced in after the pop: dequeue could not see this entry
// any more, so drain finalizes its row itself.
s.mu.Unlock()
s.finishCancelled(entry.scan.ID)
continue
}
s.active++
s.runs.Add(1)
s.mu.Unlock()
// run keeps entry.ctx: the cancels wrapper still in place cancels the
// context run actually uses, so a Cancel landing between pop and launch
// cannot be lost to a discarded context.
go s.run(entry.ctx, entry.scan, entry.work, entry.files, entry.opts, entry.deselect)
return
}
}

// snapshot captures the scan's input context once. skipCounts and
// dependencyInputs come from the discovery walk (start's caller passes them;
// direct start callers without a discovery result keep them nil).
Expand Down Expand Up @@ -291,6 +391,7 @@ func (s *Service) run(ctx context.Context, scan core.Scan, work core.Workspace,
delete(s.cancels, scan.ID)
s.active--
s.mu.Unlock()
s.drainQueue()
}()
// A panic inside an adapter must not take the whole application down with
// it or leave the scan row non-terminal: contain it, fail the scan, and
Expand Down
Loading
Loading