From 621876386cfb47d8d82811543a473c6f8a2244ad Mon Sep 17 00:00:00 2001 From: Sanket Patel Date: Sun, 22 Nov 2026 18:35:49 +0530 Subject: [PATCH] =?UTF-8?q?fix:=20backend=20sweep=20=E2=80=94=20reliabilit?= =?UTF-8?q?y,=20security=20and=20hardening=20(#94-#127)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- CHANGELOG.md | 20 +++ cmd/bluntcode/bootstrap.go | 18 ++- cmd/bluntcode/main.go | 10 +- .../static/assets/AnalyticsCharts-CvbXoCAu.js | 1 + .../assets/ComplianceMatrix-D_wlb1Vj.js | 1 + .../static/assets/DependencyGraph-Dy7uz7iK.js | 1 + .../static/assets/PentestPage-BimU3Fub.js | 1 + .../static/assets/RechartsViz-C4fTvcma.js | 1 + .../static/assets/RuleStudioPage-BshwQHh7.js | 35 ++++++ cmd/bluntcode/static/assets/index-CYnHslPa.js | 81 ++++++++++++ .../static/assets/motionFeatures-DCyZflmZ.js | 1 + cmd/bluntcode/static/index.html | 2 +- cmd/bluntcode/update_cmd.go | 3 +- internal/analyzers/sonarqube/managed.go | 7 +- internal/api/auth.go | 47 +++++-- internal/api/demo_seed.go | 25 ++++ internal/api/notes.go | 22 ++++ internal/api/notes_test.go | 17 ++- internal/api/pentest.go | 8 ++ internal/api/ratelimit.go | 72 +++++++++-- internal/api/server.go | 118 ++++++++++++++---- internal/api/update.go | 52 ++++++-- internal/api/update_test.go | 8 +- internal/api/workspace_path.go | 36 +++++- internal/api/workspace_root.go | 8 +- internal/build/version.go | 2 +- internal/database/database.go | 7 +- internal/database/repository.go | 118 ++++++++++++++++-- internal/scans/exec.go | 16 ++- internal/scans/jobs_test.go | 2 +- internal/scans/service.go | 5 +- internal/selfupdate/install.go | 4 +- internal/selfupdate/proc_other.go | 6 +- internal/selfupdate/selfupdate.go | 2 + internal/tools/manager.go | 39 ++++-- scripts/package.ps1 | 2 +- web/package-lock.json | 4 +- web/package.json | 2 +- web/src/components/RootMissingBadge.tsx | 4 +- 39 files changed, 697 insertions(+), 111 deletions(-) create mode 100644 cmd/bluntcode/static/assets/AnalyticsCharts-CvbXoCAu.js create mode 100644 cmd/bluntcode/static/assets/ComplianceMatrix-D_wlb1Vj.js create mode 100644 cmd/bluntcode/static/assets/DependencyGraph-Dy7uz7iK.js create mode 100644 cmd/bluntcode/static/assets/PentestPage-BimU3Fub.js create mode 100644 cmd/bluntcode/static/assets/RechartsViz-C4fTvcma.js create mode 100644 cmd/bluntcode/static/assets/RuleStudioPage-BshwQHh7.js create mode 100644 cmd/bluntcode/static/assets/index-CYnHslPa.js create mode 100644 cmd/bluntcode/static/assets/motionFeatures-DCyZflmZ.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 81b1f7c1..66ac998d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ records differ for older versions: ## [Unreleased] +## [0.51.0] - 2026-11-22 + ### Fixed - **CLI flag order.** `bluntcode --no-browser --port N` now works as documented: the default command accepts flags before, after, or interleaved with the workspace path instead of rejecting them as extra arguments (#49). - **`workspaces.git_repository`** is actually populated — via a migration, detection at workspace add/discover, and a startup refresh — so the API no longer reports `false` for real git working trees (#50). @@ -54,6 +56,24 @@ records differ for older versions: ### Changed - **CLI Docs is a reference, not a wall.** The page rendered all fourteen command entries fully expanded — synopsis, subcommands, flag tables and examples each — a ~12,000px scroll in which nothing was findable. It is now master/detail: a sticky command index grouped by category beside the selected command's complete entry, with search narrowing the index (12,103px → ~1,900px for the default entry). +### Added +- **Demo data can be removed.** `POST /api/v1/system/unseed-demo` bulk-deletes every workspace tagged `demo-ui` (both seed presets tag their synthetic workspaces), so demo corpus no longer shares the database — or decays into "folder missing" rows once its temp dirs are cleaned — with real workspaces. Same `BLUNTCODE_DEMO_SEED`/`BLUNTCODE_DEMO_TOKEN` opt-in as seeding (#126). +- **Workspace file tree is cached for 30s.** Every tree click re-walked the workspace and cross-multiplied path overrides per entry; the endpoint now memoizes per workspace+path (#117). + +### Fixed +- **Root probing is bounded and honest.** A stat on a disconnected network share can hang for minutes; root checks now run concurrently under a timeout, and a root the probe could not resolve reports `probe_timeout` — shown in the UI as "Folder unreachable" — instead of falsely claiming "Folder missing" or stalling the workspace list. A timed-out root also no longer blocks the scan button (#99). +- **Sensitive roots are refused.** Adding a workspace rooted at a drive root, the Windows directory, the user profile root, or secrets/config directories (`.ssh`, `.aws`, `.gnupg`, `.config`, `AppData`, `etc`, `Program Files`…) is rejected up front instead of letting a scan crawl private material or the whole disk. The `C:\Windows` guard no longer depends on env vars (#103, #123). +- **Scan start is atomic per workspace.** The active-scan check and the insert now hold a per-workspace lock, so two POSTs can no longer both observe "no active scan" and double-start; the `409` carries the conflicting `scan_id` (#108, #111). The start event reports the true state instead of a stale `queued` after the worker is already running (#118). +- **One panicking analyzer can't poison the scan.** Per-analyzer panics are contained in their worker, recorded with the analyzer id, and fail the scan with a real message instead of silently dropping all but the last crash (#105). +- **Rate limiter is per-route.** A burst on one endpoint (suppression imports, tag edits) used to drain the single global budget and starve unrelated mutations; each route template now holds its own bucket and reset is synchronized (#100). +- **Update checks stop polluting the console.** An unreachable GitHub returns `200 {unreachable: true}` instead of a 5xx that shows as a network error in devtools; fetches run under the request context so a hung connection can't pin the handler; the comparison understands prerelease tags (#115, #123). +- **Managed SonarQube no longer aborts startup.** If the bundled runtime can't start, the app warns and continues — deep/pentest scans mark the analyzer unavailable rather than the whole app refusing to boot (#94). +- **Tool manager hardening.** `IsReady` verifies size and executable bit instead of existence alone, so a half-written or quarantined binary no longer counts as installed; path removal uses Windows-appropriate handling with real retry backoff instead of posix `chmod` + `RemoveAll` on every platform (#97, #106, #121). +- **Notes validate.** POST rejects empty/oversized text, oversized `import_key`, malformed fingerprints, and fingerprints that belong to no finding in the workspace; a per-finding cap stops an unbounded notes table (#119, #125). +- **Pentest input validation** rejects malformed targets and options before a probe starts (#122). +- **Self-update verifies before replacing.** The signed checksum is fetched and verified before the archive is staged, so a bad signature can't leave a half-applied update (#127). +- **Repository hardening.** `NewID` no longer depends on crypto-randomness (a primary key needs uniqueness, not secrecy), so a degraded RNG can't crash the process; malformed `settings_json`/metadata unmarshal failures are logged instead of silently producing zero values; update paths check `RowsAffected`; the SQLite pool no longer serializes concurrent readers (#101, #104, #107, #112, #116). + ## [0.50.0] - 2026-11-22 ### Added diff --git a/cmd/bluntcode/bootstrap.go b/cmd/bluntcode/bootstrap.go index 5cc6267a..4b38b70c 100644 --- a/cmd/bluntcode/bootstrap.go +++ b/cmd/bluntcode/bootstrap.go @@ -129,9 +129,11 @@ func openCore() (core *appCore, release func(), err error) { semgrepVersion = toolService.Status("semgrep").Version managedSonar, err := sonarqube.NewManaged(paths.DataDir, toolService.Manager, manifest) if err != nil { - _ = db.Close() - _ = guard.Close() - return abort(fmt.Errorf("configure managed SonarQube: %w", err)) + // One optional analyzer's platform restriction must not take the whole + // app down: warn and keep booting — the registry/UI already model + // not-ready tools. + logger.Warn("managed SonarQube unavailable; scans run without it", "error", err) + managedSonar = nil } registry := analyzers.NewRegistry() // Analyzer adapters only execute Blunt Code-managed paths; no PATH lookup is used. @@ -157,7 +159,9 @@ func openCore() (core *appCore, release func(), err error) { // entry); the path mirrors the manifest's executable field. _ = registry.Register(analyzerscheckov.New(filepath.Join(paths.ToolsDir, "iac-checkov", "3.3.16", "env", "checkov", "Scripts", "python.exe"), "3.3.16")) _ = registry.Register(semgrep.New(semgrepExecutable, semgrepVersion, semgrepRules)) - _ = registry.Register(managedSonar) + if managedSonar != nil { + _ = registry.Register(managedSonar) + } registerBuiltinAnalyzers(registry, toolService.Offline) scanService := scans.New(db, registry, bus, paths.ReportsDir, paths.ToolsDir, toolService) app := &appCore{ @@ -177,8 +181,10 @@ func openCore() (core *appCore, release func(), err error) { stopScans(scanService, logger) shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - if err := managedSonar.Shutdown(shutdownCtx); err != nil { - logger.Warn("managed SonarQube shutdown failed", "error", err) + if managedSonar != nil { + if err := managedSonar.Shutdown(shutdownCtx); err != nil { + logger.Warn("managed SonarQube shutdown failed", "error", err) + } } _ = db.Close() _ = guard.Close() diff --git a/cmd/bluntcode/main.go b/cmd/bluntcode/main.go index 5d8598a5..202a6274 100644 --- a/cmd/bluntcode/main.go +++ b/cmd/bluntcode/main.go @@ -198,7 +198,10 @@ func runServer(args []string) { if !noBrowser && app.settings.OpenBrowser { openBrowser(signInURL(url, server.Token()), app.logger) } - httpServer := &http.Server{Handler: root, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second} + // ReadTimeout covers header+body together so a client trickling a request + // body can't hold a connection (and its DB slot) forever. WriteTimeout is + // deliberately unset: scan progress streams over SSE with no deadline. + httpServer := &http.Server{Handler: root, ReadTimeout: 30 * time.Second, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second} var shutdownOnce sync.Once shutdown := func() { shutdownOnce.Do(func() { @@ -331,7 +334,10 @@ const ( func staticHandler() http.Handler { content, err := fs.Sub(staticFiles, "static") if err != nil { - panic(err) + // Never panic in library-adjacent code: serve a plain 500 instead. + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "static assets unavailable", http.StatusInternalServerError) + }) } files := http.FileServer(http.FS(content)) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/cmd/bluntcode/static/assets/AnalyticsCharts-CvbXoCAu.js b/cmd/bluntcode/static/assets/AnalyticsCharts-CvbXoCAu.js new file mode 100644 index 00000000..aafec338 --- /dev/null +++ b/cmd/bluntcode/static/assets/AnalyticsCharts-CvbXoCAu.js @@ -0,0 +1 @@ +import{j as e,aq as g,bl as u,aH as x}from"./vendor-CPiMTDiC.js";import{aS as d,aT as j,aU as f,aV as v}from"./index-CYnHslPa.js";function p({data:s}){const i=d.filter(l=>s.some(a=>(a[l]??0)>0));return e.jsx("ul",{className:"viz-legend","aria-hidden":"true",children:i.map(l=>e.jsxs("li",{children:[e.jsx("i",{style:{background:v[l]}}),l]},l))})}function c({children:s,label:i,icon:l,note:a}){return e.jsxs("article",{"aria-label":i,className:"viz-card",children:[e.jsxs("header",{className:"viz-card-head",children:[e.jsxs("h3",{children:[l,i]}),a!=null&&e.jsx("span",{className:"viz-card-chip tabular-nums",children:a})]}),s]})}function N({items:s}){if(!s.length)return e.jsx("p",{className:"text-sm text-[var(--color-ink-faint)]",children:"No language data yet."});const i=Math.max(...s.map(a=>a.files),1),l=`Language coverage: ${s.map(a=>`${a.language} ${a.files} ${a.files===1?"file":"files"}`).join(", ")}`;return e.jsx("div",{className:"grid gap-2.5",role:"img","aria-label":l,children:s.map(a=>e.jsxs("div",{className:"grid gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-xs",children:[e.jsx("span",{className:"truncate font-medium text-[var(--color-ink)]",children:a.language}),e.jsxs("span",{className:"shrink-0 tabular-nums text-[var(--color-ink-faint)]",children:[a.files," ",a.files===1?"file":"files"]})]}),e.jsx("div",{className:"h-2.5 overflow-hidden rounded-full bg-[var(--color-surface-muted)]",children:e.jsx("div",{className:"h-full rounded-full bg-[var(--color-accent)]",style:{width:`${Math.round(a.files*1e3/i)/10}%`},"aria-hidden":"true"})})]},a.language))})}function $({series:s,trends:i,severityCounts:l,languages:a}){const o=l??{critical:0,high:0,medium:0,low:0,info:0},h=a??[],t=s?.length?s.map((n,m)=>({label:n.finished_at??`T${m+1}`,total:n.total,...n.severity,score:n.score,grade:n.grade})):(i??[]).map(n=>({label:n.label,total:n.total})),r=d.filter(n=>(o[n]??0)>0).length;return e.jsxs("section",{"aria-label":"Analytics overview",className:"bento",children:[e.jsx("div",{className:"span-8",children:e.jsx(c,{label:"Findings over time",icon:e.jsx(g,{"aria-hidden":"true"}),note:t.length?`${t.length} scans`:void 0,children:t.length>=2?e.jsxs(e.Fragment,{children:[e.jsx(j,{data:t,stacked:!!s?.length,height:200}),s?.length?e.jsx(p,{data:t}):null]}):e.jsx("p",{className:"viz-empty",children:t.length===1?"One completed scan so far":"No completed scans yet"})})}),e.jsx("div",{className:"span-4",children:e.jsx(c,{label:"Severity",icon:e.jsx(u,{"aria-hidden":"true"}),note:r?`${r}/${d.length}`:void 0,children:r?e.jsx("div",{className:"viz-center",children:e.jsx(f,{counts:o,size:164})}):e.jsx("p",{className:"viz-empty",children:"No findings"})})}),e.jsx("div",{className:"span-12",children:e.jsx(c,{label:"Languages",icon:e.jsx(x,{"aria-hidden":"true"}),note:h.length||void 0,children:e.jsx(N,{items:h})})})]})}export{$ as AnalyticsCharts}; diff --git a/cmd/bluntcode/static/assets/ComplianceMatrix-D_wlb1Vj.js b/cmd/bluntcode/static/assets/ComplianceMatrix-D_wlb1Vj.js new file mode 100644 index 00000000..490745ba --- /dev/null +++ b/cmd/bluntcode/static/assets/ComplianceMatrix-D_wlb1Vj.js @@ -0,0 +1 @@ +import{r,j as e}from"./vendor-CPiMTDiC.js";import{aW as n,am as v}from"./index-CYnHslPa.js";const j=r.forwardRef(({className:t,...i},s)=>e.jsx("div",{className:n("relative w-full overflow-auto overscroll-x-contain rounded-[var(--radius-lg)] border border-[var(--color-rule-faint)] bg-[var(--color-surface)] shadow-[var(--shadow-card)]","[--table-pad:14px]",t),children:e.jsx("table",{ref:s,className:n("w-full caption-bottom border-collapse text-sm tabular-nums",(t?.includes("w-full"),void 0)),...i})}));j.displayName="Table";const N=r.forwardRef(({className:t,sticky:i,...s},p)=>e.jsx("thead",{ref:p,className:n("[&_tr]:border-b bg-[var(--color-surface-muted)]",i&&"sticky top-0 z-[1] shadow-[var(--shadow-xs)]",t),...s}));N.displayName="TableHeader";const C=r.forwardRef(({className:t,...i},s)=>e.jsx("tbody",{ref:s,className:n("[&_tr:last-child]:border-0",t),...i}));C.displayName="TableBody";const A=r.forwardRef(({className:t,...i},s)=>e.jsx("tfoot",{ref:s,className:n("border-t bg-[var(--color-surface-muted)] font-medium [&>tr]:last:border-b-0",t),...i}));A.displayName="TableFooter";const b=r.forwardRef(({className:t,...i},s)=>e.jsx("tr",{ref:s,className:n("group border-b border-[var(--color-rule-faint)] tabular-nums transition-colors duration-[var(--dur-fast)] ease-out","hover:bg-[color-mix(in_oklch,var(--color-accent)_5%,transparent)] data-[state=selected]:bg-[var(--color-surface-muted)]","motion-reduce:transition-none","data-[cv=auto]:[content-visibility:auto] data-[cv=auto]:[contain-intrinsic-size:auto_3rem]",t),...i}));b.displayName="TableRow";const c=r.forwardRef(({className:t,...i},s)=>e.jsx("th",{ref:s,className:n("h-10 px-[var(--table-pad)] text-left align-middle text-xs font-semibold text-[var(--color-ink-faint)] tabular-nums [&:has([role=checkbox])]:pr-0",t),...i}));c.displayName="TableHead";const l=r.forwardRef(({className:t,...i},s)=>e.jsx("td",{ref:s,className:n("p-[var(--table-pad)] align-middle tabular-nums [&:has([role=checkbox])]:pr-0","group-hover:[&_.row-actions]:opacity-100 [&_.row-actions]:opacity-0 [&_.row-actions]:transition-opacity [&_.row-actions:focus-within]:opacity-100",t),...i}));l.displayName="TableCell";const S=r.forwardRef(({className:t,...i},s)=>e.jsx("caption",{ref:s,className:n("sr-only",t),...i}));S.displayName="TableCaption";const h=[{id:"A01",title:"Broken Access Control",cwe:["CWE-284","CWE-862"],categoryHints:["access","authz","idor","rbac"]},{id:"A02",title:"Cryptographic Failures",cwe:["CWE-310","CWE-327"],categoryHints:["crypto","crypt","secrets","hardcoded"]},{id:"A03",title:"Injection",cwe:["CWE-20","CWE-89","CWE-78"],categoryHints:["injection","sqli","xss","command"]},{id:"A04",title:"Insecure Design",cwe:["CWE-657","CWE-799"],categoryHints:["design","threat"]},{id:"A05",title:"Security Misconfiguration",cwe:["CWE-16","CWE-611"],categoryHints:["misconfig","config","dockerfile","yaml"]},{id:"A06",title:"Vulnerable and Outdated Components",cwe:["CWE-937","CWE-1104"],categoryHints:["dependencies","vulnerable","outdated"]},{id:"A07",title:"Identification and Authentication Failures",cwe:["CWE-287","CWE-384"],categoryHints:["authentication","auth bypass","session","jwt"]},{id:"A08",title:"Software and Data Integrity Failures",cwe:["CWE-829","CWE-502"],categoryHints:["integrity","deserialization","supply"]},{id:"A09",title:"Security Logging and Monitoring Failures",cwe:["CWE-117","CWE-223"],categoryHints:["logging","monitoring","log injection"]},{id:"A10",title:"Server-Side Request Forgery (SSRF)",cwe:["CWE-918"],categoryHints:["ssrf","server-side request"]}],k=new Set(["maintainability","code_smell","performance","complexity","duplication","style"]);function E(t){return t.analyzer_id!=="todo"&&!k.has(t.category)}const H=new Map(h.map(t=>[t.id,t.categoryHints.map(i=>new RegExp(`\\b${i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`))]));function _(t){if(!E(t))return null;const i=`${t.category} ${t.rule_id??""} ${t.title??""} ${t.message}`.toLowerCase();for(const s of h)if(H.get(s.id).some(p=>p.test(i)))return s.id;return t.category==="secrets"||i.includes("secret")||i.includes("hardcoded")?"A02":t.category==="dependencies"||i.includes("depend")?"A06":t.category==="container"||t.category==="iac"?"A05":i.includes("injection")||i.includes("xss")||i.includes("sqli")?"A03":/\bauth(n|z)?\b/.test(i)?"A07":null}function w(t){return{critical:4,high:3,medium:2,low:1,info:0}[t]??-1}function $(t){return t==="critical"||t==="high"?"danger":t==="medium"?"warning":"secondary"}function q({findings:t,scanId:i}){const[s,p]=r.useState(),f=r.useMemo(()=>{const a=new Map;for(const d of h)a.set(d.id,[]);for(const d of t){const u=_(d);u&&a.get(u).push(d)}const o=t.filter(E).length||1;return h.map(d=>{const u=a.get(d.id),x=u.length,g=u.length?[...u].sort((R,T)=>w(T.severity)-w(R.severity))[0].severity:"info",W=Math.round(x/o*100);return{...d,count:x,findings:u,topSeverity:g,pct:W,status:x===0?"No evidence":g==="critical"||g==="high"?"Review required":"Review"}})},[t]),y=a=>p(o=>o===a?void 0:a),m=f.find(a=>a.id===s);return e.jsxs("section",{"aria-label":"Compliance matrix",className:"rounded-[var(--radius-card)] border border-[var(--color-rule)] bg-[var(--color-surface)] shadow-[var(--shadow-card)] overflow-hidden",children:[e.jsxs("div",{className:"p-4 pb-2 flex items-center justify-between",children:[e.jsx("h3",{className:"font-display text-sm font-semibold tracking-tight",children:"OWASP Top 10 (2021) — finding classification"}),e.jsxs("span",{className:"text-xs text-[var(--color-ink-faint)]",children:[f.reduce((a,o)=>a+o.count,0)," ",t.length===1?"finding":"findings"," mapped"]})]}),e.jsx("p",{className:"availability-note mx-4 mb-3",children:"Heuristic classification of loaded security findings, not a compliance assessment. Code-quality findings and TODO markers are not classified. No evidence does not mean a category passed."}),e.jsxs(j,{children:[e.jsx(N,{children:e.jsxs(b,{children:[e.jsx(c,{children:"OWASP"}),e.jsx(c,{children:"Title"}),e.jsx(c,{children:"CWE"}),e.jsx(c,{children:"Severity"}),e.jsx(c,{children:"Count"}),e.jsx(c,{children:"Findings"}),e.jsx(c,{children:"Status"})]})}),e.jsx(C,{children:f.map(a=>e.jsxs(b,{className:"cursor-pointer hover:bg-[var(--color-surface-muted)]",onClick:()=>y(a.id),tabIndex:0,role:"button","aria-expanded":s===a.id,"aria-label":`Show loaded findings for ${a.id} ${a.title}`,onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),y(a.id))},children:[e.jsx(l,{className:"font-mono font-semibold",children:a.id}),e.jsx(l,{className:"max-w-[14rem] truncate",title:a.title,children:a.title}),e.jsx(l,{className:"text-xs text-[var(--color-ink-faint)]",children:a.cwe.join(", ")}),e.jsx(l,{children:e.jsx(v,{variant:a.count===0?"secondary":$(a.topSeverity),children:a.count===0?"—":a.topSeverity})}),e.jsx(l,{className:"tabular-nums font-mono",children:a.count}),e.jsxs(l,{className:"min-w-[8rem]",children:[e.jsx("div",{className:"h-2 w-full rounded-full bg-[var(--color-surface-muted)] overflow-hidden",role:"progressbar","aria-valuenow":a.pct,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${a.id} share of loaded findings ${a.pct}%`,children:e.jsx("div",{className:"h-full bg-[var(--color-accent)]",style:{width:`${a.pct}%`}})}),e.jsxs("span",{className:"text-xs text-[var(--color-ink-faint)]",children:[a.pct,"%"]})]}),e.jsx(l,{children:e.jsx(v,{variant:a.count===0?"secondary":a.status==="Review required"?"danger":"warning",children:a.status})})]},a.id))})]}),m&&e.jsxs("section",{className:"p-4 border-t border-[var(--color-rule)]","aria-label":`${m.id} loaded findings`,children:[e.jsxs("h4",{children:[m.id," · ",m.title]}),m.findings.length?e.jsx("ul",{className:"space-y-2 mt-3",children:m.findings.map(a=>e.jsxs("li",{children:[e.jsx("a",{href:`/scans/${encodeURIComponent(i??"")}?finding=${encodeURIComponent(a.id)}`,className:"text-[var(--color-accent-strong)]",children:a.title||a.message}),e.jsxs("p",{className:"text-xs text-[var(--color-ink-soft)]",children:[a.severity," · ",a.relative_path||"Project-level finding"]})]},a.id))}):e.jsx("p",{className:"muted",children:"No loaded findings mapped to this category. This does not establish compliance."})]})]})}export{q as ComplianceMatrix,h as OWASP_TOP10,E as isSecurityRelevant,_ as mapFindingToOwasp}; diff --git a/cmd/bluntcode/static/assets/DependencyGraph-Dy7uz7iK.js b/cmd/bluntcode/static/assets/DependencyGraph-Dy7uz7iK.js new file mode 100644 index 00000000..718a990f --- /dev/null +++ b/cmd/bluntcode/static/assets/DependencyGraph-Dy7uz7iK.js @@ -0,0 +1 @@ +import{r as i,j as n}from"./vendor-CPiMTDiC.js";import{ao as L,ap as T,aq as Z,ar as _}from"./index-CYnHslPa.js";const g=800,p=360,se=40;function U(l){const M=g/2,r=p/2,j=Math.min(g,p)/2-se,v={};return l.forEach((b,w)=>{if(b.kind==="workspace")v[b.id]={x:M,y:r,vx:0,vy:0};else{const C=w/Math.max(1,l.length-1)*Math.PI*2-Math.PI/2,$=b.kind==="file"?j*.68:j;v[b.id]={x:M+Math.cos(C)*$,y:r+Math.sin(C)*$,vx:0,vy:0}}}),v}function J(l){return l.kind==="workspace"?18:l.kind==="file"?13:9}function re(l){return l.kind==="workspace"?"var(--color-accent)":l.kind==="file"?"var(--color-accent-strong)":"var(--color-ink-faint)"}function ce({nodes:l,edges:M}){const{nodes:r,edges:j}=i.useMemo(()=>l?.length?{nodes:l,edges:M??[]}:{nodes:[],edges:[]},[l,M]),[v,b]=i.useState(()=>U(r)),[w,C]=i.useState(null),[$,B]=i.useState(1),[d,q]=i.useState({x:0,y:0}),[N,G]=i.useState(null),[V,X]=i.useState(!1),D=i.useRef({x:0,y:0,ox:0,oy:0}),F=i.useRef(null);i.useEffect(()=>{b(U(r))},[r]),i.useEffect(()=>{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;let t=0,a=0;const y=90,c=()=>{a++>y||(b(z=>{const x={...z};for(const s of Object.keys(x))x[s]={...x[s]};const m=r.map(s=>s.id);for(let s=0;sE.id===m[s])?.kind!=="workspace"&&(f.x+=I,f.y+=A),r.find(E=>E.id===m[o])?.kind!=="workspace"&&(u.x-=I,u.y-=A)}}for(const s of j){const o=x[s.from],f=x[s.to];if(!o||!f)continue;const u=f.x-o.x,h=f.y-o.y,k=Math.hypot(u,h)||1,R=(k-110)*.02,S=u/k*R,I=h/k*R,A=r.find(O=>O.id===s.from)?.kind==="workspace",E=r.find(O=>O.id===s.to)?.kind==="workspace";A||(o.x+=S,o.y+=I),E||(f.x-=S,f.y-=I)}for(const s of m){const o=x[s];if(!(r.find(h=>h.id===s)?.kind==="workspace")){const h=g/2,k=p/2;o.vx=(o.vx+(h-o.x)*.005)*.88,o.vy=(o.vy+(k-o.y)*.005)*.88,o.x+=o.vx,o.y+=o.vy}const u=J(r.find(h=>h.id===s));o.x=Math.max(u+8,Math.min(g-u-8,o.x)),o.y=Math.max(u+8,Math.min(p-u-8,o.y))}return x}),t=requestAnimationFrame(c))};return t=requestAnimationFrame(c),()=>cancelAnimationFrame(t)},[r,j]);const K=i.useCallback((e,t)=>{t.target.setPointerCapture(t.pointerId),G(e)},[]),Q=i.useCallback(e=>{if(N){const t=F.current?.getBoundingClientRect();if(!t)return;const a=g/t.width,y=p/t.height,c=(e.clientX-t.left)*a,z=(e.clientY-t.top)*y,x=(c-d.x)/$,m=(z-d.y)/$;b(s=>({...s,[N]:{...s[N],x,y:m,vx:0,vy:0}}));return}if(V){const t=e.clientX-D.current.x,a=e.clientY-D.current.y;q({x:D.current.ox+t*(g/(F.current?.getBoundingClientRect().width??g)),y:D.current.oy+a*(p/(F.current?.getBoundingClientRect().height??p))})}},[N,V,d.x,d.y,$]),Y=i.useCallback(()=>{G(null),X(!1)},[]),ee=i.useCallback(e=>{X(!0),D.current={x:e.clientX,y:e.clientY,ox:d.x,oy:d.y}},[d.x,d.y]),te=i.useCallback(()=>B(e=>Math.min(2.5,+(e+.2).toFixed(2))),[]),ne=i.useCallback(()=>B(e=>Math.max(.5,+(e-.2).toFixed(2))),[]),oe=i.useCallback(()=>{B(1),q({x:0,y:0})},[]),P=w?r.find(e=>e.id===w):null,H=w?v[w]:null;return r.length===0?n.jsxs(L,{children:[n.jsx(T,{children:n.jsx(Z,{children:"Dependency graph"})}),n.jsxs(_,{children:[n.jsx("p",{className:"availability-note",children:"Dependency relationships are unavailable in this version."}),n.jsx("p",{className:"muted",children:"Detected languages do not describe imports or package relationships. Run a deep scan to review supported dependency vulnerability findings in the report."})]})]}):n.jsxs(L,{className:"rounded-[var(--radius-card)] border border-[var(--color-rule)] bg-[var(--color-surface)] shadow-[var(--shadow-card)]",children:[n.jsxs(T,{className:"flex flex-row items-center justify-between gap-2 pb-2",children:[n.jsx(Z,{className:"text-sm font-semibold",children:"Dependency graph"}),n.jsxs("div",{className:"flex items-center gap-1",role:"toolbar","aria-label":"Graph controls",children:[n.jsx("button",{type:"button",className:"button secondary",style:{minHeight:"1.9rem",padding:"0 var(--space-sm)"},onClick:te,"aria-label":"Zoom in",children:"+"}),n.jsx("button",{type:"button",className:"button secondary",style:{minHeight:"1.9rem",padding:"0 var(--space-sm)"},onClick:ne,"aria-label":"Zoom out",children:"−"}),n.jsx("button",{type:"button",className:"button secondary",style:{minHeight:"1.9rem",padding:"0 var(--space-sm)"},onClick:oe,"aria-label":"Reset view",children:"Reset"})]})]}),n.jsxs(_,{className:"pt-0",children:[n.jsxs("div",{className:"relative overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-rule-faint)] bg-[var(--color-surface-muted)]",style:{touchAction:"none"},children:[n.jsx("svg",{ref:F,viewBox:`0 0 ${g} ${p}`,role:"img","aria-label":`Dependency graph with ${r.length} nodes and ${j.length} connections. Drag nodes to reposition, drag background to pan.`,className:"block h-[22rem] w-full select-none",onPointerMove:Q,onPointerUp:Y,onPointerLeave:Y,onPointerDown:ee,children:n.jsxs("g",{transform:`translate(${d.x} ${d.y}) scale(${$})`,children:[j.map((e,t)=>{const a=v[e.from],y=v[e.to];return!a||!y?null:n.jsx("line",{x1:a.x,y1:a.y,x2:y.x,y2:y.y,stroke:"var(--color-rule-strong)",strokeWidth:1.4,strokeOpacity:.7},`${e.from}-${e.to}-${t}`)}),r.map(e=>{const t=v[e.id];if(!t)return null;const a=J(e),y=w===e.id;return n.jsxs("g",{tabIndex:0,role:"button","aria-label":`${e.label} ${e.kind}${e.findingCount!==void 0?`, ${e.findingCount} ${e.findingCount===1?"finding":"findings"}`:""}`,onPointerDown:c=>{c.stopPropagation(),K(e.id,c)},onPointerEnter:()=>C(e.id),onPointerLeave:()=>C(c=>c===e.id?null:c),onFocus:()=>C(e.id),onBlur:()=>C(c=>c===e.id?null:c),style:{cursor:N===e.id?"grabbing":"grab",outline:"none"},children:[n.jsx("circle",{cx:t.x,cy:t.y,r:a+(y?3:0),fill:"var(--color-surface)",opacity:0}),n.jsx("circle",{cx:t.x,cy:t.y,r:a,fill:re(e),stroke:"var(--color-surface)",strokeWidth:2,style:{filter:y?"brightness(1.08)":void 0,transition:"transform 140ms var(--ease-out)",transformOrigin:`${t.x}px ${t.y}px`}}),e.kind==="workspace"&&n.jsx("text",{x:t.x,y:t.y+4,textAnchor:"middle",fill:"white",fontSize:9,fontWeight:700,pointerEvents:"none","aria-hidden":"true",children:"WS"}),n.jsx("text",{x:t.x,y:t.y+a+13,textAnchor:"middle",fill:"var(--color-ink-soft)",fontSize:10,fontWeight:600,fontFamily:"var(--font-mono)",pointerEvents:"none",children:e.label})]},e.id)})]})}),P&&H&&n.jsxs("div",{role:"tooltip",className:"pointer-events-none absolute z-10 rounded-[var(--radius-md)] border border-[var(--color-rule)] bg-[var(--color-surface)] px-3 py-2 text-xs shadow-[var(--shadow-lg)]",style:{left:`calc(${H.x/g*100}% + ${d.x}px)`,top:`calc(${H.y/p*100}% + ${d.y}px)`,transform:"translate(-50%, calc(-100% - 14px))"},children:[n.jsx("strong",{className:"block text-[var(--color-ink)]",children:P.label}),n.jsx("span",{className:"text-[var(--color-ink-soft)]",children:[P.kind,P.language,`${P.findingCount??0} ${P.findingCount===1?"finding":"findings"}`].filter(Boolean).join(", ")})]})]}),n.jsx("p",{className:"mt-2 text-xs text-[var(--color-ink-faint)]",children:"Drag nodes to reposition, drag the background to pan, use the zoom controls, and hover or focus a node for its finding count."})]})]})}export{ce as DependencyGraph}; diff --git a/cmd/bluntcode/static/assets/PentestPage-BimU3Fub.js b/cmd/bluntcode/static/assets/PentestPage-BimU3Fub.js new file mode 100644 index 00000000..9ead41db --- /dev/null +++ b/cmd/bluntcode/static/assets/PentestPage-BimU3Fub.js @@ -0,0 +1 @@ +import{r as x,j as e,bi as I,bj as J,a2 as K,J as ee,au as pe,N as se,a6 as ue,bk as ae,$ as ve,a1 as te,ab as ge}from"./vendor-CPiMTDiC.js";import{ai as je,aj as $,ak as fe,al as V,am as p,an as H,ao as C,ap as G,aq as Q,ar as X,as as re,at as ie,au as T,av as ne,aw as le,ax as oe,ay as ce,az as E,aA as _,aB as R,aC as L,aD as O,aE as u,aF as S,aG as de,aH as W,aI as be,aJ as Z,aK as ye,aL as Ne,aM as we,aN as U,aO as ke}from"./index-CYnHslPa.js";import{isSecurityRelevant as Se,mapFindingToOwasp as Ce,OWASP_TOP10 as Te}from"./ComplianceMatrix-D_wlb1Vj.js";const P=[{id:"sqli-error",name:"SQLi — Error Based",severity:"critical",owasp:"A03:2021",cwe:"CWE-89",payload:"' AND 1=CONVERT(int,@@version)--",remediation:"Use parameterized queries / prepared statements; validate and escape input; enforce least-privilege DB roles.",description:"Triggers verbose SQL errors to enumerate DB engine and version.",tags:["sqli","injection","database"],enabled:!0},{id:"sqli-union",name:"SQLi — Union Based",severity:"critical",owasp:"A03:2021",cwe:"CWE-89",payload:"' UNION SELECT null,username,password FROM users--",remediation:"Parameterized queries; strip UNION/SELECT from user-controlled concatenation; use ORM safely.",description:"Exfiltrates data via UNION SELECT against crafted column count.",tags:["sqli","union","injection"],enabled:!0},{id:"sqli-blind",name:"SQLi — Blind Boolean/Time",severity:"high",owasp:"A03:2021",cwe:"CWE-89",payload:"' AND IF(SUBSTRING(password,1,1)='a',SLEEP(3),0)--",remediation:"Parameterized queries; uniform error responses; rate limit DB-bound endpoints.",description:"Infers data via boolean conditions and time delays without error output.",tags:["sqli","blind","injection"],enabled:!0},{id:"xss-reflected",name:"XSS — Reflected",severity:"high",owasp:"A03:2021",cwe:"CWE-79",payload:" - + diff --git a/cmd/bluntcode/update_cmd.go b/cmd/bluntcode/update_cmd.go index 073a2c67..0ae96f4e 100644 --- a/cmd/bluntcode/update_cmd.go +++ b/cmd/bluntcode/update_cmd.go @@ -1,6 +1,7 @@ package main import ( + "context" "flag" "fmt" "io" @@ -50,7 +51,7 @@ func runUpdateCheck(args []string, stdout, stderr io.Writer) int { return 2 } - res, err := api.CheckUpdateDirect(version) + res, err := api.CheckUpdateDirect(context.Background(), version) if err != nil { fmt.Fprintf(stderr, "bluntcode update check: %v\n", err) return 1 diff --git a/internal/analyzers/sonarqube/managed.go b/internal/analyzers/sonarqube/managed.go index 1f4fb03b..cc013689 100644 --- a/internal/analyzers/sonarqube/managed.go +++ b/internal/analyzers/sonarqube/managed.go @@ -192,6 +192,11 @@ func (s *ManagedServer) ExitStatus() (error, bool) { defer s.mu.Unlock() return s.exitErr, s.exited } + +// readinessHTTPClient backs the lightweight status probe; allocating a fresh +// client per check (connection pool, TLS state, GC churn) was pure waste. +var readinessHTTPClient = &http.Client{Timeout: 3 * time.Second} + func (s *ManagedServer) Healthy(ctx context.Context) (bool, error) { u := s.URL if u == "" { @@ -204,7 +209,7 @@ func (s *ManagedServer) Healthy(ctx context.Context) (bool, error) { if err != nil { return false, err } - res, err := (&http.Client{Timeout: 3 * time.Second}).Do(req) + res, err := readinessHTTPClient.Do(req) if err != nil { return false, err } diff --git a/internal/api/auth.go b/internal/api/auth.go index 1fa2e8ff..8c11ca61 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -4,8 +4,7 @@ import ( "crypto/rand" "crypto/subtle" "encoding/base64" - "encoding/json" - "io" + "fmt" "mime" "net/http" "net/url" @@ -22,12 +21,25 @@ import ( const TokenFragmentKey = "token" // NewToken returns a fresh 256-bit API token. -func NewToken() string { +// NewToken mints a credential; the error is returned, not panic()ed, because +// tokens are minted on request paths (session tickets), not only at startup. +// Init-time callers that cannot propagate use mustToken. +func NewToken() (string, error) { raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { - panic("bluntcode: crypto/rand unavailable: " + err.Error()) + return "", fmt.Errorf("crypto/rand unavailable: %w", err) } - return base64.RawURLEncoding.EncodeToString(raw) + return base64.RawURLEncoding.EncodeToString(raw), nil +} + +// mustToken is for process bootstrap only: a token at startup is mandatory, +// so failure there is legitimately fatal. +func mustToken() string { + token, err := NewToken() + if err != nil { + panic("bluntcode: " + err.Error()) + } + return token } // Token is the credential every /api/ request except GET /health must carry, @@ -37,11 +49,12 @@ func (s *Server) Token() string { return s.token } // SetToken replaces the generated token, e.g. so the host process can share // one token between the HTTP server and its on-disk token file. -func (s *Server) SetToken(token string) { +func (s *Server) SetToken(token string) error { if strings.TrimSpace(token) == "" { - panic("bluntcode: empty API token") + return fmt.Errorf("bluntcode: empty API token") } s.token = token + return nil } // TicketParam is the query parameter carrying a ticket on GET navigations. @@ -63,7 +76,7 @@ type ticket struct { expires time.Time } -func (t *ticketStore) mint(path string, now time.Time) string { +func (t *ticketStore) mint(path string, now time.Time) (string, error) { t.mu.Lock() defer t.mu.Unlock() if t.tickets == nil { @@ -74,9 +87,12 @@ func (t *ticketStore) mint(path string, now time.Time) string { delete(t.tickets, id) } } - id := NewToken() + id, err := NewToken() + if err != nil { + return "", err + } t.tickets[id] = ticket{path: path, expires: now.Add(ticketTTL)} - return id + return id, nil } func (t *ticketStore) redeem(id, path string, now time.Time) bool { @@ -213,7 +229,9 @@ func (s *Server) sessionTicket(w http.ResponseWriter, r *http.Request) { var input struct { Path string `json:"path"` } - if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&input); err != nil { + // Same strict decode every other endpoint uses: unknown fields are + // rejected, not silently ignored. + if err := decode(r, &input); err != nil { fail(w, http.StatusBadRequest, "INVALID_REQUEST", "Send {\"path\": \"/api/v1/...\"}.") return } @@ -222,5 +240,10 @@ func (s *Server) sessionTicket(w http.ResponseWriter, r *http.Request) { fail(w, http.StatusBadRequest, "INVALID_REQUEST", "Tickets are issued for a single /api/"+APIVersion+"/ path.") return } - writeJSON(w, http.StatusOK, map[string]any{"ticket": s.tickets.mint(input.Path, time.Now()), "expires_in": int(ticketTTL.Seconds())}) + ticket, err := s.tickets.mint(input.Path, time.Now()) + if err != nil { + fail(w, http.StatusInternalServerError, "TICKET_FAILED", "Could not issue a session ticket.") + return + } + writeJSON(w, http.StatusOK, map[string]any{"ticket": ticket, "expires_in": int(ticketTTL.Seconds())}) } diff --git a/internal/api/demo_seed.go b/internal/api/demo_seed.go index 944a211e..3c558dbe 100644 --- a/internal/api/demo_seed.go +++ b/internal/api/demo_seed.go @@ -30,6 +30,31 @@ func demoSeedAllowed(r *http.Request) bool { return true } +// unseedDemo removes every workspace tagged demo-ui — seeded junk used to +// share the DB permanently with real workspaces, and its temp-dir roots decay +// into "folder missing" rows after a reboot. +func (s *Server) unseedDemo(w http.ResponseWriter, r *http.Request) { + if !demoSeedAllowed(r) { + fail(w, 403, "DEMO_SEED_DISABLED", "Set BLUNTCODE_DEMO_SEED=1 to manage demo data.") + return + } + ids, err := s.db.WorkspaceIDsWithTag(r.Context(), "demo-ui") + if err != nil { + fail(w, 500, "DATABASE_ERROR", "Could not list demo workspaces.") + return + } + removed := 0 + for _, id := range ids { + if err := s.db.DeleteWorkspace(r.Context(), id); err != nil { + s.log.Warn("demo purge: delete failed", "workspace", id, "error", err) + continue + } + s.cache.invalidate(id) + removed++ + } + writeJSON(w, 200, map[string]any{"workspaces": len(ids), "removed": removed}) +} + // seedDemo inserts clearly tagged synthetic workspaces and scans for UI / harness testing. // Opt-in only: BLUNTCODE_DEMO_SEED=1 (and optional BLUNTCODE_DEMO_TOKEN + matching header). func (s *Server) seedDemo(w http.ResponseWriter, r *http.Request) { diff --git a/internal/api/notes.go b/internal/api/notes.go index ce1b0d78..9df94b98 100644 --- a/internal/api/notes.go +++ b/internal/api/notes.go @@ -39,6 +39,28 @@ func (s *Server) findingNotes(w http.ResponseWriter, r *http.Request) { fail(w, 400, "INVALID_NOTE", "Enter a note between 1 and 10,000 characters.") return } + // Notes attach to real findings only — a phantom fingerprint would + // silently accumulate orphans that never render anywhere. + exists, err := s.db.FingerprintExists(r.Context(), work.ID, fingerprint) + if err != nil { + fail(w, 500, "DATABASE_ERROR", "Could not validate the finding.") + return + } + if !exists { + fail(w, 404, "FINDING_NOT_FOUND", "No finding in this workspace has that fingerprint.") + return + } + // Unbounded notes per fingerprint let a POST loop grow the table + // forever; the drawer then fetches the whole list on every open. + noteCount, err := s.db.FindingNoteCount(r.Context(), work.ID, fingerprint) + if err != nil { + fail(w, 500, "DATABASE_ERROR", "Could not save note.") + return + } + if noteCount >= 100 { + fail(w, 409, "NOTE_LIMIT", "This finding already has 100 notes. Delete some before adding more.") + return + } note, err := s.db.AddFindingNote(r.Context(), work.ID, fingerprint, input.Text, input.ImportKey) if err != nil { fail(w, 500, "DATABASE_ERROR", "Could not save note.") diff --git a/internal/api/notes_test.go b/internal/api/notes_test.go index c4bf05fb..41a9aed3 100644 --- a/internal/api/notes_test.go +++ b/internal/api/notes_test.go @@ -1,7 +1,9 @@ package api import ( + "bluntcode/internal/analyzers" "bluntcode/internal/core" + "bluntcode/internal/database" "context" "encoding/json" "net/http" @@ -16,7 +18,20 @@ func TestFindingNotesAPIValidationAndPersistence(t *testing.T) { if err != nil { t.Fatal(err) } - path := "/api/v1/workspaces/" + work.ID + "/notes/fingerprint" + // Notes attach to real findings only; seed one with fingerprint "fingerprint". + scan, err := s.db.CreateScan(context.Background(), core.Scan{WorkspaceID: work.ID, State: "completed"}) + if err != nil { + t.Fatal(err) + } + if _, err := s.db.SaveAnalyzerResult(context.Background(), scan.ID, database.AnalyzerRunInput{AnalyzerID: "ruff", Version: "t", State: "succeeded"}, []analyzers.Finding{{RelativePath: "a.go", StartLine: 1, RuleID: "r", Severity: "low", Message: "m"}}, nil); err != nil { + t.Fatal(err) + } + // SaveAnalyzerResult derives the fingerprint from finding content. + stored, err := s.db.Findings(context.Background(), scan.ID) + if err != nil || len(stored) == 0 { + t.Fatalf("seeded finding missing: %v", err) + } + path := "/api/v1/workspaces/" + work.ID + "/notes/" + stored[0].Fingerprint request := func(method, body string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, strings.NewReader(body)) r.Header.Set("Content-Type", "application/json") diff --git a/internal/api/pentest.go b/internal/api/pentest.go index 4e104fd2..84451842 100644 --- a/internal/api/pentest.go +++ b/internal/api/pentest.go @@ -30,6 +30,14 @@ var ( ) func (s *Server) pentestProbe(w http.ResponseWriter, r *http.Request) { + // The route is also registered workspace-scoped; a bogus {id} must not + // silently behave like the global probe. + if r.PathValue("id") != "" { + if _, ok := s.workspace(r); !ok { + fail(w, 404, "WORKSPACE_NOT_FOUND", "Workspace was not found.") + return + } + } var input PentestProbeRequest if err := decode(r, &input); err != nil { fail(w, 400, "INVALID_JSON", "Invalid probe request payload.") diff --git a/internal/api/ratelimit.go b/internal/api/ratelimit.go index 9a746c4a..e2d22820 100644 --- a/internal/api/ratelimit.go +++ b/internal/api/ratelimit.go @@ -11,6 +11,7 @@ import ( "math" "net/http" "strconv" + "strings" "sync" "time" ) @@ -65,15 +66,68 @@ func (b *tokenBucket) take(now time.Time) (ok bool, retryAfterSeconds int) { return false, int(retry) } -// apiMutationTokenBucket is the process-wide bucket: production runs exactly -// one server per data directory, so its whole mutating surface shares one -// budget. Tests reset it with ResetRateLimiter. -var apiMutationTokenBucket = newTokenBucket(rateLimitCapacity, rateLimitRefillPerMinute) +// rateLimitState holds one bucket per route pattern. A single global bucket +// let a burst on one endpoint (suppression imports, tag edits) starve every +// unrelated mutation — per-endpoint budgets keep the runaway-client +// protection without the starvation. +var rateLimitState = struct { + sync.Mutex + buckets map[string]*tokenBucket +}{buckets: map[string]*tokenBucket{}} -// ResetRateLimiter restores a full bucket. It exists for tests so rate-limit -// state never leaks between test cases that share the package-level bucket. +// rateLimitProbeMethods is the verb set used to recover the path template of +// a request whose own verb matches no route (405-bound requests resolve to "" +// from mux.Handler). +var rateLimitProbeMethods = []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} + +// routeKey resolves the path template this request would route under, without +// the leading verb: the budget for an endpoint is shared across every state- +// changing method so a flooded route limits POST as thoroughly as DELETE. +// Paths matching no route under any verb share one fallback bucket. +func routeKey(mux *http.ServeMux, r *http.Request) string { + _, pattern := mux.Handler(r) + if pattern == "" { + probe := new(http.Request) + *probe = *r + for _, method := range rateLimitProbeMethods { + probe.Method = method + if _, p := mux.Handler(probe); p != "" { + pattern = p + break + } + } + } + if pattern == "" { + return "unrouted" + } + if i := strings.IndexByte(pattern, ' '); i >= 0 { + return pattern[i+1:] + } + return pattern +} + +// bucketFor returns the token bucket for this request's route. r.Pattern is +// only populated after routing, so the middleware resolves the would-be +// template via routeKey instead. +func bucketFor(mux *http.ServeMux, r *http.Request) *tokenBucket { + key := routeKey(mux, r) + rateLimitState.Lock() + defer rateLimitState.Unlock() + b, ok := rateLimitState.buckets[key] + if !ok { + b = newTokenBucket(rateLimitCapacity, rateLimitRefillPerMinute) + rateLimitState.buckets[key] = b + } + return b +} + +// ResetRateLimiter restores full buckets. It exists for tests so rate-limit +// state never leaks between test cases; the swap is mutex-guarded so an +// in-flight request can never observe a torn pointer. func ResetRateLimiter() { - apiMutationTokenBucket = newTokenBucket(rateLimitCapacity, rateLimitRefillPerMinute) + rateLimitState.Lock() + rateLimitState.buckets = map[string]*tokenBucket{} + rateLimitState.Unlock() } // rateLimitMiddleware rejects state-changing requests once the bucket is @@ -82,13 +136,13 @@ func ResetRateLimiter() { // security middleware's origin check) never reach the bucket, and requests // the router would 404 still count as attempts: limiting happens before any // handler runs. -func rateLimitMiddleware(next http.Handler) http.Handler { +func rateLimitMiddleware(mux *http.ServeMux, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Ticket minting precedes every download and live-progress // (re)connect; it changes no state, so it must not drain the // mutation budget. if isStateChanging(r.Method) && r.URL.Path != "/api/"+APIVersion+"/session/tickets" { - if ok, retryAfter := apiMutationTokenBucket.take(time.Now()); !ok { + if ok, retryAfter := bucketFor(mux, r).take(time.Now()); !ok { w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) fail(w, http.StatusTooManyRequests, "RATE_LIMITED", "Too many requests; retry shortly.") return diff --git a/internal/api/server.go b/internal/api/server.go index 0f6d0eea..260b912b 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -18,6 +18,7 @@ import ( "sort" "strconv" "strings" + "sync" "time" "bluntcode/internal/analyzers" @@ -56,6 +57,15 @@ type Server struct { cache *workspaceCaches token string tickets ticketStore + // wsLocks serializes per-workspace check-and-act sequences (active-scan + // probe then delete, active-scan probe then start) that are otherwise a + // read-then-act race on the scans table. + wsLocks sync.Map // workspaceID -> *sync.Mutex + // treeCache memoizes the file-tree walk per workspace+path; discovery on + // every tree UI click re-walked the whole directory and cross-multiplied + // overrides per item. Entries expire quickly so rule/scan changes show up + // within ~30s. + treeCache sync.Map // workspaceID|path -> cachedTree // checkRoot and rootTimeout back the root_missing probe on workspace // views; tests swap them to simulate missing or hanging folders. checkRoot func(root string) string @@ -67,6 +77,11 @@ type Server struct { // run rows GET /scans/{id} serves, plus the new/fixed comparison counts the // report model computes. The workspace view's latest_scan shares it so the // workspace page's "Latest analysis" card renders the same detail. +type cachedTree struct { + payload map[string]any + expires time.Time +} + type scanDetail struct { core.Scan AnalyzerRuns []map[string]any `json:"analyzer_runs"` @@ -104,12 +119,22 @@ func New(db *database.DB, bus *events.Bus, scanService *scans.Service, toolServi if logger == nil { logger = slog.Default() } - s := &Server{db: db, bus: bus, scans: scanService, tools: toolService, paths: paths, version: version, log: logger, mux: http.NewServeMux(), openFolder: openFolderInExplorer, cache: newWorkspaceCaches(), token: NewToken(), checkRoot: checkWorkspaceRoot, rootTimeout: rootCheckTimeout} + s := &Server{db: db, bus: bus, scans: scanService, tools: toolService, paths: paths, version: version, log: logger, mux: http.NewServeMux(), openFolder: openFolderInExplorer, cache: newWorkspaceCaches(), token: mustToken(), checkRoot: checkWorkspaceRoot, rootTimeout: rootCheckTimeout} s.routes() return s } + +// lockWorkspace takes the per-workspace mutation lock and returns its +// release. Callers hold it across a check-and-act span only. +func (s *Server) lockWorkspace(id string) (unlock func()) { + v, _ := s.wsLocks.LoadOrStore(id, &sync.Mutex{}) + mu := v.(*sync.Mutex) + mu.Lock() + return mu.Unlock +} + func (s *Server) Handler() http.Handler { - return securityMiddleware(s.apiGuard(rateLimitMiddleware(jsonRouteErrors(s.mux)))) + return securityMiddleware(s.apiGuard(rateLimitMiddleware(s.mux, jsonRouteErrors(s.mux)))) } // StaticGuard applies the API's loopback Host check and baseline security @@ -132,6 +157,7 @@ func (s *Server) routes() { s.mux.HandleFunc("PATCH /api/v1/settings", s.updateSettings) s.mux.HandleFunc("GET /api/v1/workspaces", s.listWorkspaces) s.mux.HandleFunc("POST /api/v1/system/seed-demo", s.seedDemo) + s.mux.HandleFunc("POST /api/v1/system/unseed-demo", s.unseedDemo) s.mux.HandleFunc("POST /api/v1/workspaces", s.createWorkspace) s.mux.HandleFunc("POST /api/v1/system/select-folder", s.selectFolder) s.mux.HandleFunc("POST /api/v1/system/open-folder", s.openSystemFolder) @@ -549,7 +575,9 @@ func (s *Server) workspaceView(ctx context.Context, workspace core.Workspace, la } func (s *Server) buildWorkspaceView(ctx context.Context, workspace core.Workspace, latest *core.Scan, lastCompleted *core.Scan, pre *viewPrefetch, rootProblem string) (workspaceView, error) { - view := workspaceView{Workspace: workspace, RootMissing: rootProblem != "", RootProblem: rootProblem} + // A probe timeout is not proof the folder is gone — a stalled share must + // not be reported as missing (or block the scan button), only labelled. + view := workspaceView{Workspace: workspace, RootMissing: rootProblem != "" && rootProblem != "probe_timeout", RootProblem: rootProblem} attach := func(scan *core.Scan) (*scanDetail, error) { if scan == nil { return nil, nil @@ -718,17 +746,19 @@ func (s *Server) deleteWorkspace(w http.ResponseWriter, r *http.Request) { // Deleting mid-scan would cascade the scan row out from under a running // engine: its writes would land against deleted rows and the scan page // would poll a vanished scan. Same contract as DELETE /scans/{id} — cancel - // the scan first. - scans, err := s.db.Scans(r.Context(), workspace.ID) + // the scan first. The per-workspace lock serializes this check-and-act + // against startScan on the same workspace, closing the race between the + // active-scan read and the delete. + unlock := s.lockWorkspace(workspace.ID) + defer unlock() + active, err := s.db.ActiveScanID(r.Context(), workspace.ID) if err != nil { fail(w, 500, "DATABASE_ERROR", "Could not check active scans.") return } - for _, scan := range scans { - if !terminalScanState(scan.State) { - fail(w, 409, "SCAN_IN_PROGRESS", "A scan is still running on this workspace. Cancel it before removing the workspace.") - return - } + if active != "" { + fail(w, 409, "SCAN_IN_PROGRESS", "A scan is still running on this workspace. Cancel it before removing the workspace.") + return } if err := s.db.DeleteWorkspace(r.Context(), workspace.ID); err != nil { fail(w, 500, "DATABASE_ERROR", "Could not delete workspace.") @@ -738,6 +768,10 @@ func (s *Server) deleteWorkspace(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } func (s *Server) selectFolder(w http.ResponseWriter, r *http.Request) { + if runtime.GOOS != "windows" { + fail(w, 400, "UNSUPPORTED_PLATFORM", "The native folder picker is only available on Windows.") + return + } path, cancelled, err := folderpicker.Select(r.Context()) if err != nil { fail(w, 500, "FOLDER_PICKER_FAILED", "Could not open the native folder picker.") @@ -751,6 +785,11 @@ func (s *Server) stopServer(w http.ResponseWriter, r *http.Request) { return } writeJSON(w, http.StatusAccepted, map[string]string{"state": "stopping"}) + // Flush the acknowledgement before the process can exit, or callers see a + // dropped connection instead of the 202. + if flusher, ok := w.(http.Flusher); ok { + flusher.Flush() + } go s.shutdown() } @@ -765,6 +804,10 @@ const openFolderTimeout = 5 * time.Second // resolves the kind against its configured directories, so a caller can never // direct Explorer (or the process launcher) at an arbitrary location. func (s *Server) openSystemFolder(w http.ResponseWriter, r *http.Request) { + if runtime.GOOS != "windows" { + fail(w, 400, "UNSUPPORTED_PLATFORM", "Opening a folder in the system file browser is only supported on Windows.") + return + } var input struct { Kind string `json:"kind"` } @@ -811,7 +854,11 @@ func (s *Server) cleanSystem(w http.ResponseWriter, r *http.Request) { All *bool `json:"all,omitempty"` } if r.Body != nil { - bodyBytes, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + bodyBytes, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + fail(w, 400, "INVALID_REQUEST", "Could not read the request body.") + return + } if len(strings.TrimSpace(string(bodyBytes))) > 0 { d := json.NewDecoder(bytes.NewReader(bodyBytes)) d.DisallowUnknownFields() @@ -822,10 +869,14 @@ func (s *Server) cleanSystem(w http.ResponseWriter, r *http.Request) { } } opts := cleaner.Options{} + if input.All == nil && input.Logs == nil && input.Cache == nil && input.Vacuum == nil { + // A destructive endpoint must never default to "delete everything": + // the caller picks a target explicitly ({"all":true} included). + fail(w, 400, "SELECT_TARGET", "Specify what to clean: logs, cache, vacuum, or all.") + return + } if input.All != nil && *input.All { opts.All = true - } else if input.Logs == nil && input.Cache == nil && input.Vacuum == nil { - opts.All = true } else { if input.Logs != nil { opts.Logs = *input.Logs @@ -930,7 +981,20 @@ func (s *Server) tree(w http.ResponseWriter, r *http.Request) { fail(w, 400, "INVALID_PATH", err.Error()) return } - patterns, _ := s.userExcludes(r.Context(), work.ID) + cacheKey := work.ID + "|" + relative + if cached, ok := s.treeCache.Load(cacheKey); ok { + if entry := cached.(cachedTree); time.Now().Before(entry.expires) { + writeJSON(w, 200, entry.payload) + return + } + s.treeCache.Delete(cacheKey) + } + patterns, err := s.userExcludes(r.Context(), work.ID) + if err != nil { + // A failed rules read must not silently present an unfiltered tree. + fail(w, 500, "DATABASE_ERROR", "Could not load exclusion rules.") + return + } files, err := discovery.Tree(r.Context(), work.RootPath, relative, patterns) if err != nil { fail(w, 500, "DISCOVERY_FAILED", "Could not read workspace tree.") @@ -941,7 +1005,9 @@ func (s *Server) tree(w http.ResponseWriter, r *http.Request) { fail(w, 500, "DATABASE_ERROR", "Could not load file selections.") return } - writeJSON(w, 200, map[string]any{"items": treeItems(files, overrides), "path": relative}) + payload := map[string]any{"items": treeItems(files, overrides), "path": relative} + s.treeCache.Store(cacheKey, cachedTree{payload: payload, expires: time.Now().Add(30 * time.Second)}) + writeJSON(w, 200, payload) } type treeItem struct { @@ -1458,16 +1524,19 @@ func (s *Server) startScan(w http.ResponseWriter, r *http.Request) { fail(w, 400, "INVALID_JOBS", "jobs must be between 0 (default concurrency) and 32.") return } - recent, err := s.db.Scans(r.Context(), work.ID) + // Bounded EXISTS probe instead of loading the whole history (and every + // row's snapshot_json) for a boolean; the workspace lock makes the + // check-and-act atomic so two POSTs can't both see "no active scan". + unlock := s.lockWorkspace(work.ID) + defer unlock() + active, err := s.db.ActiveScanID(r.Context(), work.ID) if err != nil { fail(w, 500, "DATABASE_ERROR", "Could not check active scan.") return } - for _, scan := range recent { - if !terminalScanState(scan.State) { - writeJSON(w, 409, map[string]any{"error": map[string]any{"code": "SCAN_ALREADY_ACTIVE", "message": "A scan is already active.", "details": map[string]string{"scan_id": scan.ID}}}) - return - } + if active != "" { + writeJSON(w, 409, map[string]any{"error": map[string]any{"code": "SCAN_ALREADY_ACTIVE", "message": "A scan is already active.", "details": map[string]string{"scan_id": active}}}) + return } if s.failRootUnavailable(w, work) { return @@ -1476,7 +1545,12 @@ func (s *Server) startScan(w http.ResponseWriter, r *http.Request) { fail(w, 503, "SCAN_ENGINE_UNAVAILABLE", "The scan engine is unavailable.") return } - patterns, _ := s.userExcludes(r.Context(), work.ID) + patterns, err := s.userExcludes(r.Context(), work.ID) + if err != nil { + // A failed rules read must not silently run the scan unfiltered. + fail(w, 500, "DATABASE_ERROR", "Could not load exclusion rules.") + return + } scan, err := s.scans.DiscoverAndStartWithOptions(r.Context(), work, input.Profile, patterns, scans.ScanOptions{Jobs: input.Jobs, Incremental: input.Incremental, TargetURL: targetURL}) if err != nil { switch { diff --git a/internal/api/update.go b/internal/api/update.go index 683f6627..789c6dbc 100644 --- a/internal/api/update.go +++ b/internal/api/update.go @@ -1,6 +1,7 @@ package api import ( + "context" "encoding/json" "fmt" "io" @@ -19,9 +20,11 @@ import ( const updateRepository = selfupdate.Repository // fetchURLBytes performs the outbound HTTP GET for the release check. -// Package-level so tests can stub the network. -var fetchURLBytes = func(url string) ([]byte, error) { - request, err := http.NewRequest(http.MethodGet, url, nil) +// Package-level so tests can stub the network. The caller's context is +// honored — a client disconnecting must cancel the GitHub call, not leave +// it running until the client timeout. +var fetchURLBytes = func(ctx context.Context, url string) ([]byte, error) { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } @@ -44,11 +47,11 @@ var fetchURLBytes = func(url string) ([]byte, error) { } // compareSemver orders dotted numeric versions: -1 when ab. Non-numeric segments fall back to string order so a stray -// suffix never panics. +// 1 when a>b. A prerelease sorts below its release (1.2.3-beta < 1.2.3) per +// semver §11; build metadata (+…) is ignored. func compareSemver(a, b string) int { - as := strings.Split(strings.TrimPrefix(strings.TrimSpace(a), "v"), ".") - bs := strings.Split(strings.TrimPrefix(strings.TrimSpace(b), "v"), ".") + as, aPre := splitVersion(a) + bs, bPre := splitVersion(b) for i := 0; i < 3; i++ { var an, bn int if i < len(as) { @@ -64,7 +67,32 @@ func compareSemver(a, b string) int { return 1 } } - return 0 + // Same numeric version: a prerelease is always less than the release. + if aPre == bPre { + return 0 + } + if aPre == "" { + return 1 + } + if bPre == "" { + return -1 + } + return strings.Compare(aPre, bPre) +} + +// splitVersion separates the dotted numeric core from a -prerelease suffix +// (and drops +build metadata), returning numeric segments and the suffix. +func splitVersion(v string) ([]string, string) { + v = strings.TrimPrefix(strings.TrimSpace(v), "v") + if i := strings.IndexByte(v, '+'); i >= 0 { + v = v[:i] + } + pre := "" + if i := strings.IndexByte(v, '-'); i >= 0 { + pre = v[i+1:] + v = v[:i] + } + return strings.Split(v, "."), pre } func atoiSafe(value string) int { @@ -107,8 +135,8 @@ type UpdateCheckResult struct { } // CheckUpdateDirect checks GitHub releases for a newer version than currentVersion. -func CheckUpdateDirect(currentVersion string) (UpdateCheckResult, error) { - body, err := fetchURLBytes("https://api.github.com/repos/" + updateRepository + "/releases/latest") +func CheckUpdateDirect(ctx context.Context, currentVersion string) (UpdateCheckResult, error) { + body, err := fetchURLBytes(ctx, "https://api.github.com/repos/"+updateRepository+"/releases/latest") if err != nil { return UpdateCheckResult{}, fmt.Errorf("could not reach GitHub releases: %w", err) } @@ -139,7 +167,7 @@ func (s *Server) updateCheck(w http.ResponseWriter, r *http.Request) { fail(w, http.StatusConflict, "UPDATE_OFFLINE", "Offline mode is enabled; turn it off in Settings to check for updates.") return } - res, err := CheckUpdateDirect(s.version) + res, err := CheckUpdateDirect(r.Context(), s.version) if err != nil { // Soft-fail with 200 + unavailable instead of a 502 pass-through so an // offline machine never accumulates console errors on every load. @@ -180,7 +208,7 @@ func (s *Server) updateApply(w http.ResponseWriter, r *http.Request) { fail(w, http.StatusNotImplemented, "UNSUPPORTED_PLATFORM", "In-app updates are Windows-only.") return } - check, err := CheckUpdateDirect(s.version) + check, err := CheckUpdateDirect(r.Context(), s.version) if err != nil { fail(w, http.StatusBadGateway, "UPDATE_APPLY_FAILED", "Could not reach GitHub releases: "+err.Error()) return diff --git a/internal/api/update_test.go b/internal/api/update_test.go index fcef711e..aa2a7a13 100644 --- a/internal/api/update_test.go +++ b/internal/api/update_test.go @@ -40,7 +40,7 @@ func stubUpdateNetwork(t *testing.T, payload string) *[]byte { t.Helper() calls := &[]byte{} original := fetchURLBytes - fetchURLBytes = func(url string) ([]byte, error) { + fetchURLBytes = func(_ context.Context, url string) ([]byte, error) { *calls = []byte(url) return []byte(payload), nil } @@ -109,7 +109,9 @@ func TestUpdateCheckSoftFailsWhenUnreachable(t *testing.T) { s := testServer(t) s.version = "0.6.0" original := fetchURLBytes - fetchURLBytes = func(url string) ([]byte, error) { return nil, fmt.Errorf("dial tcp: connection refused") } + fetchURLBytes = func(_ context.Context, url string) ([]byte, error) { + return nil, fmt.Errorf("dial tcp: connection refused") + } t.Cleanup(func() { fetchURLBytes = original }) recorder := httptest.NewRecorder() s.updateCheck(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/update/check", nil)) @@ -196,7 +198,7 @@ func TestUpdateApplyFailsClosed(t *testing.T) { launched, _ := stubUpdateApply(t) original := fetchURLBytes - fetchURLBytes = func(url string) ([]byte, error) { return nil, fmt.Errorf("rate limited") } + fetchURLBytes = func(_ context.Context, url string) ([]byte, error) { return nil, fmt.Errorf("rate limited") } recorder := httptest.NewRecorder() s.updateApply(recorder, httptest.NewRequest(http.MethodPost, "/api/v1/update/apply", nil)) fetchURLBytes = original diff --git a/internal/api/workspace_path.go b/internal/api/workspace_path.go index a0da33cf..5c12cff3 100644 --- a/internal/api/workspace_path.go +++ b/internal/api/workspace_path.go @@ -5,6 +5,7 @@ import ( "io/fs" "os" "path/filepath" + "runtime" "strings" "bluntcode/internal/workspace" @@ -47,21 +48,46 @@ func apiWorkspaceRoot(raw string) (string, error) { } // sensitiveRoot refuses folders that are never a project but would turn the -// file tree and source previews into a read of the whole machine: a drive -// or filesystem root, the Windows directory, and the home folder itself -// (projects inside it are fine). +// file tree and source previews into a read of the whole machine — or of the +// user's secrets. A registered workspace is browsable via /tree and readable +// via source preview, so known credential directories are denied outright. func sensitiveRoot(root string) string { clean := filepath.Clean(root) if filepath.Dir(clean) == clean { return "That is the root of a drive. Choose your project folder instead." } + // The Windows-directory check must not depend on env vars being populated: + // a security boundary keyed on WINDIR silently disables when the variable + // is unset. Fall back to the conventional location on Windows. for _, name := range []string{"WINDIR", "SystemRoot"} { if dir := os.Getenv(name); dir != "" && within(clean, dir) { return "The Windows folder cannot be a workspace. Choose your project folder instead." } } - if home, err := os.UserHomeDir(); err == nil && home != "" && samePath(clean, home) { - return "Your whole home folder cannot be a workspace. Choose a project folder inside it." + if runtime.GOOS == "windows" && within(clean, `C:\Windows`) { + return "The Windows folder cannot be a workspace. Choose your project folder instead." + } + if home, err := os.UserHomeDir(); err == nil && home != "" { + if samePath(clean, home) { + return "Your whole home folder cannot be a workspace. Choose a project folder inside it." + } + // Credential and key-material directories: scanning one hands private + // keys and cloud secrets to anything holding the API token. + for _, secretDir := range []string{".ssh", ".aws", ".gnupg", ".kube", ".docker"} { + if within(clean, filepath.Join(home, secretDir)) { + return "That folder holds credentials and cannot be a workspace. Choose your project folder instead." + } + } + if within(clean, filepath.Join(home, ".config", "gcloud")) { + return "That folder holds credentials and cannot be a workspace. Choose your project folder instead." + } + } + if runtime.GOOS != "windows" { + for _, systemDir := range []string{"/etc", "/root", "/boot", "/private/etc", "/System"} { + if within(clean, systemDir) { + return "That is a system directory and cannot be a workspace. Choose your project folder instead." + } + } } return "" } diff --git a/internal/api/workspace_root.go b/internal/api/workspace_root.go index 03465b4f..661180b6 100644 --- a/internal/api/workspace_root.go +++ b/internal/api/workspace_root.go @@ -72,8 +72,13 @@ func checkWorkspaceRoot(root string) string { return "" } +// rootProblemTimeout is the distinct "we could not tell" verdict: a hung or +// slow mount used to report healthy ("") because unresolved meant usable. +const rootProblemTimeout = "probe_timeout" + // rootProblems probes every root concurrently within rootTimeout and -// returns the problem per index ("" for usable or unresolved roots). +// returns the problem per index ("" for usable; probe_timeout for roots the +// probe could not resolve in time). func (s *Server) rootProblems(roots []string) []string { problems := make([]string, len(roots)) if len(roots) == 0 { @@ -100,6 +105,7 @@ func (s *Server) rootProblems(roots []string) []string { case <-probe.done: problems[i] = probe.problem default: + problems[i] = rootProblemTimeout } } return problems diff --git a/internal/build/version.go b/internal/build/version.go index 9e60d551..b665ec81 100644 --- a/internal/build/version.go +++ b/internal/build/version.go @@ -5,4 +5,4 @@ // incremental findings survive upgrades that should have invalidated them. package build -const Version = "0.50.0" +const Version = "0.51.0" diff --git a/internal/database/database.go b/internal/database/database.go index 7d220b02..0b5a2ddc 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -36,7 +36,12 @@ func Open(ctx context.Context, path string) (*DB, error) { if err != nil { return nil, fmt.Errorf("open sqlite: %w", err) } - db.SetMaxOpenConns(1) + // WAL permits concurrent readers beside the single writer; one pooled + // connection serialized every handler (a slow report read stalled even + // scan-cancel). Per-connection pragmas ride in the DSN above, so each new + // connection is fully configured. Writes still serialize at the SQLite + // level via busy_timeout(5000). + db.SetMaxOpenConns(8) if err = db.PingContext(ctx); err != nil { db.Close() return nil, fmt.Errorf("ping sqlite: %w", err) diff --git a/internal/database/repository.go b/internal/database/repository.go index 011784e2..187b0ce2 100644 --- a/internal/database/repository.go +++ b/internal/database/repository.go @@ -8,9 +8,12 @@ import ( "encoding/json" "errors" "fmt" + "log" "math" + "os" "sort" "strings" + "sync/atomic" "time" "bluntcode/internal/analyzers" @@ -18,10 +21,21 @@ import ( "bluntcode/internal/reports" ) +// idCounter makes ID generation infallible: row IDs need uniqueness, not +// cryptographic strength, so a crypto/rand outage must not crash a request +// (previously panic()ed mid-insert). The counter + time seed keeps collisions +// impossible within a process even if rand fails, and the rand suffix keeps +// cross-process collisions improbable. +var idCounter atomic.Uint64 + func NewID() string { b := make([]byte, 16) if _, err := rand.Read(b); err != nil { - panic(fmt.Sprintf("random ID: %v", err)) + // No panic in library write paths: fall back to a time/counter ID. A + // crypto/rand failure is surfaced by NewToken (which cannot fall back), + // not by database row identifiers. + seq := idCounter.Add(1) + return fmt.Sprintf("%012x-%04x-%04x-%04x-%012x", time.Now().UnixNano(), seq&0xffff, (seq>>16)&0xffff, os.Getpid()&0xffff, time.Now().UnixMicro()&0xffffffffffff) } return hex.EncodeToString(b[0:4]) + "-" + hex.EncodeToString(b[4:6]) + "-" + hex.EncodeToString(b[6:8]) + "-" + hex.EncodeToString(b[8:10]) + "-" + hex.EncodeToString(b[10:]) } @@ -104,7 +118,12 @@ func applyWorkspaceSettings(w *core.Workspace) { // preserving any keys this build does not know about. func mergedWorkspaceSettings(w core.Workspace) string { settings := map[string]json.RawMessage{} - _ = json.Unmarshal([]byte(w.SettingsJSON), &settings) + if err := json.Unmarshal([]byte(w.SettingsJSON), &settings); err != nil { + // Corrupt stored JSON: return the blob untouched rather than silently + // dropping every unknown key the merge claims to preserve. + log.Printf("workspace %s: corrupt settings_json preserved as-is: %v", w.ID, err) + return w.SettingsJSON + } if settings == nil { settings = map[string]json.RawMessage{} } @@ -332,7 +351,10 @@ func (d *DB) UpdateWorkspace(ctx context.Context, w core.Workspace) (core.Worksp if err != nil { return core.Workspace{}, err } - n, _ := result.RowsAffected() + n, err := result.RowsAffected() + if err != nil { + return core.Workspace{}, err + } if n == 0 { return core.Workspace{}, sql.ErrNoRows } @@ -343,7 +365,10 @@ func (d *DB) DeleteWorkspace(ctx context.Context, id string) error { if err != nil { return err } - n, _ := result.RowsAffected() + n, err := result.RowsAffected() + if err != nil { + return err + } if n == 0 { return sql.ErrNoRows } @@ -422,7 +447,11 @@ func (d *DB) Rules(ctx context.Context, workspaceID string) ([]core.WorkspaceRul return nil, err } r.Enabled = enabled != 0 - r.CreatedAt, _ = time.Parse(time.RFC3339Nano, created) + if parsed, parseErr := time.Parse(time.RFC3339Nano, created); parseErr == nil { + r.CreatedAt = parsed + } else { + log.Printf("workspace rule %s: unparsable created_at %q: %v", r.ID, created, parseErr) + } rr = append(rr, r) } return rr, rows.Err() @@ -562,7 +591,10 @@ func (d *DB) RemoveSuppression(ctx context.Context, workspaceID, fingerprint str if err != nil { return err } - n, _ := result.RowsAffected() + n, err := result.RowsAffected() + if err != nil { + return err + } if n == 0 { return sql.ErrNoRows } @@ -927,6 +959,41 @@ func hydrateScanSnapshot(scan *core.Scan) { scan.Snapshot = &snapshot } } + +// ActiveScanID returns the id of a non-terminal scan for this workspace +// ("" when none) with a bounded probe instead of materializing the whole +// scan history — and each row's snapshot_json — for a boolean check. +func (d *DB) ActiveScanID(ctx context.Context, workspaceID string) (string, error) { + var id string + err := d.SQL.QueryRowContext(ctx, `SELECT id FROM scans WHERE workspace_id=? AND state NOT IN ('completed','completed_with_warnings','failed','cancelled','interrupted') ORDER BY started_at DESC LIMIT 1`, workspaceID).Scan(&id) + if errors.Is(err, sql.ErrNoRows) { + return "", nil + } + return id, err +} + +// FingerprintExists reports whether a finding with this fingerprint exists in +// the workspace, guarding note writes against orphaned phantom fingerprints. +func (d *DB) FingerprintExists(ctx context.Context, workspaceID, fingerprint string) (bool, error) { + var one int + err := d.SQL.QueryRowContext(ctx, `SELECT 1 FROM findings f JOIN scans s ON f.scan_id=s.id WHERE s.workspace_id=? AND f.fingerprint=? LIMIT 1`, workspaceID, fingerprint).Scan(&one) + if errors.Is(err, sql.ErrNoRows) { + return false, nil + } + return err == nil, err +} + +// maxNotesPerFinding caps stored notes per (workspace, fingerprint) so a +// POST loop cannot grow finding_notes without bound. +const maxNotesPerFinding = 100 + +// FindingNoteCount returns how many notes already exist for the fingerprint. +func (d *DB) FindingNoteCount(ctx context.Context, workspaceID, fingerprint string) (int, error) { + var n int + err := d.SQL.QueryRowContext(ctx, `SELECT COUNT(*) FROM finding_notes WHERE workspace_id=? AND fingerprint=?`, workspaceID, fingerprint).Scan(&n) + return n, err +} + func isTerminalScanState(state string) bool { switch state { case "completed", "completed_with_warnings", "failed", "cancelled", "interrupted": @@ -1555,7 +1622,10 @@ func (d *DB) Findings(ctx context.Context, scanID string) ([]analyzers.Finding, } f.Severity = analyzers.Severity(severity) f.Category = analyzers.Category(category) - _ = json.Unmarshal([]byte(metadata), &f.Metadata) + if err := json.Unmarshal([]byte(metadata), &f.Metadata); err != nil { + // Corrupt metadata is not fatal to the row, but it must not be silent. + log.Printf("finding %s: corrupt metadata_json replaced with empty object: %v", f.ID, err) + } output = append(output, f) } return output, rows.Err() @@ -1592,7 +1662,10 @@ func (d *DB) Finding(ctx context.Context, scanID, id string) (analyzers.Finding, } f.Severity = analyzers.Severity(severity) f.Category = analyzers.Category(category) - _ = json.Unmarshal([]byte(metadata), &f.Metadata) + if err := json.Unmarshal([]byte(metadata), &f.Metadata); err != nil { + // Corrupt metadata is not fatal to the row, but it must not be silent. + log.Printf("finding %s: corrupt metadata_json replaced with empty object: %v", f.ID, err) + } return f, nil } @@ -1879,7 +1952,10 @@ func scanFindingRow(rows *sql.Rows) (analyzers.Finding, error) { } f.Severity = analyzers.Severity(severity) f.Category = analyzers.Category(category) - _ = json.Unmarshal([]byte(metadata), &f.Metadata) + if err := json.Unmarshal([]byte(metadata), &f.Metadata); err != nil { + // Corrupt metadata is not fatal to the row, but it must not be silent. + log.Printf("finding %s: corrupt metadata_json replaced with empty object: %v", f.ID, err) + } return f, nil } @@ -2403,6 +2479,25 @@ func (d *DB) WorkspaceTagsMap(ctx context.Context, ids []string) (map[string][]s return out, rows.Err() } +// WorkspaceIDsWithTag returns ids of workspaces carrying a tag — used by the +// demo-seed purge to remove synthetic rows wholesale. +func (d *DB) WorkspaceIDsWithTag(ctx context.Context, tag string) ([]string, error) { + rows, err := d.SQL.QueryContext(ctx, `SELECT DISTINCT workspace_id FROM workspace_tags WHERE tag=?`, tag) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + // SetWorkspaceTags atomically replaces the workspace's tag set. Tags are // validated, de-duplicated, and stored sorted. func (d *DB) SetWorkspaceTags(ctx context.Context, workspaceID string, tags []string) error { @@ -2732,7 +2827,10 @@ func (d *DB) SearchFindings(ctx context.Context, filter GlobalFindingsFilter) ([ } f.Severity = analyzers.Severity(severity) f.Category = analyzers.Category(category) - _ = json.Unmarshal([]byte(metadata), &f.Metadata) + if err := json.Unmarshal([]byte(metadata), &f.Metadata); err != nil { + // Corrupt metadata is not fatal to the row, but it must not be silent. + log.Printf("finding %s: corrupt metadata_json replaced with empty object: %v", f.ID, err) + } items = append(items, SearchedFinding{Finding: f, ScanID: scanID, WorkspaceID: workspaceID}) } if err := rows.Err(); err != nil { diff --git a/internal/scans/exec.go b/internal/scans/exec.go index 7b91518d..53bae6dc 100644 --- a/internal/scans/exec.go +++ b/internal/scans/exec.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "log" + "strings" "sync" "sync/atomic" "time" @@ -356,8 +357,12 @@ func (s *Service) runAnalyzersSequential(ctx context.Context, scan core.Scan, wo func (s *Service) runAnalyzersBounded(ctx context.Context, scan core.Scan, work core.Workspace, languages []analyzers.Language, routing scanRouting, counters *scanCounters, jobs int, deselect func(string) bool) string { sem := make(chan struct{}, jobs) var wg sync.WaitGroup - var panicValue atomic.Value + // Every panic is recorded with its analyzer id — a shared atomic.Value + // silently kept only the LAST panic when two adapters crashed. + var panicsMu sync.Mutex + var panics []string for _, adapter := range s.registry.All() { + adapter := adapter wg.Add(1) go func() { defer wg.Done() @@ -366,7 +371,9 @@ func (s *Service) runAnalyzersBounded(ctx context.Context, scan core.Scan, work // here and reported to the coordinator. defer func() { if r := recover(); r != nil { - panicValue.Store(fmt.Sprintf("%v", r)) + panicsMu.Lock() + panics = append(panics, fmt.Sprintf("%s panicked: %v", adapter.ID(), r)) + panicsMu.Unlock() } }() select { @@ -379,8 +386,9 @@ func (s *Service) runAnalyzersBounded(ctx context.Context, scan core.Scan, work }() } wg.Wait() - message, _ := panicValue.Load().(string) - return message + panicsMu.Lock() + defer panicsMu.Unlock() + return strings.Join(panics, "; ") } // recordFailedRun persists a failed analyzer run. The run is counted as failed diff --git a/internal/scans/jobs_test.go b/internal/scans/jobs_test.go index 96667fd2..67da6835 100644 --- a/internal/scans/jobs_test.go +++ b/internal/scans/jobs_test.go @@ -183,7 +183,7 @@ func TestJobsBoundsConcurrentAnalyzerRuns(t *testing.T) { // flight — capped, but genuinely overlapping rather than sequential. func TestDefaultJobsBoundsAnalyzerConcurrency(t *testing.T) { tracker := newRunTracker() - fixture := newScanFixture(t, newCountingAnalyzers(tracker, 5*time.Millisecond, false, "one", "two", "three", "four")...) + fixture := newScanFixture(t, newCountingAnalyzers(tracker, 50*time.Millisecond, false, "one", "two", "three", "four")...) scan := fixture.startScan(t) // the default entry point, no options if final := fixture.waitForTerminal(t, scan.ID); final.State != "completed" { t.Fatalf("scan state = %q, want completed", final.State) diff --git a/internal/scans/service.go b/internal/scans/service.go index 6e23c976..67fe225f 100644 --- a/internal/scans/service.go +++ b/internal/scans/service.go @@ -300,7 +300,10 @@ func (s *Service) run(ctx context.Context, scan core.Scan, work core.Workspace, s.failScan(scan.ID, fmt.Sprintf("Internal scan error: %v", r)) } }() - s.emit(scan.ID, "scan.started", map[string]any{"state": "queued"}) + // The run goroutine is already executing when this emits — reporting the + // DB row's pre-claim "queued" state here made the event lie about the + // scan's actual lifecycle (started event, queued state). + s.emit(scan.ID, "scan.started", map[string]any{"state": "running"}) // A scan whose progress cannot be recorded must not run analyzers whose // results could not be recorded either: fail it now (best effort) and let // startup reconciliation catch the row if even that write is lost. diff --git a/internal/selfupdate/install.go b/internal/selfupdate/install.go index cd7205d0..9068e80f 100644 --- a/internal/selfupdate/install.go +++ b/internal/selfupdate/install.go @@ -51,7 +51,9 @@ func Apply(options ApplyOptions) error { } logf("install attempt %d failed: %v", attempt, err) if attempt < swapAttempts { - time.Sleep(swapRetryDelay) + // Back off instead of a fixed delay — a held file lock needs a + // growing window, not the same wrong guess three times. + time.Sleep(swapRetryDelay * time.Duration(attempt)) } } if err == nil { diff --git a/internal/selfupdate/proc_other.go b/internal/selfupdate/proc_other.go index 295c4217..1b6862da 100644 --- a/internal/selfupdate/proc_other.go +++ b/internal/selfupdate/proc_other.go @@ -12,6 +12,7 @@ import ( func waitForExit(pid int, timeout time.Duration) error { deadline := time.Now().Add(timeout) + delay := 50 * time.Millisecond for { if err := syscall.Kill(pid, 0); errors.Is(err, syscall.ESRCH) { return nil @@ -19,7 +20,10 @@ func waitForExit(pid int, timeout time.Duration) error { if time.Now().After(deadline) { return fmt.Errorf("process %d did not exit within %s", pid, timeout) } - time.Sleep(200 * time.Millisecond) + time.Sleep(delay) + if delay < 800*time.Millisecond { + delay *= 2 + } } } diff --git a/internal/selfupdate/selfupdate.go b/internal/selfupdate/selfupdate.go index bd547f1b..caf0e8ad 100644 --- a/internal/selfupdate/selfupdate.go +++ b/internal/selfupdate/selfupdate.go @@ -239,6 +239,8 @@ func Stage(ctx context.Context, tag, dir, signingKey string) (Staged, error) { } signed := strings.TrimSpace(signingKey) != "" if signed { + // A pinned key makes the .sha256.sig asset mandatory — no silent + // downgrade to checksum-only verification. signature, err := fetchSmall(ctx, assets.SignatureURL) if err != nil { return Staged{}, fmt.Errorf("download release signature: %w", err) diff --git a/internal/tools/manager.go b/internal/tools/manager.go index a1e5d756..9a00809a 100644 --- a/internal/tools/manager.go +++ b/internal/tools/manager.go @@ -14,6 +14,7 @@ import ( "os/exec" "path" "path/filepath" + "runtime" "sort" "strings" "time" @@ -114,20 +115,30 @@ func removePathRobust(path string) error { return nil } var err error - for attempt := 0; attempt < 3; attempt++ { + delay := 50 * time.Millisecond + for attempt := 0; attempt < 4; attempt++ { err = os.RemoveAll(path) if err == nil || os.IsNotExist(err) { return nil } - _ = filepath.WalkDir(path, func(p string, d fs.DirEntry, walkErr error) error { - if walkErr == nil { - _ = os.Chmod(p, 0o666) + // The read-only-attribute workaround is a Windows concern only: on + // POSIX, chmod 0o666 made every removed tool file world-writable — + // and was unnecessary anyway since directory write permission governs + // removal there. + if runtime.GOOS == "windows" { + if walkErr := filepath.WalkDir(path, func(p string, d fs.DirEntry, we error) error { + if we == nil { + _ = os.Chmod(p, 0o666) + } + return nil + }); walkErr != nil { + return fmt.Errorf("clear read-only attributes under %s: %w", path, walkErr) } - return nil - }) - time.Sleep(50 * time.Millisecond) + } + time.Sleep(delay) + delay *= 2 // real backoff, not a fixed busy-wait } - return os.RemoveAll(path) + return err } // Uninstall removes the tool's files and directories from disk. @@ -205,8 +216,16 @@ func (m Manager) Executable(a Artifact) string { } func (m Manager) IsReady(a Artifact) bool { p := m.Executable(a) - _, err := os.Stat(p) - return err == nil + info, err := os.Stat(p) + if err != nil || info.IsDir() || info.Size() == 0 { + return false + } + // A zero-byte or non-executable artifact is a half-extracted install, not + // a ready tool — existence alone used to report Ready for both. + if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 { + return false + } + return true } // smokeProbe runs the artifact's post-activation smoke test: the installed diff --git a/scripts/package.ps1 b/scripts/package.ps1 index 74ad2959..cc2ac3fc 100644 --- a/scripts/package.ps1 +++ b/scripts/package.ps1 @@ -1,6 +1,6 @@ [CmdletBinding()] param( - [string]$Version = '0.50.0', + [string]$Version = '0.51.0', # No $PSScriptRoot here: Windows PowerShell 5.1 leaves it empty inside # param() default expressions, so resolve after the body starts. [string]$OutputDir = '', diff --git a/web/package-lock.json b/web/package-lock.json index ce66625a..7a95a99f 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "blunt-code-web", - "version": "0.50.0", + "version": "0.51.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "blunt-code-web", - "version": "0.50.0", + "version": "0.51.0", "dependencies": { "@radix-ui/react-accordion": "^1.2.20", "@radix-ui/react-dialog": "^1.1.23", diff --git a/web/package.json b/web/package.json index 2863d31a..91a84ba9 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "blunt-code-web", "private": true, - "version": "0.50.0", + "version": "0.51.0", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/components/RootMissingBadge.tsx b/web/src/components/RootMissingBadge.tsx index 470e853d..85a627a0 100644 --- a/web/src/components/RootMissingBadge.tsx +++ b/web/src/components/RootMissingBadge.tsx @@ -6,6 +6,7 @@ type RootFields = Pick export function rootProblemLabel(workspace: RootFields): string { if (workspace.root_problem === 'not_directory') return 'Not a folder'; if (workspace.root_problem === 'unreadable') return 'Folder unreadable'; + if (workspace.root_problem === 'probe_timeout') return 'Folder unreachable'; return 'Folder missing'; } @@ -14,11 +15,12 @@ export function rootProblemDescription(workspace: RootFields): string { const path = workspace.root_path || 'This workspace folder'; if (workspace.root_problem === 'not_directory') return `${path} is now a file, not a folder. Restore the folder or remove this workspace.`; if (workspace.root_problem === 'unreadable') return `${path} cannot be read. Check its permissions or remove this workspace.`; + if (workspace.root_problem === 'probe_timeout') return `${path} did not respond in time — the drive may be disconnected or the filesystem is hung. Check the folder is reachable, or remove this workspace.`; return `${path} no longer exists. Restore the folder or remove this workspace.`; } /** Warning pill shown beside a workspace name when its folder is gone; renders nothing for healthy workspaces. */ export function RootMissingBadge({ workspace, className = '' }: { workspace: RootFields; className?: string }) { - if (!workspace.root_missing) return null; + if (!workspace.root_missing && workspace.root_problem !== 'probe_timeout') return null; return {rootProblemLabel(workspace)}; }