diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..3391da0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Fuzz corpora are exact byte inputs (crash reproducers included): never +# let core.autocrlf rewrite their line endings on checkout. +fuzz/corpus/** -text diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..e41a353 --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,89 @@ +name: Fuzz + +# Coverage-guided fuzzing (#121) of the parsers that turn untrusted input -- +# agent output, skill files, config.toml, uploaded documents, runtime +# sensor batches -- into exit codes and dashboard content. Every run first +# replays the seed corpus and the committed crash reproducers in +# fuzz/corpus// (deterministic, blocking). Then each harness fuzzes: +# 60 s and blocking nightly / on dispatch; 30 s and non-blocking on pull +# requests, so a long-standing crash found by chance never fails an unrelated +# PR -- its reproducer is still uploaded. This replaces parser-fuzz.yml. +# +# Reproduce a crash on any platform, without Atheris: +# python fuzz/fuzz_.py crash- +# then add it to fuzz/corpus// with the fix (any file name; renaming +# it crash-. helps), so tests/test_property_fuzz_targets.py and the +# replay step below run it on every build. + +on: + pull_request: + paths: + - "src/secfoo/report/**" + - "src/secfoo/skills/**" + - "src/secfoo/settings.py" + - "src/secfoo/docext.py" + - "src/secfoo/runtime/**" + - "src/secfoo/web/finding_filters.py" + - "fuzz/**" + - ".github/workflows/fuzz.yml" + schedule: + - cron: "17 3 * * *" # nightly, so slow-to-find crashes surface between PRs + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: fuzz-${{ github.ref }} + cancel-in-progress: true + +jobs: + fuzz: + name: Fuzz (${{ matrix.harness }}) + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + harness: [parsers, sarif_export, skill_loader, config, docext, runtime_ingest] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false # PR code is installed and run below + + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Install package + Atheris + run: pip install -e ".[dev]" "atheris==3.1.0" + + - name: Replay the seed corpus and crash reproducers + # -runs=0: run every committed input once and stop. Blocking, and + # deterministic: a fixed crash that comes back fails here. + run: python fuzz/fuzz_${{ matrix.harness }}.py fuzz/corpus/${{ matrix.harness }} -runs=0 + + - name: Fuzz + id: fuzz + # New inputs libFuzzer finds go to work/ (the first folder), never + # into the committed seed corpus. -timeout catches hangs (a + # pathological PDF), -rss_limit_mb decompression bombs. + continue-on-error: ${{ github.event_name == 'pull_request' }} + run: | + mkdir -p work artifacts + python fuzz/fuzz_${{ matrix.harness }}.py work fuzz/corpus/${{ matrix.harness }} \ + -max_total_time=${{ github.event_name == 'pull_request' && 30 || 60 }} \ + -timeout=30 -rss_limit_mb=2560 -artifact_prefix=artifacts/ -print_final_stats=1 + + - name: Report a non-blocking crash + if: ${{ !cancelled() && steps.fuzz.outcome == 'failure' && github.event_name == 'pull_request' }} + run: | + echo "::warning::Fuzzing found a crash in the ${{ matrix.harness }} harness. It may predate this PR; the reproducer is attached as an artifact." + + - name: Upload the crash reproducer + if: ${{ !cancelled() && steps.fuzz.outcome == 'failure' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fuzz-crash-${{ matrix.harness }} + path: artifacts/ + if-no-files-found: ignore diff --git a/.github/workflows/parser-fuzz.yml b/.github/workflows/parser-fuzz.yml deleted file mode 100644 index 9bf63b4..0000000 --- a/.github/workflows/parser-fuzz.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Parser fuzzing -on: - workflow_dispatch: - schedule: - - cron: '23 6 * * 1' -permissions: - contents: read -jobs: - fuzz: - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - persist-credentials: false - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 - with: - python-version: '3.12' - - run: pip install -e '.[dev]' atheris==2.3.0 - - run: python fuzz/fuzz_parsers.py -max_total_time=60 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8a54dd0..2deb789 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,18 +24,45 @@ ruff check . CI runs both on every push and PR, on Python 3.10 and 3.12. -The text parsers (report severities, skill frontmatter, severity filters) -also have property-based tests in `tests/test_property_parsers.py` -(Hypothesis, run as part of `pytest tests`) and a coverage-guided fuzz -harness in `fuzz/fuzz_parsers.py`: +### Fuzzing + +Everything that parses untrusted input has a coverage-guided fuzz harness +in `fuzz/`: + +| Harness | Target | Contract | +| --- | --- | --- | +| `fuzz_parsers.py` | report severities and ratings, documentation-coverage tables, skill frontmatter, severity filters | malformed reports raise only `MalformedReportError`; the coverage parser never raises | +| `fuzz_sarif_export.py` | `findings export` (SARIF and JSONL) | valid SARIF 2.1.0; JSONL round-trips | +| `fuzz_skill_loader.py` | skill files (`--skill-file`, folders, URLs) | a `Skill` or `SkillLoadError` | +| `fuzz_config.py` | `~/.secfoo/config.toml` | correctly typed config or `ConfigError` | +| `fuzz_docext.py` | uploaded PDF / DOCX / PPTX | text or `""`, within a time limit | +| `fuzz_runtime_ingest.py` | runtime sensor NDJSON batches | every line stored or skipped, never a 500 | + +The `Fuzz` workflow first replays every harness's seed corpus and committed +crash reproducers (blocking), then fuzzes each harness: for 30 seconds, +non-blocking, on PRs that touch the parsed code, and for 60 seconds, +blocking, nightly. A crash found on a PR is attached to the run as an +artifact. To run one locally (Linux or macOS): ```sh pip install atheris -python fuzz/fuzz_parsers.py -max_total_time=60 +mkdir -p work +python fuzz/fuzz_config.py work fuzz/corpus/config -max_total_time=60 ``` -If you change one of those parsers, run the harness for a minute before -opening the PR. +Each harness's `check` function also runs on every platform in +`pytest tests/test_property_fuzz_targets.py` (Hypothesis), which replays +every file in `fuzz/corpus/`. Without Atheris, a harness replays the files +or folders you pass, so a CI crash reproduces anywhere, Windows included: + +```sh +python fuzz/fuzz_config.py crash- +``` + +When you fix a crash, add its reproducer to `fuzz/corpus//` as +`crash-.` (or in `fuzz/make_seed_corpus.py`, which writes the +seed corpora) so it's replayed on every run. If you change one of these +parsers, run its harness for a minute before opening the PR. ## Adding or changing a skill diff --git a/fuzz/_common.py b/fuzz/_common.py new file mode 100644 index 0000000..572b4d3 --- /dev/null +++ b/fuzz/_common.py @@ -0,0 +1,52 @@ +"""Shared runner for the harnesses in this folder. + +Each harness defines `check(data: bytes) -> None`: it feeds the bytes to one +parser and asserts that parser's contract (a result or its own clean error, +never any other exception). The same `check` runs three ways: + + python fuzz/fuzz_config.py WORK_DIR fuzz/corpus/config -max_total_time=60 + coverage-guided fuzzing with Atheris (Linux/macOS, `pip install atheris`) + + python fuzz/fuzz_config.py crash- [more files or folders] + without Atheris installed: replay inputs through `check` -- reproduce a + CI crash on any platform, Windows included + + pytest tests/test_property_fuzz_targets.py + Hypothesis drives `check`, and every corpus file is replayed, so the + invariants and the reproducers of fixed crashes run on every platform +""" + +from __future__ import annotations + +import sys +from collections.abc import Callable +from pathlib import Path + +CORPUS_ROOT = Path(__file__).resolve().parent / "corpus" + + +def _replay(check: Callable[[bytes], None], targets: list[str]) -> int: + paths: list[Path] = [] + for target in targets: + path = Path(target) + paths.extend(sorted(p for p in path.rglob("*") if p.is_file()) if path.is_dir() else [path]) + for path in paths: + check(path.read_bytes()) # any exception propagates, with its traceback, like a fuzzer crash + print(f"replayed {len(paths)} input(s) without a crash") + return 0 + + +def main(check: Callable[[bytes], None]) -> None: + try: + import atheris + except ImportError: + targets = [arg for arg in sys.argv[1:] if not arg.startswith("-")] + if not targets: + sys.exit("atheris is not installed: pass input files or folders to replay them, " + "or `pip install atheris` (Linux/macOS) to fuzz") + sys.exit(_replay(check, targets)) + # Instrument after the harness imported its targets: everything loaded so + # far (secfoo and the libraries it parses with) gets coverage feedback. + atheris.instrument_all() + atheris.Setup(sys.argv, check) + atheris.Fuzz() diff --git a/fuzz/corpus/config/crash-defaults-not-a-table.toml b/fuzz/corpus/config/crash-defaults-not-a-table.toml new file mode 100644 index 0000000..3d8fd60 --- /dev/null +++ b/fuzz/corpus/config/crash-defaults-not-a-table.toml @@ -0,0 +1 @@ +defaults = 1 diff --git a/fuzz/corpus/config/crash-defaults-timeout-string.toml b/fuzz/corpus/config/crash-defaults-timeout-string.toml new file mode 100644 index 0000000..67664fd --- /dev/null +++ b/fuzz/corpus/config/crash-defaults-timeout-string.toml @@ -0,0 +1,2 @@ +[defaults] +timeout = 'soon' diff --git a/fuzz/corpus/config/crash-invalid-utf8.toml b/fuzz/corpus/config/crash-invalid-utf8.toml new file mode 100644 index 0000000..a9e68c0 --- /dev/null +++ b/fuzz/corpus/config/crash-invalid-utf8.toml @@ -0,0 +1,2 @@ +[defaults] +agent = "ÿþ" diff --git a/fuzz/corpus/config/crash-mcp-args-number.toml b/fuzz/corpus/config/crash-mcp-args-number.toml new file mode 100644 index 0000000..96f3ea7 --- /dev/null +++ b/fuzz/corpus/config/crash-mcp-args-number.toml @@ -0,0 +1,4 @@ +[[mcp_servers]] +name = 'a' +command = 'npx' +args = [1, 2] diff --git a/fuzz/corpus/config/crash-mcp-command-number.toml b/fuzz/corpus/config/crash-mcp-command-number.toml new file mode 100644 index 0000000..b81f289 --- /dev/null +++ b/fuzz/corpus/config/crash-mcp-command-number.toml @@ -0,0 +1,3 @@ +[[mcp_servers]] +name = 'a' +command = 5 diff --git a/fuzz/corpus/config/crash-mcp-env-table.toml b/fuzz/corpus/config/crash-mcp-env-table.toml new file mode 100644 index 0000000..8cef7db --- /dev/null +++ b/fuzz/corpus/config/crash-mcp-env-table.toml @@ -0,0 +1,4 @@ +[[mcp_servers]] +name = 'a' +command = 'x' +env = { A = { B = 1 } } diff --git a/fuzz/corpus/config/crash-mcp-name-list.toml b/fuzz/corpus/config/crash-mcp-name-list.toml new file mode 100644 index 0000000..3c35847 --- /dev/null +++ b/fuzz/corpus/config/crash-mcp-name-list.toml @@ -0,0 +1,3 @@ +[[mcp_servers]] +name = [1] +command = 'x' diff --git a/fuzz/corpus/config/crash-mcp-servers-string.toml b/fuzz/corpus/config/crash-mcp-servers-string.toml new file mode 100644 index 0000000..3ae2af6 --- /dev/null +++ b/fuzz/corpus/config/crash-mcp-servers-string.toml @@ -0,0 +1 @@ +mcp_servers = 'x' diff --git a/fuzz/corpus/config/crash-mcp-servers-table.toml b/fuzz/corpus/config/crash-mcp-servers-table.toml new file mode 100644 index 0000000..b7ea8ac --- /dev/null +++ b/fuzz/corpus/config/crash-mcp-servers-table.toml @@ -0,0 +1,3 @@ +[mcp_servers] +name = 'a' +command = 'x' diff --git a/fuzz/corpus/config/documented.toml b/fuzz/corpus/config/documented.toml new file mode 100644 index 0000000..e5dc8df --- /dev/null +++ b/fuzz/corpus/config/documented.toml @@ -0,0 +1,29 @@ +[defaults] +agent = "claude" +depth = "quick" +exclude = ["vendor/", "some-cloned-repo/"] +fail_on = "high" +max_cost_usd = 2.00 + +[agents.claude] +model = "claude-sonnet-4-6" + +[agents.api] +max_input_tokens = 150000 + +[[mcp_servers]] +name = "Atlassian-Rovo-MCP" +command = "npx" +args = ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"] + +[[mcp_servers]] +name = "wiki" +url = "https://wiki.internal/mcp" +transport = "http" +headers = { Authorization = "Bearer x" } + +[skills] +paths = ["~/team-skills"] + +[memory] +enabled = false diff --git a/fuzz/corpus/config/empty.toml b/fuzz/corpus/config/empty.toml new file mode 100644 index 0000000..e69de29 diff --git a/fuzz/corpus/docext/blank.pdf.bin b/fuzz/corpus/docext/blank.pdf.bin new file mode 100644 index 0000000..12d004f Binary files /dev/null and b/fuzz/corpus/docext/blank.pdf.bin differ diff --git a/fuzz/corpus/docext/report.docx.bin b/fuzz/corpus/docext/report.docx.bin new file mode 100644 index 0000000..bd759ec Binary files /dev/null and b/fuzz/corpus/docext/report.docx.bin differ diff --git a/fuzz/corpus/docext/summary.pptx.bin b/fuzz/corpus/docext/summary.pptx.bin new file mode 100644 index 0000000..27c08e5 Binary files /dev/null and b/fuzz/corpus/docext/summary.pptx.bin differ diff --git a/fuzz/corpus/docext/text.pdf.bin b/fuzz/corpus/docext/text.pdf.bin new file mode 100644 index 0000000..8af5f7a Binary files /dev/null and b/fuzz/corpus/docext/text.pdf.bin differ diff --git a/fuzz/corpus/parsers/sast-report.md b/fuzz/corpus/parsers/sast-report.md new file mode 100644 index 0000000..c0cdad5 --- /dev/null +++ b/fuzz/corpus/parsers/sast-report.md @@ -0,0 +1,400 @@ +# SAST Report + +## 1. Executive Summary + +OWASP NodeGoat (`https://github.com/OWASP/NodeGoat`) is an Express 4 / MongoDB application that is intentionally vulnerable for training purposes, and the static review confirms the planted defects are real and reachable. Any self-registered user can achieve server-side JavaScript execution via `eval()` on form input, perform server-side request forgery to arbitrary URLs with the response reflected back as HTML, inject into a MongoDB `$where` clause, and read or modify other users' records through missing object-level and function-level authorization. Template autoescaping is globally disabled, so every rendered field is a stored or reflected XSS vector, and passwords are stored and compared in plaintext. Secrets and seeded admin credentials are hardcoded in the repository. + +**Overall risk rating:** Critical + +| Severity | Count | +|----------|-------| +| High | 6 | +| Medium | 5 | +| Low | 1 | + +## 2. Scope + +- **Languages / frameworks:** Node.js (CommonJS), Express 4, express-session (MemoryStore), Swig templates via consolidate, MongoDB native driver 2.x, marked 0.3.5, needle 2.2.4, node-esapi. +- **Reviewed:** `server.js`, `app/routes/*.js` (all 10 files), `app/data/*.js` (all 7 DAOs), `config/config.js`, `config/env/*.js`, `artifacts/db-reset.js`, `app/views/*.html` (layout, login, signup, profile, allocations, memos, benefits, contributions, error-template), `package.json`. +- **Excluded:** `node_modules/`, `.git/`, `app/assets/vendor/**` (third-party front-end bundles, `*.min.js`), `test/**` (Cypress and Mocha fixtures), `app/views/tutorial/**` (static educational pages with no template variables), `artifacts/cert/*` (noted only as committed key material; covered by Secret Scanning). + +## 3. Findings Register + +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +| F1 | Server-side JS injection via `eval()` on POST body | High | CWE-95 | A03:2021 | AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H | `app/routes/contributions.js:32-34` | Confirmed | +| F2 | SSRF with raw response body reflected as HTML | High | CWE-918 | A10:2021 | AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:N | `app/routes/research.js:15-26` | Confirmed | +| F3 | NoSQL injection via `$where` string interpolation | High | CWE-943 | A03:2021 | AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:H | `app/data/allocations-dao.js:77-79` | Confirmed | +| F4 | IDOR: allocations looked up by URL `userId`, not session | High | CWE-639 | A01:2021 | AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N | `app/routes/allocations.js:16-23` | Confirmed | +| F5 | Missing admin check on `/benefits` (function-level access control) | High | CWE-862 | A01:2021 | AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:L/A:N | `app/routes/index.js:55-56` | Confirmed | +| F6 | Global template autoescape disabled; stored and reflected XSS | High | CWE-79 | A03:2021 | AV:N/AC:L/PR:L/UI:R/S:C/C:L/I:L/A:N | `server.js:135-137`, `app/views/layout.html:75` | Confirmed | +| F7 | Passwords stored and compared in plaintext | Medium | CWE-256 | A02:2021 | AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:N/A:N | `app/data/user-dao.js:25`, `:61` | Confirmed | +| F8 | Open redirect on `/learn?url=` | Medium | CWE-601 | A01:2021 | AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N | `app/routes/index.js:70-73` | Confirmed | +| F9 | Hardcoded session secret, crypto key, and seeded admin credentials | Medium | CWE-798 | A07:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N | `config/env/all.js:8-9`, `artifacts/db-reset.js:15-18` | Conditional | +| F10 | CSRF protection disabled on all state-changing POST handlers | Medium | CWE-352 | A01:2021 | AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:N | `server.js:104-113`, `app/views/profile.html:73` | Confirmed | +| F11 | ReDoS via nested quantifier on bank routing validator | Medium | CWE-1333 | unverified | AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H | `app/routes/profile.js:59-61` | Confirmed | +| F12 | Session cookie lacks `httpOnly`/`secure`; no regeneration on login; error page echoes raw error | Low | CWE-1004 | A05:2021 | AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N | `server.js:78-102`, `app/routes/session.js:116`, `app/routes/error.js:10-12` | Confirmed | + +## 4. Detailed Findings + +### [HIGH] F1: Server-side JS injection via `eval()` on POST body +- **Severity:** High +- **CWE:** CWE-95 +- **OWASP:** A03:2021 +- **Verdict:** Confirmed +- **Location:** `app/routes/contributions.js:32-34` +- **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. +- **Vulnerable code:** +```js +const preTax = eval(req.body.preTax); +const afterTax = eval(req.body.afterTax); +const roth = eval(req.body.roth); +``` +- **Construct:** Request body fields passed directly to a JavaScript eval call before any type validation. +- **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. + +### [HIGH] F2: SSRF with raw response body reflected as HTML +- **Severity:** High +- **CWE:** CWE-918 +- **OWASP:** A10:2021 +- **Verdict:** Confirmed +- **Location:** `app/routes/research.js:15-26` +- **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. +- **Vulnerable code:** +```js +const url = req.query.url + req.query.symbol; +return needle.get(url, (error, newResponse, body) => { + ... + if (body) { res.write(body); } +``` +- **Construct:** Outbound HTTP request whose entire target URL is built from query-string parameters, with the upstream body echoed verbatim into an HTML response. +- **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. + +### [HIGH] F3: NoSQL injection via `$where` string interpolation +- **Severity:** High +- **CWE:** CWE-943 +- **OWASP:** A03:2021 +- **Verdict:** Confirmed +- **Location:** `app/data/allocations-dao.js:77-79` +- **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. +- **Vulnerable code:** +```js +return { + $where: `this.userId == ${parsedUserId} && this.stocks > '${threshold}'` +}; +``` +- **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. +- **Recommendation:** Remove `$where`. Parse `threshold` with `parseInt`, bound it to 0-99, and use a structured filter: `{ userId: parsedUserId, stocks: { $gt: parsedThreshold } }`. + +### [HIGH] F4: IDOR: allocations looked up by URL `userId`, not session +- **Severity:** High +- **CWE:** CWE-639 +- **OWASP:** A01:2021 +- **Verdict:** Confirmed +- **Location:** `app/routes/allocations.js:16-23` +- **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. +- **Vulnerable code:** +```js +const { userId } = req.params; +const { threshold } = req.query; +allocationsDAO.getByUserIdAndThreshold(userId, threshold, ... +``` +- **Construct:** Record lookup keyed on a path parameter supplied by the client with no comparison against the authenticated principal. +- **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. + +### [HIGH] F5: Missing admin check on `/benefits` (function-level access control) +- **Severity:** High +- **CWE:** CWE-862 +- **OWASP:** A01:2021 +- **Verdict:** Confirmed +- **Location:** `app/routes/index.js:55-56` +- **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. +- **Vulnerable code:** +```js +app.get("/benefits", isLoggedIn, benefitsHandler.displayBenefits); +app.post("/benefits", isLoggedIn, benefitsHandler.updateBenefits); +/* Fix for A7 ... app.get("/benefits", isLoggedIn, isAdmin, ... +``` +- **Construct:** Administrative read and write endpoints registered with only an authentication guard, while the role-check middleware is left unused. +- **Recommendation:** Add `isAdmin` to both routes, and project only the needed fields in the users query (`{ projection: { firstName: 1, lastName: 1, benefitStartDate: 1 } }`). + +### [HIGH] F6: Global template autoescape disabled; stored and reflected XSS +- **Severity:** High +- **CWE:** CWE-79 +- **OWASP:** A03:2021 +- **Verdict:** Confirmed +- **Location:** `server.js:135-137`, `app/views/layout.html:75` +- **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. +- **Vulnerable code:** +```js +swig.setDefaults({ + // Autoescape disabled + autoescape: false +``` +```html + {{firstName}} {{lastName}} +``` +- **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. +- **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. + +### [MEDIUM] F7: Passwords stored and compared in plaintext +- **Severity:** Medium +- **CWE:** CWE-256 +- **OWASP:** A02:2021 +- **Verdict:** Confirmed +- **Location:** `app/data/user-dao.js:25`, `app/data/user-dao.js:61` +- **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. +- **Vulnerable code:** +```js +password //received from request param +... +const comparePassword = (fromDB, fromUser) => { + return fromDB === fromUser; +``` +- **Construct:** Credential stored as the raw submitted string and verified by plain string equality. +- **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`. + +### [MEDIUM] F8: Open redirect on `/learn?url=` +- **Severity:** Medium +- **CWE:** CWE-601 +- **OWASP:** A01:2021 +- **Verdict:** Confirmed +- **Location:** `app/routes/index.js:70-73` +- **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. +- **Vulnerable code:** +```js +app.get("/learn", isLoggedIn, (req, res) => { + return res.redirect(req.query.url); +}); +``` +- **Construct:** HTTP redirect whose target is taken unvalidated from a query-string parameter. +- **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. + +### [MEDIUM] F9: Hardcoded session secret, crypto key, and seeded admin credentials +- **Severity:** Medium +- **CWE:** CWE-798 +- **OWASP:** A07:2021 +- **Verdict:** Conditional (precondition: deployment uses the committed defaults or runs the seed script against a reachable instance) +- **Location:** `config/env/all.js:8-9`, `artifacts/db-reset.js:15-18` +- **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/`. +- **Vulnerable code:** +```js +cookieSecret: "session_cookie_secret_key_here", +cryptoKey: "a_secure_key_for_crypto_here", +``` +```js +"userName": "admin", ... "password": "Admin_123", "isAdmin": true +``` +- **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. +- **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. + +### [MEDIUM] F10: CSRF protection disabled on all state-changing POST handlers +- **Severity:** Medium +- **CWE:** CWE-352 +- **OWASP:** A01:2021 +- **Verdict:** Confirmed +- **Location:** `server.js:104-113`, `app/views/profile.html:73` +- **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. +- **Vulnerable code:** +```js +/* +// Fix for A8 - CSRF +app.use(csrf()); +``` +```html + +``` +- **Construct:** Session-cookie-authenticated form POST endpoints with the anti-forgery middleware commented out, leaving the token field in templates permanently empty. +- **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. + +### [MEDIUM] F11: ReDoS via nested quantifier on bank routing validator +- **Severity:** Medium +- **CWE:** CWE-1333 +- **OWASP:** unverified +- **Verdict:** Confirmed +- **Location:** `app/routes/profile.js:59-61` +- **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. +- **Vulnerable code:** +```js +const regexPattern = /([0-9]+)+\#/; +const testComplyWithRequirements = regexPattern.test(bankRouting); +``` +- **Construct:** Regular expression with a repeated group that itself contains an unbounded repeat, applied to a request body field with no length limit. +- **Recommendation:** Use `/^[0-9]{1,20}#$/` (anchored, bounded, no nesting) and cap input length before matching. + +### [LOW] F12: Session cookie lacks `httpOnly`/`secure`; no regeneration on login; error page echoes raw error +- **Severity:** Low +- **CWE:** CWE-1004 +- **OWASP:** A05:2021 +- **Verdict:** Confirmed +- **Location:** `server.js:78-102`, `app/routes/session.js:116`, `app/routes/error.js:10-12` +- **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. +- **Vulnerable code:** +```js +app.use(session({ + secret: cookieSecret, + saveUninitialized: true, + resave: true +})); +... +req.session.userId = user._id; +``` +- **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. +- **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. + +## 5. Taint Summary + +| Source | Sink | Path | Sanitized? | +|--------|------|------|------------| +| `req.body.preTax/afterTax/roth` (POST /contributions) | `eval()` | `contributions.js:32-34` | No | +| `req.query.url`, `req.query.symbol` (GET /research) | `needle.get(url)` then `res.write(body)` as HTML | `research.js:15-26` | No | +| `req.query.threshold` (GET /allocations/:userId) | MongoDB `$where` JS string | `allocations.js:19-23` → `allocations-dao.js:78` | No | +| `req.params.userId` (GET /allocations/:userId) | `allocationsCol.find({userId})` cross-user read | `allocations.js:16-23` → `allocations-dao.js:57-86` | `parseInt` only; no ownership check | +| `req.body.userId`, `benefitStartDate` (POST /benefits) | `usersCol.update` on arbitrary `_id` | `benefits.js:30-35` → `benefits-dao.js:23-30` | `parseInt` only; no role check | +| `req.body.firstName/lastName/...` (POST /profile) | Mongo `$set` then unescaped `{{firstName}}` in `layout.html:75`, `allocations.html:35`, `benefits.html:51-52` | `profile.js:42-90` → `profile-dao.js:42-82` → templates | No (autoescape off) | +| `req.body.firstName` (POST /profile, validation failure) | `href="{{firstNameSafeString}}"` | `profile.js:64-75` → `profile.html:78` | No | +| `req.body.userName` (POST /login, failure) | `value="{{userName}}"` in `login.html:110`; `console.log` | `session.js:82-98` | No | +| `req.body.memo` (POST /memos) | `marked(doc.memo)` rendered to all users | `memos.js:13` → `memos-dao.js:15-23` → `memos.html:31` | Partial: `marked` `sanitize:true` (version 0.3.5, bypass risk is an SCA matter) | +| `req.query.url` (GET /learn) | `res.redirect()` | `index.js:70-73` | No | +| `req.body.bankRouting` (POST /profile) | `/([0-9]+)+\#/.test()` | `profile.js:59-61` | No length bound | +| `req.body.password` (POST /signup) | `usersCol.insert` plaintext | `session.js:220` → `user-dao.js:17-46` | No hashing | + +## 6. Remediation Roadmap + +**P0 (blocking):** +- F1: remove `eval()`, use `parseInt` with range validation. +- F2: remove client-controlled `url`, allowlist `symbol`, do not echo upstream body as HTML. +- F3 and F4 (shared root fix in allocations): drop `$where`, use structured filter, source `userId` from session. +- F5: add `isAdmin` middleware to `/benefits` routes and project only needed user fields. + +**P1:** +- F6 and F12 (shared root: output encoding and session hardening): enable Swig autoescape, add helmet with CSP, set cookie flags, regenerate session on login, generic error page. +- F7: bcrypt hashing and comparison. +- F9: move secrets to environment, randomize seeded admin password, remove committed TLS key. + +**P2:** +- F8: allowlisted redirect targets. +- F10: enable CSRF middleware and `SameSite` cookie. +- F11: anchored, bounded routing-number regex. + +**P3:** +- F12 (remaining): sanitize CR/LF from logged `userName`; use non-default session cookie name. + +## 7. Code-Fix Appendix + +All diffs below are illustrative and untested. + +**F1: contributions eval** +```diff +--- a/app/routes/contributions.js ++++ b/app/routes/contributions.js +- const preTax = eval(req.body.preTax); +- const afterTax = eval(req.body.afterTax); +- const roth = eval(req.body.roth); ++ const toPct = v => (typeof v === "string" && /^\d{1,2}$/.test(v)) ? parseInt(v, 10) : NaN; ++ const preTax = toPct(req.body.preTax); ++ const afterTax = toPct(req.body.afterTax); ++ const roth = toPct(req.body.roth); +``` + +**F2: research SSRF** +```diff +--- a/app/routes/research.js ++++ b/app/routes/research.js ++const UPSTREAM = "https://finance.example.com/quote/"; ++const SYMBOL_RE = /^[A-Z]{1,6}$/; + this.displayResearch = (req, res) => { +- if (req.query.symbol) { +- const url = req.query.url + req.query.symbol; ++ const symbol = String(req.query.symbol || ""); ++ if (symbol) { ++ if (!SYMBOL_RE.test(symbol)) return res.status(400).send("Invalid symbol"); ++ const url = UPSTREAM + encodeURIComponent(symbol); + return needle.get(url, (error, newResponse, body) => { + ... +- if (body) { res.write(body); } ++ if (body) { res.write(ESAPI.encoder().encodeForHTML(String(body))); } +``` + +**F3 and F4: allocations injection and IDOR** +```diff +--- a/app/routes/allocations.js ++++ b/app/routes/allocations.js +- const { userId } = req.params; ++ const { userId } = req.session; +--- a/app/data/allocations-dao.js ++++ b/app/data/allocations-dao.js +- if (threshold) { +- return { +- $where: `this.userId == ${parsedUserId} && this.stocks > '${threshold}'` +- }; +- } ++ const t = parseInt(threshold, 10); ++ if (threshold !== undefined && Number.isInteger(t) && t >= 0 && t <= 99) { ++ return { userId: parsedUserId, stocks: { $gt: t } }; ++ } + return { userId: parsedUserId }; +``` + +**F5: benefits authorization** +```diff +--- a/app/routes/index.js ++++ b/app/routes/index.js +- app.get("/benefits", isLoggedIn, benefitsHandler.displayBenefits); +- app.post("/benefits", isLoggedIn, benefitsHandler.updateBenefits); ++ app.get("/benefits", isLoggedIn, isAdmin, benefitsHandler.displayBenefits); ++ app.post("/benefits", isLoggedIn, isAdmin, benefitsHandler.updateBenefits); +``` + +**F6, F12: template escaping and session hardening** +```diff +--- a/server.js ++++ b/server.js ++const helmet = require("helmet"); ++app.use(helmet()); + app.use(session({ +- secret: cookieSecret, ++ secret: process.env.SESSION_SECRET, ++ name: "sid", + saveUninitialized: false, + resave: false, ++ cookie: { httpOnly: true, secure: true, sameSite: "lax", maxAge: 30 * 60 * 1000 } + })); + swig.setDefaults({ +- autoescape: false ++ autoescape: true + }); +--- a/app/routes/session.js ++++ b/app/routes/session.js +- req.session.userId = user._id; +- return res.redirect(user.isAdmin ? "/benefits" : "/dashboard"); ++ return req.session.regenerate(() => { ++ req.session.userId = user._id; ++ return res.redirect(user.isAdmin ? "/benefits" : "/dashboard"); ++ }); +``` + +**F7: password hashing** +```diff +--- a/app/data/user-dao.js ++++ b/app/data/user-dao.js +- password //received from request param ++ password: bcrypt.hashSync(password, bcrypt.genSaltSync(12)) +... +- return fromDB === fromUser; ++ return bcrypt.compareSync(fromUser, fromDB); +``` + +**F9: secrets from environment** +```diff +--- a/config/env/all.js ++++ b/config/env/all.js +- cookieSecret: "session_cookie_secret_key_here", +- cryptoKey: "a_secure_key_for_crypto_here", ++ cookieSecret: process.env.SESSION_SECRET, ++ cryptoKey: process.env.CRYPTO_KEY, +``` + +## Coverage Notes + +Reviewed every route handler, every DAO, the server bootstrap, configuration modules, the database seed script, and the templates that render user-controlled data. Third-party front-end bundles under `app/assets/vendor`, test fixtures, and the static tutorial pages were skipped as out of scope for code-level SAST. Dependency versions (marked 0.3.5, needle 2.2.4, mongodb 2.x, bcrypt-nodejs 0.0.3) were noted but not assessed; that belongs to the SCA skill. Memos rendering through `marked` with `sanitize:true` was traced but not rated as an independent finding, since its exploitability depends on the library version rather than the application code. No external references were needed. Confidence in this assessment is high: every finding was located in source and traced from an HTTP entry point to the sink, and the application's own inline comments corroborate each defect. \ No newline at end of file diff --git a/fuzz/corpus/parsers/secret-scanning-report.md b/fuzz/corpus/parsers/secret-scanning-report.md new file mode 100644 index 0000000..3716d1d --- /dev/null +++ b/fuzz/corpus/parsers/secret-scanning-report.md @@ -0,0 +1,126 @@ +# Secret Scanning Report + +## 1. Executive Summary +The OWASP NodeGoat repository (`https://github.com/OWASP/NodeGoat`) is an intentionally vulnerable training app, and its tracked files contain several hard-coded credentials that are live in the sense that they are used by the running application. The most significant is an RSA private key committed alongside its certificate and loaded by the server for TLS, followed by a hard-coded session cookie secret and symmetric encryption key that are identical in every deployment. A static OWASP ZAP API key and seeded admin/user passwords are also committed. No cloud provider keys, SaaS tokens, or `.env` files were found tracked. + +**Overall risk rating:** High + +| Severity | Count | +|----------|-------| +| High | 3 | +| Medium | 2 | +| Low | 1 | + +| Source | Count | +|--------|-------| +| code | 3 | +| config | 3 | +| history | 0 (not available) | +| docs | 0 | + +## 2. Scope +- **Paths scanned:** all tracked files under the repository root, including `app/`, `config/`, `artifacts/`, `test/`, `.github/workflows/`, `Dockerfile`, `docker-compose.yml`, `.travis.yml`, `app.json`, `README.md`, and other Markdown docs. Excluded per instructions: `node_modules/`, `.git/`, vendored assets, `package-lock.json`. +- **Version-control history:** NOT checked. The provided clone is a shallow clone containing a single commit, so `git log` could not reveal previously committed and later removed secrets. +- **Documentation sources:** Only in-repo Markdown and HTML tutorial pages were available. No Confluence or external documentation source was provided or reachable; this is a gap, not a pass. +- **Environment files:** `git ls-files` shows no `.env`, `.env.*`, `*.pem`, `*.p12`, or service-account JSON tracked. `.gitignore` covers `.env` and `.env.local` but not `*.key`, `*.pem`, or `*.crt`. + +## 3. Findings Register +| ID | Secret type | Location | Source | Validity | Severity | +|----|-------------|----------|--------|----------|----------| +| S1 | RSA private key (TLS) | `artifacts/cert/server.key:1` | config | Looks live | High | +| S2 | Session cookie signing secret | `config/env/all.js:8` | config | Looks live | High | +| S3 | Symmetric encryption key (AES-256) | `config/env/all.js:9` | config | Looks live | High | +| S4 | OWASP ZAP API key | `config/env/development.js:6`, `config/env/test.js:6` | config | Unclear | Medium | +| S5 | Seeded admin & user passwords | `artifacts/db-reset.js:18,27,35`; `test/e2e/fixtures/users/*.json`; `test/security/profile-test.js:37` | code | Looks live | Medium | +| S6 | Tutorial example cookie secret | `app/views/tutorial/a2.html:153`, `app/views/tutorial/a3.html:176` | docs | Placeholder | Low | + +## 4. Detailed Findings + +### [HIGH] S1: RSA private key in `artifacts/cert/server.key` +- **Type:** RSA private key (PEM, unencrypted). **Source:** config. **Validity:** Looks live. +- **Location:** `artifacts/cert/server.key:1` (paired with `artifacts/cert/server.crt`); consumed at `server.js:25-26`. +- **Evidence:** `-----BEG...` header, followed by an unencrypted 1024-bit RSA key body. +- **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. +- **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. +- **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. + +### [HIGH] S2: Session cookie signing secret in `config/env/all.js` +- **Type:** express-session cookie signing secret. **Source:** config. **Validity:** Looks live (used at runtime). +- **Location:** `config/env/all.js:8`, consumed by `server.js:82`. +- **Evidence:** `session_...` (a readable fixed string, not a placeholder that fails to run). +- **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. +- **Construct:** Fixed session-signing secret hard-coded in the shared default configuration module, with no environment-variable override and no production-specific value. +- **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. + +### [HIGH] S3: AES-256 encryption key in `config/env/all.js` +- **Type:** Symmetric encryption key (used with `aes256` for profile field encryption). **Source:** config. **Validity:** Looks live. +- **Location:** `config/env/all.js:9`; used in `app/data/profile-dao.js:26-37` for PBKDF2 derivation and `createCipheriv`. +- **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. +- **Construct:** Fixed symmetric encryption key hard-coded in the shared default configuration module and used directly to encrypt sensitive user profile fields. +- **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. + +### [MEDIUM] S4: OWASP ZAP API key in `config/env/development.js` and `config/env/test.js` +- **Type:** OWASP ZAP REST API key. **Source:** config. **Validity:** Unclear. +- **Location:** `config/env/development.js:6`, `config/env/test.js:6`; used throughout `test/security/profile-test.js`. +- **Evidence:** `v9dn0bal...` paired with a private-range host (`192.168.56.x:8080`). +- **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. +- **Construct:** High-entropy security-scanner API key hard-coded in development and test configuration files alongside the scanner's internal network address. +- **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. + +### [MEDIUM] S5: Seeded admin and user passwords in `artifacts/db-reset.js` +- **Type:** Application account passwords (plaintext). **Source:** code. **Validity:** Looks live. +- **Location:** `artifacts/db-reset.js:18,27,35`; duplicated in `test/e2e/fixtures/users/admin.json:3`, `test/e2e/fixtures/users/user.json`, and `test/security/profile-test.js:37`. +- **Evidence:** `Admin_1...`, `User1_1...`, `User2_1...` (also present as commented-out bcrypt hashes). +- **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. +- **Construct:** Default administrator and user passwords written in plaintext inside the database seed script that runs automatically on deploy. +- **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. + +### [LOW] S6: Example cookie secret in tutorial HTML +- **Type:** Example session secret in educational text. **Source:** docs. **Validity:** Placeholder. +- **Location:** `app/views/tutorial/a2.html:153`, `app/views/tutorial/a3.html:176`. +- **Evidence:** `s3Cur3` inside an illustrative `session({...})` snippet. +- **Exposure:** Public, but not used by any code path. Included for completeness; readers may copy the snippet verbatim. +- **Construct:** Short illustrative secret string embedded in an HTML tutorial code sample rather than in executable configuration. +- **Remediation:** No rotation needed. Replace with an obvious placeholder such as `` to discourage copy-paste. + +## 5. Documentation & Confluence Coverage +| Source | Reached? | Secrets found | +|--------|----------|---------------| +| `README.md` (in repo) | Yes | None (connection strings are `:` placeholders) | +| `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md` | Yes | None | +| `app/views/tutorial/*.html` (in-repo tutorial pages) | Yes | S6 (placeholder only) | +| Confluence / external wiki | Not provided, not reachable | Unknown, gap | + +## 6. Remediation Roadmap +**P0 – Rotate now** +1. S1: Generate a new TLS key pair for every deployment; never reuse the committed key. +2. S2: Generate a random session cookie secret per deployment and supply via environment. +3. S3: Generate a random AES key per deployment, supply via environment, re-encrypt stored profile data. +4. S4: Regenerate the ZAP API key on any machine that used the committed value. +5. S5: Change the seeded admin password on any instance that is not purely a disposable training sandbox. + +**P1 – Remove from working tree** +- Delete `artifacts/cert/server.key` from the repo; read key/cert paths from `TLS_KEY_PATH` / `TLS_CERT_PATH`. +- Replace literals in `config/env/all.js` with `process.env.*` reads that throw when `NODE_ENV=production` and the value is missing. +- Add `*.key`, `*.pem`, `*.p12`, `*.crt` to `.gitignore`. + +**P2 – History** +- This clone is shallow, so history was not reviewed. On the full repository, run a history scan (gitleaks or trufflehog) to confirm whether any additional secrets were committed and later removed. Because the repo is public, history rewriting offers little benefit; rotation is the effective control. + +**P3 – Secret management** +- For Heroku/Docker deployments, move all secrets to config vars / Docker secrets and document this in the README so forks do not inherit shared values. + +## 7. Prevention +- **`.gitignore`:** add `*.key`, `*.pem`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.crt`, `secrets.*`, and `**/service-account*.json`. The current file only ignores `.env` and `.env.local`. +- **Pre-commit scanning:** add a `gitleaks protect --staged` or `detect-secrets` pre-commit hook. None exists today. +- **CI secret detection:** add a gitleaks or trufflehog job to `.github/workflows/lint.yml` so pull requests fail on new secrets; the current workflows only lint and run E2E tests. +- **Fail-fast config:** in `config/config.js`, refuse to start in production when `cookieSecret`, `cryptoKey`, or TLS paths are absent, instead of silently falling back to shared defaults. +- **Seed data:** generate the admin password at seed time and read it from an environment variable, printing it once to stdout. +- **Training-app caveat:** since NodeGoat is intentionally vulnerable, keep the insecure behaviour available behind an explicit flag (for example `NODEGOAT_INSECURE_DEFAULTS=true`) so that the lesson remains but accidental real-world reuse is harder. + +## Coverage Notes +- **Reviewed:** all tracked source, config, IaC (Dockerfile, docker-compose, app.json), CI (GitHub Actions, Travis), test fixtures, seed scripts, README and tutorial HTML, with targeted grep for key prefixes, connection strings, webhook URLs, and private-key headers. +- **Skipped:** `node_modules/`, vendored front-end assets, `package-lock.json`, binary assets. Git history was not available (shallow single-commit clone). No Confluence or external docs were provided. +- **Not verified:** the certificate's subject and validity dates (an `openssl` inspection was not permitted in this environment); it is almost certainly a self-signed development certificate, which does not change the severity of the committed private key. +- **Confidence:** High for in-tree findings at quick depth; low for history and external documentation because those sources were not reachable. \ No newline at end of file diff --git a/fuzz/corpus/parsers/skill-django-sast.md b/fuzz/corpus/parsers/skill-django-sast.md new file mode 100644 index 0000000..a601c7b --- /dev/null +++ b/fuzz/corpus/parsers/skill-django-sast.md @@ -0,0 +1,34 @@ +--- +id: django-sast +name: SAST — Django Application Review +short_name: SAST (Django) +description: Django-specific static review whose findings join the SAST dashboard. +version: 1 +# Reuse the built-in SAST report format, so findings land in the SAST +# dashboard and its open/closed lifecycle. +output: sast +category: Frameworks +--- + +Perform a static security review of this Django application, focusing on the +mistakes that are specific to Django and that a generic SAST pass tends to miss: + +- **Raw SQL.** `raw()`, `extra()`, `RawSQL`, and `cursor.execute()` built with + string formatting or f-strings instead of parameters. +- **Template autoescaping.** `|safe`, `mark_safe`, `{% autoescape off %}` and + `format_html` misuse on user-controlled values. +- **CSRF.** `@csrf_exempt` on views that change state, and DRF views using + `SessionAuthentication` without CSRF enforcement. +- **Object-level authorization.** Views and DRF viewsets that fetch + `Model.objects.get(pk=...)` from the URL without scoping to the requesting + user, and `get_queryset()` methods that don't filter by owner or tenant. +- **Settings.** `DEBUG = True`, a hard-coded `SECRET_KEY`, permissive + `ALLOWED_HOSTS`, missing `SECURE_*` and session-cookie flags in production + settings. +- **Mass assignment.** `ModelForm` / `ModelSerializer` with `fields = "__all__"` + or `exclude` on models that have privilege or ownership fields. +- **Unsafe deserialization and file handling.** `pickle`, `yaml.load`, and + uploads saved under user-controlled names or served from `MEDIA_ROOT` + without validation. + +Report each finding with its taint path from the request to the sink. diff --git a/fuzz/corpus/parsers/skill-graphql-api-review.md b/fuzz/corpus/parsers/skill-graphql-api-review.md new file mode 100644 index 0000000..c116d73 --- /dev/null +++ b/fuzz/corpus/parsers/skill-graphql-api-review.md @@ -0,0 +1,34 @@ +--- +id: graphql-api-review +name: GraphQL API Security Review +short_name: GraphQL API +description: Reviews a GraphQL API for authorization gaps, query-cost abuse and schema exposure. +version: 1 +output: generic +category: API +--- + +Review the GraphQL API in this codebase as an attacker with a valid but +low-privilege account would approach it. Find the schema (SDL files, code-first +type definitions, or resolver maps) and the server setup first, then work +through these risks: + +- **Authorization in resolvers.** Check every query, mutation and field + resolver that returns or changes another user's data. Authorization done only + at the HTTP route or gateway is not enough: nested fields + (`user { orders { paymentMethod } }`) are reachable from any parent type. + Flag object-level and field-level checks that are missing or inconsistent. +- **Query cost and depth.** Look for query depth limits, complexity or cost + analysis, pagination caps (`first`/`last` maximums), and batching or alias + limits. Unbounded lists and recursive types without limits are a + denial-of-service finding. +- **Introspection and errors.** Is introspection enabled in production + configuration? Do error responses include stack traces, SQL, or field + suggestions that leak the schema? +- **Injection through arguments.** Trace resolver arguments into SQL, NoSQL, + shell, file paths or downstream HTTP calls without validation. +- **Persisted queries and CSRF.** If GET queries or simple content types are + accepted, check whether mutations can be triggered cross-site. + +For each finding, name the resolver or type and the file and line where the +check is missing, and give the concrete fix (the guard to add, and where). diff --git a/fuzz/corpus/runtime_ingest/batch.ndjson b/fuzz/corpus/runtime_ingest/batch.ndjson new file mode 100644 index 0000000..816d9cc --- /dev/null +++ b/fuzz/corpus/runtime_ingest/batch.ndjson @@ -0,0 +1,3 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +{"type": "load", "session": "11111111-2222-3333-4444-555555555555", "ecosystem": "PyPI", "package": "pyyaml", "version": "5.3", "path": "/app/.venv/lib/python3.12/site-packages/yaml", "first_seen": "2026-11-08T10:00:01Z"} +{"type": "hit", "session": "11111111-2222-3333-4444-555555555555", "finding_fingerprint": "fuzz-fp-1", "symbol": "yaml.load", "route": "POST /upload", "auth": "authenticated", "count": 42, "first_seen": "2026-11-08T10:05:00Z", "last_seen": "2026-11-08T15:59:00Z", "entry_frame": "app/upload.py:31", "stack_sample": ["site-packages/yaml/__init__.py:79", "app/upload.py:31"]} diff --git a/fuzz/corpus/runtime_ingest/crash-count-over-int64.ndjson b/fuzz/corpus/runtime_ingest/crash-count-over-int64.ndjson new file mode 100644 index 0000000..ca4741c --- /dev/null +++ b/fuzz/corpus/runtime_ingest/crash-count-over-int64.ndjson @@ -0,0 +1,2 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +{"type": "hit", "session": "11111111-2222-3333-4444-555555555555", "finding_fingerprint": "fuzz-fp-1", "symbol": "yaml.load", "route": "POST /upload", "auth": "authenticated", "count": 18446744073709551616, "first_seen": "2026-11-08T10:05:00Z", "last_seen": "2026-11-08T15:59:00Z", "entry_frame": "app/upload.py:31", "stack_sample": ["site-packages/yaml/__init__.py:79", "app/upload.py:31"]} diff --git a/fuzz/corpus/runtime_ingest/crash-deep-nesting.ndjson b/fuzz/corpus/runtime_ingest/crash-deep-nesting.ndjson new file mode 100644 index 0000000..3210494 --- /dev/null +++ b/fuzz/corpus/runtime_ingest/crash-deep-nesting.ndjson @@ -0,0 +1,2 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[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]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] diff --git a/fuzz/corpus/runtime_ingest/crash-int-over-4300-digits.ndjson b/fuzz/corpus/runtime_ingest/crash-int-over-4300-digits.ndjson new file mode 100644 index 0000000..e8f6fc6 --- /dev/null +++ b/fuzz/corpus/runtime_ingest/crash-int-over-4300-digits.ndjson @@ -0,0 +1,2 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +{"type":"hit","count":100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000} diff --git a/fuzz/corpus/runtime_ingest/crash-lone-surrogate.ndjson b/fuzz/corpus/runtime_ingest/crash-lone-surrogate.ndjson new file mode 100644 index 0000000..a0d9b80 --- /dev/null +++ b/fuzz/corpus/runtime_ingest/crash-lone-surrogate.ndjson @@ -0,0 +1,2 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +{"type": "session", "id": "s2", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "\ud800", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} diff --git a/fuzz/corpus/runtime_ingest/crash-surrogate-entry-frame.ndjson b/fuzz/corpus/runtime_ingest/crash-surrogate-entry-frame.ndjson new file mode 100644 index 0000000..17b6c33 --- /dev/null +++ b/fuzz/corpus/runtime_ingest/crash-surrogate-entry-frame.ndjson @@ -0,0 +1,2 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +{"type": "hit", "session": "11111111-2222-3333-4444-555555555555", "finding_fingerprint": "fuzz-fp-1", "symbol": "yaml.load", "route": "POST /upload", "auth": "authenticated", "count": 42, "first_seen": "2026-11-08T10:05:00Z", "last_seen": "2026-11-08T15:59:00Z", "entry_frame": "app/\udcff.py:3", "stack_sample": ["site-packages/yaml/__init__.py:79", "app/upload.py:31"]} diff --git a/fuzz/corpus/runtime_ingest/mixed-valid-and-invalid.ndjson b/fuzz/corpus/runtime_ingest/mixed-valid-and-invalid.ndjson new file mode 100644 index 0000000..9f8b2be --- /dev/null +++ b/fuzz/corpus/runtime_ingest/mixed-valid-and-invalid.ndjson @@ -0,0 +1,6 @@ +{"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +not json +{"type": "hit", "session": "unknown", "finding_fingerprint": "x", "symbol": "a.b", "count": 1} +{"type": "hit", "session": "11111111-2222-3333-4444-555555555555", "finding_fingerprint": "fuzz-fp-1", "symbol": "yaml.load", "route": "GET /users/42?token=x", "auth": "authenticated", "count": 42, "first_seen": "2026-11-08T10:05:00Z", "last_seen": "2026-11-08T15:59:00Z", "entry_frame": "app/upload.py:31", "stack_sample": ["site-packages/yaml/__init__.py:79", "app/upload.py:31"]} +{"type": "hit", "session": "11111111-2222-3333-4444-555555555555", "finding_fingerprint": "not-a-finding", "symbol": "yaml.load", "route": "POST /upload", "auth": "authenticated", "count": 42, "first_seen": "2026-11-08T10:05:00Z", "last_seen": "2026-11-08T15:59:00Z", "entry_frame": "app/upload.py:31", "stack_sample": ["site-packages/yaml/__init__.py:79", "app/upload.py:31"]} + diff --git a/fuzz/corpus/sarif_export/crash-location-line-5000-digits.jsonl b/fuzz/corpus/sarif_export/crash-location-line-5000-digits.jsonl new file mode 100644 index 0000000..a0f2e04 --- /dev/null +++ b/fuzz/corpus/sarif_export/crash-location-line-5000-digits.jsonl @@ -0,0 +1 @@ +{"skill_id": "sast", "severity": "High", "location_file": "a.py", "location_line": "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"} diff --git a/fuzz/corpus/sarif_export/nodegoat-findings.jsonl b/fuzz/corpus/sarif_export/nodegoat-findings.jsonl new file mode 100644 index 0000000..4920340 --- /dev/null +++ b/fuzz/corpus/sarif_export/nodegoat-findings.jsonl @@ -0,0 +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"} diff --git a/fuzz/corpus/sarif_export/paths-and-runtime.jsonl b/fuzz/corpus/sarif_export/paths-and-runtime.jsonl new file mode 100644 index 0000000..3abf94d --- /dev/null +++ b/fuzz/corpus/sarif_export/paths-and-runtime.jsonl @@ -0,0 +1,4 @@ +{"skill_id": "sast", "severity": "High", "cwe": "CWE-89, CWE-564", "title": "SQL injection", "location_file": "C:\\work\\app db.py", "location_line": "12"} +{"skill_id": "secret-scanning", "severity": "Critical", "secret_type": "AWS key", "location_file": "//server/share/ci.yml", "location_line": "0"} +{"skill_id": "sca-reachability", "severity": "Medium", "issue": "CVE-2020-1747", "package": "pyyaml", "runtime": {"state": "reached", "routes": [{"route": "POST /upload"}, {"route": "GET /health"}]}} +{"skill_id": "sast", "severity": "informational", "location_file": "/abs/a%b.py", "location_line": "7-9"} diff --git a/fuzz/corpus/skill_loader/builtin-sast.md b/fuzz/corpus/skill_loader/builtin-sast.md new file mode 100644 index 0000000..33db4ed --- /dev/null +++ b/fuzz/corpus/skill_loader/builtin-sast.md @@ -0,0 +1,87 @@ +--- +id: sast +name: SAST — Static Code Analysis +description: Code-level vulnerability review with taint paths, CWE mapping, and concrete fixes. +short_name: SAST +version: 1 +--- + +Perform a static application security review of the source code. Stay at +the code level — design gaps belong to the Security Architecture Review +skill and dependency risk to the SCA skill. + +Prioritize these classes, roughly in this order: + +1. **Injection.** SQL/NoSQL, OS command, LDAP, template, XPath, and header + injection. Trace from an untrusted source (HTTP request, file, env, + agent/LLM output) to a dangerous sink; report only where the path is + real and you can cite both ends. + +2. **Cross-site scripting & output encoding.** Unescaped rendering, + `dangerouslySetInnerHTML` / `|safe` / `v-html`, autoescaping disabled, + and raw HTML passthrough in Markdown or template renderers. + +3. **Path traversal & file handling.** Client-controlled filenames or + paths reaching filesystem APIs, unsafe archive extraction (zip-slip), + and unrestricted upload type/size. + +4. **Deserialization & dynamic execution.** `pickle`, `yaml.load`, + `eval`, `exec`, dynamic import, unsafe reflection, and template + injection via user-controlled template strings. + +5. **AuthN/AuthZ enforcement in code.** Missing checks on state-changing + handlers, IDOR (object lookups not scoped to the caller), and + privilege checks that run *after* a side effect. + +6. **Cryptography & randomness.** Weak or legacy algorithms, ECB mode, + static/reused IVs, `random` used for security purposes, homemade + crypto, and disabled TLS certificate verification. + +7. **SSRF & unsafe outbound requests.** User-controlled URLs, missing + host allowlists, and redirect-following into internal ranges. + +8. **Hardcoded credentials.** Note them here briefly — the Secret + Scanning skill covers this in depth. + +9. **Error handling & information leakage.** Stack traces or internal + detail returned to callers; secrets or tokens written to logs. + +For every finding give `file:line`, the exploit path in one or two +sentences, a CWE ID **only** when you are confident it applies, and a +concrete fix. Never report a finding you have not actually located in the +code — an empty report is far better than a fabricated one. + +Severity: **High** = exploitable and reachable from untrusted input. +**Medium** = exploitable given a stated precondition. **Low** = +defense-in-depth, or a real defect that isn't currently reachable. + +For every finding, also state a full CVSS v3.1 base vector (all eight +metrics: AV/AC/PR/UI/S/C/I/A) — you already know everything it takes from +tracing the finding itself, so reason through each one directly: + +- **AV** (Attack Vector): can the exploit path be reached over a network + (`N`), only from the adjacent network (`A`), only with local access + (`L`), or only with physical access (`P`)? An internet-facing HTTP + handler is `N`; a CLI flag only an operator on the host can set is `L`. +- **AC** (Attack Complexity): does exploitation work reliably as-is (`L`), + or does it depend on conditions outside the attacker's control — a race, + a specific config, information they'd have to gather first (`H`)? +- **PR** (Privileges Required): does the attacker need no account (`N`), + a regular authenticated account (`L`), or admin-level access (`H`) + before reaching this code path? +- **UI** (User Interaction): does exploitation require another person to + do something (click a link, open a file) (`R`), or does it fire with no + one else involved (`N`)? +- **S** (Scope): does exploiting this let the attacker affect resources + beyond what this component itself controls — e.g. a container escape, or + a vulnerable library affecting the whole host — (`C`), or does the + impact stay within this component's own security authority (`U`)? Most + application-level findings are `U`. +- **C/I/A** (Confidentiality/Integrity/Availability impact): for each, + none (`N`), some limited exposure/tampering/disruption (`L`), or total + compromise of that property (`H`) — judged from what this specific + finding actually lets an attacker read, change, or take down, not the + worst case for the whole application. + +Do not compute or state a numeric score yourself — only the vector; the +score is derived from it deterministically elsewhere. diff --git a/fuzz/corpus/skill_loader/crash-invalid-utf8.md b/fuzz/corpus/skill_loader/crash-invalid-utf8.md new file mode 100644 index 0000000..2fcff06 --- /dev/null +++ b/fuzz/corpus/skill_loader/crash-invalid-utf8.md @@ -0,0 +1,7 @@ +--- +id: broken-encoding +name: Broken +description: x +version: 1 +--- +Review ÿþ this. diff --git a/fuzz/corpus/skill_loader/django-sast.md b/fuzz/corpus/skill_loader/django-sast.md new file mode 100644 index 0000000..a601c7b --- /dev/null +++ b/fuzz/corpus/skill_loader/django-sast.md @@ -0,0 +1,34 @@ +--- +id: django-sast +name: SAST — Django Application Review +short_name: SAST (Django) +description: Django-specific static review whose findings join the SAST dashboard. +version: 1 +# Reuse the built-in SAST report format, so findings land in the SAST +# dashboard and its open/closed lifecycle. +output: sast +category: Frameworks +--- + +Perform a static security review of this Django application, focusing on the +mistakes that are specific to Django and that a generic SAST pass tends to miss: + +- **Raw SQL.** `raw()`, `extra()`, `RawSQL`, and `cursor.execute()` built with + string formatting or f-strings instead of parameters. +- **Template autoescaping.** `|safe`, `mark_safe`, `{% autoescape off %}` and + `format_html` misuse on user-controlled values. +- **CSRF.** `@csrf_exempt` on views that change state, and DRF views using + `SessionAuthentication` without CSRF enforcement. +- **Object-level authorization.** Views and DRF viewsets that fetch + `Model.objects.get(pk=...)` from the URL without scoping to the requesting + user, and `get_queryset()` methods that don't filter by owner or tenant. +- **Settings.** `DEBUG = True`, a hard-coded `SECRET_KEY`, permissive + `ALLOWED_HOSTS`, missing `SECURE_*` and session-cookie flags in production + settings. +- **Mass assignment.** `ModelForm` / `ModelSerializer` with `fields = "__all__"` + or `exclude` on models that have privilege or ownership fields. +- **Unsafe deserialization and file handling.** `pickle`, `yaml.load`, and + uploads saved under user-controlled names or served from `MEDIA_ROOT` + without validation. + +Report each finding with its taint path from the request to the sink. diff --git a/fuzz/corpus/skill_loader/graphql-api-review.md b/fuzz/corpus/skill_loader/graphql-api-review.md new file mode 100644 index 0000000..c116d73 --- /dev/null +++ b/fuzz/corpus/skill_loader/graphql-api-review.md @@ -0,0 +1,34 @@ +--- +id: graphql-api-review +name: GraphQL API Security Review +short_name: GraphQL API +description: Reviews a GraphQL API for authorization gaps, query-cost abuse and schema exposure. +version: 1 +output: generic +category: API +--- + +Review the GraphQL API in this codebase as an attacker with a valid but +low-privilege account would approach it. Find the schema (SDL files, code-first +type definitions, or resolver maps) and the server setup first, then work +through these risks: + +- **Authorization in resolvers.** Check every query, mutation and field + resolver that returns or changes another user's data. Authorization done only + at the HTTP route or gateway is not enough: nested fields + (`user { orders { paymentMethod } }`) are reachable from any parent type. + Flag object-level and field-level checks that are missing or inconsistent. +- **Query cost and depth.** Look for query depth limits, complexity or cost + analysis, pagination caps (`first`/`last` maximums), and batching or alias + limits. Unbounded lists and recursive types without limits are a + denial-of-service finding. +- **Introspection and errors.** Is introspection enabled in production + configuration? Do error responses include stack traces, SQL, or field + suggestions that leak the schema? +- **Injection through arguments.** Trace resolver arguments into SQL, NoSQL, + shell, file paths or downstream HTTP calls without validation. +- **Persisted queries and CSRF.** If GET queries or simple content types are + accepted, check whether mutations can be triggered cross-site. + +For each finding, name the resolver or type and the file and line where the +check is missing, and give the concrete fix (the guard to add, and where). diff --git a/fuzz/fuzz_config.py b/fuzz/fuzz_config.py new file mode 100644 index 0000000..df4961a --- /dev/null +++ b/fuzz/fuzz_config.py @@ -0,0 +1,76 @@ +"""Fuzz `~/.secfoo/config.toml` loading: file bytes -> SecfooConfig. + +Input: the raw bytes of a config.toml. + +Contract: a SecfooConfig whose every field has its declared type, or +ConfigError naming the bad key -- never another exception. The types matter +beyond load_config: `[defaults]` values reach `secfoo run`, and MCP server +values end up in a subprocess argument list (`claude mcp add`), where a +number or a nested table crashed instead of failing here. + + python fuzz/fuzz_config.py WORK fuzz/corpus/config -max_total_time=60 +""" + +from __future__ import annotations + +import tempfile +from pathlib import Path + +from _common import main + +from secfoo.settings import ( + MCP_TRANSPORTS, + VALID_FAIL_ON, + ConfigError, + MCPServerConfig, + SecfooConfig, + load_config, +) + +_PATH = Path(tempfile.mkdtemp(prefix="secfoo-fuzz-config-")) / "config.toml" + + +def _optional(value, kind) -> bool: + return value is None or isinstance(value, kind) + + +def _strings(values) -> bool: + return isinstance(values, list) and all(isinstance(v, str) for v in values) + + +def _string_table(table) -> bool: + return isinstance(table, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in table.items()) + + +def check(data: bytes) -> None: + _PATH.write_bytes(data) + try: + config = load_config(_PATH) + except ConfigError: + return + assert isinstance(config, SecfooConfig) + + defaults = config.defaults + assert _optional(defaults.agent, str) and _optional(defaults.depth, str) + assert defaults.timeout is None or (type(defaults.timeout) is int and defaults.timeout > 0) + assert _strings(defaults.exclude) + assert defaults.fail_on is None or defaults.fail_on in VALID_FAIL_ON + assert defaults.max_cost_usd is None or (type(defaults.max_cost_usd) is float and defaults.max_cost_usd > 0) + + assert isinstance(config.memory_enabled, bool) + assert _strings(config.skill_paths) + assert all(isinstance(m, str) and m.strip() for m in config.agent_models.values()) + assert all(type(n) is int and n > 0 for n in config.agent_max_input_tokens.values()) + + names = [server.name for server in config.mcp_servers] + assert len(names) == len(set(names)) + for server in config.mcp_servers: + assert isinstance(server, MCPServerConfig) and isinstance(server.name, str) + assert _optional(server.command, str) and _optional(server.url, str) + assert bool(server.command) != bool(server.url) + assert _strings(server.args) and _string_table(server.env) and _string_table(server.headers) + assert server.transport in MCP_TRANSPORTS + + +if __name__ == "__main__": + main(check) diff --git a/fuzz/fuzz_docext.py b/fuzz/fuzz_docext.py new file mode 100644 index 0000000..aa540dc --- /dev/null +++ b/fuzz/fuzz_docext.py @@ -0,0 +1,48 @@ +"""Fuzz uploaded-document text extraction (PDF / DOCX / PPTX). + +Input: one selector byte (value % 3 picks .pdf, .docx or .pptx), then the +file's bytes. Seeds are small real documents, so libFuzzer mutates valid +structure rather than starting from noise. + +Contract: extract_text returns a string -- "" for anything it can't read -- +and never raises; an upload must always succeed (docext.py's own rule). +Each input must finish within PER_INPUT_SECONDS. On CI, libFuzzer's +-timeout and -rss_limit_mb additionally catch hangs and decompression bombs. + + python fuzz/fuzz_docext.py WORK fuzz/corpus/docext -max_total_time=60 -timeout=30 +""" + +from __future__ import annotations + +import tempfile +import time +from pathlib import Path + +from _common import main + +from secfoo.docext import extract_text + +SUFFIXES = (".pdf", ".docx", ".pptx") +PER_INPUT_SECONDS = 30.0 +_DIR = Path(tempfile.mkdtemp(prefix="secfoo-fuzz-docext-")) + + +def split(data: bytes) -> tuple[str, bytes]: + return SUFFIXES[data[0] % len(SUFFIXES)], data[1:] + + +def check(data: bytes) -> None: + if not data: + return + suffix, body = split(data) + path = _DIR / f"upload{suffix}" + path.write_bytes(body) + started = time.monotonic() + text = extract_text(path) + elapsed = time.monotonic() - started + assert isinstance(text, str) + assert elapsed < PER_INPUT_SECONDS, f"{suffix} extraction took {elapsed:.1f}s" + + +if __name__ == "__main__": + main(check) diff --git a/fuzz/fuzz_parsers.py b/fuzz/fuzz_parsers.py index 54b0f37..da40914 100644 --- a/fuzz/fuzz_parsers.py +++ b/fuzz/fuzz_parsers.py @@ -9,35 +9,34 @@ Run locally (Linux or macOS with clang): pip install atheris - python fuzz/fuzz_parsers.py -max_total_time=60 + python fuzz/fuzz_parsers.py WORK fuzz/corpus/parsers -max_total_time=60 -Any crash is written to the current directory as crash-; reproduce -with `python fuzz/fuzz_parsers.py crash-`. +Any crash is written to the current directory as crash-; reproduce it +on any platform, with or without Atheris, with +`python fuzz/fuzz_parsers.py crash-`. See fuzz/_common.py. """ from __future__ import annotations -import sys +from _common import main -import atheris +from secfoo.report.context_coverage import ( + MAX_NOTES_CHARS, + MAX_ROWS, + MAX_SOURCE_CHARS, + MAX_TYPE_CHARS, + parse_documentation_coverage, +) +from secfoo.report.markdown import MalformedReportError +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 -with atheris.instrument_imports(): - from secfoo.report.context_coverage import ( - MAX_NOTES_CHARS, - MAX_ROWS, - MAX_SOURCE_CHARS, - MAX_TYPE_CHARS, - parse_documentation_coverage, - ) - from secfoo.report.markdown import MalformedReportError - 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 - -def test_one_input(data: bytes) -> None: - provider = atheris.FuzzedDataProvider(data) - text = provider.ConsumeUnicodeNoSurrogates(4096) +def check(data: bytes) -> None: + # The first 4096 characters, as atheris' ConsumeUnicodeNoSurrogates(4096) + # gave before; the corpus is real reports, so decode them as text. + text = data.decode("utf-8", errors="replace")[:4096] # Report parsers may reject malformed structure only with the typed error. try: @@ -70,10 +69,5 @@ def test_one_input(data: bytes) -> None: assert normalize_severity(normalised) == normalised -def main() -> None: - atheris.Setup(sys.argv, test_one_input) - atheris.Fuzz() - - if __name__ == "__main__": - main() + main(check) diff --git a/fuzz/fuzz_runtime_ingest.py b/fuzz/fuzz_runtime_ingest.py new file mode 100644 index 0000000..0f23ad7 --- /dev/null +++ b/fuzz/fuzz_runtime_ingest.py @@ -0,0 +1,55 @@ +"""Fuzz runtime evidence ingest (#53, #66): an NDJSON batch -> stored events. + +Input: the request body of `POST /api/runtime/v1/events` (or a file for +`secfoo runtime ingest`), after decompression. + +Contract: what the API does with a batch -- decode, fill in app/env, then +`ingest_events` -- never raises. Every non-blank line is either stored or +listed as skipped with a reason, so one bad line can't roll back the rest +of the batch (which, through the API, was a 500). + + python fuzz/fuzz_runtime_ingest.py WORK fuzz/corpus/runtime_ingest -max_total_time=60 +""" + +from __future__ import annotations + +import tempfile +from pathlib import Path + +from _common import main + +from secfoo.runtime.api import _with_app_env +from secfoo.runtime.evidence import ingest_events +from secfoo.storage.repository import RunRepository + +FINGERPRINT = "fuzz-fp-1" # an SCA finding that exists, so valid hits are stored, not skipped + +_repo = RunRepository(db_path=Path(tempfile.mkdtemp(prefix="secfoo-fuzz-ingest-")) / "fuzz.sqlite") +_project = _repo.upsert_project("/fuzz", "fuzz", "local") +_run = _repo.create_run(project_id=_project, skill_id="sca-reachability", skill_name="SCA", agent_id="claude", + confluence_urls=[]) +_repo.upsert_sca_finding(project_id=_project, fingerprint=FINGERPRINT, run_id=_repo.get_run(_run).id, + current_ref="D1", package="fuzz-pkg", severity="High") + + +# Tables ingest writes. Cleared before every input so each one is judged on its +# own: otherwise sessions stored by earlier inputs change how later lines are +# handled, and a crash libFuzzer reports would not reproduce from its file. +_INGEST_TABLES = ("runtime_evidence", "runtime_packages", "runtime_sessions") + + +def check(data: bytes) -> None: + for table in _INGEST_TABLES: + _repo.connection.execute(f"DELETE FROM {table}") # noqa: S608 -- fixed table names + _repo.connection.commit() + lines = data.decode("utf-8", errors="replace").splitlines() # exactly as post_events decodes + lines = _with_app_env(lines, "fuzz-app", "fuzz-env") + report = ingest_events(_repo.connection, _project, lines) + non_blank = sum(1 for line in lines if line.strip()) + assert report.stored + len(report.skipped) == non_blank + for number, reason in report.skipped: + assert 1 <= number <= len(lines) and isinstance(reason, str) and reason + + +if __name__ == "__main__": + main(check) diff --git a/fuzz/fuzz_sarif_export.py b/fuzz/fuzz_sarif_export.py new file mode 100644 index 0000000..882c97e --- /dev/null +++ b/fuzz/fuzz_sarif_export.py @@ -0,0 +1,94 @@ +"""Fuzz `secfoo findings export`: finding records -> SARIF 2.1.0 and JSONL. + +Input: JSON Lines, one finding record per line -- the shape +`secfoo findings export --format jsonl` writes, so the seed corpus is real +exports. Each record is reduced to what a database row can hold (string, +number or null values; `skill_id` always a string; a well-formed `runtime` +block on SCA findings), because that's all the exporter ever receives. + +Contract: for any such records, +- findings_to_sarif returns a document that validates against the SARIF + 2.1.0 schema, with one result per record and every ruleIndex pointing at + its ruleId, with or without --runtime-priority; +- findings_to_jsonl writes one line per record that parses back to it; +- neither mutates the records. + + python fuzz/fuzz_sarif_export.py WORK fuzz/corpus/sarif_export -max_total_time=60 +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path + +from _common import main +from jsonschema import Draft7Validator, FormatChecker + +from secfoo.report.jsonl import findings_to_jsonl +from secfoo.report.sarif import findings_to_sarif + +SCHEMA_PATH = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "sarif-schema-2.1.0.json" +VALIDATOR = Draft7Validator(json.loads(SCHEMA_PATH.read_text(encoding="utf-8")), format_checker=FormatChecker()) + + +def _scalar(value: object) -> bool: + if isinstance(value, float): + return not math.isnan(value) # SQLite stores NaN as NULL; it never reaches the exporter + return value is None or isinstance(value, (str, int)) + + +def _runtime(value: object) -> dict | None: + """RuntimeLookup.as_sarif() output: a state and route templates.""" + if not isinstance(value, dict) or not isinstance(value.get("state"), str): + return None + routes = value.get("routes", []) + if not isinstance(routes, list) or not all(isinstance(r, dict) and isinstance(r.get("route"), str) for r in routes): + return None + return {"state": value["state"], "routes": [{"route": r["route"]} for r in routes]} + + +def records_from(data: bytes) -> list[dict]: + records = [] + for line in data.decode("utf-8", errors="replace").split("\n"): + try: + value = json.loads(line) + except (ValueError, RecursionError): + continue + if not isinstance(value, dict): + continue + record = {str(k): v for k, v in value.items() if _scalar(v)} + record["skill_id"] = str(value.get("skill_id") or "sast") + runtime = _runtime(value.get("runtime")) + if runtime is not None: + record["runtime"] = runtime + records.append(record) + return records + + +def check(data: bytes) -> None: + records = records_from(data) + before = json.dumps(records, sort_keys=True) + + for runtime_priority in (False, True): + document = findings_to_sarif(records, runtime_priority=runtime_priority) + written = json.loads(json.dumps(document, sort_keys=True)) # exactly what the CLI writes + VALIDATOR.validate(written) + run = written["runs"][0] + rules, results = run["tool"]["driver"]["rules"], run["results"] + assert len(results) == len(records) + assert len({rule["id"] for rule in rules}) == len(rules) + for result in results: + assert rules[result["ruleIndex"]]["id"] == result["ruleId"] + + text = findings_to_jsonl(records) + lines = text.split("\n")[:-1] if text else [] + assert len(lines) == len(records) + for line, record in zip(lines, records): + assert json.loads(line) == json.loads(json.dumps(record)) + + assert json.dumps(records, sort_keys=True) == before # export never mutates its input + + +if __name__ == "__main__": + main(check) diff --git a/fuzz/fuzz_skill_loader.py b/fuzz/fuzz_skill_loader.py new file mode 100644 index 0000000..cde5e98 --- /dev/null +++ b/fuzz/fuzz_skill_loader.py @@ -0,0 +1,39 @@ +"""Fuzz the custom skill loader (#79, #93): skill file bytes -> Skill. + +Input: the raw bytes of a skill file (frontmatter + instructions), exactly +what `--skill-file`, a skills folder or a `--skill-file ` download hands +to `_build_skill`. + +Contract: a Skill, or SkillLoadError naming the problem -- never another +exception (callers only catch SkillLoadError). A custom skill that loads has +a kebab-case id, a name, a description, instructions and an integer version, +and its sha256 is of the exact bytes given. + + python fuzz/fuzz_skill_loader.py WORK fuzz/corpus/skill_loader -max_total_time=60 +""" + +from __future__ import annotations + +import hashlib + +from _common import main + +from secfoo.skills.loader import ID_RE, Skill, SkillLoadError, _build_skill + + +def check(data: bytes) -> None: + for source in ("user", "url", "builtin"): # builtin skips the custom-skill checks; all must be total + try: + skill = _build_skill(data, source=source, path=None, origin="") + except SkillLoadError: + continue + assert isinstance(skill, Skill) + assert isinstance(skill.version, int) + assert skill.sha256 == hashlib.sha256(data).hexdigest() + if source != "builtin": + assert ID_RE.match(skill.id) + assert skill.name and skill.description and skill.body + + +if __name__ == "__main__": + main(check) diff --git a/fuzz/make_seed_corpus.py b/fuzz/make_seed_corpus.py new file mode 100644 index 0000000..ab1fa00 --- /dev/null +++ b/fuzz/make_seed_corpus.py @@ -0,0 +1,222 @@ +"""Write the seed corpora in fuzz/corpus//. + + python fuzz/make_seed_corpus.py + +Seeds are real inputs (the sample exports and reports in examples/, the +documented config.toml, small real PDF/DOCX/PPTX files) so fuzzing starts +from valid structure. `crash-*` files are the reproducers of crashes the +harnesses found (#121); tests/test_property_fuzz_targets.py replays every +corpus file on every platform, so a fixed crash can't come back unnoticed. + +Rerunning overwrites these files; libFuzzer's own discoveries go to the +WORK folder CI passes first, never here. +""" + +from __future__ import annotations + +import io +import json +import shutil +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CORPUS = ROOT / "fuzz" / "corpus" +EXAMPLES = ROOT / "examples" + +SESSION = {"type": "session", "id": "11111111-2222-3333-4444-555555555555", "language": "python", + "runtime": "3.12.4", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", + "ended_at": "2026-11-08T16:00:00Z", "app": "payments-api", "env": "prod", "instance": "pod-1", + "sensor_version": "0.1.0", "app_functions_total": 1840, "app_functions_executed": 1362} +LOAD = {"type": "load", "session": SESSION["id"], "ecosystem": "PyPI", "package": "pyyaml", "version": "5.3", + "path": "/app/.venv/lib/python3.12/site-packages/yaml", "first_seen": "2026-11-08T10:00:01Z"} +HIT = {"type": "hit", "session": SESSION["id"], "finding_fingerprint": "fuzz-fp-1", "symbol": "yaml.load", + "route": "POST /upload", "auth": "authenticated", "count": 42, "first_seen": "2026-11-08T10:05:00Z", + "last_seen": "2026-11-08T15:59:00Z", "entry_frame": "app/upload.py:31", + "stack_sample": ["site-packages/yaml/__init__.py:79", "app/upload.py:31"]} + + +def _ndjson(*events: dict | str) -> bytes: + return "".join((e if isinstance(e, str) else json.dumps(e)) + "\n" for e in events).encode("utf-8") + + +def _write(harness: str, name: str, data: bytes) -> None: + folder = CORPUS / harness + folder.mkdir(parents=True, exist_ok=True) + (folder / name).write_bytes(data) + + +def _copy(harness: str, source: Path, name: str | None = None) -> None: + folder = CORPUS / harness + folder.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, folder / (name or source.name)) + + +def parsers() -> None: + for report in ("sast-report.md", "secret-scanning-report.md"): + _copy("parsers", EXAMPLES / "sample-output" / "nodegoat" / report) + for skill in sorted((EXAMPLES / "skills").glob("*.md")): + _copy("parsers", skill, f"skill-{skill.name}") + + +def sarif_export() -> None: + lines = (EXAMPLES / "sample-output" / "nodegoat" / "findings.jsonl").read_text(encoding="utf-8").splitlines() + _write("sarif_export", "nodegoat-findings.jsonl", ("\n".join(lines) + "\n").encode("utf-8")) + _write("sarif_export", "paths-and-runtime.jsonl", _ndjson( + {"skill_id": "sast", "severity": "High", "cwe": "CWE-89, CWE-564", "title": "SQL injection", + "location_file": "C:\\work\\app db.py", "location_line": "12"}, + {"skill_id": "secret-scanning", "severity": "Critical", "secret_type": "AWS key", + "location_file": "//server/share/ci.yml", "location_line": "0"}, + {"skill_id": "sca-reachability", "severity": "Medium", "issue": "CVE-2020-1747", "package": "pyyaml", + "runtime": {"state": "reached", "routes": [{"route": "POST /upload"}, {"route": "GET /health"}]}}, + {"skill_id": "sast", "severity": "informational", "location_file": "/abs/a%b.py", "location_line": "7-9"}, + )) + # Crash reproducer: int() refuses strings over 4300 digits. + _write("sarif_export", "crash-location-line-5000-digits.jsonl", _ndjson( + {"skill_id": "sast", "severity": "High", "location_file": "a.py", "location_line": "1" * 5000})) + + +def skill_loader() -> None: + for skill in sorted((EXAMPLES / "skills").glob("*.md")): + _copy("skill_loader", skill) + _copy("skill_loader", ROOT / "src" / "secfoo" / "skills" / "definitions" / "sast.md", "builtin-sast.md") + # Crash reproducer: invalid UTF-8 escaped _build_skill as UnicodeDecodeError. + _write("skill_loader", "crash-invalid-utf8.md", + b"---\nid: broken-encoding\nname: Broken\ndescription: x\nversion: 1\n---\nReview \xff\xfe this.\n") + + +DOCUMENTED_CONFIG = """\ +[defaults] +agent = "claude" +depth = "quick" +exclude = ["vendor/", "some-cloned-repo/"] +fail_on = "high" +max_cost_usd = 2.00 + +[agents.claude] +model = "claude-sonnet-4-6" + +[agents.api] +max_input_tokens = 150000 + +[[mcp_servers]] +name = "Atlassian-Rovo-MCP" +command = "npx" +args = ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"] + +[[mcp_servers]] +name = "wiki" +url = "https://wiki.internal/mcp" +transport = "http" +headers = { Authorization = "Bearer x" } + +[skills] +paths = ["~/team-skills"] + +[memory] +enabled = false +""" + +CONFIG_CRASHES = { + # Each escaped load_config as something other than ConfigError. + "crash-defaults-not-a-table.toml": b"defaults = 1\n", + "crash-mcp-servers-string.toml": b"mcp_servers = 'x'\n", + "crash-mcp-servers-table.toml": b"[mcp_servers]\nname = 'a'\ncommand = 'x'\n", + "crash-mcp-name-list.toml": b"[[mcp_servers]]\nname = [1]\ncommand = 'x'\n", + "crash-invalid-utf8.toml": b"[defaults]\nagent = \"\xff\xfe\"\n", + # Loaded, then crashed later in a subprocess argument list / `secfoo run`. + "crash-mcp-args-number.toml": b"[[mcp_servers]]\nname = 'a'\ncommand = 'npx'\nargs = [1, 2]\n", + "crash-mcp-command-number.toml": b"[[mcp_servers]]\nname = 'a'\ncommand = 5\n", + "crash-mcp-env-table.toml": b"[[mcp_servers]]\nname = 'a'\ncommand = 'x'\nenv = { A = { B = 1 } }\n", + "crash-defaults-timeout-string.toml": b"[defaults]\ntimeout = 'soon'\n", +} + + +def config() -> None: + _write("config", "documented.toml", DOCUMENTED_CONFIG.encode("utf-8")) + _write("config", "empty.toml", b"") + for name, data in CONFIG_CRASHES.items(): + _write("config", name, data) + + +def docext() -> None: + import docx + from pptx import Presentation + from pptx.util import Inches + from pypdf import PdfWriter + + document = docx.Document() + document.add_paragraph("SOC 2 Type II report: access control and encryption at rest.") + table = document.add_table(rows=2, cols=2) + table.cell(0, 0).text, table.cell(0, 1).text = "Control", "Status" + table.cell(1, 0).text, table.cell(1, 1).text = "MFA", "Implemented" + buffer = io.BytesIO() + document.save(buffer) + _write("docext", "report.docx.bin", bytes([1]) + buffer.getvalue()) + + presentation = Presentation() + slide = presentation.slides.add_slide(presentation.slide_layouts[5]) + slide.shapes.title.text = "Pen test summary" + shape = slide.shapes.add_table(2, 2, Inches(1), Inches(2), Inches(6), Inches(1)).table + shape.cell(0, 0).text, shape.cell(0, 1).text = "Finding", "Severity" + shape.cell(1, 0).text, shape.cell(1, 1).text = "XSS", "High" + buffer = io.BytesIO() + presentation.save(buffer) + _write("docext", "summary.pptx.bin", bytes([2]) + buffer.getvalue()) + + writer = PdfWriter() + writer.add_blank_page(width=200, height=200) + buffer = io.BytesIO() + writer.write(buffer) + _write("docext", "blank.pdf.bin", bytes([0]) + buffer.getvalue()) + # A hand-written PDF with a text content stream, so extraction has text to find. + _write("docext", "text.pdf.bin", bytes([0]) + _text_pdf("ISO 27001 certificate")) + + +def _text_pdf(text: str) -> bytes: + stream = f"BT /F1 12 Tf 20 100 Td ({text}) Tj ET".encode("ascii") + objects = [ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + (b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Contents 4 0 R " + b"/Resources << /Font << /F1 5 0 R >> >> >>"), + b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ] + out, offsets = b"%PDF-1.4\n", [] + for number, body in enumerate(objects, start=1): + offsets.append(len(out)) + out += f"{number} 0 obj\n".encode() + body + b"\nendobj\n" + xref = len(out) + out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode() + out += b"".join(f"{offset:010d} 00000 n \n".encode() for offset in offsets) + out += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode() + return out + + +def runtime_ingest() -> None: + _write("runtime_ingest", "batch.ndjson", _ndjson(SESSION, LOAD, HIT)) + _write("runtime_ingest", "mixed-valid-and-invalid.ndjson", _ndjson( + SESSION, "not json", {"type": "hit", "session": "unknown", "finding_fingerprint": "x", "symbol": "a.b", + "count": 1}, + {**HIT, "route": "GET /users/42?token=x"}, {**HIT, "finding_fingerprint": "not-a-finding"}, "")) + # Crash reproducers. Each used to roll back the whole batch (a 500 from the + # ingest API); now the bad line is skipped and the session line is kept. + _write("runtime_ingest", "crash-deep-nesting.ndjson", _ndjson(SESSION, "[" * 20000 + "]" * 20000)) + _write("runtime_ingest", "crash-int-over-4300-digits.ndjson", + _ndjson(SESSION, '{"type":"hit","count":1' + "0" * 5000 + "}")) + _write("runtime_ingest", "crash-lone-surrogate.ndjson", + _ndjson(SESSION, json.dumps({**SESSION, "id": "s2", "app": "\ud800"}))) + _write("runtime_ingest", "crash-count-over-int64.ndjson", _ndjson(SESSION, {**HIT, "count": 2**64})) + _write("runtime_ingest", "crash-surrogate-entry-frame.ndjson", + _ndjson(SESSION, json.dumps({**HIT, "entry_frame": "app/\udcff.py:3"}))) + + +def main() -> None: + for build in (parsers, sarif_export, skill_loader, config, docext, runtime_ingest): + build() + for folder in sorted(p for p in CORPUS.iterdir() if p.is_dir()): + print(f"{folder.relative_to(ROOT)}: {len(list(folder.iterdir()))} file(s)") + + +if __name__ == "__main__": + main() diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 0b6e39b..5219955 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -29,6 +29,7 @@ from secfoo.context_run import resolve_run_context from secfoo.context_sources import ContextSourceError from secfoo.cost import format_cost, format_tokens, sum_optional +from secfoo.report.jsonl import findings_to_jsonl from secfoo.report.sarif import findings_to_sarif from secfoo.runner import _project_display_name, already_scanned_skills, execute_runs from secfoo.settings import CONFIG_PATH, ConfigError, load_config @@ -451,6 +452,16 @@ def run( if no_memory: memory_module.disable_for_this_process() + # config.toml names these as plain strings; an unknown one used to escape + # as a ValueError traceback from the enum (#121). Only checked when the + # config value is actually used: a --agent / --depth flag always wins. + for key, value, choices, flag in (("agent", file_defaults.agent, AgentId, agent), + ("depth", file_defaults.depth, DepthId, depth)): + if flag is None and value and value not in {c.value for c in choices}: + err_console.print(f"[red]Error in {CONFIG_PATH}:[/] defaults.{key} must be one of " + f"{', '.join(c.value for c in choices)}, got {value!r}") + raise typer.Exit(code=1) + if agent is None: if file_defaults.agent: agent = AgentId(file_defaults.agent) @@ -1889,8 +1900,7 @@ def findings_export( if format is FindingsFormat.SARIF: text = json.dumps(findings_to_sarif(records, runtime_priority=runtime_priority), indent=2, sort_keys=True) + "\n" else: - lines = [json.dumps(record, sort_keys=True) for record in records] - text = "\n".join(lines) + ("\n" if lines else "") + text = findings_to_jsonl(records) if output is None: sys.stdout.write(text) return diff --git a/src/secfoo/report/jsonl.py b/src/secfoo/report/jsonl.py new file mode 100644 index 0000000..0dd1756 --- /dev/null +++ b/src/secfoo/report/jsonl.py @@ -0,0 +1,16 @@ +"""Serialize exported structured findings as JSON Lines, without I/O. + +One JSON object per line, keys sorted, so `secfoo findings export` output is +stable across runs and diffs cleanly. Kept beside sarif.py so both export +formats can be fuzzed directly (#121). +""" + +from __future__ import annotations + +import json + + +def findings_to_jsonl(records: list[dict]) -> str: + """Every record as one line; "" for no records, else newline-terminated.""" + lines = [json.dumps(record, sort_keys=True) for record in records] + return "\n".join(lines) + ("\n" if lines else "") diff --git a/src/secfoo/report/sarif.py b/src/secfoo/report/sarif.py index 2bea2e8..f6dbdf8 100644 --- a/src/secfoo/report/sarif.py +++ b/src/secfoo/report/sarif.py @@ -31,10 +31,13 @@ def _location(record: dict) -> dict | None: else: uri = quote(path, safe="/") physical = {"artifactLocation": {"uri": uri}} - # Stored legacy/model-authored lines are not guaranteed to be numeric. + # Stored legacy/model-authored lines are not guaranteed to be numeric -- + # or short: int() refuses more than 4300 digits (#121), and no source + # file has a billion lines. line = str(record.get("location_line") or "").strip() - if re.fullmatch(r"[0-9]+", line) and int(line) > 0: - physical["region"] = {"startLine": int(line)} + digits = line.lstrip("0") # "0000000042" is line 42; the length cap is on the value + if re.fullmatch(r"[0-9]+", line) and 1 <= len(digits) <= 9: + physical["region"] = {"startLine": int(digits)} return {"physicalLocation": physical} diff --git a/src/secfoo/runtime/api.py b/src/secfoo/runtime/api.py index d628cd4..686f464 100644 --- a/src/secfoo/runtime/api.py +++ b/src/secfoo/runtime/api.py @@ -160,7 +160,7 @@ def _with_app_env(lines: list[str], app: str | None, env: str | None) -> list[st for line in lines: try: event = json.loads(line) - except json.JSONDecodeError: + except (ValueError, RecursionError): # JSONDecodeError, 4300+ digit ints, deep nesting (#121) out.append(line) # ingest_events reports it with its line number continue if isinstance(event, dict) and event.get("type") == "session": @@ -200,13 +200,17 @@ def _bounded_text(payload: dict, key: str, *, required: bool = False) -> str | N return None if not isinstance(value, str) or not value.strip() or len(value) > 200: raise _error(422, f"{key!r} must be a non-empty string of at most 200 characters") + try: + value.encode("utf-8") # "\ud800" decodes to a lone surrogate SQLite can't store (#121) + except UnicodeEncodeError: + raise _error(422, f"{key!r} must be valid Unicode text") from None return value def _count(payload: dict, key: str) -> int: value = payload.get(key, 0) - if isinstance(value, bool) or not isinstance(value, int) or value < 0: - raise _error(422, f"{key!r} must be a non-negative integer") + if isinstance(value, bool) or not isinstance(value, int) or value < 0 or value > 2**63 - 1: + raise _error(422, f"{key!r} must be a non-negative integer that fits in 64 bits") return value @@ -214,7 +218,7 @@ def _count(payload: dict, key: str) -> int: async def post_heartbeat(request: Request, who: Annotated[_Caller, Depends(caller)]): try: payload = json.loads(await _read_body(request) or b"{}") - except json.JSONDecodeError: + except (ValueError, RecursionError): # JSONDecodeError, 4300+ digit ints, deep nesting (#121) raise _error(400, "heartbeat body must be JSON") from None if not isinstance(payload, dict): raise _error(400, "heartbeat body must be a JSON object") diff --git a/src/secfoo/runtime/evidence.py b/src/secfoo/runtime/evidence.py index 49cee00..02200b2 100644 --- a/src/secfoo/runtime/evidence.py +++ b/src/secfoo/runtime/evidence.py @@ -47,6 +47,7 @@ MAX_LINE_BYTES = 64 * 1024 MAX_TEXT = 1024 MAX_STACK_FRAMES = 50 +MAX_COUNT = 2**63 - 1 # SQLite INTEGER; anything larger can't be stored _FRAME_RE = re.compile(rf"^\S.{{0,{MAX_TEXT - 8}}}:\d+$") _CONCRETE_URL_RE = re.compile(r"://|[?#]") @@ -82,9 +83,20 @@ def _text(event: dict, key: str, *, required: bool = False) -> str | None: raise EvidenceError(f"{key!r} must be a non-empty string") if len(value) > MAX_TEXT: raise EvidenceError(f"{key!r} is longer than {MAX_TEXT} characters") + _require_utf8(value, key) return value +def _require_utf8(value: str, key: str) -> None: + """JSON escapes like "\\ud800" decode to lone surrogates, which SQLite + can't store; without this the whole batch failed with UnicodeEncodeError + (#121).""" + try: + value.encode("utf-8") + except UnicodeEncodeError: + raise EvidenceError(f"{key!r} must be valid Unicode text (no lone surrogates)") from None + + def _timestamp(event: dict, key: str, *, required: bool = False) -> str | None: value = _text(event, key, required=required) if value is None: @@ -105,12 +117,15 @@ def _count(event: dict, key: str, *, required: bool = False, minimum: int = 0) - return None if isinstance(value, bool) or not isinstance(value, int) or value < minimum: raise EvidenceError(f"{key!r} must be an integer >= {minimum}") + if value > MAX_COUNT: + raise EvidenceError(f"{key!r} must be at most {MAX_COUNT}") return value def _frame(value: object, key: str) -> str: if not isinstance(value, str) or not _FRAME_RE.match(value): raise EvidenceError(f"{key!r} frames must be 'file:line', never variables or arguments") + _require_utf8(value, key) return value @@ -194,11 +209,23 @@ def parse_lines(lines: Iterable[str]) -> Iterator[tuple[int, dict | None, str | yield number, None, f"line is longer than {MAX_LINE_BYTES} bytes" continue try: - yield number, validate_event(json.loads(raw)), None + decoded = json.loads(raw) except json.JSONDecodeError as exc: yield number, None, f"not valid JSON ({exc.msg})" + continue + except (ValueError, RecursionError) as exc: + # json.loads raises these, not JSONDecodeError, for an integer over + # 4300 digits or nesting deeper than the stack. Uncaught, one such + # line rolled back the whole batch (a 500 on the ingest API, #121). + # Only the decode is covered: a bug in validation must surface. + yield number, None, f"not valid JSON ({exc.__class__.__name__})" + continue + try: + event = validate_event(decoded) except EvidenceError as exc: yield number, None, str(exc) + continue + yield number, event, None # ---------- storage ---------- diff --git a/src/secfoo/settings.py b/src/secfoo/settings.py index 0509e97..a57a899 100644 --- a/src/secfoo/settings.py +++ b/src/secfoo/settings.py @@ -81,7 +81,51 @@ class SecfooConfig: skill_paths: list[str] = field(default_factory=list) +MCP_TRANSPORTS = ("stdio", "sse", "http") + + +def _check_mcp_types(name: str, raw: dict) -> dict: + """These values end up in a subprocess argument list (`claude mcp add`, + `gemini mcp add`) or an agent's JSON config, where a number or a nested + table crashed with TypeError instead of naming the bad key (#121). + + Returns `raw` with the shapes that have always worked normalised rather + than rejected: a blank `command`/`url` is unset, scalar `env`/`headers` + values (`PORT = 8080`, `DEBUG = true`) become strings. Only values that + used to crash raise ConfigError.""" + raw = dict(raw) + for key in ("command", "url"): + value = raw.get(key) + if value is None: + continue + if not isinstance(value, str): + raise ConfigError(f"mcp_servers.{name}.{key} must be a string") + if not value.strip(): + raw[key] = None + args = raw.get("args", []) + if not isinstance(args, list) or not all(isinstance(a, str) for a in args): + raise ConfigError(f"mcp_servers.{name}.args must be an array of strings") + for key in ("env", "headers"): + table = raw.get(key, {}) + if not isinstance(table, dict): + raise ConfigError(f"mcp_servers.{name}.{key} must be a table") + normalised = {} + for k, v in table.items(): + if isinstance(v, bool): + normalised[k] = "true" if v else "false" + elif isinstance(v, (str, int, float)): + normalised[k] = str(v) + else: + raise ConfigError(f"mcp_servers.{name}.{key}.{k} must be a string, number or boolean") + raw[key] = normalised + transport = raw.get("transport", "stdio") + if not isinstance(transport, str) or not transport.strip(): + raise ConfigError(f"mcp_servers.{name}.transport must be a non-empty string, e.g. {', '.join(MCP_TRANSPORTS)}") + return raw + + def _parse_mcp_server(name: str, raw: dict) -> MCPServerConfig: + raw = _check_mcp_types(name, raw) hosts_raw = raw.get("hosts", []) if not isinstance(hosts_raw, list) or not all(isinstance(h, str) for h in hosts_raw): raise ConfigError(f"mcp_servers.{name}.hosts must be an array of strings") @@ -128,10 +172,16 @@ def load_config(path: Path | None = None) -> SecfooConfig: try: data = tomllib.loads(path.read_text(encoding="utf-8")) + except UnicodeDecodeError as exc: + raise ConfigError(f"{path}: not valid UTF-8 (byte {exc.start})") from None except tomllib.TOMLDecodeError as exc: raise ConfigError(f"{path}: invalid TOML: {exc}") from exc + # Every section is checked for its shape before it's read: valid TOML + # like `defaults = 1` used to escape as AttributeError (#121). defaults_raw = data.get("defaults", {}) + if not isinstance(defaults_raw, dict): + raise ConfigError("[defaults] must be a table") exclude_raw = defaults_raw.get("exclude", []) if not isinstance(exclude_raw, list) or not all(isinstance(p, str) for p in exclude_raw): raise ConfigError("defaults.exclude must be an array of strings") @@ -143,6 +193,17 @@ def load_config(path: Path | None = None) -> SecfooConfig: if isinstance(max_cost_usd, bool) or not isinstance(max_cost_usd, (int, float)) or max_cost_usd <= 0: raise ConfigError("defaults.max_cost_usd must be a positive number") max_cost_usd = float(max_cost_usd) + for key in ("agent", "depth"): + value = defaults_raw.get(key) + if value is not None and (not isinstance(value, str) or not value.strip()): + raise ConfigError(f"defaults.{key} must be a non-empty string") + timeout = defaults_raw.get("timeout") + # A whole-number float (`timeout = 1800.0`) has always worked; keep it. + if isinstance(timeout, float) and timeout.is_integer(): + timeout = int(timeout) + defaults_raw = {**defaults_raw, "timeout": timeout} + if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, int) or timeout <= 0): + raise ConfigError("defaults.timeout must be a positive integer (seconds)") context_raw = defaults_raw.get("context", []) if not isinstance(context_raw, list) or not all(isinstance(c, str) and c.strip() for c in context_raw): raise ConfigError("defaults.context must be an array of non-empty strings") @@ -177,10 +238,15 @@ def load_config(path: Path | None = None) -> SecfooConfig: servers = [] seen_names: set[str] = set() - for entry in data.get("mcp_servers", []): + servers_raw = data.get("mcp_servers", []) + if not isinstance(servers_raw, list) or not all(isinstance(entry, dict) for entry in servers_raw): + raise ConfigError("mcp_servers must be an array of tables ([[mcp_servers]])") + for entry in servers_raw: name = entry.get("name") if not name: raise ConfigError("mcp_servers entry missing required `name` field") + if not isinstance(name, str): + raise ConfigError(f"mcp_servers: name must be a string, got {name!r}") if name in seen_names: raise ConfigError(f"mcp_servers: duplicate server name {name!r}") seen_names.add(name) diff --git a/src/secfoo/skills/loader.py b/src/secfoo/skills/loader.py index e677e1a..9688618 100644 --- a/src/secfoo/skills/loader.py +++ b/src/secfoo/skills/loader.py @@ -129,7 +129,13 @@ def _parse_frontmatter(text: str, *, source: str) -> tuple[dict[str, str], str]: def _build_skill(raw: bytes, *, source: str, path: Path | None, origin: str = "") -> Skill: label = str(path) if path is not None else origin - fields, body = _parse_frontmatter(raw.decode("utf-8"), source=label) + try: + text = raw.decode("utf-8") + except UnicodeDecodeError as exc: + # A --skill-file URL or `skills validate` gets this too, not only the + # user-folder loader that happens to catch UnicodeDecodeError (#121). + raise SkillLoadError(f"{label}: not valid UTF-8 (byte {exc.start})") from None + fields, body = _parse_frontmatter(text, source=label) try: skill = Skill( id=fields["id"], diff --git a/tests/test_property_fuzz_targets.py b/tests/test_property_fuzz_targets.py new file mode 100644 index 0000000..0391c1b --- /dev/null +++ b/tests/test_property_fuzz_targets.py @@ -0,0 +1,446 @@ +"""#121: property tests for the fuzz harnesses in fuzz/, on every platform. + +Atheris (coverage-guided, `.github/workflows/fuzz.yml`) only runs on Linux. +These tests drive the *same* `check` function each harness defines with +Hypothesis-generated inputs, and replay every file in fuzz/corpus/ -- +including the `crash-*` reproducers of crashes the harnesses found -- so the +invariants hold on Windows and macOS too, and a fixed crash can't return. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st + +FUZZ_DIR = Path(__file__).resolve().parents[1] / "fuzz" +sys.path.insert(0, str(FUZZ_DIR)) + +import fuzz_config +import fuzz_docext +import fuzz_parsers +import fuzz_runtime_ingest +import fuzz_sarif_export +import fuzz_skill_loader + +HARNESSES = { + "parsers": fuzz_parsers, "sarif_export": fuzz_sarif_export, "skill_loader": fuzz_skill_loader, + "config": fuzz_config, "docext": fuzz_docext, "runtime_ingest": fuzz_runtime_ingest, +} +CORPUS = FUZZ_DIR / "corpus" +SLOW = settings(deadline=None, suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large]) + + +# ---------- the corpora: seeds and crash reproducers ---------- + + +def test_every_harness_has_a_seed_corpus(): + assert sorted(p.name for p in CORPUS.iterdir() if p.is_dir()) == sorted(HARNESSES) + for name in HARNESSES: + assert any((CORPUS / name).iterdir()), f"fuzz/corpus/{name} is empty" + + +@pytest.mark.parametrize("path", sorted(p for p in CORPUS.rglob("*") if p.is_file() and p.parent != CORPUS), + ids=lambda p: f"{p.parent.name}/{p.name}") +def test_corpus_file_replays_without_a_crash(path): + HARNESSES[path.parent.name].check(path.read_bytes()) + + +def test_replay_mode_runs_without_atheris(monkeypatch, capsys): + """`python fuzz/fuzz_x.py crash-file` reproduces a CI crash anywhere.""" + import _common + + monkeypatch.setattr(sys, "argv", ["fuzz_config.py", str(CORPUS / "config"), "-max_total_time=60"]) + monkeypatch.setitem(sys.modules, "atheris", None) # as if not installed + with pytest.raises(SystemExit) as exc: + _common.main(fuzz_config.check) + assert exc.value.code == 0 and "replayed" in capsys.readouterr().out + + +def test_replay_mode_without_inputs_explains_itself(monkeypatch): + import _common + + monkeypatch.setattr(sys, "argv", ["fuzz_config.py"]) + monkeypatch.setitem(sys.modules, "atheris", None) + with pytest.raises(SystemExit, match="pip install atheris"): + _common.main(fuzz_config.check) + + +# ---------- SARIF / JSONL export ---------- + +_PATHS = st.one_of( + st.sampled_from(["app/db.py", "C:\\work\\a b.py", "C:/x.py", "C:", "//server/share/x.py", "//", "\\\\?\\C:\\x", + "/abs/a%b.py", "file:///etc/passwd", " ", "a\\b\\c.py", "../../etc/passwd"]), + st.text(max_size=40), +) +_LINES = st.one_of(st.integers(-5, 10**12).map(str), st.text(max_size=12), st.none(), st.integers(), + st.integers(4290, 5100).map(lambda n: "1" * n)) +_VALUE = st.one_of(st.none(), st.text(max_size=60), st.integers(), st.floats(allow_nan=False)) +_RECORD = st.fixed_dictionaries( + {"skill_id": st.one_of(st.sampled_from(["sast", "sca-reachability", "secret-scanning"]), st.text(max_size=30))}, + optional={ + "severity": st.one_of(st.sampled_from(["Critical", " HIGH ", "medium", "Informational", "info"]), _VALUE), + "cwe": st.one_of(st.sampled_from(["CWE-89", "cwe-79, CWE-22", "CWE-0", "CWE-089"]), _VALUE), + "title": _VALUE, "issue": _VALUE, "secret_type": _VALUE, "description": _VALUE, "construct": _VALUE, + "evidence": _VALUE, "location_file": _PATHS, "location_line": _LINES, + "runtime": st.fixed_dictionaries({ + "state": st.sampled_from(["reached", "not_reached", "unknown"]), + "routes": st.lists(st.fixed_dictionaries({"route": st.text(max_size=30)}), max_size=4)}), + }, +) + + +@SLOW +@given(st.lists(_RECORD, max_size=12)) +def test_export_of_any_finding_records_is_valid_sarif_and_jsonl(records): + fuzz_sarif_export.check("\n".join(json.dumps(r) for r in records).encode("utf-8")) + + +@SLOW +@given(st.binary(max_size=2048)) +def test_export_harness_survives_arbitrary_bytes(data): + fuzz_sarif_export.check(data) + + +def test_a_huge_location_line_is_dropped_not_fatal(): + from secfoo.report.sarif import findings_to_sarif + + result = findings_to_sarif([{"skill_id": "sast", "location_file": "a.py", "location_line": "1" * 5000}]) + location = result["runs"][0]["results"][0]["locations"][0]["physicalLocation"] + assert location == {"artifactLocation": {"uri": "a.py"}} # the file is kept, the bogus line isn't + + +def test_jsonl_export_matches_the_previous_inline_format(): + from secfoo.report.jsonl import findings_to_jsonl + + assert findings_to_jsonl([]) == "" + assert findings_to_jsonl([{"b": 1, "a": "x"}, {"c": None}]) == '{"a": "x", "b": 1}\n{"c": null}\n' + + +# ---------- skill loader ---------- + +# A file on disk is bytes; text with lone surrogates can't be encoded into +# one, so those are left to the arbitrary-bytes test below. +_KEYS = st.one_of(st.sampled_from(["id", "name", "description", "version", "output", "short_name", "category"]), + st.text(alphabet=st.characters(blacklist_categories=("Cs",), blacklist_characters=":\r\n"), + max_size=12)) +_FIELD = st.one_of(st.sampled_from(["generic", "sast", "my-review", "1", "-3", "١٢", "1e3", "x" * 5000, ""]), + st.integers().map(str), + st.text(alphabet=st.characters(blacklist_categories=("Cs",), blacklist_characters="\r\n"), + max_size=40)) + + +@given(st.dictionaries(_KEYS, _FIELD, max_size=9), st.text(max_size=200), st.sampled_from(["\n", "\r\n"])) +def test_any_frontmatter_loads_or_fails_with_skill_load_error(fields, body, newline): + text = newline.join(["---", *(f"{k}: {v}" for k, v in fields.items()), "---", body]) + fuzz_skill_loader.check(text.encode("utf-8")) + + +@given(st.binary(max_size=1024)) +def test_skill_loader_survives_arbitrary_bytes(data): + fuzz_skill_loader.check(b"---\nid: x\n---\n" + data) + fuzz_skill_loader.check(data) + + +def test_invalid_utf8_skill_is_a_skill_load_error(): + from secfoo.skills.loader import SkillLoadError, _build_skill + + with pytest.raises(SkillLoadError, match="not valid UTF-8"): + _build_skill(b"---\nid: a\n---\n\xff", source="url", path=None, origin="https://x/s.md") + + +# ---------- config.toml ---------- + +def _toml_string(value: str) -> str: + return json.dumps(value) # a JSON string is a valid TOML basic string, \uXXXX escapes included + + +_TOML_SCALAR = st.one_of( + st.integers(-(2**63), 2**63 - 1).map(str), st.booleans().map(lambda b: "true" if b else "false"), + st.floats(allow_nan=False, allow_infinity=False).map(repr), st.text(max_size=20).map(_toml_string), +) +_TOML_VALUE = st.recursive( + _TOML_SCALAR, + lambda inner: st.one_of( + st.lists(inner, max_size=4).map(lambda items: "[" + ", ".join(items) + "]"), + st.dictionaries(st.text(min_size=1, max_size=8), inner, max_size=3).map( + lambda table: "{" + ", ".join(f"{_toml_string(k)} = {v}" for k, v in table.items()) + "}"), + ), + max_leaves=8, +) +_SECTION_KEYS = { + "defaults": ["agent", "depth", "timeout", "exclude", "fail_on", "max_cost_usd"], + "skills": ["paths"], + "memory": ["enabled"], +} +_PLAUSIBLE = st.sampled_from(['"claude"', '"quick"', "600", '["vendor/"]', '"high"', "2.5", "true", '"npx"', + '["-y", "x"]', '"stdio"', '"http"', '"https://x/mcp"', '{ A = "b" }', "0", '""']) + + +@st.composite +def _config_toml(draw) -> str: + out = [] + for key in draw(st.lists(st.sampled_from(["defaults", "agents", "mcp_servers", "skills", "memory"]), + unique=True, max_size=5)): + shape = draw(st.sampled_from(["scalar", "table", "array_of_tables"])) + if shape == "scalar": + out.append(f"{key} = {draw(_TOML_VALUE)}") + elif key == "mcp_servers" and shape == "array_of_tables": + for _ in range(draw(st.integers(1, 3))): + out.append("[[mcp_servers]]") + for field in draw(st.lists(st.sampled_from( + ["name", "command", "url", "args", "env", "headers", "transport"]), unique=True)): + out.append(f"{field} = {draw(st.one_of(_PLAUSIBLE, _TOML_VALUE))}") + elif key == "agents": + for agent in draw(st.lists(st.sampled_from(["claude", "api", "codex"]), unique=True, max_size=3)): + out.append(f"[agents.{agent}]") + for field in draw(st.lists(st.sampled_from(["model", "max_input_tokens"]), unique=True)): + out.append(f"{field} = {draw(st.one_of(_PLAUSIBLE, _TOML_VALUE))}") + else: + out.append(f"[{key}]") + for field in draw(st.lists(st.sampled_from(_SECTION_KEYS.get(key, ["x"])), unique=True)): + out.append(f"{field} = {draw(st.one_of(_PLAUSIBLE, _TOML_VALUE))}") + return "\n".join(out) + "\n" + + +@SLOW +@given(_config_toml()) +def test_any_config_loads_with_declared_types_or_fails_with_config_error(text): + fuzz_config.check(text.encode("utf-8")) + + +@given(st.binary(max_size=512)) +def test_config_loader_survives_arbitrary_bytes(data): + fuzz_config.check(data) + + +def test_the_documented_example_config_still_loads(tmp_path): + """Stricter validation must not reject what docs/REFERENCE.md shows.""" + from secfoo.settings import load_config + + path = tmp_path / "config.toml" + path.write_bytes((CORPUS / "config" / "documented.toml").read_bytes()) + config = load_config(path) + assert config.defaults.agent == "claude" and config.defaults.max_cost_usd == 2.0 + assert [s.name for s in config.mcp_servers] == ["Atlassian-Rovo-MCP", "wiki"] + assert config.mcp_servers[1].transport == "http" and config.memory_enabled is False + + +@pytest.mark.parametrize(("text", "message"), [ + ("defaults = 1", r"\[defaults\] must be a table"), + ("mcp_servers = 'x'", "array of tables"), + ("[mcp_servers]\nname = 'a'", "array of tables"), + ("[[mcp_servers]]\nname = [1]\ncommand = 'x'", "name must be a string"), + ("[[mcp_servers]]\nname = 'a'\ncommand = 'npx'\nargs = [1]", r"mcp_servers\.a\.args must be an array of strings"), + ("[[mcp_servers]]\nname = 'a'\ncommand = 5", r"mcp_servers\.a\.command must be a string"), + ("[[mcp_servers]]\nname = 'a'\ncommand = 'x'\nenv = { A = { b = 1 } }", + r"mcp_servers\.a\.env\.A must be a string, number or boolean"), + ("[[mcp_servers]]\nname = 'a'\ncommand = 'x'\nenv = [1]", r"mcp_servers\.a\.env must be a table"), + ("[[mcp_servers]]\nname = 'a'\nurl = 'https://x'\ntransport = 5", "transport must be a non-empty string"), + ("[defaults]\ntimeout = 'soon'", "defaults.timeout must be a positive integer"), + ("[defaults]\nagent = 3", "defaults.agent must be a non-empty string"), +]) +def test_config_errors_name_the_bad_key(tmp_path, text, message): + from secfoo.settings import ConfigError, load_config + + path = tmp_path / "config.toml" + path.write_text(text, encoding="utf-8") + with pytest.raises(ConfigError, match=message): + load_config(path) + + +def test_non_utf8_config_is_a_config_error(tmp_path): + from secfoo.settings import ConfigError, load_config + + path = tmp_path / "config.toml" + path.write_bytes(b"[defaults]\nagent = \"\xff\"\n") + with pytest.raises(ConfigError, match="not valid UTF-8"): + load_config(path) + + +def test_an_unknown_agent_in_config_is_a_clean_cli_error(tmp_path, monkeypatch): + from typer.testing import CliRunner + + from secfoo import cli + + path = tmp_path / "config.toml" + path.write_text('[defaults]\nagent = "nope"\n', encoding="utf-8") + monkeypatch.setattr("secfoo.settings.CONFIG_PATH", path) + monkeypatch.setattr(cli, "CONFIG_PATH", path) + result = CliRunner().invoke(cli.app, ["run", "--skill", "sast", "--target", str(tmp_path), "--yes"]) + assert result.exit_code == 1 + assert "defaults.agent must be one of" in result.output and "Traceback" not in result.output + + +# ---------- document extraction ---------- + +_SEEDS = sorted((CORPUS / "docext").iterdir()) + + +@settings(SLOW, max_examples=40) +@given(st.sampled_from(_SEEDS), st.lists(st.tuples(st.integers(0, 10**6), st.integers(0, 255)), max_size=12)) +def test_mutated_documents_extract_to_text_or_empty(seed, flips): + data = bytearray(seed.read_bytes()) + for position, value in flips: + data[1 + position % (len(data) - 1)] = value # byte 0 picks the format; keep it + fuzz_docext.check(bytes(data)) + + +@settings(SLOW, max_examples=30) +@given(st.binary(max_size=2048)) +def test_arbitrary_bytes_extract_to_text_or_empty(data): + fuzz_docext.check(data) + + +def test_document_seeds_actually_contain_text(): + from secfoo.docext import extract_text + + texts = {} + for seed in _SEEDS: + suffix, body = fuzz_docext.split(seed.read_bytes()) + path = fuzz_docext._DIR / f"seed{suffix}" + path.write_bytes(body) + texts[seed.name] = extract_text(path) + assert "MFA | Implemented" in texts["report.docx.bin"] + assert "XSS | High" in texts["summary.pptx.bin"] + assert "ISO 27001" in texts["text.pdf.bin"] + + +# ---------- runtime ingest ---------- + +_SURROGATE = st.characters(min_codepoint=0xD800, max_codepoint=0xDFFF) +_JSON_TEXT = st.one_of(st.text(max_size=30), st.lists(st.one_of(st.characters(), _SURROGATE), max_size=8).map("".join)) +_JSON_VALUE = st.recursive( + st.one_of(st.none(), st.booleans(), st.integers(-(2**70), 2**70), st.floats(allow_nan=False), _JSON_TEXT), + lambda inner: st.one_of(st.lists(inner, max_size=4), st.dictionaries(st.text(max_size=8), inner, max_size=4)), + max_leaves=10, +) +_EVENT_FIELDS = ["type", "id", "language", "source", "started_at", "ended_at", "app", "env", "session", "ecosystem", + "package", "version", "finding_fingerprint", "symbol", "route", "auth", "count", "first_seen", + "last_seen", "entry_frame", "stack_sample", "app_functions_total", "app_functions_executed"] +_VALID_BASE = { + "id": "s1", "session": "s1", "language": "python", "source": "sensor", "started_at": "2026-11-08T10:00:00Z", + "ecosystem": "PyPI", "package": "p", "version": "1", "finding_fingerprint": fuzz_runtime_ingest.FINGERPRINT, + "symbol": "p.f", "count": 1, +} +# A valid-looking event with some fields replaced by arbitrary JSON values: +# close enough to the contract to get past the first checks. +_PLAUSIBLE_EVENT = st.builds( + lambda kind, overrides: {"type": kind, **_VALID_BASE, **overrides}, + st.sampled_from(["session", "load", "hit", "other"]), + st.dictionaries(st.sampled_from(_EVENT_FIELDS), _JSON_VALUE, max_size=4), +) +_LINE = st.one_of( + _PLAUSIBLE_EVENT.map(json.dumps), + st.dictionaries(st.sampled_from(_EVENT_FIELDS), _JSON_VALUE, max_size=8).map(json.dumps), + _JSON_VALUE.map(json.dumps), + st.text(max_size=60), + st.integers(1, 30000).map(lambda n: "[" * n + "]" * n), + st.integers(4250, 5000).map(lambda n: '{"type":"hit","count":' + "9" * n + "}"), +) + + +@SLOW +@given(st.lists(_LINE, max_size=12)) +def test_any_batch_stores_or_skips_every_line(lines): + fuzz_runtime_ingest.check("\n".join(lines).encode("utf-8", errors="surrogatepass")) + + +@given(st.binary(max_size=2048)) +def test_ingest_survives_arbitrary_bytes(data): + fuzz_runtime_ingest.check(data) + + +@pytest.mark.parametrize("path", sorted((CORPUS / "runtime_ingest").glob("crash-*")), ids=lambda p: p.name) +def test_one_bad_line_no_longer_loses_the_whole_batch(path, tmp_path): + from secfoo.runtime.evidence import ingest_events + from secfoo.storage.repository import RunRepository + + with RunRepository(db_path=tmp_path / "db.sqlite") as repo: + project = repo.upsert_project("/app", "app", "local") + lines = path.read_text(encoding="utf-8").splitlines() + report = ingest_events(repo.connection, project, lines) + assert report.sessions >= 1 # the good session line before the bad one was committed + assert len(report.skipped) >= 1 + assert repo.connection.execute("SELECT COUNT(*) FROM runtime_sessions").fetchone()[0] >= 1 + + + +# ---------- review follow-ups (#149) ---------- + +def test_a_stale_config_agent_or_depth_does_not_block_explicit_flags(monkeypatch): + """CLI flags always win over config: an unknown defaults.agent/depth is + only an error when the config value would actually be used.""" + from typer.testing import CliRunner + + from secfoo.cli import app + from secfoo.settings import Defaults, SecfooConfig + config = SecfooConfig(defaults=Defaults(agent="newagent", depth="deep"), mcp_servers=[]) + monkeypatch.setattr("secfoo.cli.load_config", lambda: config) + captured = {} + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: captured.update(kw) or []) + result = CliRunner().invoke(app, ["run", "--skill", "sast", "--agent", "claude", "--depth", "quick"]) + assert "defaults.agent" not in result.output and captured.get("agent_id") == "claude" + result = CliRunner().invoke(app, ["run", "--skill", "sast", "--depth", "quick"]) + assert result.exit_code == 1 and "defaults.agent must be one of" in result.output + + +def test_config_shapes_that_always_worked_still_load(tmp_path): + from secfoo.settings import load_config + path = tmp_path / "config.toml" + path.write_text( + "[defaults]\ntimeout = 1800.0\n\n" + "[[mcp_servers]]\nname = \"local\"\ncommand = \"npx\"\nurl = \"\"\nenv = { PORT = 8080, DEBUG = true }\n\n" + "[[mcp_servers]]\nname = \"remote\"\ncommand = \"\"\nurl = \"https://mcp.example.com/mcp\"\n" + "transport = \"streamable-http\"\nheaders = { X-Retries = 3 }\n", + encoding="utf-8", + ) + config = load_config(path) + assert config.defaults.timeout == 1800 + local, remote = config.mcp_servers + assert vars(local)["env"] == {"PORT": "8080", "DEBUG": "true"} and local.url is None + assert remote.command is None and remote.transport == "streamable-http" + assert vars(remote)["headers"] == {"X-Retries": "3"} + + +def test_config_values_that_used_to_crash_are_named(tmp_path): + import pytest as _pytest + + from secfoo.settings import ConfigError, load_config + path = tmp_path / "config.toml" + path.write_text("[[mcp_servers]]\nname = \"x\"\ncommand = \"npx\"\nheaders = { NESTED = { a = 1 } }\n", + encoding="utf-8") + with _pytest.raises(ConfigError, match="headers.NESTED"): + load_config(path) + + +def test_zero_padded_sarif_lines_keep_their_region(): + from secfoo.report.sarif import _location + region = _location({"location_file": "app.py", "location_line": "0000000042"})["physicalLocation"]["region"] + assert region == {"startLine": 42} + assert "region" not in _location({"location_file": "app.py", "location_line": "1" + "0" * 12})["physicalLocation"] + assert "region" not in _location({"location_file": "app.py", "location_line": "000"})["physicalLocation"] + + +def test_a_validation_bug_is_not_reported_as_bad_json(monkeypatch): + import pytest as _pytest + + from secfoo.runtime import evidence + def broken(_event): + raise ValueError("bug in validation") + monkeypatch.setattr(evidence, "validate_event", broken) + with _pytest.raises(ValueError, match="bug in validation"): + list(evidence.parse_lines(['{"type": "session"}'])) + [(_, event, reason)] = list(evidence.parse_lines(["[" * 5000])) # decode errors are still skipped + assert event is None and "not valid JSON" in reason + + +def test_the_ingest_harness_judges_each_input_on_its_own(): + harness = HARNESSES["runtime_ingest"] + harness.check((CORPUS / "runtime_ingest" / "batch.ndjson").read_bytes()) + harness.check(b"") + assert harness._repo.connection.execute("SELECT COUNT(*) FROM runtime_sessions").fetchone()[0] == 0 diff --git a/tests/test_runtime/test_runtime_api.py b/tests/test_runtime/test_runtime_api.py index 3b2c7eb..eb69508 100644 --- a/tests/test_runtime/test_runtime_api.py +++ b/tests/test_runtime/test_runtime_api.py @@ -85,6 +85,26 @@ def test_malformed_lines_are_reported_not_fatal(client, store): assert resp.json()["hits"] == 1 and resp.json()["skipped"][0]["line"] == 2 +@pytest.mark.parametrize(("bad_line", "reason"), [ + ("[" * 20000 + "]" * 20000, "not valid JSON (RecursionError)"), + ('{"type":"hit","count":1' + "0" * 5000 + "}", "not valid JSON (ValueError)"), + (json.dumps({**SESSION, "id": "s-2", "app": "\ud800"}), "'app' must be valid Unicode text"), + (json.dumps({**HIT, "count": 2**64}), "'count' must be at most"), + (json.dumps({**HIT, "entry_frame": "app/\udcff.py:3"}), "'entry_frame' must be valid Unicode text"), +], ids=["deep-nesting", "int-over-4300-digits", "lone-surrogate", "count-over-int64", "surrogate-frame"]) +def test_lines_that_used_to_500_are_skipped_and_the_rest_is_stored(client, store, bad_line, reason): + """#121: each of these escaped ingest_events as RecursionError, ValueError, + UnicodeEncodeError or OverflowError, rolling back the whole batch and + returning a 500. Now only that line is skipped.""" + body = _ndjson(SESSION) + bad_line.encode() + b"\n" + _ndjson(HIT) + for params in ({"project": PROJECT}, {"project": PROJECT, "app": "payments-api"}): # with and without _with_app_env + resp = client.post("/api/runtime/v1/events", params=params, content=body, headers=_auth(store["key"])) + assert resp.status_code == 200, resp.text + assert resp.json()["sessions"] == 1 and resp.json()["hits"] == 1 + [skipped] = resp.json()["skipped"] + assert skipped["line"] == 2 and skipped["reason"].startswith(reason) + + # ---------- auth and access ---------- @@ -196,6 +216,18 @@ def test_heartbeat_registers_the_sensor_and_sums_drops(client, store): assert bad.status_code == 422 +@pytest.mark.parametrize("body", [ + b"[" * 20000 + b"]" * 20000, # RecursionError in json.loads + b'{"sensor_id": "s", "instances": ' + b"9" * 5000 + b"}", # ValueError: int over 4300 digits + b'{"sensor_id": "s", "instances": 18446744073709551616}', # over 64 bits: SQLite OverflowError + b'{"sensor_id": "\\ud800"}', # lone surrogate: UnicodeEncodeError +]) +def test_heartbeat_bodies_that_used_to_500_are_rejected_cleanly(client, store, body): + resp = client.post("/api/runtime/v1/heartbeat", params={"project": PROJECT}, headers=_auth(store["key"]), + content=body) + assert resp.status_code in (400, 422), resp.text + + def test_evidence_endpoint_reads_runtime_state_per_finding(client, store): client.post("/api/runtime/v1/events", params={"project": PROJECT}, content=_ndjson(SESSION, HIT), headers=_auth(store["key"]))