diff --git a/examples/sample-output/nodegoat/findings.jsonl b/examples/sample-output/nodegoat/findings.jsonl index 98299ac..0622981 100644 --- a/examples/sample-output/nodegoat/findings.jsonl +++ b/examples/sample-output/nodegoat/findings.jsonl @@ -1,18 +1,18 @@ -{"closed_at": null, "code_region_hash": null, "construct": "Session middleware with default cookie flags over plaintext HTTP, authentication that reuses the pre-login session identifier, and an error handler rendering the raw exception into HTML.", "current_ref": "F12", "cvss_score": 4.2, "cvss_vector": "AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N", "cwe": "CWE-1004", "description": "The session is served over plain HTTP with default cookie options (no `httpOnly`, no `secure`, default `connect.sid` name) and `saveUninitialized: true`. Login sets `req.session.userId` without `regenerate()`, so a pre-login session ID fixed by an attacker becomes authenticated. The global error handler renders the error object directly into an unescaped template, exposing internal messages (for example Mongo `$where` evaluation errors containing the injected payload). The login failure path also logs the raw `userName`, allowing CRLF log forging. These amplify F6 (cookie theft via XSS) rather than being independently exploitable.", "fingerprint": "081292ff2cb1345d30185ab4534f2b998d7f6ac6986c51a3108b45b88dccf1f0", "first_seen_at": "2026-11-14T09:47:38.608601+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.608601+00:00", "location_file": "server.js:78-102, app/routes/session.js:116, app/routes/error.js:10-12", "location_line": null, "owasp": "A05:2021", "project": "NodeGoat", "recommendation": "Set `cookie: { httpOnly: true, secure: true, sameSite: \"lax\", maxAge }`, use a non-default `name`, wrap the login success path in `req.session.regenerate()`, serve over HTTPS, and render a generic error message while logging details server-side with user input sanitized of CR/LF.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Low", "skill_id": "sast", "status": "open", "title": "Session cookie lacks `httpOnly`/`secure`; no regeneration on login; error page echoes raw error", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Regular expression with a repeated group that itself contains an unbounded repeat, applied to a request body field with no length limit.", "current_ref": "F11", "cvss_score": 6.5, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "cwe": "CWE-1333", "description": "The pattern `/([0-9]+)+\\#/` has a nested unbounded quantifier. A `bankRouting` value of thirty or more digits followed by a non-`#` character causes exponential backtracking in V8's regex engine and blocks the single Node event loop, denying service to all users.", "fingerprint": "f8421917b63f010bd94c0e4ee14024a6a16ea1eb1c1bde7b872f67fa7746afb0", "first_seen_at": "2026-11-14T09:47:38.608483+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.608483+00:00", "location_file": "app/routes/profile.js:59-61", "location_line": null, "owasp": "unverified", "project": "NodeGoat", "recommendation": "Use `/^[0-9]{1,20}#$/` (anchored, bounded, no nesting) and cap input length before matching.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "ReDoS via nested quantifier on bank routing validator", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Session-cookie-authenticated form POST endpoints with the anti-forgery middleware commented out, leaving the token field in templates permanently empty.", "current_ref": "F10", "cvss_score": 6.5, "cvss_vector": "AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "cwe": "CWE-352", "description": "The `csurf` middleware is commented out, so `res.locals.csrftoken` is never set and every form's hidden `_csrf` field renders empty. POST `/profile`, `/contributions`, `/benefits`, and `/memos` accept cross-origin form submissions from a logged-in victim's browser, letting an attacker change their bank account number or (via F1) execute code as the victim's session.", "fingerprint": "ee5c8d6881f2a45c7be70b6c5d0bc8f4b2f27837eaa11f16092e115e6b5457af", "first_seen_at": "2026-11-14T09:47:38.608367+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.608367+00:00", "location_file": "server.js:104-113, app/views/profile.html:73", "location_line": null, "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Enable a CSRF middleware (`csurf` or a double-submit cookie implementation), set the token in `res.locals`, and set `SameSite=Lax` or `Strict` on the session cookie.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "CSRF protection disabled on all state-changing POST handlers", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Session-signing and encryption secrets as string literals in a committed config module, plus a database seed script that creates a privileged account with a fixed password.", "current_ref": "F9", "cvss_score": 9.1, "cvss_vector": "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "cwe": "CWE-798", "description": "The express-session signing secret and the AES key are literal strings in a public repository, and `production.js` overrides nothing. The seed script creates `admin / Admin_123`, `user1 / User1_123`, `user2 / User2_123`. Anyone who knows the project can log in as admin on a seeded deployment with no prior access. A private TLS key is also committed under `artifacts/cert/`.", "fingerprint": "3b92635c00768dfa1097e9d2b6a02522637cb2ef35e88c6802e8c0049490c91a", "first_seen_at": "2026-11-14T09:47:38.608201+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.608201+00:00", "location_file": "config/env/all.js:8-9, artifacts/db-reset.js:15-18", "location_line": null, "owasp": "A07:2021", "project": "NodeGoat", "recommendation": "Read `SESSION_SECRET` and `CRYPTO_KEY` from environment variables and fail startup if absent. Have the seed script generate a random admin password and print it once, or require it from the environment. Rotate and remove the committed certificate key.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "Hardcoded session secret, crypto key, and seeded admin credentials", "verdict": "Conditional"} -{"closed_at": null, "code_region_hash": null, "construct": "HTTP redirect whose target is taken unvalidated from a query-string parameter.", "current_ref": "F8", "cvss_score": 6.1, "cvss_vector": "AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "cwe": "CWE-601", "description": "The handler redirects to whatever the `url` query parameter contains. A phishing link such as `/learn?url=https://evil.example/login` carries the trusted origin and lands a logged-in victim on an attacker page.", "fingerprint": "058c90751123c5d3f25fc3af586f5b8f3e1019bab842a24c90efa4c0632d5275", "first_seen_at": "2026-11-14T09:47:38.607461+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.607461+00:00", "location_file": "app/routes/index.js:70-73", "location_line": null, "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Map a fixed key (`?topic=iras`) to a server-side allowlist of destination URLs, or validate that the parsed URL's host is in an explicit allowlist before redirecting.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "Open redirect on `/learn?url=`", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Credential stored as the raw submitted string and verified by plain string equality.", "current_ref": "F7", "cvss_score": 5.3, "cvss_vector": "AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:N/A:N", "cwe": "CWE-256", "description": "`addUser` persists the raw password, and `validateLogin` compares with `===`. `bcrypt-nodejs` is imported but unused. Combined with F3 (dump via `$where`) or F5 (full user docs to template), the plaintext passwords are directly retrievable by any authenticated user; this is the stated precondition for the AC:H rating.", "fingerprint": "3d750566288ecf5ba6e61740994bb6bd984830707f07b8d62aaee96e665fc5e6", "first_seen_at": "2026-11-14T09:47:38.607194+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.607194+00:00", "location_file": "app/data/user-dao.js:25, :61", "location_line": null, "owasp": "A02:2021", "project": "NodeGoat", "recommendation": "Hash with `bcrypt.hashSync(password, bcrypt.genSaltSync(12))` on create and verify with `bcrypt.compareSync(fromUser, fromDB)`. Prefer the maintained `bcrypt` or `argon2` package over `bcrypt-nodejs`.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "Passwords stored and compared in plaintext", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Template engine configured with output escaping globally disabled, with user-sourced profile fields and request values rendered directly into HTML body and attribute contexts.", "current_ref": "F6", "cvss_score": 5.4, "cvss_vector": "AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "cwe": "CWE-79", "description": "Swig autoescaping is turned off globally, so every `{{ }}` in every template emits raw HTML. Stored XSS: a user sets `firstName` to `` via `/profile`; it is rendered unescaped in their own navbar, in every other user's view via `/allocations/{{id}}` (F4), and in the admin's `/benefits` table. Reflected XSS: on login failure, `userName` is echoed into the login form value attribute; on profile validation failure, raw `firstName` is placed into an `href` (`javascript:` URI). The `encodeForHTML` on `website` is the only encoding and is the wrong context for the `href` where `firstNameSafeString` is used.", "fingerprint": "9fa0229ad69eb6307509632979a1ba5e226b53ca6ee025aaa200176b02924b99", "first_seen_at": "2026-11-14T09:47:38.607078+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.607078+00:00", "location_file": "server.js:135-137, app/views/layout.html:75", "location_line": null, "owasp": "A03:2021", "project": "NodeGoat", "recommendation": "Set `autoescape: true` (the default), remove the manual `encodeForHTML` call, use a URL-encoded variant (`encodeForURL`) for any value placed in an `href`, and add a Content-Security-Policy via helmet.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "Global template autoescape disabled; stored and reflected XSS", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Administrative read and write endpoints registered with only an authentication guard, while the role-check middleware is left unused.", "current_ref": "F5", "cvss_score": 7.1, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:N", "cwe": "CWE-862", "description": "Both benefits routes are protected only by `isLoggedIn`; the `isAdmin` middleware exists but is commented out. Any user can GET `/benefits` to list all non-admin users, and POST `/benefits` with an arbitrary `userId` to change any other user's `benefitStartDate`. The DAO returns the complete user documents (including plaintext `password`, `ssn`, `bankAcc`) into the template context.", "fingerprint": "d77824269c393761c883843ee4cf79463f40d67ff13485908887fc6434c7017a", "first_seen_at": "2026-11-14T09:47:38.606292+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.606292+00:00", "location_file": "app/routes/index.js:55-56", "location_line": null, "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Add `isAdmin` to both routes, and project only the needed fields in the users query (`{ projection: { firstName: 1, lastName: 1, benefitStartDate: 1 } }`).", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "Missing admin check on `/benefits` (function-level access control)", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Record lookup keyed on a path parameter supplied by the client with no comparison against the authenticated principal.", "current_ref": "F4", "cvss_score": 4.3, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "cwe": "CWE-639", "description": "The handler reads `userId` from `req.params` rather than `req.session` and never checks it matches the caller. Any logged-in user can request `/allocations/1`, `/allocations/2`, and so on to enumerate every user's name and asset allocation, and user IDs are sequential integers.", "fingerprint": "c16b3a7fe2a661fd28efc7858b8c76e21e8bbd14319c68745e12984001ae6177", "first_seen_at": "2026-11-14T09:47:38.606174+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.606174+00:00", "location_file": "app/routes/allocations.js:16-23", "location_line": null, "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Use `req.session.userId` for the lookup and change the route to `/allocations`. If admins must view others' allocations, gate that path behind the existing `isAdmin` middleware.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "IDOR: allocations looked up by URL `userId`, not session", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Database query filter built as a JavaScript source string by template interpolation of a query-string value, executed via the server-side where operator.", "current_ref": "F3", "cvss_score": 8.1, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H", "cwe": "CWE-943", "description": "The `threshold` query parameter from `/allocations/:userId?threshold=` is interpolated unquoted into a MongoDB `$where` JavaScript expression. `threshold=0'; return true; '` returns every allocation document for every user, and `threshold=0'; while(true){}'` pins the database CPU. The `$where` operator executes server-side JavaScript in MongoDB.", "fingerprint": "36546d614b52d975a73380c204ccfaae6d63418cd1350b2db7c4f5bd2dc093cd", "first_seen_at": "2026-11-14T09:47:38.606047+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.606047+00:00", "location_file": "app/data/allocations-dao.js:77-79", "location_line": null, "owasp": "A03:2021", "project": "NodeGoat", "recommendation": "Remove `$where`. Parse `threshold` with `parseInt`, bound it to 0-99, and use a structured filter: `{ userId: parsedUserId, stocks: { $gt: parsedThreshold } }`.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "NoSQL injection via `$where` string interpolation", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Outbound HTTP request whose entire target URL is built from query-string parameters, with the upstream body echoed verbatim into an HTML response.", "current_ref": "F2", "cvss_score": 8.5, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "cwe": "CWE-918", "description": "`/research?symbol=X&url=Y` concatenates two query parameters into a URL and fetches it server-side with `needle.get`. The attacker fully controls the scheme, host, and path, so they can reach cloud metadata endpoints, internal services, or `localhost:27017`. The fetched body is written into the response as `text/html` without encoding, so this is also a reflected XSS and internal-content disclosure channel.", "fingerprint": "81357f04c3ccfc1802da1fd1a90526b5b5422fb5f9a17a93fde9cf91b4e7c909", "first_seen_at": "2026-11-14T09:47:38.605900+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.605900+00:00", "location_file": "app/routes/research.js:15-26", "location_line": null, "owasp": "A10:2021", "project": "NodeGoat", "recommendation": "Drop the `url` parameter entirely. Hardcode the upstream base URL, validate `symbol` against `^[A-Z]{1,6}$`, pass it as a URL-encoded path segment, and HTML-encode (or JSON-return) the upstream body instead of writing it as HTML.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "SSRF with raw response body reflected as HTML", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Request body fields passed directly to a JavaScript eval call before any type validation.", "current_ref": "F1", "cvss_score": 8.8, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "cwe": "CWE-95", "description": "The contributions update handler passes three fields from `req.body` straight into `eval()`. Any authenticated user (self-registration is open at `/signup`) can POST `preTax=require('child_process').execSync('id').toString()` or `preTax=process.exit()` to `/contributions` and execute arbitrary code in the Node process, or crash the server. The `isNaN` validation runs after the eval, so it does not constrain the payload.", "fingerprint": "14c496def185f104bd8d034c41ab10ccd318dda2154a845df3ed35867031b798", "first_seen_at": "2026-11-14T09:47:38.603780+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:47:38.603780+00:00", "location_file": "app/routes/contributions.js:32-34", "location_line": null, "owasp": "A03:2021", "project": "NodeGoat", "recommendation": "Replace `eval()` with `parseInt(value, 10)` (or `Number()`), reject `NaN`, negative, and out-of-range values, and validate the body with a schema before use.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "Server-side JS injection via `eval()` on POST body", "verdict": "Confirmed"} -{"closed_at": null, "code_region_hash": null, "construct": "Short illustrative secret string embedded in an HTML tutorial code sample rather than in executable configuration.", "current_ref": "S6", "evidence": "s3Cur3` ...", "exposure": "Public, but not used by any code path. Included for completeness; readers may copy the snippet verbatim.", "fingerprint": "55353f4cdcbb74d108dcb0d927c986a9ed41a7f1c0716a308e677a75e4072581", "first_seen_at": "2026-11-14T09:45:42.156481+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:45:42.156481+00:00", "location_file": "app/views/tutorial/a2.html:153, app/views/tutorial/a3.html:176", "location_line": null, "project": "NodeGoat", "remediation": "No rotation needed. Replace with an obvious placeholder such as `` to discourage copy-paste.", "secret_type": "Tutorial example cookie secret", "severity": "Low", "skill_id": "secret-scanning", "source": "docs", "status": "open", "validity": "Placeholder"} -{"closed_at": null, "code_region_hash": null, "construct": "Default administrator and user passwords written in plaintext inside the database seed script that runs automatically on deploy.", "current_ref": "S5", "evidence": "Admin_1...", "exposure": "Public. The seed script is run automatically on Heroku deploy (`app.json` postdeploy) and by `docker-compose.yml`, so every unmodified deployment has an admin account with a publicly known password. For a training app this is intended, but forks deployed to real infrastructure inherit it.", "fingerprint": "187290bd0ffd86949efdfc3e478bd0699df08a1395c21cce49ba28fc1ebc29d6", "first_seen_at": "2026-11-14T09:45:42.156307+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:45:42.156307+00:00", "location_file": "artifacts/db-reset.js:18,27,35; test/e2e/fixtures/users/*.json; test/security/profile-test.js:37", "location_line": null, "project": "NodeGoat", "remediation": "Rotate/change the admin password immediately on any non-training deployment. Have the seed script accept an `ADMIN_PASSWORD` environment variable or generate a random password and print it once. Keep fixtures for E2E tests but make them clearly test-only.", "secret_type": "Seeded admin & user passwords", "severity": "Medium", "skill_id": "secret-scanning", "source": "code", "status": "open", "validity": "Looks live"} -{"closed_at": null, "code_region_hash": null, "construct": "High-entropy security-scanner API key hard-coded in development and test configuration files alongside the scanner's internal network address.", "current_ref": "S4", "evidence": "v9dn0bal...", "exposure": "Public. The key targets a ZAP instance on a private LAN/VM address, so remote exploitation is unlikely, but anyone on the same network as a developer running this setup can drive their ZAP instance (spider, active scan, read reports). The value is high-entropy and matches ZAP's generated-key format rather than a placeholder.", "fingerprint": "dcd28f5fa9d60d18ce7503f36773b882efe8eef23798683285938450621deca5", "first_seen_at": "2026-11-14T09:45:42.156014+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:45:42.156014+00:00", "location_file": "config/env/development.js:6, config/env/test.js:6", "location_line": null, "project": "NodeGoat", "remediation": "Rotate the ZAP API key on any developer machine that used this value. Load it from an environment variable (`ZAP_API_KEY`) and replace the literal with an empty default.", "secret_type": "OWASP ZAP API key", "severity": "Medium", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Unclear"} -{"closed_at": null, "code_region_hash": "4acaa337f66575d67e4bc5df89441dbd50262b58288e9ecb3522d95acd9f8004", "construct": "Fixed symmetric encryption key hard-coded in the shared default configuration module and used directly to encrypt sensitive user profile fields.", "current_ref": "S3", "evidence": "a_secure...", "exposure": "Public. All data encrypted by any default deployment (profile SSN/DOB fields) can be decrypted by anyone with the repo. Also lacks a per-deployment IV strategy, but that is a design issue outside secret-scanning scope.", "fingerprint": "882ee6b8b33b143789f76abea27981f73f772914f08337796dab6639f8c0e1bf", "first_seen_at": "2026-11-14T09:45:42.155871+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:45:42.155871+00:00", "location_file": "config/env/all.js", "location_line": "9", "project": "NodeGoat", "remediation": "Rotate: generate a strong random key per deployment, supply via environment or a secret manager, and re-encrypt existing data under the new key. Remove the literal from source.", "secret_type": "Symmetric encryption key (AES-256)", "severity": "High", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Looks live"} -{"closed_at": null, "code_region_hash": "68770b18af8f703e4186f9226ce6749dc4d3e158435eeaed781f9c35bbb29364", "construct": "Fixed session-signing secret hard-coded in the shared default configuration module, with no environment-variable override and no production-specific value.", "current_ref": "S2", "evidence": "session_...", "exposure": "Public. Every deployment that does not override it signs session cookies with the same secret, so an attacker can forge or tamper with any session cookie for any default NodeGoat instance, including the public demo listed in the README. Production config (`config/env/production.js`) is empty and does not override it.", "fingerprint": "1d43b3e84d2338883bbf2a194601fe6b7a09fadf0ac75963873442bd8bcc4b4f", "first_seen_at": "2026-11-14T09:45:42.155534+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:45:42.155534+00:00", "location_file": "config/env/all.js", "location_line": "8", "project": "NodeGoat", "remediation": "Rotate by generating a random, per-deployment secret and reading it from `process.env.SESSION_SECRET` (fail fast if absent in production). Remove the literal from the repo.", "secret_type": "Session cookie signing secret", "severity": "High", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Looks live"} -{"closed_at": null, "code_region_hash": "a3c3bfb63617e1a2375b0152190484d0aec85d6b0ad1df2375d135f244c9ae3c", "construct": "Unencrypted PEM private key committed to the repository next to its certificate and read from disk by the web server at startup to serve HTTPS.", "current_ref": "S1", "evidence": "-----BEG...", "exposure": "Public to anyone who can read the GitHub repository. The key is loaded by the application to terminate HTTPS. Anyone running NodeGoat with the HTTPS option uses this key, so any TLS session to any such deployment can be decrypted or impersonated by anyone with the repo. Even though this is a training app, forks commonly leave it in place.", "fingerprint": "fc777763d4c605d817581208937284daf740ef9077f56904ac840f0010d0f981", "first_seen_at": "2026-11-14T09:45:42.153923+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:45:42.153923+00:00", "location_file": "artifacts/cert/server.key", "location_line": "1", "project": "NodeGoat", "remediation": "Rotate: generate a new key pair per deployment at provision time (or via a script that is run locally and ignored by git). Remove the key from the repo, add `*.key` and `*.pem` to `.gitignore`, and have `server.js` read the key path from an environment variable. Because this is a public repo, treat the key as permanently compromised; rewriting history is secondary to never reusing it.", "secret_type": "RSA private key (TLS)", "severity": "High", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Looks live"} +{"closed_at": null, "code_region_hash": "17ea6f48f2e47b000fbd5e21938d2d9ea094ae10a984eb7258605265b201d579", "construct": "Session middleware with default cookie flags over plaintext HTTP, authentication that reuses the pre-login session identifier, and an error handler rendering the raw exception into HTML.", "current_ref": "F12", "cvss_score": 4.2, "cvss_vector": "AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N", "cwe": "CWE-1004", "description": "The session is served over plain HTTP with default cookie options (no `httpOnly`, no `secure`, default `connect.sid` name) and `saveUninitialized: true`. Login sets `req.session.userId` without `regenerate()`, so a pre-login session ID fixed by an attacker becomes authenticated. The global error handler renders the error object directly into an unescaped template, exposing internal messages (for example Mongo `$where` evaluation errors containing the injected payload). The login failure path also logs the raw `userName`, allowing CRLF log forging. These amplify F6 (cookie theft via XSS) rather than being independently exploitable.", "fingerprint": "ea393dda85fa06e24af590913855037bbd7a4b2542447a9cf738cfa05301a3f9", "first_seen_at": "2026-11-14T09:47:38.608601+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.608601+00:00", "location_file": "server.js", "location_line": "78", "locations": [{"end_line": 102, "path": "server.js", "start_line": 78}, {"end_line": null, "path": "app/routes/session.js", "start_line": 116}, {"end_line": 12, "path": "app/routes/error.js", "start_line": 10}], "owasp": "A05:2021", "project": "NodeGoat", "recommendation": "Set `cookie: { httpOnly: true, secure: true, sameSite: \"lax\", maxAge }`, use a non-default `name`, wrap the login success path in `req.session.regenerate()`, serve over HTTPS, and render a generic error message while logging details server-side with user input sanitized of CR/LF.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Low", "skill_id": "sast", "status": "open", "title": "Session cookie lacks `httpOnly`/`secure`; no regeneration on login; error page echoes raw error", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "ccc4aefa22822e981ee8818f2ffe3940814e4edc2f36d05d6aba0370adaa94da", "construct": "Regular expression with a repeated group that itself contains an unbounded repeat, applied to a request body field with no length limit.", "current_ref": "F11", "cvss_score": 6.5, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H", "cwe": "CWE-1333", "description": "The pattern `/([0-9]+)+\\#/` has a nested unbounded quantifier. A `bankRouting` value of thirty or more digits followed by a non-`#` character causes exponential backtracking in V8's regex engine and blocks the single Node event loop, denying service to all users.", "fingerprint": "be7d6f49548fb49e5fb07aecdf5166d5d390b2392d828a2e5b0bc0ee47c19c3c", "first_seen_at": "2026-11-14T09:47:38.608483+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.608483+00:00", "location_file": "app/routes/profile.js", "location_line": "59", "locations": [{"end_line": 61, "path": "app/routes/profile.js", "start_line": 59}], "owasp": "unverified", "project": "NodeGoat", "recommendation": "Use `/^[0-9]{1,20}#$/` (anchored, bounded, no nesting) and cap input length before matching.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "ReDoS via nested quantifier on bank routing validator", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "136a357d6ebf482a8e72dac850ee7bfe8a4e44374a9470a58732128f3259068e", "construct": "Session-cookie-authenticated form POST endpoints with the anti-forgery middleware commented out, leaving the token field in templates permanently empty.", "current_ref": "F10", "cvss_score": 6.5, "cvss_vector": "AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N", "cwe": "CWE-352", "description": "The `csurf` middleware is commented out, so `res.locals.csrftoken` is never set and every form's hidden `_csrf` field renders empty. POST `/profile`, `/contributions`, `/benefits`, and `/memos` accept cross-origin form submissions from a logged-in victim's browser, letting an attacker change their bank account number or (via F1) execute code as the victim's session.", "fingerprint": "d91e39dd00e3cc7a1b0772f04dc6e09b789d9e254210c4b73207b10dcbd0cf6b", "first_seen_at": "2026-11-14T09:47:38.608367+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.608367+00:00", "location_file": "server.js", "location_line": "104", "locations": [{"end_line": 113, "path": "server.js", "start_line": 104}, {"end_line": null, "path": "app/views/profile.html", "start_line": 73}], "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Enable a CSRF middleware (`csurf` or a double-submit cookie implementation), set the token in `res.locals`, and set `SameSite=Lax` or `Strict` on the session cookie.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "CSRF protection disabled on all state-changing POST handlers", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "68770b18af8f703e4186f9226ce6749dc4d3e158435eeaed781f9c35bbb29364", "construct": "Session-signing and encryption secrets as string literals in a committed config module, plus a database seed script that creates a privileged account with a fixed password.", "current_ref": "F9", "cvss_score": 9.1, "cvss_vector": "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N", "cwe": "CWE-798", "description": "The express-session signing secret and the AES key are literal strings in a public repository, and `production.js` overrides nothing. The seed script creates `admin / Admin_123`, `user1 / User1_123`, `user2 / User2_123`. Anyone who knows the project can log in as admin on a seeded deployment with no prior access. A private TLS key is also committed under `artifacts/cert/`.", "fingerprint": "adc7ceee63cd364c42b4979ad3a926b16818052c1e3d8f068cbda66917cebbe3", "first_seen_at": "2026-11-14T09:47:38.608201+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.608201+00:00", "location_file": "config/env/all.js", "location_line": "8", "locations": [{"end_line": 9, "path": "config/env/all.js", "start_line": 8}, {"end_line": 18, "path": "artifacts/db-reset.js", "start_line": 15}], "owasp": "A07:2021", "project": "NodeGoat", "recommendation": "Read `SESSION_SECRET` and `CRYPTO_KEY` from environment variables and fail startup if absent. Have the seed script generate a random admin password and print it once, or require it from the environment. Rotate and remove the committed certificate key.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "Hardcoded session secret, crypto key, and seeded admin credentials", "verdict": "Conditional"} +{"closed_at": null, "code_region_hash": "6086b480d31c91bd80f7fbf16ba1cc4c868fb1d59977f30ea18dedce08b6f316", "construct": "HTTP redirect whose target is taken unvalidated from a query-string parameter.", "current_ref": "F8", "cvss_score": 6.1, "cvss_vector": "AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N", "cwe": "CWE-601", "description": "The handler redirects to whatever the `url` query parameter contains. A phishing link such as `/learn?url=https://evil.example/login` carries the trusted origin and lands a logged-in victim on an attacker page.", "fingerprint": "d8a49def2be9ee371dbe1fa80588771b0fd21d00f231bf8b4bbf83bff4089035", "first_seen_at": "2026-11-14T09:47:38.607461+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.607461+00:00", "location_file": "app/routes/index.js", "location_line": "70", "locations": [{"end_line": 73, "path": "app/routes/index.js", "start_line": 70}], "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Map a fixed key (`?topic=iras`) to a server-side allowlist of destination URLs, or validate that the parsed URL's host is in an explicit allowlist before redirecting.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "Open redirect on `/learn?url=`", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "486203cb3812a22a0a3ecf91f177cc62703dae5be29a2e68189d6324b29a8ba7", "construct": "Credential stored as the raw submitted string and verified by plain string equality.", "current_ref": "F7", "cvss_score": 5.3, "cvss_vector": "AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:N/A:N", "cwe": "CWE-256", "description": "`addUser` persists the raw password, and `validateLogin` compares with `===`. `bcrypt-nodejs` is imported but unused. Combined with F3 (dump via `$where`) or F5 (full user docs to template), the plaintext passwords are directly retrievable by any authenticated user; this is the stated precondition for the AC:H rating.", "fingerprint": "8c960919ae322c8822c4116e109eb8c5376f8a43f03c914e867b7368f8ee126e", "first_seen_at": "2026-11-14T09:47:38.607194+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.607194+00:00", "location_file": "app/data/user-dao.js", "location_line": "25", "locations": [{"end_line": null, "path": "app/data/user-dao.js", "start_line": 25}, {"end_line": null, "path": "app/data/user-dao.js", "start_line": 61}], "owasp": "A02:2021", "project": "NodeGoat", "recommendation": "Hash with `bcrypt.hashSync(password, bcrypt.genSaltSync(12))` on create and verify with `bcrypt.compareSync(fromUser, fromDB)`. Prefer the maintained `bcrypt` or `argon2` package over `bcrypt-nodejs`.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "Medium", "skill_id": "sast", "status": "open", "title": "Passwords stored and compared in plaintext", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "ada0e6ff0440e74bb680cb993bf930f9c44cf1015482510b5e92090221dda6b5", "construct": "Template engine configured with output escaping globally disabled, with user-sourced profile fields and request values rendered directly into HTML body and attribute contexts.", "current_ref": "F6", "cvss_score": 5.4, "cvss_vector": "AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N", "cwe": "CWE-79", "description": "Swig autoescaping is turned off globally, so every `{{ }}` in every template emits raw HTML. Stored XSS: a user sets `firstName` to `` via `/profile`; it is rendered unescaped in their own navbar, in every other user's view via `/allocations/{{id}}` (F4), and in the admin's `/benefits` table. Reflected XSS: on login failure, `userName` is echoed into the login form value attribute; on profile validation failure, raw `firstName` is placed into an `href` (`javascript:` URI). The `encodeForHTML` on `website` is the only encoding and is the wrong context for the `href` where `firstNameSafeString` is used.", "fingerprint": "a68b6dfa2d968398f3d53b795882b3d6cfb62d1502e0dd16cf532280fc75e66e", "first_seen_at": "2026-11-14T09:47:38.607078+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.607078+00:00", "location_file": "server.js", "location_line": "135", "locations": [{"end_line": 137, "path": "server.js", "start_line": 135}, {"end_line": null, "path": "app/views/layout.html", "start_line": 75}], "owasp": "A03:2021", "project": "NodeGoat", "recommendation": "Set `autoescape: true` (the default), remove the manual `encodeForHTML` call, use a URL-encoded variant (`encodeForURL`) for any value placed in an `href`, and add a Content-Security-Policy via helmet.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "Global template autoescape disabled; stored and reflected XSS", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "5c93b7a7d555a584c3b2ea412be741c82dafccba58c9a0bc3e2bcda5955fb9fb", "construct": "Administrative read and write endpoints registered with only an authentication guard, while the role-check middleware is left unused.", "current_ref": "F5", "cvss_score": 7.1, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:N", "cwe": "CWE-862", "description": "Both benefits routes are protected only by `isLoggedIn`; the `isAdmin` middleware exists but is commented out. Any user can GET `/benefits` to list all non-admin users, and POST `/benefits` with an arbitrary `userId` to change any other user's `benefitStartDate`. The DAO returns the complete user documents (including plaintext `password`, `ssn`, `bankAcc`) into the template context.", "fingerprint": "73a6f8dbb5f843da8fc5fee93b37115cb74085ad57877f230ca81eb6b8f43b09", "first_seen_at": "2026-11-14T09:47:38.606292+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.606292+00:00", "location_file": "app/routes/index.js", "location_line": "55", "locations": [{"end_line": 56, "path": "app/routes/index.js", "start_line": 55}], "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Add `isAdmin` to both routes, and project only the needed fields in the users query (`{ projection: { firstName: 1, lastName: 1, benefitStartDate: 1 } }`).", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "Missing admin check on `/benefits` (function-level access control)", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "e80ece85f2e8635bd9d59d7ff1bbb50aa0848f7e0653297555faa0d518cf8820", "construct": "Record lookup keyed on a path parameter supplied by the client with no comparison against the authenticated principal.", "current_ref": "F4", "cvss_score": 4.3, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N", "cwe": "CWE-639", "description": "The handler reads `userId` from `req.params` rather than `req.session` and never checks it matches the caller. Any logged-in user can request `/allocations/1`, `/allocations/2`, and so on to enumerate every user's name and asset allocation, and user IDs are sequential integers.", "fingerprint": "49d548f9a4c0c9ef84413fbdb7541989c1733d1af8d30e004052ad0325778024", "first_seen_at": "2026-11-14T09:47:38.606174+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.606174+00:00", "location_file": "app/routes/allocations.js", "location_line": "16", "locations": [{"end_line": 23, "path": "app/routes/allocations.js", "start_line": 16}], "owasp": "A01:2021", "project": "NodeGoat", "recommendation": "Use `req.session.userId` for the lookup and change the route to `/allocations`. If admins must view others' allocations, gate that path behind the existing `isAdmin` middleware.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "IDOR: allocations looked up by URL `userId`, not session", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "606d3e484d0c8f1d11805e0e3c92a6869b4f26b461eac0e40c9c709db3c3066d", "construct": "Database query filter built as a JavaScript source string by template interpolation of a query-string value, executed via the server-side where operator.", "current_ref": "F3", "cvss_score": 8.1, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H", "cwe": "CWE-943", "description": "The `threshold` query parameter from `/allocations/:userId?threshold=` is interpolated unquoted into a MongoDB `$where` JavaScript expression. `threshold=0'; return true; '` returns every allocation document for every user, and `threshold=0'; while(true){}'` pins the database CPU. The `$where` operator executes server-side JavaScript in MongoDB.", "fingerprint": "b7d5535c5cdb2330b036d20c27e0452110030e706f415e0606bb1984d59f2e7b", "first_seen_at": "2026-11-14T09:47:38.606047+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.606047+00:00", "location_file": "app/data/allocations-dao.js", "location_line": "77", "locations": [{"end_line": 79, "path": "app/data/allocations-dao.js", "start_line": 77}], "owasp": "A03:2021", "project": "NodeGoat", "recommendation": "Remove `$where`. Parse `threshold` with `parseInt`, bound it to 0-99, and use a structured filter: `{ userId: parsedUserId, stocks: { $gt: parsedThreshold } }`.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "NoSQL injection via `$where` string interpolation", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "672ae18b556cdd0e9a0e2535fe8c9c25de9f3d4315959467cdfcde60a04ad37a", "construct": "Outbound HTTP request whose entire target URL is built from query-string parameters, with the upstream body echoed verbatim into an HTML response.", "current_ref": "F2", "cvss_score": 8.5, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N", "cwe": "CWE-918", "description": "`/research?symbol=X&url=Y` concatenates two query parameters into a URL and fetches it server-side with `needle.get`. The attacker fully controls the scheme, host, and path, so they can reach cloud metadata endpoints, internal services, or `localhost:27017`. The fetched body is written into the response as `text/html` without encoding, so this is also a reflected XSS and internal-content disclosure channel.", "fingerprint": "82b93acdc09a0a8078cf08e641c60659f14d079f02d3ba83d1bd11298c34747a", "first_seen_at": "2026-11-14T09:47:38.605900+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.605900+00:00", "location_file": "app/routes/research.js", "location_line": "15", "locations": [{"end_line": 26, "path": "app/routes/research.js", "start_line": 15}], "owasp": "A10:2021", "project": "NodeGoat", "recommendation": "Drop the `url` parameter entirely. Hardcode the upstream base URL, validate `symbol` against `^[A-Z]{1,6}$`, pass it as a URL-encoded path segment, and HTML-encode (or JSON-return) the upstream body instead of writing it as HTML.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "SSRF with raw response body reflected as HTML", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "71c311428502118e6b19750006f472c78c9961a1f4418565f44418ef1251cadf", "construct": "Request body fields passed directly to a JavaScript eval call before any type validation.", "current_ref": "F1", "cvss_score": 8.8, "cvss_vector": "AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H", "cwe": "CWE-95", "description": "The contributions update handler passes three fields from `req.body` straight into `eval()`. Any authenticated user (self-registration is open at `/signup`) can POST `preTax=require('child_process').execSync('id').toString()` or `preTax=process.exit()` to `/contributions` and execute arbitrary code in the Node process, or crash the server. The `isNaN` validation runs after the eval, so it does not constrain the payload.", "fingerprint": "8e90afb544b5a4151754be67a60959b2094c1c56d71b7a6fb87ac18ef8bf1904", "first_seen_at": "2026-11-14T09:47:38.603780+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:47:38.603780+00:00", "location_file": "app/routes/contributions.js", "location_line": "32", "locations": [{"end_line": 34, "path": "app/routes/contributions.js", "start_line": 32}], "owasp": "A03:2021", "project": "NodeGoat", "recommendation": "Replace `eval()` with `parseInt(value, 10)` (or `Number()`), reject `NaN`, negative, and out-of-range values, and validate the body with a schema before use.", "review_note": null, "review_status": null, "reviewed_at": null, "reviewed_by": null, "severity": "High", "skill_id": "sast", "status": "open", "title": "Server-side JS injection via `eval()` on POST body", "verdict": "Confirmed"} +{"closed_at": null, "code_region_hash": "775584dde8b1e1705f4a3bc35eae56204c96392de47bc4d8a379d7e62b910394", "construct": "Short illustrative secret string embedded in an HTML tutorial code sample rather than in executable configuration.", "current_ref": "S6", "evidence": "s3Cur3` ...", "exposure": "Public, but not used by any code path. Included for completeness; readers may copy the snippet verbatim.", "fingerprint": "910844bb9fc5e90ddafaef833cf0909aa04a7ac14d396718891dbba7ecd91774", "first_seen_at": "2026-11-14T09:45:42.156481+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:45:42.156481+00:00", "location_file": "app/views/tutorial/a2.html", "location_line": "153", "locations": [{"end_line": null, "path": "app/views/tutorial/a2.html", "start_line": 153}, {"end_line": null, "path": "app/views/tutorial/a3.html", "start_line": 176}], "project": "NodeGoat", "remediation": "No rotation needed. Replace with an obvious placeholder such as `` to discourage copy-paste.", "secret_type": "Tutorial example cookie secret", "severity": "Low", "skill_id": "secret-scanning", "source": "docs", "status": "open", "validity": "Placeholder"} +{"closed_at": null, "code_region_hash": "6dc9855e25cb1be6c6e48a031e9d02b8320289004f8132fb5a0f5fcb8a4255e0", "construct": "Default administrator and user passwords written in plaintext inside the database seed script that runs automatically on deploy.", "current_ref": "S5", "evidence": "Admin_1...", "exposure": "Public. The seed script is run automatically on Heroku deploy (`app.json` postdeploy) and by `docker-compose.yml`, so every unmodified deployment has an admin account with a publicly known password. For a training app this is intended, but forks deployed to real infrastructure inherit it.", "fingerprint": "f1764d9e72137299169e1060b643ad9050086f3aa2256758ed89da2cbff59f2c", "first_seen_at": "2026-11-14T09:45:42.156307+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:45:42.156307+00:00", "location_file": "artifacts/db-reset.js", "location_line": "18", "locations": [{"end_line": null, "path": "artifacts/db-reset.js", "start_line": 18}, {"end_line": null, "path": "artifacts/db-reset.js", "start_line": 27}, {"end_line": null, "path": "artifacts/db-reset.js", "start_line": 35}, {"end_line": null, "path": "test/e2e/fixtures/users/*.json", "start_line": null}, {"end_line": null, "path": "test/security/profile-test.js", "start_line": 37}], "project": "NodeGoat", "remediation": "Rotate/change the admin password immediately on any non-training deployment. Have the seed script accept an `ADMIN_PASSWORD` environment variable or generate a random password and print it once. Keep fixtures for E2E tests but make them clearly test-only.", "secret_type": "Seeded admin & user passwords", "severity": "Medium", "skill_id": "secret-scanning", "source": "code", "status": "open", "validity": "Looks live"} +{"closed_at": null, "code_region_hash": "e99b05b0fec5ae0d3c35efa8ea1372fb8a87b689898c996de8653ab685506472", "construct": "High-entropy security-scanner API key hard-coded in development and test configuration files alongside the scanner's internal network address.", "current_ref": "S4", "evidence": "v9dn0bal...", "exposure": "Public. The key targets a ZAP instance on a private LAN/VM address, so remote exploitation is unlikely, but anyone on the same network as a developer running this setup can drive their ZAP instance (spider, active scan, read reports). The value is high-entropy and matches ZAP's generated-key format rather than a placeholder.", "fingerprint": "db8d43f68d952f2b0c084a29274da1acb768992f7681611c3046d456d872ca8e", "first_seen_at": "2026-11-14T09:45:42.156014+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:45:42.156014+00:00", "location_file": "config/env/development.js", "location_line": "6", "locations": [{"end_line": null, "path": "config/env/development.js", "start_line": 6}, {"end_line": null, "path": "config/env/test.js", "start_line": 6}], "project": "NodeGoat", "remediation": "Rotate the ZAP API key on any developer machine that used this value. Load it from an environment variable (`ZAP_API_KEY`) and replace the literal with an empty default.", "secret_type": "OWASP ZAP API key", "severity": "Medium", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Unclear"} +{"closed_at": null, "code_region_hash": "4acaa337f66575d67e4bc5df89441dbd50262b58288e9ecb3522d95acd9f8004", "construct": "Fixed symmetric encryption key hard-coded in the shared default configuration module and used directly to encrypt sensitive user profile fields.", "current_ref": "S3", "evidence": "a_secure...", "exposure": "Public. All data encrypted by any default deployment (profile SSN/DOB fields) can be decrypted by anyone with the repo. Also lacks a per-deployment IV strategy, but that is a design issue outside secret-scanning scope.", "fingerprint": "882ee6b8b33b143789f76abea27981f73f772914f08337796dab6639f8c0e1bf", "first_seen_at": "2026-11-14T09:45:42.155871+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:45:42.155871+00:00", "location_file": "config/env/all.js", "location_line": "9", "locations": [{"end_line": null, "path": "config/env/all.js", "start_line": 9}], "project": "NodeGoat", "remediation": "Rotate: generate a strong random key per deployment, supply via environment or a secret manager, and re-encrypt existing data under the new key. Remove the literal from source.", "secret_type": "Symmetric encryption key (AES-256)", "severity": "High", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Looks live"} +{"closed_at": null, "code_region_hash": "68770b18af8f703e4186f9226ce6749dc4d3e158435eeaed781f9c35bbb29364", "construct": "Fixed session-signing secret hard-coded in the shared default configuration module, with no environment-variable override and no production-specific value.", "current_ref": "S2", "evidence": "session_...", "exposure": "Public. Every deployment that does not override it signs session cookies with the same secret, so an attacker can forge or tamper with any session cookie for any default NodeGoat instance, including the public demo listed in the README. Production config (`config/env/production.js`) is empty and does not override it.", "fingerprint": "1d43b3e84d2338883bbf2a194601fe6b7a09fadf0ac75963873442bd8bcc4b4f", "first_seen_at": "2026-11-14T09:45:42.155534+00:00", "framework": "express", "language": "javascript", "last_seen_at": "2026-11-14T09:45:42.155534+00:00", "location_file": "config/env/all.js", "location_line": "8", "locations": [{"end_line": null, "path": "config/env/all.js", "start_line": 8}], "project": "NodeGoat", "remediation": "Rotate by generating a random, per-deployment secret and reading it from `process.env.SESSION_SECRET` (fail fast if absent in production). Remove the literal from the repo.", "secret_type": "Session cookie signing secret", "severity": "High", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Looks live"} +{"closed_at": null, "code_region_hash": "a3c3bfb63617e1a2375b0152190484d0aec85d6b0ad1df2375d135f244c9ae3c", "construct": "Unencrypted PEM private key committed to the repository next to its certificate and read from disk by the web server at startup to serve HTTPS.", "current_ref": "S1", "evidence": "-----BEG...", "exposure": "Public to anyone who can read the GitHub repository. The key is loaded by the application to terminate HTTPS. Anyone running NodeGoat with the HTTPS option uses this key, so any TLS session to any such deployment can be decrypted or impersonated by anyone with the repo. Even though this is a training app, forks commonly leave it in place.", "fingerprint": "fc777763d4c605d817581208937284daf740ef9077f56904ac840f0010d0f981", "first_seen_at": "2026-11-14T09:45:42.153923+00:00", "framework": null, "language": null, "last_seen_at": "2026-11-14T09:45:42.153923+00:00", "location_file": "artifacts/cert/server.key", "location_line": "1", "locations": [{"end_line": null, "path": "artifacts/cert/server.key", "start_line": 1}], "project": "NodeGoat", "remediation": "Rotate: generate a new key pair per deployment at provision time (or via a script that is run locally and ignored by git). Remove the key from the repo, add `*.key` and `*.pem` to `.gitignore`, and have `server.js` read the key path from an environment variable. Because this is a public repo, treat the key as permanently compromised; rewriting history is secondary to never reusing it.", "secret_type": "RSA private key (TLS)", "severity": "High", "skill_id": "secret-scanning", "source": "config", "status": "open", "validity": "Looks live"} diff --git a/examples/sample-output/nodegoat/findings.sarif b/examples/sample-output/nodegoat/findings.sarif index 8d09d00..22bab09 100644 --- a/examples/sample-output/nodegoat/findings.sarif +++ b/examples/sample-output/nodegoat/findings.sarif @@ -9,7 +9,32 @@ { "physicalLocation": { "artifactLocation": { - "uri": "server.js%3A78-102%2C%20app/routes/session.js%3A116%2C%20app/routes/error.js%3A10-12" + "uri": "server.js" + }, + "region": { + "endLine": 102, + "startLine": 78 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "app/routes/session.js" + }, + "region": { + "startLine": 116 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "app/routes/error.js" + }, + "region": { + "endLine": 12, + "startLine": 10 } } } @@ -26,7 +51,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/routes/profile.js%3A59-61" + "uri": "app/routes/profile.js" + }, + "region": { + "endLine": 61, + "startLine": 59 } } } @@ -43,7 +72,21 @@ { "physicalLocation": { "artifactLocation": { - "uri": "server.js%3A104-113%2C%20app/views/profile.html%3A73" + "uri": "server.js" + }, + "region": { + "endLine": 113, + "startLine": 104 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "app/views/profile.html" + }, + "region": { + "startLine": 73 } } } @@ -60,7 +103,22 @@ { "physicalLocation": { "artifactLocation": { - "uri": "config/env/all.js%3A8-9%2C%20artifacts/db-reset.js%3A15-18" + "uri": "config/env/all.js" + }, + "region": { + "endLine": 9, + "startLine": 8 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "artifacts/db-reset.js" + }, + "region": { + "endLine": 18, + "startLine": 15 } } } @@ -77,7 +135,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/routes/index.js%3A70-73" + "uri": "app/routes/index.js" + }, + "region": { + "endLine": 73, + "startLine": 70 } } } @@ -94,7 +156,20 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/data/user-dao.js%3A25%2C%20%3A61" + "uri": "app/data/user-dao.js" + }, + "region": { + "startLine": 25 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "app/data/user-dao.js" + }, + "region": { + "startLine": 61 } } } @@ -111,7 +186,21 @@ { "physicalLocation": { "artifactLocation": { - "uri": "server.js%3A135-137%2C%20app/views/layout.html%3A75" + "uri": "server.js" + }, + "region": { + "endLine": 137, + "startLine": 135 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "app/views/layout.html" + }, + "region": { + "startLine": 75 } } } @@ -128,7 +217,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/routes/index.js%3A55-56" + "uri": "app/routes/index.js" + }, + "region": { + "endLine": 56, + "startLine": 55 } } } @@ -145,7 +238,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/routes/allocations.js%3A16-23" + "uri": "app/routes/allocations.js" + }, + "region": { + "endLine": 23, + "startLine": 16 } } } @@ -162,7 +259,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/data/allocations-dao.js%3A77-79" + "uri": "app/data/allocations-dao.js" + }, + "region": { + "endLine": 79, + "startLine": 77 } } } @@ -179,7 +280,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/routes/research.js%3A15-26" + "uri": "app/routes/research.js" + }, + "region": { + "endLine": 26, + "startLine": 15 } } } @@ -196,7 +301,11 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/routes/contributions.js%3A32-34" + "uri": "app/routes/contributions.js" + }, + "region": { + "endLine": 34, + "startLine": 32 } } } @@ -213,7 +322,20 @@ { "physicalLocation": { "artifactLocation": { - "uri": "app/views/tutorial/a2.html%3A153%2C%20app/views/tutorial/a3.html%3A176" + "uri": "app/views/tutorial/a2.html" + }, + "region": { + "startLine": 153 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "app/views/tutorial/a3.html" + }, + "region": { + "startLine": 176 } } } @@ -230,7 +352,47 @@ { "physicalLocation": { "artifactLocation": { - "uri": "artifacts/db-reset.js%3A18%2C27%2C35%3B%20test/e2e/fixtures/users/%2A.json%3B%20test/security/profile-test.js%3A37" + "uri": "artifacts/db-reset.js" + }, + "region": { + "startLine": 18 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "artifacts/db-reset.js" + }, + "region": { + "startLine": 27 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "artifacts/db-reset.js" + }, + "region": { + "startLine": 35 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "test/e2e/fixtures/users/%2A.json" + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "test/security/profile-test.js" + }, + "region": { + "startLine": 37 } } } @@ -247,7 +409,20 @@ { "physicalLocation": { "artifactLocation": { - "uri": "config/env/development.js%3A6%2C%20config/env/test.js%3A6" + "uri": "config/env/development.js" + }, + "region": { + "startLine": 6 + } + } + }, + { + "physicalLocation": { + "artifactLocation": { + "uri": "config/env/test.js" + }, + "region": { + "startLine": 6 } } } diff --git a/fuzz/fuzz_parsers.py b/fuzz/fuzz_parsers.py index 10c932d..f3eedff 100644 --- a/fuzz/fuzz_parsers.py +++ b/fuzz/fuzz_parsers.py @@ -17,15 +17,19 @@ from __future__ import annotations +import re import sys import atheris with atheris.instrument_imports(): + from secfoo.report.sast import parse_location, parse_locations from secfoo.report.severity import count_severities, extract_overall_risk_rating from secfoo.skills.loader import SkillLoadError, _parse_frontmatter from secfoo.web.finding_filters import normalize_severity +_TRAILING_RANGE_RE = re.compile(r":\s*\d+(?:\s*-\s*\d*)?\s*$") + def test_one_input(data: bytes) -> None: provider = atheris.FuzzedDataProvider(data) @@ -50,6 +54,17 @@ def test_one_input(data: bytes) -> None: normalised = normalize_severity(text[:64]) assert normalize_severity(normalised) == normalised + # Location parsing must never return delimiters, backticks, or trailing ranges. + loc_path, _loc_line = parse_location(text[:256]) + assert all(ch not in loc_path for ch in (",", ";", "`")) + assert not _TRAILING_RANGE_RE.search(loc_path) + for site_path, start_line, end_line in parse_locations(text[:256]): + assert site_path + assert all(ch not in site_path for ch in (",", ";", "`")) + assert not _TRAILING_RANGE_RE.search(site_path) + if end_line is not None: + assert start_line is not None and end_line > start_line >= 1 + def main() -> None: atheris.Setup(sys.argv, test_one_input) diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index be29a42..3b1eda5 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -1804,7 +1804,9 @@ class FindingsFormat(str, Enum): # Lifecycle bookkeeping that means nothing outside this one SQLite file. _EXPORT_DROP_COLUMNS = {"id", "project_id", "first_seen_run_id", "last_seen_run_id", "closed_in_run_id"} -_EXPORT_LOCATION_COLUMNS = {"location_file", "location_line", "code_region_hash", "reachability_evidence"} +_EXPORT_LOCATION_COLUMNS = { + "location_file", "location_line", "locations", "code_region_hash", "reachability_evidence", +} @findings_app.command(name="export") @@ -1920,6 +1922,7 @@ def findings_show( no_runtime: Annotated[bool, typer.Option("--no-runtime", help="Skip runtime evidence (no fetch).")] = False, ) -> None: """One finding in full, with its runtime evidence and a remediation hint.""" + from secfoo.report.sast import format_location_site from secfoo.runtime.developer import remediation_hint with RunRepository() as repo: @@ -1931,7 +1934,11 @@ def findings_show( skill_id, row, runtime = matches[0] console.print(f"[bold]{_finding_title(skill_id, row)}[/] ({skill_id}, {row.get('severity')}, {row.get('status')})") console.print(f"Project: {row.get('display_name')} Fingerprint: {row['fingerprint']}") - for label, key in (("Location", "location_file"), ("Reachability", "reachability"), ("Fixed in", "fixed_in"), + rendered_sites = [format_location_site(site) for site in (row.get("locations") or [])] + location_display = ", ".join(s for s in rendered_sites if s) or row.get("location_file") + if location_display: + console.print(f"Location: {location_display}") + for label, key in (("Reachability", "reachability"), ("Fixed in", "fixed_in"), ("Recommendation", "recommendation")): if row.get(key): console.print(f"{label}: {row[key]}") diff --git a/src/secfoo/report/sarif.py b/src/secfoo/report/sarif.py index 2bea2e8..25ab6f0 100644 --- a/src/secfoo/report/sarif.py +++ b/src/secfoo/report/sarif.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import re from pathlib import PureWindowsPath from urllib.parse import quote @@ -20,17 +21,22 @@ } -def _location(record: dict) -> dict | None: - path = str(record.get("location_file") or "").strip().replace("\\", "/") +def _uri_for_path(raw_path: str) -> str | None: + path = raw_path.strip().replace("\\", "/") if not path: return None if PureWindowsPath(path).is_absolute(): - uri = PureWindowsPath(path).as_uri() - elif path.startswith("/"): - uri = "file://" + quote(path, safe="/") - else: - uri = quote(path, safe="/") - physical = {"artifactLocation": {"uri": uri}} + return PureWindowsPath(path).as_uri() + if path.startswith("/"): + return "file://" + quote(path, safe="/") + return quote(path, safe="/") + + +def _location(record: dict) -> dict | None: + uri = _uri_for_path(str(record.get("location_file") or "")) + if uri is None: + return None + physical: dict = {"artifactLocation": {"uri": uri}} # Stored legacy/model-authored lines are not guaranteed to be numeric. line = str(record.get("location_line") or "").strip() if re.fullmatch(r"[0-9]+", line) and int(line) > 0: @@ -38,6 +44,36 @@ def _location(record: dict) -> dict | None: return {"physicalLocation": physical} +def _locations(record: dict) -> list[dict]: + raw_sites = record.get("locations") + if isinstance(raw_sites, str): + try: + raw_sites = json.loads(raw_sites) + except ValueError: + raw_sites = None + if isinstance(raw_sites, list) and raw_sites: + entries: list[dict] = [] + for site in raw_sites: + if not isinstance(site, dict): + continue + uri = _uri_for_path(str(site.get("path") or "")) + if uri is None: + continue + physical: dict = {"artifactLocation": {"uri": uri}} + start = site.get("start_line") + end = site.get("end_line") + if isinstance(start, int) and not isinstance(start, bool) and start > 0: + region: dict[str, int] = {"startLine": start} + if isinstance(end, int) and not isinstance(end, bool) and end > start: + region["endLine"] = end + physical["region"] = region + entries.append({"physicalLocation": physical}) + if entries: + return entries + fallback = _location(record) + return [fallback] if fallback is not None else [] + + def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> dict: """Build one run; group rules by skill, CWE and severity. @@ -88,9 +124,9 @@ def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> } if runtime: result["properties"] = {"secfoo": {"runtime": runtime}} - location = _location(record) - if location is not None: - result["locations"] = [location] + locations = _locations(record) + if locations: + result["locations"] = locations results.append(result) return { "$schema": SCHEMA_URI, diff --git a/src/secfoo/report/sast.py b/src/secfoo/report/sast.py index 3ad7d5b..38e2b01 100644 --- a/src/secfoo/report/sast.py +++ b/src/secfoo/report/sast.py @@ -64,9 +64,18 @@ # contract field. _CONSTRUCT_FIELD_RE = re.compile(r"\*\*Construct:\*\*\s*([^\n]+)") -# "`app/db.py:42`" -> ("app/db.py", "42"); the line group is optional since -# a location without one ("`app/db.py`") should still parse. -_LOCATION_RE = re.compile(r"`?(?P[^:`]+?)(?::(?P\d+))?`?\s*$") +# Bare line or range token without a file path (e.g. "61" or "61-65" in +# "`artifacts/db-reset.js:18,27,35`"), which inherits the previous site's path. +_BARE_SPAN_RE = re.compile( + r"^(?:[Ll](?:ine)?s?\s*)?(?P[0-9]+)(?:\s*(?:[-–—]|\.\.\.?)\s*(?:[Ll](?:ine)?s?\s*)?(?P[0-9]+))?$" +) + +# Trailing `:line` or `:start-end` suffix on a path (including bare `:61` +# where the prefix before `:` is empty, and chained `:line:col` suffixes). +_TRAILING_SPAN_RE = re.compile( + r":\s*(?:[Ll](?:ine)?s?\s*)?(?P[-–—])?\s*(?P\d+)" + r"(?:\s*(?:[-–—]|\.\.\.?)\s*(?:[Ll](?:ine)?s?\s*)?(?P\d*)(?:\s*[-–—]\s*\d+)*)?\s*$" +) def extract_findings_register_rows(report_markdown: str) -> list[dict[str, str]]: @@ -127,20 +136,148 @@ def extract_construct_by_id(report_markdown: str) -> dict[str, str]: return result +def _parse_line_span( + start_text: str | None, + end_text: str | None = None, + *, + negative: bool = False, +) -> tuple[int | None, int | None]: + """Normalize parsed start/end strings into 1-based `(start_line, end_line)`.""" + if negative or not start_text or not (start_text.isascii() and start_text.isdigit()): + return None, None + start = int(start_text) + if start < 1: + return None, None + end: int | None = None + if end_text and end_text.isascii() and end_text.isdigit(): + parsed_end = int(end_text) + if parsed_end >= 1 and parsed_end != start: + if parsed_end < start: + start, end = parsed_end, start + else: + end = parsed_end + return start, end + + +def parse_locations(location: str) -> list[tuple[str, int | None, int | None]]: + """Parse a Markdown Location cell into `(path, start_line, end_line)` sites. + + Handles `path:line`, `path:start-end`, `path:line,line`, backticked spans, + comma/semicolon-separated multi-file lists, bare `:61` continuations that + inherit the previous path, and trailing ellipsis markers (`...` / `…`). + """ + cleaned = location.replace("`", "") + sites: list[tuple[str, int | None, int | None]] = [] + prev_path: str | None = None + + for raw_token in re.split(r"[,;]", cleaned): + token = raw_token.strip() + if not token or token in {"...", "…"}: + continue + + if prev_path is not None: + bare_match = _BARE_SPAN_RE.fullmatch(token) + if bare_match: + start, end = _parse_line_span(bare_match.group("start"), bare_match.group("end")) + if start is not None: + sites.append((prev_path, start, end)) + continue + + path_part = token + peeled: list[tuple[str | None, str, str | None]] = [] + while True: + trimmed = path_part.rstrip() + if trimmed.endswith(":"): + path_part = trimmed.rstrip(":").rstrip() + continue + span_match = _TRAILING_SPAN_RE.search(path_part) + if not span_match: + break + peeled.append((span_match.group("neg"), span_match.group("start"), span_match.group("end"))) + path_part = path_part[: span_match.start()].rstrip() + + start_line: int | None = None + end_line: int | None = None + if peeled: + neg, start_raw, end_raw = peeled[-1] + start_line, end_line = _parse_line_span(start_raw, end_raw, negative=bool(neg)) + + path_part = path_part.strip() + if not path_part: + if prev_path is not None and start_line is not None: + sites.append((prev_path, start_line, end_line)) + continue + + if path_part in {"...", "…"}: + continue + + prev_path = path_part + sites.append((path_part, start_line, end_line)) + + return sites + + +def locations_to_dicts( + sites: list[tuple[str, int | None, int | None]], +) -> list[dict[str, str | int | None]]: + """Serialize `(path, start_line, end_line)` tuples for JSON storage/export.""" + return [ + {"path": path, "start_line": start_line, "end_line": end_line} + for path, start_line, end_line in sites + ] + + +def locations_from_raw( + location_file: str | None, + location_line: str | None = None, +) -> list[dict[str, str | int | None]]: + """Derive structured `locations` dicts from stored `(location_file, location_line)`.""" + if not location_file or not location_file.strip(): + return [] + sites = parse_locations(location_file) + if not sites: + return [] + if location_line is not None and len(sites) == 1 and sites[0][1] is None: + line_token = location_line.strip().lstrip(":").strip() + span_match = _BARE_SPAN_RE.fullmatch(line_token) + if span_match: + start, end = _parse_line_span(span_match.group("start"), span_match.group("end")) + if start is not None: + sites = [(sites[0][0], start, end)] + return locations_to_dicts(sites) + + +def format_location_site(site: dict[str, object] | tuple[str, int | None, int | None]) -> str: + """Render one location site as `path`, `path:line`, or `path:start-end`.""" + if isinstance(site, tuple): + path, start, end = site + else: + path = str(site.get("path") or "") + start = site.get("start_line") # type: ignore[assignment] + end = site.get("end_line") # type: ignore[assignment] + if not path: + return "" + if isinstance(start, int) and not isinstance(start, bool) and start > 0: + if isinstance(end, int) and not isinstance(end, bool) and end > start: + return f"{path}:{start}-{end}" + return f"{path}:{start}" + return path + + def parse_location(location: str) -> tuple[str, str | None]: - """"`app/db.py:42`" -> ("app/db.py", "42"); a location with no line - number, or text that doesn't cleanly split into a single file:line - (e.g. a finding spanning several call sites, like - "`app.py:35`, `cli.py:308`"), degrades to (location_stripped, None) - rather than raising or silently dropping part of it -- backticks are - stripped either way since they're Markdown code-span syntax, never - part of a real path. + """Return `(first_path, first_start_line)` from a Markdown Location cell. + + Multi-site cells (`server.js:135-137, app/views/layout.html:75`) and line + ranges (`config/env/all.js:8-9`) resolve to their primary site (`("server.js", + "135")`, `("config/env/all.js", "8")`) so fingerprinting and `hash_code_region` + operate on a real file path and integer start line; callers that need every + site use `parse_locations`. """ - stripped = location.strip() - match = _LOCATION_RE.match(stripped) - if not match: - return stripped.replace("`", ""), None - return match.group("file").strip(), match.group("line") + sites = parse_locations(location) + if not sites: + return "", None + first_path, first_start, _first_end = sites[0] + return first_path, (str(first_start) if first_start is not None else None) def _normalize_path(file_path: str) -> str: @@ -174,7 +311,7 @@ def findings_with_fingerprints( report_markdown: str, *, workdir: Path | None = None, -) -> list[dict[str, str]]: +) -> list[dict[str, object]]: """One dict per Findings Register row, joined with its Detailed Findings block (description/recommendation) and its fingerprint -- computed with the per-run collision guard: only rows that share both @@ -192,16 +329,24 @@ def findings_with_fingerprints( # Group indices by (cwe, file) to detect same-run collisions before # computing any fingerprint. groups: dict[tuple[str, str], list[int]] = {} + parsed_sites_per_row: list[list[tuple[str, int | None, int | None]]] = [] parsed_locations: list[tuple[str, str | None]] = [] for row in rows: - file_path, line = parse_location(row["location"]) + sites = parse_locations(row["location"]) + parsed_sites_per_row.append(sites) + if sites: + file_path = sites[0][0] + line = str(sites[0][1]) if sites[0][1] is not None else None + else: + file_path, line = "", None parsed_locations.append((file_path, line)) key = (row.get("cwe", "").strip().lower(), _normalize_path(file_path)) groups.setdefault(key, []).append(len(parsed_locations) - 1) - results = [] + results: list[dict[str, object]] = [] for index, row in enumerate(rows): file_path, line = parsed_locations[index] + sites = parsed_sites_per_row[index] key = (row.get("cwe", "").strip().lower(), _normalize_path(file_path)) region_hash = None if workdir is not None and line is not None: @@ -218,6 +363,7 @@ def findings_with_fingerprints( **row, "location_file": file_path, "location_line": line, + "locations": locations_to_dicts(sites), "code_region_hash": region_hash, "fingerprint": fingerprint, "legacy_fingerprint": legacy_fingerprint, diff --git a/src/secfoo/report/secret_scanning.py b/src/secfoo/report/secret_scanning.py index e88981e..3e57a6c 100644 --- a/src/secfoo/report/secret_scanning.py +++ b/src/secfoo/report/secret_scanning.py @@ -14,7 +14,7 @@ from secfoo.report.architecture import _extract_section from secfoo.report.code_region import hash_code_region -from secfoo.report.sast import _normalize_path, parse_location +from secfoo.report.sast import _normalize_path, locations_to_dicts, parse_locations SKILL_ID = "secret-scanning" @@ -161,20 +161,24 @@ def fingerprint_for_row( def findings_with_fingerprints( report_markdown: str, *, workdir: Path | None = None -) -> list[dict[str, str | None]]: - """findings_with_narrative() plus parsed location, re-redacted +) -> list[dict[str, object]]: + """findings_with_narrative() plus parsed locations, re-redacted evidence, construct, and a fingerprint -- what runner.update_secret_findings persists.""" constructs = extract_construct_by_id(report_markdown) rows = findings_with_narrative(report_markdown) - parsed = [parse_location(row["location"]) for row in rows] + parsed_sites = [parse_locations(row["location"]) for row in rows] + parsed = [ + (sites[0][0], str(sites[0][1]) if sites[0][1] is not None else None) if sites else ("", None) + for sites in parsed_sites + ] groups: dict[tuple[str, str], int] = {} for row, (file_path, _line) in zip(rows, parsed): key = (_normalize_secret_type(row["secret_type"]), _normalize_path(file_path)) groups[key] = groups.get(key, 0) + 1 - results = [] - for row, (file_path, line) in zip(rows, parsed): + results: list[dict[str, object]] = [] + for row, sites, (file_path, line) in zip(rows, parsed_sites, parsed): key = (_normalize_secret_type(row["secret_type"]), _normalize_path(file_path)) region_hash = None if workdir is not None and line is not None and row.get("source", "").lower() != "history": @@ -188,6 +192,7 @@ def findings_with_fingerprints( "evidence": redact_evidence(row.get("evidence")), "location_file": file_path, "location_line": line, + "locations": locations_to_dicts(sites), "code_region_hash": region_hash, "construct": constructs.get(row["id"], ""), "fingerprint": fingerprint_for_row( diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 06e3f76..a655a07 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -240,6 +240,7 @@ def update_sast_findings( verdict=row.get("verdict") or None, location_file=row["location_file"], location_line=row.get("location_line"), + locations=row.get("locations"), code_region_hash=row.get("code_region_hash"), cvss_vector=vector or None, cvss_score=score, @@ -324,6 +325,7 @@ def update_secret_findings( secret_type=row["secret_type"], location_file=row["location_file"], location_line=row.get("location_line"), + locations=row.get("locations"), code_region_hash=row.get("code_region_hash"), source=row.get("source") or None, validity=row.get("validity") or None, diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index 03efc3e..cfe6f1c 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -1,6 +1,6 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, field @dataclass(frozen=True) @@ -174,6 +174,7 @@ class SastFindingRecord: reviewed_by: str | None = None reviewed_at: str | None = None project_display_name: str | None = None + locations: list[dict] = field(default_factory=list) @dataclass(frozen=True) @@ -232,6 +233,7 @@ class SecretFindingRecord: closed_in_run_id: int | None closed_at: str | None project_display_name: str | None = None + locations: list[dict] = field(default_factory=list) @dataclass(frozen=True) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index a400fa0..e528ff1 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -1,5 +1,6 @@ from __future__ import annotations +import hashlib import json import sqlite3 import uuid @@ -8,6 +9,8 @@ from datetime import datetime, timedelta, timezone from pathlib import Path +from typing_extensions import Self + from secfoo.config import DB_PATH, ensure_store_dirs # Lets a host process that serves multiple SQLite files (the multi-tenant @@ -35,6 +38,21 @@ def use_db_path(path: Path): yield finally: _default_db_path.reset(token) +from secfoo.report.sast import ( + SKILL_ID as SAST_SKILL_ID, +) +from secfoo.report.sast import ( + _normalize_path as _normalize_sast_path, +) +from secfoo.report.sast import ( + locations_from_raw, +) +from secfoo.report.secret_scanning import ( + SKILL_ID as SECRET_SKILL_ID, +) +from secfoo.report.secret_scanning import ( + _normalize_secret_type, +) from secfoo.report.severity import SeverityCounts, extract_overall_risk_rating from secfoo.storage.models import ( AssessmentRecord, @@ -91,6 +109,7 @@ def use_db_path(path: Path): } _SAST_FINDINGS_MIGRATIONS = { + "locations": "ALTER TABLE sast_findings ADD COLUMN locations TEXT", "code_region_hash": "ALTER TABLE sast_findings ADD COLUMN code_region_hash TEXT", "language": "ALTER TABLE sast_findings ADD COLUMN language TEXT", "framework": "ALTER TABLE sast_findings ADD COLUMN framework TEXT", @@ -104,6 +123,10 @@ def use_db_path(path: Path): "reviewed_at": "ALTER TABLE sast_findings ADD COLUMN reviewed_at TEXT", } +_SECRET_FINDINGS_MIGRATIONS = { + "locations": "ALTER TABLE secret_findings ADD COLUMN locations TEXT", +} + SAST_REVIEW_STATUSES = ("confirmed", "false_positive", "accepted_risk") # Skill id -> its per-finding lifecycle table. Every one of these tables @@ -135,6 +158,20 @@ def _now() -> str: } +def _decode_locations(raw: object) -> list[dict]: + if isinstance(raw, list): + return raw + if isinstance(raw, str) and raw: + try: + parsed = json.loads(raw) + if isinstance(parsed, list): + return parsed + except ValueError: + # Fall back to empty list on unparseable JSON string + pass + return [] + + class RunRepository: def __init__(self, db_path: Path | None = None) -> None: ensure_store_dirs() @@ -176,9 +213,214 @@ def _migrate(self) -> None: for column, ddl in _SAST_FINDINGS_MIGRATIONS.items(): if column not in existing_sast_cols: self._conn.execute(ddl) + existing_secret_cols = { + row["name"] for row in self._conn.execute("PRAGMA table_info(secret_findings)").fetchall() + } + for column, ddl in _SECRET_FINDINGS_MIGRATIONS.items(): + if column not in existing_secret_cols: + self._conn.execute(ddl) self._conn.commit() + self._migrate_finding_locations() self._migrate_attachment_kind_check() + def _migrate_finding_locations(self) -> None: + """Backfill `locations` JSON, clean `location_file` / `location_line` + to the primary site, and recompute `fingerprint` to the primary-path hash + for pre-existing rows created before `#112`. + + When two or more old rows collapse onto the same (project_id, CWE/secret_type, + primary_path), a deterministic collapse rule is applied: + 1. The primary row chosen is the one with an active `review_status`, + breaking ties by `status == 'open'`, earliest `first_seen_at`, then `id`. + 2. Any existing review status (review_status, review_note, reviewed_by, + reviewed_at) is preserved onto the primary row. + 3. Secondary collapsed rows are closed and rekeyed to a non-colliding + tombstone fingerprint (`:merged:`) so they never conflict + with subsequent scans or violate uniqueness constraints. + """ + now = _now() + # 1. SAST findings + sast_rows = self._conn.execute( + "SELECT id, project_id, cwe, location_file, location_line, code_region_hash, " + "review_status, review_note, reviewed_by, reviewed_at, status, first_seen_at, closed_at " + "FROM sast_findings WHERE locations IS NULL" + ).fetchall() + if sast_rows: + groups: dict[tuple[int, str], list[dict]] = {} + for r in sast_rows: + sites = locations_from_raw(r["location_file"], r["location_line"]) + if sites: + first_file = str(sites[0]["path"]) + first_start = sites[0]["start_line"] + first_line = str(first_start) if first_start is not None else None + else: + first_file = r["location_file"] + first_line = r["location_line"] + cwe = (r["cwe"] or "").strip().lower() + parts = [SAST_SKILL_ID, cwe, _normalize_sast_path(first_file)] + if r["code_region_hash"]: + parts.append(r["code_region_hash"]) + new_fp = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest() + row_dict = dict(r) + row_dict["_first_file"] = first_file + row_dict["_first_line"] = first_line + row_dict["_sites"] = sites + row_dict["_new_fp"] = new_fp + groups.setdefault((r["project_id"], new_fp), []).append(row_dict) + + for (project_id, new_fp), candidates in groups.items(): + existing = self._conn.execute( + "SELECT id, review_status, review_note, reviewed_by, reviewed_at " + "FROM sast_findings WHERE project_id = ? AND fingerprint = ? AND locations IS NOT NULL", + (project_id, new_fp), + ).fetchone() + + if existing: + primary_id = existing["id"] + if not existing["review_status"]: + for c in candidates: + if c["review_status"]: + self._conn.execute( + "UPDATE sast_findings SET review_status = ?, review_note = ?, " + "reviewed_by = ?, reviewed_at = ? WHERE id = ?", + ( + c["review_status"], c["review_note"], + c["reviewed_by"], c["reviewed_at"], primary_id, + ), + ) + break + for c in candidates: + merged_note = c["review_note"] or "" + sep = "; " if merged_note else "" + merged_note += f"{sep}Merged into finding #{primary_id} during location migration" + self._conn.execute( + "UPDATE sast_findings SET location_file = ?, location_line = ?, locations = ?, " + "fingerprint = ?, status = 'closed', closed_at = coalesce(closed_at, ?), " + "review_note = ? WHERE id = ?", + ( + c["_first_file"], c["_first_line"], json.dumps(c["_sites"]), + f"{new_fp}:merged:{c['id']}", now, merged_note, c["id"], + ), + ) + else: + def _sast_rank(c: dict): + has_review = 1 if c.get("review_status") else 0 + is_open = 1 if c.get("status") == "open" else 0 + first_seen = c.get("first_seen_at") or "" + cid = c.get("id") or 0 + return (-has_review, -is_open, first_seen, cid) + + candidates.sort(key=_sast_rank) + primary = candidates[0] + if not primary["review_status"]: + for other in candidates[1:]: + if other["review_status"]: + primary["review_status"] = other["review_status"] + primary["review_note"] = other["review_note"] + primary["reviewed_by"] = other["reviewed_by"] + primary["reviewed_at"] = other["reviewed_at"] + break + + for sec in candidates[1:]: + merged_note = sec["review_note"] or "" + sep = "; " if merged_note else "" + merged_note += f"{sep}Merged into finding #{primary['id']} during location migration" + self._conn.execute( + "UPDATE sast_findings SET location_file = ?, location_line = ?, locations = ?, " + "fingerprint = ?, status = 'closed', closed_at = coalesce(closed_at, ?), " + "review_note = ? WHERE id = ?", + ( + sec["_first_file"], sec["_first_line"], json.dumps(sec["_sites"]), + f"{new_fp}:merged:{sec['id']}", now, merged_note, sec["id"], + ), + ) + + self._conn.execute( + "UPDATE sast_findings SET location_file = ?, location_line = ?, locations = ?, " + "fingerprint = ?, review_status = ?, review_note = ?, reviewed_by = ?, reviewed_at = ? " + "WHERE id = ?", + ( + primary["_first_file"], primary["_first_line"], json.dumps(primary["_sites"]), + new_fp, primary["review_status"], primary["review_note"], + primary["reviewed_by"], primary["reviewed_at"], primary["id"], + ), + ) + + # 2. Secret findings + secret_rows = self._conn.execute( + "SELECT id, project_id, secret_type, location_file, location_line, code_region_hash, " + "status, first_seen_at, closed_at " + "FROM secret_findings WHERE locations IS NULL" + ).fetchall() + if secret_rows: + groups = {} + for r in secret_rows: + sites = locations_from_raw(r["location_file"], r["location_line"]) + if sites: + first_file = str(sites[0]["path"]) + first_start = sites[0]["start_line"] + first_line = str(first_start) if first_start is not None else None + else: + first_file = r["location_file"] + first_line = r["location_line"] + sec_type = _normalize_secret_type(r["secret_type"] or "") + parts = [SECRET_SKILL_ID, sec_type, _normalize_sast_path(first_file)] + if r["code_region_hash"]: + parts.append(r["code_region_hash"]) + new_fp = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest() + row_dict = dict(r) + row_dict["_first_file"] = first_file + row_dict["_first_line"] = first_line + row_dict["_sites"] = sites + row_dict["_new_fp"] = new_fp + groups.setdefault((r["project_id"], new_fp), []).append(row_dict) + + for (project_id, new_fp), candidates in groups.items(): + existing = self._conn.execute( + "SELECT id FROM secret_findings WHERE project_id = ? AND fingerprint = ? AND locations IS NOT NULL", + (project_id, new_fp), + ).fetchone() + + if existing: + for c in candidates: + self._conn.execute( + "UPDATE secret_findings SET location_file = ?, location_line = ?, locations = ?, " + "fingerprint = ?, status = 'closed', closed_at = coalesce(closed_at, ?) WHERE id = ?", + ( + c["_first_file"], c["_first_line"], json.dumps(c["_sites"]), + f"{new_fp}:merged:{c['id']}", now, c["id"], + ), + ) + else: + def _secret_rank(c: dict): + is_open = 1 if c.get("status") == "open" else 0 + first_seen = c.get("first_seen_at") or "" + cid = c.get("id") or 0 + return (-is_open, first_seen, cid) + + candidates.sort(key=_secret_rank) + primary = candidates[0] + for sec in candidates[1:]: + self._conn.execute( + "UPDATE secret_findings SET location_file = ?, location_line = ?, locations = ?, " + "fingerprint = ?, status = 'closed', closed_at = coalesce(closed_at, ?) WHERE id = ?", + ( + sec["_first_file"], sec["_first_line"], json.dumps(sec["_sites"]), + f"{new_fp}:merged:{sec['id']}", now, sec["id"], + ), + ) + + self._conn.execute( + "UPDATE secret_findings SET location_file = ?, location_line = ?, locations = ?, " + "fingerprint = ? WHERE id = ?", + ( + primary["_first_file"], primary["_first_line"], json.dumps(primary["_sites"]), + new_fp, primary["id"], + ), + ) + + self._conn.commit() + def _migrate_attachment_kind_check(self) -> None: """Widens assessment_attachments.attachment_kind's CHECK constraint to allow 'vendor_doc' on a pre-existing database. Unlike a plain @@ -217,7 +459,7 @@ def _migrate_attachment_kind_check(self) -> None: def close(self) -> None: self._conn.close() - def __enter__(self) -> "RunRepository": + def __enter__(self) -> Self: return self def __exit__(self, *exc: object) -> None: @@ -1310,6 +1552,7 @@ def osv_lookup_map(self) -> dict[tuple[str, str, str], OsvLookupRecord]: def _row_to_sast_finding(self, row: sqlite3.Row) -> SastFindingRecord: data = dict(row) project_display_name = data.pop("display_name", None) + data["locations"] = _decode_locations(data.get("locations")) return SastFindingRecord(project_display_name=project_display_name, **data) def upsert_sast_finding( @@ -1328,6 +1571,7 @@ def upsert_sast_finding( cvss_vector: str | None, cvss_score: float | None, run_id: int, + locations: list[dict] | None = None, description: str | None = None, recommendation: str | None = None, code_region_hash: str | None = None, @@ -1343,17 +1587,20 @@ def upsert_sast_finding( first-seen date rather than looking like a brand-new finding. """ now = _now() + resolved_locations = locations if locations is not None else locations_from_raw(location_file, location_line) + locations_json = json.dumps(resolved_locations) self._conn.execute( "INSERT INTO sast_findings (project_id, fingerprint, current_ref, title, severity, cwe, " - "owasp, verdict, location_file, location_line, code_region_hash, language, framework, construct, " + "owasp, verdict, location_file, location_line, locations, code_region_hash, language, framework, construct, " "cvss_vector, cvss_score, " "description, recommendation, status, first_seen_run_id, first_seen_at, last_seen_run_id, " "last_seen_at) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) " "ON CONFLICT(project_id, fingerprint) DO UPDATE SET " "current_ref = excluded.current_ref, title = excluded.title, severity = excluded.severity, " "cwe = excluded.cwe, owasp = excluded.owasp, verdict = excluded.verdict, " "location_file = excluded.location_file, location_line = excluded.location_line, " + "locations = excluded.locations, " "code_region_hash = excluded.code_region_hash, " "language = excluded.language, framework = excluded.framework, construct = excluded.construct, " "cvss_vector = excluded.cvss_vector, cvss_score = excluded.cvss_score, " @@ -1362,7 +1609,7 @@ def upsert_sast_finding( "closed_in_run_id = NULL, closed_at = NULL", ( project_id, fingerprint, current_ref, title, severity, cwe, owasp, verdict, - location_file, location_line, code_region_hash, language, framework, construct, + location_file, location_line, locations_json, code_region_hash, language, framework, construct, cvss_vector, cvss_score, description, recommendation, run_id, now, run_id, now, ), ) @@ -1518,6 +1765,7 @@ def upsert_secret_finding( location_file: str, severity: str, location_line: str | None = None, + locations: list[dict] | None = None, code_region_hash: str | None = None, source: str | None = None, validity: str | None = None, @@ -1528,6 +1776,7 @@ def upsert_secret_finding( framework: str | None = None, construct: str | None = None, ) -> None: + resolved_locations = locations if locations is not None else locations_from_raw(location_file, location_line) self._upsert_finding( "secret_findings", project_id=project_id, @@ -1535,7 +1784,8 @@ def upsert_secret_finding( run_id=run_id, fields={ "current_ref": current_ref, "secret_type": secret_type, "location_file": location_file, - "location_line": location_line, "code_region_hash": code_region_hash, "source": source, + "location_line": location_line, "locations": json.dumps(resolved_locations), + "code_region_hash": code_region_hash, "source": source, "validity": validity, "severity": severity, "evidence": evidence, "exposure": exposure, "remediation": remediation, "language": language, "framework": framework, "construct": construct, @@ -1576,6 +1826,8 @@ def list_secret_findings( def _row_to_finding(record_cls, row: sqlite3.Row): data = dict(row) project_display_name = data.pop("display_name", None) + if "locations" in data: + data["locations"] = _decode_locations(data["locations"]) return record_cls(project_display_name=project_display_name, **data) def list_structured_findings( @@ -1595,7 +1847,10 @@ def list_structured_findings( if skill_ids and skill_id not in skill_ids: continue for row in self._list_findings(table, project_id=project_id, status=status, limit=limit): - result.append((skill_id, dict(row))) + data = dict(row) + if "locations" in data: + data["locations"] = _decode_locations(data["locations"]) + result.append((skill_id, data)) return result def review_sast_finding( @@ -1655,10 +1910,10 @@ def list_sast_findings( if search: query += ( " AND (sast_findings.title LIKE ? OR sast_findings.cwe LIKE ? " - "OR sast_findings.location_file LIKE ?)" + "OR sast_findings.location_file LIKE ? OR sast_findings.locations LIKE ?)" ) like = f"%{search}%" - params.extend([like, like, like]) + params.extend([like, like, like, like]) query += " ORDER BY sast_findings.cvss_score DESC, sast_findings.last_seen_at DESC LIMIT ?" params.append(limit) rows = self._conn.execute(query, params).fetchall() diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 8c00400..3dc3ab1 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -214,6 +214,7 @@ CREATE TABLE IF NOT EXISTS sast_findings ( verdict TEXT, location_file TEXT NOT NULL, location_line TEXT, + locations TEXT, -- JSON list of {path, start_line, end_line} sites code_region_hash TEXT, -- Stack + code-free construct description (see stack.py and the -- `**Construct:**` contract field): the fields that make a finding @@ -287,6 +288,7 @@ CREATE TABLE IF NOT EXISTS secret_findings ( secret_type TEXT NOT NULL, location_file TEXT NOT NULL, location_line TEXT, + locations TEXT, -- JSON list of {path, start_line, end_line} sites code_region_hash TEXT, source TEXT, -- code / config / history / docs validity TEXT, -- Looks live / Unclear / Placeholder diff --git a/src/secfoo/web/secret_scanning_dashboard.py b/src/secfoo/web/secret_scanning_dashboard.py index f4dc0ee..e4e3890 100644 --- a/src/secfoo/web/secret_scanning_dashboard.py +++ b/src/secfoo/web/secret_scanning_dashboard.py @@ -13,6 +13,7 @@ from collections import Counter from dataclasses import dataclass, field +from secfoo.report.sast import locations_to_dicts, parse_locations from secfoo.report.secret_scanning import SKILL_ID, findings_with_narrative from secfoo.storage.repository import RunRepository from secfoo.web.dashboard_common import read_report @@ -24,10 +25,7 @@ def _strip_inline_code(value: str) -> str: """Remove Markdown backticks from a table cell value.""" - value = value.strip() - if len(value) >= 2 and value[0] == "`" and value[-1] == "`": - return value[1:-1] - return value + return value.strip().replace("`", "") def _key(project_id: int, finding_id: str, secret_type: str, location: str) -> str: @@ -50,6 +48,7 @@ class SecretFinding: evidence: str = "" exposure: str = "" remediation: str = "" + locations: list[dict] = field(default_factory=list) @dataclass @@ -75,6 +74,7 @@ def build(repo: RunRepository) -> SecretScanningDashboard: continue for row in findings_with_narrative(text): location = _strip_inline_code(row["location"]) + locations = locations_to_dicts(parse_locations(row["location"])) finding = SecretFinding( key=_key(project["project_id"], row["id"], row["secret_type"], location), finding_id=row["id"], @@ -88,6 +88,7 @@ def build(repo: RunRepository) -> SecretScanningDashboard: evidence=row["evidence"], exposure=row["exposure"], remediation=row["remediation"], + locations=locations, ) findings.append(finding) diff --git a/src/secfoo/web/templates/activities/sast_dashboard.html b/src/secfoo/web/templates/activities/sast_dashboard.html index f15215c..5d217b1 100644 --- a/src/secfoo/web/templates/activities/sast_dashboard.html +++ b/src/secfoo/web/templates/activities/sast_dashboard.html @@ -135,7 +135,7 @@

Top findings {% if f.cvss_vector | cvss_network_reachable %}External{% endif %} {{ f.title }}
{{ f.cwe or "unverified" }} - {{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %} + {% if f.locations %}{{ f.locations[0] | fmt_location }}{% if f.locations | length > 1 %} (+{{ (f.locations | length) - 1 }} more){% endif %}{% else %}{{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %}{% endif %} {{ f.last_seen_at | fmt_time }} {% if f.cvss_score is not none %} diff --git a/src/secfoo/web/templates/activities/sast_finding_detail.html b/src/secfoo/web/templates/activities/sast_finding_detail.html index a7bd1e5..1a58c13 100644 --- a/src/secfoo/web/templates/activities/sast_finding_detail.html +++ b/src/secfoo/web/templates/activities/sast_finding_detail.html @@ -13,7 +13,7 @@

{{ finding.title }}

{{ finding.cwe or "unverified" }}{% if finding.owasp and finding.owasp != "unverified" %} · {{ finding.owasp }}{% endif %} - · {{ finding.location_file }}{% if finding.location_line %}:{{ finding.location_line }}{% endif %} + · {% if finding.locations %}{% for loc in finding.locations %}{{ loc | fmt_location }}{% if not loop.last %}, {% endif %}{% endfor %}{% else %}{{ finding.location_file }}{% if finding.location_line %}:{{ finding.location_line }}{% endif %}{% endif %}

diff --git a/src/secfoo/web/templates/activities/sast_findings_list.html b/src/secfoo/web/templates/activities/sast_findings_list.html index 69f1611..af2d5bf 100644 --- a/src/secfoo/web/templates/activities/sast_findings_list.html +++ b/src/secfoo/web/templates/activities/sast_findings_list.html @@ -51,7 +51,7 @@

All findings

{% if f.cvss_vector | cvss_network_reachable %}External{% endif %} {{ f.title }}
{{ f.cwe or "unverified" }} - {{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %} + {% if f.locations %}{{ f.locations[0] | fmt_location }}{% if f.locations | length > 1 %} (+{{ (f.locations | length) - 1 }} more){% endif %}{% else %}{{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %}{% endif %} {{ f.last_seen_at | fmt_time }} {% if f.cvss_score is not none %} diff --git a/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html b/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html index 3620bf2..36a3be0 100644 --- a/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html +++ b/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html @@ -10,7 +10,7 @@

{{ finding.secret_type }}

- {{ finding.project_display_name }} · {{ finding.source }} · {{ finding.location }} + {{ finding.project_display_name }} · {{ finding.source }} · {% if finding.locations %}{% for loc in finding.locations %}{{ loc | fmt_location }}{% if not loop.last %}, {% endif %}{% endfor %}{% else %}{{ finding.location }}{% endif %}

{% if finding.validity.lower() == 'looks live' %} diff --git a/src/secfoo/web/templating.py b/src/secfoo/web/templating.py index 185585b..311676e 100644 --- a/src/secfoo/web/templating.py +++ b/src/secfoo/web/templating.py @@ -10,6 +10,7 @@ from secfoo.cvss import CvssError, parse_vector from secfoo.cvss import rating as cvss_rating from secfoo.report.architecture import classify_design_verdict +from secfoo.report.sast import format_location_site from secfoo.skills.loader import load_all_skills TEMPLATES_DIR = Path(__file__).parent / "templates" @@ -336,3 +337,4 @@ def https_url(value: str | None) -> str: templates.env.filters["responsible_ai_risk_badge"] = responsible_ai_risk_badge_class templates.env.filters["responsible_ai_status_badge"] = responsible_ai_status_badge_class templates.env.filters["design_verdict_badge"] = design_verdict_badge_class +templates.env.filters["fmt_location"] = format_location_site diff --git a/tests/test_property_parsers.py b/tests/test_property_parsers.py index 303649c..5cc2e7f 100644 --- a/tests/test_property_parsers.py +++ b/tests/test_property_parsers.py @@ -9,9 +9,12 @@ from __future__ import annotations +import re + from hypothesis import given, settings from hypothesis import strategies as st +from secfoo.report.sast import parse_location, parse_locations from secfoo.report.severity import ( SeverityCounts, count_severities, @@ -138,3 +141,91 @@ def test_normalize_severity_is_total_and_idempotent(value): @given(st.sampled_from(sorted(_VALID_SEVERITIES) + ["informational"]), st.text(alphabet=" \t", max_size=4)) def test_normalize_severity_ignores_case_and_padding(word, pad): assert normalize_severity(pad + word.upper() + pad) == normalize_severity(word) + + +# --------------------------------------------------------------------------- # +# report/sast.py location parser +# --------------------------------------------------------------------------- # + +_TRAILING_RANGE_RE = re.compile(r":\s*(?:[Ll](?:ine)?s?\s*)?[-–—]?\s*\d+(?:\s*[-–—]\s*\d*)?\s*$") + +clean_segment = st.from_regex(r"[A-Za-z0-9_.\-]{1,12}", fullmatch=True).filter( + lambda seg: seg not in {"...", "."} and not seg.isdigit() +) +clean_path = st.lists(clean_segment, min_size=1, max_size=4).map("/".join) +line_num = st.integers(min_value=1, max_value=9999) + + +@st.composite +def location_site_strategy(draw): + path = draw(clean_path) + kind = draw(st.sampled_from(["none", "single", "range"])) + if kind == "none": + return (path, None, None) + start = draw(line_num) + if kind == "single": + return (path, start, None) + end = draw(st.integers(min_value=start + 1, max_value=start + 500)) + return (path, start, end) + + +@given(st.text()) +@settings(max_examples=500) +def test_parse_location_never_returns_delimiters_backticks_or_trailing_range(text): + path, line = parse_location(text) + assert "," not in path + assert ";" not in path + assert "`" not in path + assert not _TRAILING_RANGE_RE.search(path) + if line is not None: + assert line.isascii() and line.isdigit() and int(line) >= 1 + + for site_path, start_line, end_line in parse_locations(text): + assert site_path + assert "," not in site_path + assert ";" not in site_path + assert "`" not in site_path + assert not _TRAILING_RANGE_RE.search(site_path) + if start_line is None: + assert end_line is None + else: + assert start_line >= 1 + if end_line is not None: + assert end_line > start_line + + +@given( + sites=st.lists(location_site_strategy(), min_size=1, max_size=6), + separators=st.lists(st.sampled_from([", ", "; ", ",", ";"]), min_size=5, max_size=5), + backtick_each=st.booleans(), + use_bare_continuation=st.booleans(), +) +def test_parse_locations_round_trips_structured_sites( + sites, separators, backtick_each, use_bare_continuation +): + tokens = [] + expected = [] + prev_path = None + for idx, (path, start, end) in enumerate(sites): + if use_bare_continuation and prev_path is not None and start is not None and idx % 2 == 1: + actual_path = prev_path + rendered = f":{start}-{end}" if end is not None else f":{start}" + else: + actual_path = path + if start is None: + rendered = path + elif end is None: + rendered = f"{path}:{start}" + else: + rendered = f"{path}:{start}-{end}" + prev_path = actual_path + expected.append((actual_path, start, end)) + tokens.append(f"`{rendered}`" if backtick_each else rendered) + + joined = tokens[0] + for idx, token in enumerate(tokens[1:]): + joined += separators[idx] + token + + assert parse_locations(joined) == expected + first_path, first_start, _ = expected[0] + assert parse_location(joined) == (first_path, str(first_start) if first_start is not None else None) diff --git a/tests/test_report/test_sarif.py b/tests/test_report/test_sarif.py index f2e5782..ac52388 100644 --- a/tests/test_report/test_sarif.py +++ b/tests/test_report/test_sarif.py @@ -95,3 +95,91 @@ def test_cwe_tags_are_normalized_deduplicated_and_unknown_values_ignored(): rules = run["tool"]["driver"]["rules"] assert rules[0]["properties"]["tags"] == ["security", "external/cwe/cwe-79", "external/cwe/cwe-89"] assert rules[1]["properties"]["tags"] == ["security"] + + +def test_multi_site_and_range_locations_emit_per_site_sarif_regions(): + records = [ + { + "skill_id": "sast", + "severity": "High", + "cwe": "CWE-79", + "title": "Autoescape disabled", + "location_file": "server.js", + "location_line": "135", + "locations": [ + {"path": "server.js", "start_line": 135, "end_line": 137}, + {"path": "app/views/layout.html", "start_line": 75, "end_line": None}, + ], + }, + { + "skill_id": "secret-scanning", + "severity": "Medium", + "secret_type": "Seeded passwords", + "location_file": "artifacts/db-reset.js", + "location_line": "18", + "locations": [ + {"path": "artifacts/db-reset.js", "start_line": 18, "end_line": None}, + {"path": "test/e2e/fixtures/users/*.json", "start_line": None, "end_line": None}, + ], + }, + ] + run = validate_sarif(findings_to_sarif(records)) + assert run["results"][0]["locations"] == [ + { + "physicalLocation": { + "artifactLocation": {"uri": "server.js"}, + "region": {"startLine": 135, "endLine": 137}, + } + }, + { + "physicalLocation": { + "artifactLocation": {"uri": "app/views/layout.html"}, + "region": {"startLine": 75}, + } + }, + ] + assert run["results"][1]["locations"] == [ + { + "physicalLocation": { + "artifactLocation": {"uri": "artifacts/db-reset.js"}, + "region": {"startLine": 18}, + } + }, + { + "physicalLocation": { + "artifactLocation": {"uri": "test/e2e/fixtures/users/%2A.json"}, + } + }, + ] + + +def test_nodegoat_sample_sarif_validates_and_every_result_has_a_real_uri(): + sample_dir = Path(__file__).parents[2] / "examples" / "sample-output" / "nodegoat" + sarif_doc = json.loads((sample_dir / "findings.sarif").read_text(encoding="utf-8")) + run = validate_sarif(sarif_doc) + assert len(run["results"]) == 18 + + for result in run["results"]: + assert result.get("locations"), f"missing locations on {result['ruleId']}" + for loc in result["locations"]: + physical = loc["physicalLocation"] + uri = physical["artifactLocation"]["uri"] + assert uri + assert "%3A" not in uri + assert "%2C" not in uri + assert "%3B" not in uri + assert "`" not in uri + assert "," not in uri + assert ";" not in uri + + jsonl_records = [ + json.loads(line) + for line in (sample_dir / "findings.jsonl").read_text(encoding="utf-8").splitlines() + if line.strip() + ] + assert len(jsonl_records) == 18 + for record in jsonl_records: + assert record["locations"], f"missing locations in JSONL record {record['current_ref']}" + assert all(ch not in record["location_file"] for ch in (",", ";", "`", ":")) + rebuilt_run = validate_sarif(findings_to_sarif(jsonl_records)) + assert [r["locations"] for r in rebuilt_run["results"]] == [r["locations"] for r in run["results"]] diff --git a/tests/test_report/test_sast.py b/tests/test_report/test_sast.py index 11bd2a9..b533520 100644 --- a/tests/test_report/test_sast.py +++ b/tests/test_report/test_sast.py @@ -1,5 +1,7 @@ from __future__ import annotations +import pytest + from secfoo.report.sast import ( extract_description_by_id, extract_findings_register_rows, @@ -7,6 +9,7 @@ findings_with_fingerprints, fingerprint_for_row, parse_location, + parse_locations, ) SAMPLE_REPORT = """\ @@ -134,16 +137,110 @@ def test_parse_location_handles_no_backticks(): def test_parse_location_strips_backticks_from_a_multi_location_cell(): - """A real finding can legitimately span more than one call site (e.g. - a missing-auth finding citing both the app factory and the CLI flag - that exposes it) -- the contract only anticipates one `file:line`, so - this must degrade to the whole cell as one location string, not raise - or silently drop part of it. Backticks (Markdown code-span syntax) are - still stripped either way. + """A multi-site cell resolves to the primary site in `parse_location` + while `parse_locations` preserves every call site in order. """ file_path, line = parse_location("`web/app.py:35`, `cli.py:308`") - assert file_path == "web/app.py:35, cli.py:308" - assert line is None + assert file_path == "web/app.py" + assert line == "35" + assert parse_locations("`web/app.py:35`, `cli.py:308`") == [ + ("web/app.py", 35, None), + ("cli.py", 308, None), + ] + + +@pytest.mark.parametrize( + ("raw_location", "expected_sites", "expected_primary"), + [ + ( + "config/env/all.js:8-9", + [("config/env/all.js", 8, 9)], + ("config/env/all.js", "8"), + ), + ( + "server.js:78-102, app/routes/session.js:116, …", + [("server.js", 78, 102), ("app/routes/session.js", 116, None)], + ("server.js", "78"), + ), + ( + "app/data/user-dao.js:25, :61", + [("app/data/user-dao.js", 25, None), ("app/data/user-dao.js", 61, None)], + ("app/data/user-dao.js", "25"), + ), + ( + "`server.js:135-137`, `app/views/layout.html:75`", + [("server.js", 135, 137), ("app/views/layout.html", 75, None)], + ("server.js", "135"), + ), + ( + "`app/data/user-dao.js:25`, `:61`", + [("app/data/user-dao.js", 25, None), ("app/data/user-dao.js", 61, None)], + ("app/data/user-dao.js", "25"), + ), + ( + "`artifacts/db-reset.js:18,27,35`; `test/e2e/fixtures/users/*.json`; `test/security/profile-test.js:37`", + [ + ("artifacts/db-reset.js", 18, None), + ("artifacts/db-reset.js", 27, None), + ("artifacts/db-reset.js", 35, None), + ("test/e2e/fixtures/users/*.json", None, None), + ("test/security/profile-test.js", 37, None), + ], + ("artifacts/db-reset.js", "18"), + ), + ( + "C:\\work\\app.js:10-20; /srv/app/db.py:42:7", + [("C:\\work\\app.js", 10, 20), ("/srv/app/db.py", 42, None)], + ("C:\\work\\app.js", "10"), + ), + ( + "app/db.py:8-8, app/other.py:20-12", + [("app/db.py", 8, None), ("app/other.py", 12, 20)], + ("app/db.py", "8"), + ), + ], +) +def test_parse_locations_handles_ranges_lists_and_bare_continuations( + raw_location, expected_sites, expected_primary +): + assert parse_locations(raw_location) == expected_sites + assert parse_location(raw_location) == expected_primary + + +def test_fingerprint_and_code_region_match_between_line_and_line_range(tmp_path): + (tmp_path / "config" / "env").mkdir(parents=True) + source = "\n".join(f"const line{i} = {i};" for i in range(1, 30)) + (tmp_path / "config" / "env" / "all.js").write_text(source, encoding="utf-8") + + row_range = {"cwe": "CWE-798", "location": "`config/env/all.js:8-9`, `artifacts/db-reset.js:15-18`"} + row_single = {"cwe": "CWE-798", "location": "`config/env/all.js:8`"} + assert fingerprint_for_row(row_range) == fingerprint_for_row(row_single) + + report_template = """\ +# SAST Report + +## 3. Findings Register +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +| F1 | Hardcoded secret | Medium | CWE-798 | A07:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N | {loc} | Confirmed | +""" + r_range = findings_with_fingerprints( + report_template.format(loc="`config/env/all.js:8-9`, `artifacts/db-reset.js:15-18`"), + workdir=tmp_path, + )[0] + r_single = findings_with_fingerprints( + report_template.format(loc="`config/env/all.js:8`"), + workdir=tmp_path, + )[0] + assert r_range["location_file"] == "config/env/all.js" + assert r_range["location_line"] == "8" + assert r_range["locations"] == [ + {"path": "config/env/all.js", "start_line": 8, "end_line": 9}, + {"path": "artifacts/db-reset.js", "start_line": 15, "end_line": 18}, + ] + assert r_range["code_region_hash"] is not None + assert r_range["code_region_hash"] == r_single["code_region_hash"] + assert r_range["fingerprint"] == r_single["fingerprint"] def test_fingerprint_for_row_is_stable_for_identical_cwe_and_file_without_region_hash(): diff --git a/tests/test_report/test_structured_findings.py b/tests/test_report/test_structured_findings.py index 143a196..c9c45cb 100644 --- a/tests/test_report/test_structured_findings.py +++ b/tests/test_report/test_structured_findings.py @@ -161,3 +161,32 @@ def test_secret_fingerprint_uses_the_code_region_when_the_repo_is_on_disk(tmp_pa shifted = SECRET_REPORT.replace("ci.yml:14", "ci.yml:19").replace("ci.yml:90", "ci.yml:95") after = {r["id"]: r for r in secret_scanning.findings_with_fingerprints(shifted, workdir=tmp_path)} assert after["S1"]["fingerprint"] == with_repo["S1"]["fingerprint"] + + +def test_secret_multi_site_and_range_locations_parse_and_fingerprint_on_first_path(tmp_path): + (tmp_path / "config" / "env").mkdir(parents=True) + (tmp_path / "config" / "env" / "development.js").write_text( + "\n".join(f"const x{i} = {i};" for i in range(1, 20)), encoding="utf-8" + ) + multi_report = """\ +# Secret Scanning Report + +## 3. Findings Register +| ID | Secret type | Location | Source | Validity | Severity | +|----|-------------|----------|--------|----------|----------| +| S1 | OWASP ZAP API key | `config/env/development.js:6-7`, `config/env/test.js:6` | config | Unclear | Medium | +""" + single_report = multi_report.replace( + "`config/env/development.js:6-7`, `config/env/test.js:6`", + "`config/env/development.js:6`", + ) + multi_row = secret_scanning.findings_with_fingerprints(multi_report, workdir=tmp_path)[0] + single_row = secret_scanning.findings_with_fingerprints(single_report, workdir=tmp_path)[0] + assert multi_row["location_file"] == "config/env/development.js" + assert multi_row["location_line"] == "6" + assert multi_row["locations"] == [ + {"path": "config/env/development.js", "start_line": 6, "end_line": 7}, + {"path": "config/env/test.js", "start_line": 6, "end_line": None}, + ] + assert multi_row["code_region_hash"] is not None + assert multi_row["fingerprint"] == single_row["fingerprint"] diff --git a/tests/test_storage/test_structured_findings_storage.py b/tests/test_storage/test_structured_findings_storage.py index 9c6f661..2a61927 100644 --- a/tests/test_storage/test_structured_findings_storage.py +++ b/tests/test_storage/test_structured_findings_storage.py @@ -2,6 +2,9 @@ import sqlite3 +from secfoo.report.sast import fingerprint_for_row as sast_fp +from secfoo.report.secret_scanning import fingerprint_for_row as sec_fp +from secfoo.runner import update_sast_findings from secfoo.storage.repository import RunRepository @@ -43,10 +46,10 @@ def test_sca_finding_lifecycle_open_refresh_close(tmp_path): def test_secret_finding_reopens_and_keeps_first_seen(tmp_path): repo = RunRepository(db_path=tmp_path / "db.sqlite") project_id, run_id = _project_and_run(repo) - kwargs = dict( - project_id=project_id, fingerprint="s1", run_id=run_id, current_ref="S1", secret_type="API token", - location_file="deploy/ci.yml", severity="High", evidence="TOKENJ4F...", - ) + kwargs = { + "project_id": project_id, "fingerprint": "s1", "run_id": run_id, "current_ref": "S1", "secret_type": "API token", + "location_file": "deploy/ci.yml", "severity": "High", "evidence": "TOKENJ4F...", + } repo.upsert_secret_finding(**kwargs) first_seen = repo.list_secret_findings()[0].first_seen_at repo.close_stale_findings( @@ -98,12 +101,368 @@ def test_pre_existing_sast_table_gains_stack_columns(tmp_path): repo = RunRepository(db_path=db_path) columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(sast_findings)")} + secret_columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(secret_findings)")} run_columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(runs)")} repo.close() - assert {"language", "framework", "construct", "code_region_hash"} <= columns + assert {"language", "framework", "construct", "code_region_hash", "locations"} <= columns + assert "locations" in secret_columns assert "memory_enabled" in run_columns +def test_migration_re_derives_locations_for_existing_sast_and_secret_rows(tmp_path): + db_path = tmp_path / "legacy.sqlite" + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE projects ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + identifier TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + kind TEXT NOT NULL, + first_seen_at TEXT NOT NULL, + last_run_at TEXT NOT NULL + ); + CREATE TABLE runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_uuid TEXT NOT NULL UNIQUE, + project_id INTEGER NOT NULL, + skill_id TEXT NOT NULL, + skill_name TEXT NOT NULL, + agent_id TEXT NOT NULL, + confluence_urls TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL, + exit_code INTEGER, + started_at TEXT NOT NULL, + finished_at TEXT, + duration_seconds REAL, + report_path TEXT, + prompt_path TEXT, + stderr_excerpt TEXT + ); + CREATE TABLE sast_findings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project_id INTEGER NOT NULL, + fingerprint TEXT NOT NULL, + current_ref TEXT NOT NULL, + title TEXT NOT NULL, + severity TEXT NOT NULL, + cwe TEXT, + owasp TEXT, + verdict TEXT, + location_file TEXT NOT NULL, + location_line TEXT, + code_region_hash TEXT, + language TEXT, + framework TEXT, + construct TEXT, + cvss_vector TEXT, + cvss_score REAL, + description TEXT, + recommendation TEXT, + status TEXT NOT NULL, + first_seen_run_id INTEGER NOT NULL, + first_seen_at TEXT NOT NULL, + last_seen_run_id INTEGER NOT NULL, + last_seen_at TEXT NOT NULL, + closed_in_run_id INTEGER, + closed_at TEXT, + UNIQUE (project_id, fingerprint) + ); + CREATE TABLE secret_findings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project_id INTEGER NOT NULL, + fingerprint TEXT NOT NULL, + current_ref TEXT NOT NULL, + secret_type TEXT NOT NULL, + location_file TEXT NOT NULL, + location_line TEXT, + code_region_hash TEXT, + source TEXT, + validity TEXT, + severity TEXT NOT NULL, + evidence TEXT, + exposure TEXT, + remediation TEXT, + language TEXT, + framework TEXT, + construct TEXT, + status TEXT NOT NULL, + first_seen_run_id INTEGER NOT NULL, + first_seen_at TEXT NOT NULL, + last_seen_run_id INTEGER NOT NULL, + last_seen_at TEXT NOT NULL, + closed_in_run_id INTEGER, + closed_at TEXT, + UNIQUE (project_id, fingerprint) + ); + INSERT INTO projects VALUES (1, '/tmp/nodegoat', 'NodeGoat', 'local', '2026-11-14T00:00:00Z', '2026-11-14T00:00:00Z'); + INSERT INTO runs (id, run_uuid, project_id, skill_id, skill_name, agent_id, status, started_at) + VALUES (1, 'run-1', 1, 'sast', 'SAST', 'claude', 'success', '2026-11-14T00:00:00Z'); + INSERT INTO sast_findings ( + project_id, fingerprint, current_ref, title, severity, cwe, location_file, location_line, + status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at + ) VALUES + (1, 'fp-f7', 'F7', 'Plaintext passwords', 'Medium', 'CWE-256', + 'app/data/user-dao.js:25, :61', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z'), + (1, 'fp-f6', 'F6', 'Autoescape off', 'High', 'CWE-79', + 'server.js:135-137, app/views/layout.html:75', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z'), + (1, 'fp-single', 'F1', 'SQLi', 'High', 'CWE-89', + 'app/db.py', '42', 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z'); + INSERT INTO secret_findings ( + project_id, fingerprint, current_ref, secret_type, location_file, location_line, + source, validity, severity, status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at + ) VALUES + (1, 'fp-s5', 'S5', 'Seeded passwords', + 'artifacts/db-reset.js:18,27,35; test/e2e/fixtures/users/*.json; test/security/profile-test.js:37', + NULL, 'code', 'Looks live', 'Medium', 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z'); + """ + ) + conn.close() + + with RunRepository(db_path=db_path) as repo: + sast_by_ref = {r.current_ref: r for r in repo.list_sast_findings()} + secret_by_ref = {r.current_ref: r for r in repo.list_secret_findings()} + exported = {(skill, row["current_ref"]): row for skill, row in repo.list_structured_findings()} + + assert sast_by_ref["F7"].location_file == "app/data/user-dao.js" + assert sast_by_ref["F7"].location_line == "25" + assert sast_by_ref["F7"].locations == [ + {"path": "app/data/user-dao.js", "start_line": 25, "end_line": None}, + {"path": "app/data/user-dao.js", "start_line": 61, "end_line": None}, + ] + assert sast_by_ref["F6"].location_file == "server.js" + assert sast_by_ref["F6"].location_line == "135" + assert sast_by_ref["F6"].locations == [ + {"path": "server.js", "start_line": 135, "end_line": 137}, + {"path": "app/views/layout.html", "start_line": 75, "end_line": None}, + ] + assert sast_by_ref["F1"].location_file == "app/db.py" + assert sast_by_ref["F1"].location_line == "42" + assert sast_by_ref["F1"].locations == [ + {"path": "app/db.py", "start_line": 42, "end_line": None}, + ] + assert secret_by_ref["S5"].location_file == "artifacts/db-reset.js" + assert secret_by_ref["S5"].location_line == "18" + assert secret_by_ref["S5"].locations == [ + {"path": "artifacts/db-reset.js", "start_line": 18, "end_line": None}, + {"path": "artifacts/db-reset.js", "start_line": 27, "end_line": None}, + {"path": "artifacts/db-reset.js", "start_line": 35, "end_line": None}, + {"path": "test/e2e/fixtures/users/*.json", "start_line": None, "end_line": None}, + {"path": "test/security/profile-test.js", "start_line": 37, "end_line": None}, + ] + assert isinstance(exported[("sast", "F6")]["locations"], list) + assert isinstance(exported[("secret-scanning", "S5")]["locations"], list) + assert sast_by_ref["F7"].fingerprint == sast_fp({"cwe": "CWE-256", "location": "app/data/user-dao.js:25, :61"}) + assert sast_by_ref["F6"].fingerprint == sast_fp({"cwe": "CWE-79", "location": "server.js:135-137, app/views/layout.html:75"}) + assert secret_by_ref["S5"].fingerprint == sec_fp({"secret_type": "Seeded passwords"}, file_path="artifacts/db-reset.js") + + +def test_migration_collapses_duplicate_findings_preserving_review(tmp_path): + db_path = tmp_path / "legacy.sqlite" + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE projects ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + identifier TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + kind TEXT NOT NULL, + first_seen_at TEXT NOT NULL, + last_run_at TEXT NOT NULL + ); + CREATE TABLE runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_uuid TEXT NOT NULL UNIQUE, + project_id INTEGER NOT NULL, + skill_id TEXT NOT NULL, + skill_name TEXT NOT NULL, + agent_id TEXT NOT NULL, + confluence_urls TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL, + exit_code INTEGER, + started_at TEXT NOT NULL, + finished_at TEXT, + duration_seconds REAL, + report_path TEXT, + prompt_path TEXT, + stderr_excerpt TEXT + ); + CREATE TABLE sast_findings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project_id INTEGER NOT NULL, + fingerprint TEXT NOT NULL, + current_ref TEXT NOT NULL, + title TEXT NOT NULL, + severity TEXT NOT NULL, + cwe TEXT, + owasp TEXT, + verdict TEXT, + location_file TEXT NOT NULL, + location_line TEXT, + code_region_hash TEXT, + language TEXT, + framework TEXT, + construct TEXT, + cvss_vector TEXT, + cvss_score REAL, + description TEXT, + recommendation TEXT, + status TEXT NOT NULL, + first_seen_run_id INTEGER NOT NULL, + first_seen_at TEXT NOT NULL, + last_seen_run_id INTEGER NOT NULL, + last_seen_at TEXT NOT NULL, + closed_in_run_id INTEGER, + closed_at TEXT, + review_status TEXT, + review_note TEXT, + reviewed_by TEXT, + reviewed_at TEXT, + UNIQUE (project_id, fingerprint) + ); + INSERT INTO projects VALUES (1, '/tmp/nodegoat', 'NodeGoat', 'local', '2026-11-14T00:00:00Z', '2026-11-14T00:00:00Z'); + INSERT INTO runs (id, run_uuid, project_id, skill_id, skill_name, agent_id, status, started_at) + VALUES (1, 'run-1', 1, 'sast', 'SAST', 'claude', 'success', '2026-11-14T00:00:00Z'); + INSERT INTO sast_findings ( + project_id, fingerprint, current_ref, title, severity, cwe, location_file, location_line, + status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at, + review_status, review_note, reviewed_by, reviewed_at + ) VALUES + (1, 'old-fp-1', 'F1', 'Missing HttpOnly', 'Medium', 'CWE-1004', + 'server.js:78-102', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z', + NULL, NULL, NULL, NULL), + (1, 'old-fp-2', 'F2', 'Missing HttpOnly cookie flag', 'Medium', 'CWE-1004', + 'server.js:104-113', NULL, 'open', 1, '2026-11-14T01:00:00Z', 1, '2026-11-14T01:00:00Z', + 'confirmed', 'Cookie flag verified missing', 'secops', '2026-11-15T10:00:00Z'); + """ + ) + conn.close() + + with RunRepository(db_path=db_path) as repo: + open_findings = repo.list_sast_findings(status="open") + closed_findings = repo.list_sast_findings(status="closed") + + assert len(open_findings) == 1 + assert open_findings[0].review_status == "confirmed" + assert open_findings[0].review_note == "Cookie flag verified missing" + assert open_findings[0].reviewed_by == "secops" + assert open_findings[0].reviewed_at == "2026-11-15T10:00:00Z" + assert open_findings[0].location_file == "server.js" + assert open_findings[0].locations == [{"path": "server.js", "start_line": 104, "end_line": 113}] + + assert len(closed_findings) == 1 + assert ":merged:" in closed_findings[0].fingerprint + assert closed_findings[0].status == "closed" + + +def test_migration_rescan_causes_no_churn(tmp_path): + db_path = tmp_path / "rescan.sqlite" + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE projects ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + identifier TEXT NOT NULL UNIQUE, + display_name TEXT NOT NULL, + kind TEXT NOT NULL, + first_seen_at TEXT NOT NULL, + last_run_at TEXT NOT NULL + ); + CREATE TABLE runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_uuid TEXT NOT NULL UNIQUE, + project_id INTEGER NOT NULL, + skill_id TEXT NOT NULL, + skill_name TEXT NOT NULL, + agent_id TEXT NOT NULL, + confluence_urls TEXT NOT NULL DEFAULT '[]', + status TEXT NOT NULL, + exit_code INTEGER, + started_at TEXT NOT NULL, + finished_at TEXT, + duration_seconds REAL, + report_path TEXT, + prompt_path TEXT, + stderr_excerpt TEXT + ); + CREATE TABLE sast_findings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project_id INTEGER NOT NULL, + fingerprint TEXT NOT NULL, + current_ref TEXT NOT NULL, + title TEXT NOT NULL, + severity TEXT NOT NULL, + cwe TEXT, + owasp TEXT, + verdict TEXT, + location_file TEXT NOT NULL, + location_line TEXT, + code_region_hash TEXT, + language TEXT, + framework TEXT, + construct TEXT, + cvss_vector TEXT, + cvss_score REAL, + description TEXT, + recommendation TEXT, + status TEXT NOT NULL, + first_seen_run_id INTEGER NOT NULL, + first_seen_at TEXT NOT NULL, + last_seen_run_id INTEGER NOT NULL, + last_seen_at TEXT NOT NULL, + closed_in_run_id INTEGER, + closed_at TEXT, + review_status TEXT, + review_note TEXT, + reviewed_by TEXT, + reviewed_at TEXT, + UNIQUE (project_id, fingerprint) + ); + INSERT INTO projects VALUES (1, '/tmp/nodegoat', 'NodeGoat', 'local', '2026-11-14T00:00:00Z', '2026-11-14T00:00:00Z'); + INSERT INTO runs (id, run_uuid, project_id, skill_id, skill_name, agent_id, status, started_at) + VALUES (1, 'run-1', 1, 'sast', 'SAST', 'claude', 'success', '2026-11-14T00:00:00Z'); + INSERT INTO sast_findings ( + project_id, fingerprint, current_ref, title, severity, cwe, location_file, location_line, + status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at, + review_status, review_note, reviewed_by, reviewed_at + ) VALUES + (1, 'old-fp-1', 'F1', 'Missing HttpOnly', 'Medium', 'CWE-1004', + 'server.js:78-102', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z', + 'confirmed', 'Reviewed and accepted', 'secops', '2026-11-15T10:00:00Z'); + """ + ) + conn.close() + + # Step 1: Migration runs automatically when RunRepository opens + with RunRepository(db_path=db_path) as repo: + migrated = repo.list_sast_findings(status="open") + assert len(migrated) == 1 + assert migrated[0].review_status == "confirmed" + + # Step 2: Next run scans the project and finds the vulnerability with new range/multi-site format + run_uuid = repo.create_run( + project_id=1, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] + ) + run_id = repo.get_run(run_uuid).id + report_text = """# SAST Report +## Findings Register +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +| F1 | Missing HttpOnly cookie flag | Medium | CWE-1004 | A05:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N | `server.js:78-102, :104-113` | Confirmed | +""" + update_sast_findings(repo, project_id=1, run_id=run_id, report_text=report_text) + + after_scan_open = repo.list_sast_findings(status="open") + after_scan_closed = repo.list_sast_findings(status="closed") + + assert len(after_scan_open) == 1 + assert len(after_scan_closed) == 0 + assert after_scan_open[0].review_status == "confirmed" + assert after_scan_open[0].review_note == "Reviewed and accepted" + assert after_scan_open[0].reviewed_by == "secops" + assert after_scan_open[0].last_seen_run_id == run_id + + def test_complete_run_records_memory_flag(tmp_path): repo = RunRepository(db_path=tmp_path / "db.sqlite") project_id = repo.upsert_project(identifier="/tmp/x", display_name="x", kind="local") @@ -112,8 +471,10 @@ def test_complete_run_records_memory_flag(tmp_path): untouched = repo.create_run( project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] ) - common = dict(status="success", exit_code=0, duration_seconds=1.0, report_path=None, prompt_path=None, - stderr_excerpt=None) + common = { + "status": "success", "exit_code": 0, "duration_seconds": 1.0, "report_path": None, "prompt_path": None, + "stderr_excerpt": None, + } repo.complete_run(on, memory_enabled=True, **common) repo.complete_run(off, memory_enabled=False, **common) repo.complete_run(untouched, **common) diff --git a/tests/test_web/test_sast_finding_route.py b/tests/test_web/test_sast_finding_route.py index a5c10b1..a00aacc 100644 --- a/tests/test_web/test_sast_finding_route.py +++ b/tests/test_web/test_sast_finding_route.py @@ -154,6 +154,27 @@ def test_sast_finding_detail_renders_for_a_real_finding(client): assert "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N" in resp.text +def test_sast_finding_detail_renders_every_site_and_secondary_file_is_searchable(client): + _, fingerprint = _seed_finding( + fingerprint="fp-multi", + title="Global template autoescape disabled", + location_file="server.js", + location_line="135", + locations=[ + {"path": "server.js", "start_line": 135, "end_line": 137}, + {"path": "app/views/layout.html", "start_line": 75, "end_line": None}, + ], + ) + detail = client.get(f"/activities/sast/findings/{fingerprint}") + assert detail.status_code == 200 + assert "server.js:135-137" in detail.text + assert "app/views/layout.html:75" in detail.text + + search_resp = client.get("/activities/sast/findings?q=layout.html") + assert search_resp.status_code == 200 + assert "Global template autoescape disabled" in search_resp.text + + def test_sast_finding_detail_404s_for_unknown_fingerprint(client): resp = client.get("/activities/sast/findings/does-not-exist") assert resp.status_code == 404 diff --git a/tests/test_web/test_secret_scanning_route.py b/tests/test_web/test_secret_scanning_route.py index de46951..06b0853 100644 --- a/tests/test_web/test_secret_scanning_route.py +++ b/tests/test_web/test_secret_scanning_route.py @@ -138,6 +138,38 @@ def test_secret_scanning_finding_detail_404s_for_unknown_key(client, tmp_path): assert resp.status_code == 404 +def test_secret_scanning_finding_detail_renders_every_site(client, tmp_path): + multi_site_report = """\ +# Secret Scanning Report + +## 3. Findings Register +| ID | Secret type | Location | Source | Validity | Severity | +|----|-------------|----------|--------|----------|----------| +| S1 | Seeded passwords | `artifacts/db-reset.js:18,27,35`; `test/e2e/fixtures/users/*.json`; `test/security/profile-test.js:37` | code | Looks live | Medium | + +## 4. Detailed Findings + +### [MEDIUM] S1: Seeded passwords +- **Evidence:** Admin_12... +- **Remediation:** Rotate seeded credentials. +""" + _seed(tmp_path, report_text=multi_site_report) + dashboard_resp = client.get("/activities/secret-scanning") + match = re.search(r"/activities/secret-scanning/findings/([0-9a-f]+)", dashboard_resp.text) + assert match, dashboard_resp.text + + resp = client.get(f"/activities/secret-scanning/findings/{match.group(1)}") + assert resp.status_code == 200 + for expected in ( + "artifacts/db-reset.js:18", + "artifacts/db-reset.js:27", + "artifacts/db-reset.js:35", + "test/e2e/fixtures/users/*.json", + "test/security/profile-test.js:37", + ): + assert expected in resp.text + + def test_secret_scanning_findings_list_filters_by_severity(client, tmp_path): _seed(tmp_path) # one High finding