diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4093add --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +.git +.github +tests +__pycache__ +*.pyc +.DS_Store +*.db +*.zip +*.json.tmp diff --git a/.github/workflows/pathscope.yml b/.github/workflows/pathscope.yml new file mode 100644 index 0000000..918836f --- /dev/null +++ b/.github/workflows/pathscope.yml @@ -0,0 +1,108 @@ +# Example CI pipeline for PathScope. +# +# It does three things, in order: +# 1. runs the unit test suite (no network, no dependencies), +# 2. runs the built-in self-test, +# 3. if a capture was attached to the run (artifact "pathscope-input"), +# analyses it with a policy gate and publishes JUnit + an HTML report. +# +# PathScope is passive: this workflow never contacts the targets in the +# capture. Replace the artifact step with wherever your capture comes from +# (proxy export, browser HAR, Postman collection, ...). +name: pathscope + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + name: Unit tests and self-test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Run the unit tests + run: python3 -m unittest discover -s tests -v + - name: Run the built-in self-test + run: python3 path_detector.py --no-banner --self-test + - name: Check the environment + run: python3 path_detector.py --no-banner --doctor + + install: + name: Installer smoke test + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + - name: Install into a throwaway prefix + run: | + ./install.sh --dry-run --no-path + PREFIX="$RUNNER_TEMP/pathscope" ./install.sh --no-path + - name: Run the installed launcher + run: | + "$RUNNER_TEMP/pathscope/bin/pathscope" --version + "$RUNNER_TEMP/pathscope/bin/pathscope" --no-banner --self-test + echo 'https://a.test/?file=../../etc/passwd' \ + | "$RUNNER_TEMP/pathscope/bin/pathscope" --no-banner -q --format json \ + | grep -q '"candidates": 1' + - name: Uninstall + run: PREFIX="$RUNNER_TEMP/pathscope" ./install.sh --uninstall + + triage: + name: Triage a capture (optional) + needs: test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Download the capture artifact + id: capture + uses: actions/download-artifact@v4 + continue-on-error: true + with: + name: pathscope-input + path: input + - name: Analyse with a policy gate + if: steps.capture.outcome == 'success' + id: triage + # Reports are produced first, then the gate decides the job's outcome. + run: | + set +e + python3 path_detector.py \ + -i input/capture.har \ + --preset balanced \ + --policy .pathscope/policy.json \ + --output-format junit > pathscope-junit.xml + echo "gate=$?" >> "$GITHUB_OUTPUT" + python3 path_detector.py \ + -i input/capture.har \ + --preset balanced \ + --policy .pathscope/policy.json \ + --save-report pathscope-report.html --interactive \ + --github-annotations + echo "annotations=$?" >> "$GITHUB_OUTPUT" + - name: Upload reports + if: steps.capture.outcome == 'success' + uses: actions/upload-artifact@v4 + with: + name: pathscope-reports + path: | + pathscope-junit.xml + pathscope-report.html + - name: Enforce the policy gate + if: steps.capture.outcome == 'success' && steps.triage.outputs.gate != '0' + run: | + echo "PathScope policy gate failed (exit ${{ steps.triage.outputs.gate }})." >&2 + exit 1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ad03bc7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +*.pyc +.venv/ +venv/ diff --git a/.pathscope/policy.json b/.pathscope/policy.json new file mode 100644 index 0000000..7aae98a --- /dev/null +++ b/.pathscope/policy.json @@ -0,0 +1,10 @@ +{ + "description": "Example gate: no new high-confidence candidates, at most 10 medium, 25 total", + "max_high": 0, + "max_medium": 10, + "max_total": 25, + "min_score": 0, + "fail_on_known": false, + "ignore_rules": [], + "ignore_hosts": [] +} diff --git a/.pre-commit-config.example.yaml b/.pre-commit-config.example.yaml new file mode 100644 index 0000000..ca360ee --- /dev/null +++ b/.pre-commit-config.example.yaml @@ -0,0 +1,7 @@ +# Copy to .pre-commit-config.yaml in your project and run `pre-commit install`. +repos: + - repo: https://github.com/mrdineshpathro/pathscope + rev: v2.2.0 + hooks: + - id: pathscope-selftest + - id: pathscope-no-new-high diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml new file mode 100644 index 0000000..2414805 --- /dev/null +++ b/.pre-commit-hooks.yaml @@ -0,0 +1,28 @@ +# Pre-commit hook definitions (https://pre-commit.com). +# +# repos: +# - repo: https://github.com/mrdineshpathro/pathscope +# rev: v2.2.0 +# hooks: +# - id: pathscope-selftest +# - id: pathscope-no-new-high +# +# Both hooks are offline and read only the files listed by pre-commit. +- id: pathscope-selftest + name: PathScope self-test + description: Verify the PathScope installation (parsing, scoring, escaping). + entry: python3 path_detector.py --no-banner --self-test + language: python + pass_filenames: false + always_run: true + +- id: pathscope-no-new-high + name: PathScope (no new high-confidence candidates) + description: > + Analyse the given captures and fail when a new high-confidence candidate + appears. Uses a reviewed ledger when one is provided, so a stable file does + not fail repeatedly. + entry: python3 path_detector.py --no-banner -q --policy '{"max_high": 0}' --top 5 + language: python + files: \.(har|json|txt|xml|jsonl)$ + types: [file] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e529c85 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +# PathScope container image. +# +# docker build -t pathscope . +# cat requests.txt | docker run --rm -i pathscope --stream --format text +# docker run --rm -v "$PWD:/data:ro" pathscope -i /data/requests.txt --format json +# +# The image contains nothing but PathScope and a Python runtime: no scanners, +# no networking tools, no third-party packages. + +FROM python:3.12-slim AS base + +LABEL org.opencontainers.image.title="PathScope" \ + org.opencontainers.image.description="Passive, offline triage of path-like request parameters" \ + org.opencontainers.image.source="https://github.com/mrdineshpathro/pathscope" \ + org.opencontainers.image.licenses="MIT" + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONHASHSEED=0 + +# Unprivileged user: nothing in PathScope needs root. +RUN groupadd --system --gid 10001 pathscope \ + && useradd --system --uid 10001 --gid pathscope --create-home pathscope + +WORKDIR /opt/pathscope +COPY path_detector.py ./ +COPY pathscope ./pathscope +COPY assets ./assets +COPY README.md LICENSE ./ + +# Byte-compile once so runs stay fast; drop the source copies for a smaller layer. +RUN python3 -m compileall -q pathscope path_detector.py \ + && chmod -R a+rX /opt/pathscope + +USER pathscope +WORKDIR /home/pathscope + +# Inputs are mounted read-only; the default run documents itself. +VOLUME ["/data"] +ENTRYPOINT ["python3", "/opt/pathscope/path_detector.py"] +CMD ["--help"] + +# Sanity check used by CI and `docker run --rm pathscope --self-test`. +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=1 \ + CMD ["python3", "/opt/pathscope/path_detector.py", "--no-banner", "--self-test"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..ecbebef --- /dev/null +++ b/README.md @@ -0,0 +1,2560 @@ +
+ +PathScope logo + +# PathScope + +**Passive, offline triage of URL and request parameters that may be worth +reviewing for path-traversal risk.** + +[![Python](https://img.shields.io/badge/python-3.8%2B-blue)](https://www.python.org/) +[![Standard library](https://img.shields.io/badge/dependencies-none-brightgreen)](#requirements) +[![Platform](https://img.shields.io/badge/platform-Kali%20Linux%20%7C%20Linux%20%7C%20macOS%20%7C%20Windows-lightgrey)](#requirements) +[![License](https://img.shields.io/badge/license-MIT-blue)](LICENSE) + +[GitHub](https://github.com/mrdineshpathro) · +[Instagram](https://www.instagram.com/mr_dineshpatro) · +[Support](https://buymeacoffee.com/mrdineshpathro) + +
+ +--- + +> **PathScope reports candidates for manual review. It does not find, prove, or +> confirm vulnerabilities.** A finding means “this parameter’s name or existing +> value looks path-like”. Whether it is used, validated, or remotely interesting +> is a question for a human, in scope, with authorization. + +--- + +## Table of contents + +1. [What it does](#what-it-does) +2. [Safety model](#safety-model) +3. [Requirements](#requirements) +4. [Installation](#installation) +5. [Inputs](#inputs) +6. [Quick start](#quick-start) +7. [Presets](#presets) +8. [Baselines, diff and suppression](#baselines-diff-and-suppression) +9. [Reports](#reports) +10. [Live watch mode](#live-watch-mode) +11. [Rule registry and tuning](#rule-registry-and-tuning) +12. [Multilingual and folded names](#multilingual-and-folded-names) +13. [Value-shape demotion](#value-shape-demotion) +14. [CI integration](#ci-integration) +15. [Scale and performance](#scale-and-performance) +16. [Interactive HTML report](#interactive-html-report) +17. [Terminal reviewer](#terminal-reviewer) +18. [Review ledger](#review-ledger) +19. [Analysis dashboard](#analysis-dashboard) +20. [Cross-source correlation](#cross-source-correlation) +21. [Remediation playbooks](#remediation-playbooks) +22. [Run history and trends](#run-history-and-trends) +23. [Streaming stdin](#streaming-stdin) +24. [Reproducible bundles](#reproducible-bundles) +25. [Secret scrubbing](#secret-scrubbing) +26. [Capture-to-capture diff](#capture-to-capture-diff) +27. [Offline URL extraction](#offline-url-extraction) +28. [Value statistics](#value-statistics) +29. [Rule coverage](#rule-coverage) +30. [Term packs](#term-packs) +31. [Preset comparison](#preset-comparison) +32. [Score calibration](#score-calibration) +33. [Project files](#project-files) +34. [Reviewed-aware CI](#reviewed-aware-ci) +35. [Acceptance expiry](#acceptance-expiry) +36. [Path families](#path-families) +37. [Review queue](#review-queue) +38. [Scope files](#scope-files) +39. [Deterministic sampling](#deterministic-sampling) +40. [API description matching](#api-description-matching) +41. [Policy shadow mode](#policy-shadow-mode) +42. [Work-item export](#work-item-export) +43. [Pull-request comments](#pull-request-comments) +44. [Host redaction](#host-redaction) +45. [Shell completion](#shell-completion) +46. [Waivers](#waivers) +47. [Suppression audit](#suppression-audit) +48. [Rule precision](#rule-precision) +49. [Rule impact](#rule-impact) +50. [Weight simulation](#weight-simulation) +51. [Score-change explanation](#score-change-explanation) +52. [Filtering with --where](#filtering-with---where) +53. [Run attestation](#run-attestation) +54. [Owner assignment](#owner-assignment) +55. [Ledger merge](#ledger-merge) +56. [Exit codes](#exit-codes) +57. [Detection rules](#detection-rules) +58. [Configuration file](#configuration-file) +59. [Tests](#tests) +60. [Project layout](#project-layout) +61. [Limitations](#limitations) +62. [FAQ](#faq) +63. [Authorization and legal](#authorization-and-legal) + +--- + +## What it does + +Given URLs or a HAR capture **you already have**, PathScope: + +* parses query strings, form bodies and JSON bodies **locally**; +* scores every parameter against a small, documented rule set + (name vocabulary + value shape); +* prints a ranked list of *candidates* with the rule that fired, a plain-language + reason, and a heuristic score. + +It does **not** send a request, resolve a host, crawl, fuzz, inject, replay a HAR, +or read any file named in a parameter. Parameter values are strings and nothing +else. + +Typical use: you have a proxy history or a list of URLs from an authorized +review, and you want the five parameters worth reading first instead of two +hundred. + +--- + +## Safety model + +| Guarantee | How it is enforced | +|---|---| +| No network I/O | No `socket`, `ssl`, `http`, `urllib.request`, `requests` imports anywhere in `pathscope/`; a test asserts this with an allow-list. | +| No DNS | Same as above: nothing in the package can resolve a name. | +| No crawling or scanning | Inputs are read exactly once from args, files or stdin. | +| No test payloads | Values are only read, never generated or modified. | +| No filesystem access via values | Values never reach `open`, `os.open`, `pathlib`; a test patches `open` to fail if a value is ever used as a path. | +| No root | Nothing calls `setuid`, `sudo`, or privileged APIs. | +| No third-party packages | Standard library only. | + +Additional hardening: + +* **Values hidden by default.** Reports show `` unless you pass + `--show-values`. +* **No query strings or bodies in output.** The reported `resource` is + `scheme://host[:port]/path` only; `user:pass@` in URLs is masked. +* **Terminal-safe output.** Every string from input is NFC-normalised and control + characters are removed before rendering, so a crafted value cannot inject ANSI + escapes or fake report lines. +* **Deterministic output.** No timestamps, no machine names, stable sort order — + reports diff cleanly between runs. +* **Bounded work.** Decoding is capped (default 3 passes, max 5), HAR entries and + JSON parameters are capped, and long values are truncated. + +--- + +## Requirements + +| | | +|---|---| +| Python | 3.8 or newer (developed and tested on Python 3.11, which Kali ships) | +| Packages | **none** — standard library only | +| Privileges | ordinary user; **root is not required** (the Docker image is unprivileged too) | +| Network | **never used** | + +--- + +## Installation + +PathScope is a single Python package with **no third-party dependencies**. +Pick whichever line matches your box. + +### Kali / Debian / Ubuntu / macOS / WSL (one command) + +```sh +git clone https://github.com/mrdineshpathro/pathscope +cd pathscope +./install.sh # installs into ~/.local +``` + +`install.sh` is POSIX `sh`, prints every action, and is safe to re-run: + +| Command | Effect | +|---|---| +| `./install.sh` | install to `~/.local`, add it to the PATH in `~/.profile`/`~/.zshrc` | +| `PREFIX=/opt/pathscope sudo ./install.sh` | system-wide install | +| `./install.sh --no-path` | install files but leave shell rc files alone | +| `./install.sh --dry-run` | print what would happen, change nothing | +| `./install.sh --uninstall` | remove the launcher and program files | + +It refuses to run on Python older than 3.8, verifies the copied sources import, +and finishes with `pathscope --version`. Nothing is downloaded and no Python +packages are installed. + +### Windows + +```bat +git clone https://github.com/mrdineshpathro/pathscope +cd pathscope +install.cmd +``` + +Installs to `%LOCALAPPDATA%\PathScope`, adds `...\bin` to the **user** PATH (no +admin rights needed) and writes a `pathscope.cmd` launcher. Options: +`--no-path`, `--dry-run`, `--help`; override the location with +`set PREFIX=D:\tools ^& install.cmd`. + +The terminal reviewer (`--tui`) needs `curses`; on Windows it is unavailable, and +every other feature works unchanged (PathScope reports this clearly instead of +crashing — see `pathscope --doctor`). + +### Docker (one line) + +```sh +docker build -t pathscope . +cat requests.txt | docker run --rm -i pathscope --stream +docker run --rm -v "$PWD:/data:ro" pathscope -i /data/requests.txt --format json +``` + +The image is `python:3.12-slim`, runs as an unprivileged user, contains no +scanners or networking tools, and has a `HEALTHCHECK` that runs `--self-test`. + +### Verify any install + +```sh +pathscope --doctor # interpreter, sqlite, zip, curses, package integrity +pathscope --self-test # 16 behavioural checks, no network access +``` + +### Manual (no install) + +```sh +python3 path_detector.py --help +``` + +### Kali Linux notes + +Kali ships Python 3.11; there is nothing to install. + +```bash +git clone https://github.com/mrdineshpathro/pathscope.git +cd pathscope + +python3 --version # expect 3.11.x +chmod +x path_detector.py +./path_detector.py --help + +# equivalent module form (no chmod needed) +python3 -m pathscope --help +``` + +Optional: put it on your `PATH` without root. + +```bash +mkdir -p ~/.local/bin +ln -sf "$PWD/path_detector.py" ~/.local/bin/pathscope +pathscope --version +``` + +If `~/.local/bin` is not on `PATH`, add it to your shell config +(`~/.zshrc` on Kali by default): + +```bash +echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && exec zsh +``` + +> Nothing in this project needs `sudo`. If a command fails, fix permissions in +> your home directory rather than escalating. + +--- + +## Inputs + +PathScope accepts three sources, which are merged and de-duplicated: + +| Source | Flag | Notes | +|---|---|---| +| One or more URLs | `--url URL` (repeatable) | Quote URLs containing `&`. | +| URL list | `-i urls.txt` / `-i urls2.txt` | One URL per line; blank lines and `#` comments ignored; malformed lines warn and are skipped. | +| HAR 1.2 capture | `-i capture.har` or `--format har` | Parsed locally; requests are **never replayed**. | +| Burp proxy XML | `-i burp-history.xml` or `--format burp` | Base64 and plain request blocks; form/JSON/multipart bodies parsed. | +| OpenAPI / Swagger | `-i openapi.json` or `--format openapi` | Declared parameters become a name-only inventory (no values). | +| Raw HTTP request | `-i request.txt` or `--format raw` | `GET /path?x=1 HTTP/1.1` + `Host`; several requests via `###` lines. | +| Recon output | `-i httpx.txt`, `-i nuclei.jsonl`, `--format recon` | httpx/ffuf/katana/nuclei lines or JSONL, reduced to their URLs. | +| Postman | `-i collection.json` or `--format postman` | Collection v2.0/v2.1, nested folders, query/urlencoded/formdata/raw bodies. | +| OWASP ZAP | `-i zap.json` or `--format zap` | JSON history (`site.messages`) or alert export (`alerts[].instances`). | +| mitmproxy | `-i flows.json` or `--format mitmproxy` | A single flow or a list of flows; query and JSON/form bodies. | +| GraphQL | `-i introspection.json` or `--format graphql` | Argument names of the root query/mutation fields, nested args as `a.b`. | +| Cookie jar | `-i cookies.txt` or `--format cookies` | Netscape format; **names only**, values are discarded. | +| stdin | `cat urls.txt \| pathscope`, `pathscope -i -` | Auto-detected when no other source is given. | + +### Input format + +* `--format auto` (default) — detects, in order: HAR (`.har`/`.har.json` or a + `log.entries` object), a plain URL list, Postman, ZAP, GraphQL, mitmproxy, + cookie jar, Burp XML, OpenAPI JSON, raw HTTP request, recon output. +* `--format har|burp|openapi|raw|recon|postman|zap|mitmproxy|graphql|cookies|urls` + — force an input format. +* `--input-format {...}` — the same selectors under an unambiguous name. Use + `--input-format` together with `--format json` when you want to force the + input **and** choose output. + +`--format json|csv|sarif|text` selects the **output** format instead (see below). + +### What is read from a HAR + +| HAR location | Parameters analysed | +|---|---| +| `request.url` query string and `request.queryString` | query parameters (repeated names kept) | +| `request.postData.params` | multipart/form fields, using `value` or `fileName` | +| `request.postData.text` + `mimeType` | `application/x-www-form-urlencoded` fields, or flattened JSON body (dotted paths, `[n]` for arrays) | + +Only the request side is read. Responses, cookies, headers and timings are +ignored on purpose: they are noise for this question and may contain secrets. + +--- + +## Quick start + +All examples work on Kali with the repository checked out. + +```bash +# 1. A single URL +python3 path_detector.py --url 'https://example.test/view?file=report.pdf' + +# 2. A URL list (one per line) +python3 path_detector.py -i urls.txt + +# 3. Piped stdin +cat urls.txt | python3 path_detector.py + +# 4. A local HAR capture (auto-detected) +python3 path_detector.py -i capture.har + +# 5. HAR with JSON output for a report pipeline +python3 path_detector.py -i capture.har --format json > candidates.json + +# 6. Show existing values (they may contain secrets — be careful) +python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values + +# 7. Ignore noisy parameters, in CI +python3 path_detector.py -i urls.txt --ignore-param image --ignore-param avatar \ + --fail-on-findings +``` + +Example terminal output (values hidden): + +```console +$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' +PathScope 2.6.0 - passive path-parameter triage +---------------------------------------------------------------- +GitHub: https://github.com/mrdineshpathro +Instagram: https://www.instagram.com/mr_dineshpatro +Support: https://buymeacoffee.com/mrdineshpathro +Candidates for manual review only. No network requests are made; only analyze data you are authorized to review. + +PathScope candidates for manual review +==================================================================================== +Analyzed 1 request(s) and 1 parameter(s); 1 candidate(s) at score >= 25. + +#1 file [MEDIUM score 43/100] + Host example.test + Source url (--url) + Request GET https://example.test/view + Location query + Rule name-exact + Value (use --show-values) + Why rules and evidence: + - parameter name contains path-related term 'file' (+35) + - value ends with a file-like extension '.pdf' (+8) + +Reminder: these are candidates for manual review, not confirmed vulnerabilities. No requests were sent. +``` + +--- + +## Presets + +Three reporting postures, chosen with `--preset`. They change thresholds only — +never what counts as a finding. + +| Preset | Score threshold | Weak-name evidence | Use it when | +|---|---|---|---| +| `minimal` (aliases `strict`, `high`) | 50 | off | you want a very short list | +| `balanced` (alias `default`) | 25 | on | normal triage (default) | +| `noisy` (aliases `loud`, `broad`) | 10 | on | first pass over a large capture | + +Precedence: **CLI flags > configuration file > preset**. + +```bash +python3 path_detector.py -i capture.har --preset minimal + +# Write a validated starter config for the preset you use most +python3 path_detector.py --init-config pathscope.json --preset minimal +python3 path_detector.py -i capture.har --config pathscope.json +``` + +`--init-config` refuses to overwrite an existing file, so it is safe to re-run. + +## Baselines, diff and suppression + +Every finding carries a stable 16-hex **fingerprint** derived from +`host + location + parameter name + primary rule + path`. Values, scores and the +source file name are excluded, so a baseline survives new captures and new data. + +```bash +# 1. Save a JSON baseline (any run can produce one) +python3 path_detector.py -i capture.har --json > baseline.json + +# 2. Later: report only new candidates, and fail CI only on those +python3 path_detector.py -i capture-new.har --baseline baseline.json \ + --save-report triage.md --fail-on-findings +``` + +* `--baseline FILE` — known findings are marked `known` and hidden; `resolved` + entries (in the baseline but no longer present) are listed in text/Markdown/HTML. +* `--show-known` — keep known findings in the output, labelled `KNOWN`. +* `--suppress FILE` — hide reviewed fingerprints; accepts a PathScope JSON + report or a `{"suppressions": [{"fingerprint": "...", "note": "..."}]}` file. +* `--mark-reviewed FILE` — append the current run's fingerprints (with any + baseline note) to a reviewed ledger that `--suppress` can read later. +* `--fail-on-findings` in diff mode counts **new** candidates only, so a stable + baseline gives a quiet CI gate. + +Fingerprints appear in text, JSON (`"fingerprint"`, `"status"`), CSV and SARIF +(`partialFingerprints`), so any of them can be used as a baseline. + +## Reports + +Every format contains the same fields: `host`, `source_type`, `source`, +`method`, `location` (`query`/`form`/`json`), `parameter`, `occurrences`, +`rule`, `rules`, `confidence`, `score`, `reasons`, `resource`, and — only with +`--show-values` — `value`. + +### JSON (`--format json`, `--json`) + +```json +{ + "tool": "PathScope", + "version": "2.1.0", + "disclaimer": "Candidates for manual review only. ...", + "passive": true, + "network_requests_made": 0, + "min_score": 25, + "show_values": false, + "summary": { + "requests_analyzed": 1, + "parameters_analyzed": 3, + "candidates": 1, + "confidence": {"high": 0, "medium": 1, "low": 0}, + "skipped": 0, + "sources": ["urls.txt"], + "mode": "scan", + "new": 1, + "known": 0, + "resolved": 0 + }, + "warnings": [], + "findings": [ + { + "index": 1, + "host": "example.test", + "source_type": "file", + "source": "urls.txt", + "method": "GET", + "location": "query", + "parameter": "file", + "occurrences": 1, + "rule": "name-exact", + "rules": ["name-exact", "value-extension"], + "confidence": "medium", + "score": 43, + "reasons": [ + "parameter name contains path-related term 'file' (+35)", + "value ends with a file-like extension '.pdf' (+8)" + ], + "resource": "https://example.test/view", + "value": null, + "fingerprint": "ec274fecea647284", + "status": "new", + "note": "" + } + ], + "links": { + "github": "https://github.com/mrdineshpathro", + "instagram": "https://www.instagram.com/mr_dineshpatro", + "support": "https://buymeacoffee.com/mrdineshpathro" + } +} +``` + +### CSV (`--format csv`) + +Fixed column order, one finding per row, `values` empty unless `--show-values`: + +``` +index,host,source_type,source,method,location,parameter,rule,rules,confidence,score,reasons,resource,value +1,example.test,file,urls.txt,GET,query,file,name-exact,name-exact;value-extension,medium,43,"parameter name contains path-related term 'file' (+35); value ends with a file-like extension '.pdf' (+8)",https://example.test/view, +``` + +### Markdown and HTML (`--format markdown|html`, `--save-report FILE`) + +Standalone reports for tickets and reviews: summary metadata, a candidate table +with fingerprints and statuses, a "why each candidate was flagged" section, the +resolved list in diff mode, and input warnings. HTML is fully escaped (a +parameter named `", sources.SOURCE_URL, "--self-test" + ) + report = detector.analyze_requests([request], detector.AnalysisOptions()) + markup = writers.render_html(report) + assert "" not in markup, "unescaped markup in HTML" + + def decode_bounded() -> None: + forms = textutil.decode_forms("%25252e%25252e", 1) + passes, text = forms[-1] + assert passes <= 1, passes + assert "%25" in text, text + + def scrub_redacts_secrets() -> None: + from . import scrub + + secret = "ghp_" + "a" * 36 + assert scrub.should_scrub("file", secret), "vendor token not detected" + marker = scrub.scrub_value(secret) + assert marker.startswith(" None: + from . import playbooks + from .rules import DEFAULT_BOOK + + missing = playbooks.validate_playbook_coverage() + assert not missing, f"rules without a playbook: {missing}" + assert DEFAULT_BOOK.as_dict(), "empty rule book" + + def bundle_is_reproducible() -> None: + import tempfile, os + from . import bundle, detector + + request = sources.request_from_url( + "https://a.test/?file=../../etc/passwd", sources.SOURCE_URL, "--self-test" + ) + report = detector.analyze_requests([request], detector.AnalysisOptions()) + first = tempfile.mktemp(suffix=".zip") + second = tempfile.mktemp(suffix=".zip") + try: + bundle.build_bundle(first, report) + bundle.build_bundle(second, report) + with open(first, "rb") as handle: + left = handle.read() + with open(second, "rb") as handle: + right = handle.read() + assert left == right, "bundles differ byte-for-byte" + finally: + for path in (first, second): + if os.path.exists(path): + os.unlink(path) + + def ledger_roundtrip() -> None: + import tempfile, os + from . import ledger + + path = tempfile.mktemp(suffix=".db") + try: + store = ledger.open_ledger(path) + store.record("fp-self-test", status="reviewed", host="a.test", + parameter="file", rule="name-exact", reviewer="self-test") + assert "fp-self-test" in store.fingerprints(), "record not stored" + stats = store.stats() + assert stats["total"] == 1, stats + assert stats["by_status"] == {"reviewed": 1}, stats + assert stats["reviewers"] == ["self-test"], stats + store.close() + finally: + if os.path.exists(path): + os.unlink(path) + + def stream_is_bounded() -> None: + from . import detector, stream + + text = "\n".join(f"https://h{i}.test/?file=../../x" for i in range(25)) + result = stream.stream_text(text, detector.AnalysisOptions(), batch_size=10) + assert result.stats.batches == 3, result.stats.batches + assert result.report.requests_analyzed == 25, result.report.requests_analyzed + assert result.report.candidate_count == 25, result.report.candidate_count + + def history_tracks_trends() -> None: + import tempfile, os + from . import detector, history + + path = tempfile.mktemp(suffix=".json") + try: + for count in (3, 2): + requests = [ + sources.request_from_url( + f"https://h{i}.test/?file=../../x", sources.SOURCE_URL, "t" + ) + for i in range(count) + ] + report = detector.analyze_requests(requests, detector.AnalysisOptions()) + history.append_run(path, history.run_record(report)) + trend = history.analyze_history(history.load_history(path)) + assert trend.runs == 2, trend.runs + assert trend.counts == [3, 2], trend.counts + assert len(trend.latest_resolved) == 1, trend.latest_resolved + finally: + if os.path.exists(path): + os.unlink(path) + + def expiry_math_is_sound() -> None: + from . import ledger + + stamp = ledger.parse_expiry("24h", now="2026-01-01T00:00:00Z") + assert stamp == "2026-01-02T00:00:00Z", stamp + assert ledger.parse_expiry("none") == "", "none must mean no expiry" + try: + ledger.parse_expiry("soon") + except ledger.LedgerError: + pass + else: # pragma: no cover - regression guard + raise AssertionError("a bad expiry spec was accepted") + + def capture_diff_detects_renames() -> None: + from . import capturediff + + old = sources.load_url_lines( + ["https://a.test/x?file=/a"], sources.SOURCE_URL, "selftest" + ).requests + new = sources.load_url_lines( + ["https://a.test/x?file_id=/b"], sources.SOURCE_URL, "selftest" + ).requests + diff = capturediff.compare(old, new) + assert [c.describe() for c in diff.renamed] == ["file -> file_id"], diff.renamed + # unrelated names must not be paired + other = capturediff.compare( + sources.load_url_lines(["https://a.test/x?q=/a"], sources.SOURCE_URL, "s").requests, + sources.load_url_lines(["https://a.test/x?file=/a"], sources.SOURCE_URL, "s").requests, + ) + assert other.renamed == [], other.renamed + + def extraction_is_local() -> None: + from . import extractor + + found = extractor.extract_text( + 'fetch("https://app.test/api?file=/a");', "selftest.js" + ) + assert any(entry.value.endswith("/api?file=/a") for entry in found), found + + def term_packs_reject_regex() -> None: + from . import termpacks + + try: + termpacks.validate_payload({"terms": ["file.*"]}) + except termpacks.TermPackError: + pass + else: # pragma: no cover - regression guard + raise AssertionError("a regular expression was accepted as a term") + pack = termpacks.starter_pack("selftest") + assert pack.terms, "starter pack has no terms" + + def project_paths_stay_inside() -> None: + from . import project + + try: + project.validate_payload({"version": 1, "config": "/etc/passwd"}, source="/tmp/x") + except project.ProjectError: + pass + else: # pragma: no cover - regression guard + raise AssertionError("a project file escaped its directory") + + def calibration_uses_the_rules_it_documents() -> None: + import tempfile, os + from . import calibrate, ledger + + path = tempfile.mktemp(suffix=".db") + try: + store = ledger.open_ledger(path) + for index, score in enumerate([80, 75, 70, 65, 60, 55, 50, 45]): + store.record(f"a{index}", status="accepted", score=score) + for index, score in enumerate([40, 35, 30, 25, 20, 15, 12, 10]): + store.record(f"f{index}", status="false-positive", score=score) + result = calibrate.calibrate(store) + store.close() + assert result.recommended is not None, "no recommendation from clean data" + best = result.best() + assert best.recall >= calibrate.DEFAULT_MIN_RECALL, best.recall + assert best.fp_rate <= calibrate.DEFAULT_MAX_FP_RATE, best.fp_rate + finally: + if os.path.exists(path): + os.unlink(path) + + def route_shapes_collapse_identifiers() -> None: + from . import families + + assert families.route_shape("/items/1/view") == "/items/{id}/view" + assert families.route_shape("/items/2/view") == "/items/{id}/view" + assert families.route_shape("/v2/items") == "/v2/items" + + def sampling_is_reproducible() -> None: + from . import sampling, sources + + requests = sources.load_url_lines( + [f"https://h{i % 3}.test/p/{i}?file=/a/b" for i in range(30)], + "url", + "selftest", + ).requests + first = sampling.sample(requests, 6, seed=99) + second = sampling.sample(requests, 6, seed=99) + assert first.size == 6, first.size + assert [r.url.raw for r in first.requests] == [ + r.url.raw for r in second.requests + ], "the same seed must select the same subset" + other = sampling.sample(requests, 6, seed=100) + assert [r.url.raw for r in other.requests] != [ + r.url.raw for r in first.requests + ], "a different seed should select a different subset" + + def scope_wildcard_stays_in_one_label() -> None: + from . import scope as scope_module + + parsed = scope_module.from_payload({"in_scope": ["*.a.test"]}) + assert parsed.allows("api.a.test"), "api.a.test should be in scope" + assert not parsed.allows("deep.api.a.test"), "a wildcard must not cross a dot" + assert not parsed.allows("a.test"), "a wildcard must match a label" + + def redaction_is_keyed_and_stable() -> None: + from . import redact + + first = redact.build_map("selftest-key") + second = redact.build_map("selftest-key") + other = redact.build_map("another-key") + name = first.pseudonym("a.test") + assert name == second.pseudonym("a.test"), "same key must give the same name" + assert name != other.pseudonym("a.test"), "a different key must differ" + assert "a.test" not in name, "the pseudonym must not contain the host" + + def spec_templates_match_one_segment() -> None: + from . import openapi + + spec = openapi.parse_spec( + { + "openapi": "3.0.0", + "info": {"title": "t", "version": "1"}, + "paths": {"/d/{id}/v": {"get": {}}}, + } + ) + assert len(spec.operations) == 1, "one operation expected" + + def pr_comment_states_the_truth() -> None: + from . import detector, prcomment, sources + + report = detector.analyze_requests( + sources.load_url_lines( + ["https://a.test/view?file=../../etc/passwd"], "url", "selftest" + ).requests, + detector.AnalysisOptions(), + ) + comment = prcomment.render_comment(report, exit_code=0) + assert comment.body.startswith(prcomment.MARKER), "marker must come first" + if report.findings: + assert "no new candidates" not in comment.body, ( + "a report with findings must not claim there are none" + ) + + def waivers_demand_ownership() -> None: + from . import waivers + + base = {"host": "a.test", "reason": "r", "owner": "o"} + waivers.parse_waivers({"waivers": [base]}) + for missing in ("reason", "owner"): + payload = {k: v for k, v in base.items() if k != missing} + try: + waivers.parse_waivers({"waivers": [payload]}) + except waivers.WaiverError: + continue + raise AssertionError(f"a waiver without '{missing}' was accepted") + try: + waivers.parse_waivers({"waivers": [{"reason": "r", "owner": "o"}]}) + except waivers.WaiverError: + pass + else: + raise AssertionError("a waiver matching everything was accepted") + + def expired_waiver_hides_nothing() -> None: + from . import detector, sources, waivers + + report = detector.analyze_requests( + sources.load_url_lines( + ["https://a.test/view?file=../../etc/passwd"], "url", "selftest" + ).requests, + detector.AnalysisOptions(), + ) + loaded = waivers.parse_waivers( + { + "waivers": [ + { + "host": "a.test", + "parameter": "file", + "reason": "old", + "owner": "o", + "expires": "2000-01-01", + } + ] + } + ) + hidden, skipped = waivers.apply_waivers(report.findings, loaded) + assert hidden == 0, f"an expired waiver hid {hidden} finding(s)" + assert skipped == 1, skipped + assert all(f.status != "waived" for f in report.findings) + + def query_parser_never_evaluates() -> None: + from . import query + + for expression in ("__import__('os')", "score > 1; import os"): + try: + query.parse(expression) + except query.QueryError: + continue + raise AssertionError(f"the query parser accepted {expression!r}") + node = query.parse("score > 20 and confidence = high") + assert query.describe(node), "a parsed filter must describe itself" + + def simulation_cannot_alter_the_run() -> None: + from . import detector, simulate, sources + + options = detector.AnalysisOptions() + before = dict(options.book.weights) + requests = sources.load_url_lines( + ["https://a.test/view?file=../../etc/passwd"], "url", "selftest" + ).requests + result = simulate.simulate( + requests, options, simulate.parse_changes("name-exact=off") + ) + assert result.before is not None and result.after is not None + assert options.book.weights == before, "simulation mutated the real rule book" + + def attestation_detects_edits() -> None: + import json as _json + import tempfile as _tempfile + + from . import attest + + built = attest.build(inputs=[], rendered="original body") + handle = _tempfile.NamedTemporaryFile( + "w", suffix=".json", delete=False, encoding="utf-8" + ) + handle.write(built.render()) + handle.close() + try: + assert attest.verify(handle.name, rendered="original body") == [] + problems = attest.verify(handle.name, rendered="edited body") + assert problems, "an edited report must not verify" + payload = _json.loads(built.render()) + assert payload["signature"] is None, "an attestation is not a signature" + finally: + import os as _os + + _os.unlink(handle.name) + + def merge_conflicts_are_visible() -> None: + import tempfile as _tempfile + + from . import ledger, ledgermerge + + directory = _tempfile.mkdtemp(prefix="pathscope-selftest-") + try: + left = ledger.open_ledger(_join(directory, "l.db")) + right = ledger.open_ledger(_join(directory, "r.db")) + left.record("fp", status="accepted", reviewer="a") + right.record("fp", status="false-positive", reviewer="b") + result = ledgermerge.plan(left, right) + left.close() + right.close() + assert len(result.conflicts) == 1, len(result.conflicts) + assert not result.applied, "plan() must never write" + assert "accepted" in result.conflicts[0].describe() + finally: + import shutil as _shutil + + _shutil.rmtree(directory, ignore_errors=True) + + def completion_tracks_the_parser() -> None: + from . import completion, cli + + parser = cli.build_parser() + script = completion.render("bash", parser) + assert "--redact-hosts" in script, "completion must mention --redact-hosts" + assert "--cluster" in script, "completion must mention --cluster" + flags = completion.collect_flags(parser) + assert len(flags) > 50, f"expected many flags, found {len(flags)}" + + return [ + ("banner strings are exact", banner_exact), + ("URLs are parsed locally", url_parse), + ("query strings split literally", query_split), + ("traversal values score", traversal_scores), + ("ordinary parameters stay quiet", ordinary_ignored), + ("values are hidden by default", values_hidden), + ("configuration validates", config_roundtrip), + ("every renderer produces a report", report_renderers), + ("HTML output escapes input", html_escapes), + ("decoding is bounded", decode_bounded), + ("secret scrubbing redacts credentials", scrub_redacts_secrets), + ("every rule has a playbook", playbooks_cover_rules), + ("bundle export is reproducible", bundle_is_reproducible), + ("review ledger round-trips", ledger_roundtrip), + ("streaming is batched and bounded", stream_is_bounded), + ("run history tracks trends", history_tracks_trends), + ("acceptance expiry maths is sound", expiry_math_is_sound), + ("capture diffs detect real renames", capture_diff_detects_renames), + ("URL extraction is local", extraction_is_local), + ("term packs reject regular expressions", term_packs_reject_regex), + ("project paths stay inside the project", project_paths_stay_inside), + ("calibration obeys its own bounds", calibration_uses_the_rules_it_documents), + ("route shapes collapse identifiers", route_shapes_collapse_identifiers), + ("sampling is reproducible", sampling_is_reproducible), + ("scope wildcards stay in one label", scope_wildcard_stays_in_one_label), + ("redaction is keyed and stable", redaction_is_keyed_and_stable), + ("a spec template matches one segment", spec_templates_match_one_segment), + ("the PR comment states the truth", pr_comment_states_the_truth), + ("completion tracks the parser", completion_tracks_the_parser), + ("waivers demand a reason and an owner", waivers_demand_ownership), + ("an expired waiver hides nothing", expired_waiver_hides_nothing), + ("the query parser never evaluates", query_parser_never_evaluates), + ("simulation cannot alter the real run", simulation_cannot_alter_the_run), + ("attestation detects an edited report", attestation_detects_edits), + ("a merge conflict is never silent", merge_conflicts_are_visible), + ] + + +def run_selftest() -> List[Dict[str, object]]: + """Run every built-in check. Returns ``[{name, passed, error}]``.""" + results: List[Dict[str, object]] = [] + for name, check in _selftest_checks(): + try: + check() + except Exception as exc: # noqa: BLE001 - a failed check is data, not a crash + results.append({"name": name, "passed": False, "error": str(exc) or type(exc).__name__}) + else: + results.append({"name": name, "passed": True, "error": ""}) + return results + + +def render_selftest(results: Sequence[Dict[str, object]]) -> str: + """Human-readable ``--self-test`` output.""" + lines = [f"{PROGRAM} self-test ({__version__})"] + failures = 0 + for entry in results: + status = "ok " if entry["passed"] else "FAIL" + suffix = "" if entry["passed"] else f" - {entry['error']}" + lines.append(f" [{status}] {entry['name']}{suffix}") + if not entry["passed"]: + failures += 1 + lines.append("") + if failures: + lines.append(f"{failures} of {len(results)} checks failed.") + else: + lines.append(f"All {len(results)} checks passed. No network access was used.") + return "\n".join(lines) + + +def run_doctor() -> List[Dict[str, object]]: + """Environment checks for ``--doctor``: is this install usable here? + + Unlike :func:`run_selftest` (which proves the *analysis* behaves), this + looks outward: interpreter, terminal, filesystem and optional features. + Every check is local; nothing is downloaded or resolved. + """ + import os + import platform + import sqlite3 + import sys + import tempfile + + results: List[Dict[str, object]] = [] + + def report(name: str, ok: bool, detail: str = "") -> None: + results.append({"name": name, "passed": ok, "detail": detail, "error": ""}) + + version = platform.python_version() + report( + "python version", + sys.version_info >= (3, 8), + f"{version} ({platform.python_implementation()})", + ) + report("platform", True, f"{platform.system()} {platform.release()} ({platform.machine()})") + report("executable", True, os.path.abspath(sys.executable)) + + # curses: the TUI needs it, everything else does not. + try: + import curses # noqa: F401 + + has_curses = True + except ImportError: # pragma: no cover - platform dependent + has_curses = False + report("curses (for --tui)", has_curses, "available" if has_curses else "unavailable") + + tty = False + try: + tty = bool(sys.stdout.isatty() and sys.stdin.isatty()) + except Exception: # noqa: BLE001 - exotic streams + tty = False + report("interactive terminal", True, "yes" if tty else "no (fine for CI and pipes)") + + # sqlite3 backs the review ledger; it is compiled into CPython normally. + try: + connection = sqlite3.connect(":memory:") + connection.execute("CREATE TABLE t (x INTEGER)") + connection.close() + report("sqlite3 (for --ledger)", True, f"SQLite {sqlite3.sqlite_version}") + except Exception as exc: # noqa: BLE001 + report("sqlite3 (for --ledger)", False, str(exc)) + + # A writable temp dir is needed for bundles, history and the ledger. + try: + handle = tempfile.NamedTemporaryFile(prefix="pathscope-doctor-", delete=True) + handle.write(b"ok") + handle.close() + report("temporary directory", True, tempfile.gettempdir()) + except Exception as exc: # noqa: BLE001 + report("temporary directory", False, str(exc)) + + # zipfile backs --bundle. CPython can be built without zlib. + try: + import zipfile + + buffer = tempfile.SpooledTemporaryFile() + with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr("x.txt", "y") + report("zipfile with deflate (for --bundle)", True, "available") + buffer.close() + except Exception as exc: # noqa: BLE001 + report("zipfile with deflate (for --bundle)", False, str(exc)) + + # The bundled sources must be complete, not just importable. + import pathlib + + package_dir = pathlib.Path(__file__).resolve().parent + expected = [ + "cli", "detector", "rules", "sources", "report", "writers", "analytics", + "history", "ledger", "playbooks", "scrub", "stream", "bundle", "tui", + ] + missing = [name for name in expected if not (package_dir / f"{name}.py").is_file()] + report("package integrity", not missing, ", ".join(missing) or "all modules present") + + # Nothing in the environment should make PathScope reach the network. + proxies = [key for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY") if os.environ.get(key)] + report( + "network configuration", + True, + "proxy variables set but never used" if proxies else "no networking code", + ) + return results + + +def render_doctor(results: Sequence[Dict[str, object]]) -> str: + """Human-readable ``--doctor`` output.""" + lines = [f"{PROGRAM} environment check ({__version__})"] + for entry in results: + mark = "ok " if entry["passed"] else "WARN" + detail = entry.get("detail") or entry.get("error") or "" + lines.append(f" [{mark}] {entry['name']:<38} {detail}") + warnings = sum(1 for entry in results if not entry["passed"]) + lines.append("") + if warnings: + lines.append(f"{warnings} check(s) need attention; PathScope can still run.") + else: + lines.append(f"All {len(results)} environment checks passed.") + return "\n".join(lines) + + +__all__ = [ + "JUNIT_BANDS", + "render_doctor", + "render_github_annotations", + "render_junit", + "render_selftest", + "run_doctor", + "run_selftest", +] diff --git a/pathscope/cli.py b/pathscope/cli.py new file mode 100644 index 0000000..0eb2fd0 --- /dev/null +++ b/pathscope/cli.py @@ -0,0 +1,3183 @@ +"""Command-line interface for PathScope. + +Exit codes (documented in ``--help`` and the README): + + 0 analysis completed, no candidates found + 1 analysis completed, candidates found (only with --fail-on-findings) + 2 usage error, unreadable input, invalid configuration, or no usable input + 3 internal error while producing a report + 130 interrupted with Ctrl-C + +The CLI never opens a socket. Input is read from arguments, local files or +stdin only. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from typing import Optional, Sequence + +from . import ( + GITHUB_URL, + INSTAGRAM_URL, + PROGRAM, + SUPPORT_URL, + __version__, +) +from .presets import ( + PRESET_NAMES, + STARTER_CONFIGS, + describe_presets, + resolve_preset, +) +from . import presets as presets_module +from . import assign as assign_module +from . import attest as attest_module +from . import audit as audit_module +from . import completion as completion_module +from . import impact as impact_module +from . import ledgermerge as ledgermerge_module +from . import precision as precision_module +from . import query as query_module +from . import scorechange as scorechange_module +from . import simulate as simulate_module +from . import waivers as waivers_module +from . import families as families_module +from . import openapi as openapi_module +from . import prcomment as prcomment_module +from . import queue as queue_module +from . import redact as redact_module +from . import sampling as sampling_module +from . import scope as scope_module +from . import shadow as shadow_module +from . import tickets as tickets_module +from dataclasses import replace +from .naming import describe_languages, parse_languages +from . import ci as ci_module +from .config import Config, ConfigError, describe_schema, load_config, merge_ignore +from .policy import PolicyError, Policy, evaluate as evaluate_policy, load_policy, parse_inline_policy, starter_policy +from .detector import ( + DEFAULT_MIN_SCORE, + AnalysisOptions, + Baseline, + analyze_requests, + apply_baseline, + summarize, +) +from .heuristics import analyze_parameter +from .report import ( + FORMAT_CSV, + FORMAT_HTML, + FORMAT_JSON, + FORMAT_JUNIT, + FORMAT_MARKDOWN, + FORMAT_SARIF, + FORMAT_TEXT, + FORMATS, + Palette, + render, + render_banner, + render_text, + render_explanation, + supports_color, +) +from .progress import NullProgress, Progress +from .rules import ( + RuleBook, + RuleError, + format_rule_table, + load_rule_overrides, + normalize_rule_id, +) +from .valueshape import describe_shapes +from . import analytics as analytics_module +from . import history as history_module +from . import ledger as ledger_module +from . import playbooks as playbooks_module +from . import scrub as scrub_module +from . import bundle as bundle_module +from . import stream as stream_module +from . import tui as tui_module +from . import capturediff as capturediff_module +from . import calibrate as calibrate_module +from . import extractor as extractor_module +from . import project as project_module +from . import termpacks as termpacks_module +from .sources import ( + INPUT_FORMAT_AUTO, + INPUT_FORMATS, + InputError, + LoadResult, + load_file, + load_stdin, + make_url_requests, +) +from .textutil import MAX_DECODE_PASSES +from .writers import ( + SUPPORTED_EXTENSIONS, + render_html_interactive, + write_report, + writer_supports_interactive, +) + +EXIT_OK = 0 +EXIT_FINDINGS = 1 +EXIT_USAGE = 2 +EXIT_INTERNAL = 3 +EXIT_INTERRUPTED = 130 + +#: ``--format`` accepts both input selectors and output formats, because the +#: specification uses the same flag for ``--format har`` and ``--format json``. +FORMAT_CHOICES = tuple(dict.fromkeys(INPUT_FORMATS + FORMATS)) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="path_detector.py", + description=( + "PathScope: passive, offline triage of URL and request parameters " + "that may be worth reviewing for path-traversal risk. Findings are " + "heuristic candidates for manual review, never proof of a " + "vulnerability. No requests are made and no values are sent." + ), + epilog=( + "examples:\n" + " python3 path_detector.py --url 'https://example.test/view?file=report.pdf'\n" + " python3 path_detector.py -i urls.txt\n" + " python3 path_detector.py -i capture.har --format json\n" + " cat urls.txt | python3 path_detector.py --format sarif\n" + " python3 path_detector.py -i capture.har --ignore-param image\n" + " python3 path_detector.py -i urls.txt --fail-on-findings\n" + "\n" + "note: --format selects a HAR/URLs *input* for har/urls/auto and a\n" + " report *output* for text/json/csv/sarif. Use --input-format or\n" + " --output-format to set both in one run.\n" + "\n" + "exit codes:\n" + " 0 no candidates 1 candidates with --fail-on-findings, or a\n" + " failed --policy 2 usage/input error\n" + " 3 internal error 130 interrupted (--self-test: 1 on failure)\n" + "\n" + "presets (--preset):\n" + + "\n".join(describe_presets()) + + "\n\nconfiguration file (--config FILE, JSON, literal terms only):\n" + + "\n".join(describe_schema()) + + "\n\nlinks (displayed only, never opened):\n" + f" GitHub: {GITHUB_URL}\n" + f" Instagram: {INSTAGRAM_URL}\n" + f" Support: {SUPPORT_URL}\n" + ), + formatter_class=argparse.RawDescriptionHelpFormatter, + add_help=False, + allow_abbrev=False, + ) + parser.add_argument( + "-h", "--help", action="help", help="show this help message and exit" + ) + parser.add_argument( + "--version", action="version", version=f"{PROGRAM} {__version__}" + ) + + source = parser.add_argument_group("input (sources are merged and de-duplicated)") + source.add_argument( + "--url", + action="append", + default=[], + metavar="URL", + help="URL to analyze; repeat for multiple URLs. Quote URLs containing '&'.", + ) + source.add_argument( + "-i", + "--input", + action="append", + default=[], + metavar="FILE", + help="read URLs (one per line) or a local HAR 1.2 file; may be repeated; " + "'-' reads stdin", + ) + source.add_argument( + "--format", + dest="format", + choices=FORMAT_CHOICES, + default=None, + metavar="{auto,urls,har,text,json,csv,sarif,junit}", + help="input selector (har/urls/auto) or output format (text/json/csv/sarif)", + ) + source.add_argument( + "--input-format", + choices=INPUT_FORMATS, + default=None, + metavar="{auto,urls,har,...}", + help="force the input format for files and stdin (default: auto-detect): " + + ",".join(INPUT_FORMATS), + ) + + output = parser.add_argument_group("output") + output.add_argument( + "--output-format", + choices=FORMATS, + default=None, + metavar="{text,json,csv,sarif,markdown,html,junit}", + help="report format written to stdout (default: text)", + ) + output.add_argument( + "--json", + action="store_true", + help="shorthand for --output-format json", + ) + output.add_argument( + "--show-values", + action="store_true", + help="reveal parameter values; hidden by default because they may hold secrets", + ) + output.add_argument( + "--no-color", + action="store_true", + help="disable ANSI colour even on a terminal (NO_COLOR is also honoured)", + ) + output.add_argument( + "--no-banner", + action="store_true", + help="do not print the startup banner and links", + ) + output.add_argument( + "-q", + "--quiet", + action="store_true", + help="suppress warnings and the stderr summary (stdout is unaffected)", + ) + output.add_argument( + "--save-report", + metavar="FILE", + help="also write a standalone Markdown (.md) or HTML (.html) report", + ) + output.add_argument( + "--interactive", + action="store_true", + help="with an HTML --save-report, add sorting, filtering and review " + "checkboxes (stored in this browser only)", + ) + output.add_argument( + "--progress", + action="store_true", + help="show phase progress on stderr (stdout stays machine-readable)", + ) + output.add_argument( + "--stats", + action="store_true", + help="print parse/analyze timings and counts to stderr (and JSON)", + ) + output.add_argument( + "--github-annotations", + action="store_true", + help="print GitHub Actions ::warning/::notice annotations on stdout", + ) + output.add_argument( + "--top", + type=int, + default=0, + metavar="N", + help="only show the N highest-scoring candidates in text output (0 = all)", + ) + output.add_argument( + "--group-by", + choices=("none", "host", "rule", "confidence", "location"), + default="none", + help="group text output by a field (default: none)", + ) + output.add_argument( + "--summary-only", + action="store_true", + help="print only the summary line and a per-confidence table", + ) + + tuning = parser.add_argument_group("detection and configuration") + tuning.add_argument( + "--preset", + choices=tuple(PRESET_NAMES) + ("strict", "high", "default", "loud", "broad"), + default=None, + help="reporting posture: minimal (>=50, no weak names), balanced (>=25), " + "noisy (>=10); aliases: strict/high, default, loud/broad", + ) + tuning.add_argument( + "--baseline", + metavar="FILE", + help="previous PathScope JSON report; mark its findings as known", + ) + tuning.add_argument( + "--show-known", + action="store_true", + help="with --baseline/--suppress, still list already-known candidates", + ) + tuning.add_argument( + "--suppress", + metavar="FILE", + help="JSON list of reviewed fingerprints (with optional notes) to hide", + ) + tuning.add_argument( + "--mark-reviewed", + metavar="FILE", + help="write reviewed fingerprints (with --baseline notes) to FILE", + ) + tuning.add_argument( + "--explain", + metavar="PARAM", + help="print the scoring trace for one parameter name and exit", + ) + tuning.add_argument( + "--explain-value", + metavar="VALUE", + default="", + help="value to score with --explain (treated as an inert string)", + ) + tuning.add_argument( + "--init-config", + metavar="FILE", + help="write a starter configuration (requires --preset, default balanced) and exit", + ) + tuning.add_argument( + "--ignore-param", + action="append", + default=[], + metavar="NAME", + help="ignore a parameter name entirely; may be repeated", + ) + tuning.add_argument( + "--config", + metavar="FILE", + help="JSON configuration with extra name terms, ignored names and defaults", + ) + tuning.add_argument( + "--min-score", + type=int, + default=None, + metavar="N", + help=f"report parameters scoring at least N (0-100, default: {DEFAULT_MIN_SCORE})", + ) + tuning.add_argument( + "--max-decode-passes", + type=int, + default=None, + metavar="N", + help=f"maximum percent-decoding passes per value (0-5, default: {MAX_DECODE_PASSES})", + ) + + behaviour = parser.add_argument_group("behaviour") + behaviour.add_argument( + "--fail-on-findings", + action="store_true", + help="exit 1 when candidates are found (useful in CI); 0 when none are", + ) + behaviour.add_argument( + "--watch", + metavar="FILE", + help="re-analyze FILE whenever it changes and print only new candidates " + "(Ctrl-C to stop)", + ) + behaviour.add_argument( + "--interval", + type=float, + default=2.0, + metavar="SECONDS", + help="polling interval for --watch (default: 2)", + ) + + rules_group = parser.add_argument_group("rules and tuning") + rules_group.add_argument( + "--list-rules", + action="store_true", + help="print every rule with its effective weight and exit", + ) + rules_group.add_argument( + "--rules", + metavar="FILE", + help="JSON weight overrides, e.g. {\"weights\": {\"name-exact\": 30}, " + "\"disable\": [\"name-weak\"]}", + ) + rules_group.add_argument( + "--disable-rule", + action="append", + default=[], + metavar="RULE", + help="remove a rule from scoring; may be repeated (see --list-rules)", + ) + rules_group.add_argument( + "--name-lang", + metavar="LIST", + default=None, + help="term packs: de,es,fr,pt,it,nl, auto (all) or off (default: off)", + ) + rules_group.add_argument( + "--no-fold", + action="store_true", + help="disable diacritic/compatibility folding of parameter names", + ) + rules_group.add_argument( + "--no-demote", + action="store_true", + help="disable value-shape demotion (UUID/hash/JWT/base64/email/IP/scalar)", + ) + rules_group.add_argument( + "--dedupe-by", + choices=("path", "param", "none"), + default="path", + help="collapse repeated findings by path (default), by parameter name, or not at all", + ) + rules_group.add_argument( + "--max-entries", + type=int, + default=0, + metavar="N", + help="analyze at most N input entries (0 = unlimited)", + ) + + ci_group = parser.add_argument_group("CI integration") + ci_group.add_argument( + "--policy", + metavar="FILE|JSON", + help="policy file (max_high/max_medium/max_low/max_total/min_score/...) " + "or inline JSON; exit 1 when violated", + ) + ci_group.add_argument( + "--init-policy", + metavar="FILE", + help="write a starter policy file and exit", + ) + ci_group.add_argument( + "--self-test", + action="store_true", + help="run built-in environment checks and exit (1 if any fail)", + ) + + review = parser.add_argument_group("review workflow") + review.add_argument( + "--doctor", + action="store_true", + help="check this installation (interpreter, sqlite, zip, TUI) and exit", + ) + review.add_argument( + "--tui", + action="store_true", + help="open an interactive terminal reviewer (needs a real terminal)", + ) + review.add_argument( + "--ledger", + metavar="FILE", + help="SQLite review ledger: hides reviewed fingerprints and stores an audit trail", + ) + review.add_argument( + "--ledger-mark-all", + action="store_true", + help="record every candidate in --ledger with --ledger-status", + ) + review.add_argument( + "--ledger-status", + choices=("reviewed", "accepted", "false-positive", "resolved"), + default="reviewed", + # NOTE: default None in ``_USER_SET``; argparse fills "reviewed". + help="status recorded when marking (default: reviewed)", + ) + review.add_argument( + "--reviewer", + metavar="NAME", + default="", + help="name recorded in the ledger audit trail (default: $USER)", + ) + review.add_argument( + "--review-note", + metavar="TEXT", + default="", + help="note recorded with --mark-reviewed/--ledger-status", + ) + review.add_argument( + "--ledger-query", + metavar="TEXT", + help="filter ledger reviews by host, parameter, rule or status and exit", + ) + review.add_argument( + "--ledger-export", + metavar="FILE", + help="write the ledger as a --baseline compatible JSON file and exit", + ) + review.add_argument( + "--import-ledger", + metavar="FILE", + help="import a 2.1 flat JSON ledger into --ledger and exit", + ) + + insight = parser.add_argument_group("analysis and reporting extras") + insight.add_argument( + "--dashboard", + action="store_true", + help="print score distribution, percentiles, coverage gaps and frequency", + ) + insight.add_argument( + "--inventory", + action="store_true", + help="list endpoints by number of distinct parameters", + ) + insight.add_argument( + "--correlate", + action="store_true", + help="show the parameter x host matrix, shared parameters and chains", + ) + insight.add_argument( + "--playbook", + metavar="FILE", + help="write a Markdown remediation guide for this run", + ) + insight.add_argument( + "--list-playbooks", + action="store_true", + help="list the remediation playbooks and exit", + ) + insight.add_argument( + "--history", + metavar="FILE", + help="append this run to a JSON history file (values are never stored)", + ) + insight.add_argument( + "--trend", + metavar="FILE", + help="analyse a JSON history file and print the trend, then exit", + ) + scrub_group = insight.add_mutually_exclusive_group() + scrub_group.add_argument( + "--scrub", + action="store_true", + help="redact credential-shaped values when --show-values is used", + ) + scrub_group.add_argument( + "--no-scrub", + action="store_true", + help="never redact values (bundle exports still scrub)", + ) + insight.add_argument( + "--bundle", + metavar="FILE", + help="write a reproducible, scrubbed support bundle (.zip)", + ) + insight.add_argument( + "--inspect-bundle", + metavar="FILE", + help="print the manifest of a bundle written by --bundle and exit", + ) + insight.add_argument( + "--stream", + action="store_true", + help="read stdin line by line with bounded memory (URL lists and recon)", + ) + insight.add_argument( + "--stream-batch", + type=int, + default=200, + metavar="N", + help="report every N streamed requests (default: 200)", + ) + insight.add_argument( + "--stream-json", + action="store_true", + help="with --stream, emit one JSON object per batch instead of text", + ) + + project_group = parser.add_argument_group("project and workflow") + project_group.add_argument( + "--diff-capture", + metavar="FILE", + help="compare -i/--input against an earlier capture and show what changed", + ) + project_group.add_argument( + "--diff-json", + action="store_true", + help="with --diff-capture, emit the diff as JSON instead of text", + ) + project_group.add_argument( + "--extract", + metavar="FILE", + action="append", + default=[], + help="extract endpoint strings from a local HTML/JS file and analyse them " + "(repeatable; nothing is fetched)", + ) + project_group.add_argument( + "--extract-host", + metavar="HOST", + help="resolve relative URLs in --extract files against this host", + ) + project_group.add_argument( + "--extract-all-hosts", + action="store_true", + help="keep endpoints on every host found in --extract files (default: own origin)", + ) + project_group.add_argument( + "--value-stats", + action="store_true", + help="profile value lengths/encoding/entropy without printing any value", + ) + project_group.add_argument( + "--rule-coverage", + action="store_true", + help="show which rules fired and which stayed silent on this input", + ) + project_group.add_argument( + "--terms", + metavar="FILE", + action="append", + default=[], + help="load extra literal terms from a term pack (repeatable)", + ) + project_group.add_argument( + "--init-terms", + metavar="FILE", + help="write a starter term pack and exit", + ) + project_group.add_argument( + "--list-terms", + metavar="FILE", + action="append", + default=[], + help="validate term pack(s) and print a summary, then exit", + ) + project_group.add_argument( + "--compare-presets", + action="store_true", + help="show how minimal/balanced/noisy classify the same candidates", + ) + project_group.add_argument( + "--calibrate", + action="store_true", + help="recommend a --min-score from accepted vs false-positive ledger reviews", + ) + project_group.add_argument( + "--ledger-scores", + action="store_true", + help="print the score distribution of the ledger reviews and exit", + ) + project_group.add_argument( + "--ledger-expire", + metavar="DURATION", + help="expiry for reviews written this run (30d/12h/2w, or 'none')", + ) + project_group.add_argument( + "--ledger-stale", + action="store_true", + help="list expired reviews and exit (nothing is changed)", + ) + project_group.add_argument( + "--ledger-refresh", + action="store_true", + help="clear the expiry on every stale review (audited) and exit", + ) + project_group.add_argument( + "--policy-include-reviewed", + action="store_true", + help="let --policy fail on findings already reviewed in the ledger", + ) + project_group.add_argument( + "--show-project", + action="store_true", + help="show the discovered .pathscope/project.json and what it supplies, then exit", + ) + project_group.add_argument( + "--init-project", + metavar="DIR", + help="write DIR/.pathscope/project.json and exit", + ) + project_group.add_argument( + "--no-project", + action="store_true", + help="ignore any .pathscope/project.json above the working directory", + ) + + v26 = parser.add_argument_group("governance and rule tuning") + v26.add_argument( + "--waivers", + metavar="FILE", + action="append", + default=[], + help="load committable JSON waivers (repeatable)", + ) + v26.add_argument( + "--init-waivers", + metavar="FILE", + help="write a starter waiver file and exit", + ) + v26.add_argument( + "--list-waivers", + action="store_true", + help="show the loaded waivers, what each matched, and then continue", + ) + v26.add_argument( + "--suppression-audit", + action="store_true", + help="report dead, overbroad and expired suppressions", + ) + v26.add_argument( + "--audit-json", + action="store_true", + help="with --suppression-audit, emit JSON", + ) + v26.add_argument( + "--rule-precision", + action="store_true", + help="precision per rule from labelled ledger reviews, then exit", + ) + v26.add_argument( + "--rule-impact", + action="store_true", + help="how much each rule contributes to what is reported", + ) + v26.add_argument( + "--simulate", + metavar="CHANGES", + help="re-analyse under hypothetical weights, e.g. 'name-weak=-10,x=off'", + ) + v26.add_argument( + "--simulate-json", + action="store_true", + help="with --simulate, emit JSON instead of text", + ) + v26.add_argument( + "--explain-diff", + metavar="OLD.json", + action="append", + default=[], + help="with a second report, explain which scores moved and why; then exit", + ) + v26.add_argument( + "--where", + metavar="EXPR", + help="filter findings, e.g. 'score > 60 and confidence = high'", + ) + v26.add_argument( + "--where-json", + action="store_true", + help="with --where, emit the filtered findings as JSON and exit", + ) + v26.add_argument( + "--attest", + metavar="FILE", + help="write a JSON digest of inputs, settings and output", + ) + v26.add_argument( + "--verify-attest", + metavar="FILE", + help="check a report against an attestation", + ) + v26.add_argument( + "--assign-owners", + metavar="LIST", + help="split open work across owners, e.g. alice,bob,carol", + ) + v26.add_argument( + "--assign-by", + choices=("host", "path", "parameter", "rule", "foundry"), + default="host", + help="stratum for --assign-owners (default: host)", + ) + v26.add_argument( + "--assign-dir", + metavar="DIR", + help="write one Markdown worklist per owner into DIR", + ) + v26.add_argument( + "--ledger-merge", + metavar="OTHER", + help="plan a merge of OTHER into --ledger (dry run unless --merge-apply)", + ) + v26.add_argument( + "--merge-apply", + action="store_true", + help="with --ledger-merge, actually write the merge", + ) + v26.add_argument( + "--merge-prefer", + choices=("newer", "left", "right"), + default="newer", + help="which side wins a status conflict (default: newer)", + ) + v26.add_argument( + "--merge-json", + action="store_true", + help="with --ledger-merge, emit the plan as JSON", + ) + + v25 = parser.add_argument_group("review workflow and safe sharing") + v25.add_argument( + "--cluster", + action="store_true", + help="collapse candidates into path families and review once per shape", + ) + v25.add_argument( + "--queue", + action="store_true", + help="print unreviewed work ordered by score, novelty and leverage", + ) + v25.add_argument( + "--queue-limit", + type=int, + default=20, + metavar="N", + help="items to show with --queue (default 20; 0 for all)", + ) + v25.add_argument( + "--queue-all", + action="store_true", + help="with --queue, include known and reviewed candidates", + ) + v25.add_argument( + "--policy-shadow", + metavar="FILE", + action="append", + default=[], + help="evaluate a proposed policy without failing the build (repeatable)", + ) + v25.add_argument( + "--sample", + type=int, + default=0, + metavar="N", + help="analyse a deterministic subset of N requests (0 = everything)", + ) + v25.add_argument( + "--sample-seed", + type=int, + default=sampling_module.DEFAULT_SEED, + metavar="K", + help="seed for --sample; the same seed always selects the same subset", + ) + v25.add_argument( + "--sample-by", + choices=("host", "source", "none"), + default="host", + help="stratum for --sample (default: host)", + ) + v25.add_argument( + "--scope-file", + metavar="FILE", + help="JSON file declaring in-scope and out-of-scope hosts", + ) + v25.add_argument( + "--init-scope", + metavar="FILE", + help="write a starter scope file and exit", + ) + v25.add_argument( + "--openapi", + metavar="FILE", + help="compare findings against a local OpenAPI/Swagger JSON file", + ) + v25.add_argument( + "--openapi-json", + action="store_true", + help="with --openapi, emit the comparison as JSON", + ) + v25.add_argument( + "--export-ticket", + metavar="DIR", + help="write one Markdown work item per family (or candidate) into DIR", + ) + v25.add_argument( + "--ticket-per-candidate", + action="store_true", + help="with --export-ticket, one ticket per candidate instead of per family", + ) + v25.add_argument( + "--ticket-limit", + type=int, + default=0, + metavar="N", + help="with --export-ticket, write at most N tickets (0 = all)", + ) + v25.add_argument( + "--pr-comment", + metavar="FILE", + help="write a compact Markdown summary suitable for a pull-request comment", + ) + v25.add_argument( + "--run-id", + metavar="TEXT", + help="identifier written into --pr-comment so a CI job can update in place", + ) + v25.add_argument( + "--pr-rows", + type=int, + default=prcomment_module.DEFAULT_ROWS, + metavar="N", + help="table rows in --pr-comment (default 10)", + ) + v25.add_argument( + "--redact-hosts", + action="store_true", + help="replace every host with a stable pseudonym in all outputs", + ) + v25.add_argument( + "--redact-key", + metavar="SECRET", + help="key for --redact-hosts so pseudonyms are stable across runs", + ) + v25.add_argument( + "--redact-prefix", + default=redact_module.PREFIX, + metavar="TEXT", + help="prefix for --redact-hosts pseudonyms (default: host-)", + ) + v25.add_argument( + "--redact-length", + type=int, + default=redact_module.LENGTH, + metavar="N", + help="hex characters in --redact-hosts pseudonyms (default 8)", + ) + v25.add_argument( + "--completion", + metavar="SHELL", + help="print a shell completion script generated from this parser and exit", + ) + return parser + + +def resolve_formats(args: argparse.Namespace) -> None: + """Map ``--format``/``--json`` onto the explicit input and output formats.""" + args.input_format = args.input_format or INPUT_FORMAT_AUTO + args.output_format = args.output_format or FORMAT_TEXT + + if args.format in INPUT_FORMATS: + args.input_format = args.format + elif args.format in FORMATS: + args.output_format = args.format + + if args.json: + args.output_format = FORMAT_JSON + + +def _handle_init_config(args: argparse.Namespace, stderr) -> int: + """--init-config: write a starter configuration and exit.""" + preset = resolve_preset(args.preset) if args.preset else resolve_preset("balanced") + if preset is None: # pragma: no cover - argparse restricts choices + print("error: unknown preset", file=stderr) + return EXIT_USAGE + path = args.init_config + if os.path.exists(path): + print(f"error: refusing to overwrite existing file '{path}'", file=stderr) + return EXIT_USAGE + try: + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(STARTER_CONFIGS[preset.name]) + except OSError as exc: + print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"wrote starter configuration for preset '{preset.name}' to {path}", file=stderr) + return EXIT_OK + + +def _load_baseline(path: str, stderr): + """Load a baseline or suppression file. Returns (Baseline|None, code).""" + try: + with open(path, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except OSError as exc: + print(f"error: cannot read '{path}': {exc.strerror or exc}", file=stderr) + return None, EXIT_USAGE + except json.JSONDecodeError as exc: + print(f"error: '{path}' is not valid JSON: {exc.msg}", file=stderr) + return None, EXIT_USAGE + try: + return Baseline.from_payload(payload, source=path), EXIT_OK + except ValueError as exc: + print(f"error: '{path}' is not a usable baseline/suppression file: {exc}", file=stderr) + return None, EXIT_USAGE + + +def _read_mark_reviewed(path: str) -> dict: + """Existing reviewed ledger (fingerprint -> note). Empty when absent.""" + try: + with open(path, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except (OSError, ValueError): + return {} + entries = payload.get("suppressions") if isinstance(payload, dict) else None + if not isinstance(entries, list): + return {} + ledger = {} + for entry in entries: + if isinstance(entry, dict) and isinstance(entry.get("fingerprint"), str): + note = entry.get("note") + ledger[entry["fingerprint"]] = note if isinstance(note, str) else "" + return ledger + + +def _write_reviewed(path: str, ledger: dict, stderr) -> int: + payload = { + "tool": PROGRAM, + "version": __version__, + "note": ( + "Reviewed PathScope fingerprints. Use with --suppress FILE to hide " + "them from future runs." + ), + "suppressions": [ + {"fingerprint": fp, "note": note} + for fp, note in sorted(ledger.items()) + ], + } + try: + with open(path, "w", encoding="utf-8", newline="\n") as handle: + json.dump(payload, handle, indent=2) + handle.write("\n") + except OSError as exc: + print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"reviewed {len(ledger)} fingerprint(s) written to {path}", file=stderr) + return EXIT_OK + + +def _apply_preset_and_config(args: argparse.Namespace): + """Resolve preset -> config file -> CLI overrides. Returns (Config, error).""" + config = Config() + preset = resolve_preset(args.preset) + if preset is not None: + config = preset.apply(config) + + file_config = Config() + if args.config: + try: + file_config = load_config(args.config) + except ConfigError as exc: + return None, str(exc) + # A preset chosen on the command line is a base; file values win, + # except for CLI flags which are applied further down. + if preset is not None: + config = preset.apply(config) + config = _merge_config(config, file_config) + + # CLI flags always win. + if args.min_score is not None: + config.min_score = args.min_score + config.explicit = frozenset(set(config.explicit) | {"min_score"}) + if args.max_decode_passes is not None: + config.max_decode_passes = args.max_decode_passes + config.explicit = frozenset(set(config.explicit) | {"max_decode_passes"}) + return config, None + + +def _merge_config(base: Config, overlay: Config) -> Config: + """Overlay a file config on a preset base (file values win).""" + terms = list(dict.fromkeys(list(base.name_terms) + list(overlay.name_terms))) + ignored = list(dict.fromkeys(list(base.ignore_params) + list(overlay.ignore_params))) + languages = ( + list(dict.fromkeys(list(base.name_lang) + list(overlay.name_lang))) + if overlay.is_explicit("name_lang") + else list(base.name_lang) + ) + return Config( + name_terms=terms, + ignore_params=ignored, + name_lang=languages, + fold_names=( + overlay.fold_names if overlay.is_explicit("fold_names") else base.fold_names + ), + demote_shapes=( + overlay.demote_shapes + if overlay.is_explicit("demote_shapes") + else base.demote_shapes + ), + min_score=overlay.min_score if overlay.is_explicit("min_score") else base.min_score, + max_decode_passes=( + overlay.max_decode_passes + if overlay.is_explicit("max_decode_passes") + else base.max_decode_passes + ), + weak_names=( + overlay.weak_names if overlay.is_explicit("weak_names") else base.weak_names + ), + show_values=( + overlay.show_values if overlay.is_explicit("show_values") else base.show_values + ), + source=overlay.source or base.source, + extends=overlay.extends or base.extends, + explicit=frozenset(set(base.explicit) | set(overlay.explicit)), + ) + + +def _explain( + argv: argparse.Namespace, + config: Config, + stdout, + stderr, + book: Optional[RuleBook] = None, +) -> int: + """--explain: show the scoring trace for one parameter name.""" + name = argv.explain + min_score = config.min_score + book = book or RuleBook.default() + analysis = analyze_parameter( + name, + getattr(argv, "explain_value", "") or "", + max_decode_passes=config.max_decode_passes, + extra_terms=tuple(config.merged_terms()), + ignore=tuple(config.merged_ignore()), + min_score=0, + weak_names=config.weak_names, + book=book, + languages=tuple(config.name_lang), + fold=config.fold_names, + demote=config.demote_shapes, + ) + colors = Palette(supports_color(stdout) and not argv.no_color) + print( + f"Preset/config: threshold {min_score}, max decode passes " + f"{config.max_decode_passes}, weak names {'on' if config.weak_names else 'off'}", + file=stdout, + ) + print( + f"Rules: {book.source or 'defaults'}" + + (f"; {len(book.disabled)} disabled" if book.disabled else "") + + (f"; {', '.join(book.overridden())} overridden" if book.overridden() else ""), + file=stdout, + ) + print( + "Name layer: fold=" + + ("on" if config.fold_names else "off") + + ", langs=" + + (",".join(config.name_lang) if config.name_lang else "en") + + "; value demotion=" + + ("on" if config.demote_shapes else "off"), + file=stdout, + ) + print(render_explanation(analysis, colors, name=name), file=stdout) + if analysis.score >= min_score: + print(f"\nAt the current threshold ({min_score}) this parameter WOULD be reported.", + file=stdout) + else: + print( + f"\nAt the current threshold ({min_score}) this parameter would NOT be reported " + f"(score {analysis.score}).", + file=stdout, + ) + if not getattr(argv, "explain_value", ""): + print("Tip: add --explain-value VALUE to see value rules score too.", file=stdout) + return EXIT_OK + + +def _print_banner(stream, no_banner: bool, no_color: bool) -> None: + if no_banner: + return + palette = Palette(supports_color(stream) and not no_color) + print(render_banner(palette), file=stream) + print("", file=stream) + + +def _read_stdin() -> str: + try: + return sys.stdin.read() + except (OSError, ValueError): # pragma: no cover - exotic stdin + return "" + + +def stdin_is_pipe() -> bool: + try: + return sys.stdin is not None and not sys.stdin.isatty() + except Exception: # pragma: no cover - defensive + return False + + +def collect_inputs( + args: argparse.Namespace, + stdin_text: Optional[str], +) -> LoadResult: + """Merge ``--url``, ``-i/--input`` and piped stdin into one :class:`LoadResult`. + + Raises :class:`InputError` for unreadable or malformed files; recoverable + per-line problems become warnings instead of exceptions. + """ + result = LoadResult() + result.extend(make_url_requests(args.url)) + + for path in args.input: + if path == "-": + if stdin_text is None: + raise InputError("--input '-' was requested but stdin is empty or a terminal") + result.extend(load_stdin(stdin_text, args.input_format)) + stdin_text = None + continue + result.extend(load_file(path, args.input_format)) + + # Auto-piped stdin is used only when no other source was given. + if stdin_text is not None and not args.url and not args.input: + result.extend(load_stdin(stdin_text, args.input_format)) + + unique = LoadResult(warnings=list(result.warnings), skipped=result.skipped) + seen = set() + for request in result.requests: + key = request.dedupe_key + if key in seen: + continue + seen.add(key) + unique.requests.append(request) + return unique + + +def _build_options(args, config: Config, book: RuleBook) -> "object": + """Translate parsed arguments + config into AnalysisOptions.""" + return AnalysisOptions( + min_score=config.min_score, + max_decode_passes=config.max_decode_passes, + extra_terms=tuple(config.merged_terms()), + ignore_params=tuple(merge_ignore(args.ignore_param, config)), + show_values=bool(args.show_values or config.show_values), + weak_names=config.weak_names, + book=book, + name_lang=tuple(config.name_lang), + fold_names=config.fold_names, + demote_shapes=config.demote_shapes, + dedupe_by=args.dedupe_by, + max_entries=args.max_entries, + measure=args.stats, + ) + + +def _resolve_rule_book(args, stderr): + """Build the effective RuleBook. Returns (book, code).""" + overrides = {} + disabled = list(args.disable_rule or []) + source = "defaults" + if args.rules: + try: + weights, extra_disabled = load_rule_overrides(args.rules) + except RuleError as exc: + print(f"error: {exc}", file=stderr) + return None, EXIT_USAGE + overrides = weights + disabled.extend(extra_disabled) + source = args.rules + try: + book = RuleBook.with_overrides( + overrides, [normalize_rule_id(name) for name in disabled], source=source + ) + except RuleError as exc: + print(f"error: {exc}", file=stderr) + return None, EXIT_USAGE + return book, EXIT_OK + + +def _resolve_policy(args, stderr): + """Build the CI policy from --policy (file or inline JSON).""" + if not args.policy: + return None, EXIT_OK + try: + if os.path.exists(args.policy): + return load_policy(args.policy), EXIT_OK + if args.policy.lstrip().startswith("{"): + return parse_inline_policy(args.policy), EXIT_OK + raise PolicyError(f"policy file not found: {args.policy}") + except PolicyError as exc: + print(f"error: {exc}", file=stderr) + return None, EXIT_USAGE + + +def _handle_init_policy(args, stderr) -> int: + path = args.init_policy + if os.path.exists(path): + print(f"error: refusing to overwrite existing file '{path}'", file=stderr) + return EXIT_USAGE + try: + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(starter_policy()) + except OSError as exc: + print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"wrote starter CI policy to {path}", file=stderr) + return EXIT_OK + + +def _handle_ledger_admin(args, stdout, stderr) -> int: + """--ledger-query / --ledger-export / --import-ledger (no analysis).""" + if not args.ledger: + print("error: --ledger-query, --ledger-export and --import-ledger " + "need --ledger FILE", file=stderr) + return EXIT_USAGE + try: + ledger = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + if args.import_ledger: + try: + with open(args.import_ledger, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except OSError as exc: + print(f"error: cannot read '{args.import_ledger}': " + f"{exc.strerror or exc}", file=stderr) + return EXIT_USAGE + except json.JSONDecodeError as exc: + print(f"error: '{args.import_ledger}' is not valid JSON: {exc.msg}", + file=stderr) + return EXIT_USAGE + try: + count = ledger.import_json_ledger(payload, reviewer=args.reviewer) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print(f"imported {count} review(s) into {args.ledger}", file=stderr) + return EXIT_OK + if args.ledger_export: + payload = ledger.to_baseline_payload() + try: + with open(args.ledger_export, "w", encoding="utf-8", newline="\n") as handle: + json.dump(payload, handle, indent=2) + handle.write("\n") + except OSError as exc: + print(f"error: cannot write '{args.ledger_export}': " + f"{exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print( + f"exported {len(payload['suppressions'])} review(s) to " + f"{args.ledger_export}", + file=stderr, + ) + return EXIT_OK + # --ledger-query TEXT: substring match across the useful columns. + needle = (args.ledger_query or "").strip().lower() + reviews = [ + review + for review in ledger.all_reviews() + if not needle + or needle in review.host.lower() + or needle in review.parameter.lower() + or needle in review.rule.lower() + or needle in review.status.lower() + or needle in review.reviewer.lower() + or needle in review.note.lower() + or needle in review.fingerprint.lower() + ] + print(render_ledger_query(reviews), file=stdout) + return EXIT_OK + finally: + ledger.close() + + +def _reviewer_name(args) -> str: + """Resolve --reviewer, falling back to the OS user without leaking it.""" + if args.reviewer: + return args.reviewer + return os.environ.get("USER") or os.environ.get("USERNAME") or "" + + +def _validate_float_interval(parser, args) -> None: + if args.interval <= 0: + parser.error("--interval must be a positive number of seconds") + + +def run( + argv: Optional[Sequence[str]] = None, + *, + stdout=None, + stderr=None, + stdin_text: Optional[str] = None, +) -> int: + """Programmatic entry point. Returns the process exit code.""" + stdout = stdout if stdout is not None else sys.stdout + stderr = stderr if stderr is not None else sys.stderr + argv_list = list(sys.argv[1:] if argv is None else argv) + parser = build_parser() + + _print_banner(stderr, "--no-banner" in argv_list, "--no-color" in argv_list) + + args = parser.parse_args(argv_list) + resolve_formats(args) + quiet = args.quiet + + if args.completion: + try: + script = completion_module.render(args.completion, parser) + except completion_module.CompletionError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + stdout.write(script) + return EXIT_OK + progress = Progress(args.progress, stderr) if args.progress else NullProgress() + + # -- early exits ----------------------------------------------------- + if args.init_config: + return _handle_init_config(args, stderr) + if args.init_policy: + return _handle_init_policy(args, stderr) + if args.self_test: + results = ci_module.run_selftest() + print(ci_module.render_selftest(results), file=stdout) + return EXIT_OK if all(entry["passed"] for entry in results) else EXIT_FINDINGS + if args.doctor: + results = ci_module.run_doctor() + print(ci_module.render_doctor(results), file=stdout) + return EXIT_OK if all(entry["passed"] for entry in results) else EXIT_FINDINGS + if args.list_playbooks: + print(f"{PROGRAM} remediation playbooks", file=stdout) + for line in playbooks_module.describe_all(): + print(line, file=stdout) + return EXIT_OK + if args.trend: + try: + history_doc = history_module.load_history(args.trend) + except history_module.HistoryError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print(render_trend(history_module.analyze_history(history_doc)), file=stdout) + return EXIT_OK + if args.inspect_bundle: + try: + manifest = bundle_module.read_manifest(args.inspect_bundle) + members = bundle_module.list_bundle(args.inspect_bundle) + except bundle_module.BundleError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print(f"{PROGRAM} bundle: {args.inspect_bundle}", file=stdout) + for key in sorted(manifest): + print(f" {key:<22} {manifest[key]}", file=stdout) + print(f" {'members':<22} {', '.join(sorted(members))}", file=stdout) + return EXIT_OK + if ( + args.ledger_query is not None + or args.ledger_export + or args.import_ledger + ): + return _handle_ledger_admin(args, stdout, stderr) + if args.init_terms: + return _handle_init_terms(args, stderr) + if args.list_terms: + return _handle_list_terms(args, stdout, stderr) + if args.init_project: + return _handle_init_project(args, stderr) + if args.init_scope: + return _handle_init_scope(args, stderr) + if args.init_waivers: + return _handle_init_waivers(args, stderr) + if args.rule_precision: + return _handle_rule_precision(args, stdout, stderr) + if args.explain_diff: + return _handle_explain_diff(args, stdout, stderr) + if args.ledger_merge: + return _handle_ledger_merge(args, stdout, stderr) + if args.show_project: + return _handle_show_project(args, stdout, stderr) + if args.ledger_stale or args.ledger_refresh: + return _handle_ledger_expiry(args, stdout, stderr) + if args.ledger_scores: + return _handle_ledger_scores(args, stdout, stderr) + if args.calibrate: + return _handle_calibrate(args, stdout, stderr) + + # -- 2.4 project discovery (command-line values always win) ------------ + try: + project = project_module.discover(enabled=not args.no_project) + except project_module.ProjectError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + if project is not None: + supplied = _apply_project(args, project) + if not quiet and supplied: + print( + f"pathscope: using {project.path} ({', '.join(supplied)})", + file=stderr, + ) + for missing in project.missing_files(): + print( + f"warning: project references a missing file: {missing}", + file=stderr, + ) + + config, error = _apply_preset_and_config(args) + if error: + print(f"error: {error}", file=stderr) + return EXIT_USAGE + + # -- 2.4 term packs merge into the effective term list ----------------- + if args.terms: + try: + packs = termpacks_module.load_packs(args.terms) + merged_terms, merged_ignore = termpacks_module.merge_terms( + config.merged_terms(), packs + ) + except termpacks_module.TermPackError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + config.name_terms = merged_terms + config.ignore_params = list( + dict.fromkeys(list(config.ignore_params) + merged_ignore) + ) + + if not 0 <= config.min_score <= 100: + parser.error("--min-score must be between 0 and 100") + if not 0 <= config.max_decode_passes <= 5: + parser.error("--max-decode-passes must be between 0 and 5") + if args.max_entries < 0: + parser.error("--max-entries must be 0 (unlimited) or a positive number") + + # CLI name/fold/demote switches override the configuration file. + if args.name_lang is not None: + try: + config.name_lang = list(parse_languages(args.name_lang)) + except ValueError as exc: + parser.error(f"--name-lang: {exc}") + if args.no_fold: + config.fold_names = False + if args.no_demote: + config.demote_shapes = False + + where_filter = None + if args.where: + try: + where_filter = query_module.parse(args.where) + except query_module.QueryError as exc: + print(f"error: --where: {exc}", file=stderr) + return EXIT_USAGE + + book, code = _resolve_rule_book(args, stderr) + if book is None: + return code + + if args.list_rules: + for line in format_rule_table(book): + print(line, file=stdout) + reordered = book.overridden() + if reordered: + print(f"\nOverridden in this run ({book.source}): {', '.join(reordered)}") + return EXIT_OK + + if args.explain: + return _explain(args, config, stdout, stderr, book=book) + + if args.top is not None and args.top < 0: + parser.error("--top must be 0 (all) or a positive number") + if args.interactive and not ( + args.save_report and writer_supports_interactive(args.save_report) + ): + parser.error("--interactive requires an HTML --save-report FILE") + + policy, code = _resolve_policy(args, stderr) + if policy is None and args.policy: + return code + + baseline = None + if args.baseline: + baseline, code = _load_baseline(args.baseline, stderr) + if baseline is None: + return code + if args.suppress: + suppression, code = _load_baseline(args.suppress, stderr) + if suppression is None: + return code + if baseline is None: + baseline = suppression + else: + merged = Baseline(source=f"{args.baseline} + {args.suppress}") + merged.fingerprints = dict(baseline.fingerprints) + merged.fingerprints.update(suppression.fingerprints) + merged.entries = list(baseline.entries) + list(suppression.entries) + baseline = merged + + options = _build_options(args, config, book) + + # -- 2.3 flag validation --------------------------------------------- + if args.stream_batch < 1: + parser.error("--stream-batch must be at least 1") + if args.tui: + if not tui_module.available(): + print( + "error: --tui needs an interactive terminal " + "(stdin and stdout must be TTYs)", + file=stderr, + ) + return EXIT_USAGE + if not args.ledger: + print("error: --tui needs --ledger FILE to save reviews", file=stderr) + return EXIT_USAGE + if "--ledger-status" in argv_list and not args.ledger: + print("error: --ledger-status needs --ledger FILE", file=stderr) + return EXIT_USAGE + if "--review-note" in argv_list and not args.ledger: + print("error: --review-note needs --ledger FILE", file=stderr) + return EXIT_USAGE + if args.ledger_mark_all and not args.ledger: + print("error: --ledger-mark-all needs --ledger FILE", file=stderr) + return EXIT_USAGE + + # -- watch mode ------------------------------------------------------ + if args.watch: + _validate_float_interval(parser, args) + from .watch import WatchError, watch_forever # local import keeps startup light + + if not os.path.exists(args.watch): + print(f"error: --watch file not found: {args.watch}", file=stderr) + return EXIT_USAGE + try: + watch_forever( + args.watch, + options, + interval=args.interval, + input_format=args.input_format, + stdout=stdout, + stderr=stderr, + ) + except WatchError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + return EXIT_OK + + if args.diff_capture: + return _run_capture_diff(args, stdout, stderr) + + if args.stream: + return _run_stream(args, options, stdout, stderr, stdin_text) + + if args.extract: + return _run_extract(args, options, stdout, stderr) + + needs_stdin = "-" in args.input + if stdin_text is None and needs_stdin: + stdin_text = _read_stdin() + elif stdin_text is None and not args.url and not args.input and stdin_is_pipe(): + stdin_text = _read_stdin() + + progress.start("reading input") + try: + loaded = collect_inputs(args, stdin_text) + except InputError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + except KeyboardInterrupt: + print("\ninterrupted", file=stderr) + return EXIT_INTERRUPTED + progress.finish(f"{len(loaded.requests)} request(s)") + + if not quiet: + for warning in loaded.warnings: + print(f"warning: {warning}", file=stderr) + + if args.scope_file: + try: + scope = scope_module.load_scope(args.scope_file) + except scope_module.ScopeError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + kept, scope_summary = scope_module.apply_scope(loaded.requests, scope) + message = scope_module.describe_drop(scope_summary, scope) + if scope_summary.get("dropped"): + # Never silent: a scope file that drops everything and a capture + # that was empty must not look the same in a pipeline log. + print(f"warning: {message}", file=stderr) + elif not quiet: + print(f"pathscope: {message}", file=stderr) + loaded.requests = kept + analysis_scope = scope + else: + analysis_scope = None + + if args.sample: + try: + sampled = sampling_module.sample( + loaded.requests, + args.sample, + seed=args.sample_seed, + by=args.sample_by, + ) + except sampling_module.SamplingError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + loaded.requests = sampled.requests + sample_result = sampled + if not quiet: + print(f"pathscope: {sampled.describe()}", file=stderr) + else: + sample_result = None + + if not loaded.requests: + print("error: no usable input found.", file=stderr) + print( + " Use --url URL, -i/--input FILE (or - for stdin), " + "or pipe URLs/HAR on stdin.", + file=stderr, + ) + if analysis_scope is not None: + print( + " Every request was out of scope for " + f"{args.scope_file}; check the in_scope patterns.", + file=stderr, + ) + elif sample_result is not None and sample_result.population: + print( + " --sample selected 0 of " + f"{sample_result.population} request(s).", + file=stderr, + ) + print(" Try: python3 path_detector.py --help", file=stderr) + return EXIT_USAGE + + try: + progress.start("analyzing", len(loaded.requests)) + report_data = analyze_requests(loaded.requests, options) + progress.finish(f"{report_data.candidate_count} candidate(s)") + analysis_warnings = list(report_data.warnings) + report_data.warnings = list(loaded.warnings) + analysis_warnings + report_data.skipped = loaded.skipped + if not quiet: + for warning in analysis_warnings: + print(f"warning: {warning}", file=stderr) + report_data.stats.setdefault("parse_seconds", 0.0) + report_data.rules = book.as_dict() + report_data.rules_source = book.source + report_data.name_lang = tuple(config.name_lang) + if baseline is not None: + apply_baseline(report_data, baseline, show_known=args.show_known) + if args.top: + report_data.findings = report_data.findings[: args.top] + for index, finding in enumerate(report_data.findings, start=1): + finding.index = index + colors = Palette(supports_color(stdout) and not args.no_color) + ledger_store = None + if args.ledger: + try: + ledger_store = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + hidden = 0 + # Mark ledger decisions on the findings first: SARIF suppressions, JUnit + # and the policy gate all key off finding.status, so every + # output stays consistent with what the ledger says. + if ledger_store is not None: + reviewed_now = _mark_reviewed_status(report_data, ledger_store) + if reviewed_now and not quiet: + print( + f"pathscope: {reviewed_now} finding(s) already reviewed in " + f"{args.ledger}", + file=stderr, + ) + # The TUI shows reviewed rows *marked* rather than hiding them, so the + # reviewer can see and undo a previous decision. The same applies when + # the policy is explicitly asked to fail on reviewed findings: hiding + # them first would make --policy-include-reviewed a no-op. + keep_reviewed_visible = ( + args.tui + or args.policy_include_reviewed + or args.show_known + or bool(policy is not None and policy.fail_on_reviewed) + ) + if ledger_store is not None and not keep_reviewed_visible: + hidden = _hide_reviewed(report_data, ledger_store) + if hidden: + # Never silent: the user must know results were filtered even + # with --quiet (a script reading stdout would otherwise see + # "0 candidates" and draw the wrong conclusion). + print( + f"pathscope: {hidden} candidate(s) already reviewed " + f"in {args.ledger} (use --show-known to include)", + file=stderr, + ) + # -- waivers: applied after the ledger, before every renderer and the + # policy, so all outputs agree on what has been accepted. -------------- + waiver_set = None + if args.waivers: + try: + waiver_set = waivers_module.merge( + [waivers_module.load_waivers(path) for path in args.waivers] + ) + except waivers_module.WaiverError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + waived_count, expired_skipped = waivers_module.apply_waivers( + report_data.findings, waiver_set + ) + if waived_count: + # Same contract as the ledger: filtered results are never + # silent, because a pipeline reading "0 candidates" from a + # fully-waived scan would draw exactly the wrong conclusion. + if args.show_known or args.list_waivers: + print( + f"pathscope: {waived_count} finding(s) waived by " + f"{len(args.waivers)} waiver file(s) (shown)", + file=stderr, + ) + else: + print( + f"pathscope: {waived_count} finding(s) waived by " + f"{len(args.waivers)} waiver file(s) (hidden; " + "--show-known to include)", + file=stderr, + ) + waived = [f for f in report_data.findings if f.status == "waived"] + report_data.findings = [ + f for f in report_data.findings if f.status != "waived" + ] + for index, finding in enumerate(report_data.findings, start=1): + finding.index = index + del waived + if expired_skipped: + print( + f"warning: {expired_skipped} waiver(s) have expired and hide " + "nothing; run --suppression-audit", + file=stderr, + ) + if args.list_waivers: + print("", file=stdout) + print( + waivers_module.render_waivers(waiver_set), + file=stdout, + ) + + should_scrub = not args.no_scrub and ( + args.scrub or args.bundle or args.playbook or args.dashboard + ) + if should_scrub: + report_data = scrub_module.scrub_report(report_data) + # Redaction is the last transformation before rendering: every format + # and every post-run artefact then sees pseudonyms only. It runs after + # status marking because fingerprints (which embed the host) must stay + # untouched for baselines and ledger rows to keep working. + host_map = None + if args.redact_hosts: + try: + host_map = redact_module.build_map( + args.redact_key, + prefix=args.redact_prefix, + length=args.redact_length, + ) + except redact_module.RedactionError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + report_data = redact_module.redact_report(report_data, host_map) + loaded.requests = redact_module.redact_requests(loaded.requests, host_map) + # Redaction changes what every output means, so it is announced even + # with --quiet: a reader must know hosts are pseudonyms. + print(f"pathscope: {redact_module.describe(host_map)}", file=stderr) + # The gate must judge the whole picture, not the slice the user asked + # to look at: a --where that excludes everything would otherwise turn + # --fail-on-findings into a silent pass. Snapshot the count first. + gate_candidate_count = len(report_data.findings) + if where_filter is not None: + # Filtering is a view: the policy still sees everything it was + # asked to judge, and the exit code is unchanged by --where. + matched = query_module.filter_findings(report_data.findings, where_filter) + if not quiet: + print( + f"pathscope: --where matched {len(matched)} of " + f"{len(report_data.findings)} finding(s)", + file=stderr, + ) + if args.where_json: + payload = { + "where": query_module.describe(where_filter), + "matched": len(matched), + "total": len(report_data.findings), + "findings": [finding.as_dict() for finding in matched], + } + rendered = json.dumps(payload, indent=2, ensure_ascii=False) + "\n" + report_data = replace( + report_data, findings=list(matched) + ) + matched_only = True + else: + report_data = replace(report_data, findings=list(matched)) + matched_only = False + else: + matched_only = False + + if args.github_annotations: + rendered = ci_module.render_github_annotations(report_data) + elif matched_only: + pass # --where --where-json already produced the body + elif args.summary_only: + rendered = render_summary_only(report_data, colors) + elif args.output_format == FORMAT_TEXT: + rendered = render_text(report_data, colors, group_by=args.group_by) + else: + rendered = render(report_data, args.output_format, colors) + except Exception as exc: # noqa: BLE001 - last-resort guard, never crash + print(f"error: could not produce the report ({exc})", file=stderr) + return EXIT_INTERNAL + + stdout.write(rendered) + if not rendered.endswith("\n"): + stdout.write("\n") + stdout.flush() + + # -- 2.3 insight views (printed after the main report) ---------------- + if args.dashboard and not args.summary_only: + print("", file=stdout) + print(render_dashboard(report_data, loaded.requests, colors), file=stdout) + if args.inventory: + print("", file=stdout) + print(render_inventory(loaded.requests), file=stdout) + if args.correlate: + print("", file=stdout) + print(render_correlation(report_data, loaded.requests), file=stdout) + if args.value_stats: + print("", file=stdout) + print( + analytics_module.render_value_stats( + analytics_module.value_stats(loaded.requests) + ), + file=stdout, + ) + if args.rule_coverage: + print("", file=stdout) + print( + analytics_module.render_rule_coverage( + analytics_module.rule_coverage(report_data, book) + ), + file=stdout, + ) + if args.compare_presets: + print("", file=stdout) + print( + presets_module.render_preset_comparison( + presets_module.compare_presets(report_data) + ), + file=stdout, + ) + families = None + if args.cluster: + families = families_module.cluster(report_data.findings) + print("", file=stdout) + print( + families_module.render_clusters(families, len(report_data.findings)), + file=stdout, + ) + if args.queue: + try: + if families is None: + families = families_module.cluster(report_data.findings) + items = queue_module.build_queue( + report_data.findings, + limit=args.queue_limit, + include_known=args.queue_all, + families=families, + ) + except queue_module.QueueError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + settled = sum( + 1 for f in report_data.findings if f.status in queue_module.SETTLED + ) + print("", file=stdout) + print( + queue_module.render_queue( + items, settled=settled, total=len(report_data.findings) + ), + file=stdout, + ) + if args.openapi: + try: + spec = openapi_module.load_spec(args.openapi) + except openapi_module.SpecError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + spec_report = openapi_module.compare(report_data, spec) + print("", file=stdout) + if args.openapi_json: + print( + json.dumps(spec_report.as_dict(), indent=2, ensure_ascii=False), + file=stdout, + ) + else: + print(openapi_module.render_spec_report(spec_report), file=stdout) + if args.simulate: + try: + changes = simulate_module.parse_changes(args.simulate) + simulation = simulate_module.simulate(loaded.requests, options, changes) + except simulate_module.SimulationError as exc: + print(f"error: --simulate: {exc}", file=stderr) + return EXIT_USAGE + print("", file=stdout) + if args.simulate_json: + print( + json.dumps(simulation.as_dict(), indent=2, ensure_ascii=False), + file=stdout, + ) + else: + print(simulate_module.render_simulation(simulation), file=stdout) + if args.rule_impact: + print("", file=stdout) + print( + impact_module.render_impact( + impact_module.rule_impact(report_data, book), + threshold=config.min_score, + ), + file=stdout, + ) + if args.suppression_audit: + ledger_reviews = None + if ledger_store is not None: + ledger_reviews = ledger_store.all_reviews() + audit_report = audit_module.audit( + report_data, + baseline=baseline, + waivers=waiver_set, + ledger_reviews=ledger_reviews, + ) + print("", file=stdout) + if args.audit_json: + print( + json.dumps(audit_report.as_dict(), indent=2, ensure_ascii=False), + file=stdout, + ) + else: + print(audit_module.render_audit(audit_report), file=stdout) + if args.assign_owners: + try: + owners = assign_module.parse_owners(args.assign_owners) + distribution = assign_module.assign( + [f for f in report_data.findings if f.status not in ("known", "waived")], + owners, + strategy=args.assign_by, + ) + if args.assign_dir: + written = assign_module.write_slices(args.assign_dir, distribution) + except assign_module.AssignError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + except OSError as exc: + print(f"error: cannot write worklists: {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print("", file=stdout) + print(assign_module.render_distribution(distribution), file=stdout) + if args.assign_dir: + print( + f"pathscope: wrote {len(written)} worklist file(s) to {args.assign_dir}", + file=stderr, + ) + + if args.save_report: + try: + kind = write_report( + args.save_report, report_data, interactive=args.interactive + ) + except (OSError, ValueError) as exc: + print(f"error: cannot write report: {exc}", file=stderr) + return EXIT_USAGE + if not quiet: + extra = " (interactive)" if args.interactive and kind == "html" else "" + print( + f"pathscope: wrote {kind} report{extra} to {args.save_report}", + file=stderr, + ) + + if args.playbook: + try: + markdown = playbooks_module.render_playbook_markdown(report_data) + with open(args.playbook, "w", encoding="utf-8", newline="\n") as handle: + handle.write(markdown) + if not markdown.endswith("\n"): + handle.write("\n") + except OSError as exc: + print(f"error: cannot write playbook: {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + if not quiet: + print(f"pathscope: wrote remediation playbook to {args.playbook}", file=stderr) + + if args.export_ticket: + try: + tickets = tickets_module.build_tickets( + report_data, + per_candidate=args.ticket_per_candidate, + limit=args.ticket_limit, + ) + written = tickets_module.write_tickets(args.export_ticket, tickets) + index_path = os.path.join(args.export_ticket, "INDEX.md") + with open(index_path, "w", encoding="utf-8", newline="\n") as handle: + handle.write( + tickets_module.render_index(tickets, args.export_ticket) + ) + except tickets_module.TicketError as exc: + print(f"error: cannot export tickets: {exc}", file=stderr) + return EXIT_USAGE + except OSError as exc: + print(f"error: cannot export tickets: {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + if not quiet: + print( + f"pathscope: wrote {len(written)} work item(s) to " + f"{args.export_ticket} (values never included)", + file=stderr, + ) + + if args.pr_comment: + if args.pr_rows < 0: + print("error: --pr-rows must be 0 or a positive number", file=stderr) + return EXIT_USAGE + comment = prcomment_module.render_comment( + report_data, + exit_code=EXIT_OK, + rows=args.pr_rows, + run_id=args.run_id or "", + ) + try: + with open(args.pr_comment, "w", encoding="utf-8", newline="\n") as handle: + handle.write(comment.body) + except OSError as exc: + print(f"error: cannot write PR comment: {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + if not quiet: + note = f", {comment.omitted} row(s) left out" if comment.omitted else "" + print( + f"pathscope: wrote {comment.size} char(s) to {args.pr_comment}" + f"{note}", + file=stderr, + ) + + if args.bundle: + try: + manifest = bundle_module.build_bundle( + args.bundle, + report_data, + exit_code=EXIT_OK, + settings={ + "min_score": config.min_score, + "name_lang": ",".join(config.name_lang), + "format": args.output_format, + }, + ) + except bundle_module.BundleError as exc: + print(f"error: cannot write bundle: {exc}", file=stderr) + return EXIT_USAGE + except OSError as exc: + print(f"error: cannot write bundle: {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + if not quiet: + print( + f"pathscope: wrote bundle {args.bundle} " + f"({len(manifest.get('files', []))} files, values scrubbed)", + file=stderr, + ) + + if args.history: + try: + record = history_module.run_record( + report_data, + label=" ".join(argv_list) if argv_list else "", + settings={ + "min_score": config.min_score, + "format": args.output_format, + "preset": args.preset or "", + }, + ) + document = history_module.append_run(args.history, record) + except history_module.HistoryError as exc: + print(f"error: cannot update history: {exc}", file=stderr) + return EXIT_USAGE + except OSError as exc: + print(f"error: cannot update history: {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + if not quiet: + print( + f"pathscope: appended run to {args.history} " + f"({len(document.get('runs', []))} run(s) kept)", + file=stderr, + ) + + if args.attest: + try: + attestation = attest_module.build( + inputs=list(args.input), + rendered=rendered, + settings={ + "min_score": config.min_score, + "preset": args.preset or "", + "format": args.output_format, + "dedupe_by": args.dedupe_by, + "name_lang": list(config.name_lang), + "rules": dict(report_data.rules), + "rules_source": report_data.rules_source, + "sample_seed": args.sample_seed if args.sample else 0, + "sample_size": args.sample, + "waivers": list(args.waivers), + "where": args.where or "", + }, + counts={ + "requests": report_data.requests_analyzed, + "parameters": report_data.parameters_analyzed, + "candidates": report_data.candidate_count, + }, + ) + with open(args.attest, "w", encoding="utf-8", newline="\n") as handle: + handle.write(attestation.render()) + except (attest_module.AttestationError, OSError) as exc: + print(f"error: cannot write attestation: {exc}", file=stderr) + return EXIT_USAGE + if not quiet: + print( + f"pathscope: wrote attestation to {args.attest} " + f"(digests only; values are never included)", + file=stderr, + ) + + if args.verify_attest: + try: + problems = attest_module.verify( + args.verify_attest, rendered=rendered, inputs=list(args.input) + ) + except attest_module.AttestationError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print( + attest_module.render_verification(problems, args.verify_attest), + file=stderr, + ) + if problems: + return EXIT_FINDINGS + + if args.mark_reviewed: + ledger = _read_mark_reviewed(args.mark_reviewed) + for finding in report_data.findings: + note = "" + if baseline is not None: + note = baseline.fingerprints.get(finding.fingerprint, "") + ledger[finding.fingerprint] = note + code = _write_reviewed(args.mark_reviewed, ledger, stderr) + if code != EXIT_OK: + return code + + if args.ledger_mark_all and ledger_store is not None: + try: + written = ledger_store.record_findings( + report_data.findings, + status=args.ledger_status, + reviewer=_reviewer_name(args), + note=args.review_note, + expire=args.ledger_expire or "", + owner=args.reviewer or "", + ) + except ledger_module.LedgerError as exc: + print(f"error: ledger write failed: {exc}", file=stderr) + return EXIT_USAGE + if not quiet: + print( + f"pathscope: recorded {written} review(s) in {args.ledger}", + file=stderr, + ) + + # -- 2.3 terminal reviewer -------------------------------------------- + if args.tui and ledger_store is not None: + reviewed_at_start = ledger_store.fingerprints() + # Rows already in the ledger start *marked*, so `s` is a no-op until + # the reviewer changes something; the audit trail records only diffs. + state = tui_module.build_state(report_data) + state.marked = {f.fingerprint for f in report_data.findings + if f.fingerprint in reviewed_at_start} + screen = tui_module.ReviewScreen(state) + try: + screen.open() + except tui_module.TuiUnavailable as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + def _save(fingerprints): + wanted = set(fingerprints) + changed = 0 + for fingerprint in sorted(wanted - reviewed_at_start): + ledger_store.record( + fingerprint, + status=args.ledger_status, + reviewer=_reviewer_name(args), + note=args.review_note, + ) + changed += 1 + # Unmarked rows are removed from the ledger, but the audit + # trail keeps the "forgotten" event. + for fingerprint in sorted(reviewed_at_start - wanted): + if ledger_store.forget( + fingerprint, + reviewer=_reviewer_name(args), + note=args.review_note or "unmarked in --tui", + ): + changed += 1 + return changed + + screen.run(save=_save) + changed = len(state.marked - reviewed_at_start) + len( + reviewed_at_start - state.marked + ) + except ledger_module.LedgerError as exc: + print(f"error: ledger write failed: {exc}", file=stderr) + return EXIT_USAGE + finally: + screen.close() + ledger_store.close() + ledger_store = None + print( + f"pathscope: {len(state.marked)} fingerprint(s) marked, " + f"{changed} ledger change(s) in {args.ledger}", + file=stderr, + ) + + if args.stats: + stats = report_data.stats + print( + "pathscope: stats " + f"analyze={stats.get('analyze_seconds', 0):.3f}s " + f"total={stats.get('total_seconds', 0):.3f}s " + f"entries={stats.get('input_entries', report_data.requests_analyzed)} " + f"findings={stats.get('findings', report_data.candidate_count)}", + file=stderr, + ) + if not quiet: + print(f"pathscope: {summarize(report_data)}", file=stderr) + if args.interactive and args.save_report: + print( + "pathscope: review marks in the interactive report stay in your browser", + file=stderr, + ) + if report_data.findings and args.output_format == FORMAT_TEXT and not args.summary_only: + print( + "pathscope: candidates are for manual review, not confirmed vulnerabilities", + file=stderr, + ) + + if ledger_store is not None: + ledger_store.close() + + # -- shadow policies: reported, never enforced ------------------------ + if args.policy_shadow: + shadows = [] + for path in args.policy_shadow: + try: + candidate = load_policy(path) + except PolicyError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + # A shadow policy is reported only: it cannot change the exit code. + shadows.append(shadow_module.evaluate_shadow(report_data, candidate, label=path)) + actual = ( + shadow_module.evaluate_shadow(report_data, policy, label="active") + if policy is not None + else None + ) + print("", file=stdout) + print(shadow_module.render_shadow(report_data, shadows, actual=actual), file=stdout) + + # -- gates: --policy first (more specific), then --fail-on-findings -- + if policy is not None: + if args.policy_include_reviewed: + policy = replace(policy, fail_on_reviewed=True) + result = evaluate_policy(report_data, policy) + if not quiet or not result.passed: + print(f"pathscope: {result.describe()}", file=stderr) + if not result.passed: + return EXIT_FINDINGS + return EXIT_OK + + if args.fail_on_findings and gate_candidate_count: + return EXIT_FINDINGS + return EXIT_OK + + +def render_summary_only(report_data, colors: Palette) -> str: + """Compact ``--summary-only`` view: counts per confidence and per host.""" + lines = [colors.paint("bold", "PathScope summary")] + lines.append(f"Requests analysed : {report_data.requests_analyzed}") + lines.append(f"Parameters : {report_data.parameters_analyzed}") + lines.append(f"Candidates : {report_data.candidate_count}") + for band in ("high", "medium", "low"): + lines.append(f" {band:<6} : {report_data.confidence_counts.get(band, 0)}") + if report_data.findings: + lines.append("") + by_host = {} + for finding in report_data.findings: + by_host[finding.host] = by_host.get(finding.host, 0) + 1 + lines.append(colors.paint("bold", "Candidates per host")) + for host in sorted(by_host): + lines.append(f" {host:<32} {by_host[host]}") + by_rule = {} + for finding in report_data.findings: + by_rule[finding.rule] = by_rule.get(finding.rule, 0) + 1 + lines.append("") + lines.append(colors.paint("bold", "Candidates per rule")) + for rule in sorted(by_rule): + lines.append(f" {rule:<32} {by_rule[rule]}") + lines.append("") + lines.append(colors.paint("grey", "Candidates for manual review only.")) + return "\n".join(lines) + + +def main(argv: Optional[Sequence[str]] = None) -> int: + """Console entry point used by ``path_detector.py``.""" + try: + return run(argv) + except KeyboardInterrupt: + print("\ninterrupted", file=sys.stderr) + return EXIT_INTERRUPTED + except BrokenPipeError: # e.g. `pathscope ... | head` + try: + sys.stdout.close() + except Exception: # pragma: no cover - defensive + pass + return EXIT_OK + + +__all__ = [ + "build_parser", + "collect_inputs", + "resolve_formats", + "main", + "run", + "EXIT_OK", + "EXIT_FINDINGS", + "EXIT_USAGE", + "EXIT_INTERNAL", + "EXIT_INTERRUPTED", +] + + +# --------------------------------------------------------------------------- +# Renderers for the 2.3 insight views +# --------------------------------------------------------------------------- +def render_dashboard(report_data, requests=(), colors: Optional[Palette] = None) -> str: + """``--dashboard``: distribution, percentiles, gaps and frequency.""" + colors = colors or Palette(False) + view = analytics_module.dashboard(report_data, requests) + lines = [colors.paint("bold", "PathScope dashboard")] + lines.append(f"Requests analysed : {view.requests}") + lines.append(f"Parameters analysed: {view.parameters}") + lines.append(f"Candidates : {view.findings}") + for band in analytics_module.BANDS: + lines.append(f" {band:<7} : {view.bands.get(band, 0)}") + if view.scores: + lines.append(f"Mean score : {view.mean_score:.1f}/100") + percentiles = " ".join( + f"p{rank}={value:.0f}" if value is not None else f"p{rank}=n/a" + for rank, value in view.percentiles.items() + ) + lines.append(f"Percentiles : {percentiles}") + if view.locations: + lines.append( + "Locations : " + + ", ".join(f"{name}={count}" for name, count in sorted(view.locations.items())) + ) + if view.frequent: + lines.append("") + lines.append(colors.paint("bold", "Most frequent candidates")) + for name, count in view.frequent: + lines.append(f" {name:<32} {count}") + if view.rules: + lines.append("") + lines.append(colors.paint("bold", "Rules that fired")) + for rule, count in sorted(view.rules.items(), key=lambda item: (-item[1], item[0])): + lines.append(f" {rule:<32} {count}") + if view.coverage_gaps: + lines.append("") + lines.append(colors.paint("bold", "Coverage gaps (hosts with no candidate)")) + for host in view.coverage_gaps[:analytics_module.MAX_TABLE_ROWS]: + lines.append(f" {host}") + lines.append("") + lines.append(colors.paint("grey", "Candidates for manual review only; counts are not risk ratings.")) + return "\n".join(lines) + + +def render_inventory(requests) -> str: + """``--inventory``: endpoints ordered by distinct parameters.""" + entries = analytics_module.inventory(requests) + lines = ["PathScope endpoint inventory", "=" * 84] + lines.append(f"{len(entries)} endpoint(s), busiest first (distinct parameters):") + lines.append("") + for entry in entries[: analytics_module.MAX_TABLE_ROWS]: + names = ", ".join(entry.parameters) if entry.parameters else "-" + lines.append(f" {entry.weight:>2} {entry.method:<6} {entry.host:<24} {entry.resource}") + lines.append(f" parameters: {names[:150]}") + if len(entries) > analytics_module.MAX_TABLE_ROWS: + lines.append(f" ... {len(entries) - analytics_module.MAX_TABLE_ROWS} more endpoint(s)") + return "\n".join(lines) + + +def render_correlation(report_data, requests=()) -> str: + """``--correlate``: matrix, shared parameters and chains.""" + view = analytics_module.correlate(report_data, requests) + lines = ["PathScope cross-source correlation", "=" * 84] + if not view.matrix: + lines.append("No candidates to correlate.") + return "\n".join(lines) + lines.append("") + lines.append("Parameter x host matrix:") + for name, row in sorted(view.matrix.items()): + counts = ", ".join(f"{host} x{count}" for host, count in sorted(row.items())) + lines.append(f" {name:<28} {counts}") + if view.shared: + lines.append("") + lines.append("Shared across hosts (same component, different deployments?):") + for name, hosts in view.shared[: analytics_module.MAX_TABLE_ROWS]: + lines.append(f" {name:<28} {', '.join(hosts)}") + if view.clusters: + lines.append("") + lines.append("Clusters (parameters sharing the same host set):") + for signature, members in sorted(view.clusters.items()): + lines.append(f" [{signature}] {', '.join(members)}") + if view.chained: + lines.append("") + lines.append("Chained candidates (a value embeds another candidate):") + for outer, inner, host in view.chained[: analytics_module.MAX_TABLE_ROWS]: + lines.append(f" {host}: {outer} -> {inner}") + return "\n".join(lines) + + +def render_trend(trend) -> str: + """``--trend``: counts, new/resolved and per-parameter history.""" + lines = ["PathScope run trend", "=" * 84] + if not trend.runs: + lines.append("The history file contains no runs yet.") + return "\n".join(lines) + spark = history_module.sparkline(trend.counts) + lines.append(f"Runs : {trend.runs}") + lines.append(f"Candidates per run : {', '.join(str(c) for c in trend.counts)}") + if spark: + lines.append(f"Sparkline : {spark}") + lines.append(f"New per run : {', '.join(str(c) for c in trend.new_per_run)}") + lines.append(f"Resolved per run : {', '.join(str(c) for c in trend.resolved_per_run)}") + if trend.latest_new: + lines.append("New in last run : " + ", ".join(trend.latest_new[:20])) + if trend.latest_resolved: + lines.append("Resolved in last : " + ", ".join(trend.latest_resolved[:20])) + lines.append("") + lines.append("Per parameter (first -> last run, drift):") + for entry in sorted( + trend.parameters.values(), key=lambda item: (-item.runs_seen, item.parameter) + )[: analytics_module.MAX_TABLE_ROWS]: + drift = f"{entry.drift:+d}" if entry.drift else "0" + lines.append( + f" {entry.parameter:<24} {entry.host:<24} " + f"runs {entry.first_run}-{entry.last_run} ({entry.runs_seen}x) drift {drift}" + ) + if trend.busiest_hosts: + lines.append("") + lines.append("Busiest hosts (total appearances):") + for host, count in trend.busiest_hosts: + lines.append(f" {host:<32} {count}") + return "\n".join(lines) + + +def render_ledger_query(reviews) -> str: + """``--ledger-query``: a table of matching reviews.""" + lines = ["PathScope ledger", "=" * 84] + if not reviews: + lines.append("No reviews matched.") + return "\n".join(lines) + lines.append( + f"{'status':<16} {'host':<22} {'parameter':<20} {'rule':<18} " + f"{'reviewer':<12} {'updated':<20} fingerprint" + ) + for review in reviews[: analytics_module.MAX_TABLE_ROWS]: + lines.append( + f"{review.status:<16} {review.host[:22]:<22} {review.parameter[:20]:<20} " + f"{review.rule[:18]:<18} {review.reviewer[:12]:<12} " + f"{review.updated_at:<20} {review.fingerprint}" + ) + if len(reviews) > analytics_module.MAX_TABLE_ROWS: + lines.append(f"... {len(reviews) - analytics_module.MAX_TABLE_ROWS} more") + return "\n".join(lines) + + +def _hide_reviewed(report_data, ledger) -> int: + """Drop findings whose fingerprint is already in the ledger. + + Returns the number hidden. The audit trail in the ledger is untouched; + this only affects what this run prints. + """ + reviewed = ledger.fingerprints() + if not reviewed: + return 0 + kept = [f for f in report_data.findings if f.fingerprint not in reviewed] + hidden = len(report_data.findings) - len(kept) + if hidden: + report_data.findings = kept + for index, finding in enumerate(report_data.findings, start=1): + finding.index = index + report_data.known_count = int(getattr(report_data, "known_count", 0)) + hidden + return hidden + + +def _run_stream(args, options, stdout, stderr, stdin_text) -> int: + """``--stream``: bounded-memory analysis of a piped line list.""" + if args.url: + print( + "error: --stream reads from stdin; drop --url or pass the URL on stdin", + file=stderr, + ) + return EXIT_USAGE + if stdin_text is None: + try: + stream_module.check_streamable(args.input_format) + except stream_module.StreamError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + if not stream_module.stdin_is_a_pipe(): + print( + "error: --stream reads URLs/recon lines from stdin; pipe into it " + "or pass --input -", + file=stderr, + ) + return EXIT_USAGE + + def emit(batch_number, cumulative): + if not args.stream_json: + print( + f"pathscope: batch {batch_number}: " + f"{cumulative.requests_analyzed} request(s), " + f"{cumulative.candidate_count} candidate(s)", + file=stderr, + ) + return + payload = { + "batch": batch_number, + "requests": cumulative.requests_analyzed, + "candidates": cumulative.candidate_count, + "findings": [finding.as_dict() for finding in cumulative.findings], + } + stdout.write(json.dumps(payload, ensure_ascii=False) + "\n") + stdout.flush() + + try: + if stdin_text is not None: + result = stream_module.stream_text( + stdin_text, options, batch_size=args.stream_batch, on_batch=emit + ) + else: + result = stream_module.stream_stdin( + options, batch_size=args.stream_batch, on_batch=emit + ) + except stream_module.StreamError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + except KeyboardInterrupt: + print("\ninterrupted", file=stderr) + return EXIT_INTERRUPTED + + if args.stream_json: + stdout.write( + json.dumps( + { + "complete": True, + "requests": result.report.requests_analyzed, + "candidates": result.report.candidate_count, + }, + ensure_ascii=False, + ) + + "\n" + ) + # Machine-readable output never implies a gate; only --fail-on-findings does. + return EXIT_FINDINGS if (args.fail_on_findings and result.report.new_count) else EXIT_OK + + if not args.quiet: + for warning in result.warnings: + print(f"warning: {warning}", file=stderr) + colors = Palette(supports_color(stdout) and not args.no_color) + rendered = stream_module.render_stream_summary(result, colors) + print(rendered, file=stdout) + + if args.save_report: + try: + write_report(args.save_report, result.report, interactive=args.interactive) + except (OSError, ValueError) as exc: + print(f"error: cannot write report: {exc}", file=stderr) + return EXIT_USAGE + if args.ledger: + try: + ledger = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + if args.ledger_mark_all: + ledger.record_findings( + result.report.findings, + status=args.ledger_status, + reviewer=_reviewer_name(args), + note=args.review_note, + ) + except ledger_module.LedgerError as exc: + print(f"error: ledger write failed: {exc}", file=stderr) + return EXIT_USAGE + finally: + ledger.close() + if not args.quiet: + print( + "pathscope: candidates are for manual review, not confirmed vulnerabilities", + file=stderr, + ) + if args.fail_on_findings and result.report.new_count: + return EXIT_FINDINGS + return EXIT_OK + + + +# --------------------------------------------------------------------------- +# 2.4 handlers: term packs, projects, ledger expiry, calibration +# --------------------------------------------------------------------------- +def _handle_init_terms(args, stderr) -> int: + """``--init-terms FILE``: write a valid starter term pack.""" + target = args.init_terms + directory = os.path.dirname(os.path.abspath(target)) + if directory and not os.path.isdir(directory): + print(f"error: no such directory: {directory}", file=stderr) + return EXIT_USAGE + if os.path.exists(target): + print(f"error: '{target}' already exists; refusing to overwrite", file=stderr) + return EXIT_USAGE + name = os.path.splitext(os.path.basename(target))[0] or "my-project" + try: + with open(target, "w", encoding="utf-8", newline="\n") as handle: + handle.write(termpacks_module.starter_pack(name).to_json()) + except OSError as exc: + print(f"error: cannot write '{target}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"pathscope: wrote a starter term pack to {target}", file=stderr) + print( + "pathscope: edit 'terms', then pass it with --terms FILE", + file=stderr, + ) + return EXIT_OK + + +def _handle_list_terms(args, stdout, stderr) -> int: + """``--list-terms FILE``: validate and summarise packs.""" + print(f"{PROGRAM} term packs", file=stdout) + print(f" {'pack':<24} {'terms':>9} {'ignore':>10} description", file=stdout) + failed = False + for path in args.list_terms: + try: + pack = termpacks_module.load_pack(path) + except termpacks_module.TermPackError as exc: + print(f" error: {exc}", file=stderr) + failed = True + continue + print(f" {termpacks_module.describe(pack)}", file=stdout) + if pack.terms: + print(f" terms: {', '.join(pack.terms[:12])}", file=stdout) + if len(pack.terms) > 12: + print(f" ... {len(pack.terms) - 12} more", file=stdout) + return EXIT_USAGE if failed else EXIT_OK + + +def _handle_init_scope(args, stderr) -> int: + """``--init-scope FILE``: write a starter scope file.""" + path = args.init_scope + if os.path.exists(path): + print(f"error: refusing to overwrite existing file '{path}'", file=stderr) + return EXIT_USAGE + try: + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(scope_module.starter_scope()) + except OSError as exc: + print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"wrote starter scope file to {path}", file=stderr) + print( + "note: a scope file records intent, it does not grant authorisation.", + file=stderr, + ) + return EXIT_OK + + +def _handle_init_waivers(args, stderr) -> int: + """``--init-waivers FILE``: write a starter waiver file.""" + path = args.init_waivers + if os.path.exists(path): + print(f"error: refusing to overwrite existing file '{path}'", file=stderr) + return EXIT_USAGE + try: + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(waivers_module.starter_waivers()) + except OSError as exc: + print(f"error: cannot write '{path}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"wrote starter waivers to {path}", file=stderr) + print( + "note: every waiver needs a reason, an owner and (ideally) an expiry.", + file=stderr, + ) + return EXIT_OK + + +def _handle_rule_precision(args, stdout, stderr) -> int: + """``--rule-precision``: precision per rule from the ledger, then exit.""" + if not args.ledger: + print("error: --rule-precision needs --ledger FILE", file=stderr) + return EXIT_USAGE + try: + store = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + reviews = store.all_reviews() + finally: + store.close() + report = precision_module.rule_precision(reviews) + print(precision_module.render_precision(report), file=stdout) + return EXIT_OK + + +def _handle_explain_diff(args, stdout, stderr) -> int: + """``--explain-diff OLD.json NEW.json``: why scores moved, then exit.""" + if len(args.explain_diff) != 2: + print( + "error: --explain-diff needs exactly two report files: " + "--explain-diff OLD.json --explain-diff NEW.json", + file=stderr, + ) + return EXIT_USAGE + old_path, new_path = args.explain_diff + try: + diff = scorechange_module.compare(old_path, new_path) + except scorechange_module.ScoreDiffError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print(scorechange_module.render_score_diff(diff), file=stdout) + return EXIT_OK + + +def _handle_ledger_merge(args, stdout, stderr) -> int: + """``--ledger-merge OTHER --ledger INTO``: dry run unless --merge-apply.""" + if not args.ledger: + print("error: --ledger-merge needs --ledger FILE (the destination)", file=stderr) + return EXIT_USAGE + if os.path.abspath(args.ledger) == os.path.abspath(args.ledger_merge): + print("error: cannot merge a ledger into itself", file=stderr) + return EXIT_USAGE + if not os.path.exists(args.ledger_merge): + print( + f"error: ledger to merge not found: {args.ledger_merge}", file=stderr + ) + return EXIT_USAGE + try: + left = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + try: + right = ledger_module.open_ledger(args.ledger_merge) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + result = ledgermerge_module.plan(left, right, prefer=args.merge_prefer) + if args.merge_apply: + ledgermerge_module.apply_merge(left, right, result) + except ledgermerge_module.MergeError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + finally: + right.close() + finally: + left.close() + if args.merge_json: + print( + json.dumps(result.as_dict(), indent=2, ensure_ascii=False), file=stdout + ) + else: + print(ledgermerge_module.render_merge(result), file=stdout) + return EXIT_OK + + +def _handle_init_project(args, stderr) -> int: + """``--init-project DIR``: write DIR/.pathscope/project.json.""" + base = os.path.abspath(args.init_project) + target_dir = os.path.join(base, project_module.PROJECT_DIR) + target = os.path.join(target_dir, project_module.PROJECT_FILE) + if os.path.exists(target): + print(f"error: '{target}' already exists; refusing to overwrite", file=stderr) + return EXIT_USAGE + try: + os.makedirs(target_dir, exist_ok=True) + payload = project_module.starter_project(os.path.basename(base) or "my-project") + with open(target, "w", encoding="utf-8", newline="\n") as handle: + json.dump(payload, handle, indent=2) + handle.write("\n") + except OSError as exc: + print(f"error: cannot write '{target}': {exc.strerror or exc}", file=stderr) + return EXIT_USAGE + print(f"pathscope: wrote {target}", file=stderr) + print( + "pathscope: paths in it are relative to the project root and must stay inside it", + file=stderr, + ) + return EXIT_OK + + +def _handle_show_project(args, stdout, stderr) -> int: + """``--show-project``: what discovery found and what it would apply.""" + try: + discovered = project_module.discover(enabled=not args.no_project) + except project_module.ProjectError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print( + project_module.render_project( + discovered, + searched_from=os.getcwd(), + ), + file=stdout, + ) + return EXIT_OK + + +def _handle_ledger_expiry(args, stdout, stderr) -> int: + """``--ledger-stale`` / ``--ledger-refresh``.""" + if not args.ledger: + print("error: --ledger-stale and --ledger-refresh need --ledger FILE", + file=stderr) + return EXIT_USAGE + try: + store = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + stale = store.stale() + if args.ledger_refresh: + changed = 0 + for review in stale: + if store.clear_expiry(review.fingerprint, + reviewer=_reviewer_name(args)): + changed += 1 + print( + f"pathscope: cleared the expiry on {changed} review(s)", + file=stderr, + ) + stale = store.stale() + print(render_stale_reviews(stale), file=stdout) + return EXIT_OK + finally: + store.close() + + +def _handle_ledger_scores(args, stdout, stderr) -> int: + """``--ledger-scores``: score distribution of ledger reviews.""" + if not args.ledger: + print("error: --ledger-scores needs --ledger FILE", file=stderr) + return EXIT_USAGE + try: + store = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + print( + calibrate_module.render_ledger_scores(store.all_reviews()), + file=stdout, + ) + return EXIT_OK + finally: + store.close() + + +def _handle_calibrate(args, stdout, stderr) -> int: + """``--calibrate``: recommend a threshold from the ledger.""" + if not args.ledger: + print("error: --calibrate needs --ledger FILE", file=stderr) + return EXIT_USAGE + try: + store = ledger_module.open_ledger(args.ledger) + except ledger_module.LedgerError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + try: + try: + result = calibrate_module.calibrate(store) + except calibrate_module.CalibrationError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + print(calibrate_module.render_calibration(result), file=stdout) + return EXIT_OK + finally: + store.close() + + +def render_stale_reviews(reviews) -> str: + """Text table for ``--ledger-stale``.""" + lines = ["PathScope stale reviews", "=" * 84] + if not reviews: + lines.append("No expired reviews: every acceptance is still current.") + return "\n".join(lines) + lines.append( + f"{len(reviews)} review(s) passed their expiry and need another look:" + ) + lines.append("") + lines.append( + f"{'status':<16} {'host':<22} {'parameter':<20} {'expired':<12} " + f"{'reviewer':<12} fingerprint" + ) + for review in reviews[: analytics_module.MAX_TABLE_ROWS]: + lines.append( + f"{review.status:<16} {review.host[:22]:<22} {review.parameter[:20]:<20} " + f"{review.expires_at[:10]:<12} {review.reviewer[:12]:<12} " + f"{review.fingerprint}" + ) + if len(reviews) > analytics_module.MAX_TABLE_ROWS: + lines.append(f"... {len(reviews) - analytics_module.MAX_TABLE_ROWS} more") + lines.append("") + lines.append( + "These still hide their candidates. Re-review them, then either set a new " + ) + lines.append("expiry or clear it with --ledger-refresh.") + return "\n".join(lines) + + +def _apply_project(args, project) -> list: + """Fill unset command-line options from a discovered project. + + Returns the list of option names the project supplied, for the stderr note. + A flag already on the command line is never touched. + """ + supplied: list = [] + pairs = ( + ("config", "config"), + ("policy", "policy"), + ("rules", "rules"), + ("baseline", "baseline"), + ("ledger", "ledger"), + ("history", "history"), + ) + for attribute, label in pairs: + if getattr(args, attribute, None): + continue + value = getattr(project, attribute, "") + if value: + setattr(args, attribute, value) + supplied.append(label) + if not args.terms and project.terms: + args.terms = list(project.terms) + supplied.append("terms") + return supplied + + +# --------------------------------------------------------------------------- +# 2.4: capture diff and HTML/JS extraction runners +# --------------------------------------------------------------------------- +def _load_capture(path: str, input_format: str): + """Load one capture file through the normal input pipeline.""" + if not os.path.exists(path): + raise InputError(f"capture not found: {path}") + return load_file(path, input_format) + + +def _run_capture_diff(args, stdout, stderr) -> int: + """``--diff-capture OLD``: compare an earlier capture with ``-i`` files.""" + if not args.input: + print( + "error: --diff-capture needs the new capture via -i/--input " + f"(got {PROGRAM} --diff-capture old.har -i new.har)", + file=stderr, + ) + return EXIT_USAGE + try: + old = _load_capture(args.diff_capture, args.input_format) + except (InputError, OSError) as exc: + print(f"error: cannot read '{args.diff_capture}': {exc}", file=stderr) + return EXIT_USAGE + new = LoadResult() + for path in args.input: + try: + new.extend(_load_capture(path, args.input_format)) + except (InputError, OSError) as exc: + print(f"error: cannot read '{path}': {exc}", file=stderr) + return EXIT_USAGE + try: + diff = capturediff_module.compare(old.requests, new.requests) + except capturediff_module.CaptureDiffError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + + if args.diff_json: + payload = diff.as_dict() + payload["tool"] = PROGRAM + payload["version"] = __version__ + payload["before"] = args.diff_capture + payload["after"] = list(args.input) + payload["network_requests_made"] = 0 + print(json.dumps(payload, indent=2, ensure_ascii=False), file=stdout) + else: + print( + capturediff_module.render_diff( + diff, old_label=args.diff_capture, new_label=", ".join(args.input) + ), + file=stdout, + ) + if not args.quiet: + print( + f"pathscope: {len(diff.changes)} parameter change(s), " + f"{len(diff.new_endpoints)} new endpoint(s)", + file=stderr, + ) + return EXIT_FINDINGS if diff.has_differences else EXIT_OK + + +def _run_extract(args, options, stdout, stderr) -> int: + """``--extract FILE``: analyse endpoint strings found in local HTML/JS.""" + if args.url or args.input: + print( + "error: --extract reads local files; drop --url/-i or run them separately", + file=stderr, + ) + return EXIT_USAGE + try: + found = extractor_module.extract_paths( + args.extract, + base_host=args.extract_host or "", + keep_all_hosts=args.extract_all_hosts, + ) + except extractor_module.ExtractError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + if not found.requests: + print(extractor_module.render_extract(found), file=stdout) + for warning in found.warnings: + print(f"warning: {warning}", file=stderr) + return EXIT_USAGE + + report_data = analyze_requests(found.requests, options) + report_data.warnings = list(found.warnings) + list(report_data.warnings) + report_data.rules = options.book.as_dict() + report_data.rules_source = options.book.source + colors = Palette(supports_color(stdout) and not args.no_color) + print(extractor_module.render_extract(found), file=stdout) + print("", file=stdout) + if args.output_format == FORMAT_TEXT: + print(render_text(report_data, colors, group_by=args.group_by), file=stdout) + else: + print(render(report_data, args.output_format, colors), file=stdout) + if args.save_report: + try: + write_report(args.save_report, report_data, interactive=args.interactive) + except (OSError, ValueError) as exc: + print(f"error: cannot write report: {exc}", file=stderr) + return EXIT_USAGE + if not args.quiet: + print(f"pathscope: {summarize(report_data)}", file=stderr) + print( + "pathscope: candidates are for manual review, not confirmed vulnerabilities", + file=stderr, + ) + if args.fail_on_findings and report_data.new_count: + return EXIT_FINDINGS + return EXIT_OK + + +def _mark_reviewed_status(report_data, ledger_store) -> int: + """Set ``finding.status = "reviewed"`` for fingerprints in the ledger. + + This is what makes ``--ledger`` consistent across *every* output: SARIF + suppressions, JUnit ````, the policy gate and the text report all + already understand the ``reviewed`` status, so marking happens once here + rather than in each renderer. + """ + reviewed = ledger_store.fingerprints() + if not reviewed: + return 0 + marked = 0 + for finding in report_data.findings: + if finding.fingerprint in reviewed and finding.status != "reviewed": + finding.status = "reviewed" + marked += 1 + return marked diff --git a/pathscope/completion.py b/pathscope/completion.py new file mode 100644 index 0000000..5a9eeb7 --- /dev/null +++ b/pathscope/completion.py @@ -0,0 +1,275 @@ +"""Shell completion (``--completion bash|zsh|fish``). + +Completion scripts go stale the moment a flag is added, and a stale completion +is worse than none: it teaches the wrong flags. So nothing here is hand-written. +The script is generated from the **real argument parser** every time, which +means a new flag appears in completion the moment it exists in the parser, or +it appears nowhere at all. + +Supported: bash, zsh, fish, and ``powershell``. Output goes to stdout so it can +be piped: + + pathscope --completion bash > /etc/bash_completion.d/pathscope + pathscope --completion zsh > "${fpath[1]}/_pathscope" + pathscope --completion fish > ~/.config/fish/completions/pathscope.fish + +Only flags are completed. Value choices are included where the parser declares +them (``choices=`` for ``--format``, the status list for ``--ledger-status``), +because those are the places a typo is most likely. +""" + +from __future__ import annotations + +import shlex +from dataclasses import dataclass +from typing import Dict, List, Sequence, Tuple + +SHELLS = ("bash", "zsh", "fish", "powershell") + + +class CompletionError(ValueError): + """Raised for an unsupported shell.""" + + +@dataclass(frozen=True) +class Flag: + """One option, as the parser declares it.""" + + options: Tuple[str, ...] + help: str + metavar: str = "" + choices: Tuple[str, ...] = () + + @property + def primary(self) -> str: + """The longest long option, or the only option.""" + longs = [option for option in self.options if option.startswith("--") and option != "--"] + if longs: + return max(longs, key=len) + return self.options[0] + + +def _metavar(action) -> str: + if getattr(action, "choices", None): + return "" + metavar = action.metavar or "" + if isinstance(metavar, tuple): + metavar = metavar[0] if metavar else "" + if not metavar: + metavar = action.dest.upper() + return metavar + + +def collect_flags(parser) -> List[Flag]: + """Turn argparse actions into a flat, sorted flag list.""" + flags: List[Flag] = [] + for action in parser._actions: + options = tuple( + option for option in action.option_strings if option not in ("-h", "--help") + ) + if not options: + continue + choices = tuple(str(choice) for choice in (action.choices or ())) + flags.append( + Flag( + options=options, + help=(action.help or "").split("\n")[0].strip(), + metavar=_metavar(action), + choices=choices, + ) + ) + flags.sort(key=lambda flag: flag.primary) + return flags + + +def _value_sets(flags: Sequence[Flag]) -> Dict[str, Tuple[str, ...]]: + return {flag.primary: flag.choices for flag in flags if flag.choices} + + +def _bash_quote(text: str) -> str: + return shlex.quote(text) + + +def render_bash(program: str, flags: Sequence[Flag]) -> str: + """A bash completion script generated from the parser.""" + function = f"_{program.replace('-', '_').replace('.', '_')}" + options = " ".join(_bash_quote(flag.primary) for flag in flags) + values = _value_sets(flags) + lines = [ + f"# {program} completion for bash -- generated by --completion, do not edit", + "# regenerate: " + program + " --completion bash", + "", + f"{function}() {{", + " local cur prev", + ' cur="${COMP_WORDS[COMP_CWORD]}"', + ' prev="${COMP_WORDS[COMP_CWORD-1]}"', + " case \"$prev\" in", + ] + for option, choices in sorted(values.items()): + lines.append(f" {_bash_quote(option)})") + lines.append( + f" COMPREPLY=( $(compgen -W \"{' '.join(choices)}\" -- \"$cur\") )" + ) + lines.append(" return 0 ;;") + lines.append(" esac") + lines.append(" if [[ \"$cur\" == -* ]]; then") + lines.append( + f" COMPREPLY=( $(compgen -W {_bash_quote(options)} -- \"$cur\") )" + ) + lines.append(" return 0") + lines.append(" fi") + lines.append(" COMPREPLY=( $(compgen -f -- \"$cur\") )") + lines.append("}") + lines.append("") + lines.append(f"complete -o bashdefault -o default -F {function} {_bash_quote(program)}") + return "\n".join(lines) + "\n" + + +def render_zsh(program: str, flags: Sequence[Flag]) -> str: + """A zsh completion script generated from the parser.""" + lines = [ + f"#compdef {program}", + f"# {program} completion for zsh -- generated by --completion, do not edit", + "# regenerate: " + program + " --completion zsh", + "", + f"_{program.replace('-', '_').replace('.', '_')}() {{", + " _arguments -s \\", + ] + for flag in flags: + help_text = (flag.help or "").replace("'", "\\'").replace("[", "(").replace("]", ")") + if flag.choices: + spec = "(" + " ".join(flag.choices) + ")" + lines.append(f" '{flag.primary}[{help_text}]:value:{spec}' \\") + elif flag.options and any( + option.startswith("--") and option not in ( + "--url", "--input", "--format", "--output-format", "--input-format", + "--config", "--rules", "--policy", "--baseline", "--suppress", + "--save-report", "--bundle", "--history", "--ledger", "--terms", + "--init-terms", "--list-terms", "--diff-capture", "--extract", + "--extract-host", "--openapi", "--scope-file", "--sample-seed", + "--sample-by", "--export-ticket", "--pr-comment", "--completion", + "--min-score", "--top", "--max-entries", "--ledger-status", + "--ledger-expire", "--reviewer", "--review-note", "--preset", + "--group-by", "--name-lang", "--interval", "--stream-batch", + "--redact-key", "--redact-prefix", "--redact-length", + "--policy-shadow", "--ticket-limit", "--queue-limit", + ) + for option in flag.options + ): + lines.append(f" '{flag.primary}[{help_text}]' \\") + else: + lines.append(f" '{flag.primary}[{help_text}]:value:_files' \\") + lines.append(" '*:file:_files'") + lines.append("}") + lines.append("") + lines.append(f"_{program.replace('-', '_').replace('.', '_')} \"$@\"") + return "\n".join(lines) + "\n" + + +def render_fish(program: str, flags: Sequence[Flag]) -> str: + """A fish completion script generated from the parser.""" + lines = [ + f"# {program} completion for fish -- generated by --completion, do not edit", + "# regenerate: " + program + " --completion fish", + "", + ] + for flag in flags: + conditions = " ".join(f"-l {option[2:]}" for option in flag.options if option.startswith("--")) + short = " ".join(f"-s {option[1:]}" for option in flag.options if len(option) == 2 and option.startswith("-")) + help_text = (flag.help or "").replace("'", "\\'") + prefix = " ".join(part for part in (conditions, short) if part) + if flag.choices: + choices = " ".join(f"-a {choice}" for choice in flag.choices) + lines.append(f"complete -c {program} {prefix} {choices} -d '{help_text}'") + elif flag.metavar: + lines.append( + f"complete -c {program} {prefix} -r -d '{help_text}'" + ) + else: + lines.append(f"complete -c {program} {prefix} -d '{help_text}'") + lines.append( + f"complete -c {program} -f -a '(__fish_complete_path)' -d 'input file'" + ) + return "\n".join(lines) + "\n" + + +def render_powershell(program: str, flags: Sequence[Flag]) -> str: + """A PowerShell completion script generated from the parser.""" + values = _value_sets(flags) + lines = [ + f"# {program} completion for PowerShell -- generated by --completion, do not edit", + "# regenerate: " + program + " --completion powershell", + "# add to your profile: . ", + "", + f"Register-ArgumentCompleter -Native -CommandName {program} -ScriptBlock {{", + " param($wordToComplete, $commandAst, $cursorPosition)", + " $options = @(", + ] + for flag in flags: + help_text = (flag.help or "").replace("'", "''") + lines.append(f" @{{ Name = '{flag.primary}'; Description = '{help_text}' }}") + lines.append(" )") + if values: + lines.append(" $valueChoices = @{") + for option, choices in sorted(values.items()): + joined = "', '".join(choices) + lines.append(f" '{option}' = @('{joined}')") + lines.append(" }") + else: + lines.append(" $valueChoices = @{}") + lines.append(" $elements = $commandAst.CommandElements") + lines.append(" $previous = if ($elements.Count -ge 2) { $elements[$elements.Count - 2].ToString() } else { '' }") + lines.append(" if ($valueChoices.ContainsKey($previous)) {") + lines.append(" $valueChoices[$previous] | Where-Object { $_ -like \"$wordToComplete*\" } |") + lines.append(" ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }") + lines.append(" return") + lines.append(" }") + lines.append(" $options | Where-Object { $_.Name -like \"$wordToComplete*\" } |") + lines.append(" ForEach-Object { [System.Management.Automation.CompletionResult]::new($_.Name, $_.Name, 'ParameterName', $_.Description) }") + lines.append("}") + return "\n".join(lines) + "\n" + + +RENDERERS = { + "bash": render_bash, + "zsh": render_zsh, + "fish": render_fish, + "powershell": render_powershell, +} + + +def render(shell: str, parser) -> str: + """Render a completion script for ``shell`` from ``parser``.""" + key = (shell or "").strip().lower() + if key not in RENDERERS: + raise CompletionError( + f"unsupported shell '{shell}' (choose from {', '.join(SHELLS)})" + ) + flags = collect_flags(parser) + if not flags: + raise CompletionError("the parser exposed no options to complete") + program = parser.prog + return RENDERERS[key](program, flags) + + +def describe() -> Tuple[str, ...]: + """Lines for ``--help``.""" + return ( + " --completion SHELL print a completion script generated from this parser", + " (bash, zsh, fish, powershell)", + ) + + +__all__ = [ + "CompletionError", + "Flag", + "RENDERERS", + "SHELLS", + "collect_flags", + "describe", + "render", + "render_bash", + "render_fish", + "render_powershell", + "render_zsh", +] diff --git a/pathscope/config.py b/pathscope/config.py new file mode 100644 index 0000000..dc855cd --- /dev/null +++ b/pathscope/config.py @@ -0,0 +1,368 @@ +"""Optional JSON configuration for PathScope. + +Schema (all keys optional, unknown keys rejected):: + + { + "extends": "balanced", + "name_terms": ["download", "media_file"], + "ignore_params": ["image", "avatar"], + "min_score": 25, + "max_decode_passes": 3, + "weak_names": true, + "show_values": false, + "name_lang": ["de", "es"], + "fold_names": true, + "demote_shapes": true + } + +Only literal terms are accepted. Regular expressions are deliberately not +supported: a user-supplied pattern could turn this passive triage tool into a +catastrophic-backtracking hazard, and literal terms keep results explainable. + +``extends`` names a base configuration file (relative to the including file) +or a built-in preset (``minimal`` / ``balanced`` / ``noisy`` and their aliases). +At most ``MAX_EXTENDS_DEPTH`` levels are followed, cycles are rejected. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from .textutil import MAX_DECODE_PASSES + +#: Allowed keys and their validation rules. +_TERM_PATTERN = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") + +MIN_TERM_LEN = 2 +MAX_TERM_LEN = 48 +MAX_TERM_COUNT = 200 +#: ``extends`` may chain this many files deep (the including file is level 1). +MAX_EXTENDS_DEPTH = 4 + + +class ConfigError(ValueError): + """Raised when a configuration file is missing, unreadable, or invalid.""" + + +@dataclass +class Config: + """Validated configuration values.""" + + name_terms: List[str] = field(default_factory=list) + ignore_params: List[str] = field(default_factory=list) + min_score: int = 25 + max_decode_passes: int = MAX_DECODE_PASSES + weak_names: bool = True + show_values: bool = False + #: Term-pack languages for the name layer (``()`` = English only). + name_lang: List[str] = field(default_factory=list) + #: Fold diacritics/compatibility characters before name matching. + fold_names: bool = True + #: Demote value shapes that do not look like paths (UUID, hash, ...). + demote_shapes: bool = True + source: str = "" + extends: str = "" + #: Which keys were present in the file (used so CLI > file > preset). + explicit: frozenset = field(default_factory=frozenset) + + def is_explicit(self, key: str) -> bool: + return key in self.explicit + + def merged_terms(self) -> List[str]: + return list(dict.fromkeys(self.name_terms)) + + def merged_ignore(self) -> List[str]: + return list(dict.fromkeys(self.ignore_params)) + + +ALLOWED_KEYS = { + "extends", + "name_terms", + "ignore_params", + "min_score", + "max_decode_passes", + "weak_names", + "show_values", + "name_lang", + "fold_names", + "demote_shapes", +} + +#: Languages accepted in ``name_lang`` (mirrors :mod:`pathscope.naming`). +_KNOWN_LANGUAGES = ("de", "es", "fr", "pt", "it", "nl") +LANGUAGE_SELECTORS = ("auto", "all", "off") + + +def _validate_terms(value: Any, key: str) -> List[str]: + if not isinstance(value, list): + raise ConfigError(f"'{key}' must be a JSON array of strings") + if len(value) > MAX_TERM_COUNT: + raise ConfigError(f"'{key}' may contain at most {MAX_TERM_COUNT} entries") + terms: List[str] = [] + for index, item in enumerate(value): + where = f"'{key}'[{index}]" + if not isinstance(item, str): + raise ConfigError(f"{where} must be a string") + term = item.strip() + if not (MIN_TERM_LEN <= len(term) <= MAX_TERM_LEN): + raise ConfigError( + f"{where} must be {MIN_TERM_LEN}-{MAX_TERM_LEN} characters long" + ) + if not set(term) <= _TERM_PATTERN: + raise ConfigError( + f"{where} may only contain letters, digits, '_' and '-' " + "(regular expressions and paths are not supported)" + ) + terms.append(term) + return terms + + +def validate_payload(payload: Any) -> Config: + """Validate an already-parsed JSON payload and return a :class:`Config`.""" + if not isinstance(payload, dict): + raise ConfigError("configuration must be a JSON object") + unknown = sorted(set(payload) - ALLOWED_KEYS) + if unknown: + raise ConfigError( + "unknown configuration key(s): " + + ", ".join(unknown) + + f" (allowed: {', '.join(sorted(ALLOWED_KEYS))})" + ) + + config = Config(explicit=frozenset(payload)) + if "extends" in payload: + value = payload["extends"] + if not isinstance(value, str) or not value.strip(): + raise ConfigError("'extends' must be a non-empty string") + config.extends = value.strip() + if "name_terms" in payload: + config.name_terms = _validate_terms(payload["name_terms"], "name_terms") + if "ignore_params" in payload: + config.ignore_params = _validate_terms(payload["ignore_params"], "ignore_params") + + if "min_score" in payload: + value = payload["min_score"] + if isinstance(value, bool) or not isinstance(value, int): + raise ConfigError("'min_score' must be an integer") + if not 0 <= value <= 100: + raise ConfigError("'min_score' must be between 0 and 100") + config.min_score = value + + if "max_decode_passes" in payload: + value = payload["max_decode_passes"] + if isinstance(value, bool) or not isinstance(value, int): + raise ConfigError("'max_decode_passes' must be an integer") + if not 0 <= value <= 5: + raise ConfigError("'max_decode_passes' must be between 0 and 5") + config.max_decode_passes = value + + if "weak_names" in payload: + value = payload["weak_names"] + if not isinstance(value, bool): + raise ConfigError("'weak_names' must be true or false") + config.weak_names = value + + if "show_values" in payload: + value = payload["show_values"] + if not isinstance(value, bool): + raise ConfigError("'show_values' must be true or false") + config.show_values = value + + if "name_lang" in payload: + value = payload["name_lang"] + if isinstance(value, str): + value = [value] + if not isinstance(value, list): + raise ConfigError("'name_lang' must be an array of language codes") + languages: List[str] = [] + for index, item in enumerate(value): + if not isinstance(item, str): + raise ConfigError(f"'name_lang'[{index}] must be a string") + key = item.strip().lower() + if key in LANGUAGE_SELECTORS: + if key == "off": + continue + languages = list(_KNOWN_LANGUAGES) + continue + if key not in _KNOWN_LANGUAGES: + raise ConfigError( + f"'name_lang'[{index}]: unknown language '{item}' " + f"(choose from {', '.join(_KNOWN_LANGUAGES)}, auto or off)" + ) + if key not in languages: + languages.append(key) + if len(languages) > 32: + raise ConfigError("'name_lang' may list at most 32 entries") + config.name_lang = languages + + for boolean_key in ("fold_names", "demote_shapes"): + if boolean_key in payload: + value = payload[boolean_key] + if not isinstance(value, bool): + raise ConfigError(f"'{boolean_key}' must be true or false") + setattr(config, boolean_key, value) + + return config + + +def _read_payload(path: str) -> Dict[str, Any]: + try: + with open(path, "r", encoding="utf-8-sig") as handle: + raw = handle.read() + except OSError as exc: + raise ConfigError( + f"cannot read configuration '{path}': {exc.strerror or exc}" + ) from exc + try: + payload = json.loads(raw) + except json.JSONDecodeError as exc: + raise ConfigError( + f"configuration '{path}' is not valid JSON: line {exc.lineno}, " + f"column {exc.colno}: {exc.msg}" + ) from exc + if not isinstance(payload, dict): + raise ConfigError(f"configuration '{path}' must be a JSON object") + return payload + + +def merge_configs(base: Config, overlay: Config) -> Config: + """Overlay ``overlay`` onto ``base``: lists append, scalars override.""" + terms: List[str] = [] + for item in list(base.name_terms) + list(overlay.name_terms): + if item not in terms: + terms.append(item) + ignored: List[str] = [] + for item in list(base.ignore_params) + list(overlay.ignore_params): + if item not in ignored: + ignored.append(item) + merged = Config( + name_terms=terms, + ignore_params=ignored, + min_score=overlay.min_score if overlay.is_explicit("min_score") else base.min_score, + max_decode_passes=( + overlay.max_decode_passes + if overlay.is_explicit("max_decode_passes") + else base.max_decode_passes + ), + weak_names=( + overlay.weak_names if overlay.is_explicit("weak_names") else base.weak_names + ), + show_values=( + overlay.show_values if overlay.is_explicit("show_values") else base.show_values + ), + name_lang=( + list(dict.fromkeys(list(base.name_lang) + list(overlay.name_lang))) + if overlay.is_explicit("name_lang") + else list(base.name_lang) + ), + fold_names=( + overlay.fold_names if overlay.is_explicit("fold_names") else base.fold_names + ), + demote_shapes=( + overlay.demote_shapes + if overlay.is_explicit("demote_shapes") + else base.demote_shapes + ), + source=overlay.source or base.source, + extends=overlay.extends or base.extends, + explicit=frozenset(set(base.explicit) | set(overlay.explicit)), + ) + return merged + + +def _load_with_extends(path: str, seen: Sequence[str], depth: int) -> Config: + """Load ``path``, resolving ``extends`` against files or presets.""" + from .presets import resolve_preset # local import avoids a cycle + + absolute = os.path.abspath(path) + if absolute in seen: + chain = " -> ".join(list(seen) + [absolute]) + raise ConfigError(f"configuration cycle detected: {chain}") + if depth > MAX_EXTENDS_DEPTH: + raise ConfigError( + f"configuration 'extends' chain is deeper than {MAX_EXTENDS_DEPTH} levels" + ) + + payload = _read_payload(path) + config = validate_payload(payload) + config.source = path + + if not config.extends: + return config + + base: Optional[Config] = None + preset = resolve_preset(config.extends) + if preset is not None: + base = Config( + min_score=preset.min_score, + weak_names=preset.weak_names, + explicit=frozenset({"min_score", "weak_names"}), + source=f"preset:{preset.name}", + ) + else: + base_path = config.extends + if not os.path.isabs(base_path): + base_path = os.path.join(os.path.dirname(absolute), base_path) + if not os.path.exists(base_path): + raise ConfigError( + f"configuration '{path}': 'extends' refers to unknown preset or " + f"missing file '{config.extends}'" + ) + if not base_path.lower().endswith(".json"): + raise ConfigError( + f"configuration '{path}': 'extends' file must end with .json" + ) + base = _load_with_extends(base_path, list(seen) + [absolute], depth + 1) + + merged = merge_configs(base, config) + merged.source = path + merged.extends = config.extends + return merged + + +def load_config(path: str) -> Config: + """Read and validate ``path``, following ``extends``. Raises ConfigError.""" + return _load_with_extends(path, (), 1) + + +def describe_schema() -> Tuple[str, ...]: + """Human-readable schema lines for ``--help`` and the README.""" + return ( + ' "extends": "balanced" base preset or .json file', + ' "name_terms": ["download", "media_file"] extra literal name terms', + ' "ignore_params": ["image", "avatar"] names to skip entirely', + ' "min_score": 25 integer 0-100', + ' "max_decode_passes": 3 integer 0-5', + ' "weak_names": true boolean', + ' "show_values": false boolean', + ' "name_lang": ["de", "es"] term packs (auto/off)', + ' "fold_names": true diacritic/compat folding', + ' "demote_shapes": true UUID/hash/scalar demotion', + ) + + +def dump_example() -> Dict[str, object]: + """Example configuration used in the README and tests.""" + return { + "name_terms": ["download", "media_file"], + "ignore_params": ["image", "avatar"], + "min_score": 25, + "max_decode_passes": 3, + "weak_names": True, + "show_values": False, + "name_lang": ["de", "es"], + "fold_names": True, + "demote_shapes": True, + } + + +def merge_ignore(cli_values: Sequence[str], config: Config) -> List[str]: + """Combine ``--ignore-param`` flags with the configuration's ignored names.""" + combined: List[str] = [] + for item in list(cli_values) + config.merged_ignore(): + if item and item not in combined: + combined.append(item) + return combined diff --git a/pathscope/detector.py b/pathscope/detector.py new file mode 100644 index 0000000..36d1813 --- /dev/null +++ b/pathscope/detector.py @@ -0,0 +1,444 @@ +"""Turns parsed requests into ranked, explainable candidate findings. + +This module contains no I/O. It receives :class:`pathscope.sources.Request` +objects, analyses their parameters as strings, and returns +:class:`Finding` objects suitable for any renderer. +""" + +from __future__ import annotations + +import hashlib +import time +from dataclasses import dataclass, field, replace +from typing import Dict, Iterable, List, Optional, Sequence, Tuple +from urllib.parse import urlsplit, urlunsplit + +from .heuristics import Analysis, analyze_parameter, canonical_name +from .rules import DEFAULT_BOOK, RuleBook +from .sources import LOCATION_QUERY, Parameter, Request +from .textutil import MAX_DECODE_PASSES, sanitize_text, truncate + +#: Default reporting thresholds. A score below this is not reported. +DEFAULT_MIN_SCORE = 25 + +CONFIDENCE_ORDER = {"high": 0, "medium": 1, "low": 2} + + +#: How repeated findings are collapsed. +DEDUPE_PATH = "path" +DEDUPE_PARAM = "param" +DEDUPE_NONE = "none" +DEDUPE_MODES = (DEDUPE_PATH, DEDUPE_PARAM, DEDUPE_NONE) + +LOGICAL_RULE_PREFIXES = ("value-demote-",) + + +@dataclass(frozen=True) +class AnalysisOptions: + """Knobs for one analysis run.""" + + min_score: int = DEFAULT_MIN_SCORE + max_decode_passes: int = MAX_DECODE_PASSES + extra_terms: Tuple[str, ...] = () + ignore_params: Tuple[str, ...] = () + show_values: bool = False + weak_names: bool = True + #: Effective rule weights (see :mod:`pathscope.rules`). + book: RuleBook = DEFAULT_BOOK + #: Term-pack languages for the name layer (``()`` = English only). + name_lang: Tuple[str, ...] = () + fold_names: bool = True + demote_shapes: bool = True + #: One of ``path`` (default), ``param`` or ``none``. + dedupe_by: str = DEDUPE_PATH + #: Maximum number of input entries to analyze (0 = unlimited). + max_entries: int = 0 + #: Record phase timings on the report (``--stats``). + measure: bool = False + + def with_book(self, book: RuleBook) -> "AnalysisOptions": + return replace(self, book=book) + + +@dataclass +class Finding: + """One candidate parameter, ready for any renderer.""" + + host: str + source_type: str + source_label: str + method: str + location: str + parameter: str + occurrences: int + rule: str + rules: List[str] + reasons: List[str] + score: int + confidence: str + resource: str + value: Optional[str] = None + index: int = 0 + fingerprint: str = "" + #: One of ``new``, ``known`` (baseline/suppression), ``resolved`` (diff only). + status: str = "new" + note: str = "" + + def as_dict(self) -> Dict[str, object]: + return { + "index": self.index, + "host": self.host, + "source_type": self.source_type, + "source": self.source_label, + "method": self.method, + "location": self.location, + "parameter": self.parameter, + "occurrences": self.occurrences, + "rule": self.rule, + "rules": list(self.rules), + "confidence": self.confidence, + "score": self.score, + "reasons": list(self.reasons), + "resource": self.resource, + "value": self.value, + "fingerprint": self.fingerprint, + "status": self.status, + "note": self.note, + } + + +@dataclass +class Report: + """Findings plus the metadata every output format needs.""" + + findings: List[Finding] = field(default_factory=list) + requests_analyzed: int = 0 + parameters_analyzed: int = 0 + sources: List[str] = field(default_factory=list) + warnings: List[str] = field(default_factory=list) + skipped: int = 0 + min_score: int = DEFAULT_MIN_SCORE + show_values: bool = False + #: "diff" when a baseline or suppression file was applied. + mode: str = "scan" + known_count: int = 0 + baseline_source: str = "" + #: Findings that were reported by the baseline but are no longer present. + resolved: List[Dict[str, object]] = field(default_factory=list) + #: Input entries ignored because of ``--max-entries``. + truncated_entries: int = 0 + #: Phase timings (only filled when ``--stats`` was requested). + stats: Dict[str, float] = field(default_factory=dict) + #: Effective rule configuration, for the JSON payload. + rules: Dict[str, int] = field(default_factory=dict) + rules_source: str = "" + name_lang: Tuple[str, ...] = () + #: Set by ``--redact-hosts`` so renderers can say hosts are pseudonyms. + hosts_redacted: bool = False + + @property + def candidate_count(self) -> int: + """Candidates shown in this run (i.e. after baseline filtering).""" + return len(self.findings) + + @property + def new_count(self) -> int: + return sum(1 for finding in self.findings if finding.status == "new") + + @property + def known_findings(self) -> List[Finding]: + return [finding for finding in self.findings if finding.status == "known"] + + @property + def confidence_counts(self) -> Dict[str, int]: + counts = {"high": 0, "medium": 0, "low": 0} + for finding in self.findings: + counts[finding.confidence] = counts.get(finding.confidence, 0) + 1 + return counts + + +def _mask_userinfo(url: str) -> str: + """Remove ``user:pass@`` from a URL's authority if present.""" + parts = urlsplit(url) + if "@" not in parts.netloc: + return url + return urlunsplit( + (parts.scheme, "@" + parts.netloc.rsplit("@", 1)[1], + parts.path, "", "") + ) + + +def _safe_resource(request: Request) -> str: + """Scheme, host, port and path only: query strings are never included.""" + return _mask_userinfo(request.url.display_resource) + + +def _group_parameters(parameters: Sequence[Parameter]) -> List[Tuple[str, List[Parameter]]]: + """Group repeated parameters by location and canonical name, in order.""" + groups: Dict[Tuple[str, str], List[Parameter]] = {} + order: List[Tuple[str, str]] = [] + for parameter in parameters: + key = (parameter.location, canonical_name(parameter.name)) + if key not in groups: + groups[key] = [] + order.append(key) + groups[key].append(parameter) + return [(key[1], groups[key]) for key in order] + + +def _dedupe_requests(requests: Iterable[Request]) -> List[Request]: + seen: set = set() + unique: List[Request] = [] + for request in requests: + key = request.dedupe_key + if key in seen: + continue + seen.add(key) + unique.append(request) + return unique + + +def analyze_requests( + requests: Sequence[Request], options: AnalysisOptions +) -> Report: + """Analyse requests and return a deterministic :class:`Report`.""" + report = Report( + min_score=options.min_score, + show_values=options.show_values, + sources=sorted({request.source_label for request in requests}), + rules=options.book.as_dict(), + rules_source=options.book.source or "defaults", + name_lang=tuple(options.name_lang), + ) + ignored = {canonical_name(item) for item in options.ignore_params if item} + + findings: List[Finding] = [] + started = time.perf_counter() + entries = _dedupe_requests(requests) + if options.max_entries and len(entries) > options.max_entries: + entries = entries[: options.max_entries] + report.truncated_entries = len(_dedupe_requests(requests)) - options.max_entries + report.warnings.append( + f"--max-entries={options.max_entries}: analysis truncated; " + f"{report.truncated_entries} input entr(ies) ignored" + ) + analyse_started = time.perf_counter() + for request in entries: + report.requests_analyzed += 1 + resource = _safe_resource(request) + for canonical, occurrences in _group_parameters(request.parameters): + if canonical in ignored: + continue + report.parameters_analyzed += 1 + + best: Optional[Analysis] = None + best_value = "" + for parameter in occurrences: + analysis = analyze_parameter( + parameter.name, + parameter.value, + max_decode_passes=options.max_decode_passes, + extra_terms=options.extra_terms, + ignore=options.ignore_params, + min_score=options.min_score, + weak_names=options.weak_names, + book=options.book, + languages=options.name_lang, + fold=options.fold_names, + demote=options.demote_shapes, + ) + if analysis.evidence and (best is None or analysis.score > best.score): + best = analysis + best_value = parameter.value + if best is None: + continue + + first = occurrences[0] + location = first.location or LOCATION_QUERY + fp = fingerprint( + request.url.display_host, + location, + first.name, + best.primary_rule, + resource, + ) + findings.append( + Finding( + fingerprint=fp, + host=request.url.display_host, + source_type=request.source_type, + source_label=request.source_label, + method=request.method, + location=location, + parameter=first.name, + occurrences=len(occurrences), + rule=best.primary_rule, + rules=list(best.rules), + reasons=list(best.reasons), + score=best.score, + confidence=best.confidence, + resource=resource, + value=sanitize_text(best_value) if options.show_values else None, + ) + ) + + findings.sort( + key=lambda item: ( + -item.score, + item.host, + item.location, + canonical_name(item.parameter), + item.source_label, + item.method, + truncate(item.resource, 300), + ) + ) + if options.dedupe_by != DEDUPE_NONE: + findings = _collapse_findings(findings, options.dedupe_by) + for index, finding in enumerate(findings, start=1): + finding.index = index + report.findings = findings + if options.measure: + report.stats = { + "parse_seconds": round(report.stats.get("parse_seconds", 0.0), 4), + "analyze_seconds": round(time.perf_counter() - analyse_started, 4), + "total_seconds": round(time.perf_counter() - started, 4), + "input_entries": len(entries), + "findings": len(findings), + } + return report + + +def _collapse_findings(findings: List[Finding], mode: str) -> List[Finding]: + """Collapse the same parameter seen on several resources. + + ``path`` one finding per host + location + parameter (default; the + occurrence count says how many resources mapped to it) + ``param`` one finding per parameter name, across hosts + ``none`` every (resource, parameter) pair stays separate + """ + if mode == DEDUPE_PATH: + key = lambda f: (f.host, f.location, canonical_name(f.parameter)) # noqa: E731 + elif mode == DEDUPE_PARAM: + key = lambda f: canonical_name(f.parameter) # noqa: E731 + else: # pragma: no cover - guarded by the caller + return findings + + collapsed: List[Finding] = [] + seen: Dict[Tuple, Finding] = {} + for finding in findings: + lookup = key(finding) + existing = seen.get(lookup) + if existing is None: + seen[lookup] = finding + collapsed.append(finding) + continue + existing.occurrences += finding.occurrences + if finding.resource != existing.resource: + existing.note = ( + f"also seen on {finding.resource}" + if not existing.note + else existing.note + ) + return collapsed + + +# --------------------------------------------------------------------------- +# Stable fingerprints, baselines and suppression +# --------------------------------------------------------------------------- +def fingerprint( + host: str, location: str, parameter: str, rule: str, resource: str = "" +) -> str: + """Deterministic 16-hex fingerprint for one finding identity. + + Identity = host + parameter location + canonical parameter name + primary + rule + resource path. Values, scores and source labels are excluded so a + baseline stays valid when the same parameter reappears with new data or the + capture is taken from a different file. + """ + material = "\x1f".join( + ( + host.lower(), + location, + canonical_name(parameter), + rule, + resource, + ) + ) + return hashlib.sha256(material.encode("utf-8")).hexdigest()[:16] + + +def _finding_identity(finding: Finding) -> Tuple[str, str, str, str, str]: + return ( + finding.host, + finding.location, + canonical_name(finding.parameter), + finding.rule, + finding.resource, + ) + + +@dataclass +class Baseline: + """A previous run's findings, plus review notes.""" + + source: str = "" + fingerprints: Dict[str, str] = field(default_factory=dict) # fp -> note + entries: List[Dict[str, object]] = field(default_factory=list) + + @classmethod + def from_payload(cls, payload: object, source: str = "") -> "Baseline": + baseline = cls(source=source) + if not isinstance(payload, dict): + raise ValueError("baseline must be a JSON object") + raw = payload.get("findings", payload.get("suppressions", [])) + if not isinstance(raw, list): + raise ValueError("baseline 'findings' must be an array") + for entry in raw: + if not isinstance(entry, dict): + continue + fp = entry.get("fingerprint") + if not isinstance(fp, str) or not fp: + continue + note = entry.get("note") + baseline.fingerprints[fp] = note if isinstance(note, str) else "" + baseline.entries.append(entry) + return baseline + + +def apply_baseline(report: Report, baseline: Baseline, show_known: bool = False) -> Report: + """Mark findings present in ``baseline`` as known and (optionally) hide them.""" + report.mode = "diff" + report.baseline_source = baseline.source + for finding in report.findings: + fp = finding.fingerprint + if fp in baseline.fingerprints: + finding.status = "known" + finding.note = baseline.fingerprints.get(fp, "") or "" + report.known_count += 1 + seen = {finding.fingerprint for finding in report.findings} + for entry in baseline.entries: + fp = entry.get("fingerprint") + if fp not in seen: + report.resolved.append(dict(entry)) + if not show_known: + report.findings = [f for f in report.findings if f.status == "new"] + return report + + +def summarize(report: Report) -> str: + """One-line summary used by renderers and the CLI stderr trailer.""" + counts = report.confidence_counts + text = ( + f"{report.requests_analyzed} request(s), {report.parameters_analyzed} " + f"parameter(s), {report.candidate_count} candidate(s) " + f"(high {counts.get('high', 0)}, medium {counts.get('medium', 0)}, " + f"low {counts.get('low', 0)}), {report.skipped} input line(s) skipped" + ) + if report.mode == "diff": + text += ( + f"; diff vs {report.baseline_source or 'baseline'}: " + f"{report.new_count} new, {report.known_count} known, " + f"{len(report.resolved)} resolved" + ) + return text diff --git a/pathscope/extra_formats.py b/pathscope/extra_formats.py new file mode 100644 index 0000000..322edd1 --- /dev/null +++ b/pathscope/extra_formats.py @@ -0,0 +1,693 @@ +"""Additional local input formats for PathScope. + +Everything here is pure parsing of files the user already has: + +``burp`` + Burp Suite *proxy history* XML export (```` with a raw + request block). Only the request line, ``Host`` header and form/JSON body + are read. Responses are ignored. + +``openapi`` + Swagger 2.0 / OpenAPI 3.x descriptions, reduced to a parameter inventory: + every declared query/form/path parameter name becomes an analyzed + parameter with no value of its own (only names can be judged). + +``raw`` + A single raw HTTP request (``GET /path?file=x HTTP/1.1`` + headers). + Multiple requests in one file may be separated by a ``###`` line. + ``Host`` is taken from the header, so this works with curl ``--trace`` + style copies, Repeater saves and hand-written snippets. + +``httpx`` / ``ffuf`` / ``gobuster`` / ``katana`` / ``nuclei`` + Line-oriented recon output is reduced to the URLs it contains. JSONL export + modes (httpx ``-json``, nuclei ``-jsonl``, katana ``-jsonl``) are also + accepted; only URL-like fields are used. +""" + +from __future__ import annotations + +import json +import re +import xml.etree.ElementTree as ET +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import unquote_plus, urlsplit + +from .sources import ( + LOCATION_FORM, + LOCATION_JSON, + LOCATION_QUERY, + SOURCE_FILE, + HarError, + LoadResult, + Parameter, + Request, + URLInfo, + URLParseError, + _as_text, + _form_parameters, + _json_parameters, + canonical, + parse_url, + query_parameters, + split_query, +) +from .textutil import sanitize_text + +# Input format identifiers. +INPUT_FORMAT_BURP = "burp" +INPUT_FORMAT_OPENAPI = "openapi" +INPUT_FORMAT_RAW = "raw" +INPUT_FORMAT_HTTPX = "httpx" +INPUT_FORMAT_FFUF = "ffuf" +INPUT_FORMAT_NUCLEI = "nuclei" + +#: Identifier used in reports for every line-oriented recon export. +SOURCE_RECON = "recon" + +#: Hard limits so a hostile or accidental huge file cannot exhaust memory. +MAX_XML_BYTES = 64 * 1024 * 1024 +MAX_REQUEST_BYTES = 4 * 1024 * 1024 + +URL_IN_TEXT_RE = re.compile(r"https?://[^\s\"'<>\\]+", re.IGNORECASE) +STATUS_SUFFIX_RE = re.compile( + r"\s+\[(?:status[- ]?code:\s*)?\d{1,3}(?:,\s*\d+\s*(?:B|KB|MB))?\]\s*$", + re.IGNORECASE, +) + + +# --------------------------------------------------------------------------- +# Burp Suite proxy-history XML +# --------------------------------------------------------------------------- +def looks_like_burp(text: str, path: str = "") -> bool: + head = text.lstrip("\ufeff \t\r\n")[:8192].lower() + if " Tuple[str, str, Optional[str]]: + """Return ``(request_target, host, body)`` from one Burp ````.""" + request = item.find("request") + if request is None: + raise HarError("missing element") + if (request.get("base64") or "").lower() == "true": + import base64 + + try: + raw = base64.b64decode(request.text or "", validate=False).decode( + "latin-1", "replace" + ) + except (ValueError, TypeError) as exc: # pragma: no cover - defensive + raise HarError(f"invalid base64 request ({exc})") from exc + else: + raw = request.text or "" + raw = raw[:MAX_REQUEST_BYTES] + if not raw.strip(): + raise HarError("empty request block") + + head, _sep, body = raw.replace("\r\n", "\n").partition("\n\n") + lines = head.split("\n") + request_line = lines[0].strip() + parts = request_line.split() + if len(parts) < 2: + raise HarError("malformed request line") + target = parts[1] + + host = "" + for line in lines[1:]: + name, _colon, value = line.partition(":") + if name.strip().lower() == "host": + host = value.strip() + break + + # Absolute-form targets (proxy style) already contain the host. + if target.lower().startswith("http://") or target.lower().startswith("https://"): + return target, "", body + if not host: + raise HarError("request has no Host header") + scheme = "https" if "https" in request_line.lower() else "http" + if not target.startswith("/"): + target = "/" + target + return f"{scheme}://{host}{target}", host, body + + +def _burp_request_parameters( + body: str, content_type: str, label: str, warnings: List[str] +) -> List[Parameter]: + if not body: + return [] + lowered = (content_type or "").lower() + if "application/json" in lowered: + try: + payload = json.loads(body) + except ValueError as exc: + warnings.append(f"{label}: malformed JSON body skipped ({exc})") + return [] + return _json_parameters(payload, warnings, label) + if "x-www-form-urlencoded" in lowered or not lowered: + pairs = split_query(body.strip()) + if pairs and "=" in body: + decoded_pairs = [] + for name, raw_value in pairs: + try: + decoded_value = unquote_plus(raw_value) + except (UnicodeError, ValueError): # pragma: no cover - defensive + decoded_value = raw_value + decoded_pairs.append((name, sanitize_text(decoded_value)[:20000])) + return [ + Parameter(name=name, value=value, location=LOCATION_FORM) + for name, value in decoded_pairs + if name + ] + if "multipart/form-data" in lowered: + return _multipart_parameters(body, label) + return [] + + +BOUNDARY_RE = re.compile(r"boundary=\"?([^\";]+)\"?", re.IGNORECASE) +PART_NAME_RE = re.compile( + r'content-disposition:[^\r\n]*\bname="([^"]+)"([^\r\n]*)', re.IGNORECASE +) +PART_FILENAME_RE = re.compile(r'\bfilename="([^"]*)"', re.IGNORECASE) + + +def _multipart_parameters(body: str, label: str) -> List[Parameter]: + """Extract part names (and file names) from a multipart body.""" + parameters: List[Parameter] = [] + for part in re.split(r"\r?\n--[^\r\n]+", body): + match = PART_NAME_RE.search(part) + if not match: + continue + name = match.group(1) + filename = PART_FILENAME_RE.search(part) + if filename: + value = filename.group(1) + else: + _head, _sep, content = part.partition("\r\n\r\n") + if not _sep: + _head, _sep, content = part.partition("\n\n") + value = content.strip() + parameters.append( + Parameter( + name=sanitize_text(name), + value=sanitize_text(value)[:20000], + location=LOCATION_FORM, + ) + ) + return parameters + + +def load_burp(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse a Burp proxy-history XML export. Raises :class:`HarError`.""" + source_label = source_label or label + if len(text.encode("utf-8", "ignore")) > MAX_XML_BYTES: + raise HarError(f"{label}: file exceeds the {MAX_XML_BYTES // (1024 * 1024)} MB limit") + try: + root = ET.fromstring(text.lstrip("\ufeff")) + except ET.ParseError as exc: + raise HarError(f"{label}: not valid XML ({exc})") from exc + + items = root.findall(".//item") + if not items: + raise HarError(f"{label}: no elements found (export Burp proxy history as XML)") + + result = LoadResult() + seen = set() + for index, item in enumerate(items): + item_label = f"{label} item {index}" + try: + url, _host, body = _burp_raw_request(item) + info = parse_url(url) + content_type = "" + request_el = item.find("request") + if request_el is not None: + raw_text = request_el.text or "" + for line in raw_text.replace("\r\n", "\n").split("\n")[1:]: + name, _colon, value = line.partition(":") + if name.strip().lower() == "content-type": + content_type = value.strip() + break + parameters = query_parameters(info.query) + parameters.extend( + _burp_request_parameters(body, content_type, item_label, result.warnings) + ) + method = (item.findtext("method") or "GET").strip().upper() + if not method: + raw_text = (item.findtext("request") or "").split("\n", 1)[0] + pieces = raw_text.split() + method = pieces[0].upper() if pieces else "GET" + except (HarError, URLParseError) as exc: + result.warnings.append(f"{item_label}: skipped ({exc})") + result.skipped += 1 + continue + except Exception as exc: # noqa: BLE001 - never abort the run + result.warnings.append(f"{item_label}: skipped unreadable item ({exc})") + result.skipped += 1 + continue + + key = (method, info.raw, tuple((p.location, p.name, p.value) for p in parameters)) + if key in seen: + continue + seen.add(key) + result.requests.append( + Request( + url=info, + source_type="burp", + source_label=source_label, + parameters=parameters, + method=method, + index=len(result.requests), + ) + ) + return result + + +def load_burp_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_burp(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# OpenAPI / Swagger +# --------------------------------------------------------------------------- +HTTP_METHODS = ("get", "put", "post", "delete", "options", "head", "patch", "trace") + + +def looks_like_openapi(payload: Any) -> bool: + return isinstance(payload, dict) and ( + "openapi" in payload or "swagger" in payload + ) and isinstance(payload.get("paths"), dict) + + +def _schema_parameter_names(schema: Any, warnings: List[str], label: str) -> List[Parameter]: + """Flatten an OpenAPI schema's properties into named parameters (no values).""" + parameters: List[Parameter] = [] + + def walk(node: Any, prefix: str, depth: int) -> None: + if depth > 8 or len(parameters) > 2000: + return + if not isinstance(node, dict): + return + properties = node.get("properties") + if isinstance(properties, dict): + for name, child in properties.items(): + path = f"{prefix}.{name}" if prefix else str(name) + kind = child.get("type") if isinstance(child, dict) else None + if kind in (None, "object") and isinstance(child, dict) and "properties" in child: + walk(child, path, depth + 1) + else: + parameters.append( + Parameter(name=path, value="", location=LOCATION_JSON) + ) + items = node.get("items") + if isinstance(items, dict): + walk(items, f"{prefix}[]" if prefix else "[]", depth + 1) + + walk(schema, "", 0) + return parameters + + +def _openapi_requests(payload: Any, warnings: List[str], label: str) -> List[Request]: + """Build one synthetic GET request per path+method with declared parameters.""" + base_url = "" + servers = payload.get("servers") + if isinstance(servers, list) and servers and isinstance(servers[0], dict): + base_url = str(servers[0].get("url") or "") + if not base_url and isinstance(payload.get("host"), str): + scheme = "https" + if isinstance(payload.get("schemes"), list) and payload["schemes"]: + scheme = str(payload["schemes"][0]) + base_url = f"{scheme}://{payload['host']}{payload.get('basePath') or ''}" + try: + parsed = urlsplit(base_url) if base_url else None + host = (parsed.hostname if parsed else "") or "openapi.local" + scheme = (parsed.scheme if parsed else "") or "https" + except ValueError: + host, scheme = "openapi.local", "https" + + requests: List[Request] = [] + paths = payload.get("paths") or {} + for raw_path, path_item in paths.items(): + if not isinstance(path_item, dict): + continue + for method in HTTP_METHODS: + operation = path_item.get(method) + if not isinstance(operation, dict): + continue + parameters: List[Parameter] = [] + declared = list(path_item.get("parameters") or []) + list( + operation.get("parameters") or [] + ) + for entry in declared: + if not isinstance(entry, dict): + continue + if "$ref" in entry and "name" not in entry: + # Unresolved $ref: name unknown, note it and move on. + warnings.append( + f"{label}: unresolved parameter $ref in {method.upper()} {raw_path}" + ) + continue + name = entry.get("name") + if not isinstance(name, str) or not name: + continue + location = str(entry.get("in") or "query").lower() + if location not in ("query", "formData", "path", "header", "cookie"): + location = "query" + if location == "header": + # Header names are not path consumers in this model. + continue + parameters.append( + Parameter( + name=name, + value="", + location=LOCATION_FORM if location == "formData" else LOCATION_QUERY, + ) + ) + + request_body = operation.get("requestBody") + if isinstance(request_body, dict): + content = request_body.get("content") + if isinstance(content, dict): + for mime, media in content.items(): + if not isinstance(media, dict): + continue + if "json" in str(mime): + parameters.extend( + _schema_parameter_names( + media.get("schema"), warnings, label + ) + ) + elif "form" in str(mime): + schema = media.get("schema") + if isinstance(schema, dict): + properties = schema.get("properties") + if isinstance(properties, dict): + for prop in properties: + parameters.append( + Parameter( + name=str(prop), + value="", + location=LOCATION_FORM, + ) + ) + # Swagger 2.0 body parameter + for entry in declared: + if isinstance(entry, dict) and entry.get("in") == "body": + schema = entry.get("schema") + if isinstance(schema, dict): + parameters.extend( + _schema_parameter_names(schema, warnings, label) + ) + + path_with_params = raw_path or "/" + try: + info = URLInfo( + raw=f"{scheme}://{host}{path_with_params}", + scheme=scheme, + host=host, + port=None, + path=path_with_params, + query="", + ) + except Exception: # pragma: no cover - defensive + continue + if not parameters: + continue + # de-duplicate declared names within the operation + unique: List[Parameter] = [] + seen_names = set() + for parameter in parameters: + key = (parameter.location, canonical(parameter.name)) + if key in seen_names: + continue + seen_names.add(key) + unique.append(parameter) + requests.append( + Request( + url=info, + source_type="openapi", + source_label=label, + parameters=unique, + method=method.upper(), + index=len(requests), + ) + ) + return requests + + +def load_openapi(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse an OpenAPI/Swagger document into a parameter inventory.""" + source_label = source_label or label + try: + payload = json.loads(text.lstrip("\ufeff")) + except ValueError as exc: + raise HarError(f"{label}: not valid JSON ({exc})") from exc + if not looks_like_openapi(payload): + raise HarError( + f"{label}: not an OpenAPI/Swagger document (expected 'openapi'/'swagger' " + "and a 'paths' object)" + ) + result = LoadResult() + result.requests = _openapi_requests(payload, result.warnings, source_label) + if not result.requests: + result.warnings.append(f"{label}: document declares no usable parameters") + return result + + +def load_openapi_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_openapi(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# Raw HTTP requests +# --------------------------------------------------------------------------- +def looks_like_raw_http(text: str, path: str = "") -> bool: + stripped = text.lstrip("\ufeff \t\r\n") + first = stripped.split("\n", 1)[0].strip() + return bool(re.match(r"^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\S+\s+HTTP/\d\.\d$", first)) + + +def load_raw_http(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse one or more raw HTTP requests separated by ``###`` lines.""" + source_label = source_label or label + result = LoadResult() + chunks = re.split(r"(?m)^###+\s*$", text.lstrip("\ufeff")) + seen = set() + for index, chunk in enumerate(chunks): + chunk = chunk.strip("\r\n") + if not chunk.strip(): + continue + chunk_label = f"{label} request {index + 1}" + try: + info, parameters, method = _parse_raw_http_chunk(chunk, chunk_label, result.warnings) + except (HarError, URLParseError) as exc: + result.warnings.append(f"{chunk_label}: skipped ({exc})") + result.skipped += 1 + continue + key = (method, info.raw, tuple((p.location, p.name, p.value) for p in parameters)) + if key in seen: + continue + seen.add(key) + result.requests.append( + Request( + url=info, + source_type="raw", + source_label=source_label, + parameters=parameters, + method=method, + index=len(result.requests), + ) + ) + if not result.requests: + raise HarError(f"{label}: no usable HTTP requests found") + return result + + +def _parse_raw_http_chunk( + chunk: str, label: str, warnings: List[str] +) -> Tuple[URLInfo, List[Parameter], str]: + chunk = chunk[:MAX_REQUEST_BYTES] + head, _sep, body = chunk.replace("\r\n", "\n").partition("\n\n") + lines = [line for line in head.split("\n")] + request_line = lines[0].strip() if lines else "" + match = re.match(r"^([A-Za-z]+)\s+(\S+)\s+HTTP/\d(?:\.\d)?$", request_line) + if not match: + raise HarError("malformed request line") + method = match.group(1).upper() + target = match.group(2) + + headers: Dict[str, str] = {} + for line in lines[1:]: + if not line.strip(): + continue + if line[:1] in (" ", "\t"): # folded header + continue + name, _colon, value = line.partition(":") + if not _colon: + continue + headers.setdefault(name.strip().lower(), value.strip()) + + host = headers.get("host", "") + if target.lower().startswith(("http://", "https://")): + url = target + else: + if not host: + raise HarError("request has no Host header") + scheme = "https" if "https" in headers.get("x-forwarded-proto", "").lower() else "http" + if not target.startswith("/"): + target = "/" + target + url = f"{scheme}://{host}{target}" + + info = parse_url(url) + parameters = query_parameters(info.query) + content_type = headers.get("content-type", "") + parameters.extend(_burp_request_parameters(body, content_type, label, warnings)) + return info, parameters, method + + +def load_raw_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_raw_http(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# Recon / tool exports (httpx, ffuf, gobuster, katana, nuclei, ...) +# --------------------------------------------------------------------------- +def _urls_from_line(line: str) -> List[str]: + """Extract URL candidates from a tool-output line, including JSONL.""" + stripped = line.strip() + if not stripped: + return [] + if stripped.startswith("{"): + try: + payload = json.loads(stripped) + except ValueError: + pass + else: + found: List[str] = [] + if isinstance(payload, dict): + for key in ("url", "input", "endpoint", "matched-at", "host"): + value = payload.get(key) + if isinstance(value, str) and value.lower().startswith(("http://", "https://")): + found.append(value) + break + return found + # Strip ffuf/gobuster status suffix, then find URL-looking tokens. + cleaned = STATUS_SUFFIX_RE.sub("", stripped) + urls = URL_IN_TEXT_RE.findall(cleaned) + if urls: + return [urls[0]] + return [] + + +def load_recon_text( + text: str, label: str, source_type: str = "recon", source_label: Optional[str] = None +) -> LoadResult: + """Reduce line/JSONL recon output to analysable URLs.""" + source_label = source_label or label + result = LoadResult() + urls: List[str] = [] + for line_number, line in enumerate(text.splitlines(), start=1): + for url in _urls_from_line(line): + urls.append(url) + if not urls: + raise HarError( + f"{label}: no http(s) URLs found in {source_type} output" + ) + seen = set() + for index, raw in enumerate(urls): + if raw in seen: + continue + try: + info = parse_url(raw) + except URLParseError as exc: + result.warnings.append(f"{label} line {index + 1}: skipped malformed URL ({exc})") + result.skipped += 1 + continue + seen.add(raw) + result.requests.append( + Request( + url=info, + source_type=source_type, + source_label=source_label, + parameters=query_parameters(info.query), + method="GET", + index=len(result.requests), + ) + ) + return result + + +def load_recon_file(path: str, source_type: str = "recon") -> LoadResult: + import os + + from .sources import read_text + + return load_recon_text( + read_text(path), os.path.basename(path) or path, source_type, source_label=path + ) + + +# --------------------------------------------------------------------------- +# Detection helpers +# --------------------------------------------------------------------------- +def detect_extra_format(text: str, path: str = "") -> Optional[str]: + """Return one of the extra format ids, or ``None`` if nothing matches.""" + lowered_path = (path or "").lower() + stripped = text.lstrip("\ufeff \t\r\n") + if looks_like_burp(text, path): + return INPUT_FORMAT_BURP + if stripped.startswith("{"): + try: + payload = json.loads(stripped) + except ValueError: + payload = None + if looks_like_openapi(payload): + return INPUT_FORMAT_OPENAPI + if lowered_path.endswith((".yaml", ".yml")): + # YAML OpenAPI files cannot be parsed with the standard library. + if "openapi" in text[:2048].lower() or "swagger" in text[:2048].lower(): + return "openapi-yaml" + if looks_like_raw_http(text, path): + return INPUT_FORMAT_RAW + if lowered_path.endswith((".xml",)): + return INPUT_FORMAT_BURP if " LoadResult: + if fmt == INPUT_FORMAT_BURP: + return load_burp_file(path) + if fmt == INPUT_FORMAT_OPENAPI: + return load_openapi_file(path) + if fmt == INPUT_FORMAT_RAW: + return load_raw_file(path) + if fmt == "openapi-yaml": + raise HarError( + f"{path}: YAML OpenAPI files are not supported (standard library only); " + "convert to JSON with `python3 -c \"import sys,json,yaml;" + "json.dump(yaml.safe_load(sys.stdin), sys.stdout)\" < spec.yaml > spec.json`" + ) + return load_recon_file(path, fmt) + + +def load_extra_text(text: str, fmt: str, label: str) -> LoadResult: + if fmt == INPUT_FORMAT_BURP: + return load_burp(text, label) + if fmt == INPUT_FORMAT_OPENAPI: + return load_openapi(text, label) + if fmt == INPUT_FORMAT_RAW: + return load_raw_http(text, label) + return load_recon_text(text, label, fmt) diff --git a/pathscope/extractor.py b/pathscope/extractor.py new file mode 100644 index 0000000..d128980 --- /dev/null +++ b/pathscope/extractor.py @@ -0,0 +1,373 @@ +"""Offline URL extraction from local HTML and JavaScript (``--extract``). + +The usual starting point for a review is "here is the front-end, what does it +call?". Normally that means reading a bundle by hand or watching a proxy. This +module reads **files you already have** and pulls the endpoint strings out: + +* ``fetch("…")``, ``axios.get("…")``, ``xhr.open("GET", "…")``, ``$.ajax``, +* ``href`` / ``src`` / ``action`` / ``formaction`` attributes and ``
`` + definitions, +* bare absolute URLs and quoted path+query strings, +* ``import("…")`` and dynamic ``importScripts`` targets. + +Nothing is fetched, opened or resolved: the input files are read as text and +the extracted strings are treated exactly like a URL list. Only endpoints on +the files' own origin are kept by default (a bundle is full of CDN and analytics +noise); ``--extract-all-hosts`` keeps everything. + +Every extracted string goes through the same sanitiser and size limits as a +piped URL list, so a hostile file cannot inject terminal escapes or blow up +memory. +""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence + +from .sources import ( + SOURCE_FILE, + LoadResult, + URLParseError, + request_from_url, +) +from .textutil import sanitize_text + +#: Files larger than this are skipped with a warning (a minified bundle is big). +MAX_FILE_BYTES = 8 * 1024 * 1024 +#: Cap on extracted candidates per file, so one generated bundle stays sane. +MAX_URLS_PER_FILE = 20_000 + +#: The attribute/receiver patterns that mean "a URL is coming next". +_JS_CALL_PATTERNS = ( + # fetch("…"), fetch(`…`) + re.compile(r"""\bfetch\s*\(\s*(['"`])([^'"`\s]{1,2048})\1"""), + # axios.get("…"), axios.post('…') + re.compile(r"""\baxios\s*\.\s*(?:get|post|put|patch|delete|head|options)\s*\(\s*(['"`])([^'"`\s]{1,2048})\1"""), + # xhr.open("GET", "…") + re.compile(r"""\.open\s*\(\s*(['"`])[A-Za-z]{3,7}\1\s*,\s*(['"`])([^'"`\s]{1,2048})\2"""), + # $.ajax({url: "…"}), jQuery.get("…") + re.compile(r"""\b(?:url|uri)\s*:\s*(['"`])([^'"`\s]{1,2048})\1"""), + re.compile(r"""\$\.(?:get|post|ajax|getJSON)\s*\(\s*(['"`])([^'"`\s]{1,2048})\1"""), + # new URL("…", location), new Request("…") + re.compile(r"""\bnew\s+(?:URL|Request)\s*\(\s*(['"`])([^'"`\s]{1,2048})\1"""), + # import("…"), importScripts("…") + re.compile(r"""\bimport\s*\(\s*(['"`])([^'"`\s]{1,2048})\1"""), + re.compile(r"""\bimportScripts\s*\(\s*(['"`])([^'"`\s]{1,2048})\1"""), + # location.href = "…", window.location = "…" + re.compile(r"""\blocation(?:\.href)?\s*=\s*(['"`])([^'"`\s]{1,2048})\1"""), +) + +#: HTML attributes whose value is normally a URL. +_HTML_ATTRIBUTES = ( + "href", "src", "action", "formaction", "data-url", "data-href", + "data-action", "poster", "cite", +) +_HTML_ATTR_RE = re.compile( + r"""\b(?:""" + "|".join(_HTML_ATTRIBUTES) + r""")\s*=\s*(["'])([^"']{1,2048})\1""", + re.IGNORECASE, +) +#: A quoted string that looks like an absolute URL. +_ABS_URL_RE = re.compile(r"""(['"])(https?://[^'"\s]{3,2048})\1""", re.IGNORECASE) +#: A quoted string that looks like "/path?query" or "path?query". +_PATH_QUERY_RE = re.compile(r"""(['"])((?:\.{0,2}/)?[A-Za-z0-9._~%/-]{1,512}\?[^'"\s=]{1,800}=[^'"\s]{0,1024})\1""") +#: Inline single-quoted query fragments inside a template literal. +_TEMPLATE_RE = re.compile(r"""`([^`]{1,2048}\?[^`]{1,2048})`""") + + +class ExtractError(RuntimeError): + """Raised when extraction cannot proceed (bad file, nothing readable).""" + + +@dataclass +class Extracted: + """One candidate string found in a file, with where it came from.""" + + value: str + file: str + line: int + kind: str # fetch | attribute | absolute | path-query | template + + +@dataclass +class ExtractResult: + """Everything one ``--extract`` run produced.""" + + requests: List[object] = field(default_factory=list) + warnings: List[str] = field(default_factory=list) + found: List[Extracted] = field(default_factory=list) + files_read: int = 0 + skipped_files: int = 0 + per_file: Dict[str, int] = field(default_factory=dict) + + def as_load_result(self, origin_hosts: Sequence[str]) -> LoadResult: + """Return a :class:`LoadResult` ready for the normal analysis pipeline.""" + return LoadResult(requests=list(self.requests), warnings=list(self.warnings)) + + +# --------------------------------------------------------------------------- +# extraction +# --------------------------------------------------------------------------- +def _line_of(text: str, index: int) -> int: + return text.count("\n", 0, index) + 1 + + +def _collect(regex: re.Pattern, text: str, kind: str, path: str) -> List[Extracted]: + """Run one pattern and take the **last** capture group as the value. + + Every pattern here is written so the value is its final group: quoted + strings put the quote first, and the attribute pattern is + ``(quote) (value)``, while ``xhr.open`` is ``(quote) METHOD (quote) (value)``. + """ + out: List[Extracted] = [] + group = regex.groups + for match in regex.finditer(text): + value = match.group(group) + if not value: + continue + out.append( + Extracted( + value=sanitize_text(value).strip(), + file=path, + line=_line_of(text, match.start()), + kind=kind, + ) + ) + return out + + +def extract_text(text: str, path: str = "") -> List[Extracted]: + """Extract every URL-looking string from one document, in file order.""" + found: List[Extracted] = [] + for pattern in _JS_CALL_PATTERNS: + found.extend(_collect(pattern, text, "fetch", path)) + found.extend(_collect(_HTML_ATTR_RE, text, "attribute", path)) + found.extend(_collect(_ABS_URL_RE, text, "absolute", path)) + found.extend(_collect(_PATH_QUERY_RE, text, "path-query", path)) + found.extend(_collect(_TEMPLATE_RE, text, "template", path)) + # Stable, deduplicated order: first occurrence wins. + seen: set = set() + unique: List[Extracted] = [] + for entry in found: + key = entry.value + if not key or key in seen: + continue + seen.add(key) + unique.append(entry) + return unique[:MAX_URLS_PER_FILE] + + +def _origin_of(value: str): + from .sources import parse_url + + try: + return parse_url(value).host.lower() + except URLParseError: + return "" + + +def origin_hosts(paths: Sequence[str], texts: Optional[Sequence[str]] = None) -> List[str]: + """Guess the app's own host(s) from the file names and any absolute URLs. + + A bundle called ``app.js`` says nothing, but a page that references + ``https://app.test/api`` does: we keep that host so relative paths can be + resolved against it. + """ + hosts: List[str] = [] + for text in list(texts or ()) + list(paths): + for match in _ABS_URL_RE.finditer(text): + host = _origin_of(match.group(2)) + if host and host not in hosts: + hosts.append(host) + return hosts + + +#: Host fragments that almost always mean "not the application itself". +THIRD_PARTY_HINTS = ( + "cdn.", "static.", "assets.", "fonts.", "analytics.", "googletagmanager", + "google-analytics", "doubleclick", "facebook", "twitter", "linkedin", + "cloudflare", "jsdelivr", "unpkg", "bootstrapcdn", "gstatic", "sentry", + "segment.", "mixpanel", "hotjar", "newrelic", "datadoghq", "bugsnag", +) + + +def _looks_like_third_party(host: str) -> bool: + lowered = (host or "").lower() + return any(hint in lowered for hint in THIRD_PARTY_HINTS) + + +def _to_url(value: str, host: str) -> str: + """Turn an extracted string into something the URL parser accepts.""" + text = value.strip() + if text.startswith("//"): + return "https:" + text + if text.startswith("/"): + return f"https://{host}{text}" if host else "" + if re.match(r"^https?://", text, re.IGNORECASE): + return text + if host and ("?" in text or text.startswith("./") or text.startswith("../")): + return f"https://{host}/{text.lstrip('./')}" + return "" + + +def extract_paths( + paths: Sequence[str], + *, + base_host: str = "", + keep_all_hosts: bool = False, + read=None, +) -> ExtractResult: + """Extract endpoints from local files and build analysable requests.""" + result = ExtractResult() + if not paths: + raise ExtractError("--extract needs at least one local file") + + texts: List[str] = [] + for path in paths: + if not os.path.exists(path): + raise ExtractError(f"cannot read '{path}': no such file") + if os.path.isdir(path): + raise ExtractError(f"'{path}' is a directory; pass files, not folders") + try: + size = os.path.getsize(path) + except OSError as exc: # pragma: no cover - filesystem edge + raise ExtractError(f"cannot stat '{path}': {exc.strerror or exc}") from exc + if size > MAX_FILE_BYTES: + result.skipped_files += 1 + result.warnings.append( + f"{path}: skipped ({size} bytes; limit {MAX_FILE_BYTES})" + ) + continue + payload = read(path) if read is not None else _read_file(path) + result.files_read += 1 + texts.append(payload) + found = extract_text(payload, path) + result.found.extend(found) + result.per_file[path] = len(found) + + hosts_all = origin_hosts(paths, texts) + # The app's own origin is the host with the most absolute references in the + # files, which in practice is the front-end itself; CDN, analytics and font + # hosts each appear once or twice. Adopting a lone third-party host as the + # origin would resolve relative paths onto somebody else's domain, so a + # clear winner is required. + counts: Dict[str, int] = {} + for text in texts: + for match in _ABS_URL_RE.finditer(text): + host_name = _origin_of(match.group(2)) + if host_name: + counts[host_name] = counts.get(host_name, 0) + 1 + primary = "" + if counts: + ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0])) + # A lone host is only trusted when it looks like the app itself rather + # than a CDN/analytics domain; otherwise a relative path would be + # silently resolved onto a third party. + if len(ranked) == 1: + if not _looks_like_third_party(ranked[0][0]): + primary = ranked[0][0] + elif ranked[0][1] > ranked[1][1]: + primary = ranked[0][0] + if not primary and not base_host: + result.warnings.append( + "no single application origin could be inferred from the files; " + "pass --extract-host (or --extract-all-hosts) to resolve relative paths" + ) + host = base_host or primary + # With no trusted origin there is nothing to resolve against and no basis + # for deciding which absolute hosts belong to the app, so only an explicit + # --extract-host (or --extract-all-hosts) produces output. Dropping them is + # the honest outcome: a guess here would misattribute someone's CDN. + allowed = {base_host} if base_host else ({primary} if primary else set()) + if not allowed and not keep_all_hosts: + result.warnings.append( + "refusing to guess the application origin; pass --extract-host HOST " + "for relative paths or --extract-all-hosts to keep every absolute URL" + ) + + seen: set = set() + for entry in result.found: + url = _to_url(entry.value, host) + if not url: + continue + if not keep_all_hosts: + host_of_url = _origin_of(url) + # An empty `allowed` set means "no trusted origin", not "anything + # goes": keep nothing that we cannot attribute to the app. + if host_of_url and host_of_url not in allowed: + continue + if url in seen: + continue + seen.add(url) + try: + request = request_from_url(url, SOURCE_FILE, f"{entry.file}:{entry.line}") + except URLParseError: + continue + result.requests.append(request) + if not result.requests: + result.warnings.append( + "no usable endpoints were extracted " + "(relative paths need an absolute URL in the same file for the origin)" + ) + return result + + +def _read_file(path: str) -> str: + try: + with open(path, "r", encoding="utf-8-sig", errors="replace") as handle: + return handle.read() + except OSError as exc: + raise ExtractError(f"cannot read '{path}': {exc.strerror or exc}") from exc + + +# --------------------------------------------------------------------------- +# rendering +# --------------------------------------------------------------------------- +def render_extract(result: ExtractResult, *, limit: int = 40) -> str: + """Summary of what was found, and where.""" + lines = ["PathScope extraction", "=" * 84] + lines.append(f"Files read : {result.files_read}") + if result.skipped_files: + lines.append(f"Files skipped : {result.skipped_files}") + lines.append(f"Endpoints found : {len(result.requests)}") + lines.append("") + for path, count in sorted(result.per_file.items()): + lines.append(f" {sanitize_text(path):<44} {count} string(s)") + by_kind: Dict[str, int] = {} + for entry in result.found: + by_kind[entry.kind] = by_kind.get(entry.kind, 0) + 1 + if by_kind: + lines.append("") + lines.append("By source") + for kind in sorted(by_kind): + lines.append(f" {kind:<16} {by_kind[kind]}") + if result.found: + lines.append("") + lines.append("First endpoints (file:line)") + for entry in result.found[:limit]: + lines.append( + f" {sanitize_text(entry.file)}:{entry.line} " + f"{sanitize_text(entry.value)[:90]}" + ) + if len(result.found) > limit: + lines.append(f" ... {len(result.found) - limit} more") + for warning in result.warnings: + lines.append(f"warning: {sanitize_text(warning)}") + lines.append("") + lines.append("Extraction is passive: the files are read locally and never fetched.") + return "\n".join(lines) + + +__all__ = [ + "ExtractError", + "ExtractResult", + "Extracted", + "MAX_FILE_BYTES", + "MAX_URLS_PER_FILE", + "extract_paths", + "extract_text", + "origin_hosts", + "render_extract", +] diff --git a/pathscope/families.py b/pathscope/families.py new file mode 100644 index 0000000..083e3eb --- /dev/null +++ b/pathscope/families.py @@ -0,0 +1,252 @@ +"""Path-family clustering (``--cluster``). + +Two hundred candidates is not two hundred decisions. Most of them are the same +parameter appearing on routes that differ only in an identifier: + + /api/v1/documents/8811/view?file=... + /api/v1/documents/9002/view?file=... + /api/v1/documents/1450/view?file=... + +That is **one** family, not three. Reviewer attention should be spent once per +shape of route, not once per row in a log. + +This module groups findings into families by a *route shape*: the resource path +with identifier-looking segments replaced by a placeholder, plus the parameter +name. Grouping is a **view**: it never rewrites findings, never merges +fingerprints and never changes what the ledger records. A review still applies +to one concrete fingerprint, so clustering cannot quietly accept endpoints +nobody looked at. + +No value is ever read here; only the resource path and the parameter name. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Dict, List, Sequence, Tuple +from urllib.parse import urlsplit + +from .detector import Finding +from .heuristics import canonical_name + +#: Placeholder written into a normalised route. +ID_PLACEHOLDER = "{id}" + +#: A segment that is an identifier rather than a word. +_ID_PATTERNS: Tuple[re.Pattern, ...] = ( + re.compile(r"^\d+$"), # 8811 + re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"), # uuid + re.compile(r"^[0-9a-f]{16,}$"), # long hex + re.compile(r"^[0-9a-f]{8,}-[0-9a-f-]+$"), # dashed id + re.compile(r"^v?\d+(\.\d+)?$"), # version-ish, kept out of route shape + re.compile(r"^[A-Za-z0-9_-]{20,}$"), # opaque token segment +) + + +@dataclass +class Family: + """One route shape plus the parameter candidates seen on it.""" + + key: str + host: str + route: str + parameter: str + members: List[Finding] = field(default_factory=list) + + @property + def count(self) -> int: + return len(self.members) + + @property + def location(self) -> str: + return self.best.location + + @property + def best(self) -> Finding: + return max(self.members, key=lambda f: (f.score, f.occurrences)) + + @property + def score(self) -> int: + return self.best.score + + @property + def confidence(self) -> str: + order = {"high": 0, "medium": 1, "low": 2} + return min( + (member.confidence for member in self.members), + key=lambda c: order.get(c, 3), + ) + + @property + def rules(self) -> List[str]: + seen: List[str] = [] + for member in self.members: + for rule in member.rules: + if rule not in seen: + seen.append(rule) + return seen + + @property + def resources(self) -> List[str]: + return sorted({member.resource for member in self.members}) + + @property + def occurrences(self) -> int: + return sum(member.occurrences for member in self.members) + + def as_dict(self) -> Dict[str, object]: + return { + "key": self.key, + "host": self.host, + "route": self.route, + "parameter": self.parameter, + "location": self.location, + "score": self.score, + "confidence": self.confidence, + "candidates": self.count, + "occurrences": self.occurrences, + "rules": self.rules, + "resources": self.resources, + "fingerprints": [member.fingerprint for member in self.members], + } + + +def _looks_like_identifier(segment: str) -> bool: + return any(pattern.match(segment) for pattern in _ID_PATTERNS) + + +def route_shape(path: str) -> str: + """Normalise one path into a route shape. + + ``/api/v1/documents/8811/view`` -> ``/api/v1/documents/{id}/view`` + + Version prefixes (``v1``, ``v2.1``) are **kept** on purpose: an upgrade is + a genuinely different surface and burying it would defeat the point. + """ + segments = [part for part in (path or "/").split("/") if part != ""] + shaped: List[str] = [] + previous = "" + for segment in segments: + if _looks_like_identifier(segment) and not _is_version(segment): + shaped.append(ID_PLACEHOLDER) + else: + shaped.append(segment) + previous = segment + del previous + return "/" + "/".join(shaped) if shaped else "/" + + +def _is_version(segment: str) -> bool: + return bool(re.match(r"^v\d+(\.\d+)?$", segment, re.IGNORECASE)) + + +def _path_of(resource: str) -> str: + """Extract the path component from a resource string (never the query).""" + if not resource: + return "/" + parts = urlsplit(resource) + if parts.scheme or parts.netloc: + return parts.path or "/" + # A bare path was given. + return resource.split("?", 1)[0] or "/" + + +def family_key(finding) -> str: + """The grouping key for one finding (or the key of an existing family). + + Accepting a :class:`Family` as well makes it possible to ask "would these + two clusters merge?" without reaching into internals. + """ + if isinstance(finding, Family): + return "\x1f".join( + ( + finding.host.lower(), + finding.route, + finding.location, + canonical_name(finding.parameter), + ) + ) + return "\x1f".join( + ( + finding.host.lower(), + route_shape(_path_of(finding.resource)), + finding.location, + canonical_name(finding.parameter), + ) + ) + + +def cluster(findings: Sequence[Finding]) -> List[Family]: + """Group findings into families, best-scoring family first.""" + grouped: Dict[str, Family] = {} + order: List[str] = [] + for finding in findings: + key = family_key(finding) + family = grouped.get(key) + if family is None: + family = Family( + key=key, + host=finding.host, + route=route_shape(_path_of(finding.resource)), + parameter=finding.parameter, + ) + grouped[key] = family + order.append(key) + family.members.append(finding) + families = [grouped[key] for key in order] + families.sort( + key=lambda fam: ( + -fam.score, + -fam.count, + fam.host, + fam.route, + canonical_name(fam.parameter), + ) + ) + return families + + +def render_clusters(families: Sequence[Family], total: int = 0) -> str: + """``--cluster`` as text: one line per family plus the collapse ratio.""" + lines = ["PathScope path families", "=" * 84] + if not families: + lines.append("No candidates to cluster.") + return "\n".join(lines) + + lines.append( + f"{total or sum(fam.count for fam in families)} candidate(s) collapsed " + f"into {len(families)} family/families." + ) + lines.append("") + lines.append(f" {'#':>3} {'score':>5} {'conf':<6} {'rows':>4} family") + for index, family in enumerate(families, start=1): + lines.append( + f" {index:>3} {family.score:>5} {family.confidence:<6} " + f"{family.count:>4} {family.host}{family.route} " + f"[{family.location}] {family.parameter}" + ) + lines.append("") + lines.append( + "A family is a view, not a merge: each row keeps its own fingerprint and " + "a review still covers one endpoint." + ) + lines.append( + "Review the family once, then decide the pattern -- not every row in it." + ) + return "\n".join(lines) + + +def as_dict(families: Sequence[Family]) -> List[Dict[str, object]]: + return [family.as_dict() for family in families] + + +__all__ = [ + "Family", + "ID_PLACEHOLDER", + "as_dict", + "cluster", + "family_key", + "render_clusters", + "route_shape", +] diff --git a/pathscope/heuristics.py b/pathscope/heuristics.py new file mode 100644 index 0000000..e30b298 --- /dev/null +++ b/pathscope/heuristics.py @@ -0,0 +1,740 @@ +"""Transparent, easy-to-edit heuristics for PathScope. + +Two independent signals are combined: + +``name`` + What the parameter is called (``file``, ``base_path``, ``template`` ...). + +``value`` + What the parameter *already* contains, treated purely as a string: + traversal segments, encoded slashes, absolute paths, Windows paths, + file extensions, and so on. + +Neither signal is a vulnerability test. They rank reading order. All tables +live at module level so a user can adjust them without touching logic. + +Scoring: every :class:`Evidence` carries a weight; the score is their sum, +clamped to ``0..100``. Default weights live in :mod:`pathscope.rules` so they +can be listed (``--list-rules``), overridden (``--rules``) and disabled +(``--disable-rule``). ``--explain`` prints the effective trace for one name. + +Names are matched after folding diacritics and compatibility characters, and +optionally against multilingual term packs plus leet spellings (``f1le``). +Values are additionally checked for shapes that *do not* look like paths +(UUIDs, hashes, JWTs, base64, e-mail, IPs, booleans/numbers) and demoted with +an explicit, visible negative rule. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Dict, FrozenSet, Iterable, List, Tuple + +from . import naming, valueshape +from .rules import ( + DEFAULT_BOOK, + GENERIC_BONUS, + MULTIWORD_BONUS, + PREFIX_DISCOUNT, + RULE_INDEX, + STRONG_NAME_WEIGHT, + SUFFIX_DISCOUNT, + RuleBook, +) +from .textutil import MAX_DECODE_PASSES, decode_forms, sanitize_text + +NAME_CAP = 45 +VALUE_CAP = 55 +MAX_SCORE = 100 + +#: Section headings used by ``--list-rules``/``--explain``. +SECTION_NAME = "name" +SECTION_VALUE = "value" +SECTION_DEMOTION = "demotion" + +# --------------------------------------------------------------------------- +# Parameter-name vocabulary +# --------------------------------------------------------------------------- +#: Exact tokens that strongly suggest a path-like consumer. +PATH_NAME_TERMS: FrozenSet[str] = frozenset( + """ + file filename filepath files document doc download upload attachment + archive export path dir directory folder root base basedir basepath uri + url link dest destination src resource asset media storage page + view layout theme tpl template include inc load action module plugin + script config conf settings log logfile + style css js data db database report render read open pathname fname + folderpath filepathname + """.split() +) + +#: Names that are only meaningful when the existing value is path-like. +GENERIC_NAME_TERMS: FrozenSet[str] = frozenset( + """ + image img photo avatar target ref referer referrer site key callback + filetarget + """.split() +) + +# --------------------------------------------------------------------------- +# Value indicators +# --------------------------------------------------------------------------- +#: Traversal must be a path *segment*: two dots bounded by separators or the +#: ends of the string. ``report..pdf`` or ``v1..2`` never match. +SEGMENT_TRAVERSAL_RE = re.compile(r"(?:^|[/\\])\.\.(?:[/\\]|$)") +#: A Windows drive path, e.g. ``C:\Windows`` or ``D:/data``. +WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[/\\]") +#: A UNC path, e.g. ``\\server\share``. +UNC_PATH_RE = re.compile(r"^\\\\[A-Za-z0-9._$-]+[\\/]") +#: A POSIX absolute path (but not a protocol-relative URL like ``//cdn``). +ABSOLUTE_PATH_RE = re.compile(r"^/(?!/)[A-Za-z0-9._~%-]") +#: Anything that parses as a full URL, e.g. ``https://`` or ``file://``. +FULL_URL_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://") + +#: Percent-encoded octet sequences worth naming in a reason. +ENCODED_MARKERS: Tuple[Tuple[str, str], ...] = ( + ("%2e%2e", "encoded-dotdot"), + ("%2f", "encoded-slash"), + ("%5c", "encoded-backslash"), + ("%00", "encoded-nul"), + ("%252e", "nested-encoded-dotdot"), +) + +#: Well-known file extensions. Extension-only evidence is weak (+8). +FILE_EXTENSIONS: FrozenSet[str] = frozenset( + """ + apk avi bak bash bat bin bmp bz2 c cgi conf config crt cs csr csv css db + dll doc docx dot drawio dtd env eot exe flac gif go gz h htm html ico ini + iso jar java jpeg jpg js json jsx key kt log md mkv mov mp3 mp4 msi odt + ogg otf pdf pem php phtml plist png ppt pptx ps1 py pyc rar rb rst sh so + sql svg swf tar tgz tif tiff toml ts tsx txt vhd wav webp woff woff2 xls + xlsx xml xsd yaml yml zip + """.split() +) +MULTI_EXTENSIONS: Tuple[str, ...] = ("tar.gz", "tar.bz2", "tar.xz", "tar.zst") + + +@dataclass(frozen=True) +class Evidence: + """One explainable reason a parameter was considered path-like.""" + + rule: str + reason: str + weight: int + layer: str # "name" or "value" + + def as_dict(self) -> Dict[str, object]: + return { + "rule": self.rule, + "layer": self.layer, + "weight": self.weight, + "reason": self.reason, + } + + +@dataclass +class Analysis: + """Aggregated evidence for one parameter identity.""" + + name: str + evidence: List[Evidence] = field(default_factory=list) + decoded_value: str = "" + decode_passes: int = 0 + + @property + def score(self) -> int: + return max(0, min(MAX_SCORE, sum(item.weight for item in self.evidence))) + + @property + def rules(self) -> List[str]: + return [item.rule for item in self.evidence] + + @property + def primary_rule(self) -> str: + return self.rules[0] if self.rules else "none" + + @property + def reasons(self) -> List[str]: + return [item.reason for item in self.evidence] + + @property + def confidence(self) -> str: + """Heuristic band. Never an exploitability judgement.""" + if self.score >= 70: + return "high" + if self.score >= 40: + return "medium" + return "low" + + +# --------------------------------------------------------------------------- +# Tokenisation +# --------------------------------------------------------------------------- +_CAMEL_SPLIT_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])") +_NON_ALNUM_RE = re.compile(r"[^A-Za-z0-9]+") +_DIGIT_SPLIT_RE = re.compile(r"(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])") + + +def tokenize_name(name: str, fold: bool = True) -> List[str]: + """Split a parameter name into lowercase ASCII tokens. + + ``fileName`` -> ``['file', 'name']`` + ``base_path`` -> ``['base', 'path']`` + ``X-File-Path`` -> ``['x', 'file', 'path']`` + ``fıle`` -> ``['file']`` (diacritics are folded first) + """ + if not name: + return [] + cleaned = sanitize_text(name).strip() + text = naming.fold_name(cleaned) if fold else cleaned + tokens: List[str] = [] + for chunk in _NON_ALNUM_RE.split(_CAMEL_SPLIT_RE.sub(" ", text)): + for piece in _DIGIT_SPLIT_RE.split(chunk): + if piece: + tokens.append(piece.lower()) + return tokens + + +def canonical_name(name: str) -> str: + """Stable, comparable form of a parameter name.""" + return "_".join(tokenize_name(name)) or sanitize_text(name).lower() + + +def extension_of(text: str) -> str: + """Return the file extension at the end of ``text`` (``""`` if none).""" + cleaned = text.strip().strip("\"'").rstrip(".,;:!?)]}") + last = re.split(r"[/\\]", cleaned)[-1].lower() + for multi in MULTI_EXTENSIONS: + if last.endswith("." + multi): + return multi + if "." not in last: + return "" + candidate = last.rsplit(".", 1)[1] + return candidate if candidate in FILE_EXTENSIONS else "" + + +# --------------------------------------------------------------------------- +# Name analysis +# --------------------------------------------------------------------------- +def _weight(book: RuleBook, rule: str) -> int: + """Effective weight for ``rule`` in ``book`` (0 when disabled).""" + return book.weight(rule) + + +def _books(book: RuleBook, rule: str, reason: str, layer: str) -> List[Evidence]: + """Build Evidence only when the rule is enabled and has a non-zero weight.""" + weight = _weight(book, rule) + if book.is_disabled(rule) or weight == 0: + return [] + if reason.endswith(")"): + # Replace the default "(+N)" tail with the effective weight so that an + # overridden rule is described accurately in every report. + reason = reason[: reason.rfind(" (")] + f" ({weight:+d})" + return [Evidence(rule, reason, weight, layer)] + + +def _weak_name_evidence(book: RuleBook) -> List[Evidence]: + return _books( + book, + "name-weak", + "multiword parameter name without a path term (weak, +5)", + "name", + ) + + +def _generic_name_evidence() -> List[Evidence]: + """Zero-weight context marker; kept even at weight 0 so pairing works.""" + weight = DEFAULT_BOOK.weight("name-generic") + return [ + Evidence( + "name-generic", + "parameter name is generic (image/target/ref/...): considered only " + "when its value is path-like (+0)", + weight, + "name", + ) + ] + + +def analyze_name( + name: str, + extra_terms: Iterable[str] = (), + weak_names: bool = True, + *, + book: RuleBook = DEFAULT_BOOK, + languages: Tuple[str, ...] = (), + fold: bool = True, +) -> List[Evidence]: + """Return name-based evidence. + + Rules (weights from ``book``): + ``name-custom`` exact user-configured term + ``name-exact`` exact built-in path term (+multiword bonus) + ``name-compound`` the whole name is a known compound + ``name-prefix`` name starts with a path term + ``name-suffix`` name ends with a path term + ``name-folded`` term appears only after diacritic/compatibility folding + ``name-leet`` term appears only after leet expansion (``f1le``) + ``name-i18n`` term from a non-English term pack + ``name-i18n-fold`` as above, only after folding + ``name-generic`` generic name (image/target/...), 0 (context only) + ``name-weak`` multiword name without a path term (never alone) + """ + if not name: + return [] + tokens = tokenize_name(name, fold=fold) + if not tokens: + return [] + joined = "".join(tokens) + + custom = {term.strip().lower().replace("-", "_") for term in extra_terms if term.strip()} + path_terms = PATH_NAME_TERMS | (custom - GENERIC_NAME_TERMS) + + # Configured terms may be single tokens ("blob") or compounds ("cdn_blob"). + canonical_names = {joined, sanitize_text(name).lower(), canonical_name(name)} + custom_candidates = [token for token in tokens if token in custom] + custom_candidates += [candidate for candidate in canonical_names if candidate in custom] + builtin_hit = any(token in PATH_NAME_TERMS for token in tokens) + if custom_candidates and not builtin_hit: + term = custom_candidates[0] + return _books( + book, + "name-custom", + f"parameter name contains configured term '{term}' (+30)", + "name", + ) + + hits = [token for token in tokens if token in path_terms] + if hits: + best = max(hits, key=len) + bonus = MULTIWORD_BONUS if len(tokens) > 1 else 0 + suffix = f", +{bonus} multiword" if bonus else "" + weight = _weight(book, "name-exact") + bonus + if book.is_disabled("name-exact"): + return [] + return [ + Evidence( + "name-exact", + f"parameter name contains path-related term '{best}' ({weight:+d}{suffix})", + weight, + "name", + ) + ] + + # A term can also hide in a folded or de-leeted spelling. + if fold: + folded_joined = "".join(tokenize_name(naming.fold_name(name))) + if folded_joined != joined: + folded_hits = [ + term for term in path_terms if len(term) >= 4 and term in folded_joined + ] + if folded_hits: + evidence = _books( + book, + "name-folded", + "parameter name matches a path term only after diacritic/" + f"compatibility folding ('{max(folded_hits, key=len)}') (+20)", + "name", + ) + if evidence: + return evidence + + leet_hits: List[str] = [] + leet_candidates = _NON_ALNUM_RE.split( + naming.fold_name(sanitize_text(name)).lower() + ) + for token in [item for item in leet_candidates if len(item) >= 3]: + for variant in naming.leet_variants(token): + found = [term for term in path_terms if len(term) >= 4 and term in variant] + if found: + leet_hits.append(max(found, key=len)) + break + if leet_hits: + break + if leet_hits: + evidence = _books( + book, + "name-leet", + f"parameter name matches path term '{leet_hits[0]}' only after leet " + "expansion (+12)", + "name", + ) + if evidence: + return evidence + + # Non-English term packs (German, Spanish, ...). A token that already + # exists in an English table (generic words like "image"/"document") is + # never re-labelled as foreign. + language_hits: List[Tuple[str, str, bool]] = [] + if languages: + packs = naming.language_terms(languages) + english_tokens = PATH_NAME_TERMS | GENERIC_NAME_TERMS + # ``sanitize_text`` already applies NFKC, which removes the accents + # that NFKD folding would normally strip. So a folded-only match is one + # that still needed folding *after* sanitisation (e.g. dotless "ı"). + # Join with the same rule tokenisation uses (ASCII punctuation only), + # so accented letters survive into ``plain_joined`` and a match there + # really means "no folding was needed". + sanitized = sanitize_text(name) + folded_joined = "".join(tokenize_name(naming.fold_name(sanitized))) + plain_joined = "".join(tokenize_name(sanitized, fold=False)) + for tag, terms in packs.items(): + for term in terms: + if len(term) < 4 or term in english_tokens: + continue + # Order matters: a spelling that needed folding is a weaker + # signal even though the folded tokens would also match. + if term in folded_joined and term not in plain_joined: + language_hits.append((tag, term, True)) + elif term in tokens or term in plain_joined: + language_hits.append((tag, term, False)) + if language_hits: + tag, term, folded = max(language_hits, key=lambda item: (len(item[1]), item[1])) + label = naming.LANGUAGE_LABELS.get(tag, tag) + if folded: + evidence = _books( + book, + "name-i18n-fold", + f"parameter name matches {label} path term '{term}' only after " + "folding (+21)", + "name", + ) + else: + evidence = _books( + book, + "name-i18n", + f"parameter name contains {label} path-related term '{term}' (+25)", + "name", + ) + if evidence: + return evidence + + if "_" not in joined and joined in path_terms and len(joined) > 4: + return _books( + book, + "name-compound", + f"parameter name '{joined}' is a known path compound (+35)", + "name", + ) + + # Prefix/suffix matching keeps only whole-word boundaries so that + # "urlencoded" is not read as "url" and "landscape" is not read as "page". + prefix_match = "" + suffix_match = "" + for term in sorted(path_terms, key=len, reverse=True): + if len(term) < 4: + continue + if joined.startswith(term) and len(joined) > len(term): + prefix_match = term + break + if joined.endswith(term) and len(joined) > len(term): + suffix_match = term + break + if prefix_match: + weight = _weight(book, "name-prefix") + if not book.is_disabled("name-prefix") and weight: + return [ + Evidence( + "name-prefix", + f"parameter name starts with path-related term '{prefix_match}' " + f"({weight:+d})", + weight, + "name", + ) + ] + if suffix_match: + weight = _weight(book, "name-suffix") + if not book.is_disabled("name-suffix") and weight: + return [ + Evidence( + "name-suffix", + f"parameter name ends with path-related term '{suffix_match}' " + f"({weight:+d})", + weight, + "name", + ) + ] + + if any(token in GENERIC_NAME_TERMS for token in tokens): + if book.is_disabled("name-generic"): + return [] + return _generic_name_evidence() + + if len(tokens) > 1 and weak_names: + return _weak_name_evidence(book) + return [] + + +# --------------------------------------------------------------------------- +# Value analysis +# --------------------------------------------------------------------------- +def _is_segment_traversal(text: str) -> bool: + return bool(SEGMENT_TRAVERSAL_RE.search(text)) + + +def _value_evidence( + book: RuleBook, rule: str, reason: str, default_weight: int +) -> List[Evidence]: + """Value-layer evidence with the effective weight (and disabled check).""" + if book.is_disabled(rule): + return [] + weight = book.weight(rule) + if weight == 0: + return [] + if reason.endswith(")"): + reason = reason[: reason.rfind(" (")] + f" ({weight:+d})" + return [Evidence(rule, reason, weight, "value")] + + +def analyze_value( + value: str, + max_decode_passes: int = MAX_DECODE_PASSES, + *, + book: RuleBook = DEFAULT_BOOK, + demote: bool = True, +) -> List[Evidence]: + """Return value-based evidence. The value is treated purely as a string. + + Rules: + ``value-traversal`` ``..`` used as a path segment, +30 + ``value-encoded-traversal`` ``..`` only visible after decoding, +15 + ``value-encoded-slash`` ``%2f``/``%5c`` present, +12 + ``value-double-encoded`` two or more decoding passes needed, +10 + ``value-windows-drive`` ``C:\\`` or ``D:/`` prefix, +15 + ``value-unc`` ``\\\\server\\share`` prefix, +15 + ``value-absolute`` starts with ``/`` (but not ``//``), +12 + ``value-multi-segment`` 2+ path separators, +6 + ``value-extension`` known file extension at the end, +8 + ``value-path-list`` semicolon/comma separated paths, +5 + ``value-full-url`` an ``scheme://`` URL, -10 + ``value-demote-*`` UUID/hash/JWT/base64/e-mail/IP/scalar, negative + """ + raw = sanitize_text(value or "") + if not raw: + return [] + + lowered_raw = raw.lower() + forms = decode_forms(raw, max_decode_passes) + deepest = forms[-1][1] + max_pass = forms[-1][0] + evidence: List[Evidence] = [] + + if any(marker in lowered_raw for marker, _name in ENCODED_MARKERS): + evidence.append( + Evidence( + "value-encoded", + "value contains percent-encoded octets (informational, +0)", + 0, + "value", + ) + ) + if "%2f" in lowered_raw or "%5c" in lowered_raw: + evidence.extend( + _value_evidence( + book, + "value-encoded-slash", + "value contains an encoded slash or backslash (%2f / %5c) (+12)", + 12, + ) + ) + if max_pass >= 2: + evidence.extend( + _value_evidence( + book, + "value-double-encoded", + f"value required {max_pass} decoding passes (nested encoding) (+10)", + 10, + ) + ) + + if _is_segment_traversal(raw): + evidence.extend( + _value_evidence( + book, + "value-traversal", + "value contains a '..' path segment ('../', '..\\' or bare '..') (+30)", + 30, + ) + ) + shape = raw + elif _is_segment_traversal(deepest): + evidence.extend( + _value_evidence( + book, + "value-encoded-traversal", + "value contains a '..' segment only after percent-decoding (+15)", + 15, + ) + ) + shape = deepest + else: + shape = deepest + + if WINDOWS_DRIVE_RE.match(shape): + evidence.extend( + _value_evidence( + book, + "value-windows-drive", + "value looks like a Windows drive path ('C:\\...') (+15)", + 15, + ) + ) + elif UNC_PATH_RE.match(shape): + evidence.extend( + _value_evidence( + book, + "value-unc", + "value looks like a Windows UNC path ('\\\\server\\share') (+15)", + 15, + ) + ) + elif ABSOLUTE_PATH_RE.match(shape): + evidence.extend( + _value_evidence( + book, + "value-absolute", + "value starts with a path separator (absolute-looking) (+12)", + 12, + ) + ) + + if FULL_URL_RE.match(shape): + evidence.extend( + _value_evidence( + book, + "value-full-url", + "value is a full URL rather than a local path (-10)", + -10, + ) + ) + else: + # A trailing separator right after ".." ("../etc/passwd") is part of the + # traversal evidence, so it is not counted a second time here. + separators = shape.count("/") + shape.count("\\") + if _is_segment_traversal(shape): + separators = max(0, separators - 1) + if separators >= 2: + evidence.extend( + _value_evidence( + book, + "value-multi-segment", + f"value contains {separators} path separators (+6)", + 6, + ) + ) + extension = extension_of(shape) + if extension: + evidence.extend( + _value_evidence( + book, + "value-extension", + f"value ends with a file-like extension '.{extension}' (+8)", + 8, + ) + ) + if separators and any(sep in shape for sep in (";", ",")): + evidence.extend( + _value_evidence( + book, + "value-path-list", + "value looks like a semicolon/comma separated list of paths (+5)", + 5, + ) + ) + + if demote: + evidence.extend(demotion_evidence(raw, book)) + + # Percent-encoding alone is not a path signal; drop the placeholder so the + # evidence list only contains scoring rules. + return [item for item in evidence if item.weight != 0] + + +def demotion_evidence(value: str, book: RuleBook = DEFAULT_BOOK) -> List[Evidence]: + """Negative evidence for value shapes that do not look like paths.""" + evidence: List[Evidence] = [] + for rule, reason in valueshape.demotions(sanitize_text(value)): + if book.is_disabled(rule): + continue + weight = book.weight(rule) + if weight == 0: + continue + if weight > 0: # a positive override would invert the rule's meaning + weight = -weight + reason = reason[: reason.rfind(" (")] + f" ({weight:+d})" if reason.endswith(")") else reason + evidence.append(Evidence(rule, reason, weight, "value")) + return evidence + + +# --------------------------------------------------------------------------- +# Combine +# --------------------------------------------------------------------------- +def analyze_parameter( + name: str, + value: str, + *, + max_decode_passes: int = MAX_DECODE_PASSES, + extra_terms: Iterable[str] = (), + ignore: Iterable[str] = (), + min_score: int = 25, + weak_names: bool = True, + book: RuleBook = DEFAULT_BOOK, + languages: Tuple[str, ...] = (), + fold: bool = True, + demote: bool = True, +) -> Analysis: + """Combine name and value evidence for one parameter. + + Returns an :class:`Analysis` whose ``evidence`` is empty when the + parameter is not a candidate. Generic names only score through their + value; strong names can score on their own. + """ + if canonical_name(name) in {canonical_name(item) for item in ignore}: + return Analysis(name=name) + + name_evidence = analyze_name( + name, + extra_terms, + weak_names=weak_names, + book=book, + languages=languages, + fold=fold, + ) + value_evidence = analyze_value(value, max_decode_passes, book=book, demote=demote) + + generic = any(item.rule == "name-generic" for item in name_evidence) + has_path_value = any(item.weight > 0 for item in value_evidence) + + if generic: + name_evidence = [] # generic names never contribute on their own + if not has_path_value: + return Analysis(name=name) + + evidence: List[Evidence] = list(name_evidence) + list(value_evidence) + if generic and has_path_value and not book.is_disabled("value-pairs-with-generic-name"): + pairing_weight = book.weight("value-pairs-with-generic-name") + if pairing_weight: + evidence.append( + Evidence( + "value-pairs-with-generic-name", + "generic parameter name is paired with a path-like value " + f"({pairing_weight:+d})", + pairing_weight, + "value", + ) + ) + + analysis = Analysis(name=name, evidence=evidence) + if analysis.score < max(1, min_score): + return Analysis(name=name) + + decoded_value = value or "" + passes = 0 + if value: + forms = decode_forms(sanitize_text(value), max_decode_passes) + decoded_value = forms[-1][1] + passes = forms[-1][0] + analysis.decoded_value = decoded_value + analysis.decode_passes = passes + return analysis diff --git a/pathscope/history.py b/pathscope/history.py new file mode 100644 index 0000000..2813a4c --- /dev/null +++ b/pathscope/history.py @@ -0,0 +1,285 @@ +"""Run history and trend analysis (``--history FILE`` / ``--trend``). + +A history file is an append-only JSON document. Each run adds one compact +record: counts, the effective settings, and one entry per reported finding +(fingerprint, host, parameter, rule, score). No values are stored, ever. + +Trend analysis answers questions a single run cannot: + +* Is the finding count growing or shrinking? +* Which parameters are new, which are stable, which disappeared? +* Did a parameter's score drift between runs? +* When was something first and last seen? +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +from . import __version__ +from .detector import Report + +#: History format version, bumped when the record shape changes. +HISTORY_VERSION = 1 +#: Hard cap so a long-lived history file cannot grow without bound. +MAX_RUNS = 2000 + +JSON_INDENT = 2 + + +class HistoryError(ValueError): + """Raised when a history file is unreadable or malformed.""" + + +# --------------------------------------------------------------------------- +# Reading and writing +# --------------------------------------------------------------------------- +def empty_history() -> Dict[str, object]: + return { + "tool": "PathScope", + "history_version": HISTORY_VERSION, + "runs": [], + } + + +def load_history(path: str) -> Dict[str, object]: + """Read a history file, returning an empty history when it does not exist.""" + if not os.path.exists(path): + return empty_history() + try: + with open(path, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except OSError as exc: + raise HistoryError(f"cannot read history '{path}': {exc.strerror or exc}") from exc + except json.JSONDecodeError as exc: + raise HistoryError( + f"history '{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + if not isinstance(payload, dict): + raise HistoryError(f"history '{path}' must be a JSON object") + runs = payload.get("runs") + if runs is None: + payload["runs"] = [] + elif not isinstance(runs, list): + raise HistoryError(f"history '{path}': 'runs' must be an array") + payload.setdefault("history_version", HISTORY_VERSION) + payload.setdefault("tool", "PathScope") + return payload + + +def run_record(report: Report, *, label: str = "", settings: Optional[Dict] = None) -> Dict: + """Build one history entry from a finished report (never stores values).""" + return { + "tool_version": __version__, + "label": label, + "settings": dict(settings or {}), + "requests": report.requests_analyzed, + "parameters": report.parameters_analyzed, + "candidates": report.candidate_count, + "bands": dict(report.confidence_counts), + "mode": report.mode, + "baseline": report.baseline_source, + "rules_source": report.rules_source, + "findings": [ + { + "fingerprint": finding.fingerprint, + "host": finding.host, + "parameter": finding.parameter, + "location": finding.location, + "rule": finding.rule, + "score": finding.score, + "confidence": finding.confidence, + "status": finding.status, + } + for finding in report.findings + ], + } + + +def append_run(path: str, record: Dict) -> Dict[str, object]: + """Append ``record`` to ``path`` and return the updated history.""" + history = load_history(path) + runs = list(history.get("runs") or []) + runs.append(record) + if len(runs) > MAX_RUNS: + runs = runs[-MAX_RUNS:] + history["runs"] = runs + history["tool"] = "PathScope" + history["history_version"] = HISTORY_VERSION + write_history(path, history) + return history + + +def write_history(path: str, history: Dict[str, object]) -> None: + """Write a history document atomically enough for local use.""" + directory = os.path.dirname(os.path.abspath(path)) + if directory and not os.path.isdir(directory): + raise HistoryError(f"cannot write history '{path}': no such directory") + try: + with open(path, "w", encoding="utf-8", newline="\n") as handle: + json.dump(history, handle, indent=JSON_INDENT) + handle.write("\n") + except OSError as exc: + raise HistoryError(f"cannot write history '{path}': {exc.strerror or exc}") from exc + + +# --------------------------------------------------------------------------- +# Trend analysis +# --------------------------------------------------------------------------- +@dataclass +class ParameterTrend: + """One parameter's life across runs.""" + + fingerprint: str + host: str + parameter: str + rule: str + first_run: int + last_run: int + runs_seen: int = 0 + scores: List[int] = field(default_factory=list) + + @property + def drift(self) -> int: + """Score change between the first and last appearance.""" + if len(self.scores) < 2: + return 0 + return self.scores[-1] - self.scores[0] + + @property + def active(self) -> bool: + """True when the parameter appeared in the most recent run.""" + return self.last_run == self.runs_seen # compared with total runs below + + +@dataclass +class Trend: + """Aggregate trend over a history file.""" + + runs: int = 0 + counts: List[int] = field(default_factory=list) + new_per_run: List[int] = field(default_factory=list) + resolved_per_run: List[int] = field(default_factory=list) + parameters: Dict[str, ParameterTrend] = field(default_factory=dict) + latest_new: List[str] = field(default_factory=list) + latest_resolved: List[str] = field(default_factory=list) + busiest_hosts: List[Tuple[str, int]] = field(default_factory=list) + + def as_dict(self) -> Dict[str, object]: + return { + "runs": self.runs, + "counts": list(self.counts), + "new_per_run": list(self.new_per_run), + "resolved_per_run": list(self.resolved_per_run), + "parameters": [ + { + "fingerprint": trend.fingerprint, + "host": trend.host, + "parameter": trend.parameter, + "rule": trend.rule, + "first_run": trend.first_run, + "last_run": trend.last_run, + "runs_seen": trend.runs_seen, + "scores": list(trend.scores), + "drift": trend.drift, + } + for trend in self.parameters.values() + ], + "latest_new": list(self.latest_new), + "latest_resolved": list(self.latest_resolved), + "busiest_hosts": [{"host": h, "count": c} for h, c in self.busiest_hosts], + } + + +def analyze_history(history: Dict[str, object]) -> Trend: + """Compute a :class:`Trend` from a history document.""" + runs = [run for run in (history.get("runs") or []) if isinstance(run, dict)] + view = Trend(runs=len(runs)) + seen_before: set = set() + host_totals: Dict[str, int] = {} + + for index, run in enumerate(runs, start=1): + findings = [f for f in (run.get("findings") or []) if isinstance(f, dict)] + view.counts.append(int(run.get("candidates", len(findings)) or 0)) + current = {str(f.get("fingerprint", "")): f for f in findings} + new = [fp for fp in current if fp and fp not in seen_before] + resolved = [fp for fp in seen_before if fp and fp not in current] + view.new_per_run.append(len(new)) + view.resolved_per_run.append(len(resolved)) + + for fingerprint, finding in current.items(): + if not fingerprint: + continue + entry = view.parameters.get(fingerprint) + if entry is None: + entry = ParameterTrend( + fingerprint=fingerprint, + host=str(finding.get("host", "")), + parameter=str(finding.get("parameter", "")), + rule=str(finding.get("rule", "")), + first_run=index, + last_run=index, + ) + view.parameters[fingerprint] = entry + entry.last_run = index + entry.runs_seen += 1 + try: + entry.scores.append(int(finding.get("score", 0))) + except (TypeError, ValueError): + entry.scores.append(0) + host = str(finding.get("host", "")) + host_totals[host] = host_totals.get(host, 0) + 1 + + if index == len(runs): + view.latest_new = sorted(current[fp].get("parameter", "") for fp in new if fp in current) + view.latest_resolved = _describe_resolved(runs[: index - 1], resolved) + + seen_before |= set(current) + + view.busiest_hosts = sorted(host_totals.items(), key=lambda item: (-item[1], item[0]))[:10] + return view + + +def _describe_resolved(previous_runs: Sequence[Dict], fingerprints: Sequence[str]) -> List[str]: + """Look up parameter names for fingerprints that disappeared.""" + wanted = set(fingerprints) + names: List[str] = [] + for run in reversed(previous_runs): + for finding in run.get("findings") or []: + if isinstance(finding, dict) and finding.get("fingerprint") in wanted: + names.append(str(finding.get("parameter", ""))) + wanted.discard(finding.get("fingerprint")) + if not wanted: + break + return sorted(name for name in names if name) + + +def sparkline(values: Sequence[int]) -> str: + """Unicode sparkline for a series of counts (empty string for no data).""" + if not values: + return "" + bars = "▁▂▃▄▅▆▇█" + low, high = min(values), max(values) + if high == low: + return bars[0] * len(values) + step = (high - low) / (len(bars) - 1) + return "".join(bars[int(round((value - low) / step))] for value in values) + + +__all__ = [ + "HISTORY_VERSION", + "MAX_RUNS", + "HistoryError", + "ParameterTrend", + "Trend", + "analyze_history", + "append_run", + "empty_history", + "load_history", + "run_record", + "sparkline", + "write_history", +] diff --git a/pathscope/impact.py b/pathscope/impact.py new file mode 100644 index 0000000..28aa150 --- /dev/null +++ b/pathscope/impact.py @@ -0,0 +1,217 @@ +"""Rule impact (``--rule-impact``). + +``--rule-coverage`` answers "did this rule fire at all?". That is a +participation trophy: a rule can fire on 300 findings and contribute nothing to +whether any of them are reported, and another can fire on 12 and be the entire +reason those 12 exist. + +Impact measures the second thing. For every rule it reports: + +* **appearances** -- findings the rule is part of; +* **deciding** -- findings where removing this rule would drop the finding below + the reporting threshold. That is the rule's actual contribution; +* **points** -- total weight this rule added across the corpus; +* **share** -- its share of all added points. + +The distinction matters because the registry has both kinds. A positive rule +adds evidence; a demotion rule subtracts it, so its "impact" is negative and it +can *cause* a finding to disappear. Both are reported in the same table with +their sign, because pretending demotions have no effect is how a rule book +becomes folklore. + +Nothing here changes scoring. It is arithmetic over evidence already recorded. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List + +from .detector import Report +from .rules import DEMOTION_PREFIX + + +@dataclass +class RuleImpact: + """Contribution of one rule to a report.""" + + rule: str + appearances: int = 0 + deciding: int = 0 + points: int = 0 + weight: int = 0 + #: Findings where this rule is the highest-weight positive contributor. + leading: int = 0 + + @property + def is_demotion(self) -> bool: + return self.rule.startswith(DEMOTION_PREFIX) + + @property + def mean_points(self) -> float: + return self.points / self.appearances if self.appearances else 0.0 + + def as_dict(self) -> Dict[str, object]: + return { + "rule": self.rule, + "weight": self.weight, + "appearances": self.appearances, + "deciding": self.deciding, + "leading": self.leading, + "points": self.points, + "mean_points": round(self.mean_points, 2), + "demotion": self.is_demotion, + } + + +@dataclass +class ImpactReport: + """Impact across every rule in one report.""" + + rules: Dict[str, RuleImpact] = field(default_factory=dict) + findings: int = 0 + total_points: int = 0 + + @property + def positive_total(self) -> int: + return sum(item.points for item in self.rules.values() if item.points > 0) + + def ranked(self) -> List[RuleImpact]: + """Largest absolute contribution first.""" + return sorted( + self.rules.values(), + key=lambda item: (-abs(item.points), -item.deciding, item.rule), + ) + + def deciding_rules(self) -> List[RuleImpact]: + return [item for item in self.ranked() if item.deciding] + + def silent_rules(self) -> List[RuleImpact]: + return [item for item in self.ranked() if not item.appearances] + + def as_dict(self) -> Dict[str, object]: + return { + "findings": self.findings, + "total_points": self.total_points, + "positive_points": self.positive_total, + "rules": [item.as_dict() for item in self.ranked()], + } + + +def rule_impact(report: Report, book=None) -> ImpactReport: + """Compute per-rule impact for ``report``. + + ``book`` supplies effective weights; without it the weights recorded on the + report are used, falling back to zero for unknown rules. + """ + weights: Dict[str, int] = {} + if book is not None: + weights = book.as_dict() + elif getattr(report, "rules", None): + weights = dict(report.rules) + + result = ImpactReport(findings=len(report.findings)) + threshold = report.min_score + for finding in report.findings: + rules = list(finding.rules or []) + for rule in rules: + entry = result.rules.get(rule) + if entry is None: + entry = RuleImpact(rule=rule, weight=weights.get(rule, 0)) + result.rules[rule] = entry + entry.appearances += 1 + # A demotion already carries a negative weight; do not re-sign it. + entry.points += entry.weight + result.total_points += entry.weight + # Deciding = this rule being gone would drop the finding under the + # threshold. Computed from the rule's own weight, not its share. + if finding.score - entry.weight < threshold <= finding.score: + entry.deciding += 1 + positive = [ + rule for rule in rules if weights.get(rule, 0) > 0 + ] + if positive: + leader = max(positive, key=lambda rule: weights.get(rule, 0)) + entry = result.rules.get(leader) + if entry is not None: + entry.leading += 1 + return result + + +def render_impact(report: ImpactReport, threshold: int = 0) -> str: + """``--rule-impact`` as text.""" + lines = ["PathScope rule impact", "=" * 84] + if not report.rules: + lines.append("No rules fired on this input: nothing to measure.") + return "\n".join(lines) + + lines.append( + f"{report.findings} finding(s); " + f"{report.positive_total} positive point(s) contributed in total." + ) + lines.append( + f"'deciding' counts findings that would fall below the threshold " + f"({threshold}) without this rule. 'leading' counts findings where it is " + "the strongest positive rule." + ) + lines.append("") + lines.append( + f" {'rule':<28} {'weight':>6} {'seen':>5} {'leading':>7} " + f"{'deciding':>8} {'points':>7} share" + ) + positive_total = report.positive_total or 1 + for entry in report.ranked(): + share = ( + f"{entry.points / positive_total:>6.1%}" + if entry.points > 0 + else " -" + ) + marker = " (demotion)" if entry.is_demotion else "" + lines.append( + f" {entry.rule:<28} {entry.weight:>6} {entry.appearances:>5} " + f"{entry.leading:>7} {entry.deciding:>8} {entry.points:>7} {share}{marker}" + ) + lines.append("") + + deciders = report.deciding_rules() + if deciders: + lines.append( + "Rules that actually decide what you see: " + + ", ".join(entry.rule for entry in deciders[:8]) + + (" ..." if len(deciders) > 8 else "") + + "." + ) + lines.append("") + chatter = [ + entry + for entry in report.ranked() + if entry.appearances >= 20 and not entry.deciding and entry.weight > 0 + ] + if chatter: + lines.append( + "Rules that add points without deciding anything on this corpus: " + + ", ".join(entry.rule for entry in chatter[:8]) + + ". They may still matter at a different threshold." + ) + lines.append("") + demotions = [entry for entry in report.ranked() if entry.is_demotion and entry.appearances] + if demotions: + suppressed = sum(entry.points for entry in demotions) + lines.append( + f"Demotions removed {abs(suppressed)} point(s) across " + f"{sum(entry.appearances for entry in demotions)} appearance(s)." + ) + lines.append("") + lines.append( + "Impact is arithmetic over recorded evidence. Use --simulate to test a " + "weight change before making one." + ) + return "\n".join(lines) + + +__all__ = [ + "ImpactReport", + "RuleImpact", + "render_impact", + "rule_impact", +] diff --git a/pathscope/ledger.py b/pathscope/ledger.py new file mode 100644 index 0000000..6d19583 --- /dev/null +++ b/pathscope/ledger.py @@ -0,0 +1,620 @@ +"""Review ledger backed by SQLite (``--ledger FILE``). + +The flat JSON ledgers from 2.1 answer "is this fingerprint reviewed?". A team +eventually needs more: *who* reviewed it, *why*, *when*, and what changed +afterwards. This module stores that in a single local SQLite database using the +standard library's :mod:`sqlite3` module. + +Schema + ``reviews`` one row per reviewed fingerprint: status, reviewer, note, + timestamps, first/last score, host, parameter, rule. + ``events`` append-only audit trail: every state change with its actor + and note, so history is never lost. + +Nothing here leaves the machine, and no parameter value is ever stored. +""" + +from __future__ import annotations + +import calendar +import os +import re +import sqlite3 +import time +from dataclasses import dataclass +from typing import Dict, Iterable, List, Optional + +from .detector import Finding + +SCHEMA_VERSION = 2 + +#: Review statuses accepted on the command line. +STATUS_REVIEWED = "reviewed" +STATUS_ACCEPTED = "accepted" # reviewed and accepted as-is (risk decision) +STATUS_FALSE_POSITIVE = "false-positive" +STATUS_RESOLVED = "resolved" +STATUSES = (STATUS_REVIEWED, STATUS_ACCEPTED, STATUS_FALSE_POSITIVE, STATUS_RESOLVED) + +#: Statuses that count as "known" for a baseline. +KNOWN_STATUSES = frozenset(STATUSES) + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS reviews ( + fingerprint TEXT PRIMARY KEY, + status TEXT NOT NULL, + host TEXT NOT NULL DEFAULT '', + parameter TEXT NOT NULL DEFAULT '', + leaf TEXT NOT NULL DEFAULT '', + location TEXT NOT NULL DEFAULT '', + rule TEXT NOT NULL DEFAULT '', + score INTEGER NOT NULL DEFAULT 0, + reviewer TEXT NOT NULL DEFAULT '', + owner TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + expires_at TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS reviews_host ON reviews(host); +CREATE INDEX IF NOT EXISTS reviews_status ON reviews(status); +CREATE INDEX IF NOT EXISTS reviews_parameter ON reviews(parameter); +CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + fingerprint TEXT NOT NULL, + action TEXT NOT NULL, + status TEXT NOT NULL, + reviewer TEXT NOT NULL DEFAULT '', + note TEXT NOT NULL DEFAULT '', + at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS events_fingerprint ON events(fingerprint); +""" + + +class LedgerError(RuntimeError): + """Raised when the ledger cannot be opened, written or queried.""" + + +def _now() -> str: + """UTC timestamp, second precision (deterministic enough for an audit log).""" + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + + +#: Accepted ``--ledger-expire`` grammars: ``30d``, ``12h``, ``90m``, ``2w``, ``none``. +_EXPIRE_PATTERN = re.compile(r"^(\d+)\s*([smhdw])$", re.IGNORECASE) +_EXPIRE_UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} + + +def parse_expiry(spec: str, *, now: Optional[str] = None) -> str: + """Turn ``30d`` (or ``none``) into an absolute UTC timestamp. + + Returns an empty string for ``none``/``never``, meaning the review does not + expire. Raises :class:`LedgerError` for anything else, so a typo never + silently creates a review that lives forever. + """ + text = (spec or "").strip().lower() + if text in ("", "none", "never", "no", "off"): + return "" + match = _EXPIRE_PATTERN.match(text) + if not match: + raise LedgerError( + f"invalid expiry '{spec}': use Ns/Nm/Nh/Nd/Nw (e.g. 30d) or 'none'" + ) + amount = int(match.group(1)) + unit = match.group(2).lower() + seconds = amount * _EXPIRE_UNITS[unit] + base = _ts_to_epoch(now or _now()) + return _epoch_to_ts(base + seconds) + + +def _ts_to_epoch(stamp: str) -> float: + """Parse ``YYYY-MM-DDTHH:MM:SSZ`` (or a bare date) to epoch seconds.""" + text = (stamp or "").strip() + if not text: + return time.time() + for fmt in ("%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d"): + try: + return calendar.timegm(time.strptime(text[:19] if "%S" in fmt else text, fmt)) + except ValueError: + continue + raise LedgerError(f"invalid timestamp '{stamp}'") + + +def _epoch_to_ts(epoch: float) -> str: + return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(epoch)) + + +def days_until(stamp: str, now: Optional[str] = None) -> Optional[int]: + """Whole days from ``now`` to ``stamp``; ``None`` for an empty stamp.""" + if not stamp: + return None + delta = _ts_to_epoch(stamp) - _ts_to_epoch(now or _now()) + # Floor toward zero so "5 days away" never reads as "6". + days = int(delta // 86400) if delta >= 0 else -int((-delta + 86399) // 86400) + return days + + +@dataclass +class Review: + """One reviewed fingerprint.""" + + fingerprint: str + status: str + host: str = "" + parameter: str = "" + leaf: str = "" + location: str = "" + rule: str = "" + score: int = 0 + reviewer: str = "" + owner: str = "" + note: str = "" + #: ISO-8601 UTC date/time after which this review is stale. Empty = never. + expires_at: str = "" + created_at: str = "" + updated_at: str = "" + + def is_expired(self, now: Optional[str] = None) -> bool: + """True when the review carried an expiry that has now passed.""" + if not self.expires_at: + return False + return self.expires_at <= (now or _now()) + + def expires_in_days(self, now: Optional[str] = None) -> Optional[int]: + """Whole days until expiry (negative when overdue), or ``None``.""" + remaining = days_until(self.expires_at, now) + return remaining + + +#: Columns added after schema 1, with the SQL used to backfill them. +_MIGRATIONS = ( + ("reviews", "owner", "ALTER TABLE reviews ADD COLUMN owner TEXT NOT NULL DEFAULT ''"), + ("reviews", "expires_at", "ALTER TABLE reviews ADD COLUMN expires_at TEXT NOT NULL DEFAULT ''"), +) + + +def _columns(connection: sqlite3.Connection, table: str) -> set: + return { + row[1] + for row in connection.execute(f"PRAGMA table_info({table})").fetchall() + } + + +def _migrate(connection: sqlite3.Connection) -> None: + """Bring a ledger written by an older PathScope up to the current schema. + + Old ledgers keep working: missing columns are added with neutral defaults + (no owner, no expiry), so nothing suddenly becomes stale. + """ + existing = _columns(connection, "reviews") + if not existing: # pragma: no cover - schema just created it + return + for table, column, statement in _MIGRATIONS: + if table == "reviews" and column not in existing: + connection.execute(statement) + version = connection.execute( + "SELECT value FROM meta WHERE key = 'schema_version'" + ).fetchone() + if version is not None and str(version[0]) != str(SCHEMA_VERSION): + connection.execute( + "UPDATE meta SET value = ? WHERE key = 'schema_version'", + (str(SCHEMA_VERSION),), + ) + + +class Ledger: + """A local SQLite review ledger.""" + + def __init__(self, path: str) -> None: + self.path = path + self._connection: Optional[sqlite3.Connection] = None + + # -- lifecycle -------------------------------------------------------- + def connect(self) -> sqlite3.Connection: + if self._connection is not None: + return self._connection + try: + connection = sqlite3.connect(self.path, timeout=5.0) + except sqlite3.Error as exc: # pragma: no cover - filesystem edge + raise LedgerError(f"cannot open ledger '{self.path}': {exc}") from exc + connection.row_factory = sqlite3.Row + try: + connection.executescript(SCHEMA) + _migrate(connection) + connection.execute( + "INSERT OR IGNORE INTO meta(key, value) VALUES('schema_version', ?)", + (str(SCHEMA_VERSION),), + ) + connection.execute( + "INSERT OR IGNORE INTO meta(key, value) VALUES('tool', 'PathScope')", + (), + ) + connection.commit() + except sqlite3.Error as exc: + raise LedgerError(f"cannot initialise ledger '{self.path}': {exc}") from exc + self._connection = connection + return connection + + def close(self) -> None: + if self._connection is not None: + self._connection.close() + self._connection = None + + def __enter__(self) -> "Ledger": + self.connect() + return self + + def __exit__(self, *_exc) -> None: + self.close() + + # -- writes ----------------------------------------------------------- + def record( + self, + fingerprint: str, + *, + status: str = STATUS_REVIEWED, + host: str = "", + parameter: str = "", + location: str = "", + rule: str = "", + score: int = 0, + reviewer: str = "", + owner: str = "", + note: str = "", + expire: str = "", + action: str = "marked", + ) -> Review: + """Insert or update one review and append an audit event. + + ``expire`` accepts ``30d``-style durations (see :func:`parse_expiry`); + an existing expiry is kept unless a new one is given. + """ + if status not in STATUSES: + raise LedgerError( + f"unknown status '{status}' (choose from {', '.join(STATUSES)})" + ) + if not fingerprint: + raise LedgerError("fingerprint must not be empty") + connection = self.connect() + now = _now() + expires_at = parse_expiry(expire, now=now) if expire else "" + try: + existing = connection.execute( + "SELECT * FROM reviews WHERE fingerprint = ?", (fingerprint,) + ).fetchone() + if existing is None: + connection.execute( + "INSERT INTO reviews(fingerprint, status, host, parameter, leaf," + " location, rule, score, reviewer, owner, note, expires_at," + " created_at, updated_at)" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + ( + fingerprint, status, host, parameter, parameter.lower(), + location, rule, int(score), reviewer, owner, note, + expires_at, now, now, + ), + ) + action = "marked" + else: + connection.execute( + "UPDATE reviews SET status=?, host=COALESCE(NULLIF(?, ''), host)," + " parameter=COALESCE(NULLIF(?, ''), parameter)," + " leaf=COALESCE(NULLIF(?, ''), leaf)," + " location=COALESCE(NULLIF(?, ''), location)," + " rule=COALESCE(NULLIF(?, ''), rule)," + " score=?, reviewer=COALESCE(NULLIF(?, ''), reviewer)," + " owner=COALESCE(NULLIF(?, ''), owner)," + " note=?, expires_at=COALESCE(NULLIF(?, ''), expires_at)," + " updated_at=? WHERE fingerprint=?", + ( + status, host, parameter, parameter.lower(), location, rule, + int(score), reviewer, owner, note, expires_at, now, + fingerprint, + ), + ) + connection.execute( + "INSERT INTO events(fingerprint, action, status, reviewer, note, at)" + " VALUES(?,?,?,?,?,?)", + (fingerprint, action, status, reviewer, note, now), + ) + connection.commit() + except sqlite3.Error as exc: + raise LedgerError(f"cannot write ledger '{self.path}': {exc}") from exc + stored = self.get(fingerprint) + assert stored is not None # just written + return stored + + def record_findings( + self, + findings: Iterable[Finding], + *, + status: str = STATUS_REVIEWED, + reviewer: str = "", + owner: str = "", + note: str = "", + expire: str = "", + ) -> int: + """Mark every finding as reviewed. Returns the number of rows written.""" + count = 0 + for finding in findings: + self.record( + finding.fingerprint, + status=status, + host=finding.host, + parameter=finding.parameter, + location=finding.location, + rule=finding.rule, + score=finding.score, + reviewer=reviewer, + owner=owner, + note=note, + expire=expire, + ) + count += 1 + return count + + def forget(self, fingerprint: str, *, reviewer: str = "", note: str = "") -> bool: + """Remove one review (an audit event is still recorded).""" + connection = self.connect() + try: + cursor = connection.execute( + "DELETE FROM reviews WHERE fingerprint = ?", (fingerprint,) + ) + if cursor.rowcount: + connection.execute( + "INSERT INTO events(fingerprint, action, status, reviewer, note, at)" + " VALUES(?,?,?,?,?,?)", + (fingerprint, "forgot", "", reviewer, note, _now()), + ) + connection.commit() + return bool(cursor.rowcount) + except sqlite3.Error as exc: + raise LedgerError(f"cannot write ledger '{self.path}': {exc}") from exc + + # -- reads ------------------------------------------------------------ + def get(self, fingerprint: str) -> Optional[Review]: + connection = self.connect() + row = connection.execute( + "SELECT * FROM reviews WHERE fingerprint = ?", (fingerprint,) + ).fetchone() + return _row_to_review(row) if row else None + + def all_reviews(self) -> List[Review]: + connection = self.connect() + rows = connection.execute( + "SELECT * FROM reviews ORDER BY updated_at DESC, fingerprint" + ).fetchall() + return [_row_to_review(row) for row in rows] + + def find( + self, + *, + host: str = "", + parameter: str = "", + status: str = "", + rule: str = "", + reviewer: str = "", + ) -> List[Review]: + """Filter reviews by any combination of columns (literal matches).""" + clauses: List[str] = [] + values: List[str] = [] + for column, value in ( + ("host", host), + ("parameter", parameter), + ("status", status), + ("rule", rule), + ("reviewer", reviewer), + ): + if value: + clauses.append(f"{column} = ?") + values.append(value) + query = "SELECT * FROM reviews" + if clauses: + query += " WHERE " + " AND ".join(clauses) + query += " ORDER BY updated_at DESC, fingerprint" + connection = self.connect() + return [_row_to_review(row) for row in connection.execute(query, values)] + + def fingerprints(self) -> set: + """All reviewed fingerprints, for baseline/suppression use.""" + connection = self.connect() + return { + row[0] + for row in connection.execute("SELECT fingerprint FROM reviews").fetchall() + } + + def stale(self, *, now: Optional[str] = None) -> List[Review]: + """Reviews carrying an expiry that has passed, soonest first.""" + moment = now or _now() + expired = [ + review + for review in self.all_reviews() + if review.expires_at and review.expires_at <= moment + ] + expired.sort(key=lambda review: (review.expires_at, review.fingerprint)) + return expired + + def expiring_soon(self, days: int = 7, *, now: Optional[str] = None) -> List[Review]: + """Reviews expiring within ``days`` (excluding those already stale).""" + moment = now or _now() + horizon = _epoch_to_ts(_ts_to_epoch(moment) + max(0, days) * 86400) + upcoming = [ + review + for review in self.all_reviews() + if review.expires_at and moment < review.expires_at <= horizon + ] + upcoming.sort(key=lambda review: (review.expires_at, review.fingerprint)) + return upcoming + + def clear_expiry(self, fingerprint: str, *, reviewer: str = "") -> bool: + """Make one review permanent again (audited as ``extended``).""" + connection = self.connect() + try: + cursor = connection.execute( + "UPDATE reviews SET expires_at = '', updated_at = ?" + " WHERE fingerprint = ? AND expires_at != ''", + (_now(), fingerprint), + ) + if cursor.rowcount: + connection.execute( + "INSERT INTO events(fingerprint, action, status, reviewer, note, at)" + " VALUES(?,?,?,?,?,?)", + (fingerprint, "extended", "no-expiry", reviewer, "", _now()), + ) + connection.commit() + return bool(cursor.rowcount) + except sqlite3.Error as exc: + raise LedgerError(f"cannot write ledger '{self.path}': {exc}") from exc + + def notes(self) -> Dict[str, str]: + """Fingerprint -> note map, for the ``--show-known`` Status column.""" + connection = self.connect() + return { + row["fingerprint"]: row["note"] or row["status"] + for row in connection.execute( + "SELECT fingerprint, note, status FROM reviews" + ).fetchall() + } + + def events(self, fingerprint: str = "", limit: int = 50) -> List[Dict[str, object]]: + """Audit trail, newest last (or newest first when limited).""" + connection = self.connect() + if fingerprint: + rows = connection.execute( + "SELECT * FROM events WHERE fingerprint = ? ORDER BY id DESC LIMIT ?", + (fingerprint, max(1, int(limit))), + ).fetchall() + else: + rows = connection.execute( + "SELECT * FROM events ORDER BY id DESC LIMIT ?", (max(1, int(limit)),) + ).fetchall() + return [dict(row) for row in rows] + + def stats(self, *, now: Optional[str] = None) -> Dict[str, object]: + """Counts per status, first/last activity, and how many reviews are stale.""" + connection = self.connect() + by_status = { + row["status"]: row["count"] + for row in connection.execute( + "SELECT status, COUNT(*) AS count FROM reviews GROUP BY status" + ).fetchall() + } + total = connection.execute("SELECT COUNT(*) FROM reviews").fetchone()[0] + events = connection.execute("SELECT COUNT(*) FROM events").fetchone()[0] + first = connection.execute( + "SELECT MIN(created_at) FROM reviews" + ).fetchone()[0] or "" + last = connection.execute( + "SELECT MAX(updated_at) FROM reviews" + ).fetchone()[0] or "" + reviewers = [ + row[0] + for row in connection.execute( + "SELECT DISTINCT reviewer FROM reviews WHERE reviewer != ''" + " ORDER BY reviewer" + ).fetchall() + ] + moment = now or _now() + stale = connection.execute( + "SELECT COUNT(*) FROM reviews WHERE expires_at != '' AND expires_at <= ?", + (moment,), + ).fetchone()[0] + with_expiry = connection.execute( + "SELECT COUNT(*) FROM reviews WHERE expires_at != ''" + ).fetchone()[0] + return { + "total": total, + "by_status": by_status, + "events": events, + "first": first, + "last": last, + "reviewers": reviewers, + "with_expiry": with_expiry, + "stale": stale, + } + + # -- interoperability ------------------------------------------------ + def to_baseline_payload(self) -> Dict[str, object]: + """Export as a ``--baseline``/``--suppress`` compatible document.""" + return { + "tool": "PathScope", + "source": "ledger", + "suppressions": [ + {"fingerprint": review.fingerprint, "note": review.note or review.status} + for review in self.all_reviews() + ], + } + + def import_json_ledger(self, payload: object, *, reviewer: str = "") -> int: + """Import the flat ``{"suppressions": [...]}`` format from 2.1.""" + entries = payload.get("suppressions") if isinstance(payload, dict) else None + if not isinstance(entries, list): + raise LedgerError("expected a JSON object with a 'suppressions' array") + count = 0 + for entry in entries: + if not isinstance(entry, dict): + continue + fingerprint = entry.get("fingerprint") + if not isinstance(fingerprint, str) or not fingerprint: + continue + note = entry.get("note") + self.record( + fingerprint, + host=str(entry.get("host", "")), + parameter=str(entry.get("parameter", "")), + rule=str(entry.get("rule", "")), + score=int(entry.get("score", 0) or 0), + reviewer=reviewer, + note=note if isinstance(note, str) else "", + action="imported", + ) + count += 1 + return count + + +def _row_to_review(row: sqlite3.Row) -> Review: + return Review( + fingerprint=row["fingerprint"], + status=row["status"], + host=row["host"], + parameter=row["parameter"], + leaf=row["leaf"], + location=row["location"], + rule=row["rule"], + score=row["score"], + reviewer=row["reviewer"], + owner=row["owner"] if "owner" in row.keys() else "", + note=row["note"], + expires_at=row["expires_at"] if "expires_at" in row.keys() else "", + created_at=row["created_at"], + updated_at=row["updated_at"], + ) + + +def open_ledger(path: str) -> Ledger: + """Open (and initialise) a ledger, translating errors to :class:`LedgerError`.""" + directory = os.path.dirname(os.path.abspath(path)) + if directory and not os.path.isdir(directory): + raise LedgerError(f"cannot open ledger '{path}': no such directory") + ledger = Ledger(path) + ledger.connect() + return ledger + + +__all__ = [ + "KNOWN_STATUSES", + "SCHEMA_VERSION", + "STATUSES", + "STATUS_ACCEPTED", + "STATUS_FALSE_POSITIVE", + "STATUS_RESOLVED", + "STATUS_REVIEWED", + "Ledger", + "LedgerError", + "Review", + "open_ledger", +] diff --git a/pathscope/ledgermerge.py b/pathscope/ledgermerge.py new file mode 100644 index 0000000..bf6f0ae --- /dev/null +++ b/pathscope/ledgermerge.py @@ -0,0 +1,235 @@ +"""Ledger merge (``--ledger-merge OTHER --ledger INTO``). + +Two people review the same application, each with their own local ledger. Both +decisions are real. Merging them is not a copy: it is a **conflict** problem, +and the one thing a merge tool must never do is resolve a disagreement silently. + +Rules, each chosen because the alternative is worse: + +* **Same fingerprint, same status** -- keep the later ``updated_at``. Nothing + was in dispute. +* **Same fingerprint, different status** -- a **conflict**. The default keeps + the newer decision and *reports both*, so a human can look. ``--merge-prefer`` + makes the rule explicit instead of implicit. +* **Only in one ledger** -- carried over untouched, including owner, expiry and + the audit trail. +* **Audit events are never rewritten** -- the merge appends to the destination + ledger's event log, so "alice accepted this on the 3rd" survives a merge that + prefers bob's later decision. + +A dry run is the default. Writing requires ``--merge-apply``, because a merge +that runs by accident is unrecoverable. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List + +from .ledger import Ledger, Review + + +class MergeError(RuntimeError): + """Raised when a merge cannot be performed.""" + + +@dataclass +class Conflict: + """One fingerprint on which two ledgers disagree.""" + + fingerprint: str + left: Review + right: Review + winner: str = "right" + + def describe(self) -> str: + return ( + f"{self.fingerprint}: {self.left.status}@{self.left.updated_at} " + f"vs {self.right.status}@{self.right.updated_at} -> keeping {self.winner}" + ) + + def as_dict(self) -> Dict[str, object]: + return { + "fingerprint": self.fingerprint, + "left": { + "status": self.left.status, + "updated_at": self.left.updated_at, + "reviewer": self.left.reviewer, + }, + "right": { + "status": self.right.status, + "updated_at": self.right.updated_at, + "reviewer": self.right.reviewer, + }, + "winner": self.winner, + } + + +@dataclass +class MergeResult: + """What a merge would do (or did).""" + + left_path: str = "" + right_path: str = "" + added: int = 0 + updated: int = 0 + unchanged: int = 0 + conflicts: List[Conflict] = field(default_factory=list) + applied: bool = False + prefer: str = "newer" + + @property + def total_left(self) -> int: + return self.added + self.updated + self.unchanged + len(self.conflicts) + + def as_dict(self) -> Dict[str, object]: + return { + "left": self.left_path, + "right": self.right_path, + "applied": self.applied, + "prefer": self.prefer, + "added": self.added, + "updated": self.updated, + "unchanged": self.unchanged, + "conflicts": [conflict.as_dict() for conflict in self.conflicts], + } + + +def _newer(left: Review, right: Review) -> str: + return "right" if (right.updated_at or "") >= (left.updated_at or "") else "left" + + +def plan( + left: Ledger, + right: Ledger, + *, + prefer: str = "newer", +) -> MergeResult: + """Work out what merging ``right`` into ``left`` would change.""" + if prefer not in ("newer", "left", "right"): + raise MergeError("--merge-prefer must be 'newer', 'left' or 'right'") + result = MergeResult( + left_path=left.path, right_path=right.path, prefer=prefer + ) + left_reviews = {review.fingerprint: review for review in left.all_reviews()} + right_reviews = {review.fingerprint: review for review in right.all_reviews()} + + for fingerprint, incoming in right_reviews.items(): + current = left_reviews.get(fingerprint) + if current is None: + result.added += 1 + continue + if current.status == incoming.status: + result.unchanged += 1 + continue + # A genuine disagreement about the same endpoint. + if prefer == "newer": + winner = _newer(current, incoming) + else: + winner = prefer + result.conflicts.append( + Conflict( + fingerprint=fingerprint, + left=current, + right=incoming, + winner=winner, + ) + ) + result.conflicts.sort(key=lambda conflict: conflict.fingerprint) + return result + + +def apply_merge( + left: Ledger, + right: Ledger, + result: MergeResult, +) -> MergeResult: + """Write the planned merge into ``left`` and return the result. + + Every write goes through :meth:`Ledger.record`, so the destination keeps a + complete audit trail of the merge itself -- a merge is a change to the + record and is recorded like one. + """ + left_reviews = {review.fingerprint: review for review in left.all_reviews()} + right_reviews = {review.fingerprint: review for review in right.all_reviews()} + conflicts = {conflict.fingerprint: conflict for conflict in result.conflicts} + written = 0 + for fingerprint, incoming in right_reviews.items(): + current = left_reviews.get(fingerprint) + conflict = conflicts.get(fingerprint) + if conflict is not None and conflict.winner == "left": + continue + if conflict is None and current is not None: + continue + # Deliberately not carrying expires_at: an expiry belongs to the + # decision that set it. Carrying a stale date across a merge would + # silently expire somebody else's fresh acceptance, or revive one. + left.record( + fingerprint, + status=incoming.status, + host=incoming.host, + parameter=incoming.parameter, + location=incoming.location, + rule=incoming.rule, + score=incoming.score, + reviewer=incoming.reviewer, + owner=incoming.owner, + note=incoming.note, + action="merged", + ) + written += 1 + result.applied = True + return result + + +def render_merge(result: MergeResult) -> str: + """Text view of a merge plan or result.""" + lines = ["PathScope ledger merge", "=" * 84] + lines.append(f"into : {result.left_path}") + lines.append(f"from : {result.right_path}") + lines.append(f"prefer: {result.prefer}") + lines.append("") + lines.append(f" added : {result.added}") + lines.append(f" unchanged : {result.unchanged}") + lines.append(f" conflicts : {len(result.conflicts)}") + lines.append("") + if result.conflicts: + lines.append("Conflicts (both decisions are shown; nothing is hidden)") + for conflict in result.conflicts: + lines.append(f" {conflict.describe()}") + lines.append( + f" left {conflict.left.status:<15} by " + f"{conflict.left.reviewer or '?'} at {conflict.left.updated_at}" + ) + lines.append( + f" right {conflict.right.status:<15} by " + f"{conflict.right.reviewer or '?'} at {conflict.right.updated_at}" + ) + lines.append("") + lines.append( + "A conflict is two humans disagreeing about the same endpoint. " + "Resolve it by reviewing the finding again, not by re-running the merge." + ) + lines.append("") + if result.applied: + lines.append( + f"Applied. {result.added + len(result.conflicts)} row(s) written to " + f"{result.left_path}; the destination audit trail records each one as " + "'merged'." + ) + else: + lines.append( + "Dry run: nothing was written. Re-run with --merge-apply to write, " + "or --merge-json for a machine-readable plan." + ) + return "\n".join(lines) + + +__all__ = [ + "Conflict", + "MergeError", + "MergeResult", + "apply_merge", + "plan", + "render_merge", +] diff --git a/pathscope/naming.py b/pathscope/naming.py new file mode 100644 index 0000000..be5ed5c --- /dev/null +++ b/pathscope/naming.py @@ -0,0 +1,296 @@ +"""Name folding and multilingual path terminology. + +Two independent additions to the name layer: + +**Folding** (:func:`fold_name`, :func:`leet_variants`) + ``fıle`` (dotless i), ``file`` (fullwidth), ``f1le`` and ``f_i_l_e`` all + denote ``file``. Folding is applied *before* tokenisation so the existing + term tables keep working unchanged. Folded matches are reported with their + own weaker rules, so a leet spelling never looks as strong as a plain one. + +**Term packs** (:data:`LANGUAGE_PACKS`) + Path-related vocabulary for German, Spanish, French, Portuguese, Italian + and Dutch. ``--name-lang de,es`` enables a list, ``auto`` uses all packs, + ``off`` (default) uses English only. + +Everything here is a literal lookup table. No regular expressions are built +from user input, and nothing is network-aware. +""" + +from __future__ import annotations + +import unicodedata +from typing import Dict, FrozenSet, List, Sequence, Tuple + +#: Languages with a built-in term pack, in display order. +LANGUAGE_NAMES: Tuple[str, ...] = ("de", "es", "fr", "pt", "it", "nl") + +LANGUAGE_LABELS: Dict[str, str] = { + "de": "German", + "es": "Spanish", + "fr": "French", + "pt": "Portuguese", + "it": "Italian", + "nl": "Dutch", +} + +#: ``--name-lang`` selectors. +NAME_LANG_OFF = "off" +NAME_LANG_AUTO = "auto" +NAME_LANG_ALL = "all" + +#: Path-related terms per language. Deliberately small, high-signal lists: +#: words that commonly name a file/path consumer in that language. +LANGUAGE_PACKS: Dict[str, FrozenSet[str]] = { + "de": frozenset( + """ + datei dateipfad pfad ordner verzeichnis herunterladen hochladen + anhang bild dokument speichern laden oeffnen oeffne quelle ziel + vorlage seite verwenden + """.split() + ), + "es": frozenset( + """ + archivo ruta carpeta directorio descargar subir adjunto documento + imagen guardar cargar abrir origen destino plantilla pagina recurso + indice + """.split() + ), + "fr": frozenset( + """ + fichier chemin dossier repertoire telecharger televerser piece jointe + document image enregistrer charger ouvrir source cible modele page + ressource + """.split() + ), + "pt": frozenset( + """ + arquivo caminho pasta diretorio baixar carregar enviar anexo documento + imagem salvar abrir origem destino modelo pagina recurso + """.split() + ), + "it": frozenset( + """ + percorso cartella scaricare caricare allegato documento immagine + salvare aprire origine destinazione modello pagina risorsa + """.split() + ), + "nl": frozenset( + """ + bestand pad map downloaden uploaden bijlage afbeelding opslaan laden + openen bron doel sjabloon pagina bronbestand + """.split() + ), +} + +#: Aliases accepted on the command line for each pack. +LANGUAGE_ALIASES: Dict[str, str] = { + "german": "de", + "deutsch": "de", + "spanish": "es", + "espanol": "es", + "español": "es", + "french": "fr", + "francais": "fr", + "français": "fr", + "portuguese": "pt", + "portugues": "pt", + "português": "pt", + "italian": "it", + "italiano": "it", + "dutch": "nl", + "nederlands": "nl", + "english": "en", + "en": "en", +} + +#: Leet substitutions used for the *weak* folded rule. Each mapping is applied +#: one at a time to the whole token; only tokens of 3+ characters are folded so +#: that short identifiers (``id1``) are not mangled into false positives. +LEET_MAP: Dict[str, Tuple[str, ...]] = { + "1": ("l", "i"), + "0": ("o",), + "3": ("e",), + "4": ("a",), + "5": ("s",), + "7": ("t",), + "@": ("a",), + "$": ("s",), +} + +#: Bound so a pathological token cannot explode into thousands of variants. +MAX_LEET_VARIANTS = 48 + +#: Characters that are folded to an ASCII equivalent before tokenisation. +_DIACRITIC_FOLD = { + "ı": "i", + "ß": "ss", + "ø": "o", + "đ": "d", + "ð": "d", + "ł": "l", + "æ": "ae", + "œ": "oe", + "þ": "th", + "ħ": "h", + "ŧ": "t", + "ĸ": "k", +} + +#: Characters that are treated as separators when they appear in a name. +_SEPARATOR_FOLD = { + "\u2010": "-", # hyphen + "\u2011": "-", + "\u2012": "-", + "\u2013": "-", + "\u2014": "-", + "\u2212": "-", + "\uff0d": "-", + "\u2044": "/", +} + +#: Zero-width and bidi control characters that are stripped outright. +_INVISIBLE = frozenset( + "\u200b\u200c\u200d\u2060\ufeff\u00ad" + "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069" +) + + +def fold_name(name: str) -> str: + """Return an ASCII-folded copy of ``name`` suitable for tokenisation. + + Handles compatibility forms (fullwidth letters), accent stripping, + Turkish dotless i, common ligatures, exotic separators and invisible + characters. The result is a plain string; it is never executed or opened. + """ + if not name: + return "" + # NFKC folds fullwidth/halfwidth forms and compatibility characters. + text = unicodedata.normalize("NFKC", name) + out: List[str] = [] + for char in text: + if char in _INVISIBLE: + continue + if char in _SEPARATOR_FOLD: + out.append(_SEPARATOR_FOLD[char]) + continue + lowered = char.lower() + if lowered in _DIACRITIC_FOLD: + out.append(_DIACRITIC_FOLD[lowered]) + continue + decomposed = unicodedata.normalize("NFKD", char) + out.append("".join(ch for ch in decomposed if not unicodedata.combining(ch))) + # Remove stray combining marks left by decomposition of unusual sequences. + result = unicodedata.normalize("NFKD", "".join(out)) + return "".join(ch for ch in result if not unicodedata.combining(ch)) + + +def leet_variants(token: str) -> List[str]: + """Return de-leeted spellings of ``token`` (``f1le`` -> ``file``). + + Deterministic and bounded: each digit is expanded once, in order, and the + result is truncated to :data:`MAX_LEET_VARIANTS`. + """ + if len(token) < 3: + return [] + variants: List[str] = [] + frontier = [token] + for index, char in enumerate(token): + replacements = LEET_MAP.get(char) + if not replacements: + continue + next_frontier: List[str] = [] + for base in frontier: + for replacement in replacements: + candidate = base[:index] + replacement + base[index + 1 :] + next_frontier.append(candidate) + if len(next_frontier) >= MAX_LEET_VARIANTS: + break + if len(next_frontier) >= MAX_LEET_VARIANTS: + break + frontier = next_frontier + for candidate in frontier: + if candidate != token and candidate not in variants: + variants.append(candidate) + return variants + + +def language_terms(languages: Sequence[str]) -> Dict[str, FrozenSet[str]]: + """Return ``{tag: terms}`` for the requested language tags. + + Unknown tags are ignored; ``auto``/``all`` expand to every pack. + """ + wanted: List[str] = [] + for entry in languages: + for piece in str(entry).replace(";", ",").split(","): + key = piece.strip().lower() + if not key: + continue + key = LANGUAGE_ALIASES.get(key, key) + if key in (NAME_LANG_AUTO, NAME_LANG_ALL): + wanted.extend(LANGUAGE_NAMES) + elif key in LANGUAGE_PACKS: + wanted.append(key) + ordered = [tag for tag in LANGUAGE_NAMES if tag in set(wanted)] + return {tag: LANGUAGE_PACKS[tag] for tag in ordered} + + +def parse_languages(value: str) -> Tuple[str, ...]: + """Parse a ``--name-lang`` value into normalized tags. + + ``"off"`` and empty strings return ``()``; ``auto``/``all`` return every + pack. Unknown tags raise :class:`ValueError` so a typo is visible. + """ + if not value or not value.strip(): + return () + tokens = [ + token.strip().lower() + for token in str(value).replace(";", ",").split(",") + if token.strip() + ] + result: List[str] = [] + for token in tokens: + canonical = LANGUAGE_ALIASES.get(token, token) + if canonical in (NAME_LANG_OFF, "none", "english-only"): + continue + if canonical in (NAME_LANG_AUTO, NAME_LANG_ALL): + for tag in LANGUAGE_NAMES: + if tag not in result: + result.append(tag) + continue + if canonical not in LANGUAGE_PACKS: + raise ValueError( + f"unknown language '{token}' (choose from " + f"{', '.join(LANGUAGE_NAMES)} or auto/off)" + ) + if canonical not in result: + result.append(canonical) + return tuple(result) + + +def describe_languages() -> Tuple[str, ...]: + """Lines describing the term packs, used in ``--help`` and the README.""" + lines: List[str] = [] + for tag in LANGUAGE_NAMES: + sample = ", ".join(sorted(LANGUAGE_PACKS[tag])[:6]) + lines.append(f" {tag:<3} {LANGUAGE_LABELS[tag]:<11} {sample} ...") + lines.append(f" {NAME_LANG_AUTO:<11} every pack above") + return tuple(lines) + + +__all__ = [ + "LANGUAGE_NAMES", + "LANGUAGE_LABELS", + "LANGUAGE_PACKS", + "LANGUAGE_ALIASES", + "LEET_MAP", + "NAME_LANG_AUTO", + "NAME_LANG_ALL", + "NAME_LANG_OFF", + "MAX_LEET_VARIANTS", + "describe_languages", + "fold_name", + "language_terms", + "leet_variants", + "parse_languages", +] diff --git a/pathscope/openapi.py b/pathscope/openapi.py new file mode 100644 index 0000000..fe1bdaf --- /dev/null +++ b/pathscope/openapi.py @@ -0,0 +1,487 @@ +"""Local API description matching (``--openapi SPEC.json``). + +Most teams already have a description of their API: an OpenAPI or Swagger +document, committed next to the code. Comparing a PathScope report against it +answers a question no amount of scoring can: + +* which analysed endpoints are **not described** by the spec, and +* which described parameters the spec **does not declare**. + +An endpoint nobody documented is where undocumented behaviour lives; a +parameter the spec forgot is what the code actually reads anyway. Both are +review prompts, not findings. + +Only **JSON** documents are read, and the file is read from disk and never +fetched. A YAML document is reported as such rather than half-parsed: a +partial parse of an API description would produce confident nonsense, which is +worse than refusing. + +Supported: OpenAPI 3.x (``paths`` -> ``parameters`` + ``requestBody``) and +Swagger 2.0 (``paths`` -> ``parameters`` + ``in: body``). Path templating uses +``{name}`` and matches any single segment. Server/base paths are applied before +matching, so ``servers: [{url: "https://api.test/v1"}]`` and a route +``/documents/{id}`` match ``https://api.test/v1/documents/8811``. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Set, Tuple +from urllib.parse import urlsplit + +from .detector import Finding +from .heuristics import canonical_name + +#: Cap so a generated spec cannot exhaust memory. +MAX_PATHS = 20000 +MAX_SPEC_BYTES = 32 * 1024 * 1024 + + +class SpecError(ValueError): + """Raised when a specification cannot be read or is not usable.""" + + +@dataclass(frozen=True) +class Operation: + """One described path+method pair.""" + + path: str + method: str + parameters: Tuple[str, ...] = () + summary: str = "" + + @property + def signature(self) -> str: + return f"{self.method.upper()} {self.path}" + + +@dataclass +class Spec: + """A parsed API description: base URLs plus operations.""" + + title: str = "" + version: str = "" + kind: str = "openapi" + bases: List[str] = field(default_factory=list) + operations: List[Operation] = field(default_factory=list) + source: str = "" + + @property + def described_parameters(self) -> Set[str]: + names: Set[str] = set() + for operation in self.operations: + for parameter in operation.parameters: + names.add(canonical_name(parameter)) + return names + + +# --------------------------------------------------------------------------- +# parsing +# --------------------------------------------------------------------------- +def _strip_version(path: str) -> str: + return (path or "").strip().rstrip("/") or "/" + + +def _join_base(base: str, path: str) -> str: + """Combine a server/base URL with a documented path.""" + base_path = urlsplit(base).path if base else "" + base_path = _strip_version(base_path) + path = _strip_version(path) + if base_path in ("", "/"): + return path + return _strip_version(base_path.rstrip("/") + "/" + path.lstrip("/")) + + +def _loads(raw: str, source: str) -> Dict[str, object]: + stripped = raw.lstrip("\ufeff \t\r\n") + if not stripped: + raise SpecError(f"spec file '{source}' is empty") + if stripped[0] not in "{[": + if re.search(r"^\s*(openapi|swagger)\s*:", stripped, re.MULTILINE): + raise SpecError( + f"spec file '{source}' looks like YAML. PathScope reads JSON " + "specs only, because a partial YAML parse of an API description " + "produces confident nonsense. Convert it first, e.g. " + "`python3 -c \"import json,sys;print(json.dumps(...))\"` or keep a " + "JSON export in the repository." + ) + raise SpecError(f"spec file '{source}' is not JSON") + try: + payload = json.loads(stripped) + except json.JSONDecodeError as exc: + raise SpecError( + f"spec file '{source}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + if not isinstance(payload, dict): + raise SpecError(f"spec file '{source}' must contain a JSON object") + return payload + + +def _parameter_names(entries: object) -> Tuple[str, ...]: + names: List[str] = [] + if not isinstance(entries, list): + return () + for entry in entries: + if not isinstance(entry, dict): + continue + name = entry.get("name") + if isinstance(name, str) and name and name not in names: + names.append(name) + return tuple(names) + + +def _body_parameters(operation: Dict[str, object]) -> Tuple[str, ...]: + """Parameter names a request body declares (one level deep).""" + names: List[str] = [] + + def consume(schema: object) -> None: + if not isinstance(schema, dict): + return + properties = schema.get("properties") + if isinstance(properties, dict): + for key in properties: + if isinstance(key, str) and key not in names: + names.append(key) + + request_body = operation.get("requestBody") + if isinstance(request_body, dict): + content = request_body.get("content") + if isinstance(content, dict): + for media in content.values(): + if isinstance(media, dict): + consume(media.get("schema")) + # Swagger 2: in: body with a schema + for entry in operation.get("parameters") or []: + if isinstance(entry, dict) and entry.get("in") == "body": + consume(entry.get("schema")) + return tuple(names) + + +def parse_spec(payload: Dict[str, object], source: str = "") -> Spec: + """Build a :class:`Spec` from a decoded JSON document.""" + if not isinstance(payload, dict): + raise SpecError("a spec document must be a JSON object") + if "openapi" in payload: + kind = "openapi" + info = payload.get("info") if isinstance(payload.get("info"), dict) else {} + bases = [] + servers = payload.get("servers") + if isinstance(servers, list): + for server in servers: + if isinstance(server, dict) and isinstance(server.get("url"), str): + bases.append(server["url"]) + elif "swagger" in payload: + kind = "swagger" + info = payload.get("info") if isinstance(payload.get("info"), dict) else {} + bases = [] + host = payload.get("host") + base_path = payload.get("basePath") or "/" + scheme = "https" + schemes = payload.get("schemes") + if isinstance(schemes, list) and schemes and isinstance(schemes[0], str): + scheme = schemes[0] + if isinstance(host, str) and host: + bases.append(f"{scheme}://{host}{base_path}") + else: + bases.append(str(base_path)) + else: + raise SpecError( + "the document is JSON but declares neither 'openapi' nor 'swagger'; " + "PathScope needs one to know what it is reading" + ) + + paths = payload.get("paths") + if not isinstance(paths, dict): + raise SpecError("the spec has no 'paths' object") + if len(paths) > MAX_PATHS: + raise SpecError(f"the spec describes {len(paths)} paths (limit {MAX_PATHS})") + + operations: List[Operation] = [] + for path, item in paths.items(): + if not isinstance(item, dict): + continue + # Path-level parameters apply to every operation under that path. + shared = _parameter_names(item.get("parameters")) + for method, operation in item.items(): + if method.lower() not in ( + "get", "put", "post", "delete", "options", "head", "patch", "trace" + ): + continue + if not isinstance(operation, dict): + continue + names: List[str] = list(shared) + for name in _parameter_names(operation.get("parameters")): + if name not in names: + names.append(name) + for name in _body_parameters(operation): + if name not in names: + names.append(name) + summary = operation.get("summary") + operations.append( + Operation( + path=_strip_version(str(path)), + method=method.lower(), + parameters=tuple(names), + summary=summary if isinstance(summary, str) else "", + ) + ) + operations.sort(key=lambda op: (op.path, op.method)) + + title = info.get("title") if isinstance(info.get("title"), str) else "" + version = info.get("version") if isinstance(info.get("version"), str) else "" + return Spec( + title=title, + version=version, + kind=kind, + bases=bases or ["/"], + operations=operations, + source=source, + ) + + +def load_spec(path: str) -> Spec: + """Read a JSON spec from disk. Raises :class:`SpecError`.""" + try: + size = len(open(path, "rb").read(MAX_SPEC_BYTES + 1)) + except OSError as exc: + raise SpecError(f"cannot read spec '{path}': {exc.strerror or exc}") from exc + if size > MAX_SPEC_BYTES: + raise SpecError(f"spec '{path}' is larger than {MAX_SPEC_BYTES} bytes") + try: + with open(path, "r", encoding="utf-8-sig") as handle: + raw = handle.read() + except OSError as exc: + raise SpecError(f"cannot read spec '{path}': {exc.strerror or exc}") from exc + return parse_spec(_loads(raw, path), source=path) + + +# --------------------------------------------------------------------------- +# matching +# --------------------------------------------------------------------------- +_TEMPLATE = re.compile(r"\{[^/{}]+\}") + + +def _template_regex(path: str) -> "re.Pattern": + """Compile a documented path into a matcher for concrete paths.""" + parts: List[str] = [] + index = 0 + for match in _TEMPLATE.finditer(path): + parts.append(re.escape(path[index : match.start()])) + parts.append("[^/]+") + index = match.end() + parts.append(re.escape(path[index:])) + return re.compile("^" + "".join(parts) + "$", re.IGNORECASE) + + +@dataclass(frozen=True) +class _Compiled: + base: str + path: str + matcher: "re.Pattern" + operation: Operation + + +def _compile(spec: Spec) -> List[_Compiled]: + compiled: List[_Compiled] = [] + seen: Set[Tuple[str, str, str]] = set() + for base in spec.bases: + for operation in spec.operations: + full = _join_base(base, operation.path) + key = (full, operation.method, base) + if key in seen: + continue + seen.add(key) + compiled.append( + _Compiled( + base=base, + path=full, + matcher=_template_regex(full), + operation=operation, + ) + ) + return compiled + + +def _match_path(compiled: Sequence[_Compiled], method: str, path: str) -> Optional[_Compiled]: + method = (method or "get").lower() + fallback: Optional[_Compiled] = None + for entry in compiled: + if not entry.matcher.match(path): + continue + if entry.operation.method == method: + return entry + if fallback is None: + fallback = entry + return fallback + + +@dataclass +class Undocumented: + """An analysed finding whose endpoint is not described.""" + + finding: Finding + path: str + + def as_dict(self) -> Dict[str, object]: + return { + "host": self.finding.host, + "method": self.finding.method.upper(), + "path": self.path, + "parameter": self.finding.parameter, + "location": self.finding.location, + "score": self.finding.score, + "fingerprint": self.finding.fingerprint, + } + + +@dataclass +class UndeclaredParameter: + """A parameter the spec's operation does not declare.""" + + finding: Finding + operation: str + + def as_dict(self) -> Dict[str, object]: + return { + "host": self.finding.host, + "operation": self.operation, + "parameter": self.finding.parameter, + "location": self.finding.location, + "score": self.finding.score, + "fingerprint": self.finding.fingerprint, + } + + +@dataclass +class SpecReport: + """Result of comparing a report against a specification.""" + + spec: Spec + documented: int = 0 + undocumented: List[Undocumented] = field(default_factory=list) + undeclared: List[UndeclaredParameter] = field(default_factory=list) + unmatched_operations: List[str] = field(default_factory=list) + + @property + def coverage(self) -> float: + total = self.documented + len(self.undocumented) + return self.documented / total if total else 0.0 + + def as_dict(self) -> Dict[str, object]: + return { + "spec": { + "title": self.spec.title, + "version": self.spec.version, + "kind": self.spec.kind, + "source": self.spec.source, + "operations": len(self.spec.operations), + }, + "documented": self.documented, + "coverage": round(self.coverage, 4), + "undocumented": [item.as_dict() for item in self.undocumented], + "undeclared_parameters": [item.as_dict() for item in self.undeclared], + "unmatched_operations": list(self.unmatched_operations), + } + + +def compare(report, spec: Spec) -> SpecReport: + """Compare findings in ``report`` against ``spec``.""" + compiled = _compile(spec) + result = SpecReport(spec=spec) + matched_signatures: Set[str] = set() + + for finding in report.findings: + resource = finding.resource or "/" + parts = urlsplit(resource) + path = parts.path or "/" + entry = _match_path(compiled, finding.method, path) + if entry is None: + result.undocumented.append(Undocumented(finding=finding, path=path)) + continue + result.documented += 1 + matched_signatures.add(entry.operation.signature) + declared = {canonical_name(name) for name in entry.operation.parameters} + if canonical_name(finding.parameter) not in declared: + result.undeclared.append( + UndeclaredParameter(finding=finding, operation=entry.operation.signature) + ) + + described = {op.signature for op in spec.operations if op.signature in matched_signatures} + all_signatures = sorted({op.signature for op in spec.operations}) + result.unmatched_operations = [sig for sig in all_signatures if sig not in described] + return result + + +def render_spec_report(result: SpecReport) -> str: + """``--openapi`` as text.""" + spec = result.spec + title = spec.title or "(untitled)" + lines = ["PathScope specification comparison", "=" * 84] + lines.append(f"spec : {title} {spec.version} [{spec.kind}] from {spec.source}") + lines.append(f"operations: {len(spec.operations)} described") + lines.append( + f"coverage : {result.documented} finding(s) on described endpoints, " + f"{len(result.undocumented)} on undocumented ones " + f"({result.coverage:.1%} described)" + ) + lines.append("") + + if result.undocumented: + lines.append(f"Undocumented endpoints ({len(result.undocumented)})") + for item in result.undocumented[:40]: + lines.append( + f" {item.finding.method.upper():<6} {item.finding.host}{item.path}" + f" [{item.finding.location}] {item.finding.parameter}" + f" (score {item.finding.score})" + ) + if len(result.undocumented) > 40: + lines.append(f" ... and {len(result.undocumented) - 40} more") + lines.append("") + else: + lines.append("Undocumented endpoints (0): every finding is on a described route.") + lines.append("") + + if result.undeclared: + lines.append(f"Parameters the spec does not declare ({len(result.undeclared)})") + for item in result.undeclared[:40]: + lines.append( + f" {item.operation:<40} {item.finding.parameter}" + f" [{item.finding.location}] (score {item.finding.score})" + ) + if len(result.undeclared) > 40: + lines.append(f" ... and {len(result.undeclared) - 40} more") + lines.append("") + + if result.unmatched_operations: + lines.append( + f"Described but not seen in this capture ({len(result.unmatched_operations)})" + ) + for signature in result.unmatched_operations[:20]: + lines.append(f" {signature}") + if len(result.unmatched_operations) > 20: + lines.append(f" ... and {len(result.unmatched_operations) - 20} more") + lines.append("") + + lines.append( + "An undocumented endpoint is not a vulnerability: it is a route whose " + "intended behaviour nobody wrote down." + ) + return "\n".join(lines) + + +__all__ = [ + "MAX_PATHS", + "MAX_SPEC_BYTES", + "Operation", + "Spec", + "SpecError", + "SpecReport", + "UndeclaredParameter", + "Undocumented", + "compare", + "load_spec", + "parse_spec", + "render_spec_report", +] diff --git a/pathscope/playbooks.py b/pathscope/playbooks.py new file mode 100644 index 0000000..4973e2f --- /dev/null +++ b/pathscope/playbooks.py @@ -0,0 +1,394 @@ +"""Remediation playbooks (``--playbook``). + +A playbook turns a heuristic rule into an actionable note for two audiences: + +**the reviewer** — what to test by hand, in what order, and what a safe answer +looks like; and + +**the developer** — what to change in code so the finding goes away for good. + +These are generic, conservative checklists. They never instruct PathScope to do +anything itself, and they never claim a finding is a vulnerability: each entry +is framed as "if you confirm X, do Y". +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, List, Sequence + +from .detector import Finding, Report +from .rules import RULE_INDEX + +#: Shared developer guidance that applies to almost every path-like input. +COMMON_FIXES = ( + "Resolve the requested path against a fixed allow-listed base directory.", + "Canonicalise the path (real path on the resolved inode) *before* any check.", + "Reject the request if the canonical path leaves the base directory.", + "Prefer opaque identifiers (database IDs) over client-supplied paths.", + "Log the rejection with the request ID; never log the raw value.", +) + +#: Shared reviewer guidance. +COMMON_CHECKS = ( + "Confirm the parameter really reaches a filesystem/storage call.", + "Note the encoding the client uses (plain, percent, double percent).", + "Check whether the value is validated by a schema or allow-list upstream.", +) + + +@dataclass(frozen=True) +class Playbook: + """Guidance for one rule (or one umbrella section).""" + + key: str + title: str + what_it_means: str + how_to_test: Sequence[str] + how_to_fix: Sequence[str] + severity_note: str = "heuristic only, not a vulnerability" + + def as_dict(self) -> Dict[str, object]: + return { + "key": self.key, + "title": self.title, + "what_it_means": self.what_it_means, + "how_to_test": list(self.how_to_test), + "how_to_fix": list(self.how_to_fix), + "severity_note": self.severity_note, + } + + +_NAME_TEST = ( + "Send a benign relative path (e.g. `public/logo.png`) and confirm it renders.", + "Send `../` segments one at a time and confirm the response changes shape.", + "Try an absolute path only against a system you are authorised to test.", +) +_NAME_FIX = ( + "Treat the parameter as untrusted input even if a UI restricts it.", + "Validate with a strict schema (length, character class, no separators).", +) + COMMON_FIXES[:2] + +_VALUE_TEST = ( + "Re-send the recorded value unchanged and compare responses.", + "Re-encode the traversal (single, double, mixed slashes) and compare.", + "Check server-side normalisation: `/a/../b` must not escape `/a`.", +) +_VALUE_FIX = ( + "Normalise before validating, then validate the normalised form.", + "Do not rely on client-side filtering or URL rewriting alone.", +) + COMMON_FIXES[:3] + +GENERIC_PLAYBOOK = Playbook( + key="generic", + title="Path-like parameter", + what_it_means=( + "A parameter name and/or value looks like it addresses a file or path. " + "That is a reading-order hint only." + ), + how_to_test=COMMON_CHECKS + _NAME_TEST[:2], + how_to_fix=COMMON_FIXES, +) + +DEMOTION_PLAYBOOK = Playbook( + key="demotion", + title="Value shape demoted", + what_it_means=( + "The value is a UUID/hash/JWT/base64/e-mail/IP/scalar, so the parameter " + "was ranked lower. It is not necessarily harmless." + ), + how_to_test=( + "Confirm the parameter consumes an identifier rather than a path.", + "If it stores user-chosen file names, the demotion does not apply.", + ), + how_to_fix=( + "If it is an identifier, keep it opaque and validate its format.", + "If it becomes a path later, resolve that path against a base directory.", + ), +) + +PLAYBOOKS: Dict[str, Playbook] = { + "name-exact": Playbook( + "name-exact", + "Path-like parameter name", + "The parameter name contains a term the codebase commonly uses for files.", + _NAME_TEST, + _NAME_FIX, + ), + "name-custom": Playbook( + "name-custom", + "Project-specific path term", + "The name matches a term your configuration added to the vocabulary.", + _NAME_TEST, + _NAME_FIX, + ), + "name-prefix": Playbook( + "name-prefix", + "Name starts with a path term", + "A file-like word is a prefix of a longer parameter name.", + _NAME_TEST, + _NAME_FIX, + ), + "name-suffix": Playbook( + "name-suffix", + "Name ends with a path term", + "A file-like word is a suffix of a longer parameter name.", + _NAME_TEST, + _NAME_FIX, + ), + "name-folded": Playbook( + "name-folded", + "Folded name looks path-like", + "Only after folding diacritics/compatibility characters does the name look path-like.", + _NAME_TEST + ("Check how the application normalises Unicode in names.",), + _NAME_FIX, + ), + "name-leet": Playbook( + "name-leet", + "Obfuscated (leet) name", + "The name only matches a path term after de-obfuscation (f1le -> file).", + _NAME_TEST, + _NAME_FIX, + ), + "name-i18n": Playbook( + "name-i18n", + "Non-English path term", + "The name contains a path-related word from another language.", + _NAME_TEST, + _NAME_FIX, + ), + "name-i18n-fold": Playbook( + "name-i18n-fold", + "Folded non-English path term", + "A non-English path word appears only after folding.", + _NAME_TEST, + _NAME_FIX, + ), + "name-weak": Playbook( + "name-weak", + "Weak multiword name", + "A multiword name with no path term; weak evidence on its own.", + ("Treat as noise unless the value is path-like.",) + COMMON_CHECKS[:1], + COMMON_FIXES[:2], + ), + "name-generic": Playbook( + "name-generic", + "Generic name with a path-like value", + "A generic name (image/target/ref) whose value looks like a path.", + _VALUE_TEST, + _VALUE_FIX, + ), + "name-compound": Playbook( + "name-compound", + "Compound path name", + "The whole parameter name is a known compound such as `filepath`.", + _NAME_TEST, + _NAME_FIX, + ), + "value-traversal": Playbook( + "value-traversal", + "Traversal segment in the value", + "The recorded value contains a `..` path segment.", + _VALUE_TEST, + _VALUE_FIX, + ), + "value-encoded-traversal": Playbook( + "value-encoded-traversal", + "Encoded traversal", + "`..` appears only after percent-decoding, so a naive filter would miss it.", + _VALUE_TEST, + _VALUE_FIX + ("Decode once, fully, and normalise before validating.",), + ), + "value-double-encoded": Playbook( + "value-double-encoded", + "Nested encoding", + "The value needed two or more decoding passes.", + _VALUE_TEST + ("Confirm how many times the server decodes.",), + _VALUE_FIX + ("Decode exactly once, then validate; never decode in a loop.",), + ), + "value-encoded-slash": Playbook( + "value-encoded-slash", + "Encoded separators", + "The value contains `%2f`/`%5c`.", + _VALUE_TEST, + _VALUE_FIX, + ), + "value-absolute": Playbook( + "value-absolute", + "Absolute-looking path", + "The value starts with a path separator.", + _VALUE_TEST, + _VALUE_FIX, + ), + "value-windows-drive": Playbook( + "value-windows-drive", + "Windows drive path", + "The value looks like `C:\\...`.", + _VALUE_TEST, + _VALUE_FIX + ("On Windows, also block device names (CON, NUL, COM1).",), + ), + "value-unc": Playbook( + "value-unc", + "UNC path", + "The value looks like `\\\\server\\share`.", + _VALUE_TEST, + _VALUE_FIX + ("Reject UNC prefixes unless explicitly allowed.",), + ), + "value-multi-segment": Playbook( + "value-multi-segment", + "Multiple path segments", + "The value contains at least two separators.", + _VALUE_TEST, + _VALUE_FIX, + ), + "value-extension": Playbook( + "value-extension", + "File extension", + "The value ends with a known file extension.", + _VALUE_TEST, + _VALUE_FIX, + ), + "value-path-list": Playbook( + "value-path-list", + "Path list", + "The value looks like a list of paths.", + _VALUE_TEST + ("Check whether every element is validated, or only the first.",), + _VALUE_FIX, + ), + "value-full-url": Playbook( + "value-full-url", + "Full URL value", + "The value is a URL, not a local path; usually a redirect target.", + ( + "Check for open-redirect behaviour rather than file access.", + "Confirm whether the server follows the URL itself.", + ), + ( + "Allow-list redirect hosts and schemes explicitly.", + "Never fetch a user-supplied URL from the server.", + ), + ), + "value-pairs-with-generic-name": Playbook( + "value-pairs-with-generic-name", + "Generic name with path value", + "A generic parameter name paired with a path-like value.", + _VALUE_TEST, + _VALUE_FIX, + ), + "demotion": DEMOTION_PLAYBOOK, +} + + +def playbook_for(rule: str) -> Playbook: + """Return the playbook for a rule id (falls back to the generic entry).""" + if rule.startswith("value-demote-"): + return DEMOTION_PLAYBOOK + return PLAYBOOKS.get(rule, GENERIC_PLAYBOOK) + + +def sections_for(report: Report) -> List[tuple]: + """Group a report's findings by their playbook section, in rule order.""" + order: List[str] = [] + grouped: Dict[str, List[Finding]] = {} + for finding in report.findings: + key = "demotion" if finding.rule.startswith("value-demote-") else finding.rule + if key not in grouped: + grouped[key] = [] + order.append(key) + grouped[key].append(finding) + return [(playbook_for(key), grouped[key]) for key in order] + + +def describe_all() -> tuple: + """Summary lines for ``--list-playbooks``.""" + lines = [] + for key in sorted(PLAYBOOKS): + entry = PLAYBOOKS[key] + lines.append(f" {key:<26} {entry.title}") + lines.append(f" {'demotion':<26} {DEMOTION_PLAYBOOK.title}") + return tuple(lines) + + +def render_playbook_markdown(report: Report) -> str: + """Markdown fix guide: one section per rule that produced candidates.""" + from . import PROGRAM, __version__ + from .report import DISCLAIMER + + lines: List[str] = [ + f"# {PROGRAM} remediation playbook", + "", + f"{PROGRAM} {__version__}. {DISCLAIMER}", + "", + "Each section below lists what the rule means, how to confirm it by hand,", + "and what to change so it stops firing. Sections are ordered by the best", + "score in the report.", + "", + ] + sections = sections_for(report) + if not sections: + lines.append("No candidates were reported: there is nothing to work through.") + return "\n".join(lines) + "\n" + + sections.sort(key=lambda pair: -max(f.score for f in pair[1])) + for playbook, findings in sections: + best = max(findings, key=lambda f: f.score) + lines.append(f"## {playbook.title} (`{playbook.key}`)") + lines.append("") + lines.append(f"*{playbook.what_it_means}*") + lines.append("") + lines.append( + f"{len(findings)} candidate(s); best score {best.score}/100 " + f"({best.confidence}). {playbook.severity_note}." + ) + lines.append("") + lines.append("### Confirm by hand") + lines.append("") + for item in playbook.how_to_test: + lines.append(f"- {item}") + lines.append("") + lines.append("### Fix in code") + lines.append("") + for item in playbook.how_to_fix: + lines.append(f"- {item}") + lines.append("") + lines.append("### Candidates") + lines.append("") + lines.append("| Host | Location | Parameter | Score | Fingerprint |") + lines.append("|---|---|---|---|---|") + for finding in sorted(findings, key=lambda f: (-f.score, f.host, f.parameter))[:40]: + lines.append( + f"| {finding.host} | {finding.location} | `{finding.parameter}` | " + f"{finding.score} | `{finding.fingerprint}` |" + ) + if len(findings) > 40: + lines.append(f"| … | | {len(findings) - 40} more | | |") + lines.append("") + return "\n".join(lines) + + +def validate_playbook_coverage() -> List[str]: + """Return rule ids that have no dedicated playbook (tests use this).""" + missing = [] + for rule in RULE_INDEX: + if rule in ("name-weak", "name-generic"): + continue # intentionally covered by generic/weak entries + if rule.startswith("value-demote-"): + continue # all demotions share one section + if rule not in PLAYBOOKS: + missing.append(rule) + return missing + + +__all__ = [ + "COMMON_CHECKS", + "COMMON_FIXES", + "DEMOTION_PLAYBOOK", + "GENERIC_PLAYBOOK", + "PLAYBOOKS", + "Playbook", + "describe_all", + "playbook_for", + "render_playbook_markdown", + "sections_for", + "validate_playbook_coverage", +] diff --git a/pathscope/policy.py b/pathscope/policy.py new file mode 100644 index 0000000..c3fdac4 --- /dev/null +++ b/pathscope/policy.py @@ -0,0 +1,274 @@ +"""CI policy evaluation for PathScope. + +A policy answers one question: *should this run fail the build?* It is +deliberately separate from ``--fail-on-findings`` (which is "any new candidate"). + +Policy file (JSON, all keys optional):: + + { + "max_high": 0, + "max_medium": 5, + "max_low": 100, + "max_total": 25, + "min_score": 40, + "fail_on_known": false, + "ignore_rules": ["name-weak"], + "ignore_hosts": ["static.example.test"] + } + +Evaluation counts only *new* findings unless ``fail_on_known`` is true, so a +saved baseline keeps a pipeline quiet. Every decision is explainable: the +result carries the rule that fired and the numbers behind it. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence + +from .detector import Finding, Report + +#: Keys accepted in a policy file. +POLICY_KEYS = ( + "max_high", + "max_medium", + "max_low", + "max_total", + "min_score", + "fail_on_known", + "fail_on_reviewed", + "ignore_rules", + "ignore_hosts", + "description", +) + +DEFAULT_POLICY = "default" + + +class PolicyError(ValueError): + """Raised when a policy file is invalid.""" + + +@dataclass +class Policy: + """A validated CI gate.""" + + max_high: Optional[int] = None + max_medium: Optional[int] = None + max_low: Optional[int] = None + max_total: Optional[int] = None + min_score: int = 0 + fail_on_known: bool = False + #: When true, findings already decided in the review ledger still count + #: toward the gate. Off by default: reviewed triage should stop alerting. + fail_on_reviewed: bool = False + ignore_rules: Sequence[str] = () + ignore_hosts: Sequence[str] = () + description: str = "" + source: str = "" + + # -- construction ----------------------------------------------------- + @classmethod + def from_payload(cls, payload: object, source: str = "") -> "Policy": + if payload is None: + payload = {} + if not isinstance(payload, dict): + raise PolicyError("policy must be a JSON object") + unknown = sorted(set(payload) - set(POLICY_KEYS)) + if unknown: + raise PolicyError( + "unknown policy key(s): " + ", ".join(unknown) + + f" (allowed: {', '.join(POLICY_KEYS)})" + ) + policy = cls(source=source) + for key in ("max_high", "max_medium", "max_low", "max_total"): + if key in payload: + value = payload[key] + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise PolicyError(f"'{key}' must be a non-negative integer") + setattr(policy, key, value) + if "min_score" in payload: + value = payload["min_score"] + if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100: + raise PolicyError("'min_score' must be an integer between 0 and 100") + policy.min_score = value + if "fail_on_known" in payload: + if not isinstance(payload["fail_on_known"], bool): + raise PolicyError("'fail_on_known' must be true or false") + policy.fail_on_known = payload["fail_on_known"] + if "fail_on_reviewed" in payload: + if not isinstance(payload["fail_on_reviewed"], bool): + raise PolicyError("'fail_on_reviewed' must be true or false") + policy.fail_on_reviewed = payload["fail_on_reviewed"] + for key in ("ignore_rules", "ignore_hosts"): + if key in payload: + value = payload[key] + if not isinstance(value, list) or not all(isinstance(x, str) for x in value): + raise PolicyError(f"'{key}' must be an array of strings") + if len(value) > 200: + raise PolicyError(f"'{key}' may contain at most 200 entries") + setattr(policy, key, [item.strip() for item in value if item.strip()]) + if "description" in payload: + if not isinstance(payload["description"], str): + raise PolicyError("'description' must be a string") + policy.description = payload["description"][:200] + return policy + + # -- queries ---------------------------------------------------------- + def is_empty(self) -> bool: + return ( + self.max_high is None + and self.max_medium is None + and self.max_low is None + and self.max_total is None + and self.min_score == 0 + ) + + def describe(self) -> str: + parts: List[str] = [] + for key in ("max_high", "max_medium", "max_low", "max_total"): + value = getattr(self, key) + if value is not None: + parts.append(f"{key}={value}") + if self.min_score: + parts.append(f"min_score={self.min_score}") + if self.fail_on_known: + parts.append("fail_on_known=true") + if self.ignore_rules: + parts.append("ignore_rules=" + ",".join(self.ignore_rules)) + if self.ignore_hosts: + parts.append("ignore_hosts=" + ",".join(self.ignore_hosts)) + return "; ".join(parts) or "no limits" + + +@dataclass +class PolicyResult: + """Outcome of applying a policy to one report.""" + + passed: bool + violations: List[str] = field(default_factory=list) + counts: Dict[str, int] = field(default_factory=dict) + policy: Optional[Policy] = None + ignored: int = 0 + + @property + def exit_code(self) -> int: + return 0 if self.passed else 1 + + def describe(self) -> str: + if self.passed: + return "policy passed" + return "policy failed: " + "; ".join(self.violations) + + +def _eligible(finding: Finding, policy: Policy) -> bool: + if policy.ignore_rules and finding.rule in policy.ignore_rules: + return False + if policy.ignore_hosts and finding.host in policy.ignore_hosts: + return False + if policy.min_score and finding.score < policy.min_score: + return False + if finding.status == "known" and not policy.fail_on_known: + return False + # A ledger decision is a human saying "stop showing me this". It should stop + # the gate too, unless the policy explicitly asks to keep failing on it. + if finding.status == "reviewed" and not policy.fail_on_reviewed: + return False + # A waiver exists for exactly one reason: to stop this gate from failing on + # an accepted risk. Honouring it conditionally would make it decorative. + # `fail_on_reviewed` deliberately does not re-enable waivers -- a waiver is + # a declared, owned, usually time-limited exception, not a review note. + if finding.status == "waived": + return False + return True + + +def evaluate(report: Report, policy: Policy) -> PolicyResult: + """Apply ``policy`` to ``report`` (uses new findings unless told otherwise).""" + counts = {"high": 0, "medium": 0, "low": 0, "total": 0} + ignored = 0 + for finding in report.findings: + if not _eligible(finding, policy): + if ( + finding.status not in ("known", "reviewed") + and policy.min_score + and finding.score < policy.min_score + ): + ignored += 1 + continue + counts[finding.confidence] = counts.get(finding.confidence, 0) + 1 + counts["total"] += 1 + + violations: List[str] = [] + checks = ( + ("max_high", counts["high"]), + ("max_medium", counts["medium"]), + ("max_low", counts["low"]), + ("max_total", counts["total"]), + ) + for key, actual in checks: + limit = getattr(policy, key) + if limit is not None and actual > limit: + violations.append(f"{key}={limit} exceeded ({actual} found)") + return PolicyResult( + passed=not violations, + violations=violations, + counts=counts, + policy=policy, + ignored=ignored, + ) + + +def load_policy(path: str) -> Policy: + """Read a policy file. Raises :class:`PolicyError`.""" + try: + with open(path, "r", encoding="utf-8-sig") as handle: + raw = handle.read() + except OSError as exc: + raise PolicyError(f"cannot read policy '{path}': {exc.strerror or exc}") from exc + try: + payload = json.loads(raw) + except json.JSONDecodeError as exc: + raise PolicyError( + f"policy '{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + return Policy.from_payload(payload, source=path) + + +def starter_policy() -> str: + """Default policy written by ``--init-policy``.""" + return ( + "{\n" + ' "description": "PathScope CI gate: no new high-confidence candidates",\n' + ' "max_high": 0,\n' + ' "max_medium": 10,\n' + ' "max_total": 20,\n' + ' "min_score": 0,\n' + ' "fail_on_known": false,\n' + ' "ignore_rules": [],\n' + ' "ignore_hosts": []\n' + "}\n" + ) + + +def parse_inline_policy(text: str) -> Policy: + """Parse a ``--policy`` value that is JSON rather than a file path.""" + try: + payload = json.loads(text) + except json.JSONDecodeError as exc: + raise PolicyError(f"inline policy is not valid JSON: {exc.msg}") from exc + return Policy.from_payload(payload) + + +__all__ = [ + "DEFAULT_POLICY", + "POLICY_KEYS", + "Policy", + "PolicyError", + "PolicyResult", + "evaluate", + "load_policy", + "parse_inline_policy", + "starter_policy", +] diff --git a/pathscope/prcomment.py b/pathscope/prcomment.py new file mode 100644 index 0000000..aea48e4 --- /dev/null +++ b/pathscope/prcomment.py @@ -0,0 +1,222 @@ +"""Compact pull-request comment (``--pr-comment FILE``). + +A CI run that fails should say why in the place the reviewer is already +looking. This writes a Markdown comment sized for a pull-request thread: a +short verdict, a table of the worst rows, and a marker so the same comment can +be updated in place rather than stacked up on every push. + +Three constraints shape the output: + +* **It must fit.** Comments are clipped by CI services at unpredictable + lengths, so the renderer budgets characters and truncates by rows, never + mid-table, and always states how many rows were left out. +* **It must be stable.** The same run produces the same comment, so a diff of + the comment shows what actually changed. No timestamps in the body (the + marker line carries the run id instead). +* **It must not disclose values.** Only hosts, resources, parameter names and + scores appear. There is no code path that writes a value here. + +The file begins with ```` so a workflow can find and +replace its previous comment with a single API call. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import List + +from .detector import Report + +#: Marker a CI workflow greps for to update the existing comment. +MARKER = "" + +#: Default budget, comfortably under GitHub's 65536-character comment limit. +DEFAULT_BUDGET = 5500 +#: Rows in the headline table before the budget takes over. +DEFAULT_ROWS = 10 + + +@dataclass +class PrComment: + """A rendered comment and what it cost.""" + + body: str + rows: int + omitted: int + truncated: bool + + @property + def size(self) -> int: + return len(self.body) + + def as_dict(self) -> dict: + return { + "rows": self.rows, + "omitted": self.omitted, + "truncated": self.truncated, + "characters": self.size, + } + + +def _escape(text: str) -> str: + """Make a cell safe inside a Markdown table.""" + return ( + (text or "") + .replace("\\", "\\\\") + .replace("|", "\\|") + .replace("`", "'") + .replace("\n", " ") + .replace("\r", " ") + ) + + +def _verdict(report: Report, exit_code: int) -> str: + """The one line a reviewer reads first. + + It follows the *report*, not the caller's guess about the exit code: a + comment that says "no new candidates" above a table of four candidates is + worse than no comment at all. + """ + if exit_code == 2: + return "**PathScope: input or usage error.**" + if exit_code not in (0, 1): + return "**PathScope: run did not complete.**" + new = [f for f in report.findings if f.status == "new"] + if not new: + return "**PathScope: no new candidates.**" + worst = max(new, key=lambda f: f.score) + top = report.confidence_counts + confidence = "high" if top.get("high") else ("medium" if top.get("medium") else "low") + return ( + f"**PathScope: {len(new)} new candidate(s) need review** " + f"(best score {worst.score}/100, {confidence} confidence)." + ) + + +def render_comment( + report: Report, + *, + exit_code: int = 0, + budget: int = DEFAULT_BUDGET, + rows: int = DEFAULT_ROWS, + run_id: str = "", + details_url: str = "", +) -> PrComment: + """Render a PR comment for one report.""" + lines: List[str] = [MARKER, ""] + lines.append(_verdict(report, exit_code)) + lines.append("") + + counts = report.confidence_counts + lines.append( + f"`{report.requests_analyzed}` request(s) · " + f"`{report.parameters_analyzed}` parameter(s) · " + f"`{report.candidate_count}` candidate(s) at score ≥ {report.min_score} · " + f"high `{counts.get('high', 0)}` · medium `{counts.get('medium', 0)}` · " + f"low `{counts.get('low', 0)}`" + ) + lines.append("") + + findings = [finding for finding in report.findings if finding.status != "known"] + omitted = 0 + if findings: + header = [ + "| score | host | resource | parameter | location |", + "|---:|---|---|---|---|", + ] + body_rows: List[str] = [] + for finding in findings[:rows]: + body_rows.append( + f"| {finding.score} | {_escape(finding.host)} | " + f"{_escape(finding.resource)} | `{_escape(finding.parameter)}` | " + f"{_escape(finding.location)} |" + ) + omitted = max(0, len(findings) - len(body_rows)) + lines.extend(header) + lines.extend(body_rows) + if omitted: + lines.append("") + lines.append(f"_{omitted} more candidate(s) not shown._") + else: + lines.append("No candidates at the current threshold.") + lines.append("") + + if report.mode == "diff" and (report.known_count or report.resolved): + lines.append( + f"Baseline applied: `{report.known_count}` known, " + f"`{len(report.resolved)}` resolved." + ) + lines.append("") + + footer = [ + f"*Generated by {report and 'PathScope'} from a local capture; " + "no request was made.*", + "*Candidates are for manual review, not confirmed vulnerabilities.*", + ] + if details_url: + footer.append(f"[Full report]({details_url})") + if run_id: + footer.append(f"") + lines.extend(footer) + + body = "\n".join(lines) + "\n" + truncated = False + # Budget guard: drop table rows from the end until it fits. Never cut a + # table in half, and always say what was dropped. + while len(body) > budget and findings: + if rows <= 1: + break + rows = max(1, rows - 1) + rebuilt = render_comment( + report, + exit_code=exit_code, + budget=0, + rows=rows, + run_id=run_id, + details_url=details_url, + ) + body = rebuilt.body + omitted = rebuilt.omitted + truncated = True + break + if len(body) > budget: + # Even one row does not fit: fall back to a summary with a link. + head = [ + MARKER, + "", + _verdict(report, exit_code), + "", + f"`{report.candidate_count}` candidate(s) at score ≥ {report.min_score}; " + "the table does not fit in a comment.", + "", + ] + if details_url: + head.append(f"[Full report]({details_url})") + head.append("") + body = "\n".join(head) + "\n" + truncated = True + omitted = len(findings) + return PrComment( + body=body, + rows=0 if truncated and omitted == len(findings) else len(findings) - omitted, + omitted=omitted, + truncated=truncated, + ) + + +def describe() -> tuple: + """Lines for ``--help``.""" + return ( + " --pr-comment FILE write a compact, truncation-aware Markdown summary", + f" {'':<21} (starts with {MARKER})", + ) + + +__all__ = [ + "DEFAULT_BUDGET", + "DEFAULT_ROWS", + "MARKER", + "PrComment", + "describe", + "render_comment", +] diff --git a/pathscope/precision.py b/pathscope/precision.py new file mode 100644 index 0000000..eca7432 --- /dev/null +++ b/pathscope/precision.py @@ -0,0 +1,203 @@ +"""Per-rule precision (``--rule-precision``). + +Every rule in the registry makes a claim: "this bit of evidence is worth +reporting". The ledger records what humans actually decided. Putting the two +together gives each rule a precision: + + precision = accepted / (accepted + false-positive) + +for every finding where the rule appears. That number is not a quality score on +its own -- a rule that fires twice and was right both times is not better than +one that fires 400 times and was right 380 -- so the report always shows the +sample size and refuses to rank rules on thin evidence. + +What it is for: a rule with 30 labelled findings and 3% precision is costing +reviewers time, and that is a fact about *this* estate, not about the rule in +the abstract. A rule with 5 labels is not evidence of anything. + +Only labelled reviews are counted. ``reviewed`` and ``resolved`` rows say +somebody looked, not what they concluded. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence + +#: Below this many labelled findings, precision is reported but never judged. +MIN_LABELS = 5 +#: A rule must have at least this precision to be called "earning its weight". +GOOD_PRECISION = 0.70 +#: ... and at most this to be called a candidate for demotion. +POOR_PRECISION = 0.30 + +LABEL_ACCEPTED = "accepted" +LABEL_FALSE_POSITIVE = "false-positive" + + +@dataclass +class RulePrecision: + """How one rule has been judged.""" + + rule: str + accepted: int = 0 + false_positives: int = 0 + other: int = 0 + + @property + def labelled(self) -> int: + return self.accepted + self.false_positives + + @property + def precision(self) -> Optional[float]: + return self.accepted / self.labelled if self.labelled else None + + @property + def verdict(self) -> str: + if self.labelled < MIN_LABELS: + return "thin evidence" + precision = self.precision or 0.0 + if precision >= GOOD_PRECISION: + return "earning its weight" + if precision <= POOR_PRECISION: + return "candidate for demotion" + return "borderline" + + def as_dict(self) -> Dict[str, object]: + return { + "rule": self.rule, + "accepted": self.accepted, + "false_positives": self.false_positives, + "other": self.other, + "labelled": self.labelled, + "precision": None if self.precision is None else round(self.precision, 4), + "verdict": self.verdict, + } + + +@dataclass +class PrecisionReport: + """Per-rule precision across every labelled review.""" + + rules: Dict[str, RulePrecision] = field(default_factory=dict) + reviews_read: int = 0 + reviews_labelled: int = 0 + + def ranked(self) -> List[RulePrecision]: + """Best evidence first: most labels, then best precision.""" + return sorted( + self.rules.values(), + key=lambda item: (-item.labelled, -(item.precision or 0.0), item.rule), + ) + + @property + def actionable(self) -> List[RulePrecision]: + return [ + item + for item in self.ranked() + if item.verdict == "candidate for demotion" + ] + + def as_dict(self) -> Dict[str, object]: + return { + "reviews_read": self.reviews_read, + "reviews_labelled": self.reviews_labelled, + "min_labels": MIN_LABELS, + "rules": [item.as_dict() for item in self.ranked()], + } + + +def _rules_of(review) -> List[str]: + """Every rule id a review can be attributed to. + + Ledgers written before rules were stored fall back to the review's primary + rule, which is the one PathScope used to produce the finding. + """ + rules = getattr(review, "rules", None) + if isinstance(rules, (list, tuple)) and rules: + return [str(rule) for rule in rules if rule] + primary = getattr(review, "rule", "") or "" + return [primary] if primary else [] + + +def rule_precision(reviews: Sequence) -> PrecisionReport: + """Compute precision per rule from ledger reviews.""" + report = PrecisionReport(reviews_read=len(reviews)) + for review in reviews: + status = getattr(review, "status", "") + if status not in (LABEL_ACCEPTED, LABEL_FALSE_POSITIVE): + continue + report.reviews_labelled += 1 + for rule in _rules_of(review): + entry = report.rules.get(rule) + if entry is None: + entry = RulePrecision(rule=rule) + report.rules[rule] = entry + if status == LABEL_ACCEPTED: + entry.accepted += 1 + else: + entry.false_positives += 1 + return report + + +def render_precision(report: PrecisionReport) -> str: + """``--rule-precision`` as text.""" + lines = ["PathScope rule precision", "=" * 84] + if not report.reviews_labelled: + lines.append( + f"{report.reviews_read} review(s) read, none labelled. " + "Precision needs 'accepted' or 'false-positive' decisions; " + "'reviewed' only says somebody looked." + ) + return "\n".join(lines) + + lines.append( + f"{report.reviews_labelled} labelled review(s) of " + f"{report.reviews_read} read. Precision is per rule, counting every " + "rule that contributed to a finding." + ) + lines.append("") + lines.append( + f" {'rule':<26} {'labelled':>8} {'accepted':>8} {'fp':>5} " + f"{'precision':>9} verdict" + ) + for entry in report.ranked(): + precision = ( + f"{entry.precision:.0%}" if entry.precision is not None else "-" + ) + lines.append( + f" {entry.rule:<26} {entry.labelled:>8} {entry.accepted:>8} " + f"{entry.false_positives:>5} {precision:>9} {entry.verdict}" + ) + lines.append("") + if any(entry.labelled < MIN_LABELS for entry in report.rules.values()): + lines.append( + f"Rules with fewer than {MIN_LABELS} labelled findings are reported " + f"but not judged: a precision from four rows is a coincidence." + ) + lines.append("") + if report.actionable: + names = ", ".join(entry.rule for entry in report.actionable) + lines.append( + f"Candidates for demotion on this evidence: {names}." + ) + lines.append( + "Check with --simulate before changing a weight: precision says the " + "rule was wrong, not that its weight is wrong." + ) + else: + lines.append("No rule has enough bad evidence to justify demotion.") + return "\n".join(lines) + + +__all__ = [ + "GOOD_PRECISION", + "LABEL_ACCEPTED", + "LABEL_FALSE_POSITIVE", + "MIN_LABELS", + "POOR_PRECISION", + "PrecisionReport", + "RulePrecision", + "render_precision", + "rule_precision", +] diff --git a/pathscope/presets.py b/pathscope/presets.py new file mode 100644 index 0000000..0a5d894 --- /dev/null +++ b/pathscope/presets.py @@ -0,0 +1,294 @@ +"""Built-in scoring presets. + +Presets only change *reporting* thresholds and the weight of the weakest +name rule. They never invent findings and never claim exploitability. + + minimal high-signal only: threshold 50, weak names off + balanced default posture: threshold 25 + noisy broad triage: threshold 10, weak names on +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import Dict, List, Tuple + +from .config import Config + +PRESET_MINIMAL = "minimal" +PRESET_BALANCED = "balanced" +PRESET_NOISY = "noisy" +PRESET_ALL = "all" + +PRESET_NAMES: Tuple[str, ...] = (PRESET_MINIMAL, PRESET_BALANCED, PRESET_NOISY) + +#: Rows printed by ``--compare-presets`` before truncating. +MAX_COMPARE_ROWS = 80 + + +@dataclass(frozen=True) +class Preset: + """Reporting posture applied before a configuration file is merged in.""" + + name: str + min_score: int + weak_names: bool + description: str + + def apply(self, config: Config) -> Config: + """Return ``config`` with this preset's explicit defaults applied. + + A value already set in a configuration file wins over the preset, so + ``--preset strict`` plus ``"min_score": 40`` means 40. + """ + if not config.is_explicit("min_score"): + config = replace(config, min_score=self.min_score) + if not config.is_explicit("weak_names"): + config = replace(config, weak_names=self.weak_names) + return config + + +PRESETS: Dict[str, Preset] = { + PRESET_MINIMAL: Preset( + name=PRESET_MINIMAL, + min_score=50, + weak_names=False, + description="high-signal only (score >= 50, no weak-name evidence)", + ), + PRESET_BALANCED: Preset( + name=PRESET_BALANCED, + min_score=25, + weak_names=True, + description="default posture (score >= 25)", + ), + PRESET_NOISY: Preset( + name=PRESET_NOISY, + min_score=10, + weak_names=True, + description="broad triage (score >= 10, includes weak names)", + ), +} + +#: Aliases accepted on the command line. +PRESET_ALIASES = { + "strict": PRESET_MINIMAL, + "high": PRESET_MINIMAL, + "default": PRESET_BALANCED, + "loud": PRESET_NOISY, + "broad": PRESET_NOISY, +} + +#: Per-preset starter configuration written by ``--init-config``. +STARTER_CONFIGS = { + PRESET_MINIMAL: ( + '{\n' + ' "name_terms": [],\n' + ' "ignore_params": ["image", "avatar", "thumb", "logo"],\n' + ' "min_score": 50,\n' + ' "max_decode_passes": 3,\n' + ' "weak_names": false,\n' + ' "name_lang": [],\n' + ' "fold_names": true,\n' + ' "demote_shapes": true,\n' + ' "show_values": false\n' + '}\n' + ), + PRESET_BALANCED: ( + '{\n' + ' "name_terms": [],\n' + ' "ignore_params": [],\n' + ' "min_score": 25,\n' + ' "max_decode_passes": 3,\n' + ' "weak_names": true,\n' + ' "name_lang": [],\n' + ' "fold_names": true,\n' + ' "demote_shapes": true,\n' + ' "show_values": false\n' + '}\n' + ), + PRESET_NOISY: ( + '{\n' + ' "name_terms": [],\n' + ' "ignore_params": [],\n' + ' "min_score": 10,\n' + ' "max_decode_passes": 3,\n' + ' "weak_names": true,\n' + ' "name_lang": [],\n' + ' "fold_names": true,\n' + ' "demote_shapes": true,\n' + ' "show_values": false\n' + '}\n' + ), +} + + +def resolve_preset(name: str | None) -> Preset | None: + """Return the preset for ``name`` (or ``None`` when unset/unknown).""" + if not name: + return None + key = name.strip().lower() + key = PRESET_ALIASES.get(key, key) + return PRESETS.get(key) + + +def describe_presets() -> Tuple[str, ...]: + """Lines used in ``--help`` and the README.""" + return tuple( + f" {preset.name:<9} {preset.description}" for preset in PRESETS.values() + ) + + +# --------------------------------------------------------------------------- +# 2.4: preset comparison +# --------------------------------------------------------------------------- +@dataclass +class PresetDiffRow: + """One candidate as the presets classify it.""" + + host: str + parameter: str + location: str + score: int + #: preset name -> True when that preset would report this candidate. + reported: Dict[str, bool] = field(default_factory=dict) + + @property + def pattern(self) -> str: + """Compact per-preset marker, e.g. ``-xx`` (hidden, billed, billed).""" + return "".join("x" if self.reported.get(name) else "-" for name in sorted(self.reported)) + + def as_dict(self) -> Dict[str, object]: + return { + "host": self.host, + "parameter": self.parameter, + "location": self.location, + "score": self.score, + "reported": dict(self.reported), + } + + +@dataclass +class PresetComparison: + """How each preset treats the same scored candidate set.""" + + rows: List[PresetDiffRow] = field(default_factory=list) + #: preset name -> number of candidates it reports. + counts: Dict[str, int] = field(default_factory=dict) + #: preset name -> threshold used. + thresholds: Dict[str, int] = field(default_factory=dict) + #: Candidates that at least one preset reports. + total_scored: int = 0 + + @property + def minimal_and_above(self) -> List[PresetDiffRow]: + """Reported by the strictest preset, and therefore by all three.""" + return [row for row in self.rows if row.reported.get(PRESET_MINIMAL)] + + @property + def noisy_only(self) -> List[PresetDiffRow]: + """Reported by ``noisy`` alone: what only the loosest threshold shows.""" + return [ + row for row in self.rows + if row.reported.get(PRESET_NOISY) + and not row.reported.get(PRESET_BALANCED) + and not row.reported.get(PRESET_MINIMAL) + ] + + @property + def balanced_but_not_minimal(self) -> List[PresetDiffRow]: + """Reported by balanced and noisy, hidden by minimal.""" + return [ + row for row in self.rows + if row.reported.get(PRESET_BALANCED) and not row.reported.get(PRESET_MINIMAL) + ] + + def as_dict(self) -> Dict[str, object]: + return { + "presets": list(PRESET_NAMES), + "thresholds": dict(self.thresholds), + "counts": dict(self.counts), + "scored": self.total_scored, + "candidates": [row.as_dict() for row in self.rows], + } + + +def compare_presets(report) -> PresetComparison: + """Score the report's findings against every preset threshold. + + The detector already scored each candidate; this compares those scores with + each preset's ``min_score`` and ``weak_names`` setting. It never re-scores, + so a candidate cannot appear or disappear for any reason other than the + preset's own threshold — which is exactly the question ``--compare-presets`` + is asked. + """ + comparison = PresetComparison(total_scored=len(report.findings)) + for name in PRESET_NAMES: + comparison.thresholds[name] = PRESETS[name].min_score + comparison.counts[name] = 0 + + for finding in report.findings: + row = PresetDiffRow( + host=finding.host, + parameter=finding.parameter, + location=finding.location, + score=finding.score, + ) + for name in PRESET_NAMES: + preset = PRESETS[name] + reported = finding.score >= preset.min_score + if reported and not preset.weak_names: + # "weak names off" means weak-name-only evidence is not enough. + reported = bool(finding.score >= preset.min_score) and ( + "name-weak" not in (finding.rules or ()) + ) + row.reported[name] = reported + if reported: + comparison.counts[name] += 1 + comparison.rows.append(row) + + comparison.rows.sort(key=lambda item: (-item.score, item.host, item.parameter)) + return comparison + + +def render_preset_comparison(comparison: PresetComparison) -> str: + """Text view of :func:`compare_presets`.""" + lines = ["PathScope preset comparison", "=" * 84] + lines.append( + " preset threshold reports share" + ) + for name in PRESET_NAMES: + count = comparison.counts.get(name, 0) + share = (count / comparison.total_scored * 100) if comparison.total_scored else 0.0 + lines.append( + f" {name:<12} {comparison.thresholds.get(name, 0):>9} " + f"{count:>8} {share:5.1f}%" + ) + lines.append("") + if not comparison.rows: + lines.append("No candidates were scored, so there is nothing to compare.") + return "\n".join(lines) + + header = " score " + " ".join(f"{name[:7]:<7}" for name in PRESET_NAMES) + lines.append(header + " candidate") + for row in comparison.rows[: MAX_COMPARE_ROWS]: + marks = " ".join( + f"{('yes' if row.reported.get(name) else '-'):<7}" for name in PRESET_NAMES + ) + lines.append( + f" {row.score:>5} {marks} {row.host} {row.location}:{row.parameter}" + ) + if len(comparison.rows) > MAX_COMPARE_ROWS: + lines.append(f" ... {len(comparison.rows) - MAX_COMPARE_ROWS} more") + lines.append("") + strict = comparison.counts.get(PRESET_MINIMAL, 0) + loose = comparison.counts.get(PRESET_NOISY, 0) + lines.append( + f"minimal reports {strict}, balanced {comparison.counts.get(PRESET_BALANCED, 0)}, " + f"noisy {loose}; {max(0, loose - strict)} candidate(s) are shown by a " + f"looser threshold than minimal." + ) + lines.append( + "Choosing a preset changes what is shown, never what is scored; " + "the underlying evidence is identical." + ) + return "\n".join(lines) diff --git a/pathscope/progress.py b/pathscope/progress.py new file mode 100644 index 0000000..bdbd4bb --- /dev/null +++ b/pathscope/progress.py @@ -0,0 +1,108 @@ +"""Optional stderr progress reporting (``--progress``). + +Progress goes to stderr only, is rate-limited, and never writes to stdout, so +``--format json`` stays machine-readable. Lines are plain ASCII and are erased +in place with ``\\r`` only when stderr is a terminal; otherwise each update is +printed as its own line (CI logs keep a readable history). +""" + +from __future__ import annotations + +import sys +import time +from typing import Callable, Optional, TextIO + +#: Minimum seconds between two updates (rate limit). +MIN_UPDATE_INTERVAL = 0.25 + + +class Progress: + """A small, dependency-free progress reporter.""" + + def __init__( + self, + enabled: bool = False, + stream: Optional[TextIO] = None, + interval: float = MIN_UPDATE_INTERVAL, + now: Callable[[], float] = time.monotonic, + ) -> None: + self.enabled = enabled + self.stream = stream if stream is not None else sys.stderr + self.interval = interval + self.now = now + self._last = 0.0 + self._phase = "" + self._total = 0 + self._count = 0 + self._started = 0.0 + self._interactive = False + try: + self._interactive = bool(self.stream.isatty()) + except Exception: # pragma: no cover - exotic streams + self._interactive = False + + # -- lifecycle -------------------------------------------------------- + def start(self, phase: str, total: int = 0) -> None: + if not self.enabled: + return + self._phase = phase + self._total = max(0, total) + self._count = 0 + self._started = self.now() + # Backdate so the first update is always shown, then rate-limit. + self._last = self._started - self.interval + self._write(self._format(), force=True) + + def update(self, count: int, total: Optional[int] = None) -> None: + if not self.enabled: + return + self._count = count + if total is not None: + self._total = max(0, total) + current = self.now() + if current - self._last < self.interval: + return + self._last = current + self._write(self._format()) + + def advance(self, step: int = 1) -> None: + self.update(self._count + step) + + def finish(self, note: str = "") -> None: + if not self.enabled: + return + elapsed = max(0.0, self.now() - self._started) + detail = f" in {elapsed:.2f}s" if elapsed >= 0.01 else "" + suffix = f" - {note}" if note else "" + self._write(f"{self._phase}: done{detail}{suffix}", force=True, final=True) + + # -- rendering -------------------------------------------------------- + def _format(self) -> str: + if self._total: + percent = min(100, int(self._count * 100 / self._total)) + return f"{self._phase}: {self._count}/{self._total} ({percent}%)" + return f"{self._phase}: {self._count}" + + def _write(self, text: str, force: bool = False, final: bool = False) -> None: + if not self.enabled and not force: + return + try: + if self._interactive and not final: + self.stream.write("\r" + text.ljust(72)) + if final: + self.stream.write("\n") + else: + self.stream.write(text + "\n") + self.stream.flush() + except (OSError, ValueError): # pragma: no cover - closed stderr + self.enabled = False + + +class NullProgress(Progress): + """A disabled progress reporter (used when ``--progress`` is absent).""" + + def __init__(self) -> None: # noqa: D107 - trivial + super().__init__(enabled=False) + + +__all__ = ["MIN_UPDATE_INTERVAL", "NullProgress", "Progress"] diff --git a/pathscope/project.py b/pathscope/project.py new file mode 100644 index 0000000..f091b42 --- /dev/null +++ b/pathscope/project.py @@ -0,0 +1,299 @@ +"""Project auto-discovery (``.pathscope/project.json``). + +Running PathScope from inside a repository should not need six flags. A project +file records the choices that belong to the project rather than to one run: + +.. code-block:: json + + { + "project": "acme-api", + "version": 1, + "config": "pathscope.json", + "policy": "policy.json", + "rules": "rules.json", + "terms": ["terms/acme.json", "terms/vendor.json"], + "ledger": "reviews.db", + "history": "runs.json" + } + +Discovery walks **up** from the working directory and stops at the first +``.pathscope/project.json`` it finds (or at the filesystem root). Paths inside +the file are resolved relative to the project file, so a project works from any +subdirectory. + +Rules that keep this predictable and safe: + +* every referenced path must resolve **inside** the project directory — a + project file cannot point at ``/etc/passwd`` or ``../../secrets``, +* nothing is downloaded and nothing is executed: the file names inputs only, +* command-line flags always beat project values, and +* ``--no-project`` disables discovery entirely. + +The whole feature can be inspected without running a scan: ``--show-project`` +prints what was found, what it would apply, and what the command line overrode. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence + +#: Directory that holds the project file. +PROJECT_DIR = ".pathscope" +#: The file name inside :data:`PROJECT_DIR`. +PROJECT_FILE = "project.json" +#: Schema version accepted by this build. +PROJECT_VERSION = 1 +#: Keys allowed at the top level. +ALLOWED_KEYS = { + "project", "version", "description", + "config", "policy", "rules", "terms", "ledger", "history", "baseline", +} +#: Keys whose value is a single relative path. +PATH_KEYS = ("config", "policy", "rules", "ledger", "history", "baseline") +#: Keys whose value is a list of relative paths. +LIST_KEYS = ("terms",) +MAX_PROJECT_BYTES = 64 * 1024 + + +class ProjectError(ValueError): + """Raised when a project file is malformed or points outside the project.""" + + +@dataclass +class Project: + """A validated project file with absolute, containment-checked paths.""" + + root: str + path: str + name: str = "" + description: str = "" + config: str = "" + policy: str = "" + rules: str = "" + baseline: str = "" + ledger: str = "" + history: str = "" + terms: List[str] = field(default_factory=list) + + def as_dict(self) -> Dict[str, object]: + return { + "project": self.name, + "root": self.root, + "file": self.path, + "config": self.config, + "policy": self.policy, + "rules": self.rules, + "baseline": self.baseline, + "ledger": self.ledger, + "history": self.history, + "terms": list(self.terms), + } + + def missing_files(self) -> List[str]: + """Referenced paths that do not exist (a warning, not an error).""" + missing: List[str] = [] + for path in ( + self.config, self.policy, self.rules, self.baseline, self.ledger + ): + if path and not os.path.exists(path): + missing.append(path) + for path in self.terms: + if path and not os.path.exists(path): + missing.append(path) + return missing + + +def find_project(start: Optional[str] = None) -> Optional[str]: + """Walk up from ``start`` and return the first project file, or ``None``.""" + current = os.path.abspath(start or os.getcwd()) + while True: + candidate = os.path.join(current, PROJECT_DIR, PROJECT_FILE) + if os.path.isfile(candidate): + return candidate + parent = os.path.dirname(current) + if parent == current: + return None + current = parent + + +def _resolve(root: str, value: str, key: str) -> str: + """Resolve a project-relative path, refusing anything outside ``root``.""" + if not isinstance(value, str) or not value.strip(): + raise ProjectError(f"'{key}' must be a non-empty relative path") + text = value.strip() + if os.path.isabs(text): + raise ProjectError( + f"'{key}' must be relative to the project directory, not absolute: {text}" + ) + resolved = os.path.realpath(os.path.join(root, text)) + real_root = os.path.realpath(root) + if resolved != real_root and not resolved.startswith(real_root + os.sep): + raise ProjectError( + f"'{key}' resolves outside the project directory: {text}" + ) + return resolved + + +def load_project(path: str) -> Project: + """Read and validate one project file.""" + if not os.path.isfile(path): + raise ProjectError(f"no project file at '{path}'") + try: + size = os.path.getsize(path) + except OSError as exc: # pragma: no cover - filesystem edge + raise ProjectError(f"cannot stat '{path}': {exc.strerror or exc}") from exc + if size > MAX_PROJECT_BYTES: + raise ProjectError( + f"project file '{path}' is {size} bytes; the limit is {MAX_PROJECT_BYTES}" + ) + try: + with open(path, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except OSError as exc: + raise ProjectError(f"cannot read '{path}': {exc.strerror or exc}") from exc + except json.JSONDecodeError as exc: + raise ProjectError( + f"'{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + return validate_payload(payload, source=path) + + +def validate_payload(payload: object, source: str = "") -> Project: + """Validate a parsed project document.""" + if not isinstance(payload, dict): + raise ProjectError(f"{source or 'project file'} must be a JSON object") + unknown = set(payload) - ALLOWED_KEYS + if unknown: + raise ProjectError( + f"unknown key(s): {', '.join(sorted(unknown))}; " + f"allowed: {', '.join(sorted(ALLOWED_KEYS))}" + ) + version = payload.get("version", PROJECT_VERSION) + if not isinstance(version, int) or isinstance(version, bool): + raise ProjectError("'version' must be an integer") + if version != PROJECT_VERSION: + raise ProjectError( + f"unsupported project version {version} (this build reads {PROJECT_VERSION})" + ) + root = os.path.dirname(os.path.dirname(os.path.abspath(source))) if source else os.getcwd() + + project = Project(root=root, path=source) + project.name = str(payload.get("project", "") or "")[:64] + project.description = str(payload.get("description", "") or "")[:500] + for key in PATH_KEYS: + raw = payload.get(key) + if raw in (None, ""): + continue + setattr(project, key, _resolve(root, raw, key)) + raw_terms = payload.get("terms", []) + if raw_terms in (None, ""): + raw_terms = [] + if not isinstance(raw_terms, list): + raise ProjectError("'terms' must be an array of relative paths") + if len(raw_terms) > 32: + raise ProjectError("'terms' may list at most 32 packs") + project.terms = [_resolve(root, entry, "terms") for entry in raw_terms] + return project + + +def discover(start: Optional[str] = None, *, enabled: bool = True) -> Optional[Project]: + """Find and load a project, or return ``None`` when there is none.""" + if not enabled: + return None + found = find_project(start) + if found is None: + return None + return load_project(found) + + +# --------------------------------------------------------------------------- +# rendering +# --------------------------------------------------------------------------- +def render_project( + project: Optional[Project], + *, + overridden: Sequence[str] = (), + searched_from: str = "", +) -> str: + """Explain what was found, what it supplies, and what the CLI replaced.""" + lines = ["PathScope project", "=" * 84] + if project is None: + lines.append( + f"No {PROJECT_DIR}/{PROJECT_FILE} found above " + f"{searched_from or os.getcwd()}." + ) + lines.append("") + lines.append( + "Create one to stop repeating flags in a repository (--init-project)." + ) + return "\n".join(lines) + + lines.append(f"Found : {project.path}") + if project.name: + lines.append(f"Project : {project.name}") + if project.description: + lines.append(f"Description : {project.description}") + lines.append("") + supplied = 0 + for label, value in ( + ("config", project.config), + ("policy", project.policy), + ("rules", project.rules), + ("baseline", project.baseline), + ("ledger", project.ledger), + ("history", project.history), + ): + if value: + supplied += 1 + mark = " (overridden by the command line)" if label in overridden else "" + lines.append(f" {label:<10} {value}{mark}") + for path in project.terms: + supplied += 1 + mark = " (overridden by the command line)" if "terms" in overridden else "" + lines.append(f" {'terms':<10} {path}{mark}") + if not supplied: + lines.append(" (the file sets no paths)") + + missing = project.missing_files() + if missing: + lines.append("") + lines.append("Referenced but missing (will be ignored)") + for path in missing: + lines.append(f" {path}") + lines.append("") + lines.append("Command-line values always win; --no-project ignores this file.") + return "\n".join(lines) + + +def starter_project(name: str = "my-project") -> Dict[str, object]: + """The document ``--init-project`` writes.""" + return { + "project": name, + "version": PROJECT_VERSION, + "description": "Shared PathScope settings for this repository.", + "config": "pathscope.json", + "policy": "policy.json", + "terms": ["terms/paths.json"], + } + + +__all__ = [ + "ALLOWED_KEYS", + "LIST_KEYS", + "MAX_PROJECT_BYTES", + "PATH_KEYS", + "PROJECT_DIR", + "PROJECT_FILE", + "PROJECT_VERSION", + "Project", + "ProjectError", + "discover", + "find_project", + "load_project", + "render_project", + "starter_project", + "validate_payload", +] diff --git a/pathscope/query.py b/pathscope/query.py new file mode 100644 index 0000000..0d8e055 --- /dev/null +++ b/pathscope/query.py @@ -0,0 +1,376 @@ +"""Safe report filtering (``--where EXPR``). + +A report is a list of rows and people want slices of it: "high confidence, score +above 60, on the api host, whose rule is a name rule". Rather than adding a +dozen narrow flags, this accepts a small expression: + + --where "score > 60 and confidence = high" + --where "host ~= *.api.test and not status = known" + --where "rule starts_with name- or parameter in file,template" + +Grammar, in full:: + + expr := term (('and' | 'or') term)* + term := ['not'] comparison + comparison := field op value | field op value (',' value)* (in only) + op := '=' | '!=' | '>' | '>=' | '<' | '<=' | '~=' | 'in' + | 'starts_with' | 'ends_with' | 'contains' + value := bare-word | "quoted string" | 'quoted string' + +``and`` binds tighter than ``or``. There are no parentheses, no functions and +no evaluation: the expression is tokenised and parsed into a small tree, and a +fixed set of field accessors is applied to it. ``eval`` is never used, so a +crafted expression cannot execute anything -- it can only filter rows. + +Fields: ``host``, ``resource``, ``parameter``, ``location``, ``rule``, +``confidence``, ``status``, ``method``, ``source``, ``score``, ``occurrences``, +``fingerprint``. + +Errors name the position, because a filter that silently matches nothing is how +people conclude the tool is broken. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Dict, List, Optional, Sequence, Tuple + +from .detector import Finding + + +class QueryError(ValueError): + """Raised when an expression cannot be parsed.""" + + +#: Field names a filter may reference, mapped to how the value is read. +FIELDS: Dict[str, str] = { + "host": "text", + "resource": "text", + "parameter": "text", + "location": "text", + "rule": "text", + "confidence": "text", + "status": "text", + "method": "text", + "source": "text", + "fingerprint": "text", + "score": "number", + "occurrences": "number", +} + +TEXT_OPS = ("=", "!=", "~=", "starts_with", "ends_with", "contains", "in", "not_in") +NUMBER_OPS = ("=", "!=", ">", ">=", "<", "<=") + +_TOKEN = re.compile( + r""" + (?P\s+) + | (?P>=|<=|!=|~=|=|>|<) + | (?P"[^"]*"|'[^']*') + | (?P[A-Za-z0-9_.*:/?=&%+-]+) + | (?P,) + """, + re.VERBOSE, +) + +_KEYWORDS = ("and", "or", "not", "in", "not_in", "starts_with", "ends_with", "contains") + + +@dataclass(frozen=True) +class Token: + kind: str + text: str + position: int + + +@dataclass(frozen=True) +class Comparison: + field: str + op: str + values: Tuple[str, ...] + position: int + + def describe(self) -> str: + return f"{self.field} {self.op} {' '.join(self.values)}" + + +@dataclass(frozen=True) +class Not: + child: "Node" + + +@dataclass(frozen=True) +class And: + children: Tuple["Node", ...] + + +@dataclass(frozen=True) +class Or: + children: Tuple["Node", ...] + + +Node = object # Comparison | Not | And | Or + + +def tokenize(text: str) -> List[Token]: + """Split an expression into tokens, rejecting anything unrecognised.""" + tokens: List[Token] = [] + index = 0 + while index < len(text): + match = _TOKEN.match(text, index) + if not match: + raise QueryError( + f"unexpected character {text[index]!r} at position {index + 1}" + ) + kind = match.lastgroup or "" + value = match.group() + index = match.end() + if kind == "space": + continue + if kind == "quote": + tokens.append(Token("value", value[1:-1], match.start() + 1)) + continue + if kind == "comma": + tokens.append(Token("comma", ",", match.start() + 1)) + continue + if kind == "op": + tokens.append(Token("op", value, match.start() + 1)) + continue + lowered = value.lower() + if lowered in ("and", "or", "not"): + tokens.append(Token(lowered, lowered, match.start() + 1)) + elif lowered in ("in", "not_in", "starts_with", "ends_with", "contains"): + tokens.append(Token("op", lowered, match.start() + 1)) + else: + tokens.append(Token("value", value, match.start() + 1)) + return tokens + + +class _Parser: + def __init__(self, tokens: Sequence[Token], text: str) -> None: + self.tokens = list(tokens) + self.index = 0 + self.text = text + + def peek(self) -> Optional[Token]: + return self.tokens[self.index] if self.index < len(self.tokens) else None + + def next(self) -> Token: + token = self.peek() + if token is None: + raise QueryError( + f"expression ended early; expected more after position " + f"{len(self.text)}" + ) + self.index += 1 + return token + + def parse(self) -> Node: + node = self.parse_or() + leftover = self.peek() + if leftover is not None: + raise QueryError( + f"unexpected '{leftover.text}' at position {leftover.position}" + ) + return node + + def parse_or(self) -> Node: + children = [self.parse_and()] + while True: + token = self.peek() + if token is None or token.kind != "or": + break + self.next() + children.append(self.parse_and()) + return children[0] if len(children) == 1 else Or(tuple(children)) + + def parse_and(self) -> Node: + children = [self.parse_term()] + while True: + token = self.peek() + if token is None or token.kind != "and": + break + self.next() + children.append(self.parse_term()) + return children[0] if len(children) == 1 else And(tuple(children)) + + def parse_term(self) -> Node: + token = self.peek() + if token is not None and token.kind == "not": + self.next() + return Not(self.parse_term()) + return self.parse_comparison() + + def parse_comparison(self) -> Node: + field_token = self.next() + if field_token.kind != "value": + raise QueryError( + f"expected a field name at position {field_token.position}, " + f"found '{field_token.text}'" + ) + field = field_token.text.lower() + if field not in FIELDS: + raise QueryError( + f"unknown field '{field_token.text}' at position " + f"{field_token.position} (known: {', '.join(sorted(FIELDS))})" + ) + op_token = self.next() + if op_token.kind != "op": + raise QueryError( + f"expected an operator after '{field}' at position " + f"{op_token.position}, found '{op_token.text}'" + ) + op = op_token.text + allowed = NUMBER_OPS if FIELDS[field] == "number" else TEXT_OPS + if op not in allowed: + raise QueryError( + f"operator '{op}' cannot be used with '{field}' at position " + f"{op_token.position} (allowed: {', '.join(allowed)})" + ) + values: List[str] = [] + while True: + value_token = self.next() + if value_token.kind != "value": + raise QueryError( + f"expected a value at position {value_token.position}, " + f"found '{value_token.text}'" + ) + values.append(value_token.text) + following = self.peek() + if following is None or following.kind != "comma": + break + self.next() + if op not in ("in", "not_in"): + raise QueryError( + f"comma lists are only valid with 'in' and 'not_in' " + f"(position {following.position})" + ) + if FIELDS[field] == "number": + for value in values: + try: + float(value) + except ValueError: + raise QueryError( + f"'{field}' is numeric but '{value}' is not a number" + ) from None + return Comparison(field=field, op=op, values=tuple(values), position=field_token.position) + + +def parse(text: str) -> Node: + """Parse an expression into a filter tree.""" + if not text or not text.strip(): + raise QueryError("--where needs an expression, e.g. 'score > 60'") + return _Parser(tokenize(text), text).parse() + + +def _text(finding: Finding, field: str) -> str: + if field == "source": + return finding.source_label or "" + if field == "method": + return finding.method or "" + return str(getattr(finding, field, "") or "") + + +def _number(finding: Finding, field: str) -> float: + return float(getattr(finding, field, 0) or 0) + + +def _wildcard(value: str, pattern: str) -> bool: + """``~=``: glob match, case-insensitive, ``*`` and ``?`` only.""" + import fnmatch + + return fnmatch.fnmatch(value.lower(), pattern.lower()) + + +def evaluate(node: Node, finding: Finding) -> bool: + """Apply a parsed filter to one finding.""" + if isinstance(node, Comparison): + if FIELDS[node.field] == "number": + actual = _number(finding, node.field) + wanted = float(node.values[0]) + return { + "=": actual == wanted, + "!=": actual != wanted, + ">": actual > wanted, + ">=": actual >= wanted, + "<": actual < wanted, + "<=": actual <= wanted, + }[node.op] + actual = _text(finding, node.field) + lowered = actual.lower() + wanted = [value.lower() for value in node.values] + if node.op == "=": + return lowered == wanted[0] + if node.op == "!=": + return lowered != wanted[0] + if node.op == "~=": + return _wildcard(actual, node.values[0]) + if node.op == "starts_with": + return lowered.startswith(wanted[0]) + if node.op == "ends_with": + return lowered.endswith(wanted[0]) + if node.op == "contains": + return wanted[0] in lowered + if node.op == "in": + return lowered in wanted + if node.op == "not_in": + return lowered not in wanted + raise QueryError(f"unsupported operator '{node.op}'") # pragma: no cover + if isinstance(node, Not): + return not evaluate(node.child, finding) + if isinstance(node, And): + return all(evaluate(child, finding) for child in node.children) + if isinstance(node, Or): + return any(evaluate(child, finding) for child in node.children) + raise QueryError("invalid filter tree") # pragma: no cover + + +def filter_findings(findings: Sequence[Finding], node: Node) -> List[Finding]: + """Return the findings that satisfy ``node``.""" + return [finding for finding in findings if evaluate(node, finding)] + + +def describe(node: Node) -> str: + """Human-readable rendering, used in the report header.""" + if isinstance(node, Comparison): + return node.describe() + if isinstance(node, Not): + return f"not ({describe(node.child)})" + if isinstance(node, And): + return " and ".join( + f"({describe(child)})" if not isinstance(child, Comparison) else describe(child) + for child in node.children + ) + if isinstance(node, Or): + return " or ".join( + f"({describe(child)})" if not isinstance(child, Comparison) else describe(child) + for child in node.children + ) + return "?" # pragma: no cover + + +def describe_schema() -> Tuple[str, ...]: + """Lines for ``--help``.""" + return ( + ' --where "score > 60 and confidence = high"', + " operators: = != > >= < <= ~= (glob) in starts_with ends_with contains", + " combine with and/or/not; numbers and text are never eval'd.", + ) + + +__all__ = [ + "And", + "Comparison", + "FIELDS", + "Node", + "Not", + "Or", + "QueryError", + "Token", + "describe", + "describe_schema", + "evaluate", + "filter_findings", + "parse", + "tokenize", +] diff --git a/pathscope/queue.py b/pathscope/queue.py new file mode 100644 index 0000000..c294d78 --- /dev/null +++ b/pathscope/queue.py @@ -0,0 +1,228 @@ +"""Prioritised review queue (``--queue``). + +PathScope already sorts by score. That is not a review order: the highest-scoring +row may be the one a human already rejected, and the tenth may be the only +unreviewed one. A queue is the answer to "what should I look at *next*", which +needs three inputs the score alone does not carry: + +* **score** -- how much evidence there is, +* **novelty** -- whether a human has already decided this, +* **leverage** -- how many concrete endpoints a decision here would cover. + +The third matters because of clustering: accepting one family of forty rows is +worth more than deciding a singleton. The queue never decides anything; it only +orders work. + +Nothing here reads a value. It reads scores, statuses, families and ledger +decisions. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +from .detector import Finding +from .families import Family, cluster + +#: Weights for the queue score. They are stated in the output so the ordering +#: is auditable rather than mysterious. +SCORE_WEIGHT = 0.55 +LEVERAGE_WEIGHT = 0.30 +CONFIDENCE_WEIGHT = 0.15 + +CONFIDENCE_VALUE = {"high": 1.0, "medium": 0.7, "low": 0.4} + +#: Statuses that mean "a human has already decided"; they never enter the queue. +SETTLED = ("known", "reviewed") + + +class QueueError(ValueError): + """Raised when a queue cannot be built.""" + + +@dataclass +class QueueItem: + """One row of the queue: a family to decide, with its reasoning.""" + + position: int + family: Family + priority: float + novelty: str + reasons: List[str] = field(default_factory=list) + + @property + def finding(self) -> Finding: + return self.family.best + + def as_dict(self) -> Dict[str, object]: + return { + "position": self.position, + "priority": round(self.priority, 3), + "novelty": self.novelty, + "host": self.family.host, + "route": self.family.route, + "parameter": self.family.parameter, + "location": self.finding.location, + "score": self.family.score, + "confidence": self.family.confidence, + "candidates": self.family.count, + "occurrences": self.family.occurrences, + "reasons": list(self.reasons), + "fingerprints": [member.fingerprint for member in self.family.members], + } + + +def _leverage(family: Family, ceiling: int) -> float: + """0..1: how many endpoints a single decision on this family would cover.""" + if ceiling <= 1: + return 1.0 if family.count > 1 or family.occurrences > 1 else 0.5 + raw = max(family.count, 1) / ceiling + return min(1.0, raw) + + +def build_queue( + findings: Sequence[Finding], + *, + limit: int = 0, + include_known: bool = False, + families: Optional[Sequence[Family]] = None, +) -> List[QueueItem]: + """Order unreviewed work. ``limit`` 0 means every family.""" + if limit < 0: + raise QueueError("queue limit must be 0 (all) or a positive number") + + pending: List[Finding] = [] + for finding in findings: + if not include_known and finding.status in SETTLED: + continue + pending.append(finding) + if not pending: + return [] + + grouped = list(families) if families is not None else cluster(pending) + # A family built from a wider set can contain settled rows; keep only the + # part of it that is still open. + open_rows: List[Family] = [] + for family in grouped: + members = [ + member + for member in family.members + if include_known or member.status not in SETTLED + ] + if not members: + continue + if len(members) != len(family.members): + trimmed = Family( + key=family.key, + host=family.host, + route=family.route, + parameter=family.parameter, + members=members, + ) + open_rows.append(trimmed) + else: + open_rows.append(family) + if not open_rows: + return [] + + ceiling = max(len(family.members) for family in open_rows) + scored: List[Tuple[float, Family, str, List[str]]] = [] + for family in open_rows: + best = family.best + confidence_value = CONFIDENCE_VALUE.get(family.confidence, 0.4) + priority = ( + SCORE_WEIGHT * (family.score / 100.0) + + LEVERAGE_WEIGHT * _leverage(family, ceiling) + + CONFIDENCE_WEIGHT * confidence_value + ) + novelty = "open" if all(m.status == "new" for m in family.members) else "partial" + reasons = [] + reasons.append(f"score {family.score}/100") + if family.count > 1: + reasons.append(f"{family.count} endpoint(s) in one family") + if family.occurrences > family.count: + reasons.append(f"seen {family.occurrences} time(s)") + if family.confidence == "high": + reasons.append("high-confidence evidence") + if novelty == "partial": + reasons.append("some rows settled") + reasons.append(f"primary rule {best.rule}") + scored.append((priority, family, novelty, reasons)) + + scored.sort( + key=lambda item: ( + -item[0], + -item[1].score, + -item[1].count, + item[1].host, + item[1].route, + ) + ) + if limit: + scored = scored[:limit] + return [ + QueueItem( + position=index, + family=family, + priority=priority, + novelty=novelty, + reasons=reasons, + ) + for index, (priority, family, novelty, reasons) in enumerate(scored, start=1) + ] + + +def render_queue(items: Sequence[QueueItem], settled: int = 0, total: int = 0) -> str: + """``--queue`` as text.""" + lines = ["PathScope review queue", "=" * 84] + if not items: + lines.append("Nothing queued: every candidate is either settled or absent.") + return "\n".join(lines) + shown = sum(item.family.count for item in items) + lines.append( + f"{len(items)} item(s) covering {shown} candidate(s)" + + (f" of {total}" if total else "") + + "." + ) + if settled: + lines.append( + f"{settled} candidate(s) already known/reviewed and left out " + "(use --queue-all to include them)." + ) + lines.append("") + for item in items: + family = item.family + lines.append( + f" {item.position:>3}. [{family.score:>3}] {family.host}{family.route}" + f" [{family.location}] {family.parameter}" + f" ({family.confidence}, {family.count} row(s))" + ) + lines.append(f" priority {item.priority:.2f} {item.novelty} " + f"-- {', '.join(item.reasons)}") + lines.append("") + lines.append( + f"Ordering = {SCORE_WEIGHT:.2f}*score + {LEVERAGE_WEIGHT:.2f}*leverage " + f"+ {CONFIDENCE_WEIGHT:.2f}*confidence. Leverage is how many endpoints " + "one decision covers." + ) + lines.append("The queue orders work; it never records a decision.") + return "\n".join(lines) + + +def as_dict(items: Sequence[QueueItem]) -> List[Dict[str, object]]: + return [item.as_dict() for item in items] + + +__all__ = [ + "CONFIDENCE_VALUE", + "QueueError", + "QueueItem", + "SCORE_WEIGHT", + "LEVERAGE_WEIGHT", + "CONFIDENCE_WEIGHT", + "SETTLED", + "as_dict", + "build_queue", + "render_queue", +] diff --git a/pathscope/redact.py b/pathscope/redact.py new file mode 100644 index 0000000..fb91ee5 --- /dev/null +++ b/pathscope/redact.py @@ -0,0 +1,233 @@ +"""Host pseudonymisation (``--redact-hosts``). + +A PathScope report names hosts and paths. That is fine on the machine that took +the capture and not fine in a ticket, a slide, a vendor email or a public issue. + +This module replaces every host with a **stable pseudonym** derived from a +secret, so that: + +* the same host is the same pseudonym throughout a report and across reports + produced with the same secret -- two runs still correlate; +* different hosts never collide by accident; +* without the secret, the mapping cannot be reversed by guessing: the pseudonym + is a truncated keyed digest of the host, not an index into an obvious list, + and not a plain hash of a hostname (which is guessable for a short domain). + +An index-style name (``host-a``, ``host-b``) would be friendlier but leaks +ordering and re-uses names across unrelated runs, so the default is a short +token with an optional ``host-`` prefix and an optional per-run salt for +readability. + +Only hosts are rewritten. Paths, parameter names, scores and fingerprints are +untouched. Fingerprints *do* contain the host, so they are left exactly as they +are and the report states that they are opaque -- changing them would break +every baseline and ledger row. +""" + +from __future__ import annotations + +import hashlib +import hmac +import re +import secrets +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional + +from .detector import Report +from .sources import URLInfo, Request + +#: Prefix for generated pseudonyms. +PREFIX = "host-" +#: Characters of the keyed digest kept: 8 hex chars = 32 bits, plenty to avoid +#: collisions in a single estate, short enough to read in a report. +LENGTH = 8 + +_LOCAL = re.compile(r"^(localhost|127\.0\.0\.1|\[::1\]|::1)$", re.IGNORECASE) + + +class RedactionError(ValueError): + """Raised when redaction cannot be applied safely.""" + + +@dataclass +class HostMap: + """Bidirectional map of real hosts to pseudonyms.""" + + key: bytes + prefix: str = PREFIX + length: int = LENGTH + keep_local: bool = True + forward: Dict[str, str] = field(default_factory=dict) + reverse: Dict[str, str] = field(default_factory=dict) + + def pseudonym(self, host: str) -> str: + """Stable pseudonym for ``host`` (never the host itself).""" + if not host: + return host + if self.keep_local and _LOCAL.match(host): + return host + existing = self.forward.get(host) + if existing is not None: + return existing + digest = hmac.new( + self.key, host.lower().encode("utf-8", "surrogatepass"), hashlib.sha256 + ).hexdigest() + token = digest[: self.length] + # Collisions are improbable but not impossible; walk the digest rather + # than silently mapping two hosts to one name. + offset = self.length + while token in self.reverse and self.reverse[token] != host: + token = digest[offset : offset + self.length] or digest[: self.length] + offset += self.length + if offset >= len(digest): + raise RedactionError( + f"cannot derive a unique pseudonym for '{host}'; " + "use a longer --redact-length" + ) + name = f"{self.prefix}{token}" + self.forward[host] = name + self.reverse[token] = host + return name + + def as_dict(self) -> Dict[str, str]: + """The mapping itself. Only written when explicitly asked for.""" + return dict(sorted(self.forward.items())) + + @property + def count(self) -> int: + return len(self.forward) + + +def build_map( + key: Optional[str] = None, + *, + prefix: str = PREFIX, + length: int = LENGTH, + keep_local: bool = True, +) -> HostMap: + """Create a redaction map. + + With no key a random one is generated for this run: pseudonyms are stable + *within* the report and useless across reports, which is the safe default. + Passing a key makes them stable across runs, at the cost of the key becoming + a secret that grants correlation. + """ + if length < 4 or length > 32: + raise RedactionError("--redact-length must be between 4 and 32") + if prefix and not re.match(r"^[A-Za-z0-9_.-]*$", prefix): + raise RedactionError("--redact-prefix may only contain letters, digits, . _ -") + if key: + material = key.encode("utf-8", "surrogatepass") + else: + material = secrets.token_bytes(32) + return HostMap(key=material, prefix=prefix, length=length, keep_local=keep_local) + + +def _rewrite_resource(resource: str, hostmap: HostMap) -> str: + """Rewrite the host portion of a resource string, keeping the path.""" + if not resource: + return resource + scheme_sep = resource.find("://") + if scheme_sep >= 0: + scheme = resource[:scheme_sep] + rest = resource[scheme_sep + 3 :] + slash = rest.find("/") + authority = rest if slash < 0 else rest[:slash] + tail = "" if slash < 0 else rest[slash:] + userinfo = "" + if "@" in authority: + userinfo, authority = authority.split("@", 1) + userinfo += "@" + host = authority + port = "" + if authority.startswith("["): + close = authority.find("]") + if close > 0: + host = authority[: close + 1] + port = authority[close + 1 :] + elif ":" in authority: + host, _, port_text = authority.partition(":") + port = ":" + port_text + return f"{scheme}://{userinfo}{hostmap.pseudonym(host)}{port}{tail}" + # A bare host/path resource. + slash = resource.find("/") + if slash < 0: + return hostmap.pseudonym(resource) + return hostmap.pseudonym(resource[:slash]) + resource[slash:] + + +def redact_finding(finding, hostmap: HostMap): + """Return a copy of ``finding`` with host and resource redacted.""" + from dataclasses import replace + + return replace( + finding, + host=hostmap.pseudonym(finding.host), + resource=_rewrite_resource(finding.resource, hostmap), + ) + + +def redact_requests( + requests: Iterable[Request], hostmap: HostMap +) -> List[Request]: + """Return copies of requests with redacted URLs (paths kept intact).""" + from dataclasses import replace + + redacted: List[Request] = [] + for request in requests: + url = request.url + new_url = URLInfo( + raw=_rewrite_resource(url.raw, hostmap), + scheme=url.scheme, + host=hostmap.pseudonym(url.host), + port=url.port, + path=url.path, + query=url.query, + ) + redacted.append(replace(request, url=new_url)) + return redacted + + +def redact_report(report: Report, hostmap: HostMap) -> Report: + """Return a copy of ``report`` with every host pseudonymised. + + ``resolved`` entries (from a baseline) are dicts, so they are copied and + rewritten field by field. ``fingerprints`` are deliberately untouched: they + are opaque tokens and rewriting them would invalidate baselines and ledger + rows. The report carries a flag so renderers can say so. + """ + from dataclasses import replace + + findings = [redact_finding(finding, hostmap) for finding in report.findings] + resolved = [] + for entry in report.resolved: + copy = dict(entry) + if isinstance(copy.get("host"), str): + copy["host"] = hostmap.pseudonym(copy["host"]) + if isinstance(copy.get("resource"), str): + copy["resource"] = _rewrite_resource(copy["resource"], hostmap) + resolved.append(copy) + redacted = replace(report, findings=findings, resolved=resolved) + redacted.hosts_redacted = True + return redacted + + +def describe(hostmap: HostMap) -> str: + """One line for the stderr trailer.""" + return ( + f"redacted {hostmap.count} host(s) to stable pseudonyms " + f"(fingerprints are unchanged and remain opaque)" + ) + + +__all__ = [ + "HostMap", + "LENGTH", + "PREFIX", + "RedactionError", + "build_map", + "describe", + "redact_finding", + "redact_report", + "redact_requests", +] diff --git a/pathscope/report.py b/pathscope/report.py new file mode 100644 index 0000000..57f9961 --- /dev/null +++ b/pathscope/report.py @@ -0,0 +1,494 @@ +"""Renderers: readable terminal output, JSON, CSV and SARIF 2.1.0. + +All renderers are deterministic: no timestamps, no hostnames of the analysing +machine, no random ordering. Every string that originates from input passes +through :func:`pathscope.textutil.sanitize_text`, so control characters cannot +reach a terminal or a report. +""" + +from __future__ import annotations + +import csv +import io +import json +from typing import Dict, List + +from . import PROGRAM, __version__ +from .detector import Analysis, Report +from .textutil import encode_display, sanitize_text, truncate + +FORMAT_TEXT = "text" +FORMAT_JSON = "json" +FORMAT_CSV = "csv" +FORMAT_SARIF = "sarif" +FORMAT_MARKDOWN = "markdown" +FORMAT_HTML = "html" +FORMAT_JUNIT = "junit" +FORMATS = ( + FORMAT_TEXT, + FORMAT_JSON, + FORMAT_CSV, + FORMAT_SARIF, + FORMAT_MARKDOWN, + FORMAT_HTML, + FORMAT_JUNIT, +) + +#: Human label for a confidence band (never an exploitability claim). +CONFIDENCE_LABELS = { + "high": "high confidence (textual match)", + "medium": "medium confidence", + "low": "low confidence", +} + + +def confidence_label(confidence: str) -> str: + return CONFIDENCE_LABELS.get(confidence, "low confidence") + +CSV_COLUMNS = ( + "index", + "host", + "source_type", + "source", + "method", + "location", + "parameter", + "rule", + "rules", + "confidence", + "score", + "reasons", + "resource", + "fingerprint", + "status", + "note", + "value", +) + +DISCLAIMER = ( + "Candidates for manual review only. PathScope is passive and offline: it " + "sends no requests, performs no DNS lookups, injects no test values, and " + "never confirms or proves a vulnerability." +) + +TERMINAL_WIDTH = 84 + + +# --------------------------------------------------------------------------- +# Colour helper +# --------------------------------------------------------------------------- +class Palette: + """ANSI colours that are enabled only for interactive terminals.""" + + CODES = { + "bold": "1", + "dim": "2", + "red": "31", + "green": "32", + "yellow": "33", + "blue": "34", + "magenta": "35", + "cyan": "36", + "grey": "90", + } + + def __init__(self, enabled: bool) -> None: + self.enabled = enabled + + def paint(self, style: str, text: str) -> str: + if not self.enabled: + return text + return f"\x1b[{self.CODES[style]}m{text}\x1b[0m" + + +def supports_color(stream) -> bool: + """True only when ``stream`` is a genuine interactive TTY (and TERM is sane).""" + try: + if not stream.isatty(): + return False + except Exception: # pragma: no cover - exotic stream objects + return False + import os + + if os.environ.get("NO_COLOR"): + return False + if os.environ.get("TERM", "") == "dumb": + return False + return True + + +# --------------------------------------------------------------------------- +# Text +# --------------------------------------------------------------------------- +def _group_key(finding, group_by: str) -> str: + if group_by == "host": + return finding.host + if group_by == "rule": + return finding.rule + if group_by == "confidence": + return finding.confidence + if group_by == "location": + return finding.location + return "" + + +def render_text(report: Report, colors: Palette, group_by: str = "none") -> str: + lines: List[str] = [] + heading = "PathScope candidates for manual review" + lines.append(colors.paint("bold", heading)) + lines.append(colors.paint("grey", "=" * TERMINAL_WIDTH)) + lines.append( + f"Analyzed {report.requests_analyzed} request(s) and " + f"{report.parameters_analyzed} parameter(s); " + f"{report.candidate_count} candidate(s) at score >= {report.min_score}." + ) + if report.skipped: + lines.append(colors.paint("yellow", f"Skipped {report.skipped} input line(s) / entries.")) + lines.append("") + + if not report.findings: + lines.append( + colors.paint( + "green", + "No path-like parameter candidates were flagged. " + "This is not proof that the application is safe.", + ) + ) + current_group = None + for finding in report.findings: + if group_by != "none": + key = _group_key(finding, group_by) + if key != current_group: + current_group = key + if group_by == "confidence": + heading_group = f"{key} confidence" + else: + heading_group = key or "(empty)" + lines.append("") + lines.append(colors.paint("bold", f"== {heading_group} ==")) + lines.append("") + band_color = {"high": colors.paint("red", "HIGH"), + "medium": colors.paint("yellow", "MEDIUM"), + "low": colors.paint("cyan", "LOW")}[finding.confidence] + lines.append( + f"#{finding.index} {colors.paint('bold', finding.parameter)} " + f"[{band_color} score {finding.score}/100]" + ) + lines.append(f" {'Host':<12} {finding.host}") + lines.append(f" {'Source':<12} {finding.source_type}" + f" ({truncate(encode_display(finding.source_label), 60)})") + lines.append(f" {'Request':<12} {finding.method} {truncate(encode_display(finding.resource), 110)}") + lines.append(f" {'Location':<12} {finding.location}") + lines.append(f" {'Rule':<12} {finding.rule}") + if finding.occurrences > 1: + lines.append(f" {'Repeats':<12} {finding.occurrences} occurrence(s)") + lines.append(f" {'Fingerprint':<12} {finding.fingerprint}") + if finding.status != "new": + label = finding.status.upper() + note = f" ({finding.note})" if finding.note else "" + lines.append(f" {'Status':<12} {label}{note}") + if report.show_values: + shown = truncate(encode_display(finding.value or ""), 120) + lines.append(f" {'Value':<12} {shown if shown else ''}") + else: + lines.append( + f" {'Value':<12} {colors.paint('grey', '')} " + f"(use --show-values)" + ) + lines.append(f" {'Why':<12} rules and evidence:") + for reason in finding.reasons: + lines.append(f" - {truncate(encode_display(reason), 140)}") + lines.append("") + + if report.mode == "diff": + lines.append( + colors.paint( + "bold", + f"Diff mode: {report.new_count} new, {report.known_count} known, " + f"{len(report.resolved)} resolved (baseline: " + f"{report.baseline_source or 'unspecified'})", + ) + ) + if report.resolved: + lines.append(colors.paint("grey", "Resolved since the baseline:")) + for entry in report.resolved[:50]: + fp = str(entry.get("fingerprint", "")) + parameter = str(entry.get("parameter", "?")) + host = str(entry.get("host", "?")) + lines.append(f" - {encode_display(parameter)} @ {encode_display(host)} ({fp})") + lines.append("") + + lines.append(colors.paint("grey", "Reminder: these are candidates for manual review, not " + "confirmed vulnerabilities. No requests were sent.")) + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# JSON +# --------------------------------------------------------------------------- +def build_json_payload(report: Report) -> Dict[str, object]: + return { + "tool": PROGRAM, + "version": __version__, + "disclaimer": DISCLAIMER, + "passive": True, + "network_requests_made": 0, + "min_score": report.min_score, + "show_values": report.show_values, + "summary": { + "requests_analyzed": report.requests_analyzed, + "parameters_analyzed": report.parameters_analyzed, + "candidates": report.candidate_count, + "confidence": report.confidence_counts, + "skipped": report.skipped, + "sources": list(report.sources), + "mode": report.mode, + "new": report.new_count, + "known": report.known_count, + "resolved": len(report.resolved), + "truncated_entries": report.truncated_entries, + }, + "rules": dict(report.rules), + "rules_source": report.rules_source, + "name_lang": list(report.name_lang), + "stats": dict(report.stats), + "warnings": list(report.warnings), + "findings": [finding.as_dict() for finding in report.findings], + "links": { + "github": "https://github.com/mrdineshpathro", + "instagram": "https://www.instagram.com/mr_dineshpatro", + "support": "https://buymeacoffee.com/mrdineshpathro", + }, + } + + +def render_json(report: Report) -> str: + return json.dumps(build_json_payload(report), indent=2, ensure_ascii=False) + "\n" + + +# --------------------------------------------------------------------------- +# CSV +# --------------------------------------------------------------------------- +def render_csv(report: Report) -> str: + buffer = io.StringIO() + writer = csv.writer(buffer, lineterminator="\n", quoting=csv.QUOTE_MINIMAL) + writer.writerow(CSV_COLUMNS) + for finding in report.findings: + writer.writerow( + [ + finding.index, + finding.host, + finding.source_type, + finding.source_label, + finding.method, + finding.location, + finding.parameter, + finding.rule, + ";".join(finding.rules), + finding.confidence, + finding.score, + "; ".join(finding.reasons), + finding.resource, + finding.fingerprint, + finding.status, + finding.note, + finding.value if report.show_values else "", + ] + ) + return buffer.getvalue() + + +# --------------------------------------------------------------------------- +# SARIF 2.1.0 +# --------------------------------------------------------------------------- +SARIF_LEVELS = {"high": "warning", "medium": "note", "low": "note"} + + +def rule_catalogue(report: Report) -> List[str]: + """All rule ids used by the findings, in deterministic sorted order.""" + return sorted({rule for finding in report.findings for rule in finding.rules}) + + +def sarif_rules(report: Report) -> List[Dict[str, object]]: + """Deterministic rule catalogue built from the findings only.""" + return [ + { + "id": rule, + "name": rule, + "shortDescription": { + "text": f"PathScope heuristic: {rule}", + }, + "help": { + "text": ( + "Heuristic indicator of a path-like request parameter. " + "This is a candidate for manual review, not a vulnerability." + ) + }, + } + for rule in rule_catalogue(report) + ] + + +def render_sarif(report: Report) -> str: + results: List[Dict[str, object]] = [] + catalogue = rule_catalogue(report) + for finding in report.findings: + results.append( + { + "ruleId": finding.rule, + "partialFingerprints": { + "pathscope/v1": finding.fingerprint, + }, + "baselineState": ( + "unchanged" if finding.status == "known" else "new" + ), + **( + { + # A ledger decision is a real suppression: consumers + # such as GitHub code scanning will not re-alert on it. + "suppressions": [ + { + "kind": "external", + "status": "accepted", + "justification": ( + "Reviewed and accepted in the PathScope ledger " + "(fingerprint " + finding.fingerprint + ")." + ), + } + ] + } + if finding.status == "reviewed" + else {} + ), + "ruleIndex": catalogue.index(finding.rule), + "level": SARIF_LEVELS.get(finding.confidence, "note"), + "message": { + "text": ( + f"Parameter '{sanitize_text(finding.parameter)}' in the " + f"{finding.location} of {finding.method} {finding.resource} " + f"looks path-like (heuristic score {finding.score}/100). " + "Candidate for manual review only." + ) + }, + "locations": [ + { + "physicalLocation": { + "artifactLocation": {"uri": sanitize_text(finding.resource)}, + }, + "logicalLocations": [ + {"fullyQualifiedName": sanitize_text(finding.parameter)} + ], + } + ], + "properties": { + "host": finding.host, + "sourceType": finding.source_type, + "location": finding.location, + "method": finding.method, + "parameter": finding.parameter, + "score": finding.score, + "confidence": finding.confidence, + "occurrences": finding.occurrences, + "rules": list(finding.rules), + "reasons": list(finding.reasons), + "valueIncluded": report.show_values, + "fingerprint": finding.fingerprint, + "status": finding.status, + "reviewed": finding.status == "reviewed", + }, + } + ) + + payload = { + "$schema": "https://json.schemastore.org/sarif-2.1.0.json", + "version": "2.1.0", + "runs": [ + { + "tool": { + "driver": { + "name": PROGRAM, + "version": __version__, + "informationUri": "https://github.com/mrdineshpathro", + "semanticVersion": __version__, + "rules": sarif_rules(report), + "properties": { + "passive": True, + "disclaimer": DISCLAIMER, + }, + } + }, + "properties": { + "requestsAnalyzed": report.requests_analyzed, + "parametersAnalyzed": report.parameters_analyzed, + "candidates": report.candidate_count, + "minScore": report.min_score, + }, + "results": results, + } + ], + } + return json.dumps(payload, indent=2, ensure_ascii=False) + "\n" + + +def render(report: Report, output_format: str, colors: Palette) -> str: + from .writers import render_html, render_markdown # local import avoids a cycle + + if output_format == FORMAT_JUNIT: + from .ci import render_junit # local import avoids a cycle + + return render_junit(report) + if output_format == FORMAT_JSON: + return render_json(report) + if output_format == FORMAT_CSV: + return render_csv(report) + if output_format == FORMAT_SARIF: + return render_sarif(report) + if output_format == FORMAT_MARKDOWN: + return render_markdown(report) + if output_format == FORMAT_HTML: + return render_html(report) + return render_text(report, colors) + + +# --------------------------------------------------------------------------- +# Banner +# --------------------------------------------------------------------------- +def render_explanation(analysis: Analysis, colors: Palette, name: str = "") -> str: + """Render one parameter's full scoring trace (``--explain``).""" + lines: List[str] = [] + lines.append(colors.paint("bold", f"Explanation for parameter {name or analysis.name}")) + lines.append(colors.paint("grey", "-" * 64)) + if not analysis.evidence: + lines.append("No rule fired: this parameter is not a candidate at the current threshold.") + return "\n".join(lines) + lines.append(f"{'Score':<12} {analysis.score}/100 ({analysis.confidence})") + lines.append("") + total = 0 + for item in analysis.evidence: + total += item.weight + sign = "+" if item.weight >= 0 else "" + lines.append( + f" {item.rule:<28} {sign}{item.weight:>4} [{item.layer}] {item.reason}" + ) + lines.append("") + lines.append(colors.paint("grey", f"Sum of weights: {total} (clamped to 0-100)")) + if analysis.decode_passes: + lines.append(colors.paint("grey", f"Decoding passes applied: {analysis.decode_passes}")) + return "\n".join(lines) + + +def render_banner(palette: Palette) -> str: + from . import BANNER_LINKS + + lines = [palette.paint("bold", f"{PROGRAM} {__version__} - passive path-parameter triage")] + lines.append(palette.paint("grey", "-" * 64)) + for label, url in BANNER_LINKS: + lines.append(f"{palette.paint('bold', label + ':')} {palette.paint('blue', url)}") + lines.append( + palette.paint( + "yellow", + "Candidates for manual review only. No network requests are made; " + "only analyze data you are authorized to review.", + ) + ) + return "\n".join(lines) diff --git a/pathscope/rules.py b/pathscope/rules.py new file mode 100644 index 0000000..2c7c207 --- /dev/null +++ b/pathscope/rules.py @@ -0,0 +1,445 @@ +"""The PathScope rule registry. + +Every scoring rule lives here with its default weight, the layer it belongs to +(``name`` or ``value``) and a one-line description. The registry is the single +source of truth used by ``--list-rules``, ``--rules overrides.json``, +``--disable-rule``, ``--explain`` and the README. + +Rules are heuristic ranking signals only. None of them is a vulnerability test. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, replace +from typing import Dict, FrozenSet, List, Optional, Sequence, Tuple + +#: ``--list-rules`` group order. +LAYER_NAME = "name" +LAYER_VALUE = "value" + +# --------------------------------------------------------------------------- +# Default weights +# --------------------------------------------------------------------------- +#: Weight for an exact, strong name term. +STRONG_NAME_WEIGHT = 35 +#: Extra weight when a strong term is part of a multiword name (``download_file``). +MULTIWORD_BONUS = 5 +#: Discount for ``name-prefix`` and ``name-suffix`` matches. +PREFIX_DISCOUNT = 7 +SUFFIX_DISCOUNT = 12 +#: Bonus when a generic name (``image``, ``target`` ...) has a path-like value. +GENERIC_BONUS = 10 + + +@dataclass(frozen=True) +class RuleSpec: + """One rule in the registry.""" + + rule: str + layer: str + weight: int + description: str + + +#: Registry order is the order ``--list-rules`` and ``--explain`` use inside a +#: layer; it is stable so output is deterministic. +DEFAULT_RULES: Tuple[RuleSpec, ...] = ( + # --- name layer ------------------------------------------------------- + RuleSpec( + "name-custom", + LAYER_NAME, + 30, + "exact user-configured term from the configuration file", + ), + RuleSpec( + "name-exact", + LAYER_NAME, + STRONG_NAME_WEIGHT, + "parameter name contains a built-in path-related term (+multiword bonus)", + ), + RuleSpec( + "name-compound", + LAYER_NAME, + STRONG_NAME_WEIGHT, + "the whole name is a known path compound", + ), + RuleSpec( + "name-prefix", + LAYER_NAME, + STRONG_NAME_WEIGHT - PREFIX_DISCOUNT, + "name starts with a path-related term (filedata)", + ), + RuleSpec( + "name-suffix", + LAYER_NAME, + STRONG_NAME_WEIGHT - SUFFIX_DISCOUNT, + "name ends with a path-related term (userfile)", + ), + RuleSpec( + "name-generic", + LAYER_NAME, + 0, + "generic name (image/target/ref); only counts with a path-like value", + ), + RuleSpec( + "name-weak", + LAYER_NAME, + 5, + "multiword name without a path term (never enough on its own)", + ), + RuleSpec( + "name-folded", + LAYER_NAME, + 20, + "name matches a path term only after diacritic/compatibility folding", + ), + RuleSpec( + "name-leet", + LAYER_NAME, + 12, + "name matches a path term only after leet expansion (f1le -> file)", + ), + RuleSpec( + "name-i18n", + LAYER_NAME, + 25, + "name contains a path term from another language", + ), + RuleSpec( + "name-i18n-fold", + LAYER_NAME, + 21, + "non-English term matched only after diacritic folding", + ), + # --- value layer ------------------------------------------------------ + RuleSpec( + "value-traversal", + LAYER_VALUE, + 30, + "'..' used as a path segment", + ), + RuleSpec( + "value-encoded-traversal", + LAYER_VALUE, + 15, + "'..' segment appears only after percent-decoding", + ), + RuleSpec( + "value-encoded-slash", + LAYER_VALUE, + 12, + "encoded slash/backslash (%2f / %5c)", + ), + RuleSpec( + "value-double-encoded", + LAYER_VALUE, + 10, + "two or more decoding passes were required", + ), + RuleSpec( + "value-windows-drive", + LAYER_VALUE, + 15, + "looks like a Windows drive path (C:\\...)", + ), + RuleSpec( + "value-unc", + LAYER_VALUE, + 15, + "looks like a UNC path (\\\\server\\share)", + ), + RuleSpec( + "value-absolute", + LAYER_VALUE, + 12, + "starts with a path separator (absolute-looking)", + ), + RuleSpec( + "value-multi-segment", + LAYER_VALUE, + 6, + "two or more path separators", + ), + RuleSpec( + "value-extension", + LAYER_VALUE, + 8, + "ends with a known file-like extension", + ), + RuleSpec( + "value-path-list", + LAYER_VALUE, + 5, + "semicolon/comma separated list of paths", + ), + RuleSpec( + "value-pairs-with-generic-name", + LAYER_VALUE, + GENERIC_BONUS, + "generic parameter name paired with a path-like value", + ), + RuleSpec( + "value-full-url", + LAYER_VALUE, + -10, + "a full URL rather than a local path", + ), + # --- value-shape demotion -------------------------------------------- + RuleSpec( + "value-demote-uuid", + LAYER_VALUE, + -20, + "value is a UUID", + ), + RuleSpec( + "value-demote-hash", + LAYER_VALUE, + -18, + "value is a hex digest or long hex string", + ), + RuleSpec( + "value-demote-jwt", + LAYER_VALUE, + -20, + "value is a JWT (three base64url segments)", + ), + RuleSpec( + "value-demote-base64", + LAYER_VALUE, + -12, + "value is a base64 blob", + ), + RuleSpec( + "value-demote-email", + LAYER_VALUE, + -8, + "value is an e-mail address", + ), + RuleSpec( + "value-demote-ip", + LAYER_VALUE, + -10, + "value is an IP address", + ), + RuleSpec( + "value-demote-scalar", + LAYER_VALUE, + -10, + "value is a bool, number or short enum-like token", + ), +) + +RULE_INDEX: Dict[str, RuleSpec] = {spec.rule: spec for spec in DEFAULT_RULES} +RULE_NAMES: Tuple[str, ...] = tuple(spec.rule for spec in DEFAULT_RULES) + +#: Rule ids that may never be overridden to a positive number that inverts +#: their meaning: demotions must stay non-positive. +DEMOTION_PREFIX = "value-demote-" + +#: Bounds for a user-supplied weight. +MIN_WEIGHT = -100 +MAX_WEIGHT = 100 + +#: Upper bound on overrides in one file, so a hostile file cannot be huge. +MAX_OVERRIDES = 200 + + +class RuleError(ValueError): + """Raised when a rule override file is invalid.""" + + +@dataclass(frozen=True) +class RuleBook: + """The effective weights for one run. + + ``weights`` maps every known rule id to its weight; rules missing from a + user override file keep their default. ``disabled`` holds rule ids removed + from scoring entirely (they also disappear from ``--explain``). + """ + + weights: Dict[str, int] + disabled: FrozenSet[str] = frozenset() + source: str = "" + + # -- construction ----------------------------------------------------- + @classmethod + def default(cls) -> "RuleBook": + return cls(weights={spec.rule: spec.weight for spec in DEFAULT_RULES}) + + @classmethod + def with_overrides( + cls, + overrides: Optional[Dict[str, int]] = None, + disabled: Sequence[str] = (), + source: str = "", + ) -> "RuleBook": + """Validate and apply explicit weights plus a disabled set.""" + book = cls.default() + weights = dict(book.weights) + for rule, weight in (overrides or {}).items(): + if rule not in RULE_INDEX: + raise RuleError(f"unknown rule '{rule}' (see --list-rules)") + if isinstance(weight, bool) or not isinstance(weight, int): + raise RuleError(f"weight for '{rule}' must be an integer") + if not MIN_WEIGHT <= weight <= MAX_WEIGHT: + raise RuleError( + f"weight for '{rule}' must be between {MIN_WEIGHT} and {MAX_WEIGHT}" + ) + if rule.startswith(DEMOTION_PREFIX) and weight > 0: + raise RuleError( + f"'{rule}' is a demotion rule and may not have a positive weight" + ) + weights[rule] = weight + disabled_set = frozenset(name.strip().lower() for name in disabled if name) + for rule in disabled_set: + if rule not in RULE_INDEX: + raise RuleError(f"unknown rule '{rule}' (see --list-rules)") + return cls(weights=weights, disabled=disabled_set, source=source) + + # -- queries ---------------------------------------------------------- + def weight(self, rule: str) -> int: + """Effective weight (0 when the rule is disabled or unknown).""" + if rule in self.disabled: + return 0 + return self.weights.get(rule, RULE_INDEX[rule].weight if rule in RULE_INDEX else 0) + + def is_disabled(self, rule: str) -> bool: + return rule in self.disabled + + def default_weight(self, rule: str) -> int: + spec = RULE_INDEX.get(rule) + return spec.weight if spec else 0 + + def overridden(self) -> List[str]: + """Rule ids whose effective weight differs from the default.""" + return [ + rule + for rule in RULE_NAMES + if rule not in self.disabled and self.weights.get(rule) != self.default_weight(rule) + ] + + def enabled_specs(self) -> List[RuleSpec]: + return [spec for spec in DEFAULT_RULES if spec.rule not in self.disabled] + + def as_dict(self) -> Dict[str, int]: + return {spec.rule: self.weight(spec.rule) for spec in DEFAULT_RULES} + + def clone(self) -> "RuleBook": + return replace(self, weights=dict(self.weights)) + + +#: The book used when the user passes nothing. +DEFAULT_BOOK = RuleBook.default() + + +# --------------------------------------------------------------------------- +# --rules FILE parsing +# --------------------------------------------------------------------------- +def parse_rule_payload(payload: object) -> Dict[str, int]: + """Accept ``{"weights": {...}, "disable": [...]}`` or a bare weight map.""" + if not isinstance(payload, dict): + raise RuleError("rule overrides must be a JSON object") + raw_weights = payload.get("weights", None) + if raw_weights is None: + # A bare mapping of rule -> weight is also accepted. + raw_weights = { + key: value + for key, value in payload.items() + if key not in ("disable", "tool", "version", "note") + } + if not isinstance(raw_weights, dict): + raise RuleError("'weights' must be a JSON object of rule -> integer") + if len(raw_weights) > MAX_OVERRIDES: + raise RuleError(f"at most {MAX_OVERRIDES} weight overrides are allowed") + weights: Dict[str, int] = {} + for rule, weight in raw_weights.items(): + if not isinstance(rule, str): + raise RuleError("rule ids must be strings") + weights[rule.strip()] = weight # validated by RuleBook.with_overrides + disabled = payload.get("disable", []) + if isinstance(disabled, str): + disabled = [disabled] + if not isinstance(disabled, list) or not all(isinstance(x, str) for x in disabled): + raise RuleError("'disable' must be an array of rule ids") + # ``disable`` entries are validated and applied by RuleBook.with_overrides. + return weights + + +def load_rule_overrides(path: str) -> Tuple[Dict[str, int], List[str]]: + """Read a ``--rules`` file. Raises :class:`RuleError`.""" + try: + with open(path, "r", encoding="utf-8-sig") as handle: + raw = handle.read() + except OSError as exc: + raise RuleError(f"cannot read rule overrides '{path}': {exc.strerror or exc}") from exc + try: + payload = json.loads(raw) + except json.JSONDecodeError as exc: + raise RuleError( + f"rule overrides '{path}' are not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + weights = parse_rule_payload(payload) + disabled = payload.get("disable", []) if isinstance(payload, dict) else [] + if isinstance(disabled, str): + disabled = [disabled] + return weights, [str(item) for item in disabled] + + +def normalize_rule_id(name: str) -> str: + """Map a friendly alias onto a rule id (``traversal`` -> ``value-traversal``).""" + key = (name or "").strip().lower() + if key in RULE_INDEX: + return key + if f"value-{key}" in RULE_INDEX: + return f"value-{key}" + if f"name-{key}" in RULE_INDEX: + return f"name-{key}" + if f"value-demote-{key}" in RULE_INDEX: + return f"value-demote-{key}" + return key + + +def format_rule_table(book: Optional[RuleBook] = None) -> List[str]: + """Lines for ``--list-rules``: id, effective weight, default, description.""" + book = book or DEFAULT_BOOK + lines: List[str] = [] + for layer in (LAYER_NAME, LAYER_VALUE): + lines.append(f"{layer} rules:") + for spec in DEFAULT_RULES: + if spec.layer != layer: + continue + effective = book.weight(spec.rule) + if spec.rule in book.disabled: + weight = "off" + elif effective != spec.weight: + weight = f"{effective:+d} (default {spec.weight:+d})" + else: + weight = f"{spec.weight:+d}" + lines.append(f" {spec.rule:<28} {weight:<22} {spec.description}") + lines.append("") + lines.append("Weights are heuristic ranking points, not exploitability scores.") + lines.append("Change them with --rules FILE or remove them with --disable-rule RULE.") + return lines + + +__all__ = [ + "DEFAULT_RULES", + "DEFAULT_BOOK", + "RuleSpec", + "RuleBook", + "RuleError", + "RULE_INDEX", + "RULE_NAMES", + "format_rule_table", + "load_rule_overrides", + "normalize_rule_id", + "parse_rule_payload", + "STRONG_NAME_WEIGHT", + "MULTIWORD_BONUS", + "PREFIX_DISCOUNT", + "SUFFIX_DISCOUNT", + "GENERIC_BONUS", + "LAYER_NAME", + "LAYER_VALUE", +] diff --git a/pathscope/sampling.py b/pathscope/sampling.py new file mode 100644 index 0000000..89f8773 --- /dev/null +++ b/pathscope/sampling.py @@ -0,0 +1,215 @@ +"""Deterministic sampling (``--sample N --sample-seed K``). + +A capture with 40,000 entries takes a while and produces a report nobody reads. +Analysing a subset is reasonable; analysing a *different* subset every run is +not, because then two people comparing notes are describing different data and +a trend line measures the sampler rather than the application. + +This module samples **deterministically**: each request is hashed together with +a seed, and the lowest hashes are kept. That gives + +* the same subset for the same seed on every machine and every Python version + (it uses SHA-256, not ``hash()``, whose value is randomised per process), +* an even spread across hosts and sources rather than "the first 200 lines", +* stability under growth: adding entries to a capture adds candidates, it does + not reshuffle the ones already chosen. + +The selection is stratified by *stratum key* (host by default) so a busy host +cannot crowd out a quiet one. Each stratum gets a share of the budget that is +proportional to its size, with at least one slot where possible -- a host with +two entries in a 10,000-entry capture is still the host nobody has looked at. + +Selection is by hash, never by value: no parameter value influences sampling. +""" + +from __future__ import annotations + +import hashlib +import math +from dataclasses import dataclass, field +from typing import Dict, List, Sequence, Tuple + +from .sources import Request + +#: Accepts ``--sample-seed``; any integer keeps runs reproducible. +DEFAULT_SEED = 1 +MAX_SEED = 2**32 - 1 + + +class SamplingError(ValueError): + """Raised when a sample cannot be drawn.""" + + +@dataclass +class SampleResult: + """The chosen requests plus the bookkeeping a report needs.""" + + requests: List[Request] = field(default_factory=list) + population: int = 0 + requested: int = 0 + seed: int = DEFAULT_SEED + strata: Dict[str, int] = field(default_factory=dict) + + @property + def size(self) -> int: + return len(self.requests) + + @property + def coverage(self) -> float: + """Share of the population actually analysed (0..1).""" + return self.size / self.population if self.population else 0.0 + + @property + def taken_everything(self) -> bool: + return self.size >= self.population + + def describe(self) -> str: + return ( + f"sampled {self.size} of {self.population} request(s) " + f"({self.coverage:.1%}) with seed {self.seed} across " + f"{len(self.strata)} stratum/strata" + ) + + def as_dict(self) -> Dict[str, object]: + return { + "seed": self.seed, + "requested": self.requested, + "population": self.population, + "selected": self.size, + "coverage": round(self.coverage, 4), + "strata": dict(sorted(self.strata.items())), + } + + +def _rank(request: Request, seed: int) -> int: + """Stable per-request rank: SHA-256 of seed + identity. + + Identity deliberately excludes values and scores, so sampling cannot be + steered by the data being sampled. + """ + material = "\x1f".join( + ( + str(seed), + request.source_type, + request.source_label, + request.method, + request.url.host.lower(), + request.url.path or "/", + request.url.query, + str(request.index), + ) + ) + return int.from_bytes( + hashlib.sha256(material.encode("utf-8", "surrogatepass")).digest()[:8], "big" + ) + + +def _stratum(request: Request, by: str) -> str: + if by == "source": + return request.source_label or "(none)" + if by == "none": + return "" + return request.url.host.lower() or "(no host)" + + +def _allocate(sizes: Dict[str, int], budget: int) -> Dict[str, int]: + """Largest-remainder apportionment of ``budget`` across strata. + + Proportional, but every non-empty stratum gets one slot when the budget + allows it -- a rare host is exactly the one worth looking at. + """ + total = sum(sizes.values()) + if total == 0 or budget <= 0: + return {key: 0 for key in sizes} + keys = sorted(sizes) + if budget >= len(keys): + # Guarantee one each, then share the rest proportionally. + allocation = {key: 1 for key in keys} + remaining = budget - len(keys) + sizes_after = {key: max(0, sizes[key] - 1) for key in keys} + total_after = sum(sizes_after.values()) + else: + allocation = {key: 0 for key in keys} + remaining = budget + sizes_after = dict(sizes) + total_after = total + + if remaining > 0 and total_after > 0: + quotas = {key: remaining * sizes_after[key] / total_after for key in keys} + floors = {key: int(math.floor(quotas[key])) for key in keys} + for key in keys: + allocation[key] += floors[key] + used = sum(floors.values()) + leftover = remaining - used + # Largest remainder gets the crumbs, ties broken by key for stability. + order = sorted(keys, key=lambda key: (-(quotas[key] - floors[key]), key)) + for key in order[: max(0, leftover)]: + allocation[key] += 1 + + # Never allocate more than a stratum holds. + for key in keys: + allocation[key] = min(allocation[key], sizes[key]) + return allocation + + +def sample( + requests: Sequence[Request], + size: int, + *, + seed: int = DEFAULT_SEED, + by: str = "host", +) -> SampleResult: + """Draw a deterministic stratified sample of ``size`` requests.""" + if size < 0: + raise SamplingError("--sample must be 0 (all) or a positive number") + if not 0 <= int(seed) <= MAX_SEED: + raise SamplingError(f"--sample-seed must be between 0 and {MAX_SEED}") + if by not in ("host", "source", "none"): + raise SamplingError(f"unknown sampling stratum '{by}'") + + population = len(requests) + result = SampleResult(population=population, requested=size, seed=int(seed)) + if size == 0 or size >= population: + result.requests = list(requests) + for request in result.requests: + key = _stratum(request, by) + result.strata[key] = result.strata.get(key, 0) + 1 + return result + + buckets: Dict[str, List[Request]] = {} + for request in requests: + buckets.setdefault(_stratum(request, by), []).append(request) + sizes = {key: len(bucket) for key, bucket in buckets.items()} + allocation = _allocate(sizes, size) + + chosen: List[Request] = [] + for key in sorted(buckets): + take = allocation.get(key, 0) + if take <= 0: + continue + ranked = sorted(buckets[key], key=lambda item: _rank(item, int(seed))) + chosen.extend(ranked[:take]) + result.strata[key] = take + # Restore input order so the report reads like the capture, not like a hash. + chosen.sort(key=lambda item: item.index) + result.requests = chosen + return result + + +def describe_sampling() -> Tuple[str, ...]: + """Lines for ``--help``/README.""" + return ( + " --sample N analyse a deterministic subset of N requests", + " --sample-seed K the subset is identical for the same seed", + " --sample-by KEY stratify by host (default), source, or none", + ) + + +__all__ = [ + "DEFAULT_SEED", + "MAX_SEED", + "SampleResult", + "SamplingError", + "describe_sampling", + "sample", +] diff --git a/pathscope/scope.py b/pathscope/scope.py new file mode 100644 index 0000000..c238fd0 --- /dev/null +++ b/pathscope/scope.py @@ -0,0 +1,255 @@ +"""Authorization scope file (``--scope-file``). + +A scan is only meaningful inside the boundary somebody was allowed to name. +This module reads a small JSON file that declares that boundary, and applies it +**before analysis**, so out-of-scope requests are never turned into findings in +the first place: + + { + "scope": "acme-api assessment", + "in_scope": ["api.acme.test", "*.acme.test", "acme.test/app/*"], + "out_of_scope": ["legacy.acme.test", "*.vendor.test"] + } + +Rules, in plain language: + +* a pattern with a ``/`` matches against ``host/path``; +* a pattern without one matches only the host; +* ``*`` matches one label or one path segment, ``**`` matches any number; +* ``out_of_scope`` always wins over ``in_scope`` -- doubt resolves to exclusion; +* an empty ``in_scope`` list means "everything not explicitly excluded"; +* a file that declares neither list is rejected rather than treated as + "everything is in scope", because that is the one failure mode that could + turn a typo into unauthorised work. + +The scope file is *not* a security control against a hostile input; it is an +intent control that keeps an honest run honest. It also never authorises +anything: holding a scope file is not permission to test. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Dict, List, Sequence, Tuple + +from .sources import Request + +SCOPE_KEYS = ("scope", "description", "in_scope", "out_of_scope", "version") +SCOPE_VERSION = 1 + +#: Upper bound so a silly file cannot make matching quadratic in practice. +MAX_PATTERNS = 500 + + +class ScopeError(ValueError): + """Raised when a scope file cannot be read or is not usable.""" + + +def _compile(pattern: str) -> "re.Pattern": + """Translate a scope glob into an anchored regular expression. + + ``*`` one host label or one path segment (never a ``.`` or ``/``) + ``**`` anything, including separators + + A single ``*`` must not cross a dot in a host pattern, or ``*.a.test`` + would silently cover ``deep.api.a.test`` -- a much wider boundary than the + one somebody wrote down. + """ + single = "[^/]*" if "/" in pattern else "[^/.]*" + parts: List[str] = [] + index = 0 + while index < len(pattern): + char = pattern[index] + if char == "*": + if index + 1 < len(pattern) and pattern[index + 1] == "*": + parts.append(".*") + index += 2 + continue + parts.append(single) + index += 1 + continue + parts.append(re.escape(char)) + index += 1 + return re.compile("^" + "".join(parts) + "$", re.IGNORECASE) + + +@dataclass(frozen=True) +class Pattern: + """One in-scope or out-of-scope entry.""" + + text: str + matches_path: bool + regex: "re.Pattern" = field(repr=False, compare=False) + + def matches(self, host: str, path: str) -> bool: + subject = f"{host}{path}" if self.matches_path else host + return bool(self.regex.match(subject)) + + +def _make_pattern(text: str) -> Pattern: + cleaned = (text or "").strip() + if not cleaned: + raise ScopeError("scope patterns must not be empty") + if cleaned.startswith(("http://", "https://")): + raise ScopeError( + f"scope pattern '{cleaned}' must be a host or host/path, not a URL" + ) + cleaned = cleaned.rstrip("/") + return Pattern( + text=cleaned, + matches_path="/" in cleaned, + regex=_compile(cleaned), + ) + + +@dataclass +class Scope: + """A parsed scope file.""" + + name: str = "" + in_scope: List[Pattern] = field(default_factory=list) + out_of_scope: List[Pattern] = field(default_factory=list) + source: str = "" + + def decision(self, host: str, path: str = "/") -> Tuple[bool, str]: + """``(allowed, reason)`` for one host/path pair.""" + for pattern in self.out_of_scope: + if pattern.matches(host, path): + return False, f"matches out-of-scope pattern '{pattern.text}'" + if not self.in_scope: + return True, "nothing excluded and no in-scope list given" + for pattern in self.in_scope: + if pattern.matches(host, path): + return True, f"matches in-scope pattern '{pattern.text}'" + return False, "no in-scope pattern matched" + + def allows(self, host: str, path: str = "/") -> bool: + return self.decision(host, path)[0] + + +def load_scope(path: str) -> Scope: + """Read and validate a scope file. Raises :class:`ScopeError`.""" + try: + with open(path, "r", encoding="utf-8-sig") as handle: + raw = handle.read() + except OSError as exc: + raise ScopeError(f"cannot read scope file '{path}': {exc.strerror or exc}") from exc + try: + payload = json.loads(raw) + except json.JSONDecodeError as exc: + raise ScopeError( + f"scope file '{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + return from_payload(payload, source=path) + + +def from_payload(payload: object, source: str = "") -> Scope: + """Validate a decoded scope payload.""" + if not isinstance(payload, dict): + raise ScopeError("a scope file must be a JSON object") + unknown = [key for key in payload if key not in SCOPE_KEYS] + if unknown: + raise ScopeError( + "unknown key(s) in scope file: " + + ", ".join(sorted(unknown)) + + f" (accepted: {', '.join(SCOPE_KEYS)})" + ) + version = payload.get("version", SCOPE_VERSION) + if version != SCOPE_VERSION: + raise ScopeError(f"unsupported scope version {version!r} (expected {SCOPE_VERSION})") + + def patterns(key: str) -> List[Pattern]: + value = payload.get(key, []) + if value is None: + value = [] + if isinstance(value, str): + raise ScopeError(f"'{key}' must be a list of patterns, not a string") + if not isinstance(value, list): + raise ScopeError(f"'{key}' must be a list of patterns") + if len(value) > MAX_PATTERNS: + raise ScopeError(f"'{key}' has {len(value)} patterns (limit {MAX_PATTERNS})") + result: List[Pattern] = [] + for entry in value: + if not isinstance(entry, str): + raise ScopeError(f"'{key}' entries must be strings") + result.append(_make_pattern(entry)) + return result + + scope = Scope( + name=str(payload.get("scope") or payload.get("description") or ""), + in_scope=patterns("in_scope"), + out_of_scope=patterns("out_of_scope"), + source=source, + ) + if not scope.in_scope and not scope.out_of_scope: + raise ScopeError( + f"scope file '{source or ''}' declares no in_scope or " + "out_of_scope patterns; an empty scope would silently mean " + "'everything', which is not a decision this tool will make for you" + ) + return scope + + +def apply_scope(requests: Sequence[Request], scope: Scope) -> Tuple[List[Request], Dict[str, int]]: + """Split requests into kept and dropped, counting reasons.""" + kept: List[Request] = [] + dropped = 0 + reasons: Dict[str, int] = {} + for request in requests: + allowed, reason = scope.decision(request.url.host, request.url.path or "/") + if allowed: + kept.append(request) + continue + dropped += 1 + reasons[reason] = reasons.get(reason, 0) + 1 + summary = {"kept": len(kept), "dropped": dropped, "total": len(requests)} + return kept, {**summary, **{f"reason:{k}": v for k, v in reasons.items()}} + + +def describe_drop(summary: Dict[str, int], scope: Scope) -> str: + """One-line, never-silent description of what the scope removed.""" + name = f" '{scope.name}'" if scope.name else "" + return ( + f"scope{name}: kept {summary.get('kept', 0)} of {summary.get('total', 0)} " + f"request(s); dropped {summary.get('dropped', 0)} out of scope" + ) + + +def starter_scope() -> str: + """Contents written by ``--init-scope``.""" + return ( + "{\n" + ' "scope": "replace with the assessment name",\n' + ' "version": 1,\n' + ' "in_scope": ["app.example.test"],\n' + ' "out_of_scope": ["*.vendor.test", "status.example.test"]\n' + "}\n" + ) + + +def describe_schema() -> Tuple[str, ...]: + """Lines for ``--help``/README.""" + return ( + ' {"scope": "name", "in_scope": ["host", "*.host", "host/path/*"],', + ' "out_of_scope": ["legacy.host"], "version": 1}', + " out_of_scope wins; * is one label or segment; ** is any number.", + " a scope file records intent, it does not grant authorisation.", + ) + + +__all__ = [ + "MAX_PATTERNS", + "Pattern", + "SCOPE_KEYS", + "SCOPE_VERSION", + "Scope", + "ScopeError", + "apply_scope", + "describe_drop", + "describe_schema", + "from_payload", + "load_scope", + "starter_scope", +] diff --git a/pathscope/scorechange.py b/pathscope/scorechange.py new file mode 100644 index 0000000..a497bea --- /dev/null +++ b/pathscope/scorechange.py @@ -0,0 +1,307 @@ +"""Score-change explanation (``--explain-diff OLD.json NEW.json``). + +``--baseline`` answers "which findings are new". That is the question CI asks. +The question a maintainer asks after tuning is different: *the finding did not +appear or disappear -- why did its score move?* + +Two JSON reports carry enough to answer that: each finding records its score, +its rules and its reasons. Where a reason is a signed contribution, the +difference between the two reason lists names the exact rule whose evidence +changed. Where only rule ids are available, that is all this claims. + + pathscope -i before.har --format json > before.json + pathscope -i after.har --format json > after.json + pathscope --explain-diff before.json after.json + +Identity is (host, path, parameter, location), the same tuple that survives +edits to values and source labels. A finding present in both is *tracked*, even +when its rule changed. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from typing import Dict, List, Sequence, Tuple +from urllib.parse import urlsplit + +from .heuristics import canonical_name + + +class ScoreDiffError(ValueError): + """Raised when a report cannot be read or is not a PathScope JSON report.""" + + +#: ``"... term 'file' (+35)"`` -- the signed contribution at the end of a reason. +_CONTRIBUTION = re.compile(r"\((?P[+-]\d+)\)\s*$") + + +@dataclass(frozen=True) +class Reading: + """One finding as it appears in a saved JSON report.""" + + key: Tuple[str, str, str, str] + host: str + resource: str + parameter: str + location: str + score: int + confidence: str + rule: str + rules: Tuple[str, ...] + reasons: Tuple[str, ...] + + @property + def label(self) -> str: + path = _path_of(self.resource) + return f"{self.host}{path} [{self.location}] {self.parameter}" + + +@dataclass +class Change: + """A tracked finding whose score moved.""" + + before: Reading + after: Reading + gained: List[str] = field(default_factory=list) + lost: List[str] = field(default_factory=list) + points: int = 0 + + @property + def delta(self) -> int: + return self.after.score - self.before.score + + def as_dict(self) -> Dict[str, object]: + return { + "host": self.after.host, + "resource": self.after.resource, + "parameter": self.after.parameter, + "location": self.after.location, + "before": self.before.score, + "after": self.after.score, + "delta": self.delta, + "confidence_before": self.before.confidence, + "confidence_after": self.after.confidence, + "gained": list(self.gained), + "lost": list(self.lost), + "rule_before": self.before.rule, + "rule_after": self.after.rule, + } + + +@dataclass +class ScoreDiff: + """Everything that changed between two JSON reports.""" + + before_label: str = "" + after_label: str = "" + before_count: int = 0 + after_count: int = 0 + tracked: int = 0 + changed: List[Change] = field(default_factory=list) + added: List[Reading] = field(default_factory=list) + removed: List[Reading] = field(default_factory=list) + + @property + def unchanged(self) -> int: + return self.tracked - len(self.changed) + + def as_dict(self) -> Dict[str, object]: + return { + "before": {"source": self.before_label, "findings": self.before_count}, + "after": {"source": self.after_label, "findings": self.after_count}, + "tracked": self.tracked, + "changed": [change.as_dict() for change in self.changed], + "added": [reading.label for reading in self.added], + "removed": [reading.label for reading in self.removed], + } + + +def _path_of(resource: str) -> str: + parts = urlsplit(resource or "/") + if parts.scheme or parts.netloc: + return parts.path or "/" + return (resource or "/").split("?", 1)[0] or "/" + + +def _key(entry: Dict[str, object]) -> Tuple[str, str, str, str]: + return ( + str(entry.get("host") or "").lower(), + _path_of(str(entry.get("resource") or "")), + str(entry.get("location") or ""), + canonical_name(str(entry.get("parameter") or "")), + ) + + +def _read(path: str) -> Dict[str, Reading]: + try: + with open(path, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except OSError as exc: + raise ScoreDiffError(f"cannot read report '{path}': {exc.strerror or exc}") from exc + except json.JSONDecodeError as exc: + raise ScoreDiffError( + f"report '{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + if not isinstance(payload, dict) or "findings" not in payload: + raise ScoreDiffError( + f"'{path}' is not a PathScope JSON report (no 'findings' array). " + "Produce one with --format json." + ) + findings = payload.get("findings") + if not isinstance(findings, list): + raise ScoreDiffError(f"'{path}' has a non-array 'findings' field") + readings: Dict[Tuple[str, str, str, str], Reading] = {} + for entry in findings: + if not isinstance(entry, dict): + continue + key = _key(entry) + if key in readings: + # Two rows for one identity: keep the higher score so the diff is + # about the finding, not about which duplicate came first. + if int(entry.get("score") or 0) <= readings[key].score: + continue + readings[key] = Reading( + key=key, + host=str(entry.get("host") or ""), + resource=str(entry.get("resource") or ""), + parameter=str(entry.get("parameter") or ""), + location=str(entry.get("location") or ""), + score=int(entry.get("score") or 0), + confidence=str(entry.get("confidence") or ""), + rule=str(entry.get("rule") or ""), + rules=tuple(str(rule) for rule in (entry.get("rules") or [])), + reasons=tuple(str(reason) for reason in (entry.get("reasons") or [])), + ) + return readings + + +def _contributions(reasons: Sequence[str]) -> Dict[str, int]: + """Map reason text (without its score) to the signed contribution.""" + result: Dict[str, int] = {} + for reason in reasons: + match = _CONTRIBUTION.search(reason) + if not match: + continue + text = _CONTRIBUTION.sub("", reason).strip() + result[text] = int(match.group("sign")) + return result + + +def compare(before_path: str, after_path: str) -> ScoreDiff: + """Explain how scores moved between two saved JSON reports.""" + before = _read(before_path) + after = _read(after_path) + result = ScoreDiff( + before_label=before_path, + after_label=after_path, + before_count=len(before), + after_count=len(after), + ) + for key, old in before.items(): + new = after.get(key) + if new is None: + result.removed.append(old) + continue + result.tracked += 1 + if old.score == new.score: + continue + change = Change(before=old, after=new) + old_parts = _contributions(old.reasons) + new_parts = _contributions(new.reasons) + for text, points in new_parts.items(): + if text not in old_parts: + change.gained.append(f"{text} ({points:+d})") + change.points += points + elif old_parts[text] != points: + delta = points - old_parts[text] + change.gained.append(f"{text} ({points:+d}, was {old_parts[text]:+d})") + change.points += delta + for text, points in old_parts.items(): + if text not in new_parts: + change.lost.append(f"{text} ({-points:+d})") + change.points -= points + if not old_parts and not new_parts: + # No signed reasons available: report rule-level movement instead. + if old.rule != new.rule: + change.gained.append(f"primary rule changed {old.rule} -> {new.rule}") + gained_rules = [rule for rule in new.rules if rule not in old.rules] + lost_rules = [rule for rule in old.rules if rule not in new.rules] + for rule in gained_rules: + change.gained.append(f"rule {rule} now contributes") + for rule in lost_rules: + change.lost.append(f"rule {rule} no longer contributes") + result.changed.append(change) + for key, new in after.items(): + if key not in before: + result.added.append(new) + result.changed.sort(key=lambda change: (-abs(change.delta), change.after.host)) + result.added.sort(key=lambda reading: reading.label) + result.removed.sort(key=lambda reading: reading.label) + return result + + +def render_score_diff(diff: ScoreDiff) -> str: + """``--explain-diff`` as text.""" + lines = ["PathScope score-change explanation", "=" * 84] + lines.append(f"before : {diff.before_label} ({diff.before_count} finding(s))") + lines.append(f"after : {diff.after_label} ({diff.after_count} finding(s))") + lines.append( + f"tracked {diff.tracked} finding(s): {len(diff.changed)} changed score, " + f"{diff.unchanged} unchanged." + ) + lines.append("") + + if diff.changed: + for change in diff.changed: + arrow = f"{change.before.score} -> {change.after.score}" + lines.append(f" {change.after.label}: {arrow} ({change.delta:+d})") + if change.before.confidence != change.after.confidence: + lines.append( + f" confidence {change.before.confidence} -> " + f"{change.after.confidence}" + ) + for item in change.gained: + lines.append(f" + {item}") + for item in change.lost: + lines.append(f" - {item}") + if not change.gained and not change.lost: + lines.append( + " the report did not record signed contributions; " + "only the score changed" + ) + lines.append("") + else: + lines.append("No tracked finding changed score.") + lines.append("") + + if diff.added: + lines.append(f"Only in the new report ({len(diff.added)})") + for reading in diff.added[:15]: + lines.append(f" + {reading.label} ({reading.score})") + if len(diff.added) > 15: + lines.append(f" ... and {len(diff.added) - 15} more") + lines.append("") + if diff.removed: + lines.append(f"Only in the old report ({len(diff.removed)})") + for reading in diff.removed[:15]: + lines.append(f" - {reading.label} ({reading.score})") + if len(diff.removed) > 15: + lines.append(f" ... and {len(diff.removed) - 15} more") + lines.append("") + + lines.append( + "This compares saved reports, not captures. It never re-analyses input." + ) + return "\n".join(lines) + + +__all__ = [ + "Change", + "Reading", + "ScoreDiff", + "ScoreDiffError", + "compare", + "render_score_diff", +] diff --git a/pathscope/scrub.py b/pathscope/scrub.py new file mode 100644 index 0000000..e18eb39 --- /dev/null +++ b/pathscope/scrub.py @@ -0,0 +1,227 @@ +"""Deterministic, offline redaction of secret-shaped parameter values. + +PathScope never shows values unless ``--show-values`` is used, but even then a +value may be a session token, an API key or a signed URL. Two situations need +redaction: + +* ``--scrub`` on any report, and +* every bundle written by ``--bundle`` (bundles are meant to be shared). + +Redaction is deliberately simple and reproducible: + +1. a value is *secret-shaped* when its parameter name looks sensitive + (``token``, ``secret``, ``password``, ``signature`` ...), or when the value + itself is long and high-entropy; and +2. the replacement is ```` where ``NNNNNNNN`` is the first + eight hex characters of the value's SHA-256. + +The digest keeps two redacted values comparable (same secret -> same digest) +without revealing anything useful, and it never changes a finding's +fingerprint, score or rule, because those are computed from names only. +""" + +from __future__ import annotations + +import hashlib +import math +import re +from collections import Counter +from dataclasses import replace +from typing import Iterable, Optional + +from .detector import Finding, Report + +#: Shorter values are never considered high-entropy secrets. +MIN_SECRET_LEN = 12 +#: Bits per character above which a long value is treated as a random secret. +ENTROPY_THRESHOLD = 3.5 +#: At or above this length a value is checked even without a name hint. +LONG_VALUE_LEN = 40 +#: Marker written in place of a scrubbed value. +MARKER_TEMPLATE = "" + +#: Parameter-name hints (lowercase, matched on canonical names). +SECRET_NAME_TERMS = frozenset( + """ + token accesstoken refreshtoken idtoken bearer jwt api_key apikey api-key + secret clientsecret client_secret password passwd pwd passphrase + signature sig hmac cookie session sessionid auth authorization credential + credentials privatekey private_key accesskey secretkey csrf xsrf nonce + ticket sas sastoken presigned + """.split() +) +#: Substrings that make a name sensitive even when glued to other words. +SECRET_NAME_SUBSTRINGS = ( + "token", "secret", "passw", "apikey", "api_key", "signature", "sessionid", + "privatekey", "private_key", "accesskey", "credential", "authorization", +) + +#: Values that are already known-safe placeholders. +SAFE_PLACEHOLDERS = frozenset({"", "none", "null", "true", "false", "0", "1"}) + +#: Vendor token prefixes: a value starting with one is a credential whatever +#: its entropy looks like (real tokens are random, but test fixtures are not). +SECRET_PREFIXES = ( + "ghp_", "gho_", "ghu_", "ghs_", "ghr_", # GitHub + "github_pat_", # GitHub fine-grained + "glpat-", # GitLab + "sk_live_", "sk_test_", "rk_live_", "rk_test_", # Stripe + "AKIA", "ASIA", # AWS access key id + "xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxs-", # Slack + "AIza", # Google API key + "ya29.", # Google OAuth + "sk-", # OpenAI-style + "eyJ", # JWT header + "SG.", # SendGrid + "npm_", # npm + "pypi-AgEIcHlwaS5vcmc", # PyPI + "dop_v1_", "doo_v1_", # DigitalOcean + "shpat_", "shpss_", "shpca_", "shppa_", # Shopify + "AccountKey=", # Azure + "-----BEGIN", # PEM private key +) +#: Prefixes whose remaining payload must also look token-ish. +_SHORT_PREFIXES = frozenset({"AKIA", "ASIA", "AIza", "sk-", "SG."}) + +_HEXISH = re.compile(r"^[0-9a-f]{16,}$", re.IGNORECASE) +_BASE64ISH = re.compile(r"^[A-Za-z0-9+/_-]{16,}={0,2}$") + + +def shannon_entropy(text: str) -> float: + """Bits of entropy per character (0 for empty input).""" + if not text: + return 0.0 + counts = Counter(text) + length = len(text) + return -sum( + (count / length) * math.log2(count / length) for count in counts.values() + ) + + +def is_sensitive_name(name: str) -> bool: + """True when a parameter *name* suggests a credential.""" + lowered = (name or "").lower() + tokens = re.split(r"[^a-z0-9]+", lowered) + for token in tokens: + compact = token.replace("-", "") + if compact in SECRET_NAME_TERMS or token in SECRET_NAME_TERMS: + return True + return any(marker in lowered for marker in SECRET_NAME_SUBSTRINGS) + + +def looks_like_secret(value: str) -> bool: + """True when a value itself looks like a credential (ignoring its name).""" + text = (value or "").strip() + if len(text) < MIN_SECRET_LEN or text.lower() in SAFE_PLACEHOLDERS: + return False + if _HEXISH.match(text) and len(text) >= 32: + return True + if matches_secret_prefix(text): + return True + if len(text) >= LONG_VALUE_LEN and _BASE64ISH.match(text): + return shannon_entropy(text) >= ENTROPY_THRESHOLD + # Long random-looking values in general. + if len(text) >= LONG_VALUE_LEN and shannon_entropy(text) >= ENTROPY_THRESHOLD + 0.5: + return True + return False + + +def digest(value: str) -> str: + """Stable short digest used inside the redaction marker.""" + return hashlib.sha256((value or "").encode("utf-8", "replace")).hexdigest()[:8] + + +def should_scrub(name: str, value: Optional[str]) -> bool: + """Decide whether one (name, value) pair must be redacted.""" + if not value: + return False + return is_sensitive_name(name) or looks_like_secret(value) + + +def matches_secret_prefix(value: str) -> bool: + """True when ``value`` carries a well-known vendor credential prefix.""" + text = (value or "").strip() + for prefix in SECRET_PREFIXES: + if not text.startswith(prefix): + continue + payload = text[len(prefix):] + if prefix in _SHORT_PREFIXES: + # Short prefixes also appear in prose ("sk-123", "AIza..."). + # Require a long, symbol-dense payload before calling it a secret. + if len(payload) < 16 or not _BASE64ISH.match(payload): + continue + elif len(payload) < 8: + continue + return True + return False + + +def scrub_value(value: Optional[str]) -> Optional[str]: + """Replace ``value`` with a marker that keeps it comparable.""" + if value is None: + return None + return MARKER_TEMPLATE.format(digest=digest(value)) + + +def scrub_finding(finding: Finding, show_values: bool = True) -> Finding: + """Return ``finding`` with a redacted value when one would be shown.""" + if finding.value is None or not show_values: + return finding + if not should_scrub(finding.parameter, finding.value): + return finding + return replace(finding, value=scrub_value(finding.value)) + + +def scrub_report(report: Report) -> Report: + """Return a copy of ``report`` with every sensitive shown value redacted.""" + if not report.show_values: + return report + findings = [scrub_finding(finding, True) for finding in report.findings] + scrubbed = replace(report, findings=findings) + scrubbed.scrubbed = True + return scrubbed + + +def scrub_parameter_map(parameters: Iterable) -> list: + """Scrub a list of :class:`pathscope.sources.Parameter`-like objects.""" + cleaned = [] + for parameter in parameters: + name = getattr(parameter, "name", "") + value = getattr(parameter, "value", "") + if should_scrub(name, value): + cleaned.append(replace(parameter, value=scrub_value(value))) + else: + cleaned.append(parameter) + return cleaned + + +def describe_policy() -> tuple: + """Lines for ``--help``/README describing what gets redacted.""" + return ( + " values whose parameter name looks sensitive (token, secret, password,", + " signature, session, api_key, csrf, ...) are always redacted;", + " long high-entropy values (>= 12 chars, >= 3.5 bits/char) are redacted", + " even when the name looks harmless;", + " replacements look like ; the digest is a SHA-256", + " prefix so the same secret is recognisable without being revealed.", + ) + + +__all__ = [ + "ENTROPY_THRESHOLD", + "LONG_VALUE_LEN", + "MARKER_TEMPLATE", + "MIN_SECRET_LEN", + "SAFE_PLACEHOLDERS", + "SECRET_NAME_TERMS", + "describe_policy", + "digest", + "is_sensitive_name", + "looks_like_secret", + "scrub_finding", + "scrub_parameter_map", + "scrub_report", + "scrub_value", + "shannon_entropy", + "should_scrub", +] diff --git a/pathscope/shadow.py b/pathscope/shadow.py new file mode 100644 index 0000000..a01ea6a --- /dev/null +++ b/pathscope/shadow.py @@ -0,0 +1,149 @@ +"""Policy shadow mode (``--policy-shadow FILE``). + +Adopting a policy is a one-way door in most pipelines: the first build that +fails it teaches everyone to add an exception. Shadow mode opens the door +halfway. A candidate policy is evaluated against the current run and its verdict +is **reported**, but the exit code stays 0, so a team can watch a proposed gate +for a week before it starts failing builds. + +Two policies can be compared at once: + + pathscope -i capture.har --policy current.json --policy-shadow proposed.json + +The output says, for each, what it would have failed on and which findings each +rule would have caught -- so the difference between "it fails" and "it fails on +the thing we care about" is visible. + +Shadow evaluation is read-only. It never changes ``finding.status``, never +touches the ledger and never affects the real gate. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Optional, Sequence + +from .detector import Report +from .policy import Policy, PolicyResult, evaluate + + +@dataclass +class ShadowResult: + """One policy, evaluated for information only.""" + + policy: Policy + result: PolicyResult + label: str = "shadow" + + @property + def would_fail(self) -> bool: + return not self.result.passed + + def as_dict(self) -> dict: + return { + "label": self.label, + "would_fail": self.would_fail, + "violations": list(self.result.violations), + "counts": dict(self.result.counts), + "ignored": self.result.ignored, + "source": self.policy.source, + } + + +def evaluate_shadow(report: Report, policy: Policy, label: str = "shadow") -> ShadowResult: + """Evaluate ``policy`` without changing anything about the report.""" + return ShadowResult(policy=policy, result=evaluate(report, policy), label=label) + + +def _caught(report: Report, policy: Policy) -> List: + """Findings the policy would count against the build.""" + from .policy import _eligible + + return [finding for finding in report.findings if _eligible(finding, policy)] + + +def render_shadow( + report: Report, + shadows: Sequence[ShadowResult], + actual: Optional[ShadowResult] = None, +) -> str: + """``--policy-shadow`` as text.""" + lines = ["PathScope policy shadow", "=" * 84] + lines.append( + "Shadow evaluation reports what a policy would do. It never changes the " + "exit code." + ) + lines.append("") + + rows = list(shadows) + if actual is not None: + rows = [actual] + rows + + for shadow in rows: + source = shadow.policy.source or "(inline)" + verdict = "WOULD FAIL" if shadow.would_fail else "would pass" + lines.append(f"{shadow.label}: {source}") + lines.append(f" verdict : {verdict}") + counts = shadow.result.counts + lines.append( + f" counted : {counts.get('total', 0)} finding(s) " + f"(high {counts.get('high', 0)}, medium {counts.get('medium', 0)}, " + f"low {counts.get('low', 0)})" + ) + if shadow.result.violations: + for violation in shadow.result.violations: + lines.append(f" violated: {violation}") + caught = _caught(report, shadow.policy) + if caught: + by_rule: dict = {} + for finding in caught: + by_rule[finding.rule] = by_rule.get(finding.rule, 0) + 1 + summary = ", ".join( + f"{rule} x{count}" for rule, count in sorted(by_rule.items(), key=lambda kv: -kv[1]) + ) + lines.append(f" by rule : {summary}") + top = sorted(caught, key=lambda f: -f.score)[:5] + for finding in top: + lines.append( + f" - {finding.resource} " + f"[{finding.location}] {finding.parameter} ({finding.score})" + ) + if len(caught) > 5: + lines.append(f" ... and {len(caught) - 5} more") + else: + lines.append(" by rule : nothing counted") + lines.append("") + + if actual is not None and shadows: + # A direct comparison is the whole point of shadowing. + lines.append("Difference") + for shadow in shadows: + if shadow.would_fail == actual.would_fail: + lines.append( + f" {shadow.label}: same verdict as the active policy " + f"({'both fail' if shadow.would_fail else 'both pass'})" + ) + else: + lines.append( + f" {shadow.label}: would " + f"{'fail' if shadow.would_fail else 'pass'} where the active " + f"policy {'fails' if actual.would_fail else 'passes'}" + ) + lines.append("") + lines.append( + "Adopt a policy when you are ready for it to fail builds: rerun without " + "--policy-shadow." + ) + return "\n".join(lines) + + +def as_dict(shadows: Sequence[ShadowResult]) -> List[dict]: + return [shadow.as_dict() for shadow in shadows] + + +__all__ = [ + "ShadowResult", + "as_dict", + "evaluate_shadow", + "render_shadow", +] diff --git a/pathscope/simulate.py b/pathscope/simulate.py new file mode 100644 index 0000000..b299230 --- /dev/null +++ b/pathscope/simulate.py @@ -0,0 +1,335 @@ +"""Weight simulation (``--simulate CHANGES``). + +Changing a rule weight is a guess unless you can see what it does. Deducting a +rule's share from recorded findings is tempting and wrong: evidence is capped at +100, demotions can take a score to zero, and removing the *leading* rule changes +which rule is primary. So this module does the honest thing -- it **re-analyses** +the same requests under the modified rule book. + + pathscope -i capture.har --simulate "name-weak=-10,value-absolute=+5" + +Output is a before/after table: candidates, high/medium/low counts, and which +findings moved. The real report is printed unchanged and the exit code is +untouched, so `--simulate` is safe to run inside a pipeline. + +The syntax is deliberately small: + + name-weak=-10 set a weight + name-weak=off disable the rule entirely + name-weak=default restore the registry default + name-weak=-10,value-absolute=5 + +Commas separate changes; a bare ``+5`` or ``5`` both mean "add five". +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import Dict, List, Optional, Sequence, Tuple + +from .detector import AnalysisOptions, Report +from .heuristics import canonical_name +from .textutil import display_location +from .rules import ( + DEFAULT_BOOK, + DEMOTION_PREFIX, + MAX_WEIGHT, + MIN_WEIGHT, + RULE_INDEX, + RuleBook, + normalize_rule_id, +) + + +class SimulationError(ValueError): + """Raised when a simulation spec cannot be parsed or is invalid.""" + + +@dataclass(frozen=True) +class Change: + """One requested rule change.""" + + rule: str + kind: str # set | off | default + value: int = 0 + + def describe(self) -> str: + before = DEFAULT_BOOK.default_weight(self.rule) + if self.kind == "off": + return f"{self.rule}: {before} -> disabled" + if self.kind == "default": + return f"{self.rule}: {before} (default)" + return f"{self.rule}: {before} -> {self.value}" + + +def parse_changes(spec: str) -> List[Change]: + """Parse ``"a=-10,b=off,c=default"`` into validated changes.""" + if not spec or not spec.strip(): + raise SimulationError("--simulate needs at least one change, e.g. name-weak=-10") + changes: List[Change] = [] + seen: Dict[str, int] = {} + for index, piece in enumerate(spec.split(","), start=1): + text = piece.strip() + if not text: + continue + if "=" not in text: + raise SimulationError( + f"change #{index} '{text}' has no '=': use rule=weight, rule=off " + "or rule=default" + ) + raw_rule, raw_value = text.split("=", 1) + rule = normalize_rule_id(raw_rule.strip()) + if rule not in RULE_INDEX: + raise SimulationError( + f"unknown rule '{raw_rule.strip()}' (see --list-rules)" + ) + if rule in seen: + raise SimulationError( + f"rule '{rule}' is changed twice (#{seen[rule]} and #{index}); " + "one change per rule keeps the result unambiguous" + ) + seen[rule] = index + value = raw_value.strip().lower() + if value in ("off", "disable", "disabled", "0", "false"): + changes.append(Change(rule=rule, kind="off")) + continue + if value in ("default", "reset"): + changes.append(Change(rule=rule, kind="default")) + continue + try: + weight = int(value, 10) + except ValueError: + raise SimulationError( + f"weight for '{rule}' must be an integer, 'off' or 'default', " + f"got '{raw_value.strip()}'" + ) from None + if not MIN_WEIGHT <= weight <= MAX_WEIGHT: + raise SimulationError( + f"weight for '{rule}' must be between {MIN_WEIGHT} and {MAX_WEIGHT}" + ) + if rule.startswith(DEMOTION_PREFIX) and weight > 0: + raise SimulationError( + f"'{rule}' is a demotion rule and may not have a positive weight" + ) + changes.append(Change(rule=rule, kind="set", value=weight)) + if not changes: + raise SimulationError("--simulate contained no usable changes") + return changes + + +def build_book(changes: Sequence[Change], base: Optional[RuleBook] = None) -> RuleBook: + """Apply ``changes`` on top of ``base`` (default: the registry default).""" + base = base or DEFAULT_BOOK + weights: Dict[str, int] = {} + disabled = set(base.disabled) + for change in changes: + if change.kind == "off": + disabled.add(change.rule) + continue + disabled.discard(change.rule) + if change.kind == "default": + weights[change.rule] = DEFAULT_BOOK.default_weight(change.rule) + else: + weights[change.rule] = change.value + merged = dict(base.weights) + merged.update(weights) + return RuleBook(weights=merged, disabled=frozenset(disabled), source="simulation") + + +@dataclass +class Move: + """One finding whose score or status changed.""" + + host: str + resource: str + parameter: str + location: str + before: int + after: int + + @property + def delta(self) -> int: + return self.after - self.before + + def describe(self) -> str: + sign = f"{self.delta:+d}" + return ( + f"{display_location(self.host, self.resource)} " + f"[{self.location}] {self.parameter}: " + f"{self.before} -> {self.after} ({sign})" + ) + + def as_dict(self) -> Dict[str, object]: + return { + "host": self.host, + "resource": self.resource, + "parameter": self.parameter, + "location": self.location, + "before": self.before, + "after": self.after, + "delta": self.delta, + } + + +@dataclass +class Simulation: + """The result of running the corpus twice.""" + + changes: List[Change] = field(default_factory=list) + before: Optional[Report] = None + after: Optional[Report] = None + moved: List[Move] = field(default_factory=list) + appeared: List[str] = field(default_factory=list) + disappeared: List[str] = field(default_factory=list) + + def counts(self, report: Optional[Report]) -> Dict[str, int]: + if report is None: + return {"total": 0, "high": 0, "medium": 0, "low": 0} + confidence = report.confidence_counts + return { + "total": report.candidate_count, + "high": confidence.get("high", 0), + "medium": confidence.get("medium", 0), + "low": confidence.get("low", 0), + } + + def as_dict(self) -> Dict[str, object]: + return { + "changes": [ + {"rule": change.rule, "kind": change.kind, "value": change.value} + for change in self.changes + ], + "before": self.counts(self.before), + "after": self.counts(self.after), + "moved": [move.as_dict() for move in self.moved], + "appeared": list(self.appeared), + "disappeared": list(self.disappeared), + } + + +def _key(finding) -> Tuple[str, str, str, str]: + return ( + finding.host.lower(), + finding.resource, + finding.location, + canonical_name(finding.parameter), + ) + + +def simulate( + requests, + options: AnalysisOptions, + changes: Sequence[Change], +) -> Simulation: + """Analyse ``requests`` under the original and modified rule books.""" + from .detector import analyze_requests + + before = analyze_requests(requests, options) + new_book = build_book(changes, base=options.book) + simulated_options = replace(options, book=new_book) + after = analyze_requests(requests, simulated_options) + + result = Simulation(changes=list(changes), before=before, after=after) + before_by_key = {_key(finding): finding for finding in before.findings} + after_by_key = {_key(finding): finding for finding in after.findings} + for key, old in before_by_key.items(): + new = after_by_key.get(key) + if new is None: + result.disappeared.append( + f"{display_location(old.host, old.resource)} " + f"[{old.location}] {old.parameter}" + ) + elif new.score != old.score: + result.moved.append( + Move( + host=old.host, + resource=old.resource, + parameter=old.parameter, + location=old.location, + before=old.score, + after=new.score, + ) + ) + for key, new in after_by_key.items(): + if key not in before_by_key: + result.appeared.append( + f"{display_location(new.host, new.resource)} " + f"[{new.location}] {new.parameter}" + ) + result.moved.sort(key=lambda move: (-abs(move.delta), move.host, move.parameter)) + result.appeared.sort() + result.disappeared.sort() + return result + + +def render_simulation(result: Simulation) -> str: + """``--simulate`` as text.""" + lines = ["PathScope weight simulation", "=" * 84] + lines.append("Nothing below was applied: the report above used the real rule book.") + lines.append("") + lines.append("Changes") + for change in result.changes: + lines.append(f" {change.describe()}") + lines.append("") + + before = result.counts(result.before) + after = result.counts(result.after) + + def row(label: str, old: int, new: int) -> str: + delta = new - old + sign = f"{delta:+d}" if delta else "0" + return f" {label:<10} {old:>5} -> {new:<5} {sign:>5}" + + lines.append("Candidates") + lines.append( + f" {'':<10} {'before':>5} {'after':<5} {'delta':>5}" + ) + for label in ("total", "high", "medium", "low"): + lines.append(row(label, before[label], after[label])) + lines.append("") + + if result.moved: + lines.append(f"Score changes ({len(result.moved)})") + for move in result.moved[:20]: + lines.append(f" {move.describe()}") + if len(result.moved) > 20: + lines.append(f" ... and {len(result.moved) - 20} more") + lines.append("") + if result.appeared: + lines.append(f"Newly reported ({len(result.appeared)})") + for item in result.appeared[:10]: + lines.append(f" + {item}") + if len(result.appeared) > 10: + lines.append(f" ... and {len(result.appeared) - 10} more") + lines.append("") + if result.disappeared: + lines.append(f"No longer reported ({len(result.disappeared)})") + for item in result.disappeared[:10]: + lines.append(f" - {item}") + if len(result.disappeared) > 10: + lines.append(f" ... and {len(result.disappeared) - 10} more") + lines.append("") + + if not (result.moved or result.appeared or result.disappeared): + lines.append( + "These changes had no effect on this corpus. That is a real answer: " + "the rules you are editing did not decide anything here." + ) + lines.append("") + lines.append( + "To apply a change, put it in a --rules file. Simulation itself never " + "writes anything." + ) + return "\n".join(lines) + + +__all__ = [ + "Change", + "Move", + "Simulation", + "SimulationError", + "build_book", + "parse_changes", + "render_simulation", + "simulate", +] diff --git a/pathscope/sources.py b/pathscope/sources.py new file mode 100644 index 0000000..31fcfef --- /dev/null +++ b/pathscope/sources.py @@ -0,0 +1,662 @@ +"""Input parsing for PathScope: URLs, URL lists, stdin and local HAR 1.2 files. + +All parsing is local. No URL is fetched, no connection is opened, and HAR +entries are never replayed. Parameter values are carried as plain strings. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple +from urllib.parse import unquote_plus, urlsplit, urlunsplit + +from .textutil import sanitize_text + +# Source kinds shown in reports. +SOURCE_URL = "url" +SOURCE_FILE = "file" +SOURCE_STDIN = "stdin" +SOURCE_HAR = "har" + +# Parameter locations. +LOCATION_QUERY = "query" +LOCATION_FORM = "form" +LOCATION_JSON = "json" + +#: Safety limits so a hostile or accidental huge HAR cannot exhaust memory. +MAX_HAR_ENTRIES = 20000 +MAX_JSON_DEPTH = 24 +MAX_JSON_PARAMETERS = 5000 +MAX_VALUE_CHARS = 20000 + +QUERY_SEPARATORS = "&" + + +class URLParseError(ValueError): + """Raised when a line cannot be interpreted as an http(s) URL.""" + + +class InputError(RuntimeError): + """Raised when an input file cannot be read or is not what it claims.""" + + +@dataclass(frozen=True) +class URLInfo: + """Locally parsed URL metadata.""" + + raw: str + scheme: str + host: str + port: Optional[int] + path: str + query: str + + @property + def display_host(self) -> str: + host = self.host + if ":" in host and not host.startswith("["): + host = f"[{host}]" + if self.port and self.port not in (80, 443): + return f"{host}:{self.port}" + return host + + @property + def display_resource(self) -> str: + """Scheme+host+path only: the query string is never shown by default.""" + host = self.host + if ":" in host and not host.startswith("["): + host = f"[{host}]" + netloc = host if not self.port else f"{host}:{self.port}" + return urlunsplit((self.scheme, netloc, self.path or "/", "", "")) + + +@dataclass(frozen=True) +class Parameter: + """One name/value pair exactly as it appears in the input.""" + + name: str + value: str + location: str = LOCATION_QUERY + occurrence: int = 1 + + def key(self) -> Tuple[str, str]: + return (self.location, canonical(self.name)) + + +@dataclass +class Request: + """A single analysed request and the source it came from.""" + + url: URLInfo + source_type: str + source_label: str + parameters: List[Parameter] = field(default_factory=list) + method: str = "GET" + index: int = 0 + + @property + def dedupe_key(self) -> Tuple[Any, ...]: + return ( + self.source_type, + self.source_label, + self.method, + self.url.raw, + tuple((p.location, p.name, p.value) for p in self.parameters), + ) + + +@dataclass +class LoadResult: + """Requests plus recoverable diagnostics produced while loading.""" + + requests: List[Request] = field(default_factory=list) + warnings: List[str] = field(default_factory=list) + skipped: int = 0 + + def extend(self, other: "LoadResult") -> None: + self.requests.extend(other.requests) + self.warnings.extend(other.warnings) + self.skipped += other.skipped + + +def canonical(name: str) -> str: + """Comparable form of a parameter name, without importing heuristics.""" + text = sanitize_text(name or "").strip().lower() + return "_".join(part for part in text.replace("-", "_").split("_") if part) + + +# --------------------------------------------------------------------------- +# URLs +# --------------------------------------------------------------------------- +def parse_url(raw: str) -> URLInfo: + """Validate and split one URL locally. Never resolves or contacts the host.""" + text = sanitize_text(raw or "").strip() + if not text: + raise URLParseError("blank input") + if any(ch.isspace() for ch in text): + raise URLParseError("contains whitespace") + if any(ord(ch) < 32 or ord(ch) == 127 for ch in raw or ""): + raise URLParseError("contains control characters") + try: + parts = urlsplit(text) + host = parts.hostname + port = parts.port + except ValueError as exc: + raise URLParseError(f"malformed URL ({exc})") from exc + scheme = (parts.scheme or "").lower() + if scheme not in ("http", "https"): + raise URLParseError(f"unsupported scheme (expected http/https, got '{scheme or 'none'}')") + if not parts.netloc or not host: + raise URLParseError("missing host") + return URLInfo( + raw=text, + scheme=scheme, + host=host, + port=port, + path=parts.path or "/", + query=parts.query, + ) + + +def split_query(query: str) -> List[Tuple[str, str]]: + """Split a raw query string into ``(name, value)`` pairs. + + Kept literal (split on ``&`` then the first ``=``) so repeated parameters + and percent-encoded names/values survive intact. ``+`` is decoded as space + in the name only, matching form conventions. + """ + pairs: List[Tuple[str, str]] = [] + if not query: + return pairs + for chunk in query.split(QUERY_SEPARATORS): + if not chunk: + continue + raw_name, _sep, raw_value = chunk.partition("=") + try: + name = unquote_plus(raw_name) + except (UnicodeError, ValueError): # pragma: no cover - defensive + name = raw_name + pairs.append((sanitize_text(name), raw_value)) + return pairs + + +def query_parameters(query: str) -> List[Parameter]: + """Return query parameters with occurrence counters for repeated names.""" + counts: Dict[str, int] = {} + parameters: List[Parameter] = [] + for name, value in split_query(query): + if not name: + continue + key = canonical(name) + counts[key] = counts.get(key, 0) + 1 + parameters.append( + Parameter( + name=sanitize_text(name), + value=sanitize_text(value)[:MAX_VALUE_CHARS], + location=LOCATION_QUERY, + occurrence=counts[key], + ) + ) + return parameters + + +def request_from_url( + raw: str, source_type: str, source_label: str, index: int = 0 +) -> Request: + """Build a :class:`Request` from a URL string.""" + info = parse_url(raw) + return Request( + url=info, + source_type=source_type, + source_label=source_label, + parameters=query_parameters(info.query), + index=index, + ) + + +# --------------------------------------------------------------------------- +# URL lists and stdin +# --------------------------------------------------------------------------- +def read_text(path: str) -> str: + """Read a UTF-8 (BOM-tolerant) text file, raising :class:`InputError`.""" + try: + with open(path, "r", encoding="utf-8-sig", errors="replace") as handle: + return handle.read() + except OSError as exc: + raise InputError(f"cannot read input file '{path}': {exc.strerror or exc}") from exc + + +def load_url_lines( + lines: Iterable[str], source_type: str, label: str +) -> LoadResult: + """Load one-URL-per-line input, skipping blanks, comments and duplicates.""" + result = LoadResult() + seen: set = set() + for line_number, line in enumerate(lines, start=1): + candidate = sanitize_text(line).strip() + if not candidate or candidate.startswith("#"): + continue + if candidate in seen: + continue + try: + request = request_from_url(candidate, source_type, label, len(result.requests)) + except URLParseError as exc: + result.warnings.append( + f"{label} line {line_number}: skipped malformed URL ({exc})" + ) + result.skipped += 1 + continue + seen.add(candidate) + result.requests.append(request) + return result + + +def load_url_file(path: str) -> LoadResult: + return load_url_lines(read_text(path).splitlines(), SOURCE_FILE, path) + + +def load_stdin_urls(text: str) -> LoadResult: + return load_url_lines(text.splitlines(), SOURCE_STDIN, "stdin") + + +# --------------------------------------------------------------------------- +# HAR 1.2 +# --------------------------------------------------------------------------- +class HarError(InputError): + """Raised when a document is not a usable HAR file.""" + + +def looks_like_har(text: str, path_hint: str = "") -> bool: + """Cheap local heuristic: ``.har`` extension or a top-level ``log`` object.""" + lowered = (path_hint or "").lower() + if lowered.endswith(".har") or lowered.endswith(".har.json"): + return True + stripped = text.lstrip("\ufeff \t\r\n") + if not stripped.startswith("{"): + return False + head = stripped[:4096].lower() + return '"log"' in head and '"entries"' in head + + +def _as_text(value: Any) -> str: + if value is None: + return "" + if isinstance(value, str): + return sanitize_text(value)[:MAX_VALUE_CHARS] + return sanitize_text(json.dumps(value, ensure_ascii=False, sort_keys=True))[ + :MAX_VALUE_CHARS + ] + + +def _json_parameters( + payload: Any, warnings: List[str], entry_label: str +) -> List[Parameter]: + """Flatten a JSON body into ``(path, scalar)`` parameters. + + Nested objects use dots (``user.file``) and arrays use brackets + (``files[0].path``). Only scalar leaves become parameters; numbers and + booleans are stringified. The payload is never written anywhere. + """ + parameters: List[Parameter] = [] + stack: List[Tuple[str, Any, int]] = [("", payload, 0)] + truncated = False + + while stack: + prefix, node, depth = stack.pop(0) + if len(parameters) >= MAX_JSON_PARAMETERS: + truncated = True + break + if depth > MAX_JSON_DEPTH: + truncated = True + continue + if isinstance(node, dict): + for key, value in reversed(list(node.items())): + name = str(key) + new_prefix = f"{prefix}.{name}" if prefix else name + stack.insert(0, (new_prefix, value, depth + 1)) + elif isinstance(node, list): + for index, value in enumerate(node): + new_prefix = f"{prefix}[{index}]" + stack.insert(0, (new_prefix, value, depth + 1)) + else: + if prefix: + parameters.append( + Parameter( + name=prefix, + value=_as_text(node), + location=LOCATION_JSON, + ) + ) + + if truncated: + warnings.append( + f"{entry_label}: JSON body exceeded limits " + f"({MAX_JSON_PARAMETERS} parameters / depth {MAX_JSON_DEPTH}); " + "analysis truncated" + ) + return parameters + + +def _form_parameters( + body: Dict[str, Any], entry_label: str, warnings: List[str] +) -> List[Parameter]: + """Extract form parameters from a HAR ``postData`` object.""" + parameters: List[Parameter] = [] + mime = str(body.get("mimeType") or "").lower() + text = body.get("text") + raw_params = body.get("params") + + if isinstance(raw_params, list): + for item in raw_params: + if not isinstance(item, dict): + continue + name = _as_text(item.get("name")) + if not name: + continue + if item.get("value") is not None: + value = _as_text(item.get("value")) + elif item.get("fileName"): + # Multipart uploads record the client-side file name here. + value = _as_text(item.get("fileName")) + else: + value = "" + parameters.append(Parameter(name=name, value=value, location=LOCATION_FORM)) + if parameters: + return parameters + + if isinstance(text, str) and text: + if "json" in mime: + try: + payload = json.loads(text) + except ValueError as exc: + warnings.append(f"{entry_label}: malformed JSON body skipped ({exc})") + return [] + return _json_parameters(payload, warnings, entry_label) + if "x-www-form-urlencoded" in mime or mime == "": + pairs = split_query(text) + if pairs and "=" in text: + return [ + Parameter( + name=name, + value=sanitize_text(value)[:MAX_VALUE_CHARS], + location=LOCATION_FORM, + ) + for name, value in pairs + if name + ] + return parameters + + +def _har_entry_parameters( + request: Dict[str, Any], entry_label: str, warnings: List[str] +) -> Tuple[URLInfo, List[Parameter]]: + raw_url = request.get("url") + if not isinstance(raw_url, str) or not raw_url: + raise URLParseError("missing request.url") + info = parse_url(raw_url) + + parameters: List[Parameter] = [] + + # Query: prefer the recorded queryString, else derive from the URL. + query_list = request.get("queryString") + if isinstance(query_list, list) and query_list: + counts: Dict[str, int] = {} + for item in query_list: + if not isinstance(item, dict): + continue + name = _as_text(item.get("name")) + if not name: + continue + key = canonical(name) + counts[key] = counts.get(key, 0) + 1 + parameters.append( + Parameter( + name=name, + value=_as_text(item.get("value")), + location=LOCATION_QUERY, + occurrence=counts[key], + ) + ) + else: + parameters.extend(query_parameters(info.query)) + + # Bodies: only present when the HAR recorded them. + post_data = request.get("postData") + if isinstance(post_data, dict): + parameters.extend(_form_parameters(post_data, entry_label, warnings)) + + return info, parameters + + +def load_har(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse a HAR 1.2 document. Raises :class:`HarError` if unusable.""" + source_label = source_label or label + try: + document = json.loads(text.lstrip("\ufeff")) + except ValueError as exc: + raise HarError(f"{label}: not valid JSON ({exc})") from exc + + if not isinstance(document, dict): + raise HarError(f"{label}: HAR root must be a JSON object") + log = document.get("log") + if not isinstance(log, dict): + raise HarError(f"{label}: missing HAR 'log' object") + version = log.get("version") + if not isinstance(version, str) or not version.startswith("1."): + warnings_version = version if isinstance(version, str) else "missing" + # Not fatal: many exporters omit or vary the version field. + version_warning = ( + f"{label}: HAR version '{warnings_version}' is not 1.x; " + "entries will still be parsed defensively" + ) + else: + version_warning = "" + + entries = log.get("entries") + if not isinstance(entries, list): + raise HarError(f"{label}: HAR 'log.entries' must be an array") + + result = LoadResult() + if version_warning: + result.warnings.append(version_warning) + if len(entries) > MAX_HAR_ENTRIES: + result.warnings.append( + f"{label}: {len(entries)} entries exceed the limit of {MAX_HAR_ENTRIES}; " + "only the first entries are analyzed" + ) + entries = entries[:MAX_HAR_ENTRIES] + + seen: set = set() + for entry_index, entry in enumerate(entries): + entry_label = f"{label} entry {entry_index}" + if not isinstance(entry, dict): + result.warnings.append(f"{entry_label}: skipped non-object entry") + result.skipped += 1 + continue + request = entry.get("request") + if not isinstance(request, dict): + result.warnings.append(f"{entry_label}: skipped entry without a request") + result.skipped += 1 + continue + try: + info, parameters = _har_entry_parameters(request, entry_label, result.warnings) + except URLParseError as exc: + result.warnings.append(f"{entry_label}: skipped malformed request URL ({exc})") + result.skipped += 1 + continue + except (TypeError, ValueError) as exc: # pragma: no cover - defensive + result.warnings.append(f"{entry_label}: skipped unreadable entry ({exc})") + result.skipped += 1 + continue + + method = _as_text(request.get("method") or "GET").upper() + request_key = (method, info.raw, tuple((p.location, p.name, p.value) for p in parameters)) + if request_key in seen: + continue + seen.add(request_key) + + result.requests.append( + Request( + url=info, + source_type=SOURCE_HAR, + source_label=source_label, + parameters=parameters, + method=method, + index=len(result.requests), + ) + ) + return result + + +def load_har_file(path: str) -> LoadResult: + return load_har(read_text(path), os.path.basename(path) or path, source_label=path) + + +def load_stdin_har(text: str) -> LoadResult: + return load_har(text, "stdin") + + +# --------------------------------------------------------------------------- +# Format detection and dispatch +# --------------------------------------------------------------------------- +INPUT_FORMAT_AUTO = "auto" +INPUT_FORMAT_URLS = "urls" +INPUT_FORMAT_HAR = "har" +#: Selectable formats. The extra ones live in :mod:`pathscope.extra_formats`. +INPUT_FORMATS = ( + INPUT_FORMAT_AUTO, + INPUT_FORMAT_URLS, + INPUT_FORMAT_HAR, + "burp", + "openapi", + "raw", + "httpx", + "ffuf", + "nuclei", + "recon", + "postman", + "zap", + "mitmproxy", + "graphql", + "cookies", +) + + +def detect_input_format(text: str, path: str = "") -> str: + """Return a format id for a text blob and optional filename. + + HAR wins first (an explicit ``log.entries`` shape), then the extra formats + (Burp XML, OpenAPI, raw HTTP, recon output), then a plain URL list. + """ + if looks_like_har(text, path): + return INPUT_FORMAT_HAR + + # A plain URL list stays a URL list even though every line contains a URL. + meaningful = [ + line.strip() + for line in text.splitlines() + if line.strip() and not line.strip().startswith("#") + ] + if meaningful: + clean = sum( + 1 + for line in meaningful + if line.lower().startswith(("http://", "https://")) and not line.strip()[4:].count(" ") + ) + looks_like_tool_output = sum(1 for line in meaningful if "[" in line or line.startswith("{")) + # Predominantly bare URLs with no tool-output decoration: a URL list. + if clean and looks_like_tool_output == 0 and clean >= len(meaningful) - 1: + return INPUT_FORMAT_URLS + + from .extra_formats import detect_extra_format # local import avoids a cycle + from .tool_formats import detect_tool_format + + # Tool exports (Postman/ZAP/mitmproxy/GraphQL/cookies) are checked before + # the recon fallback, which would otherwise claim any text with a URL. + tool = detect_tool_format(text, path) + if tool: + return tool + + extra = detect_extra_format(text, path) + if extra: + return extra + return INPUT_FORMAT_URLS + + +#: Formats handled by :mod:`pathscope.tool_formats`. +TOOL_FORMATS = ("postman", "zap", "mitmproxy", "graphql", "cookies") + + +def _load_extra(path_or_text: str, fmt: str, *, is_path: bool) -> "LoadResult": + from .extra_formats import load_extra_file, load_extra_text # local import + + if fmt in TOOL_FORMATS: + from .tool_formats import load_tool_file, load_tool_text + + if is_path: + return load_tool_file(path_or_text, fmt) + return load_tool_text(path_or_text, fmt, "stdin") + + if is_path: + return load_extra_file(path_or_text, fmt) + label = "stdin" + return load_extra_text(path_or_text, fmt, label) + + +def load_file(path: str, input_format: str = INPUT_FORMAT_AUTO) -> LoadResult: + """Load a file in any supported format, honouring an explicit format.""" + if input_format == INPUT_FORMAT_HAR: + return load_har_file(path) + if input_format == INPUT_FORMAT_URLS: + return load_url_file(path) + if input_format not in (INPUT_FORMAT_AUTO,): + return _load_extra(path, input_format, is_path=True) + + text = read_text(path) + detected = detect_input_format(text, path) + if detected == INPUT_FORMAT_HAR: + return load_har(text, os.path.basename(path) or path, source_label=path) + if detected == INPUT_FORMAT_URLS: + return load_url_lines(text.splitlines(), SOURCE_FILE, path) + return _load_extra(path, detected, is_path=True) + + +def load_stdin(text: str, input_format: str = INPUT_FORMAT_AUTO) -> LoadResult: + if input_format == INPUT_FORMAT_HAR: + return load_stdin_har(text) + if input_format == INPUT_FORMAT_URLS: + return load_stdin_urls(text) + if input_format not in (INPUT_FORMAT_AUTO,): + return _load_extra(text, input_format, is_path=False) + + detected = detect_input_format(text) + if detected == INPUT_FORMAT_HAR: + return load_stdin_har(text) + if detected == INPUT_FORMAT_URLS: + return load_stdin_urls(text) + return _load_extra(text, detected, is_path=False) + + +def make_url_requests(urls: Sequence[str]) -> LoadResult: + """Load ``--url`` values, reporting each malformed one non-fatally.""" + result = LoadResult() + seen: set = set() + for index, raw in enumerate(urls, start=1): + candidate = sanitize_text(raw).strip() + if not candidate: + result.warnings.append(f"--url #{index}: skipped blank URL") + result.skipped += 1 + continue + if candidate in seen: + continue + try: + request = request_from_url(candidate, SOURCE_URL, "--url") + except URLParseError as exc: + result.warnings.append(f"--url #{index}: skipped malformed URL ({exc})") + result.skipped += 1 + continue + seen.add(candidate) + result.requests.append(request) + return result diff --git a/pathscope/stream.py b/pathscope/stream.py new file mode 100644 index 0000000..d120abf --- /dev/null +++ b/pathscope/stream.py @@ -0,0 +1,292 @@ +"""Streaming stdin (``--stream``). + +``--stream`` reads a pipe line by line instead of loading it into memory. That +matters when a recon tool or a ``tail -f capture.log`` feeds URLs forever: + +* memory stays bounded (no full-text buffer, no accumulating request list), +* candidates are analysed and written incrementally, and +* the input is still parsed exactly like a normal URL list. + +Only one pass is made over stdin, so formats that need random access (HAR, +OpenAPI, ...) are rejected up front: streaming is for line-oriented input. + +All rendering still happens locally; nothing is requested. +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass, field +from typing import Callable, Iterable, List, Optional, TextIO + +from .detector import AnalysisOptions, Report +from .sources import SOURCE_STDIN, URLParseError, Request, request_from_url +from .textutil import sanitize_text + +#: How many requests to batch between renderings (1 = fully live). +DEFAULT_BATCH = 1 +#: Safety cap on total lines accepted (0 = unlimited). +MAX_STREAM_LINES = 5_000_000 + + +class StreamError(RuntimeError): + """Raised when streaming input is unusable.""" + + +@dataclass +class StreamStats: + """What the stream saw, for the closing summary.""" + + lines: int = 0 + blank: int = 0 + comments: int = 0 + skipped: int = 0 + requests: int = 0 + analysed: int = 0 + batches: int = 0 + warnings: List[str] = field(default_factory=list) + + def summary(self) -> str: + return ( + f"{self.lines} line(s) read, {self.requests} URL(s), " + f"{self.skipped} skipped, {self.analysed} candidate(s)" + ) + + +def iter_url_requests( + lines: Iterable[str], + stats: StreamStats, + *, + label: str = "stdin", + max_lines: int = MAX_STREAM_LINES, +) -> Iterable[Request]: + """Yield :class:`Request` objects from an iterable of lines, one at a time.""" + seen: set = set() + for raw in lines: + stats.lines += 1 + if max_lines and stats.lines > max_lines: + raise StreamError(f"stream exceeded {max_lines} lines") + line = sanitize_text(raw).strip() + if not line: + stats.blank += 1 + continue + if line.startswith("#"): + stats.comments += 1 + continue + if line in seen: + stats.skipped += 1 + continue + try: + request = request_from_url(line, SOURCE_STDIN, label) + except URLParseError as exc: + stats.skipped += 1 + if len(stats.warnings) < 20: + stats.warnings.append(f"{label} line {stats.lines}: skipped ({exc})") + continue + seen.add(line) + stats.requests += 1 + yield request + + +def stream_report( + requests: Iterable[Request], + analyse: Callable[[List[Request]], Report], + *, + batch_size: int = DEFAULT_BATCH, +) -> Iterable[Report]: + """Analyse requests in bounded batches and yield one report per batch.""" + batch: List[Request] = [] + for request in requests: + batch.append(request) + if len(batch) >= max(1, batch_size): + yield analyse(batch) + batch = [] + if batch: + yield analyse(batch) + + +def stream_lines(stream: Optional[TextIO] = None) -> Iterable[str]: + """Iterate stdin line by line without buffering the whole input.""" + handle = stream if stream is not None else sys.stdin + if handle is None: # pragma: no cover - defensive + raise StreamError("stdin is unavailable") + try: + for line in handle: + yield line + except (OSError, ValueError) as exc: # pragma: no cover - pipe errors + raise StreamError(f"cannot read stdin: {exc}") from exc + + +@dataclass +class StreamResult: + """The finished stream: one report, one stats block, one warning list.""" + + report: Report + stats: StreamStats + warnings: List[str] = field(default_factory=list) + complete: bool = True + + @property + def candidates(self) -> int: + return self.report.candidate_count + + +def _merge_report(target: Report, batch: Report) -> None: + """Fold one batch report into the running total (deterministic order).""" + target.requests_analyzed += batch.requests_analyzed + target.parameters_analyzed += batch.parameters_analyzed + target.skipped += batch.skipped + target.truncated_entries += batch.truncated_entries + target.warnings.extend(batch.warnings) + for source in batch.sources: + if source not in target.sources: + target.sources.append(source) + for finding in batch.findings: + target.findings.append(finding) + for index, finding in enumerate(target.findings, start=1): + finding.index = index + if batch.rules: + target.rules = dict(batch.rules) + target.rules_source = batch.rules_source + if batch.name_lang and not target.name_lang: + target.name_lang = batch.name_lang + + +def stream_analysis( + lines: Iterable[str], + options: AnalysisOptions, + *, + analyse: Optional[Callable[[List[Request], AnalysisOptions], Report]] = None, + batch_size: int = DEFAULT_BATCH, + on_batch: Optional[Callable[[int, Report], None]] = None, + label: str = "stdin", + max_lines: int = MAX_STREAM_LINES, +) -> StreamResult: + """Analyse line-oriented input in bounded batches and merge the result. + + ``lines`` is consumed lazily, so nothing but the current batch is held in + memory. ``on_batch(batch_number, cumulative_report)`` is called after each + batch so callers can print progress (e.g. ``--stream-json``). + """ + if analyse is None: # imported lazily to keep startup light + from .detector import analyze_requests as analyse # type: ignore[assignment] + + stats = StreamStats() + total = Report(min_score=options.min_score, show_values=options.show_values) + batch_number = 0 + for batch in stream_report( + iter_url_requests(lines, stats, label=label, max_lines=max_lines), + lambda requests: analyse(requests, options), + batch_size=max(1, batch_size), + ): + batch_number += 1 + stats.batches = batch_number + stats.analysed = total.candidate_count + batch.candidate_count + _merge_report(total, batch) + if on_batch is not None: + on_batch(batch_number, total) + stats.analysed = total.candidate_count + return StreamResult(report=total, stats=stats, warnings=list(stats.warnings)) + + +def stream_stdin( + options: AnalysisOptions, + *, + batch_size: int = DEFAULT_BATCH, + on_batch: Optional[Callable[[int, Report], None]] = None, + stream: Optional[TextIO] = None, +) -> StreamResult: + """``--stream`` entry point: read the process stdin lazily.""" + return stream_analysis( + stream_lines(stream), + options, + batch_size=batch_size, + on_batch=on_batch, + label="stdin", + ) + + +def stream_text( + text: str, + options: AnalysisOptions, + *, + batch_size: int = DEFAULT_BATCH, + on_batch: Optional[Callable[[int, Report], None]] = None, + label: str = "stdin", +) -> StreamResult: + """Same as :func:`stream_stdin` for an already-captured string (tests).""" + return stream_analysis( + text.splitlines(), + options, + batch_size=batch_size, + on_batch=on_batch, + label=label, + ) + + +def render_stream_summary(result: StreamResult, colors=None) -> str: + """Closing text for ``--stream`` when ``--stream-json`` is not used.""" + paint = getattr(colors, "paint", lambda _style, text: text) + stats = result.stats + report = result.report + lines = [paint("bold", "PathScope streaming summary")] + lines.append(f"Lines read : {stats.lines}") + if stats.blank: + lines.append(f"Blank lines : {stats.blank}") + if stats.comments: + lines.append(f"Comment lines : {stats.comments}") + if stats.skipped: + lines.append(f"Skipped lines : {stats.skipped}") + lines.append(f"URLs analysed : {report.requests_analyzed}") + lines.append(f"Parameters : {report.parameters_analyzed}") + lines.append(f"Batches : {stats.batches}") + lines.append(f"Candidates : {report.candidate_count}") + for band in ("high", "medium", "low"): + lines.append(f" {band:<7} : {report.confidence_counts.get(band, 0)}") + if report.findings: + lines.append("") + by_rule: dict = {} + for finding in report.findings: + by_rule[finding.rule] = by_rule.get(finding.rule, 0) + 1 + lines.append(paint("bold", "Candidates per rule")) + for rule in sorted(by_rule): + lines.append(f" {rule:<28} {by_rule[rule]}") + lines.append("") + lines.append(paint("grey", "Candidates for manual review only.")) + return "\n".join(lines) + + +def stdin_is_a_pipe() -> bool: + """True when stdin is piped/redirected rather than an interactive TTY.""" + try: + return not sys.stdin.isatty() + except (AttributeError, ValueError): # pragma: no cover - exotic streams + return True + + +def check_streamable(input_format: str) -> None: + """Reject formats that cannot be streamed in a single pass.""" + streamable = {"auto", "urls", "httpx", "ffuf", "nuclei", "recon"} + if input_format not in streamable: + raise StreamError( + f"--stream works with line-oriented input ({', '.join(sorted(streamable))}); " + f"'{input_format}' requires a complete document. Drop --stream or pipe URLs." + ) + + +__all__ = [ + "DEFAULT_BATCH", + "MAX_STREAM_LINES", + "StreamError", + "StreamStats", + "check_streamable", + "iter_url_requests", + "stream_analysis", + "stream_lines", + "stream_report", + "stream_stdin", + "stdin_is_a_pipe", + "stream_text", + "render_stream_summary", + "StreamResult", +] diff --git a/pathscope/termpacks.py b/pathscope/termpacks.py new file mode 100644 index 0000000..bd508c6 --- /dev/null +++ b/pathscope/termpacks.py @@ -0,0 +1,258 @@ +"""Shareable custom term packs (``--terms`` / ``--init-terms``). + +Custom path terms already exist through the config file's ``name_terms``. That +works for one person; it does not work for a team, because the terms live +inside a config that also carries unrelated settings (thresholds, languages, +decode depth), and merging two people's configs is a recipe for surprises. + +A term pack is the term list **on its own**: + +.. code-block:: json + + { + "pack": "acme-api", + "version": 1, + "description": "Path-like names used by Acme's document service", + "terms": ["attachment", "document", "receipt", "scan"], + "ignore": ["utm_source", "cache_bust"] + } + +Design rules, inherited from the config file and enforced here: + +* **No regular expressions.** Every term is a literal, checked against the same + character and length limits as ``name_terms``. A pack cannot become a + mini-language, a ReDoS vector, or an unexplainable scorer. +* **No code, no paths, no includes.** A pack is data. Loading one reads a single + file you named; it never pulls in another file. +* **Strict.** Unknown keys, wrong types and duplicate terms are errors, not + warnings — a typo in a shared pack should fail loudly for everybody. + +Packs merge with the config in a fixed order: config terms first, then each +``--terms`` pack in command-line order, then ``--init-terms`` output round-trips +cleanly. Duplicates are dropped, first occurrence wins, so ordering is stable. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass, field +from typing import Dict, List, Sequence, Tuple + +from .config import ( + MAX_TERM_COUNT, + MAX_TERM_LEN, + ConfigError, + _validate_terms, +) + +#: Schema version written by ``--init-terms`` and accepted by ``--terms``. +PACK_VERSION = 1 +#: Keys allowed at the top level of a pack. +ALLOWED_PACK_KEYS = {"pack", "version", "description", "terms", "ignore"} +#: A pack may not be larger than this, so a shared file cannot blow up scoring. +MAX_PACK_TERMS = MAX_TERM_COUNT +MAX_PACK_BYTES = 256 * 1024 + + +class TermPackError(ValueError): + """Raised when a term pack is missing, malformed, or out of bounds.""" + + +@dataclass +class TermPack: + """A validated, literal-only bundle of custom terms.""" + + name: str + terms: List[str] = field(default_factory=list) + ignore: List[str] = field(default_factory=list) + description: str = "" + version: int = PACK_VERSION + source: str = "" + + def as_dict(self) -> Dict[str, object]: + return { + "pack": self.name, + "version": self.version, + "description": self.description, + "terms": list(self.terms), + "ignore": list(self.ignore), + } + + def to_json(self) -> str: + return json.dumps(self.as_dict(), indent=2, sort_keys=False) + "\n" + + +def _require_text(payload: Dict[str, object], key: str, limit: int = 200) -> str: + value = payload.get(key, "") + if value is None: + return "" + if not isinstance(value, str): + raise TermPackError(f"'{key}' must be a string") + if len(value) > limit: + raise TermPackError(f"'{key}' is longer than {limit} characters") + return value + + +def validate_payload(payload: object, source: str = "") -> TermPack: + """Validate a parsed pack. Raises :class:`TermPackError` on any problem.""" + if not isinstance(payload, dict): + raise TermPackError(f"{source or 'term pack'} must be a JSON object") + unknown = set(payload) - ALLOWED_PACK_KEYS + if unknown: + raise TermPackError( + f"unknown key(s) in {source or 'term pack'}: " + + ", ".join(sorted(unknown)) + + f"; allowed: {', '.join(sorted(ALLOWED_PACK_KEYS))}" + ) + version = payload.get("version", PACK_VERSION) + if not isinstance(version, int) or isinstance(version, bool): + raise TermPackError("'version' must be an integer") + if version != PACK_VERSION: + raise TermPackError( + f"unsupported term pack version {version} (this build reads {PACK_VERSION})" + ) + + raw_terms = payload.get("terms", []) + if raw_terms is None: + raw_terms = [] + if not isinstance(raw_terms, list): + raise TermPackError("'terms' must be an array of strings") + if len(raw_terms) > MAX_PACK_TERMS: + raise TermPackError( + f"'terms' has {len(raw_terms)} entries; the limit is {MAX_PACK_TERMS}" + ) + try: + terms = _validate_terms(raw_terms, "terms") + except ConfigError as exc: + raise TermPackError(str(exc)) from exc + + duplicates = { + term for term in terms if terms.count(term) > 1 + } if len(terms) != len(set(terms)) else set() + if duplicates: + raise TermPackError( + "duplicate term(s): " + ", ".join(sorted(duplicates)) + ) + + raw_ignore = payload.get("ignore", []) + if raw_ignore is None: + raw_ignore = [] + if not isinstance(raw_ignore, list): + raise TermPackError("'ignore' must be an array of strings") + if len(raw_ignore) > MAX_PACK_TERMS: + raise TermPackError(f"'ignore' has {len(raw_ignore)} entries; the limit is {MAX_PACK_TERMS}") + ignore: List[str] = [] + for entry in raw_ignore: + if not isinstance(entry, str): + raise TermPackError("'ignore' entries must be strings") + text = entry.strip() + if not text: + continue + if len(text) > MAX_TERM_LEN: + raise TermPackError(f"ignore name '{text[:20]}...' is too long") + ignore.append(text) + if len(set(ignore)) != len(ignore): + raise TermPackError("duplicate entries in 'ignore'") + + return TermPack( + name=_require_text(payload, "pack", 64) or "unnamed", + terms=terms, + ignore=ignore, + description=_require_text(payload, "description", 500), + version=version, + source=source, + ) + + +def load_pack(path: str) -> TermPack: + """Read and validate one pack file.""" + if not os.path.exists(path): + raise TermPackError(f"cannot read term pack '{path}': no such file") + if os.path.isdir(path): + raise TermPackError(f"'{path}' is a directory; pass a .json file") + try: + size = os.path.getsize(path) + except OSError as exc: # pragma: no cover - filesystem edge + raise TermPackError(f"cannot stat '{path}': {exc.strerror or exc}") from exc + if size > MAX_PACK_BYTES: + raise TermPackError( + f"term pack '{path}' is {size} bytes; the limit is {MAX_PACK_BYTES}" + ) + try: + with open(path, "r", encoding="utf-8-sig") as handle: + payload = json.load(handle) + except OSError as exc: + raise TermPackError(f"cannot read '{path}': {exc.strerror or exc}") from exc + except json.JSONDecodeError as exc: + raise TermPackError( + f"'{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + return validate_payload(payload, source=path) + + +def load_packs(paths: Sequence[str]) -> List[TermPack]: + """Load several packs in command-line order.""" + return [load_pack(path) for path in paths] + + +def merge_terms(base: Sequence[str], packs: Sequence[TermPack]) -> Tuple[List[str], List[str]]: + """Merge config terms and pack terms. Returns ``(terms, ignore)``. + + Order is config first, then packs as given on the command line; duplicates + keep their first position so the scoring trace stays stable between runs. + """ + terms: List[str] = [] + ignore: List[str] = [] + for term in list(base): + if term not in terms: + terms.append(term) + for pack in packs: + for term in pack.terms: + if term not in terms: + terms.append(term) + for name in pack.ignore: + if name not in ignore: + ignore.append(name) + if len(terms) > MAX_TERM_COUNT: + raise TermPackError( + f"merging produced {len(terms)} terms; the limit is {MAX_TERM_COUNT}" + ) + return terms, ignore + + +def starter_pack(name: str = "my-project") -> TermPack: + """The pack ``--init-terms`` writes: valid, small, and self-documenting.""" + return TermPack( + name=name, + terms=["attachment", "document", "receipt"], + ignore=["utm_source", "utm_medium", "cache_bust"], + description=( + "Literal path-like parameter names for this project. " + "No regular expressions: add words, not patterns." + ), + ) + + +def describe(pack: TermPack) -> str: + """One-line summary used by ``--list-terms``.""" + return ( + f"{pack.name:<24} {len(pack.terms):>3} term(s) " + f"{len(pack.ignore):>3} ignore(s) {pack.description[:60]}" + ) + + +__all__ = [ + "ALLOWED_PACK_KEYS", + "MAX_PACK_BYTES", + "MAX_PACK_TERMS", + "PACK_VERSION", + "TermPack", + "TermPackError", + "describe", + "load_pack", + "load_packs", + "merge_terms", + "starter_pack", + "validate_payload", +] diff --git a/pathscope/textutil.py b/pathscope/textutil.py new file mode 100644 index 0000000..f9df57e --- /dev/null +++ b/pathscope/textutil.py @@ -0,0 +1,126 @@ +"""String helpers shared by PathScope. + +Everything in this module is pure string processing. Nothing here touches the +filesystem, the network, or the process environment beyond explicit arguments. +""" + +from __future__ import annotations + +import unicodedata +from typing import Iterable, List, Tuple +from urllib.parse import unquote, unquote_plus + +#: Maximum number of percent-decoding passes applied to one value. Early exit +#: keeps decoding cheap when the value contains nothing encoded. +MAX_DECODE_PASSES = 3 + +#: A value is decoded only when it contains a percent escape. This keeps large +#: bodies and ordinary words out of the decoder entirely. +_PERCENT = "%" + + +def sanitize_text(value: str) -> str: + """Normalise to NFC and remove Unicode control characters. + + This is applied to every string that reaches a renderer, so a crafted + parameter value cannot inject ANSI escapes or other terminal control codes + into the output. + """ + normalized = unicodedata.normalize("NFC", value) + return "".join(ch for ch in normalized if unicodedata.category(ch)[0] != "C") + + +def truncate(text: str, limit: int = 160) -> str: + """Shorten ``text`` to ``limit`` characters with a trailing ellipsis.""" + if len(text) <= limit: + return text + if limit <= 1: + return "\u2026"[:limit] + return text[: limit - 1] + "\u2026" + + +def decode_value(value: str, max_passes: int = MAX_DECODE_PASSES, plus: bool = False) -> Tuple[str, int]: + """Percent-decode ``value`` in memory, at most ``max_passes`` times. + + Returns ``(decoded_text, passes_applied)``. Decoding never raises: malformed + escapes are left as-is and invalid UTF-8 is replaced, because the goal is to + *read* a value, never to interpret or use it. + """ + decoder = unquote_plus if plus else unquote + current = value + passes = 0 + while passes < max_passes and _PERCENT in current: + try: + decoded = decoder(current, errors="replace") + except (UnicodeError, ValueError): # pragma: no cover - defensive only + break + if decoded == current: + break + current = decoded + passes += 1 + return current, passes + + +def decode_forms(value: str, max_passes: int = MAX_DECODE_PASSES) -> List[Tuple[int, str]]: + """Return every decoding stage of ``value`` as ``(passes, text)``. + + Stage 0 is the untouched value. Later stages are produced by + repeated percent-decoding, and duplicate stages are collapsed so a value + is never scored twice for the same evidence. + """ + forms: List[Tuple[int, str]] = [(0, value)] + current = value + for stage in range(1, max_passes + 1): + if _PERCENT not in current: + break + try: + decoded = unquote(current, errors="replace") + except (UnicodeError, ValueError): # pragma: no cover - defensive only + break + if decoded == current: + break + current = decoded + forms.append((stage, decoded)) + return forms + + +def dedupe(items: Iterable[str]) -> List[str]: + """Order-preserving de-duplication.""" + seen = set() + result: List[str] = [] + for item in items: + if item in seen: + continue + seen.add(item) + result.append(item) + return result + + +def display_location(host: str, resource: str) -> str: + """``host`` + ``resource`` without doubling the host. + + A finding's ``resource`` is usually a full URL (``https://a.test/view``) and + occasionally a bare path. Concatenating ``host`` onto it produces + ``a.testhttps://a.test/view`` -- a defect that has now been introduced in + three separate modules, so it lives here instead of being re-typed. + """ + from urllib.parse import urlsplit + + resource = resource or "/" + parts = urlsplit(resource) + if parts.scheme or parts.netloc: + return f"{host}{parts.path or '/'}" if parts.path else host + return f"{host}{resource.split('?', 1)[0]}" + + +def encode_display(text: str) -> str: + """Flatten ``text`` onto one display line. + + Control characters are replaced with a single space (not deleted) so that + ``"a\nb"`` does not silently become ``"ab"`` in reports. + """ + flattened = "".join( + " " if (ch.isspace() or unicodedata.category(ch)[0] == "C") else ch + for ch in text + ) + return " ".join(flattened.split()) diff --git a/pathscope/tickets.py b/pathscope/tickets.py new file mode 100644 index 0000000..07add6f --- /dev/null +++ b/pathscope/tickets.py @@ -0,0 +1,269 @@ +"""Work-item export (``--export-ticket DIR``). + +A finding is only useful once it lands where work happens. This module writes +one Markdown document per unit of work, sized to be pasted into any tracker: +title, the evidence PathScope has, the reasoning behind the score, a remediation +pointer, and the fingerprint so the ticket can be tied back to a ledger row. + +Two modes: + +* one ticket per **family** (default when clustering makes sense) -- the unit a + human actually decides, with the individual endpoints listed underneath; +* one ticket per **candidate** when a decision really is per-endpoint. + +Values are never written. Even with ``--show-values``, ticket export refuses: +the point of a ticket is that it will be pasted somewhere with different access +controls than the terminal it came from. + +Files are named for the host, route and parameter so re-running overwrites the +same ticket instead of producing duplicates. +""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass +from typing import List, Optional, Sequence +from urllib.parse import urlsplit + +from .detector import Finding, Report +from .families import Family, cluster +from .playbooks import playbook_for +from .report import DISCLAIMER + +#: Guard against a runaway export. +MAX_TICKETS = 5000 +MAX_TICKET_BYTES = 64 * 1024 + +_UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") + + +class TicketError(RuntimeError): + """Raised when tickets cannot be written.""" + + +@dataclass +class Ticket: + """One rendered work item.""" + + filename: str + title: str + body: str + fingerprints: List[str] + + @property + def size(self) -> int: + return len(self.body.encode("utf-8")) + + +def _slug(text: str, limit: int = 60) -> str: + cleaned = _UNSAFE.sub("-", text).strip("-.") + return (cleaned or "ticket")[:limit] + + +def _display_path(resource: str) -> str: + """Path part of a resource, falling back to the whole string.""" + if not resource: + return "/" + parts = urlsplit(resource) + if parts.scheme or parts.netloc: + return parts.path or "/" + return resource.split("?", 1)[0] or "/" + + +def _safe_name(index: int, host: str, route: str, parameter: str) -> str: + route_part = _slug(route.replace("/", "-"), 40) + return f"{index:04d}-{_slug(host, 32)}-{route_part}-{_slug(parameter, 32)}.md".strip("-") + + +def _evidence_table(finding: Finding) -> List[str]: + lines = [ + "| field | value |", + "|---|---|", + f"| host | `{finding.host}` |", + f"| method | `{finding.method.upper()}` |", + f"| resource | `{finding.resource}` |", + f"| location | `{finding.location}` |", + f"| parameter | `{finding.parameter}` |", + f"| score | {finding.score}/100 |", + f"| confidence | {finding.confidence} |", + f"| occurrences | {finding.occurrences} |", + f"| fingerprint | `{finding.fingerprint}` |", + ] + return lines + + +def render_ticket( + finding: Finding, + *, + index: int = 1, + family: Optional[Family] = None, + ledger_hint: str = "", +) -> Ticket: + """Render one ticket for a finding (optionally the head of a family).""" + playbook = playbook_for(finding.rule) + path = _display_path(finding.resource) + if family is not None and family.count > 1: + title = ( + f"[PathScope] {finding.host}{family.route} -- " + f"{finding.parameter} across {family.count} endpoint(s)" + ) + else: + title = ( + f"[PathScope] {finding.host}{path} -- " + f"{finding.parameter} [{finding.location}]" + ) + + lines: List[str] = [f"# {title}", ""] + lines.append(f"*{DISCLAIMER}*") + lines.append("") + lines.append(f"**Score** {finding.score}/100 · **confidence** {finding.confidence} · " + f"**rule** `{finding.rule}`") + lines.append("") + + lines.append("## Why this is here") + lines.append("") + lines.append(playbook.what_it_means) + lines.append("") + if finding.reasons: + for reason in finding.reasons: + lines.append(f"- {reason}") + lines.append("") + + lines.append("## Evidence") + lines.append("") + lines.extend(_evidence_table(finding)) + lines.append("") + if finding.rules: + lines.append(f"Rules involved: {', '.join('`' + r + '`' for r in finding.rules)}") + lines.append("") + + if family is not None and family.count > 1: + lines.append(f"## Endpoints in this family ({family.count})") + lines.append("") + for member in family.members[:50]: + lines.append( + f"- `{member.method.upper()} {member.resource}` · {member.score} · " + f"`{member.fingerprint}`" + ) + if family.count > 50: + lines.append(f"- ... and {family.count - 50} more") + lines.append("") + + lines.append("## How to confirm by hand") + lines.append("") + for step in playbook.how_to_test: + lines.append(f"1. {step}") + lines.append("") + lines.append("## What to change") + lines.append("") + for step in playbook.how_to_fix: + lines.append(f"1. {step}") + lines.append("") + + if ledger_hint: + lines.append("## Recording the decision") + lines.append("") + lines.append("```sh") + lines.append(ledger_hint.format(fingerprint=finding.fingerprint)) + lines.append("```") + lines.append("") + + lines.append("---") + lines.append("") + lines.append( + "Generated by PathScope from a local capture. No request was made and no " + "value is included in this ticket." + ) + body = "\n".join(lines) + "\n" + if len(body.encode("utf-8")) > MAX_TICKET_BYTES: + body = body[:MAX_TICKET_BYTES] + "\n\n(truncated at the ticket size limit)\n" + return Ticket( + filename=_safe_name(index, finding.host, path, finding.parameter), + title=title, + body=body, + fingerprints=[member.fingerprint for member in (family.members if family else [finding])], + ) + + +def build_tickets( + report: Report, + *, + per_candidate: bool = False, + limit: int = 0, +) -> List[Ticket]: + """Render every ticket for a report.""" + tickets: List[Ticket] = [] + if per_candidate: + for finding in report.findings: + tickets.append(render_ticket(finding, index=len(tickets) + 1)) + else: + for family in cluster(report.findings): + tickets.append( + render_ticket(family.best, index=len(tickets) + 1, family=family) + ) + if limit: + tickets = tickets[:limit] + if len(tickets) > MAX_TICKETS: + raise TicketError( + f"{len(tickets)} tickets would be written (limit {MAX_TICKETS}); " + "use --ticket-limit or cluster first" + ) + return tickets + + +def write_tickets(directory: str, tickets: Sequence[Ticket]) -> List[str]: + """Write tickets into ``directory``, returning the paths written.""" + if not directory: + raise TicketError("--export-ticket needs a directory") + try: + os.makedirs(directory, exist_ok=True) + except OSError as exc: + raise TicketError(f"cannot create '{directory}': {exc.strerror or exc}") from exc + written: List[str] = [] + for ticket in tickets: + target = os.path.join(directory, ticket.filename) + try: + with open(target, "w", encoding="utf-8", newline="\n") as handle: + handle.write(ticket.body) + except OSError as exc: + raise TicketError(f"cannot write '{target}': {exc.strerror or exc}") from exc + written.append(target) + return written + + +def render_index(tickets: Sequence[Ticket], directory: str = "") -> str: + """``INDEX.md`` listing every exported ticket.""" + lines = ["# PathScope work items", ""] + if directory: + lines.append(f"Written to `{directory}`.") + lines.append("") + if not tickets: + lines.append("No candidates: nothing to open.") + return "\n".join(lines) + "\n" + lines.append(f"{len(tickets)} ticket(s).") + lines.append("") + lines.append("| ticket | title | fingerprints |") + lines.append("|---|---|---|") + for ticket in tickets: + lines.append( + f"| [`{ticket.filename}`]({ticket.filename}) | {ticket.title} | " + f"{', '.join('`' + fp + '`' for fp in ticket.fingerprints[:3])}" + + (" ..." if len(ticket.fingerprints) > 3 else "") + + " |" + ) + lines.append("") + lines.append(DISCLAIMER) + return "\n".join(lines) + "\n" + + +__all__ = [ + "MAX_TICKETS", + "Ticket", + "TicketError", + "build_tickets", + "render_index", + "render_ticket", + "write_tickets", +] diff --git a/pathscope/tool_formats.py b/pathscope/tool_formats.py new file mode 100644 index 0000000..fca76c7 --- /dev/null +++ b/pathscope/tool_formats.py @@ -0,0 +1,785 @@ +"""More local tool exports: Postman, ZAP, mitmproxy and GraphQL. + +Every loader follows the same rules as the rest of PathScope: + +* only files the user already has are read; +* nothing is fetched, replayed, resolved or opened; +* only parameter *names* (and inert literal values already present in the + export) are carried forward, bounded in size; +* malformed entries become warnings, never crashes. + +Formats + ``postman`` Postman Collection v2.0 / v2.1 (nested ``item`` folders, + ``url.query``, ``urlencoded``/``formdata``/``raw`` bodies) + ``zap`` OWASP ZAP JSON history export (``site`` -> ``alerts`` or + ``messages``) + ``mitmproxy`` mitmproxy ``flow`` JSON export (``request`` with ``query`` + and ``content``) + ``graphql`` GraphQL introspection response, reduced to argument names of + queries and mutations +""" + +from __future__ import annotations + +import json +import re +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import parse_qsl + +from .sources import ( + LOCATION_FORM, + LOCATION_JSON, + LOCATION_QUERY, + HarError, + LoadResult, + Parameter, + Request, + URLInfo, + URLParseError, + _as_text, + _json_parameters, + canonical, + parse_url, + query_parameters, +) +from .textutil import sanitize_text + +INPUT_FORMAT_POSTMAN = "postman" +INPUT_FORMAT_ZAP = "zap" +INPUT_FORMAT_MITM = "mitmproxy" +INPUT_FORMAT_GRAPHQL = "graphql" +INPUT_FORMAT_COOKIES = "cookies" + +#: Identifier used in reports for all these formats. +SOURCE_POSTMAN = "postman" +SOURCE_ZAP = "zap" +SOURCE_MITM = "mitmproxy" +SOURCE_GRAPHQL = "graphql" +SOURCE_COOKIES = "cookies" + +#: Hard limits (shared with the other readers). +MAX_COLLECTION_ITEMS = 50000 +MAX_GRAPHQL_DEPTH = 12 +MAX_TEXT_BODY = 4 * 1024 * 1024 + +#: Netscape cookie-file separator is a TAB; the regex is fixed, not user input. +_COOKIE_SPLIT_RE = re.compile(r"\t+") + + +# --------------------------------------------------------------------------- +# Postman Collection v2.0 / v2.1 +# --------------------------------------------------------------------------- +def looks_like_postman(payload: Any) -> bool: + return isinstance(payload, dict) and isinstance(payload.get("info"), dict) and ( + "schema" in payload["info"] or "item" in payload + ) and isinstance(payload.get("item"), list) + + +def _postman_url(raw_url: Any) -> Optional[str]: + """Turn a Postman ``url`` (string or object) into a URL string.""" + if isinstance(raw_url, str): + candidate = raw_url.strip() + return candidate if candidate.lower().startswith(("http://", "https://")) else None + if isinstance(raw_url, dict): + if isinstance(raw_url.get("raw"), str) and raw_url["raw"].strip(): + raw = raw_url["raw"].strip() + return raw if raw.lower().startswith(("http://", "https://")) else None + host = raw_url.get("host") + if isinstance(host, list): + host = ".".join(str(part) for part in host) + if not isinstance(host, str) or not host: + return None + path = raw_url.get("path") + if isinstance(path, list): + path = "/".join(str(part) for part in path) + if not isinstance(path, str): + path = "" + protocol = str(raw_url.get("protocol") or "https").lower() + if protocol not in ("http", "https"): + protocol = "https" + port = raw_url.get("port") + netloc = host if not port else f"{host}:{port}" + return f"{protocol}://{netloc}/{path.lstrip('/')}" + return None + + +def _postman_query(raw_url: Any) -> List[Parameter]: + parameters: List[Parameter] = [] + if isinstance(raw_url, dict) and isinstance(raw_url.get("query"), list): + for entry in raw_url["query"]: + if not isinstance(entry, dict): + continue + name = entry.get("key") + if not isinstance(name, str) or not name or entry.get("disabled") is True: + continue + parameters.append( + Parameter(name=name, value=_as_text(entry.get("value")), location=LOCATION_QUERY) + ) + return parameters + + +def _postman_body(body: Any, label: str) -> List[Parameter]: + parameters: List[Parameter] = [] + if not isinstance(body, dict): + return parameters + mode = str(body.get("mode") or "").lower() + for key in ("urlencoded", "formdata"): + entries = body.get(key) + if not isinstance(entries, list): + continue + for entry in entries: + if not isinstance(entry, dict): + continue + name = entry.get("key") + if not isinstance(name, str) or not name or entry.get("disabled") is True: + continue + value = entry.get("value") + if value is None and isinstance(entry.get("src"), str): + value = entry["src"] + parameters.append( + Parameter(name=name, value=_as_text(value), location=LOCATION_FORM) + ) + if mode == "raw" and isinstance(body.get("raw"), str) and body["raw"].strip(): + raw = body["raw"][:MAX_TEXT_BODY] + language = str((body.get("options") or {}).get("raw", {}).get("language") or "").lower() + stripped = raw.lstrip() + if language == "json" or stripped.startswith(("{", "[")): + try: + payload = json.loads(raw) + except ValueError: + return parameters + parameters.extend(_json_parameters(payload, [], label)) + elif "=" in raw: + for name, value in parse_qsl(raw, keep_blank_values=True): + if name: + parameters.append( + Parameter(name=sanitize_text(name), value=sanitize_text(value), location=LOCATION_FORM) + ) + return parameters + + +def _walk_items(items: Any, label: str, warnings: List[str], requests: List[Request]) -> None: + if not isinstance(items, list): + return + stack = list(reversed(items)) + while stack and len(requests) < MAX_COLLECTION_ITEMS: + item = stack.pop() + if not isinstance(item, dict): + continue + if isinstance(item.get("item"), list): + # Folder: descend, preserving order. + stack.extend(reversed(item["item"])) + continue + request = item.get("request") + name = sanitize_text(str(item.get("name") or "")) + if isinstance(request, str): + url = request.strip() + request = {"url": url} + if not isinstance(request, dict): + continue + url = _postman_url(request.get("url")) + if not url: + warnings.append(f"{label}: item '{name or '?'}' has no usable URL") + continue + try: + info = parse_url(url) + except URLParseError as exc: + warnings.append(f"{label}: item '{name or '?'}' skipped ({exc})") + continue + parameters = list(query_parameters(info.query)) + parameters.extend(_postman_query(request.get("url"))) + parameters = _merge_parameters(parameters) + parameters.extend(_postman_body(request.get("body"), label)) + method = str(request.get("method") or "GET").upper()[:12] + requests.append( + Request( + url=info, + source_type=SOURCE_POSTMAN, + source_label=label, + parameters=_merge_parameters(parameters), + method=method, + index=len(requests), + ) + ) + + +def load_postman(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse a Postman Collection v2.0/v2.1 export.""" + label = source_label or label + try: + payload = json.loads(text.lstrip("\ufeff")) + except ValueError as exc: + raise HarError(f"{label}: not valid JSON ({exc})") from exc + if not looks_like_postman(payload): + raise HarError( + f"{label}: not a Postman v2 collection (expected 'info' and 'item')" + ) + result = LoadResult() + _walk_items(payload.get("item"), label, result.warnings, result.requests) + if not result.requests: + result.warnings.append(f"{label}: collection contains no usable requests") + return result + + +def load_postman_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_postman(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# OWASP ZAP JSON export +# --------------------------------------------------------------------------- +def looks_like_zap(payload: Any) -> bool: + if not isinstance(payload, dict): + return False + if "site" in payload and isinstance(payload["site"], (list, dict)): + return True + if "alerts" in payload and isinstance(payload["alerts"], list): + return True + return isinstance(payload.get("@programName"), str) and "ZAP" in str(payload.get("@programName")) + + +def _zap_sites(payload: Any) -> List[Dict[str, Any]]: + sites = payload.get("site") if isinstance(payload, dict) else None + if isinstance(sites, dict): + return [sites] + if isinstance(sites, list): + return [site for site in sites if isinstance(site, dict)] + return [] + + +def _zap_message_urls(message: Any) -> List[str]: + urls: List[str] = [] + if not isinstance(message, dict): + return urls + for key in ("url", "uri", "endpoint", "matched-at", "requestHeader", "requestUri"): + value = message.get(key) + if isinstance(value, str): + match = re.search(r"https?://[^\s\"'<>]+", value) + if match: + urls.append(match.group(0)) + break + if key == "requestUri" and value.startswith("/"): + host = message.get("host") or message.get("hostname") or "" + if isinstance(host, str) and host: + urls.append(f"http://{host}{value}") + break + return urls + + +def _zap_request_text(message: Any) -> List[Parameter]: + """Parse a recorded request header/body for parameters.""" + parameters: List[Parameter] = [] + if not isinstance(message, dict): + return parameters + header = message.get("requestHeader") or "" + body = message.get("requestBody") or message.get("body") or "" + if isinstance(header, str): + head, _sep, inline_body = header.partition("\n\n") + if not isinstance(body, str) or not body: + body = inline_body + headers: Dict[str, str] = {} + for line in head.splitlines(): + name, _colon, value = line.partition(":") + if _colon: + headers.setdefault(name.strip().lower(), value.strip()) + content_type = headers.get("content-type", "").lower() + else: + content_type = "" + if isinstance(body, str) and body: + body = body[:MAX_TEXT_BODY] + if "application/json" in content_type or body.lstrip().startswith(("{", "[")): + try: + payload = json.loads(body) + except ValueError: + payload = None + if payload is not None: + parameters.extend(_json_parameters(payload, [], "zap")) + elif "x-www-form-urlencoded" in content_type or "=" in body: + for name, value in parse_qsl(body, keep_blank_values=True): + if name: + parameters.append( + Parameter(name=sanitize_text(name), value=sanitize_text(value), location=LOCATION_FORM) + ) + return parameters + + +def load_zap(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse a ZAP JSON history/alert export into requests.""" + label = source_label or label + try: + payload = json.loads(text.lstrip("\ufeff")) + except ValueError as exc: + raise HarError(f"{label}: not valid JSON ({exc})") from exc + if not looks_like_zap(payload): + raise HarError( + f"{label}: not a ZAP JSON export (expected 'site' or 'alerts')" + ) + result = LoadResult() + seen: set = set() + urls: List[Tuple[str, Any]] = [] + for site in _zap_sites(payload): + for message in site.get("messages") or []: + for url in _zap_message_urls(message): + urls.append((url, message)) + if not urls: + for alert in payload.get("alerts") or []: + if isinstance(alert, dict): + for url in _zap_message_urls(alert): + urls.append((url, alert)) + if isinstance(alert.get("instances"), list): + for instance in alert["instances"]: + for url in _zap_message_urls(instance): + urls.append((url, instance)) + for url, message in urls: + if url in seen: + continue + seen.add(url) + try: + info = parse_url(url) + except URLParseError: + result.skipped += 1 + continue + parameters = list(query_parameters(info.query)) + parameters.extend(_zap_request_text(message)) + result.requests.append( + Request( + url=info, + source_type=SOURCE_ZAP, + source_label=label, + parameters=_merge_parameters(parameters), + method=str(message.get("method") or "GET").upper()[:12] + if isinstance(message, dict) + else "GET", + index=len(result.requests), + ) + ) + if not result.requests: + result.warnings.append(f"{label}: no usable requests found in ZAP export") + return result + + +def load_zap_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_zap(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# mitmproxy flow export (JSON) +# --------------------------------------------------------------------------- +def looks_like_mitm(payload: Any) -> bool: + entries = payload if isinstance(payload, list) else [payload] + for entry in entries[:3]: + if not isinstance(entry, dict): + continue + request = entry.get("request") + if isinstance(request, dict) and ( + "scheme" in request + or "host" in request + or ("path" in request and "query" in request) + or isinstance(request.get("url"), str) + ): + return True + return False + + +def _mitm_url(request: Any) -> Optional[str]: + if not isinstance(request, dict): + return None + url = request.get("url") + if isinstance(url, str) and url.lower().startswith(("http://", "https://")): + return url + scheme = str(request.get("scheme") or "https").lower() + if scheme not in ("http", "https"): + scheme = "https" + host = request.get("host") + if not isinstance(host, str) or not host: + return None + port = request.get("port") + netloc = host if not port or str(port) in ("80", "443") else f"{host}:{port}" + path = request.get("path") or "/" + if not isinstance(path, str): + path = "/" + query = request.get("query") + if isinstance(query, list): + pairs = [] + for entry in query: + if isinstance(entry, dict) and isinstance(entry.get("key"), str): + pairs.append((entry["key"], _as_text(entry.get("value")))) + if pairs: + from urllib.parse import urlencode + + path = f"{path}?{urlencode(pairs, doseq=True)}" + elif isinstance(query, str) and query: + path = f"{path}?{query}" + return f"{scheme}://{netloc}{path if path.startswith('/') else '/' + path}" + + +def _mitm_body(request: Any) -> List[Parameter]: + if not isinstance(request, dict): + return [] + content = request.get("content") + if isinstance(content, dict): + text_value = content.get("text") + mime = str(content.get("mimeType") or content.get("contentType") or "").lower() + else: + text_value = content if isinstance(content, str) else None + mime = "" + if not isinstance(text_value, str) or not text_value.strip(): + return [] + body = text_value[:MAX_TEXT_BODY] + if "json" in mime or body.lstrip().startswith(("{", "[")): + try: + payload = json.loads(body) + except ValueError: + return [] + return _json_parameters(payload, [], "mitmproxy") + if "x-www-form-urlencoded" in mime or "=" in body: + parameters = [] + for name, value in parse_qsl(body, keep_blank_values=True): + if name: + parameters.append( + Parameter(name=sanitize_text(name), value=sanitize_text(value), location=LOCATION_FORM) + ) + return parameters + return [] + + +def load_mitm(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Parse a mitmproxy ``flow`` JSON export (single flow or a list).""" + label = source_label or label + try: + payload = json.loads(text.lstrip("\ufeff")) + except ValueError as exc: + raise HarError(f"{label}: not valid JSON ({exc})") from exc + entries = payload if isinstance(payload, list) else [payload] + if not looks_like_mitm(payload): + raise HarError( + f"{label}: not a mitmproxy flow export (expected 'request' objects)" + ) + result = LoadResult() + seen: set = set() + for entry in entries[:MAX_COLLECTION_ITEMS]: + if not isinstance(entry, dict): + continue + request = entry.get("request") + url = _mitm_url(request) + if not url: + result.skipped += 1 + continue + if url in seen: + continue + seen.add(url) + try: + info = parse_url(url) + except URLParseError: + result.skipped += 1 + continue + parameters = list(query_parameters(info.query)) + parameters.extend(_mitm_body(request)) + result.requests.append( + Request( + url=info, + source_type=SOURCE_MITM, + source_label=label, + parameters=_merge_parameters(parameters), + method=str(request.get("method") or "GET").upper()[:12], + index=len(result.requests), + ) + ) + if not result.requests: + result.warnings.append(f"{label}: no usable flows found") + return result + + +def load_mitm_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_mitm(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# GraphQL introspection +# --------------------------------------------------------------------------- +def _graphql_schema(payload: Any) -> Any: + if not isinstance(payload, dict): + return None + schema = payload.get("__schema") + if schema is None and isinstance(payload.get("data"), dict): + schema = payload["data"].get("__schema") + return schema + + +def looks_like_graphql(payload: Any) -> bool: + schema = _graphql_schema(payload) + if not isinstance(schema, dict): + return False + types = schema.get("types") + return isinstance(schema.get("queryType"), dict) and isinstance(types, (list, dict)) + + +def _graphql_arguments(schema: Any, warnings: List[str], label: str) -> List[Parameter]: + parameters: List[Parameter] = [] + if not isinstance(schema, dict): + return parameters + types = schema.get("types") + type_list: List[Dict[str, Any]] = [] + if isinstance(types, list): + type_list = [entry for entry in types if isinstance(entry, dict)] + elif isinstance(types, dict): + type_list = [entry for entry in types.values() if isinstance(entry, dict)] + + root_names: set = set() + for key in ("queryType", "mutationType", "subscriptionType"): + node = schema.get(key) + if isinstance(node, dict) and isinstance(node.get("name"), str): + root_names.add(node["name"]) + + def walk_args(args: Any, prefix: str, depth: int) -> None: + if depth > MAX_GRAPHQL_DEPTH or not isinstance(args, list): + return + for arg in args: + if not isinstance(arg, dict): + continue + name = arg.get("name") + if not isinstance(name, str) or not name: + continue + path = f"{prefix}.{name}" if prefix else name + parameters.append( + Parameter(name=path, value="", location=LOCATION_FORM) + ) + walk_args(arg.get("args"), path, depth + 1) + + for type_entry in type_list: + type_name = type_entry.get("name") + if not isinstance(type_name, str): + continue + if root_names and type_name not in root_names: + # Only the query/mutation/subscription roots describe entry points. + continue + for field in type_entry.get("fields") or []: + if not isinstance(field, dict) or not isinstance(field.get("name"), str): + continue + walk_args(field.get("args"), "", 0) + return parameters + + +def load_graphql(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Reduce a GraphQL introspection result to per-operation argument names.""" + label = source_label or label + try: + payload = json.loads(text.lstrip("\ufeff")) + except ValueError as exc: + raise HarError(f"{label}: not valid JSON ({exc})") from exc + if not looks_like_graphql(payload): + raise HarError( + f"{label}: not a GraphQL introspection result (expected '__schema')" + ) + schema = _graphql_schema(payload) + result = LoadResult() + parameters = _graphql_arguments(schema, result.warnings, label) + if not parameters: + result.warnings.append(f"{label}: introspection result declares no arguments") + return result + host = "graphql.local" + root_names: Dict[str, Any] = {} + for key in ("queryType", "mutationType"): + node = (schema or {}).get(key) + if isinstance(node, dict) and isinstance(node.get("name"), str): + root_names[node["name"]] = key + + # One synthetic request per operation type so findings stay attributable. + grouped: Dict[str, List[Parameter]] = {} + for parameter in parameters: + grouped.setdefault("query", []).append(parameter) + for method, entries in grouped.items(): + info = URLInfo( + raw=f"https://{host}/graphql", + scheme="https", + host=host, + port=None, + path="/graphql", + query="", + ) + result.requests.append( + Request( + url=info, + source_type=SOURCE_GRAPHQL, + source_label=label, + parameters=entries, + method="POST", + index=len(result.requests), + ) + ) + return result + + +def load_graphql_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_graphql(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# Netscape cookie jars (curl/Chromium export) +# --------------------------------------------------------------------------- +def looks_like_cookies(text: str) -> bool: + lines = [line for line in text.splitlines() if line.strip()] + if not lines: + return False + if lines[0].startswith("# Netscape HTTP Cookie File"): + return True + tabs = sum(1 for line in lines[:20] if "\t" in line and not line.startswith("#")) + return tabs >= 2 + + +def load_cookies(text: str, label: str, source_label: Optional[str] = None) -> LoadResult: + """Treat a Netscape cookie file as a name-only inventory. + + Cookie values are secrets: they are deliberately discarded. Only the + *names* survive, attached to a synthetic request, so a cookie called + ``file_path`` can be reviewed without exposing its value. + """ + label = source_label or label + result = LoadResult() + names: List[str] = [] + seen: set = set() + for line in text.splitlines(): + line = line.rstrip("\r\n") + if not line or line.startswith("#"): + continue + fields = _COOKIE_SPLIT_RE.split(line) + if len(fields) < 7: + continue + name = sanitize_text(fields[5]).strip() + if not name or len(name) > 120 or name in seen: + continue + seen.add(name) + names.append(name) + if not names: + raise HarError(f"{label}: no cookie names found (expected a Netscape cookie file)") + info = URLInfo( + raw="https://cookies.local/", + scheme="https", + host="cookies.local", + port=None, + path="/", + query="", + ) + result.requests.append( + Request( + url=info, + source_type=SOURCE_COOKIES, + source_label=label, + parameters=[ + Parameter(name=name, value="", location=LOCATION_FORM) for name in names + ], + method="GET", + index=0, + ) + ) + return result + + +def load_cookies_file(path: str) -> LoadResult: + import os + + from .sources import read_text + + return load_cookies(read_text(path), os.path.basename(path) or path, source_label=path) + + +# --------------------------------------------------------------------------- +# Shared helpers +# --------------------------------------------------------------------------- +def _merge_parameters(parameters: List[Parameter]) -> List[Parameter]: + """Drop duplicate (location, canonical name) pairs, keeping the first.""" + unique: List[Parameter] = [] + seen = set() + for parameter in parameters: + key = (parameter.location, canonical(parameter.name)) + if key in seen: + continue + seen.add(key) + unique.append(parameter) + return unique + + +# --------------------------------------------------------------------------- +# Detection and dispatch +# --------------------------------------------------------------------------- +def detect_tool_format(text: str, path: str = "") -> Optional[str]: + """Return one of this module's format ids, or ``None``.""" + stripped = text.lstrip("\ufeff \t\r\n") + lowered = (path or "").lower() + if stripped.startswith("{") or stripped.startswith("["): + try: + payload = json.loads(stripped) + except ValueError: + payload = None + if looks_like_postman(payload): + return INPUT_FORMAT_POSTMAN + if looks_like_zap(payload): + return INPUT_FORMAT_ZAP + if looks_like_graphql(payload): + return INPUT_FORMAT_GRAPHQL + if looks_like_mitm(payload): + return INPUT_FORMAT_MITM + if looks_like_cookies(text): + return INPUT_FORMAT_COOKIES + return None + + +def load_tool_file(path: str, fmt: str) -> LoadResult: + if fmt == INPUT_FORMAT_POSTMAN: + return load_postman_file(path) + if fmt == INPUT_FORMAT_ZAP: + return load_zap_file(path) + if fmt == INPUT_FORMAT_MITM: + return load_mitm_file(path) + if fmt == INPUT_FORMAT_GRAPHQL: + return load_graphql_file(path) + if fmt == INPUT_FORMAT_COOKIES: + return load_cookies_file(path) + raise HarError(f"unsupported input format '{fmt}'") + + +def load_tool_text(text: str, fmt: str, label: str) -> LoadResult: + if fmt == INPUT_FORMAT_POSTMAN: + return load_postman(text, label) + if fmt == INPUT_FORMAT_ZAP: + return load_zap(text, label) + if fmt == INPUT_FORMAT_MITM: + return load_mitm(text, label) + if fmt == INPUT_FORMAT_GRAPHQL: + return load_graphql(text, label) + if fmt == INPUT_FORMAT_COOKIES: + return load_cookies(text, label) + raise HarError(f"unsupported input format '{fmt}'") + + +__all__ = [ + "INPUT_FORMAT_POSTMAN", + "INPUT_FORMAT_ZAP", + "INPUT_FORMAT_MITM", + "INPUT_FORMAT_GRAPHQL", + "INPUT_FORMAT_COOKIES", + "detect_tool_format", + "load_cookies", + "load_graphql", + "load_mitm", + "load_postman", + "load_tool_file", + "load_tool_text", + "load_zap", +] diff --git a/pathscope/tui.py b/pathscope/tui.py new file mode 100644 index 0000000..957976c --- /dev/null +++ b/pathscope/tui.py @@ -0,0 +1,419 @@ +"""A small, dependency-free terminal reviewer (``--tui``). + +The TUI is a *viewer + marker*: it never runs a scan, never touches the network +and never writes anything but the reviewed ledger you point it at. It is built +on the standard library's :mod:`curses`, so it works over SSH on any Kali box. + +Layout + ┌ candidates ─────────────┬ details ──────────────────────────┐ + │ # score host param │ parameter, host, rule, reasons │ + │ ... │ fingerprint, status │ + └─────────────────────────┴───────────────────────────────────┘ + f filter c confidence m mark reviewed u unmark s save ? help q quit + +Because curses needs a real terminal, the screen logic is isolated in +:class:`ReviewScreen` and the pure parts (filtering, navigation, status text) +are ordinary functions that the test suite exercises without a TTY. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import List, Optional, Sequence, Tuple + +from .detector import Finding, Report + +#: Keys handled by the screen (documented in the help pane). +HELP_LINES = ( + "PathScope reviewer", + "", + " j / down next candidate", + " k / up previous candidate", + " g / G first / last candidate", + " pgup/pgdn move one page", + " / filter by text (host, parameter, rule)", + " c cycle confidence filter (all -> high -> medium -> low)", + " m mark current candidate reviewed", + " u unmark current candidate", + " s save reviewed set to the ledger", + " r refresh the view", + " ? toggle this help", + " q quit", + "", + "Marking only records the fingerprint; no request is ever sent.", +) + +BANDS = ("high", "medium", "low") + + +class TuiUnavailable(RuntimeError): + """Raised when curses cannot be used (no TTY, dumb terminal).""" + + +@dataclass +class ReviewState: + """Everything the reviewer needs, independent of the screen.""" + + report: Report + marked: set = field(default_factory=set) + filter_text: str = "" + bands: Tuple[str, ...] = () # empty = all confidence levels + band_index: int = 0 # 0=all, 1=high, 2=medium, 3=low + cursor: int = 0 + dirty: bool = False + + # -- filtering -------------------------------------------------------- + def visible(self) -> List[Finding]: + """Findings after the text and confidence filters, in report order.""" + needle = self.filter_text.lower().strip() + band = BANDS[self.band_index - 1] if self.band_index else "" + rows: List[Finding] = [] + for finding in self.report.findings: + if band and finding.confidence != band: + continue + if needle: + haystack = " ".join( + ( + finding.host, + finding.parameter, + finding.rule, + finding.location, + finding.fingerprint, + ) + ).lower() + if needle not in haystack: + continue + rows.append(finding) + return rows + + # -- navigation ------------------------------------------------------- + def clamp(self) -> None: + rows = self.visible() + if not rows: + self.cursor = 0 + else: + self.cursor = max(0, min(self.cursor, len(rows) - 1)) + + def move(self, delta: int) -> None: + self.cursor += delta + self.clamp() + + def first(self) -> None: + self.cursor = 0 + + def last(self) -> None: + self.cursor = max(0, len(self.visible()) - 1) + + def page(self, size: int) -> None: + self.move(max(1, size)) + + def current(self) -> Optional[Finding]: + rows = self.visible() + return rows[self.cursor] if 0 <= self.cursor < len(rows) else None + + # -- filters ---------------------------------------------------------- + def set_filter(self, text: str) -> None: + self.filter_text = text + self.cursor = 0 + self.clamp() + + def cycle_band(self) -> str: + self.band_index = (self.band_index + 1) % (len(BANDS) + 1) + self.cursor = 0 + self.clamp() + return self.band_label() + + def band_label(self) -> str: + return BANDS[self.band_index - 1] if self.band_index else "all" + + # -- marking ---------------------------------------------------------- + def toggle_mark(self) -> bool: + finding = self.current() + if finding is None: + return False + if finding.fingerprint in self.marked: + self.marked.discard(finding.fingerprint) + else: + self.marked.add(finding.fingerprint) + self.dirty = True + return True + + def unmark(self) -> bool: + finding = self.current() + if finding is None: + return False + self.marked.discard(finding.fingerprint) + self.dirty = True + return True + + def status_line(self) -> str: + rows = self.visible() + position = f"{self.cursor + 1}/{len(rows)}" if rows else "0/0" + return ( + f"{self.report.candidate_count} candidate(s) | {position} | " + f"conf={self.band_label()} | marked={len(self.marked)}" + + (f" | filter='{self.filter_text}'" if self.filter_text else "") + + (" | UNSAVED" if self.dirty else "") + ) + + +def build_state(report: Report, marked: Optional[Sequence[str]] = None) -> ReviewState: + """Create a :class:`ReviewState` from a report and optional ledger set.""" + return ReviewState(report=report, marked=set(marked or ())) + + +# --------------------------------------------------------------------------- +# curses screen +# --------------------------------------------------------------------------- +class ReviewScreen: + """Thin curses wrapper around :class:`ReviewState`.""" + + def __init__(self, state: ReviewState) -> None: + self.state = state + self.stdscr = None + self.show_help = False + self.message = "" + + # -- lifecycle -------------------------------------------------------- + def open(self) -> None: + try: + import curses + except ImportError as exc: # pragma: no cover - Windows without curses + raise TuiUnavailable(f"curses is unavailable: {exc}") from exc + try: + self.stdscr = curses.initscr() + curses.noecho() + curses.cbreak() + self.stdscr.keypad(True) + try: + curses.curs_set(0) + except curses.error: # pragma: no cover - some terminals + pass + except Exception as exc: # pragma: no cover - terminal edge cases + self.close() + raise TuiUnavailable(f"cannot initialise the terminal: {exc}") from exc + + def close(self) -> None: + try: + import curses + + if self.stdscr is not None: + self.stdscr.keypad(False) + curses.nocbreak() + curses.echo() + curses.endwin() + except Exception: # pragma: no cover - best effort restore + pass + self.stdscr = None + + # -- drawing ---------------------------------------------------------- + def draw(self) -> None: + import curses + + screen = self.stdscr + if screen is None: # pragma: no cover - defensive + return + screen.erase() + height, width = screen.getmaxyx() + rows = self.state.visible() + + title = f" PathScope reviewer - {self.state.status_line()} " + _safe_addstr(screen, 0, 0, title[: width - 1], curses.A_REVERSE) + + if self.show_help: + for index, line in enumerate(HELP_LINES, start=2): + if index >= height - 2: + break + _safe_addstr(screen, index, 2, line[: width - 3]) + _footer(screen, height - 1, width, " ? close help q quit ") + screen.refresh() + return + + list_width = max(30, min(60, width // 2)) + _safe_addstr(screen, 1, 1, "Candidates"[: list_width - 2], curses.A_BOLD) + visible_capacity = max(1, height - 4) + start = max(0, min(self.state.cursor, max(0, len(rows) - visible_capacity))) + for offset in range(visible_capacity): + index = start + offset + if index >= len(rows): + break + finding = rows[index] + marker = "*" if finding.fingerprint in self.state.marked else " " + line = ( + f"{marker}{index + 1:>3} {finding.score:>3} " + f"{finding.confidence[:4]:<4} {finding.parameter[:18]:<18} " + f"{finding.host[: max(0, list_width - 34)]}" + ) + attribute = curses.A_REVERSE if index == self.state.cursor else 0 + _safe_addstr(screen, 2 + offset, 0, line.ljust(list_width)[: list_width], attribute) + + _safe_addstr(screen, 1, list_width + 2, "Details"[: width - list_width - 3], curses.A_BOLD) + finding = self.state.current() + detail_lines = self._detail_lines(finding) if finding else ["No candidate selected."] + for offset, line in enumerate(detail_lines[: height - 4]): + _safe_addstr(screen, 2 + offset, list_width + 2, line[: width - list_width - 4]) + + footer = " j/k move / filter c confidence m mark u unmark s save ? help q quit " + if self.message: + footer = f" {self.message} " + footer + _footer(screen, height - 1, width, footer) + screen.refresh() + + def _detail_lines(self, finding: Finding) -> List[str]: + lines = [ + f"#{finding.index} {finding.parameter}", + f"host {finding.host}", + f"location {finding.location}", + f"rule {finding.rule}", + f"score {finding.score}/100 ({finding.confidence})", + f"fingerprint {finding.fingerprint}", + f"request {finding.method} {finding.resource}", + f"marked {'yes' if finding.fingerprint in self.state.marked else 'no'}", + "", + "Why:", + ] + lines.extend(f" - {reason}" for reason in finding.reasons) + return lines + + # -- input ------------------------------------------------------------ + def handle_key(self, key: int) -> bool: + """Apply one key. Returns False when the screen should close.""" + import curses + + state = self.state + page = max(1, (self.stdscr.getmaxyx()[0] if self.stdscr else 24) - 4) + if key in (ord("q"), 27): + return False + if key == ord("?"): + self.show_help = not self.show_help + elif key in (ord("j"), curses.KEY_DOWN): + state.move(1) + elif key in (ord("k"), curses.KEY_UP): + state.move(-1) + elif key == ord("g"): + state.first() + elif key == ord("G"): + state.last() + elif key == curses.KEY_NPAGE: + state.page(page) + elif key == curses.KEY_PPAGE: + state.page(-page) + elif key == ord("c"): + self.message = f"confidence: {state.cycle_band()}" + elif key == ord("m"): + if state.toggle_mark(): + self.message = "marked" if state.current() and state.current().fingerprint in state.marked else "unmarked" + elif key == ord("u"): + if state.unmark(): + self.message = "unmarked" + elif key == ord("r"): + state.clamp() + self.message = "refreshed" + elif key == ord("s"): + self.message = "__SAVE__" + elif key == ord("/"): + self.message = "__FILTER__" + return True + + def prompt(self, label: str, initial: str = "") -> str: + """Read a single-line string at the bottom of the screen.""" + import curses + + screen = self.stdscr + if screen is None: # pragma: no cover - defensive + return initial + height, width = screen.getmaxyx() + try: + curses.curs_set(1) + except curses.error: # pragma: no cover + pass + buffer = list(initial) + while True: + _footer(screen, height - 1, width, f" {label}: {''.join(buffer)}") + screen.refresh() + key = screen.getch() + if key in (10, 13, curses.KEY_ENTER): + break + if key == 27: + buffer = [] + break + if key in (curses.KEY_BACKSPACE, 127, 8): + if buffer: + buffer.pop() + continue + if 32 <= key < 127: + buffer.append(chr(key)) + try: + curses.curs_set(0) + except curses.error: # pragma: no cover + pass + return "".join(buffer) + + # -- main loop -------------------------------------------------------- + def run(self, save: Optional[callable] = None) -> int: + """Event loop. Returns the number of fingerprints marked.""" + screen = self.stdscr + if screen is None: # pragma: no cover - defensive + return 0 + while True: + self.draw() + key = screen.getch() + if not self.handle_key(key): + break + if self.message == "__SAVE__": + self.message = "" + if save is not None: + try: + count = save(sorted(self.state.marked)) + except Exception as exc: # noqa: BLE001 - show, never crash + self.message = f"save failed: {exc}" + else: + self.state.dirty = False + self.message = f"saved {count} fingerprint(s)" + elif self.message == "__FILTER__": + self.message = "" + text = self.prompt("filter", self.state.filter_text) + self.state.set_filter(text) + return len(self.state.marked) + + +def _safe_addstr(screen, y: int, x: int, text: str, attribute: int = 0) -> None: + """``addstr`` that tolerates the bottom-right corner and narrow terminals.""" + try: + screen.addstr(y, x, text, attribute) + except Exception: # noqa: BLE001 - curses raises at the screen edge + pass + + +def _footer(screen, y: int, width: int, text: str) -> None: + try: + import curses + + screen.addstr(y, 0, text[: width - 1].ljust(width - 1), curses.A_REVERSE) + except Exception: # noqa: BLE001 + pass + + +def available() -> bool: + """True when a curses screen can probably be opened.""" + import sys + + try: + import curses # noqa: F401 + except ImportError: # pragma: no cover - platform dependent + return False + try: + return bool(sys.stdout.isatty() and sys.stdin.isatty()) + except Exception: # pragma: no cover - exotic streams + return False + + +__all__ = [ + "BANDS", + "HELP_LINES", + "ReviewScreen", + "ReviewState", + "TuiUnavailable", + "available", + "build_state", +] diff --git a/pathscope/valueshape.py b/pathscope/valueshape.py new file mode 100644 index 0000000..0cf2f9b --- /dev/null +++ b/pathscope/valueshape.py @@ -0,0 +1,244 @@ +"""Value-shape demotions. + +A parameter called ``file`` whose value is a UUID, a hash, a JWT, a base64 +blob, an e-mail address, an IP address, or a plain bool/number/short enum is +usually not a filesystem path. These shapes produce *negative* evidence so the +candidate ranks lower without ever being hidden silently: the demotion rule +name and the reason appear in ``--explain``, in every report format, and can be +tuned with ``--rules`` or removed with ``--disable-rule``. + +Everything here inspects the value as an inert string. Nothing is decoded into +a file, fetched, or resolved. +""" + +from __future__ import annotations + +import re +from typing import List, Optional, Tuple + +#: Rule ids (kept in sync with :data:`pathscope.rules.DEFAULT_RULES`). +RULE_UUID = "value-demote-uuid" +RULE_HASH = "value-demote-hash" +RULE_JWT = "value-demote-jwt" +RULE_BASE64 = "value-demote-base64" +RULE_EMAIL = "value-demote-email" +RULE_IP = "value-demote-ip" +RULE_SCALAR = "value-demote-scalar" + +#: A canonical UUID, either hyphenated or as 32 bare hex characters. +UUID_RE = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", + re.IGNORECASE, +) +UUID_BARE_RE = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE) +#: MD5 / SHA-1 / SHA-256 / SHA-512 hex digests, or any 32+ hex run. +HASH_RE = re.compile(r"^[0-9a-f]{32,128}$", re.IGNORECASE) +HASH_PREFIXED_RE = re.compile(r"^(md5|sha1|sha256|sha512)[:=][0-9a-f]{32,128}$", re.IGNORECASE) +#: Three base64url segments separated by dots. +JWT_RE = re.compile( + r"^eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{8,}$" +) +#: Long base64-looking blob (no separators, mixed case, optional padding). +BASE64_RE = re.compile(r"^[A-Za-z0-9+/_-]{40,}={0,2}$") +EMAIL_RE = re.compile(r"^[^@\s/\\]{1,64}@[A-Za-z0-9.-]{3,253}$") +#: IPv4 literal (no validation of octet ranges beyond three digits). +IPV4_RE = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}$") +#: Bracket-less IPv6 literal, only when it contains at least two colons. +IPV6_RE = re.compile(r"^[0-9a-f:]{4,45}$", re.IGNORECASE) +NUMBER_RE = re.compile(r"^-?\d{1,20}(?:\.\d{1,10})?$") +#: Drive-letter or UNC paths (the letter/path shape only, never the value). +WIN_PATH_RE = re.compile(r"^(?:[A-Za-z]:[\\/]|\\\\[^\\/])") +HEX_RE = re.compile(r"^0x[0-9a-f]{1,16}$", re.IGNORECASE) + +#: Short, common enum-like tokens that never name a file on their own. +ENUM_TOKENS = frozenset( + """ + true false null none nil yes no on off enable enabled disable disabled + active inactive all any default auto public private inherit readonly + read write admin user guest ascending descending asc desc ascendent + """.split() +) +#: Longer enum-like tokens that are still not paths. +ENUM_LONG_TOKENS = frozenset( + """ + undefined unset unknown pending deleted archived completed failed success + approved rejected visible hidden internal external ephemeral + """.split() +) + +MAX_REASON_VALUE = 40 + + +def _short(value: str) -> str: + """Short, sanitized excerpt used inside a reason string.""" + text = value.strip() + if len(text) <= MAX_REASON_VALUE: + return text + return text[: MAX_REASON_VALUE - 1] + "…" + + +def _looks_like_base64(value: str) -> bool: + """Heuristic: long, mixed-class, no separators, plausible padding.""" + if not BASE64_RE.match(value): + return False + has_upper = any(c.isupper() for c in value) + has_lower = any(c.islower() for c in value) + has_digit = any(c.isdigit() for c in value) + # Require two of the three classes so long lowercase words are not demoted. + return sum((has_upper, has_lower, has_digit)) >= 2 + + +def _looks_like_ipv6(value: str) -> bool: + if value.count(":") < 2: + return False + if not IPV6_RE.match(value): + return False + # ``::`` compresses groups; otherwise require the full eight-group form. + # This rejects clock times such as ``12:30:45``. + if "::" in value: + return True + return len(value.split(":")) == 8 + + +def classify(value: str) -> Optional[Tuple[str, str]]: + """Return ``(rule, reason)`` for the strongest matching shape, or ``None``. + + Order matters: JWT before base64, UUID before hash, e-mail before scalar. + """ + text = (value or "").strip().strip("\"'") + if not text: + return None + if JWT_RE.match(text): + return RULE_JWT, "value looks like a JWT (three base64url segments) (-20)" + if UUID_RE.match(text): + return ( + RULE_UUID, + f"value looks like a UUID ('{_short(text)}') rather than a path (-20)", + ) + if HASH_PREFIXED_RE.match(text) or HASH_RE.match(text): + kind = "SHA-256" if len(text) == 64 else "a hex digest" + return ( + RULE_HASH, + f"value looks like {kind} ('{_short(text)}') rather than a path (-18)", + ) + if UUID_BARE_RE.match(text): + return ( + RULE_UUID, + f"value looks like a bare UUID ('{_short(text)}') rather than a path (-20)", + ) + if EMAIL_RE.match(text): + return ( + RULE_EMAIL, + f"value looks like an e-mail address ('{_short(text)}') (-8)", + ) + if IPV4_RE.match(text) or _looks_like_ipv6(text): + return RULE_IP, f"value looks like an IP address ('{_short(text)}') (-10)" + if text.lower() in ENUM_TOKENS: + return ( + RULE_SCALAR, + f"value is an enum-like token ('{_short(text)}') rather than a path (-10)", + ) + if text.lower() in ENUM_LONG_TOKENS or text.lower() in ("true", "false", "null"): + return ( + RULE_SCALAR, + f"value is a boolean/state token ('{_short(text)}') (-10)", + ) + if NUMBER_RE.match(text): + return ( + RULE_SCALAR, + f"value is a plain number ('{_short(text)}') rather than a path (-10)", + ) + if HEX_RE.match(text): + return ( + RULE_SCALAR, + f"value is a numeric literal ('{_short(text)}') (-10)", + ) + if _looks_like_base64(text): + return ( + RULE_BASE64, + f"value looks like a base64 blob ({len(text)} chars) rather than a path (-12)", + ) + return None + + +def demotions(value: str) -> List[Tuple[str, str]]: + """All demotions that apply, as ``[(rule, reason)]`` (usually zero or one).""" + match = classify(value) + return [match] if match else [] + + +def describe_shapes() -> Tuple[str, ...]: + """``--help`` summary of the demotion shapes.""" + return tuple( + f" {rule:<24} {reason}" + for rule, reason in ( + (RULE_UUID, "UUID values"), + (RULE_HASH, "hex digests / prefixed hashes"), + (RULE_JWT, "JWTs"), + (RULE_BASE64, "base64 blobs"), + (RULE_EMAIL, "e-mail addresses"), + (RULE_IP, "IPv4/IPv6 literals"), + (RULE_SCALAR, "booleans, numbers, short enums"), + ) + ) + + +__all__ = [ + "RULE_UUID", + "RULE_HASH", + "RULE_JWT", + "RULE_BASE64", + "RULE_EMAIL", + "RULE_IP", + "RULE_SCALAR", + "classify", + "demotions", + "describe_shapes", +] + + +#: Path-ish shapes are not demotions, but a capture diff wants to name them. +_PATH_SHAPE_ORDER = ( + ("traversal", lambda text: ".." in text.replace("\\", "/").split("/")), + ("absolute-path", lambda text: text.startswith("/")), + ("windows-path", lambda text: bool(WIN_PATH_RE.match(text))), + ("path-like", lambda text: "\\" in text or ("/" in text and len(text) > 3)), +) + + +def shape_label(value: str) -> str: + """A short, **value-free** label describing a value's shape. + + Used where a report must say "the shape changed" without echoing the value: + capture diffs, value statistics and calibration summaries. + + Returns one of ``empty``, ``jwt``, ``uuid``, ``hash``, ``email``, ``ip``, + ``enum``, ``number``, ``boolean``, ``base64``, ``traversal``, + ``absolute-path``, ``windows-path``, ``path-like`` or ``text``. + """ + text = (value or "").strip() + if not text: + return "empty" + demotion = classify(text) + if demotion is not None: + rule = demotion[0] + return { + RULE_JWT: "jwt", + RULE_UUID: "uuid", + RULE_HASH: "hash", + RULE_EMAIL: "email", + RULE_IP: "ip", + RULE_BASE64: "base64", + RULE_SCALAR: "scalar", + }.get(rule, "text") + lowered = text.lower() + if lowered in ("true", "false", "null", "none", "0", "1"): + return "boolean" + for label, check in _PATH_SHAPE_ORDER: + try: + if check(text): + return label + except Exception: # pragma: no cover - defensive + continue + return "text" + diff --git a/pathscope/waivers.py b/pathscope/waivers.py new file mode 100644 index 0000000..a045271 --- /dev/null +++ b/pathscope/waivers.py @@ -0,0 +1,407 @@ +"""Committable waiver files (``--waivers FILE``). + +The SQLite ledger is a good review store and a bad review *artefact*: it is +binary, it lives next to the person who ran the scan, and a pull request cannot +show a diff of it. A waiver file is the opposite -- plain JSON, in the +repository, reviewed like code: + + { + "version": 1, + "description": "Accepted risks for the acme-api surface", + "waivers": [ + { + "host": "api.acme.test", + "path": "/documents/*", + "parameter": "file", + "rule": "name-exact", + "reason": "values are validated against a signed allow-list upstream", + "owner": "platform-team", + "expires": "2027-01-31" + } + ] + } + +Design rules, and why each one: + +* **Every waiver needs a reason and an owner.** A waiver without either is an + anonymous permanent exception, which is what this feature exists to prevent. +* **A waiver needs at least one match dimension.** ``{}`` would waive every + finding in every future run; that is refused rather than honoured. +* **Expiry is a date, not a duration.** A duration restarts every run, so it + never actually expires. +* **Unknown keys are errors.** A typo in ``expirse`` must not silently produce + an immortal waiver. +* **Matching is explicit.** A waiver never falls back to a fuzzy match: it + matches on the fields it names and is silent about the rest. + +Waivers are applied after the ledger and before the policy, so every output +(SARIF, JUnit, text, policy) sees the same decision. +""" + +from __future__ import annotations + +import datetime as _dt +import fnmatch +import json +import re +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +from .detector import Finding + +WAIVER_KEYS = ( + "host", + "path", + "parameter", + "rule", + "location", + "reason", + "owner", + "expires", + "ticket", + "id", +) +REQUIRED_KEYS = ("reason", "owner") +#: Fields that, if present, make a waiver selective rather than global. +MATCH_KEYS = ("host", "path", "parameter", "rule", "location") + +MAX_WAIVERS = 5000 +_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + + +class WaiverError(ValueError): + """Raised when a waiver file cannot be read or is not usable.""" + + +@dataclass(frozen=True) +class Waiver: + """One declared, time-limited acceptance.""" + + reason: str + owner: str + host: str = "" + path: str = "" + parameter: str = "" + rule: str = "" + location: str = "" + expires: str = "" + ticket: str = "" + id: str = "" + line: int = 0 + + def expired(self, today: Optional[str] = None) -> bool: + if not self.expires: + return False + return self.expires < (today or _today()) + + def days_left(self, today: Optional[str] = None) -> Optional[int]: + if not self.expires: + return None + start = _dt.date.fromisoformat(today or _today()) + end = _dt.date.fromisoformat(self.expires) + return (end - start).days + + def describe(self) -> str: + parts = [ + value + for value in ( + self.host or "*", + self.path or "*", + f"[{self.location}]" if self.location else "", + self.parameter or "*", + f"rule={self.rule}" if self.rule else "", + ) + if value + ] + return " ".join(parts) + + def as_dict(self) -> Dict[str, object]: + payload: Dict[str, object] = { + "host": self.host, + "path": self.path, + "parameter": self.parameter, + "rule": self.rule, + "location": self.location, + "reason": self.reason, + "owner": self.owner, + "expires": self.expires, + } + if self.ticket: + payload["ticket"] = self.ticket + if self.id: + payload["id"] = self.id + return payload + + +def _today() -> str: + return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%d") + + +def _path_of(finding: Finding) -> str: + from urllib.parse import urlsplit + + resource = finding.resource or "/" + parts = urlsplit(resource) + return parts.path if (parts.scheme or parts.netloc) else resource.split("?", 1)[0] + + +def waiver_matches(waiver: Waiver, finding: Finding) -> bool: + """True when every field the waiver names matches the finding.""" + if waiver.host and not fnmatch.fnmatch(finding.host.lower(), waiver.host.lower()): + return False + if waiver.path and not fnmatch.fnmatch(_path_of(finding), waiver.path): + return False + if waiver.parameter and not fnmatch.fnmatch( + finding.parameter.lower(), waiver.parameter.lower() + ): + return False + if waiver.rule and finding.rule != waiver.rule: + return False + if waiver.location and finding.location != waiver.location: + return False + return True + + +@dataclass +class WaiverSet: + """Every waiver in one or more files, plus what they matched.""" + + source: str = "" + waivers: List[Waiver] = field(default_factory=list) + #: fingerprint -> waiver ids that matched it + matches: Dict[str, List[str]] = field(default_factory=dict) + #: waiver id -> number of findings it matched + counts: Dict[str, int] = field(default_factory=dict) + + def active(self, today: Optional[str] = None) -> List[Waiver]: + return [waiver for waiver in self.waivers if not waiver.expired(today)] + + def expired(self, today: Optional[str] = None) -> List[Waiver]: + return [waiver for waiver in self.waivers if waiver.expired(today)] + + +def _identify(waiver: Waiver, index: int) -> str: + if waiver.id: + return waiver.id + return f"waiver-{index}" if index else "waiver" + + +def parse_waivers(payload: object, source: str = "") -> WaiverSet: + """Validate a decoded waiver document.""" + if not isinstance(payload, dict): + raise WaiverError("a waiver file must be a JSON object") + unknown = [key for key in payload if key not in ("version", "description", "waivers")] + if unknown: + raise WaiverError( + "unknown top-level key(s): " + + ", ".join(sorted(unknown)) + + " (accepted: version, description, waivers)" + ) + version = payload.get("version", 1) + if version != 1: + raise WaiverError(f"unsupported waiver version {version!r} (expected 1)") + raw = payload.get("waivers") + if not isinstance(raw, list): + raise WaiverError("'waivers' must be an array") + if len(raw) > MAX_WAIVERS: + raise WaiverError(f"{len(raw)} waivers (limit {MAX_WAIVERS})") + + result = WaiverSet(source=source) + seen_ids: Dict[str, int] = {} + for index, entry in enumerate(raw, start=1): + if not isinstance(entry, dict): + raise WaiverError(f"waiver #{index} must be a JSON object") + unknown_fields = [key for key in entry if key not in WAIVER_KEYS] + if unknown_fields: + raise WaiverError( + f"waiver #{index} has unknown key(s): " + + ", ".join(sorted(unknown_fields)) + + f" (accepted: {', '.join(WAIVER_KEYS)})" + ) + for required in REQUIRED_KEYS: + value = entry.get(required) + if not isinstance(value, str) or not value.strip(): + raise WaiverError( + f"waiver #{index} needs a non-empty '{required}': an " + "exception without one is an anonymous permanent decision" + ) + if not any(entry.get(key) for key in MATCH_KEYS): + raise WaiverError( + f"waiver #{index} names no host, path, parameter, rule or " + "location, so it would waive every finding in every run" + ) + expires = entry.get("expires", "") + if expires: + if not isinstance(expires, str) or not _DATE.match(expires): + raise WaiverError( + f"waiver #{index} 'expires' must be YYYY-MM-DD, got {expires!r}. " + "Durations are refused because they restart every run." + ) + try: + _dt.date.fromisoformat(expires) + except ValueError as exc: + raise WaiverError( + f"waiver #{index} 'expires' is not a real date: {expires}" + ) from exc + fields = { + key: entry.get(key, "") + for key in WAIVER_KEYS + if key not in ("reason", "owner") + } + waiver = Waiver( + reason=str(entry["reason"]).strip(), + owner=str(entry["owner"]).strip(), + **{key: (value if isinstance(value, str) else "") for key, value in fields.items()}, + line=index, + ) + waiver = _with_id(waiver, _identify(waiver, len(result.waivers) + 1)) + if waiver.id in seen_ids: + raise WaiverError( + f"duplicate waiver id '{waiver.id}' (#{seen_ids[waiver.id]} and #{index})" + ) + seen_ids[waiver.id] = index + result.waivers.append(waiver) + return result + + +def _with_id(waiver: Waiver, identifier: str) -> Waiver: + from dataclasses import replace + + return replace(waiver, id=identifier) + + +def load_waivers(path: str) -> WaiverSet: + """Read a waiver file from disk. Raises :class:`WaiverError`.""" + try: + with open(path, "r", encoding="utf-8-sig") as handle: + raw = handle.read() + except OSError as exc: + raise WaiverError(f"cannot read waivers '{path}': {exc.strerror or exc}") from exc + try: + payload = json.loads(raw) + except json.JSONDecodeError as exc: + raise WaiverError( + f"waivers '{path}' is not valid JSON: line {exc.lineno}: {exc.msg}" + ) from exc + return parse_waivers(payload, source=path) + + +def merge(sets: Sequence[WaiverSet], source: str = "") -> WaiverSet: + """Combine several waiver sets, refusing duplicate ids across files.""" + combined = WaiverSet(source=source or ", ".join( + item.source for item in sets if item.source + )) + seen: Dict[str, str] = {} + for item in sets: + for waiver in item.waivers: + if waiver.id in seen: + raise WaiverError( + f"waiver id '{waiver.id}' appears in both {seen[waiver.id]} " + f"and {item.source}" + ) + seen[waiver.id] = item.source + combined.waivers.append(waiver) + return combined + + +def apply_waivers( + findings: Sequence[Finding], + waivers: WaiverSet, + *, + today: Optional[str] = None, +) -> Tuple[int, int]: + """Mark waived findings ``status='waived'``; returns ``(waived, expired_skipped)``. + + Expired waivers do **not** hide anything. That is the whole point of an + expiry: the exception stops applying the day somebody said it would. + """ + active = waivers.active(today) + skipped = len(waivers.expired(today)) + waived = 0 + for finding in findings: + for waiver in active: + if waiver_matches(waiver, finding): + finding.status = "waived" + finding.note = ( + f"waived by {waiver.id} ({waiver.owner}): {waiver.reason}" + + (f"; expires {waiver.expires}" if waiver.expires else "; no expiry") + ) + waivers.matches.setdefault(finding.fingerprint, []).append(waiver.id) + waivers.counts[waiver.id] = waivers.counts.get(waiver.id, 0) + 1 + waived += 1 + break + return waived, skipped + + +def render_waivers(waivers: WaiverSet, today: Optional[str] = None) -> str: + """Text view of a waiver set and what it matched.""" + lines = ["PathScope waivers", "=" * 84] + if not waivers.waivers: + lines.append("No waivers loaded.") + return "\n".join(lines) + active = waivers.active(today) + expired = waivers.expired(today) + lines.append( + f"{len(waivers.waivers)} waiver(s) from {waivers.source or '(inline)'}: " + f"{len(active)} active, {len(expired)} expired" + ) + lines.append("") + for waiver in waivers.waivers: + state = "EXPIRED" if waiver.expired(today) else "active " + count = waivers.counts.get(waiver.id, 0) + lines.append(f" [{state}] {waiver.id}: {waiver.describe()}") + lines.append(f" owner {waiver.owner}; matched {count} finding(s)") + lines.append(f" reason: {waiver.reason}") + if waiver.expires: + lines.append(f" expires {waiver.expires}") + lines.append("") + if expired: + lines.append( + f"{len(expired)} waiver(s) have expired and no longer hide anything. " + "Renew them, or delete them and fix the finding." + ) + lines.append("") + lines.append( + "A waiver is a recorded, owned decision -- not a finding going away." + ) + return "\n".join(lines) + + +def starter_waivers() -> str: + """Contents written by ``--init-waivers``.""" + return ( + "{\n" + ' "version": 1,\n' + ' "description": "Accepted risks for this repository",\n' + ' "waivers": [\n' + " {\n" + ' "host": "api.example.test",\n' + ' "path": "/documents/*",\n' + ' "parameter": "file",\n' + ' "rule": "name-exact",\n' + ' "reason": "validated against a signed allow-list upstream",\n' + ' "owner": "platform-team",\n' + ' "expires": "2027-01-31",\n' + ' "ticket": "SEC-1234"\n' + " }\n" + " ]\n" + "}\n" + ) + + +__all__ = [ + "MATCH_KEYS", + "MAX_WAIVERS", + "REQUIRED_KEYS", + "WAIVER_KEYS", + "Waiver", + "WaiverError", + "WaiverSet", + "apply_waivers", + "load_waivers", + "merge", + "parse_waivers", + "render_waivers", + "starter_waivers", + "waiver_matches", +] diff --git a/pathscope/watch.py b/pathscope/watch.py new file mode 100644 index 0000000..41808b5 --- /dev/null +++ b/pathscope/watch.py @@ -0,0 +1,220 @@ +"""Live re-analysis of a growing capture file (``--watch``). + +A proxy or browser keeps appending to a HAR file; this module re-reads it on a +timer and reports **only** candidates that were not reported before. Nothing is +sent, no file is opened beyond the capture the user named, and every iteration +is a normal local parse. + +The loop is deliberately synchronous and easy to test: :func:`watch_once` +performs one stable read + diffuse and returns what changed, while +:func:`watch_forever` adds the sleeping and Ctrl-C handling. +""" + +from __future__ import annotations + +import hashlib +import os +import sys +import time +from dataclasses import dataclass, field +from typing import Callable, List, Optional, Set, TextIO + +from .detector import AnalysisOptions, Finding, Report, analyze_requests +from .sources import INPUT_FORMAT_AUTO, InputError, LoadResult, load_file + +#: Minimum and maximum accepted polling interval, in seconds. +MIN_INTERVAL = 0.2 +MAX_INTERVAL = 3600.0 + + +class WatchError(RuntimeError): + """Raised when the watched file cannot be read.""" + + +@dataclass +class WatchState: + """Everything the loop remembers between polls.""" + + seen_fingerprints: Set[str] = field(default_factory=set) + signature: str = "" + polls: int = 0 + reports: int = 0 + warnings: Set[str] = field(default_factory=set) + last_report: Optional[Report] = None + skipped: int = 0 + last_size: int = -1 + + def note_size(self, size: int) -> bool: + """Return True when the file shrank (rotated/replaced) and reset state.""" + shrank = self.last_size >= 0 and size < self.last_size + if shrank: + self.seen_fingerprints.clear() + self.warnings.clear() + self.last_size = size + return shrank + + +def file_signature(path: str) -> str: + """Cheap content signature (size + mtime), used to skip unchanged polls.""" + try: + info = os.stat(path) + except OSError as exc: + raise WatchError(f"cannot stat '{path}': {exc.strerror or exc}") from exc + return f"{info.st_size}:{info.st_mtime_ns}" + + +def _content_hash(requests: List[object]) -> str: + digest = hashlib.sha256() + for request in requests: + digest.update(repr(getattr(request, "dedupe_key", request)).encode("utf-8", "replace")) + return digest.hexdigest() + + +def watch_once( + path: str, + options: AnalysisOptions, + state: WatchState, + input_format: str = INPUT_FORMAT_AUTO, +) -> tuple: + """One poll. Returns ``(new_findings, warnings, loaded_count, changed)``. + + ``changed`` is false when the file has not moved since the previous poll, in + which case no parsing happens at all. + """ + signature = file_signature(path) + if signature == state.signature: + return [], [], 0, False + state.signature = signature + state.polls += 1 + size = int(signature.split(":", 1)[0]) + rotated = state.note_size(size) + try: + loaded: LoadResult = load_file(path, input_format) + except InputError as exc: + raise WatchError(str(exc)) from exc + except Exception as exc: # noqa: BLE001 - partial writes are normal + raise WatchError(f"cannot parse '{path}': {exc}") from exc + + state.skipped = loaded.skipped + report = analyze_requests(loaded.requests, options) + report.warnings = list(loaded.warnings) + report.skipped = loaded.skipped + state.last_report = report + + fresh: List[Finding] = [] + for finding in report.findings: + if finding.fingerprint in state.seen_fingerprints: + continue + state.seen_fingerprints.add(finding.fingerprint) + fresh.append(finding) + new_warnings = [w for w in loaded.warnings if w not in state.warnings] + state.warnings.update(new_warnings) + if rotated: + # A replaced capture starts a new baseline: everything in it is new. + state.seen_fingerprints = {finding.fingerprint for finding in fresh} | { + finding.fingerprint for finding in report.findings + } + if fresh: + state.reports += 1 + return fresh, new_warnings, len(loaded.requests), True + + +def format_watch_batch( + findings: List[Finding], stream: TextIO, color: bool = False +) -> None: + """Print a compact one-line-per-new-candidate summary to ``stream``.""" + for finding in findings: + band = finding.confidence.upper() + if color: + code = {"HIGH": "31", "MEDIUM": "33", "LOW": "36"}.get(band, "0") + band = f"\x1b[{code}m{band}\x1b[0m" + stream.write( + f"[new] {finding.host:<28} {finding.location:<6} " + f"{finding.parameter:<20} {band:<10} {finding.score:>3}/100 " + f"{finding.rule}\n" + ) + stream.flush() + + +def watch_forever( + path: str, + options: AnalysisOptions, + *, + interval: float = 2.0, + input_format: str = INPUT_FORMAT_AUTO, + stdout: Optional[TextIO] = None, + stderr: Optional[TextIO] = None, + sleep: Callable[[float], None] = time.sleep, + now: Callable[[], float] = time.monotonic, + max_polls: Optional[int] = None, +) -> int: + """Poll ``path`` until interrupted (or ``max_polls`` is reached). + + Returns the number of batches emitted. Ctrl-C is handled by the caller. + """ + stdout = stdout or sys.stdout + stderr = stderr or sys.stderr + interval = max(MIN_INTERVAL, min(MAX_INTERVAL, float(interval))) + state = WatchState() + started = now() + stdout.write( + f"Watching {path} every {interval:g}s for new candidates. " + "Press Ctrl-C to stop. No requests are sent.\n" + ) + stdout.flush() + poll_count = 0 + shown_waiting = False + retries = 0 + try: + while True: + poll_count += 1 + try: + fresh, warnings, loaded, changed = watch_once( + path, options, state, input_format + ) + except WatchError as exc: + retries += 1 + # Transient failures are expected while a proxy is writing; + # report the first few and then stay quiet until it recovers. + if retries <= 3: + print(f"watch: {exc} (will retry)", file=stderr) + fresh, warnings, loaded, changed = [], [], 0, True + else: + retries = 0 + if changed: + for warning in warnings: + print(f"warning: {warning}", file=stderr) + if fresh: + format_watch_batch(fresh, stdout) + shown_waiting = False + elif not shown_waiting: + stdout.write( + f"No candidates yet ({loaded} request(s) analyzed). " + "Waiting for changes...\n" + ) + stdout.flush() + shown_waiting = True + if max_polls is not None and poll_count >= max_polls: + break + sleep(interval) + except KeyboardInterrupt: + stdout.write("\n") + elapsed = now() - started + stdout.write( + f"Stopped after {poll_count} poll(s) in {elapsed:.1f}s; " + f"{len(state.seen_fingerprints)} candidate(s) seen in total.\n" + ) + stdout.flush() + return state.reports + + +__all__ = [ + "MAX_INTERVAL", + "MIN_INTERVAL", + "WatchError", + "WatchState", + "file_signature", + "format_watch_batch", + "watch_forever", + "watch_once", +] diff --git a/pathscope/writers.py b/pathscope/writers.py new file mode 100644 index 0000000..9a26cbf --- /dev/null +++ b/pathscope/writers.py @@ -0,0 +1,561 @@ +"""Standalone report files (Markdown and HTML) plus ``--explain`` output. + +These writers are used by ``--save-report FILE``. They are deliberately +self-contained: no templates, no external assets, and every dynamic value is +sanitised and HTML-escaped so a crafted parameter cannot break the document. +""" + +from __future__ import annotations + +import html +from typing import List + +from . import PROGRAM, __version__ +from .detector import Finding, Report +from .report import DISCLAIMER +from .textutil import encode_display, truncate + +#: Extension -> writer kind. +SUPPORTED_EXTENSIONS = (".md", ".markdown", ".html", ".htm") + + +def writer_for_path(path: str) -> str: + lowered = path.lower() + if lowered.endswith((".html", ".htm")): + return "html" + if lowered.endswith((".md", ".markdown")): + return "markdown" + raise ValueError( + f"unsupported report extension for '{path}' (use .md, .markdown, .html or .htm)" + ) + + +def writer_supports_interactive(path: str) -> bool: + """True when ``path`` is an HTML report that can carry the interactive UI.""" + try: + return writer_for_path(path) == "html" + except ValueError: + return False + + +def _status(finding: Finding) -> str: + if finding.status == "known": + return "known" + (f" — {finding.note}" if finding.note else "") + return finding.status + + +def _finding_rows(findings: List[Finding]) -> List[List[str]]: + rows: List[List[str]] = [] + for finding in findings: + rows.append( + [ + str(finding.index), + finding.host, + finding.location, + finding.parameter, + finding.rule, + finding.confidence, + str(finding.score), + str(finding.occurrences), + finding.fingerprint, + _status(finding), + finding.method + " " + finding.resource, + ] + ) + return rows + + +HEADERS = ( + "#", + "Host", + "Location", + "Parameter", + "Rule", + "Confidence", + "Score", + "Repeats", + "Fingerprint", + "Status", + "Request", +) + +HTML_HEADERS = HEADERS + ("Value",) + + +def render_markdown(report: Report) -> str: + lines: List[str] = [] + lines.append(f"# {PROGRAM} report") + lines.append("") + lines.append(f"- Tool: {PROGRAM} {__version__} (passive, offline)") + lines.append(f"- Threshold: score >= {report.min_score}") + lines.append(f"- Requests analyzed: {report.requests_analyzed}") + lines.append(f"- Parameters analyzed: {report.parameters_analyzed}") + lines.append(f"- Candidates: {report.candidate_count}") + lines.append(f"- Sources: {', '.join(report.sources) or '—'}") + lines.append(f"- Mode: {report.mode}") + if report.mode == "diff": + lines.append( + f"- Diff: {report.new_count} new, {report.known_count} known, " + f"{len(report.resolved)} resolved (baseline {report.baseline_source or 'unspecified'})" + ) + lines.append(f"- Values included: {'yes' if report.show_values else 'no'}") + lines.append("") + lines.append(f"> {DISCLAIMER}") + lines.append("") + + if not report.findings: + lines.append("No path-like parameter candidates were flagged.") + lines.append("") + else: + lines.append("## Candidates") + lines.append("") + lines.append("| " + " | ".join(HEADERS) + " |") + lines.append("|" + "|".join(["---"] * len(HEADERS)) + "|") + for row in _finding_rows(report.findings): + lines.append( + "| " + + " | ".join(encode_display(truncate(cell, 120)) for cell in row) + + " |" + ) + lines.append("") + lines.append("## Why each candidate was flagged") + lines.append("") + for finding in report.findings: + lines.append( + f"### #{finding.index} `{encode_display(finding.parameter)}` " + f"({finding.confidence}, {finding.score}/100)" + ) + lines.append("") + lines.append(f"- Host: `{encode_display(finding.host)}`") + lines.append(f"- Rule: `{finding.rule}`") + lines.append(f"- Fingerprint: `{finding.fingerprint}`") + for reason in finding.reasons: + lines.append(f" - {encode_display(reason)}") + lines.append("") + + if report.mode == "diff" and report.resolved: + lines.append("## Resolved since baseline") + lines.append("") + for entry in report.resolved: + lines.append( + f"- `{encode_display(str(entry.get('parameter', '?')))}` " + f"@ `{encode_display(str(entry.get('host', '?')))}` " + f"({entry.get('fingerprint', '')})" + ) + lines.append("") + + if report.warnings: + lines.append("## Input warnings") + lines.append("") + for warning in report.warnings: + lines.append(f"- {encode_display(warning)}") + lines.append("") + return "\n".join(lines).rstrip() + "\n" + + +def _esc(value: object) -> str: + return html.escape(encode_display(str(value)), quote=True) + + +def render_html(report: Report) -> str: + counts = report.confidence_counts + rows: List[str] = [] + for finding in report.findings: + rows.append( + "" + f"{finding.index}" + f"{_esc(finding.host)}" + f"{_esc(finding.location)}" + f"{_esc(finding.parameter)}" + f"{_esc(finding.rule)}" + f'{_esc(finding.confidence)}' + f"{finding.score}" + f"{finding.occurrences}" + f"{_esc(finding.fingerprint)}" + f"{_esc(_status(finding))}" + f"{_esc(finding.method)} {_esc(finding.resource)}" + f"{_esc(finding.value) if report.show_values else ''}" + "" + ) + + reasons: List[str] = [] + for finding in report.findings: + items = "".join(f"
  • {_esc(reason)}
  • " for reason in finding.reasons) + reasons.append( + f"

    #{finding.index} {_esc(finding.parameter)} " + f"({_esc(finding.confidence)}, {finding.score}/100)

    " + f"

    Rule {_esc(finding.rule)} · " + f"fingerprint {_esc(finding.fingerprint)}

      {items}
    " + ) + + warning_block = "" + if report.warnings: + items = "".join(f"
  • {_esc(w)}
  • " for w in report.warnings) + warning_block = f"

    Input warnings

      {items}
    " + + resolved_block = "" + if report.mode == "diff" and report.resolved: + items = "".join( + f"
  • {_esc(entry.get('parameter', '?'))} @ " + f"{_esc(entry.get('host', '?'))} " + f"({_esc(entry.get('fingerprint', ''))})
  • " + for entry in report.resolved + ) + resolved_block = f"

    Resolved since baseline

      {items}
    " + + table = ( + "" + + "".join(f"" for header in HTML_HEADERS) + + "" + + "".join(rows) + + "
    {_esc(header)}
    " + if report.findings + else "

    No path-like parameter candidates were flagged.

    " + ) + + diff_line = "" + if report.mode == "diff": + diff_line = ( + f"
  • Diff: {report.new_count} new, {report.known_count} known, " + f"{len(report.resolved)} resolved (baseline " + f"{_esc(report.baseline_source or 'unspecified')})
  • " + ) + + return f""" + + + + +{PROGRAM} report + + + +

    {PROGRAM} report

    +

    {_esc(DISCLAIMER)}

    +
      +
    • Version: {_esc(__version__)} (passive, offline)
    • +
    • Threshold: score >= {report.min_score}
    • +
    • Requests analyzed: {report.requests_analyzed}
    • +
    • Parameters analyzed: {report.parameters_analyzed}
    • +
    • Candidates: {report.candidate_count} (high {counts.get('high', 0)}, + medium {counts.get('medium', 0)}, low {counts.get('low', 0)})
    • +
    • Sources: {_esc(', '.join(report.sources) or '—')}
    • +
    • Mode: {_esc(report.mode)}
    • +{diff_line} +
    • Values included: {'yes' if report.show_values else 'no'}
    • +
    +

    Candidates

    +{table} +

    Why each candidate was flagged

    +{''.join(reasons) if reasons else '

    Nothing to explain.

    '} +{resolved_block} +{warning_block} +
    +

    Generated by {PROGRAM} {_esc(__version__)}. Findings are heuristic +candidates for manual review, not confirmed vulnerabilities.

    + + +""" + + +def write_report(path: str, report: Report, interactive: bool = False) -> str: + """Write ``report`` to ``path`` and return the writer kind used.""" + kind = writer_for_path(path) + if kind == "markdown": + content = render_markdown(report) + elif interactive: + content = render_html_interactive(report) + else: + content = render_html(report) + with open(path, "w", encoding="utf-8", newline="\n") as handle: + handle.write(content) + return kind + + +# --------------------------------------------------------------------------- +# Interactive HTML report (--save-report FILE.html --interactive) +# --------------------------------------------------------------------------- +#: Interactive features stay dependency-free: a small inline script only. +INTERACTIVE_SCRIPT = """ +(function () { + 'use strict'; + var table = document.getElementById('findings'); + if (!table) { return; } + var rows = Array.prototype.slice.call(table.tBodies[0].rows); + var filter = document.getElementById('filter'); + var confidence = document.getElementById('confidence'); + var reviewedOnly = document.getElementById('reviewed-only'); + var counter = document.getElementById('counter'); + var state = {}; + + function loadState() { + try { + state = JSON.parse(window.localStorage.getItem('pathscope-reviewed') || '{}'); + } catch (err) { state = {}; } + } + function saveState() { + try { + window.localStorage.setItem('pathscope-reviewed', JSON.stringify(state)); + } catch (err) { /* storage disabled: review marks stay in-memory */ } + } + function reviewedCount() { + return Object.keys(state).filter(function (key) { return state[key]; }).length; + } + function apply() { + var needle = (filter && filter.value ? filter.value : '').toLowerCase(); + var band = confidence && confidence.value ? confidence.value : ''; + var only = reviewedOnly && reviewedOnly.checked; + var shown = 0; + rows.forEach(function (row) { + var text = row.getAttribute('data-search') || ''; + var rowBand = row.getAttribute('data-confidence') || ''; + var fingerprint = row.getAttribute('data-fingerprint') || ''; + var reviewed = !!state[fingerprint]; + row.classList.toggle('is-reviewed', reviewed); + var box = row.querySelector('input[type=checkbox]'); + if (box) { box.checked = reviewed; } + var visible = (!band || rowBand === band) && + (needle === '' || text.indexOf(needle) !== -1) && + (!only || reviewed); + row.style.display = visible ? '' : 'none'; + if (visible) { shown += 1; } + }); + if (counter) { + counter.textContent = shown + ' of ' + rows.length + + ' shown, ' + reviewedCount() + ' marked reviewed (this browser only)'; + } + } + rows.forEach(function (row) { + var box = row.querySelector('input[type=checkbox]'); + if (!box) { return; } + box.addEventListener('change', function () { + var fingerprint = row.getAttribute('data-fingerprint') || ''; + state[fingerprint] = box.checked; + saveState(); + apply(); + }); + }); + Array.prototype.forEach.call(table.querySelectorAll('th[data-sort]'), function (th) { + th.addEventListener('click', function () { + var index = parseInt(th.getAttribute('data-sort'), 10); + var numeric = th.getAttribute('data-numeric') === '1'; + var ascending = th.getAttribute('data-dir') !== 'asc'; + Array.prototype.forEach.call(table.querySelectorAll('th'), function (other) { + other.removeAttribute('data-dir'); + }); + th.setAttribute('data-dir', ascending ? 'asc' : 'desc'); + rows.sort(function (left, right) { + var a = left.cells[index] ? left.cells[index].textContent.trim() : ''; + var b = right.cells[index] ? right.cells[index].textContent.trim() : ''; + var result = numeric ? (parseFloat(a) || 0) - (parseFloat(b) || 0) : a.localeCompare(b); + return ascending ? result : -result; + }); + rows.forEach(function (row) { table.tBodies[0].appendChild(row); }); + }); + }); + if (filter) { filter.addEventListener('input', apply); } + if (confidence) { confidence.addEventListener('change', apply); } + if (reviewedOnly) { reviewedOnly.addEventListener('change', apply); } + Array.prototype.forEach.call(document.querySelectorAll('[data-copy]'), function (button) { + button.addEventListener('click', function () { + var text = button.getAttribute('data-copy') || ''; + if (navigator.clipboard && navigator.clipboard.writeText) { + navigator.clipboard.writeText(text); + button.textContent = 'copied'; + setTimeout(function () { button.textContent = 'copy'; }, 1200); + } + }); + }); + loadState(); + apply(); +})(); +""" + +INTERACTIVE_CSS = """ +.controls { display: flex; gap: 1rem; flex-wrap: wrap; align-items: center; + margin: 1rem 0; } +.controls input[type=search] { min-width: 16rem; padding: 0.35rem 0.5rem; } +.reviewed { color: #2471a3; } +table.sortable th[data-sort] { cursor: pointer; user-select: none; } +table.sortable th[data-sort]:after { content: " \\2195"; color: #8888; } +tr.is-reviewed td { opacity: 0.55; } +.copy { font-size: 0.75rem; padding: 0.1rem 0.35rem; cursor: pointer; } +footer { margin-top: 2rem; } +@media print { + .controls, .copy { display: none; } + body { max-width: none; } + tr { page-break-inside: avoid; } +} +""" + + +def render_html_interactive(report: Report) -> str: + """A self-contained, sortable/filterable HTML report. + + No external assets and no network calls: the page works from ``file://``. + Review checkboxes are stored in ``localStorage`` on the reader's machine; + nothing is uploaded. Every dynamic string is escaped exactly like the + static report. + """ + counts = report.confidence_counts + rows: List[str] = [] + for finding in report.findings: + search = " ".join( + [finding.host, finding.parameter, finding.rule, finding.location] + + (finding.reasons if not report.show_values else []) + ).lower() + rows.append( + f'' + f'' + f"{finding.index}" + f"{_esc(finding.host)}" + f"{_esc(finding.location)}" + f"{_esc(finding.parameter)}" + f"{_esc(finding.rule)}" + f'{_esc(finding.confidence)}' + f"{finding.score}" + f"{finding.occurrences}" + f"{_esc(finding.fingerprint)} " + f'' + f"{_esc(_status(finding))}" + f"{_esc(finding.method)} {_esc(finding.resource)}" + + (f"{_esc(finding.value or '')}" if report.show_values else "") + + "" + ) + + headers = ["", "#", "Host", "Location", "Parameter", "Rule", "Confidence", + "Score", "Repeats", "Fingerprint", "Status", "Request"] + if report.show_values: + headers.append("Value") + numeric = {"7"} + header_html = "".join( + f'{_esc(name)}" + for index, name in enumerate(headers) + ) + + reasons: List[str] = [] + for finding in report.findings: + items = "".join(f"
  • {_esc(reason)}
  • " for reason in finding.reasons) + reasons.append( + f"
    #{finding.index} {_esc(finding.parameter)} " + f"({_esc(finding.confidence)}, {finding.score}/100)" + f'

    Rule {_esc(finding.rule)} · ' + f"fingerprint {_esc(finding.fingerprint)}

    " + f"
      {items}
    " + ) + + warning_block = "" + if report.warnings: + items = "".join(f"
  • {_esc(w)}
  • " for w in report.warnings) + warning_block = f"

    Input warnings

      {items}
    " + + resolved_block = "" + if report.mode == "diff" and report.resolved: + items = "".join( + f"
  • {_esc(entry.get('parameter', '?'))} @ " + f"{_esc(entry.get('host', '?'))} " + f"({_esc(entry.get('fingerprint', ''))})
  • " + for entry in report.resolved + ) + resolved_block = f"

    Resolved since baseline

      {items}
    " + + diff_line = "" + if report.mode == "diff": + diff_line = ( + f"
  • Diff: {report.new_count} new, {report.known_count} known, " + f"{len(report.resolved)} resolved (baseline " + f"{_esc(report.baseline_source or 'unspecified')})
  • " + ) + + table = ( + '' + + header_html + + "" + + "".join(rows) + + "
    " + if report.findings + else "

    No path-like parameter candidates were flagged.

    " + ) + + return f""" + + + + +{PROGRAM} interactive report + + + +

    {PROGRAM} interactive report

    +

    {_esc(DISCLAIMER)}

    +
      +
    • Version: {_esc(__version__)} (passive, offline)
    • +
    • Threshold: score >= {report.min_score}
    • +
    • Requests analyzed: {report.requests_analyzed}
    • +
    • Parameters analyzed: {report.parameters_analyzed}
    • +
    • Candidates: {report.candidate_count} (high {counts.get('high', 0)}, + medium {counts.get('medium', 0)}, low {counts.get('low', 0)})
    • +
    • Sources: {_esc(', '.join(report.sources) or '—')}
    • +
    • Mode: {_esc(report.mode)}
    • +{diff_line} +
    • Values included: {'yes' if report.show_values else 'no'}
    • +
    +
    + + + + +
    +

    Candidates

    +{table} +

    Why each candidate was flagged

    +{''.join(reasons) if reasons else '

    Nothing to explain.

    '} +{resolved_block} +{warning_block} +
    +

    Generated by {PROGRAM} {_esc(__version__)}. Findings are heuristic +candidates for manual review, not confirmed vulnerabilities. Review marks are +stored only in this browser (localStorage) and are never sent anywhere.

    + + + +""" diff --git a/tests/test_features.py b/tests/test_features.py new file mode 100644 index 0000000..5270062 --- /dev/null +++ b/tests/test_features.py @@ -0,0 +1,895 @@ +#!/usr/bin/env python3 +"""Tests for the PathScope 2.1 feature set. + +Covers: presets and configuration inheritance, baselines/diff/suppression, +``--explain``, Markdown/HTML report writers, Burp XML, OpenAPI, raw HTTP and +recon-output inputs, plus the new CLI flags (``--top``, ``--group-by``, +``--summary-only``, ``--mark-reviewed``, ``--init-config``). + +Run with: + + python3 -m unittest discover -s tests -v +""" + +from __future__ import annotations + +import base64 +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import cli, config, detector, extra_formats, heuristics, presets, report # noqa: E402 +from pathscope import sources, writers # noqa: E402 + + +def write_temp(name: str, content: str) -> str: + handle = tempfile.NamedTemporaryFile("w", suffix=name, delete=False, encoding="utf-8") + with handle as stream: + stream.write(content) + return handle.name + + +def cleanup(*paths: str) -> None: + for path in paths: + try: + os.unlink(path) + except OSError: + pass + + +def run_inprocess(*args: str, stdin: str = ""): + out, err = io.StringIO(), io.StringIO() + code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin) + return code, out.getvalue(), err.getvalue() + + +def analyze(url: str, **options) -> detector.Report: + request = sources.request_from_url(url, sources.SOURCE_URL, "--url") + return detector.analyze_requests([request], detector.AnalysisOptions(**options)) + + +HAR = { + "log": { + "version": "1.2", + "entries": [ + { + "request": { + "method": "GET", + "url": "https://app.test/files?path=../../etc/passwd&lang=en", + "queryString": [ + {"name": "path", "value": "../../etc/passwd"}, + {"name": "lang", "value": "en"}, + ], + } + } + ], + } +} + +BURP_XML = """ + + + + + + + + + + + +""" + + +def burp_xml() -> str: + raw = ( + "GET /dl?path=../../etc/passwd HTTP/1.1\r\n" + "Host: app.test\r\n" + "Accept: */*\r\n\r\n" + ) + encoded = base64.b64encode(raw.encode("latin-1")).decode("ascii") + return BURP_XML.format(encoded_get=encoded) + + +OPENAPI = { + "openapi": "3.0.3", + "servers": [{"url": "https://api.test/v1"}], + "paths": { + "/files/{fileId}": { + "get": { + "parameters": [ + {"name": "fileId", "in": "path"}, + {"name": "download", "in": "query"}, + {"name": "X-Trace", "in": "header"}, + ] + } + }, + "/render": { + "post": { + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "template": {"type": "string"}, + "options": { + "type": "object", + "properties": {"layout": {"type": "string"}}, + }, + }, + } + } + } + } + } + }, + }, +} + + +# --------------------------------------------------------------------------- +# Presets +# --------------------------------------------------------------------------- +class TestPresets(unittest.TestCase): + def test_preset_thresholds(self): + self.assertEqual(presets.PRESETS["minimal"].min_score, 50) + self.assertEqual(presets.PRESETS["balanced"].min_score, 25) + self.assertEqual(presets.PRESETS["noisy"].min_score, 10) + + def test_aliases(self): + self.assertIs(presets.resolve_preset("strict"), presets.PRESETS["minimal"]) + self.assertIs(presets.resolve_preset("default"), presets.PRESETS["balanced"]) + self.assertIs(presets.resolve_preset("broad"), presets.PRESETS["noisy"]) + self.assertIsNone(presets.resolve_preset(None)) + self.assertIsNone(presets.resolve_preset("nonsense")) + + def test_preset_applies_to_defaults_only(self): + cfg = config.Config(min_score=25, explicit=frozenset()) + applied = presets.resolve_preset("minimal").apply(cfg) + self.assertEqual(applied.min_score, 50) + self.assertFalse(applied.weak_names) + + explicit = config.Config(min_score=33, explicit=frozenset({"min_score"})) + applied = presets.resolve_preset("minimal").apply(explicit) + self.assertEqual(applied.min_score, 33) + + def test_cli_preset_changes_results(self): + low = run_inprocess("--no-banner", "-q", "--json", "--preset", "noisy", + "--url", "https://a.test/?page=2")[1] + strict = run_inprocess("--no-banner", "-q", "--json", "--preset", "minimal", + "--url", "https://a.test/?page=2")[1] + self.assertGreater(len(json.loads(low)["findings"]), 0) + self.assertEqual(json.loads(strict)["findings"], []) + + def test_minimal_preset_raises_the_bar(self): + url = "https://a.test/?some_thing=/a/b.pdf" + noisy = json.loads(run_inprocess( + "--no-banner", "-q", "--json", "--preset", "noisy", "--url", url)[1]) + minimal = json.loads(run_inprocess( + "--no-banner", "-q", "--json", "--preset", "minimal", "--url", url)[1]) + self.assertEqual(noisy["min_score"], 10) + self.assertEqual(minimal["min_score"], 50) + self.assertGreater(len(noisy["findings"]), len(minimal["findings"])) + + def test_weak_names_flag_in_heuristics(self): + with_weak = heuristics.analyze_name("some_thing") + without = heuristics.analyze_name("some_thing", weak_names=False) + self.assertTrue(with_weak) + self.assertEqual(without, []) + + def test_init_config(self): + directory = tempfile.mkdtemp() + target = os.path.join(directory, "starter.json") + code, out, err = run_inprocess("--no-banner", "-q", "--init-config", target, + "--preset", "noisy") + self.assertEqual(code, cli.EXIT_OK) + self.assertTrue(os.path.exists(target)) + payload = json.loads(Path(target).read_text()) + self.assertEqual(payload["min_score"], 10) + # Loading it back must validate. + self.assertEqual(config.load_config(target).min_score, 10) + # Refuses to overwrite. + code, _out, err = run_inprocess("--no-banner", "-q", "--init-config", target) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("refusing to overwrite", err) + cleanup(target) + + def test_init_config_unwritable(self): + code, _out, err = run_inprocess("--no-banner", "-q", "--init-config", + "/no/such/dir/file.json") + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("cannot write", err) + + +# --------------------------------------------------------------------------- +# Configuration inheritance (extends) +# --------------------------------------------------------------------------- +class TestConfigExtends(unittest.TestCase): + def test_extends_file(self): + directory = tempfile.mkdtemp() + base = os.path.join(directory, "base.json") + child = os.path.join(directory, "child.json") + Path(base).write_text(json.dumps({"name_terms": ["blob"], "min_score": 40, + "weak_names": False}), encoding="utf-8") + Path(child).write_text(json.dumps({"extends": "base.json", + "name_terms": ["cdn"], + "ignore_params": ["image"]}), encoding="utf-8") + cfg = config.load_config(child) + self.assertEqual(cfg.name_terms, ["blob", "cdn"]) + self.assertEqual(cfg.ignore_params, ["image"]) + self.assertEqual(cfg.min_score, 40) + self.assertFalse(cfg.weak_names) + cleanup(base, child) + + def test_extends_preset(self): + directory = tempfile.mkdtemp() + path = os.path.join(directory, "child.json") + Path(path).write_text(json.dumps({"extends": "strict", "name_terms": ["blob"]}), + encoding="utf-8") + cfg = config.load_config(path) + self.assertEqual(cfg.min_score, 50) + self.assertFalse(cfg.weak_names) + self.assertEqual(cfg.name_terms, ["blob"]) + cleanup(path) + + def test_extends_cycle_detected(self): + directory = tempfile.mkdtemp() + first = os.path.join(directory, "a.json") + second = os.path.join(directory, "b.json") + Path(first).write_text(json.dumps({"extends": "b.json"}), encoding="utf-8") + Path(second).write_text(json.dumps({"extends": "a.json"}), encoding="utf-8") + with self.assertRaises(config.ConfigError) as ctx: + config.load_config(first) + self.assertIn("cycle", str(ctx.exception)) + cleanup(first, second) + + def test_extends_missing_file(self): + directory = tempfile.mkdtemp() + path = os.path.join(directory, "child.json") + Path(path).write_text(json.dumps({"extends": "nope.json"}), encoding="utf-8") + with self.assertRaises(config.ConfigError): + config.load_config(path) + cleanup(path) + + def test_extends_rejects_non_json(self): + directory = tempfile.mkdtemp() + path = os.path.join(directory, "child.json") + Path(path).write_text(json.dumps({"extends": "base.txt"}), encoding="utf-8") + with self.assertRaises(config.ConfigError): + config.load_config(path) + cleanup(path) + + def test_extends_depth_limited(self): + directory = tempfile.mkdtemp() + paths = [] + for index in range(config.MAX_EXTENDS_DEPTH + 2): + path = os.path.join(directory, f"c{index}.json") + payload = {"extends": f"c{index + 1}.json"} + Path(path).write_text(json.dumps(payload), encoding="utf-8") + paths.append(path) + last = os.path.join(directory, f"c{config.MAX_EXTENDS_DEPTH + 2}.json") + Path(last).write_text(json.dumps({"min_score": 5}), encoding="utf-8") + with self.assertRaises(config.ConfigError): + config.load_config(paths[0]) + for path in paths + [last]: + cleanup(path) + + def test_weak_names_validated(self): + with self.assertRaises(config.ConfigError): + config.validate_payload({"weak_names": "yes"}) + + def test_cli_config_with_preset_base(self): + path = write_temp(".json", json.dumps({"name_terms": ["cdn_blob"]})) + try: + code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--preset", "minimal", + "--config", path, "--url", "https://a.test/?cdn_blob=/x", + ) + finally: + cleanup(path) + self.assertEqual(code, cli.EXIT_OK) + payload = json.loads(out) + # Preset base sets the threshold; the file adds the term. + self.assertEqual(payload["min_score"], 50) + self.assertEqual(payload["summary"]["candidates"], 0) # score 30 < 50 + + +# --------------------------------------------------------------------------- +# Fingerprints, baselines, diff, suppression +# --------------------------------------------------------------------------- +class TestFingerprints(unittest.TestCase): + def test_fingerprint_is_stable_and_value_independent(self): + first = analyze("https://a.test/?file=one.pdf").findings[0].fingerprint + second = analyze("https://a.test/?file=/deep/two.txt").findings[0].fingerprint + self.assertEqual(first, second) + self.assertEqual(len(first), 16) + + def test_fingerprint_changes_with_identity(self): + base = analyze("https://a.test/?file=a.pdf").findings[0].fingerprint + other_host = analyze("https://b.test/?file=a.pdf").findings[0].fingerprint + other_param = analyze("https://a.test/?path=a.pdf").findings[0].fingerprint + self.assertNotEqual(base, other_host) + self.assertNotEqual(base, other_param) + + def test_fingerprint_excludes_source_label(self): + requests = [ + sources.request_from_url("https://a.test/?file=a.pdf", "url", "--url"), + sources.request_from_url("https://a.test/?file=a.pdf", "file", "list.txt"), + ] + report_one = detector.analyze_requests(requests[:1], detector.AnalysisOptions()) + report_two = detector.analyze_requests(requests[1:], detector.AnalysisOptions()) + self.assertEqual( + report_one.findings[0].fingerprint, report_two.findings[0].fingerprint + ) + + +class TestBaseline(unittest.TestCase): + def make_baseline(self, *urls: str) -> detector.Baseline: + report_data = detector.Report() + for url in urls: + report_data.findings.extend(analyze(url).findings) + payload = json.loads(report.render_json(report_data)) + return detector.Baseline.from_payload(payload, source="baseline.json") + + def test_known_findings_are_hidden(self): + baseline = self.make_baseline("https://a.test/?file=x.pdf") + result = analyze("https://a.test/?file=x.pdf") + detector.apply_baseline(result, baseline) + self.assertEqual(result.findings, []) + self.assertEqual(result.known_count, 1) + self.assertEqual(result.mode, "diff") + + def test_new_findings_survive(self): + baseline = self.make_baseline("https://a.test/?file=x.pdf") + result = analyze("https://a.test/?file=x.pdf&download=/tmp/a.zip") + detector.apply_baseline(result, baseline) + self.assertEqual([f.parameter for f in result.findings], ["download"]) + self.assertEqual(result.new_count, 1) + + def test_show_known_keeps_them(self): + baseline = self.make_baseline("https://a.test/?file=x.pdf") + result = analyze("https://a.test/?file=x.pdf") + detector.apply_baseline(result, baseline, show_known=True) + self.assertEqual(len(result.findings), 1) + self.assertEqual(result.findings[0].status, "known") + + def test_resolved_entries_reported(self): + baseline = self.make_baseline("https://a.test/?file=x.pdf") + result = analyze("https://a.test/?q=hello") + detector.apply_baseline(result, baseline) + self.assertEqual(len(result.resolved), 1) + self.assertEqual(result.resolved[0]["parameter"], "file") + + def test_notes_are_carried(self): + payload = { + "findings": [ + {"fingerprint": analyze("https://a.test/?file=x.pdf").findings[0].fingerprint, + "note": "reviewed 2024-01-01"} + ] + } + baseline = detector.Baseline.from_payload(payload) + result = analyze("https://a.test/?file=x.pdf") + detector.apply_baseline(result, baseline, show_known=True) + self.assertEqual(result.findings[0].note, "reviewed 2024-01-01") + + def test_invalid_baseline_payloads(self): + with self.assertRaises(ValueError): + detector.Baseline.from_payload([]) + with self.assertRaises(ValueError): + detector.Baseline.from_payload({"findings": "nope"}) + # Entries without fingerprints are ignored rather than fatal. + baseline = detector.Baseline.from_payload({"findings": [{"parameter": "file"}]}) + self.assertEqual(baseline.fingerprints, {}) + + def test_cli_baseline_flow_and_exit_codes(self): + directory = tempfile.mkdtemp() + baseline_path = os.path.join(directory, "baseline.json") + code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--url", "https://a.test/?file=x.pdf" + ) + self.assertEqual(code, cli.EXIT_OK) + Path(baseline_path).write_text(out, encoding="utf-8") + + # Same input again: nothing new, so --fail-on-findings exits 0. + code, out, err = run_inprocess( + "--no-banner", "-q", "--json", "--baseline", baseline_path, + "--fail-on-findings", "--url", "https://a.test/?file=x.pdf", + ) + self.assertEqual(code, cli.EXIT_OK) + payload = json.loads(out) + self.assertEqual(payload["summary"]["known"], 1) + self.assertEqual(payload["summary"]["mode"], "diff") + self.assertIn("diff vs", err if err else "diff vs") + + # A genuinely new parameter still fails the gate. + code, _out, _err = run_inprocess( + "--no-banner", "-q", "--baseline", baseline_path, "--fail-on-findings", + "--url", "https://a.test/?file=x.pdf&download=/tmp/a.zip", + ) + self.assertEqual(code, cli.EXIT_FINDINGS) + cleanup(baseline_path) + + def test_cli_missing_baseline_is_usage_error(self): + code, _out, err = run_inprocess("--no-banner", "-q", "--baseline", + "/no/such/baseline.json", + "--url", "https://a.test/?file=x.pdf") + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("cannot read", err) + + +class TestSuppression(unittest.TestCase): + def test_suppress_hides_reviewed_fingerprint(self): + directory = tempfile.mkdtemp() + reviewed = os.path.join(directory, "reviewed.json") + code, _out, err = run_inprocess( + "--no-banner", "-q", "--json", "--url", "https://a.test/?file=x.pdf", + "--mark-reviewed", reviewed, + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertTrue(os.path.exists(reviewed)) + payload = json.loads(Path(reviewed).read_text()) + self.assertEqual(len(payload["suppressions"]), 1) + self.assertTrue(payload["suppressions"][0]["fingerprint"]) + + code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--suppress", reviewed, + "--url", "https://a.test/?file=x.pdf", + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertEqual(json.loads(out)["findings"], []) + cleanup(reviewed) + + def test_suppress_accepts_notes_and_plain_lists(self): + directory = tempfile.mkdtemp() + payload = { + "suppressions": [ + {"fingerprint": "deadbeefdeadbeef", "note": "false positive: docs link"} + ] + } + path = os.path.join(directory, "suppress.json") + Path(path).write_text(json.dumps(payload), encoding="utf-8") + baseline = detector.Baseline.from_payload(json.loads(Path(path).read_text())) + self.assertEqual(baseline.fingerprints, {"deadbeefdeadbeef": "false positive: docs link"}) + cleanup(path) + + def test_mark_reviewed_merges_existing_ledger(self): + directory = tempfile.mkdtemp() + ledger = os.path.join(directory, "reviewed.json") + Path(ledger).write_text( + json.dumps({"suppressions": [{"fingerprint": "0000000000000000", "note": "old"}]}), + encoding="utf-8", + ) + code, _out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--url", "https://a.test/?file=x.pdf", + "--mark-reviewed", ledger, + ) + self.assertEqual(code, cli.EXIT_OK) + payload = json.loads(Path(ledger).read_text()) + fingerprints = {entry["fingerprint"] for entry in payload["suppressions"]} + self.assertIn("0000000000000000", fingerprints) + self.assertEqual(len(fingerprints), 2) + cleanup(ledger) + + +# --------------------------------------------------------------------------- +# --explain +# --------------------------------------------------------------------------- +class TestExplain(unittest.TestCase): + def test_explain_shows_rules(self): + code, out, _err = run_inprocess("--no-banner", "-q", "--explain", "file") + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("name-exact", out) + self.assertIn("WOULD be reported", out) + + def test_explain_with_value(self): + code, out, _err = run_inprocess( + "--no-banner", "-q", "--explain", "file", + "--explain-value", "../../etc/passwd", + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("value-traversal", out) + self.assertIn("71/100", out) + + def test_explain_ordinary_parameter(self): + code, out, _err = run_inprocess("--no-banner", "-q", "--explain", "lang") + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("No rule fired", out) + + +# --------------------------------------------------------------------------- +# Markdown / HTML writers +# --------------------------------------------------------------------------- +class TestWriters(unittest.TestCase): + def build_report(self, show_values: bool = False): + requests = [ + sources.request_from_url( + "https://example.test/view?file=report.pdf", sources.SOURCE_URL, "--url" + ), + sources.request_from_url( + "https://other.test/dl?path=../../etc/passwd", sources.SOURCE_FILE, "urls.txt" + ), + ] + return detector.analyze_requests( + requests, detector.AnalysisOptions(show_values=show_values) + ) + + def test_extension_dispatch(self): + self.assertEqual(writers.writer_for_path("report.md"), "markdown") + self.assertEqual(writers.writer_for_path("report.markdown"), "markdown") + self.assertEqual(writers.writer_for_path("report.HTML"), "html") + self.assertEqual(writers.writer_for_path("report.htm"), "html") + with self.assertRaises(ValueError): + writers.writer_for_path("report.pdf") + + def test_markdown_content(self): + text = writers.render_markdown(self.build_report()) + self.assertIn("# PathScope report", text) + self.assertIn("| # | Host |", text) + self.assertIn("Fingerprint", text) + self.assertIn("manual review", text) + self.assertIn("Values included: no", text) + shown = writers.render_markdown(self.build_report(True)) + self.assertIn("Values included: yes", shown) + self.assertNotIn("report.pdf", text) # values never leak by default + + def test_html_is_escaped_and_well_formed(self): + requests = [ + sources.request_from_url( + "https://a.test/?file=.pdf", + sources.SOURCE_URL, + "--url", + ) + ] + data = detector.analyze_requests( + requests, detector.AnalysisOptions(show_values=True) + ) + html_text = writers.render_html(data) + # No raw markup from the input may survive into the document. + self.assertNotIn("", html_text) + self.assertIn("<script>", html_text) + self.assertIn("</script>", html_text) + self.assertIn("", html_text) + self.assertIn("manual review", html_text) + + def test_save_report_flag(self): + directory = tempfile.mkdtemp() + for name, marker in (("report.md", "# PathScope report"), + ("report.html", "")): + path = os.path.join(directory, name) + code, out, err = run_inprocess( + "--no-banner", "-q", "--save-report", path, + "--url", "https://a.test/?file=/x/y.pdf", + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertTrue(os.path.exists(path)) + self.assertIn(marker, Path(path).read_text()) + cleanup(path) + + def test_save_report_rejects_unknown_extension(self): + code, _out, err = run_inprocess( + "--no-banner", "-q", "--save-report", "/tmp/report.pdf", + "--url", "https://a.test/?file=x.pdf", + ) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("unsupported report extension", err) + + def test_output_format_markdown_and_html(self): + for fmt, marker in (("markdown", "# PathScope report"), + ("html", "")): + code, out, _err = run_inprocess( + "--no-banner", "-q", "--output-format", fmt, + "--url", "https://a.test/?file=x.pdf", + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn(marker, out) + + +# --------------------------------------------------------------------------- +# Burp XML +# --------------------------------------------------------------------------- +class TestBurpInput(unittest.TestCase): + def test_base64_and_plain_requests(self): + result = extra_formats.load_burp(burp_xml(), "sample.xml") + self.assertEqual(len(result.requests), 2) + self.assertEqual(result.skipped, 1) + query = [p for r in result.requests for p in r.parameters + if p.location == sources.LOCATION_QUERY] + form = [p for r in result.requests for p in r.parameters + if p.location == sources.LOCATION_FORM] + self.assertEqual([p.name for p in query], ["path"]) + self.assertEqual([p.name for p in form], ["attachment"]) + self.assertIn("secret.txt", form[0].value) + + def test_burp_request_shape(self): + result = extra_formats.load_burp(burp_xml(), "sample.xml") + first = result.requests[0] + self.assertEqual(first.source_type, "burp") + self.assertEqual(first.method, "GET") + self.assertEqual(first.url.host, "app.test") + self.assertEqual(first.url.path, "/dl") + + def test_burp_missing_items(self): + with self.assertRaises(extra_formats.HarError): + extra_formats.load_burp("no items", "x.xml") + + def test_burp_invalid_xml(self): + with self.assertRaises(extra_formats.HarError): + extra_formats.load_burp("", "broken.xml") + + def test_burp_detection(self): + self.assertEqual( + extra_formats.detect_extra_format(burp_xml(), "capture.xml"), + extra_formats.INPUT_FORMAT_BURP, + ) + + def test_cli_burp_file(self): + path = write_temp(".xml", burp_xml()) + try: + code, out, _err = run_inprocess("--no-banner", "-q", "--json", "-i", path) + finally: + cleanup(path) + self.assertEqual(code, cli.EXIT_OK) + payload = json.loads(out) + self.assertEqual({f["source_type"] for f in payload["findings"]}, {"burp"}) + self.assertEqual(payload["summary"]["candidates"], 2) + + +# --------------------------------------------------------------------------- +# OpenAPI +# --------------------------------------------------------------------------- +class TestOpenApiInput(unittest.TestCase): + def test_parameters_are_inventoried(self): + result = extra_formats.load_openapi(json.dumps(OPENAPI), "api.json") + names = {(r.method, p.location, p.name) for r in result.requests for p in r.parameters} + self.assertIn(("GET", "query", "fileId"), names) + self.assertIn(("GET", "query", "download"), names) + self.assertNotIn(("GET", "query", "X-Trace"), names) # headers ignored + self.assertIn(("POST", "json", "template"), names) + self.assertIn(("POST", "json", "options.layout"), names) + + def test_requests_are_synthetic_and_value_free(self): + result = extra_formats.load_openapi(json.dumps(OPENAPI), "api.json") + for request in result.requests: + self.assertEqual(request.source_type, "openapi") + for parameter in request.parameters: + self.assertEqual(parameter.value, "") + + def test_not_openapi(self): + with self.assertRaises(extra_formats.HarError): + extra_formats.load_openapi(json.dumps({"paths": {}}), "x.json") + + def test_swagger2_host(self): + payload = { + "swagger": "2.0", + "host": "legacy.test", + "basePath": "/api", + "schemes": ["https"], + "paths": {"/x": {"get": {"parameters": [{"name": "file", "in": "query"}]}}}, + } + result = extra_formats.load_openapi(json.dumps(payload), "swagger.json") + self.assertEqual(result.requests[0].url.host, "legacy.test") + self.assertEqual(result.requests[0].url.scheme, "https") + + def test_yaml_hint_is_explicit(self): + path = write_temp(".yaml", "openapi: 3.0.0\npaths: {}\n") + try: + with self.assertRaises(extra_formats.HarError) as ctx: + extra_formats.load_extra_file(path, "openapi-yaml") + finally: + cleanup(path) + self.assertIn("YAML", str(ctx.exception)) + + def test_cli_openapi_file(self): + path = write_temp(".json", json.dumps(OPENAPI)) + try: + code, out, _err = run_inprocess("--no-banner", "-q", "--json", "-i", path) + finally: + cleanup(path) + self.assertEqual(code, cli.EXIT_OK) + payload = json.loads(out) + self.assertEqual(payload["summary"]["candidates"], 4) + self.assertEqual({f["location"] for f in payload["findings"]}, {"query", "json"}) + + +# --------------------------------------------------------------------------- +# Raw HTTP +# --------------------------------------------------------------------------- +class TestRawHttpInput(unittest.TestCase): + def test_single_request(self): + text = ( + "GET /view?file=../../etc/passwd HTTP/1.1\n" + "Host: app.test\n" + "Accept: */*\n\n" + ) + result = extra_formats.load_raw_http(text, "request.txt") + self.assertEqual(len(result.requests), 1) + self.assertEqual(result.requests[0].url.host, "app.test") + self.assertEqual([p.name for p in result.requests[0].parameters], ["file"]) + + def test_form_body(self): + text = ( + "POST /import HTTP/1.1\n" + "Host: app.test\n" + "Content-Type: application/x-www-form-urlencoded\n\n" + "source=%2Fvar%2Fwww%2Fdump.sql&format=csv\n" + ) + result = extra_formats.load_raw_http(text, "request.txt") + form = {p.name: p.value for p in result.requests[0].parameters} + self.assertEqual(form["source"], "/var/www/dump.sql") + + def test_multiple_requests(self): + text = ( + "GET /a?file=x HTTP/1.1\nHost: a.test\n\n" + "###\n" + "GET /b?path=y HTTP/1.1\nHost: b.test\n\n" + ) + result = extra_formats.load_raw_http(text, "requests.txt") + self.assertEqual([r.url.host for r in result.requests], ["a.test", "b.test"]) + + def test_missing_host(self): + with self.assertRaises(extra_formats.HarError): + extra_formats.load_raw_http("GET /a?file=x HTTP/1.1\n\n", "x.txt") + + def test_malformed_request_line(self): + with self.assertRaises(extra_formats.HarError): + extra_formats.load_raw_http("nonsense\nHost: a.test\n\n", "x.txt") + + def test_detection(self): + text = "POST /x HTTP/1.1\nHost: a.test\n\n" + self.assertEqual( + extra_formats.detect_extra_format(text, "req.txt"), + extra_formats.INPUT_FORMAT_RAW, + ) + + +# --------------------------------------------------------------------------- +# Recon exports +# --------------------------------------------------------------------------- +class TestReconInput(unittest.TestCase): + def test_httpx_lines(self): + text = ( + '"https://app.test/dl?file=x.pdf" [200] [1234 bytes]\n' + "https://app.test/api?path=/var/www [404] [12 bytes]\n" + ) + result = extra_formats.load_recon_text(text, "httpx.txt") + self.assertEqual(len(result.requests), 2) + self.assertEqual({p.name for r in result.requests for p in r.parameters}, + {"file", "path"}) + + def test_ffuf_lines(self): + # ffuf directory hits are not URLs; only URL-bearing lines are used. + text = ( + "admin [Status: 200, Size: 123]\n" + "https://app.test/dl?file=x.pdf [Status: 200, Size: 999]\n" + ) + result = extra_formats.load_recon_text(text, "ffuf.txt") + self.assertEqual(len(result.requests), 1) + self.assertEqual(result.requests[0].url.host, "app.test") + + def test_nuclei_jsonl(self): + line = json.dumps({"template": "t", "matched-at": "https://app.test/?file=x"}) + result = extra_formats.load_recon_text(line, "nuclei.jsonl") + self.assertEqual(result.requests[0].url.host, "app.test") + + def test_no_urls_is_an_error(self): + with self.assertRaises(extra_formats.HarError): + extra_formats.load_recon_text("nothing here\n", "x.txt") + + def test_plain_url_list_is_not_recon(self): + text = "https://a.test/?file=1\nhttps://b.test/?path=2\n" + self.assertEqual(sources.detect_input_format(text), sources.INPUT_FORMAT_URLS) + + def test_recon_detection(self): + text = "https://a.test/x [200] [1234 bytes]\n" + self.assertEqual( + sources.detect_input_format(text), sources.FORMAT_RECON + if hasattr(sources, "FORMAT_RECON") else "recon", + ) + + +# --------------------------------------------------------------------------- +# Terminal UX: --top, --group-by, --summary-only +# --------------------------------------------------------------------------- +SAMPLE_URLS = [ + "https://a.test/?file=/x/a.pdf", + "https://b.test/?path=/var/www", + "https://c.test/?download=/tmp/x.zip", +] + + +class TestTerminalUx(unittest.TestCase): + def test_top_limits_output(self): + stdin = "\n".join(SAMPLE_URLS) + full = run_inprocess("--no-banner", "-q", "--url", SAMPLE_URLS[0], + "--url", SAMPLE_URLS[1], "--url", SAMPLE_URLS[2])[1] + limited = run_inprocess("--no-banner", "-q", "--top", "1", + "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[1], + "--url", SAMPLE_URLS[2])[1] + self.assertGreater(full.count("#"), limited.count("#")) + self.assertIn("#1", limited) + self.assertNotIn("#2", limited) + + def test_top_zero_shows_all(self): + out = run_inprocess("--no-banner", "-q", "--top", "0", + "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[1])[1] + self.assertIn("#2", out) + + def test_group_by_host(self): + out = run_inprocess("--no-banner", "-q", "--group-by", "host", + "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[1])[1] + self.assertIn("== a.test ==", out) + self.assertIn("== b.test ==", out) + + def test_group_by_confidence(self): + out = run_inprocess("--no-banner", "-q", "--group-by", "confidence", + "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[2])[1] + self.assertIn("confidence", out) + + def test_summary_only(self): + code, out, _err = run_inprocess("--no-banner", "-q", "--summary-only", + "--url", SAMPLE_URLS[0]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("PathScope summary", out) + self.assertIn("Candidates per host", out) + self.assertIn("Candidates per rule", out) + self.assertNotIn("Why", out) + + +# --------------------------------------------------------------------------- +# Report metadata for the new features +# --------------------------------------------------------------------------- +class TestReportMetadata(unittest.TestCase): + def test_json_summary_includes_mode_and_diff_counts(self): + requests = [sources.request_from_url("https://a.test/?file=x.pdf", + sources.SOURCE_URL, "--url")] + payload = json.loads( + report.render_json(detector.analyze_requests(requests, detector.AnalysisOptions())) + ) + self.assertEqual(payload["summary"]["mode"], "scan") + self.assertEqual(payload["summary"]["new"], 1) + self.assertEqual(payload["summary"]["known"], 0) + self.assertEqual(payload["findings"][0]["status"], "new") + self.assertTrue(payload["findings"][0]["fingerprint"]) + + def test_csv_has_fingerprint_and_status(self): + requests = [sources.request_from_url("https://a.test/?file=x.pdf", + sources.SOURCE_URL, "--url")] + text = report.render_csv(detector.analyze_requests(requests, + detector.AnalysisOptions())) + header = text.splitlines()[0].split(",") + self.assertIn("fingerprint", header) + self.assertIn("status", header) + self.assertIn("note", header) + + def test_sarif_has_partial_fingerprints_and_baseline_state(self): + requests = [sources.request_from_url("https://a.test/?file=x.pdf", + sources.SOURCE_URL, "--url")] + payload = json.loads( + report.render_sarif(detector.analyze_requests(requests, + detector.AnalysisOptions())) + ) + result = payload["runs"][0]["results"][0] + self.assertIn("partialFingerprints", result) + self.assertIn("pathscope/v1", result["partialFingerprints"]) + self.assertEqual(result["baselineState"], "new") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_features_v22.py b/tests/test_features_v22.py new file mode 100644 index 0000000..f255cd9 --- /dev/null +++ b/tests/test_features_v22.py @@ -0,0 +1,1502 @@ +#!/usr/bin/env python3 +"""Tests for the PathScope 2.2 feature batch. + +Covers, feature by feature: + +1. live watch mode (``--watch``): stable polls, new-only output, rotation +2. interactive HTML report: sorting hooks, escaping, no external assets +3. rule introspection: ``--list-rules``, ``--rules``, ``--disable-rule`` +4. CI toolkit: ``--policy``, JUnit, GitHub annotations, ``--self-test`` +5. scale helpers: ``--dedupe-by``, ``--max-entries``, ``--stats`` +6. extra tool exports: Postman, ZAP, mitmproxy, GraphQL, cookie jars +7. name folding and multilingual term packs +8. value-shape demotion + +Run with:: + + python3 -m unittest discover -s tests -v +""" + +from __future__ import annotations + +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import ( # noqa: E402 + ci, + config, + detector, + heuristics, + naming, + policy, + progress, + report, + rules, + sources, + tool_formats, + valueshape, + watch, + writers, +) + + +# --------------------------------------------------------------------------- +# helpers +# --------------------------------------------------------------------------- +def temp_file(content: str, suffix: str = ".txt") -> str: + handle = tempfile.NamedTemporaryFile( + "w", suffix=suffix, delete=False, encoding="utf-8" + ) + with handle as stream: + stream.write(content) + return handle.name + + +def cleanup(*paths: str) -> None: + for path in paths: + try: + os.unlink(path) + except OSError: + pass + + +def run_inprocess(*args: str, stdin: str = ""): + out, err = io.StringIO(), io.StringIO() + code = __import__("pathscope.cli", fromlist=["run"]).run( + list(args), stdout=out, stderr=err, stdin_text=stdin + ) + return code, out.getvalue(), err.getvalue() + + +def analyze(url: str, **options) -> detector.Report: + request = sources.request_from_url(url, sources.SOURCE_URL, "--url") + return detector.analyze_requests([request], detector.AnalysisOptions(**options)) + + +def scores(report_data: detector.Report): + return [(finding.parameter, finding.score, finding.rule) for finding in report_data.findings] + + +# --------------------------------------------------------------------------- +# Feature 1: live watch mode +# --------------------------------------------------------------------------- +class TestWatchMode(unittest.TestCase): + def setUp(self): + self.path = temp_file("https://a.test/?file=/x/one.pdf\n") + self.options = detector.AnalysisOptions() + + def tearDown(self): + cleanup(self.path) + + def test_first_poll_reports_candidates(self): + state = watch.WatchState() + fresh, warnings, loaded, changed = watch.watch_once( + self.path, self.options, state + ) + self.assertTrue(changed) + self.assertEqual(loaded, 1) + self.assertEqual(warnings, []) + self.assertEqual([finding.parameter for finding in fresh], ["file"]) + + def test_unchanged_file_is_not_reparsed(self): + state = watch.WatchState() + watch.watch_once(self.path, self.options, state) + fresh, _warnings, _loaded, changed = watch.watch_once( + self.path, self.options, state + ) + self.assertFalse(changed) + self.assertEqual(fresh, []) + self.assertEqual(state.polls, 1) + + def test_only_new_candidates_are_returned(self): + state = watch.WatchState() + watch.watch_once(self.path, self.options, state) + with open(self.path, "a", encoding="utf-8") as handle: + handle.write("https://b.test/?path=../../etc/passwd\n") + fresh, _warnings, loaded, changed = watch.watch_once( + self.path, self.options, state + ) + self.assertTrue(changed) + self.assertEqual(loaded, 2) + self.assertEqual([finding.host for finding in fresh], ["b.test"]) + + def test_replaced_file_starts_a_new_baseline(self): + state = watch.WatchState() + watch.watch_once(self.path, self.options, state) + with open(self.path, "w", encoding="utf-8") as handle: + handle.write("https://c.test/?file=/a/b\n") + fresh, *_rest = watch.watch_once(self.path, self.options, state) + self.assertEqual([finding.host for finding in fresh], ["c.test"]) + + def test_missing_file_raises_watch_error(self): + with self.assertRaises(watch.WatchError): + watch.file_signature("/nonexistent/pathscope-test-file") + + def test_watch_forever_stops_after_max_polls(self): + out, err = io.StringIO(), io.StringIO() + batches = watch.watch_forever( + self.path, + self.options, + interval=0.01, + stdout=out, + stderr=err, + sleep=lambda _seconds: None, + max_polls=2, + ) + self.assertEqual(batches, 1) + self.assertIn("Watching", out.getvalue()) + self.assertIn("[new] a.test", out.getvalue()) + self.assertIn("Stopped after 2 poll(s)", out.getvalue()) + + def test_watch_forever_handles_keyboard_interrupt(self): + out = io.StringIO() + + def boom(_seconds): + raise KeyboardInterrupt + + watch.watch_forever( + self.path, + self.options, + interval=0.01, + stdout=out, + stderr=io.StringIO(), + sleep=boom, + ) + self.assertIn("Stopped after 1 poll(s)", out.getvalue()) + + def test_interval_is_clamped(self): + out = io.StringIO() + watch.watch_forever( + self.path, + self.options, + interval=0.0001, + stdout=out, + stderr=io.StringIO(), + sleep=lambda _seconds: None, + max_polls=1, + ) + self.assertIn(f"every {watch.MIN_INTERVAL:g}s", out.getvalue()) + + def test_cli_watch_missing_file_is_a_usage_error(self): + code, _out, err = run_inprocess( + "--no-banner", "-q", "--watch", "/nonexistent/x.har" + ) + self.assertEqual(code, 2) + self.assertIn("--watch file not found", err) + + def test_cli_watch_interval_must_be_positive(self): + with self.assertRaises(SystemExit): + run_inprocess( + "--no-banner", "-q", "--watch", self.path, "--interval", "0" + ) + + +# --------------------------------------------------------------------------- +# Feature 2: interactive HTML report +# --------------------------------------------------------------------------- +class TestInteractiveReport(unittest.TestCase): + def build(self, url="https://a.test/?file=../../etc/passwd"): + return analyze(url) + + def test_interactive_html_has_controls_and_script(self): + markup = writers.render_html_interactive(self.build()) + self.assertIn('', markup) + self.assertIn('id="filter"', markup) + self.assertIn('id="confidence"', markup) + self.assertIn('id="reviewed-only"', markup) + self.assertIn("localStorage", markup) + self.assertIn("data-sort=", markup) + self.assertIn("data-fingerprint=", markup) + + def test_interactive_html_is_self_contained(self): + markup = writers.render_html_interactive(self.build()) + for banned in ("http://", "https://", "" in the input is stripped by sanitize_text, so + # the document can never contain raw script markup from a parameter. + hostile = writers.render_html_interactive( + analyze("https://a.test/?file=") + ) + self.assertNotIn("", hostile) + + def test_values_only_when_requested(self): + without = writers.render_html_interactive(self.build()) + with_values = writers.render_html_interactive( + analyze("https://a.test/?file=/etc/passwd", show_values=True) + ) + self.assertNotIn("/etc/passwd", without) + self.assertIn("/etc/passwd", with_values) + + def test_save_report_interactive_writes_html(self): + path = temp_file("", ".html") + cleanup(path) + try: + code, _out, err = run_inprocess( + "--no-banner", + "-q", + "--interactive", + "--save-report", + path, + "--url", + "https://a.test/?file=/a/b", + ) + self.assertEqual(code, 0, err) + content = Path(path).read_text(encoding="utf-8") + self.assertIn("localStorage", content) + finally: + cleanup(path) + + def test_interactive_requires_html_report(self): + with self.assertRaises(SystemExit): + run_inprocess( + "--no-banner", "-q", "--interactive", "--url", "https://a.test/?file=x" + ) + + def test_interactive_script_implements_review_and_filters(self): + """The inline script must wire review state, filters and sorting.""" + script = writers.INTERACTIVE_SCRIPT + for marker in ( + "localStorage", + "pathscope-reviewed", + "data-fingerprint", + "data-search", + "data-confidence", + "reviewed-only", + "data-sort", + "navigator.clipboard", + ): + self.assertIn(marker, script, marker) + # Review state must never leave the browser: no network primitives. + for banned in ("fetch(", "XMLHttpRequest", "WebSocket", "sendBeacon"): + self.assertNotIn(banned, script, banned) + + def test_interactive_css_hides_controls_when_printing(self): + self.assertIn("@media print", writers.INTERACTIVE_CSS) + self.assertIn(".controls, .copy { display: none; }", writers.INTERACTIVE_CSS) + + def test_static_html_has_no_script(self): + markup = writers.render_html(analyze("https://a.test/?file=/a")) + self.assertNotIn("&y=1")) + ET.fromstring(document) # must not raise + + def test_junit_format_on_cli(self): + code, out, _err = run_inprocess( + "--no-banner", "-q", "--output-format", "junit", "--url", + "https://a.test/?file=/a", + ) + self.assertEqual(code, 0) + self.assertTrue(out.startswith(" i + self.assertIn("fllero", variants) # 1 -> l + self.assertEqual(naming.leet_variants("ab"), []) # too short + self.assertNotIn("f1le", naming.leet_variants("f1le")) # no self-copy + + def test_language_packs(self): + for tag in naming.LANGUAGE_NAMES: + self.assertTrue(naming.LANGUAGE_PACKS[tag], tag) + self.assertIn("de", naming.language_terms(["de"])) + self.assertEqual(len(naming.language_terms(["auto"])), 6) + + def test_i18n_names_score_only_when_enabled(self): + # Without the German pack this is only a weak multiword name (+5), + # which is below the default threshold on its own. + self.assertEqual( + [item.rule for item in heuristics.analyze_name("bild_datei")], ["name-weak"] + ) + evidence = heuristics.analyze_name("bild_datei", languages=("de",)) + self.assertEqual([item.rule for item in evidence], ["name-i18n"]) + + def test_i18n_does_not_duplicate_english(self): + # ``image`` is English/generic; adding French must not inflate it. + evidence = heuristics.analyze_name("image", languages=("fr",)) + self.assertEqual([item.rule for item in evidence], ["name-generic"]) + + def test_i18n_fold_rule(self): + # Accented spellings only match after folding and use the weaker rule. + for spelling in ("página", "ındice"): + evidence = heuristics.analyze_name(spelling, languages=("es",)) + self.assertEqual([item.rule for item in evidence], ["name-i18n-fold"], spelling) + self.assertEqual( + [item.rule for item in heuristics.analyze_name("archivo", languages=("es",))], + ["name-i18n"], + ) + + def test_parse_languages(self): + self.assertEqual(naming.parse_languages(""), ()) + self.assertEqual(naming.parse_languages("off"), ()) + self.assertEqual(naming.parse_languages("de, Español"), ("de", "es")) + self.assertEqual(naming.parse_languages("auto"), naming.LANGUAGE_NAMES) + with self.assertRaises(ValueError): + naming.parse_languages("xx") + + def test_cli_name_lang(self): + code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--name-lang", "de", + "--url", "https://a.test/?bild_datei=/x", + ) + payload = json.loads(out) + self.assertEqual(code, 0) + self.assertEqual(payload["findings"][0]["rule"], "name-i18n") + self.assertEqual(payload["name_lang"], ["de"]) + + def test_cli_name_lang_auto_and_config(self): + path = temp_file(json.dumps({"name_lang": ["es"]}), ".json") + try: + _code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--config", path, + "--url", "https://a.test/?archivo=/x", + ) + self.assertEqual(json.loads(out)["findings"][0]["rule"], "name-i18n") + _code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--name-lang", "auto", + "--url", "https://a.test/?archivo=/x", + ) + self.assertEqual(json.loads(out)["name_lang"], list(naming.LANGUAGE_NAMES)) + finally: + cleanup(path) + + def test_cli_bad_language_is_usage_error(self): + with self.assertRaises(SystemExit): + run_inprocess("--no-banner", "-q", "--name-lang", "xx", "--url", "https://a.test/?file=x") + + def test_no_fold_disables_folding(self): + # Fullwidth letters are folded by NFKC; --no-fold must stop that. + url = "https://a.test/?%EF%BD%86%EF%BD%89%EF%BD%8C%EF%BD%85=/x" + _code, folded, _err = run_inprocess( + "--no-banner", "-q", "--json", "--url", url + ) + self.assertEqual(len(json.loads(folded)["findings"]), 1) + code, plain, _err = run_inprocess( + "--no-banner", "-q", "--json", "--no-fold", "--url", url + ) + self.assertEqual(code, 0) + self.assertEqual(json.loads(plain)["findings"], []) + + def test_config_rejects_unknown_language(self): + with self.assertRaises(config.ConfigError): + config.validate_payload({"name_lang": ["xx"]}) + + +# --------------------------------------------------------------------------- +# Feature 8: value-shape demotion +# --------------------------------------------------------------------------- +class TestValueShape(unittest.TestCase): + UUID = "550e8400-e29b-41d4-a716-446655440000" + HASH = "d41d8cd98f00b204e9800998ecf8427e" + JWT = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abcdefghijklmnop" + + def test_shapes_classify(self): + cases = { + self.UUID: valueshape.RULE_UUID, + self.HASH: valueshape.RULE_HASH, + self.JWT: valueshape.RULE_JWT, + "user@example.test": valueshape.RULE_EMAIL, + "192.168.1.1": valueshape.RULE_IP, + "2001:db8::1": valueshape.RULE_IP, + "true": valueshape.RULE_SCALAR, + "42": valueshape.RULE_SCALAR, + "3.14": valueshape.RULE_SCALAR, + } + for value, expected in cases.items(): + match = valueshape.classify(value) + self.assertIsNotNone(match, value) + self.assertEqual(match[0], expected, value) + + def test_paths_are_not_demoted(self): + for value in ( + "/var/www/html", + "../../etc/passwd", + "report.pdf", + "C:\\Windows", + "images/photo.png", + "v1..2", + ): + self.assertIsNone(valueshape.classify(value), value) + + def test_times_are_not_ip_addresses(self): + self.assertIsNone(valueshape.classify("12:30:45")) + + def test_demotion_lowers_score_and_is_explained(self): + analysis = heuristics.analyze_parameter("file", self.UUID, min_score=0) + rules_hit = [item.rule for item in analysis.evidence] + self.assertIn("value-demote-uuid", rules_hit) + self.assertLess(analysis.score, 35 + 1) + reason = next( + item.reason for item in analysis.evidence + if item.rule == "value-demote-uuid" + ) + self.assertIn("UUID", reason) + + def test_uuid_value_is_below_default_threshold(self): + report_data = analyze(f"https://a.test/?file={self.UUID}") + self.assertEqual(report_data.findings, []) + + def test_demotions_can_be_disabled(self): + report_data = analyze( + f"https://a.test/?file={self.UUID}", demote_shapes=False + ) + self.assertEqual(scores(report_data), [("file", 35, "name-exact")]) + + def test_disable_rule_removes_a_demotion(self): + book = rules.RuleBook.with_overrides({}, ["value-demote-uuid"]) + analysis = heuristics.analyze_parameter( + "file", self.UUID, book=book, min_score=0 + ) + self.assertEqual(analysis.score, 35) + + def test_traversal_is_not_demoted(self): + analysis = heuristics.analyze_parameter("file", "../../etc/passwd") + self.assertFalse( + [rule for rule in analysis.rules if rule.startswith("value-demote-")] + ) + self.assertEqual(analysis.score, 71) + + def test_cli_no_demote(self): + code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--no-demote", "--url", + f"https://a.test/?file={self.UUID}", + ) + self.assertEqual(code, 0) + self.assertEqual(len(json.loads(out)["findings"]), 1) + + def test_config_demote_shapes_false(self): + path = temp_file(json.dumps({"demote_shapes": False}), ".json") + try: + _code, out, _err = run_inprocess( + "--no-banner", "-q", "--json", "--config", path, + "--url", f"https://a.test/?file={self.UUID}", + ) + self.assertEqual(len(json.loads(out)["findings"]), 1) + finally: + cleanup(path) + + def test_scalar_demotion_lowers_but_does_not_hide_a_strong_name(self): + # A strong name (35) minus the scalar demotion (10) is exactly at the + # default threshold (25): nothing is silently hidden, the candidate + # simply ranks at the bottom of the list with the demotion explained. + analysis = heuristics.analyze_parameter("file", "true", min_score=0) + self.assertEqual(analysis.score, 25) + self.assertIn("value-demote-scalar", analysis.rules) + weak = heuristics.analyze_parameter("target", "true", min_score=0) + self.assertEqual(weak.evidence, []) # generic name + scalar: nothing + + +# --------------------------------------------------------------------------- +# Cross-cutting: config plumbing and determinism +# --------------------------------------------------------------------------- +class TestConfigPlumbing(unittest.TestCase): + def test_new_keys_validate(self): + cfg = config.validate_payload( + { + "name_lang": ["de", "auto"], + "fold_names": False, + "demote_shapes": False, + } + ) + self.assertEqual(cfg.name_lang, list(naming.LANGUAGE_NAMES)) + self.assertFalse(cfg.fold_names) + self.assertFalse(cfg.demote_shapes) + + def test_merged_through_extends(self): + base = temp_file(json.dumps({"name_lang": ["de"]}), ".json") + child = temp_file(json.dumps({"extends": base, "fold_names": False}), ".json") + try: + cfg = config.load_config(child) + self.assertEqual(cfg.name_lang, ["de"]) + self.assertFalse(cfg.fold_names) + finally: + cleanup(base, child) + + def test_starter_configs_are_valid(self): + from pathscope import presets + + for start in presets.STARTER_CONFIGS.values(): + parsed = config.validate_payload(json.loads(start)) + self.assertTrue(parsed.demote_shapes) + + def test_json_payload_documents_rules_and_languages(self): + report_data = analyze("https://a.test/?file=/a") + payload = json.loads(report.render_json(report_data)) + self.assertIn("name-exact", payload["rules"]) + self.assertEqual(payload["rules_source"], "defaults") + self.assertIn("name_lang", payload) + + def test_deterministic_with_new_features(self): + urls = [ + "https://a.test/?bild_datei=/a", + "https://b.test/?f1le=/x/y", + "https://c.test/?file=550e8400-e29b-41d4-a716-446655440000", + ] + first = run_inprocess( + "--no-banner", "-q", "--json", "--name-lang", "auto", "--url", urls[0], + "--url", urls[1], "--url", urls[2], + )[1] + second = run_inprocess( + "--no-banner", "-q", "--json", "--name-lang", "auto", "--url", urls[2], + "--url", urls[0], "--url", urls[1], + )[1] + self.assertEqual(first, second) + + def test_self_test_covers_new_features(self): + results = {entry["name"]: entry["passed"] for entry in ci.run_selftest()} + self.assertTrue(results["values are hidden by default"]) + self.assertTrue(results["HTML output escapes input"]) + + def test_safety_imports(self): + """The new modules must import only the standard library.""" + import ast + + allowed = { + "argparse", "json", "os", "sys", "typing", "dataclasses", "re", + "hashlib", "time", "unicodedata", "urllib", "io", "csv", "html", + "xml", "xml.sax", "xml.sax.saxutils", "base64", "collections", + "pathlib", "textwrap", "copy", "datetime", "__future__", + # 2.3 additions + "math", "sqlite3", "zipfile", "curses", "platform", "shutil", + "tempfile", "calendar", "shlex", "hmac", "secrets", + } + for name in ( + "rules", "naming", "valueshape", "policy", "ci", "watch", + "progress", "tool_formats", "heuristics", "detector", + ): + path = REPO_ROOT / "pathscope" / f"{name}.py" + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + root = alias.name.split(".")[0] + self.assertIn(root, {item.split(".")[0] for item in allowed}, alias.name) + elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0: + root = node.module.split(".")[0] + self.assertIn(root, {item.split(".")[0] for item in allowed}, node.module) + + +if __name__ == "__main__": + unittest.main(verbosity=2) + + +# --------------------------------------------------------------------------- +# Deliverables in the repository: CI files, policy, README +# --------------------------------------------------------------------------- +class TestRepositoryDeliverables(unittest.TestCase): + def test_workflow_file_exists_and_is_plain_yaml(self): + path = REPO_ROOT / ".github" / "workflows" / "pathscope.yml" + text = path.read_text(encoding="utf-8") + self.assertIn("python3 -m unittest discover", text) + self.assertIn("--self-test", text) + self.assertIn("--policy", text) + # Only first-party or official actions: no arbitrary third-party code. + for line in text.splitlines(): + if "uses:" in line: + action = line.split("uses:", 1)[1].strip() + self.assertTrue( + action.startswith( + ("actions/checkout@", "actions/setup-python@", + "actions/download-artifact@", "actions/upload-artifact@") + ), + action, + ) + + def test_precommit_hooks_are_declared(self): + path = REPO_ROOT / ".pre-commit-hooks.yaml" + text = path.read_text(encoding="utf-8") + self.assertIn("id: pathscope-selftest", text) + self.assertIn("id: pathscope-no-new-high", text) + self.assertIn("pass_filenames: false", text) + + def test_example_policy_is_valid(self): + path = REPO_ROOT / ".pathscope" / "policy.json" + loaded = policy.load_policy(str(path)) + self.assertEqual(loaded.max_high, 0) + self.assertEqual(loaded.max_medium, 10) + + def test_ci_policy_file_matches_starter_schema(self): + starter = json.loads(policy.starter_policy()) + on_disk = json.loads((REPO_ROOT / ".pathscope" / "policy.json").read_text()) + self.assertEqual(set(starter) ^ set(on_disk), set()) + for key in ("max_high", "max_medium", "max_total"): + self.assertIn(key, on_disk) + + def test_banner_links_are_still_verbatim(self): + from pathscope import BANNER_LINKS, GITHUB_URL, INSTAGRAM_URL, SUPPORT_URL, banner_lines + + self.assertEqual( + BANNER_LINKS, + ( + ("GitHub", GITHUB_URL), + ("Instagram", INSTAGRAM_URL), + ("Support", SUPPORT_URL), + ), + ) + self.assertFalse( + (REPO_ROOT / ".github" / "workflows" / "pathscope.yml") + .read_text(encoding="utf-8") + .count("curl") + ) + + def test_readme_documents_every_new_flag(self): + readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8") + for flag in ( + "--watch", "--interval", "--interactive", "--list-rules", "--rules", + "--disable-rule", "--policy", "--init-policy", "--self-test", + "--github-annotations", "--name-lang", "--no-fold", "--no-demote", + "--dedupe-by", "--max-entries", "--stats", "--progress", "junit", + "postman", "mitmproxy", "graphql", + ): + self.assertIn(flag, readme, flag) + + def test_readme_table_of_contents_anchors_resolve(self): + import re + + readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8") + titles = re.findall(r"^#+ (.+)$", readme, re.M) + + def slug(title: str) -> str: + cleaned = re.sub(r"[^a-z0-9 -]", "", title.lower()) + return cleaned.replace(" ", "-") + + anchors = {slug(title) for title in titles} + for match in re.finditer(r"\]\(#([a-z0-9-]+)\)", readme): + self.assertIn(match.group(1), anchors, match.group(1)) + + def test_every_rule_is_documented(self): + readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8") + for rule in rules.RULE_NAMES: + if rule == "value-demote-hash": + continue # grouped under value-demote-* in the table + if rule.startswith("value-demote-"): + self.assertIn("value-demote-*", readme) + continue + self.assertIn(f"`{rule}`", readme, rule) + + +# --------------------------------------------------------------------------- +# Prompt-derived guarantees +# --------------------------------------------------------------------------- +class TestPromptGuarantees(unittest.TestCase): + def test_watch_and_policy_never_touch_the_network(self): + from unittest import mock + + path = temp_file("https://a.test/?file=../../etc/passwd\n") + + def boom(*_args, **_kwargs): + raise AssertionError("network operation attempted") + + try: + with mock.patch("socket.socket", side_effect=boom), \ + mock.patch("socket.create_connection", side_effect=boom), \ + mock.patch("socket.getaddrinfo", side_effect=boom): + code, _out, _err = run_inprocess( + "--no-banner", "-q", "--policy", '{"max_high": 0}', "-i", path + ) + self.assertEqual(code, 1) # policy failed, but no socket was used + finally: + cleanup(path) + + def test_cookie_values_are_never_rendered(self): + text = "# Netscape HTTP Cookie File\n.a\tTRUE\t/\tFALSE\t0\tfile_path\tTOPSECRET\n" + loaded = tool_formats.load_cookies(text, "c.txt") + report_data = detector.analyze_requests( + loaded.requests, detector.AnalysisOptions(show_values=True) + ) + rendered = report.render_json(report_data) + report.render_csv(report_data) + self.assertNotIn("TOPSECRET", rendered) + + def test_demotion_reasons_use_neutral_language(self): + analysis = heuristics.analyze_parameter( + "file", "550e8400-e29b-41d4-a716-446655440000", min_score=0 + ) + blob = " ".join(analysis.reasons).lower() + for banned in ("vulnerable", "exploitable", "attack", "confirmed"): + self.assertNotIn(banned, blob) + + def test_all_new_flags_appear_in_help(self): + import contextlib + + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + with self.assertRaises(SystemExit): + __import__("pathscope.cli", fromlist=["build_parser"]).build_parser().parse_args( + ["--help"] + ) + help_text = buffer.getvalue() + for flag in ( + "--watch", "--list-rules", "--rules", "--disable-rule", "--policy", + "--self-test", "--name-lang", "--dedupe-by", "--max-entries", + "--stats", "--progress", "--interactive", "--github-annotations", + ): + self.assertIn(flag, help_text, flag) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/test_features_v23.py b/tests/test_features_v23.py new file mode 100644 index 0000000..1022474 --- /dev/null +++ b/tests/test_features_v23.py @@ -0,0 +1,896 @@ +"""Tests for the PathScope 2.3 feature set. + +Every feature from the 2.3 menu has a class here: + +1. terminal reviewer -> :class:`TestTerminalUi` +2. run history and trends -> :class:`TestRunHistory` +3. installer and packaging -> :class:`TestPackaging` +4. analysis dashboard -> :class:`TestDashboard` +5. review ledger -> :class:`TestReviewLedger` +6. remediation playbooks -> :class:`TestPlaybooks` +7. streaming stdin -> :class:`TestStreaming` +8. reproducible bundles -> :class:`TestBundle` +9. cross-source correlation -> :class:`TestCorrelation` +10. secret scrubbing -> :class:`TestScrubbing` + +plus :class:`TestIntegration` which drives the public CLI end to end. +""" + +from __future__ import annotations + +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import types +import unittest +import zipfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import ( # noqa: E402 + __version__, + analytics, + bundle, + cli, + detector, + history, + ledger, + playbooks, + scrub, + sources, + stream, + tui, +) + +URLS = [ + "https://a.test/?file=../../etc/passwd&download=/x/y", + "https://b.test/?template=/a/b&download=/z", + "https://clean.test/?q=hello", +] + + +def make_requests(urls=URLS): + return sources.load_url_lines(list(urls), "url", "test").requests + + +def make_report(urls=URLS, **options): + report = detector.analyze_requests( + make_requests(urls), detector.AnalysisOptions(**options) + ) + report.rules = {"name-exact": 35} + return report + + +def run_cli(args, stdin=None): + """Run cli.run in-process and return ``(code, stdout, stderr)``.""" + out, err = io.StringIO(), io.StringIO() + code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin) + return code, out.getvalue(), err.getvalue() + + +def tempdir(): + return tempfile.mkdtemp(prefix="pathscope-v23-") + + +class TempDirMixin(unittest.TestCase): + def setUp(self): + self.tmp = tempdir() + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def path(self, name): + return os.path.join(self.tmp, name) + + +# --------------------------------------------------------------------------- +# 1. terminal reviewer +# --------------------------------------------------------------------------- +class TestTerminalUi(TempDirMixin): + def test_state_filters_by_text_and_band(self): + report = make_report() + state = tui.build_state(report) + self.assertEqual(len(state.visible()), report.candidate_count) + state.set_filter("template") + self.assertEqual([f.parameter for f in state.visible()], ["template"]) + state.set_filter("") + label = state.cycle_band() + self.assertIn(label, tui.BANDS) + for _ in range(len(tui.BANDS)): + state.cycle_band() + self.assertEqual(state.band_label(), "all") + + def test_navigation_clamps_at_the_edges(self): + state = tui.build_state(make_report()) + state.move(-99) + self.assertEqual(state.cursor, 0) + state.last() + self.assertEqual(state.cursor, len(state.visible()) - 1) + state.move(999) + self.assertEqual(state.cursor, len(state.visible()) - 1) + state.first() + self.assertEqual(state.cursor, 0) + + def test_marking_tracks_dirty_state(self): + state = tui.build_state(make_report()) + fingerprint = state.current().fingerprint + self.assertTrue(state.toggle_mark()) + self.assertIn(fingerprint, state.marked) + self.assertTrue(state.dirty) + state.toggle_mark() + self.assertNotIn(fingerprint, state.marked) + + def test_status_line_reports_counts(self): + state = tui.build_state(make_report()) + line = state.status_line() + self.assertIn("candidate(s)", line) + self.assertIn("conf=all", line) + + def test_screen_renders_without_a_real_terminal(self): + """Drive the curses screen through a fake stdscr.""" + fake_curses = types.SimpleNamespace( + A_REVERSE=1, A_BOLD=2, KEY_DOWN=258, KEY_UP=259, KEY_NPAGE=338, + KEY_PPAGE=339, KEY_ENTER=343, KEY_BACKSPACE=263, error=Exception, + initscr=lambda: None, noecho=lambda: None, cbreak=lambda: None, + nocbreak=lambda: None, echo=lambda: None, endwin=lambda: None, + curs_set=lambda _n: None, + ) + saved_modules = sys.modules.get("curses") + sys.modules["curses"] = fake_curses + self.addCleanup( + lambda: sys.modules.__setitem__("curses", saved_modules) + if saved_modules is not None + else sys.modules.pop("curses", None) + ) + + class Screen: + def __init__(self, keys): + self.keys = list(keys) + self.written = [] + + def getmaxyx(self): + return (24, 100) + + def erase(self): + self.written.clear() + + def addstr(self, y, x, text, _attr=0): + if y >= 23 and x + len(text) >= 99: + raise Exception("bottom right corner") + self.written.append(text) + + def refresh(self): + pass + + def getch(self): + return self.keys.pop(0) if self.keys else ord("q") + + def keypad(self, _flag): + pass + + report = make_report() + state = tui.build_state(report) + screen = tui.ReviewScreen(state) + screen.stdscr = Screen([ord("j"), ord("m"), ord("c"), ord("?"), ord("?"), ord("s"), ord("q")]) + recorded = {} + + def save(fingerprints): + recorded["fingerprints"] = fingerprints + return len(fingerprints) + + marked = screen.run(save=save) + self.assertEqual(marked, 1) + self.assertEqual(len(recorded["fingerprints"]), 1) + screen.show_help = False + screen.draw() + self.assertTrue(any("candidate(s)" in line for line in screen.stdscr.written)) + + def test_tui_refuses_without_a_terminal(self): + code, _out, err = run_cli( + ["--no-banner", "--url", URLS[0], "--tui", "--ledger", self.path("l.db")] + ) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("interactive terminal", err) + + def test_tui_requires_a_ledger(self): + # Without a TTY the terminal check fires first; with a faked TTY the + # missing --ledger must be reported. Both are usage errors. + code, _out, err = run_cli(["--no-banner", "--url", URLS[0], "--tui"]) + self.assertEqual(code, cli.EXIT_USAGE) + original = tui.available + tui.available = lambda: True + try: + code, _out, err = run_cli(["--no-banner", "--url", URLS[0], "--tui"]) + finally: + tui.available = original + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("--ledger", err) + + def test_unmarking_in_the_tui_forgets_the_review_but_keeps_the_audit(self): + from pathscope import ledger as ledger_module + + path = self.path("l.db") + run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path, + "--ledger-mark-all", "--reviewer", "seed"]) + store = ledger_module.open_ledger(path) + seeded = set(store.fingerprints()) + store.close() + self.assertTrue(seeded) + + real_open, real_run = tui.ReviewScreen.open, tui.ReviewScreen.run + original_available = tui.available + tui.available = lambda: True + + def fake_open(screen_self): + screen_self.stdscr = object() + + def fake_run(screen_self, save=None): + screen_self.state.marked.clear() # every row unmarked + if save is not None: + save(sorted(screen_self.state.marked)) + return 0 + + tui.ReviewScreen.open, tui.ReviewScreen.run = fake_open, fake_run + try: + code, _out, _err = run_cli( + ["--no-banner", "--url", URLS[0], "--ledger", path, "--tui"] + ) + finally: + tui.ReviewScreen.open, tui.ReviewScreen.run = real_open, real_run + tui.available = original_available + self.assertEqual(code, cli.EXIT_OK) + + store = ledger_module.open_ledger(path) + self.assertEqual(store.fingerprints(), set()) + self.assertGreaterEqual(store.stats()["events"], len(seeded) * 2) + store.close() + + def test_reviewed_rows_are_visible_when_the_tui_opens(self): + """--tui must not pre-hide reviews: they are shown marked instead.""" + path = self.path("l.db") + run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path, + "--ledger-mark-all"]) + seen = {} + real_open, real_run = tui.ReviewScreen.open, tui.ReviewScreen.run + original_available = tui.available + tui.available = lambda: True + + def fake_open(screen_self): + screen_self.stdscr = object() + + def fake_run(screen_self, save=None): + seen["visible"] = len(screen_self.state.visible()) + seen["marked"] = len(screen_self.state.marked) + return 0 + + tui.ReviewScreen.open, tui.ReviewScreen.run = fake_open, fake_run + try: + run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path, "--tui"]) + finally: + tui.ReviewScreen.open, tui.ReviewScreen.run = real_open, real_run + tui.available = original_available + self.assertGreater(seen["visible"], 0) + self.assertEqual(seen["marked"], seen["visible"]) + + def test_help_text_mentions_no_requests(self): + joined = " ".join(tui.HELP_LINES) + self.assertIn("no request is ever sent", joined) + + +# --------------------------------------------------------------------------- +# 2. run history and trends +# --------------------------------------------------------------------------- +class TestRunHistory(TempDirMixin): + def test_history_is_empty_when_missing(self): + document = history.load_history(self.path("none.json")) + self.assertEqual(document["runs"], []) + + def test_appended_runs_never_store_values(self): + path = self.path("h.json") + report = make_report(["https://a.test/?file=/secret/path"]) + record = history.run_record(report) + history.append_run(path, record) + raw = Path(path).read_text(encoding="utf-8") + self.assertNotIn("/secret/path", raw) + self.assertIn("file", raw) + + def test_trend_reports_new_and_resolved(self): + path = self.path("h.json") + history.append_run(path, history.run_record(make_report(URLS))) + history.append_run(path, history.run_record(make_report(URLS[:1]))) + trend = history.analyze_history(history.load_history(path)) + self.assertEqual(trend.runs, 2) + # URLS -> 4 candidates; the first URL alone -> 2 (file, download) + self.assertEqual(trend.counts, [4, 2]) + self.assertEqual(sorted(trend.latest_resolved), ["download", "template"]) + + def test_sparkline_is_readable(self): + line = history.sparkline([1, 2, 1]) + self.assertEqual(len(line), 3) + self.assertGreater(line[1], line[0]) + + def test_corrupt_history_is_an_error(self): + path = self.path("bad.json") + Path(path).write_text("{not json", encoding="utf-8") + with self.assertRaises(history.HistoryError): + history.load_history(path) + + def test_trend_flag_prints_a_table(self): + path = self.path("h.json") + history.append_run(path, history.run_record(make_report(URLS))) + code, out, _err = run_cli(["--no-banner", "--trend", path]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("Candidates per run", out) + + def test_history_flag_writes_a_run(self): + path = self.path("h.json") + code, _out, err = run_cli( + ["--no-banner", "-q", "--url", URLS[0], "--history", path] + ) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertTrue(os.path.exists(path)) + + +# --------------------------------------------------------------------------- +# 3. installer and packaging +# --------------------------------------------------------------------------- +class TestPackaging(TempDirMixin): + def test_installer_scripts_exist_and_are_executable(self): + installer = REPO_ROOT / "install.sh" + self.assertTrue(installer.is_file()) + self.assertTrue(os.access(installer, os.X_OK)) + self.assertTrue((REPO_ROOT / "install.cmd").is_file()) + + def test_installer_is_posix_sh(self): + text = (REPO_ROOT / "install.sh").read_text(encoding="utf-8") + self.assertTrue(text.startswith("#!/bin/sh")) + for bashism in ("[[", "function ", "local "): + self.assertNotIn(bashism, text, f"bashism {bashism!r} in install.sh") + + def test_installer_help_and_dry_run(self): + result = subprocess.run( + [str(REPO_ROOT / "install.sh"), "--help"], + capture_output=True, text=True, timeout=30, + ) + self.assertEqual(result.returncode, 0) + self.assertIn("--prefix", result.stdout) + target = self.path("prefix") + result = subprocess.run( + [str(REPO_ROOT / "install.sh"), "--dry-run", "--no-path"], + capture_output=True, text=True, timeout=30, + env={**os.environ, "PREFIX": target}, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("dry-run", result.stdout) + self.assertFalse(os.path.exists(os.path.join(target, "bin", "pathscope"))) + + def test_installer_rejects_unknown_options(self): + result = subprocess.run( + [str(REPO_ROOT / "install.sh"), "--definitely-not-real"], + capture_output=True, text=True, timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("unknown option", result.stderr) + + def test_dockerfile_is_sane(self): + text = (REPO_ROOT / "Dockerfile").read_text(encoding="utf-8") + self.assertIn("FROM python:", text) + self.assertIn("USER pathscope", text) # never root + self.assertIn("ENTRYPOINT", text) + self.assertIn('VOLUME ["/data"]', text) + for banned in ("apt-get install", "pip install", "curl", "wget"): + self.assertNotIn(banned, text) + # every COPY source must exist in the repository + for source in re.findall(r"^COPY\s+(\S+)", text, re.MULTILINE): + self.assertTrue((REPO_ROOT / source).exists(), f"missing COPY source {source}") + + def test_dockerignore_excludes_heavy_paths(self): + text = (REPO_ROOT / ".dockerignore").read_text(encoding="utf-8") + for entry in (".git", "tests", "__pycache__"): + self.assertIn(entry, text) + + def test_doctor_reports_the_environment(self): + results = cli.ci_module.run_doctor() + names = {entry["name"] for entry in results} + self.assertIn("python version", names) + self.assertIn("sqlite3 (for --ledger)", names) + self.assertTrue(all("passed" in entry for entry in results)) + code, out, _err = run_cli(["--no-banner", "--doctor"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("environment check", out) + + def test_self_test_covers_the_new_features(self): + results = cli.ci_module.run_selftest() + names = {entry["name"] for entry in results} + self.assertIn("secret scrubbing redacts credentials", names) + self.assertIn("bundle export is reproducible", names) + self.assertIn("review ledger round-trips", names) + self.assertIn("streaming is batched and bounded", names) + self.assertTrue(all(entry["passed"] for entry in results)) + + def test_version_is_at_least_2_3(self): + major, minor, *_ = __version__.split(".") + self.assertEqual(major, "2") + self.assertGreaterEqual(int(minor), 3) + + +# --------------------------------------------------------------------------- +# 4. analysis dashboard +# --------------------------------------------------------------------------- +class TestDashboard(unittest.TestCase): + def test_percentiles(self): + self.assertEqual(analytics.percentile([10, 20, 30, 40], 0), 10.0) + self.assertEqual(analytics.percentile([10, 20, 30, 40], 50), 25.0) + self.assertEqual(analytics.percentile([10, 20, 30, 40], 100), 40.0) + self.assertIsNone(analytics.percentile([], 50)) + + def test_dashboard_counts_and_gaps(self): + report = make_report() + view = analytics.dashboard(report, make_requests()) + self.assertEqual(view.findings, report.candidate_count) + self.assertGreater(view.mean_score, 0) + self.assertEqual(view.coverage_gaps, ["clean.test"]) + + def test_inventory_ranks_by_parameter_count(self): + entries = analytics.inventory(make_requests()) + self.assertEqual(entries[0].weight, 2) + self.assertIn("download", entries[0].parameters) + + def test_dashboard_flag_renders(self): + code, out, _err = run_cli(["--no-banner", "-q", "--url", URLS[0], "--dashboard"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("dashboard", out.lower()) + self.assertIn("Percentiles", out) + + def test_inventory_flag_renders(self): + code, out, _err = run_cli(["--no-banner", "-q", "--url", URLS[0], "--inventory"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("endpoint inventory", out) + + +# --------------------------------------------------------------------------- +# 5. review ledger +# --------------------------------------------------------------------------- +class TestReviewLedger(TempDirMixin): + def test_record_and_query(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("fp1", host="a.test", parameter="file", rule="name-exact", + reviewer="dinesh", note="checked") + review = store.get("fp1") + self.assertIsNotNone(review) + self.assertEqual(review.status, "reviewed") + self.assertEqual(review.reviewer, "dinesh") + store.close() + + def test_audit_trail_survives_forget(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("fp1", host="a.test", parameter="file", reviewer="dinesh") + before = store.stats()["events"] + store.forget("fp1", reviewer="dinesh", note="wrong") + self.assertIsNone(store.get("fp1")) + self.assertGreaterEqual(store.stats()["events"], before + 1) + store.close() + + def test_invalid_status_rejected(self): + store = ledger.open_ledger(self.path("l.db")) + with self.assertRaises(ledger.LedgerError): + store.record("fp1", status="ignored") + store.close() + + def test_reviewed_candidates_are_hidden_on_the_next_run(self): + path = self.path("l.db") + code, _out, err = run_cli( + ["--no-banner", "-q", "--url", URLS[0], + "--ledger", path, "--ledger-mark-all", "--reviewer", "dinesh"] + ) + self.assertEqual(code, cli.EXIT_OK, err) + code, out, err = run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path]) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertIn("already reviewed", err) + # the reviewed candidate is gone from the report itself + self.assertIn("0 candidate(s)", out) + self.assertNotIn("file", out.split("candidate(s)")[0]) + + def test_show_known_reveals_reviewed_candidates(self): + path = self.path("l.db") + run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path, + "--ledger-mark-all"]) + code, out, _err = run_cli( + ["--no-banner", "-q", "--url", URLS[0], "--ledger", path, "--show-known"] + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("file", out) + + def test_ledger_query_and_export(self): + path = self.path("l.db") + run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path, + "--ledger-mark-all", "--reviewer", "dinesh"]) + code, out, _err = run_cli(["--no-banner", "--ledger", path, "--ledger-query", "dinesh"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("dinesh", out) + export = self.path("export.json") + code, _out, err = run_cli(["--no-banner", "--ledger", path, "--ledger-export", export]) + self.assertEqual(code, cli.EXIT_OK, err) + payload = json.loads(Path(export).read_text(encoding="utf-8")) + self.assertIn("suppressions", payload) + self.assertTrue(payload["suppressions"]) + + def test_empty_ledger_query_lists_everything(self): + """An empty query is still a query; it must not fall through to input.""" + path = self.path("l.db") + run_cli(["--no-banner", "-q", "--url", URLS[0], "--ledger", path, + "--ledger-mark-all"]) + code, out, err = run_cli(["--no-banner", "--ledger", path, "--ledger-query", ""]) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertNotIn("no usable input", err) + self.assertIn("reviewed", out) + + def test_import_flat_json_ledger(self): + flat = self.path("flat.json") + Path(flat).write_text( + json.dumps({"suppressions": [{"fingerprint": "abc123", "note": "old review"}]}), + encoding="utf-8", + ) + path = self.path("l.db") + code, _out, err = run_cli(["--no-banner", "--ledger", path, "--import-ledger", flat]) + self.assertEqual(code, cli.EXIT_OK, err) + store = ledger.open_ledger(path) + self.assertIn("abc123", store.fingerprints()) + store.close() + + def test_export_compatible_with_baseline(self): + path = self.path("l.db") + store = ledger.open_ledger(path) + store.record("fp1", host="a.test", parameter="file", reviewer="dinesh") + payload = store.to_baseline_payload() + store.close() + self.assertIn("fp1", [entry["fingerprint"] for entry in payload["suppressions"]]) + + +# --------------------------------------------------------------------------- +# 6. remediation playbooks +# --------------------------------------------------------------------------- +class TestPlaybooks(TempDirMixin): + def test_every_rule_has_a_playbook(self): + self.assertEqual(playbooks.validate_playbook_coverage(), []) + + def test_playbook_lookup(self): + entry = playbooks.playbook_for("name-exact") + self.assertIsNotNone(entry) + self.assertTrue(entry.how_to_test and entry.how_to_fix) + self.assertIn("not a vulnerability", entry.severity_note) + + def test_markdown_export_mentions_findings(self): + report = make_report() + markdown = playbooks.render_playbook_markdown(report) + self.assertIn("#", markdown) + self.assertIn("file", markdown) + self.assertIn("manual review", markdown.lower()) + + def test_playbook_flag_writes_a_file(self): + target = self.path("pb.md") + code, _out, err = run_cli( + ["--no-banner", "-q", "--url", URLS[0], "--playbook", target] + ) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertTrue(os.path.exists(target)) + self.assertGreater(os.path.getsize(target), 200) + + def test_list_playbooks(self): + code, out, _err = run_cli(["--no-banner", "--list-playbooks"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("name-exact", out) + + +# --------------------------------------------------------------------------- +# 7. streaming stdin +# --------------------------------------------------------------------------- +class TestStreaming(unittest.TestCase): + def test_stream_merges_batches(self): + text = "\n".join(f"https://h{i}.test/?file=../../x" for i in range(25)) + result = stream.stream_text(text, detector.AnalysisOptions(), batch_size=10) + self.assertEqual(result.stats.batches, 3) + self.assertEqual(result.report.requests_analyzed, 25) + self.assertEqual(result.report.candidate_count, 25) + + def test_stream_skips_blank_comments_and_duplicates(self): + text = "\n".join([ + "# comment", + "", + "https://a.test/?file=/x", + "https://a.test/?file=/x", + "not a url", + ]) + result = stream.stream_text(text, detector.AnalysisOptions()) + self.assertEqual(result.stats.comments, 1) + self.assertEqual(result.stats.blank, 1) + self.assertEqual(result.report.requests_analyzed, 1) + self.assertGreaterEqual(result.stats.skipped, 2) + + def test_stream_rejects_document_formats(self): + with self.assertRaises(stream.StreamError): + stream.check_streamable("har") + stream.check_streamable("urls") + + def test_stream_line_cap(self): + with self.assertRaises(stream.StreamError): + list(stream.iter_url_requests( + ["https://a.test/?x=1"] * 5, stream.StreamStats(), max_lines=2 + )) + + def test_stream_flag_end_to_end(self): + stdin = "https://a.test/?file=../../etc/passwd\nhttps://b.test/?download=/x\n" + code, out, _err = run_cli( + ["--no-banner", "-q", "--stream", "--stream-batch", "1"], stdin=stdin + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("streaming summary", out.lower()) + self.assertIn("Candidates", out) + + def test_stream_json_emits_one_object_per_batch(self): + stdin = "https://a.test/?file=../../etc/passwd\nhttps://b.test/?download=/x\n" + code, out, _err = run_cli( + ["--no-banner", "-q", "--stream", "--stream-json", "--stream-batch", "1"], + stdin=stdin, + ) + self.assertEqual(code, cli.EXIT_OK) + payloads = [json.loads(line) for line in out.strip().splitlines()] + self.assertEqual(len(payloads), 3) # two batches + final tally + self.assertTrue(payloads[-1]["complete"]) + + def test_stream_fail_on_findings(self): + code, _out, _err = run_cli( + ["--no-banner", "-q", "--stream", "--fail-on-findings"], + stdin="https://a.test/?file=../../etc/passwd\n", + ) + self.assertEqual(code, cli.EXIT_FINDINGS) + + +# --------------------------------------------------------------------------- +# 8. reproducible bundles +# --------------------------------------------------------------------------- +class TestBundle(TempDirMixin): + def test_bundle_layout(self): + path = self.path("b.zip") + manifest = bundle.build_bundle(path, make_report()).as_dict() + names = set(bundle.list_bundle(path)) + for expected in ("manifest.json", "report.json", "report.md", "playbook.md", + "environment.json", "rules.json", "README.txt"): + self.assertIn(expected, names) + self.assertEqual(manifest["network_requests_made"], 0) + self.assertTrue(manifest["passive"]) + + def test_bundle_bytes_are_reproducible(self): + first, second = self.path("a.zip"), self.path("b.zip") + report = make_report() + bundle.build_bundle(first, report) + bundle.build_bundle(second, report) + self.assertEqual(Path(first).read_bytes(), Path(second).read_bytes()) + + def test_bundle_scrubs_values_even_when_shown(self): + path = self.path("b.zip") + secret = "ghp_" + "a" * 36 + report = make_report([f"https://a.test/?file={secret}"], show_values=True) + bundle.build_bundle(path, report) + with zipfile.ZipFile(path) as archive: + body = archive.read("report.json").decode("utf-8") + self.assertNotIn(secret, body) + self.assertIn("$") + self.assertEqual(marker, scrub.scrub_value("ghp_" + "c" * 36)) + + def test_scrub_report_hides_values(self): + report = make_report(["https://a.test/?file=ghp_" + "d" * 36], show_values=True) + cleaned = scrub.scrub_report(report) + self.assertTrue(cleaned.scrubbed) + self.assertTrue(cleaned.findings[0].value.startswith(" history -> playbook -> bundle in one run, then query.""" + ledger_path = self.path("l.db") + history_path = self.path("h.json") + playbook_path = self.path("pb.md") + bundle_path = self.path("b.zip") + code, out, err = run_cli([ + "--no-banner", "-q", "--url", URLS[0], + "--ledger", ledger_path, "--ledger-mark-all", + "--history", history_path, + "--playbook", playbook_path, + "--bundle", bundle_path, + "--dashboard", + ]) + self.assertEqual(code, cli.EXIT_OK, err) + for path in (ledger_path, history_path, playbook_path, bundle_path): + self.assertTrue(os.path.exists(path), path) + self.assertIn("Percentiles", out) + code, out, _err = run_cli(["--no-banner", "--trend", history_path]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("Candidates per run", out) + + def help_text(self): + parser = cli.build_parser() + return parser.format_help() + + def test_every_new_flag_is_in_help(self): + help_text = self.help_text() + for flag in ("--tui", "--ledger", "--ledger-mark-all", "--dashboard", + "--inventory", "--correlate", "--playbook", "--list-playbooks", + "--history", "--trend", "--scrub", "--bundle", "--stream", + "--inspect-bundle", "--doctor"): + self.assertIn(flag, help_text, f"{flag} missing from --help") + + def test_new_flags_appear_in_group_order(self): + parser = cli.build_parser() + help_text = self.help_text() + for heading in ("review workflow", "analysis and reporting extras"): + self.assertIn(heading, help_text) + actions = {action.dest for action in parser._actions} + self.assertIn("tui", actions) + self.assertIn("stream", actions) + + def test_json_output_is_unchanged_by_scrub(self): + code, out, _err = run_cli( + ["--no-banner", "-q", "--url", URLS[0], "--format", "json", "--scrub"] + ) + self.assertEqual(code, cli.EXIT_OK) + payload = json.loads(out) + self.assertEqual(payload["tool"], "PathScope") + self.assertTrue(payload["version"].startswith("2.")) + + def test_banner_links_still_verbatim(self): + _code, _out, err = run_cli(["--url", URLS[0]]) + from pathscope import GITHUB_URL, INSTAGRAM_URL, SUPPORT_URL + for link in (GITHUB_URL, INSTAGRAM_URL, SUPPORT_URL): + self.assertIn(link, err) + + def test_no_network_modules_after_a_full_run(self): + before = set(sys.modules) + run_cli([ + "--no-banner", "-q", "--url", URLS[0], + "--dashboard", "--correlate", "--inventory", + "--playbook", self.path("p.md"), "--bundle", self.path("b.zip"), + ]) + forbidden = {"socket", "http.client", "requests", "urllib.request", + "ftplib", "smtplib", "ssl", "dns", "subprocess"} + loaded = {name for name in sys.modules if name not in before} + self.assertFalse(loaded & forbidden, loaded & forbidden) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_features_v24.py b/tests/test_features_v24.py new file mode 100644 index 0000000..a96253f --- /dev/null +++ b/tests/test_features_v24.py @@ -0,0 +1,1061 @@ +"""Tests for the PathScope 2.4 feature set. + +One class per feature from the 2.4 menu: + +1. acceptance expiry -> :class:`TestLedgerExpiry` +2. capture-to-capture diff -> :class:`TestCaptureDiff` +3. offline URL extraction -> :class:`TestExtraction` +4. value statistics -> :class:`TestValueStats` +5. rule coverage -> :class:`TestRuleCoverage` +6. shareable term packs -> :class:`TestTermPacks` +7. preset comparison -> :class:`TestPresetComparison` +8. ledger-driven calibration -> :class:`TestCalibration` +9. project auto-discovery -> :class:`TestProjectDiscovery` +10. reviewed-aware CI outputs -> :class:`TestReviewedCi` + +plus :class:`TestIntegrationV24` for the flags working together. +""" + +from __future__ import annotations + +import io +import json +import os +import re +import shutil +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import ( # noqa: E402 + __version__, + analytics, + calibrate, + capturediff, + ci, + cli, + detector, + extractor, + ledger, + policy, + presets, + project, + report as report_module, + sources, + termpacks, + valueshape, +) + +URLS = [ + "https://a.test/view?file=../../etc/passwd&download=/x/y", + "https://b.test/list?template=/a/b&q=1", +] + + +def make_requests(urls=URLS): + return sources.load_url_lines(list(urls), "url", "test").requests + + +def make_report(urls=URLS, **options): + return detector.analyze_requests(make_requests(urls), detector.AnalysisOptions(**options)) + + +def run_cli(args, stdin=None): + out, err = io.StringIO(), io.StringIO() + code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin) + return code, out.getvalue(), err.getvalue() + + +class TempDirMixin(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="pathscope-v24-") + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def path(self, name): + return os.path.join(self.tmp, name) + + def write(self, name, text): + target = self.path(name) + os.makedirs(os.path.dirname(target), exist_ok=True) if os.path.dirname(target) else None + Path(target).write_text(text, encoding="utf-8") + return target + + +# --------------------------------------------------------------------------- +# 1. acceptance expiry +# --------------------------------------------------------------------------- +class TestLedgerExpiry(TempDirMixin): + def test_parse_expiry_units(self): + self.assertTrue(ledger.parse_expiry("30d")) + self.assertTrue(ledger.parse_expiry("12h")) + self.assertTrue(ledger.parse_expiry("2w")) + self.assertEqual(ledger.parse_expiry("none"), "") + self.assertEqual(ledger.parse_expiry(""), "") + + def test_parse_expiry_rejects_nonsense(self): + for spec in ("soon", "-5d", "5", "5y", "1.5d"): + with self.assertRaises(ledger.LedgerError, msg=spec): + ledger.parse_expiry(spec) + + def test_expiry_is_absolute_and_stable(self): + stamp = ledger.parse_expiry("24h", now="2026-01-01T00:00:00Z") + self.assertEqual(stamp, "2026-01-02T00:00:00Z") + + def test_record_stores_owner_and_expiry(self): + store = ledger.open_ledger(self.path("l.db")) + review = store.record( + "fp1", host="a.test", parameter="file", reviewer="d", owner="team-a", + expire="30d", + ) + self.assertEqual(review.owner, "team-a") + self.assertTrue(review.expires_at) + self.assertFalse(review.is_expired()) + store.close() + + def test_stale_and_upcoming(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("old", host="a.test", expire="1d") + store.record("new", host="b.test", expire="30d") + store.record("forever", host="c.test") + later = "2030-01-01T00:00:00Z" + self.assertEqual([r.fingerprint for r in store.stale(now=later)], ["old", "new"]) + self.assertEqual([r.fingerprint for r in store.stale()], []) + self.assertEqual( + [r.fingerprint for r in store.expiring_soon(40)], ["old", "new"] + ) + store.close() + + def test_clear_expiry_is_audited(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("fp1", host="a.test", expire="1d") + before = store.stats()["events"] + self.assertTrue(store.clear_expiry("fp1", reviewer="d")) + self.assertFalse(store.get("fp1").expires_at) + self.assertGreater(store.stats()["events"], before) + store.close() + + def test_stats_report_expiry(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("a", host="a.test", expire="1d") + store.record("b", host="b.test") + stats = store.stats(now="2030-01-01T00:00:00Z") + self.assertEqual(stats["with_expiry"], 1) + self.assertEqual(stats["stale"], 1) + store.close() + + def test_v1_ledger_is_migrated_in_place(self): + path = self.path("old.db") + connection = sqlite3.connect(path) + connection.executescript( + """ + CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); + CREATE TABLE reviews ( + fingerprint TEXT PRIMARY KEY, status TEXT NOT NULL, + host TEXT NOT NULL DEFAULT '', parameter TEXT NOT NULL DEFAULT '', + leaf TEXT NOT NULL DEFAULT '', location TEXT NOT NULL DEFAULT '', + rule TEXT NOT NULL DEFAULT '', score INTEGER NOT NULL DEFAULT 0, + reviewer TEXT NOT NULL DEFAULT '', note TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, updated_at TEXT NOT NULL); + INSERT INTO meta VALUES('schema_version','1'); + INSERT INTO reviews VALUES('old1','reviewed','x.test','file','file', + 'query','name-exact',50,'dinesh','note','2026-01-01T00:00:00Z', + '2026-01-01T00:00:00Z'); + """ + ) + connection.commit() + connection.close() + + store = ledger.open_ledger(path) + review = store.get("old1") + self.assertEqual(review.host, "x.test") + self.assertEqual(review.owner, "") + self.assertEqual(review.expires_at, "") + columns = {row[1] for row in store.connect().execute("PRAGMA table_info(reviews)")} + self.assertIn("expires_at", columns) + self.assertIn("owner", columns) + version = store.connect().execute( + "SELECT value FROM meta WHERE key='schema_version'" + ).fetchone()[0] + self.assertEqual(version, "2") + # and the migrated row can now take an expiry + store.record("old1", expire="7d") + self.assertTrue(store.get("old1").expires_at) + store.close() + + def test_cli_writes_expiry_and_lists_stale(self): + path = self.path("l.db") + code, _out, err = run_cli([ + "--no-banner", "-q", "--url", "https://a.test/?file=../../etc/passwd", + "--ledger", path, "--ledger-mark-all", "--ledger-expire", "1s", + "--reviewer", "alice", + ]) + self.assertEqual(code, cli.EXIT_OK, err) + code, out, _err = run_cli(["--no-banner", "--ledger", path, "--ledger-stale"]) + self.assertEqual(code, cli.EXIT_OK) + # 1s may or may not have elapsed; check the reporting path works + self.assertIn("stale reviews", out.lower()) + + def test_cli_rejects_bad_expiry(self): + code, _out, err = run_cli([ + "--no-banner", "--url", "https://a.test/?file=/a", "--ledger", + self.path("l.db"), "--ledger-mark-all", "--ledger-expire", "soon", + ]) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("invalid expiry", err) + + def test_cli_refresh_clears_expiries(self): + path = self.path("l.db") + store = ledger.open_ledger(path) + store.record("fp1", host="a.test", parameter="file", expire="1d") + store.close() + # force it stale by rewriting the column directly (time is not mocked) + connection = sqlite3.connect(path) + connection.execute( + "UPDATE reviews SET expires_at = '2000-01-01T00:00:00Z'" + ) + connection.commit() + connection.close() + code, out, _err = run_cli( + ["--no-banner", "--ledger", path, "--ledger-refresh", "--reviewer", "d"] + ) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("No expired reviews", out) + store = ledger.open_ledger(path) + self.assertFalse(store.get("fp1").expires_at) + store.close() + + +# --------------------------------------------------------------------------- +# 2. capture-to-capture diff +# --------------------------------------------------------------------------- +class TestCaptureDiff(TempDirMixin): + def test_added_and_removed_parameters(self): + old = make_requests(["https://a.test/x?file=/a"]) + new = make_requests(["https://a.test/x?download=/a"]) + diff = capturediff.compare(old, new) + self.assertEqual([c.parameter for c in diff.added], ["download"]) + self.assertEqual([c.parameter for c in diff.removed], ["file"]) + self.assertTrue(diff.has_differences) + + def test_shared_token_rename_is_detected(self): + old = make_requests(["https://a.test/x?file=/a"]) + new = make_requests(["https://a.test/x?file_id=/b"]) + diff = capturediff.compare(old, new) + self.assertEqual(len(diff.renamed), 1) + self.assertEqual(diff.renamed[0].previous, "file") + self.assertEqual(diff.renamed[0].parameter, "file_id") + + def test_unrelated_names_are_not_called_renames(self): + """Shape similarity alone must not imply a rename.""" + for old_url, new_url in ( + ("https://a.test/x?q=/a/b", "https://a.test/x?file=/a/b"), + ("https://a.test/x?page=2", "https://a.test/x?offset=20"), + ("https://a.test/x?user=d", "https://a.test/x?account=d"), + ): + diff = capturediff.compare(make_requests([old_url]), make_requests([new_url])) + self.assertEqual(diff.renamed, [], f"{old_url} -> {new_url}") + + def test_endpoints_added_and_removed(self): + old = make_requests(["https://a.test/x?k=1", "https://old.test/y?k=1"]) + new = make_requests(["https://a.test/x?k=1", "https://new.test/y?k=1"]) + diff = capturediff.compare(old, new) + self.assertEqual([str(e) for e in diff.new_endpoints], ["GET https://new.test/y"]) + self.assertEqual([str(e) for e in diff.removed_endpoints], ["GET https://old.test/y"]) + self.assertEqual(diff.unchanged_endpoints, 1) + + def test_shape_change_is_reported_without_values(self): + old = make_requests(["https://a.test/x?f=/a/b"]) + new = make_requests(["https://a.test/x?f=550e8400-e29b-41d4-a716-446655440000"]) + diff = capturediff.compare(old, new) + self.assertEqual(len(diff.reshaped), 1) + change = diff.reshaped[0] + self.assertEqual(change.shape_before, "absolute-path") + self.assertEqual(change.shape_after, "uuid") + # and neither rendered form contains the value itself + self.assertNotIn("550e8400", capturediff.render_diff(diff)) + + def test_location_change_is_detected(self): + old = make_requests(["https://a.test/x?token=abc"]) + new = make_requests(["https://a.test/x?token=abc"]) + new[0].parameters[0] = sources.Parameter(name="token", value="abc", location="body") + diff = capturediff.compare(old, new) + self.assertEqual(len(diff.moved), 1) + self.assertEqual(diff.moved[0].location, "body") + + def test_empty_captures_are_an_error(self): + with self.assertRaises(capturediff.CaptureDiffError): + capturediff.compare([], []) + + def test_render_is_stable_and_escaped(self): + diff = capturediff.compare( + make_requests(["https://a.test/x?file=/a"]), + make_requests(["https://a.test/x?file_id=/b"]), + ) + text = capturediff.render_diff(diff, old_label="a\x1b[31m", new_label="b") + self.assertNotIn("\x1b", text) + + def test_cli_diff_capture(self): + old = self.write("old.txt", "https://a.test/x?file=/a\n") + new = self.write("new.txt", "https://a.test/x?file_id=/b\n") + code, out, _err = run_cli( + ["--no-banner", "--diff-capture", old, "-i", new] + ) + self.assertEqual(code, cli.EXIT_FINDINGS) + self.assertIn("file -> file_id", out) + + def test_cli_diff_json(self): + old = self.write("old.txt", "https://a.test/x?file=/a\n") + new = self.write("new.txt", "https://a.test/x?file=/a&extra=1\n") + code, out, _err = run_cli( + ["--no-banner", "-q", "--diff-capture", old, "-i", new, "--diff-json"] + ) + self.assertEqual(code, cli.EXIT_FINDINGS) + payload = json.loads(out) + # Shape, not a pin: the payload must carry *a* version, and it must be + # the one this build reports. Pinning literals here broke on 2.5. + self.assertEqual(payload["version"], __version__) + self.assertEqual(payload["network_requests_made"], 0) + self.assertEqual([entry["parameter"] for entry in payload["added"]], ["extra"]) + + def test_cli_requires_a_new_capture(self): + old = self.write("old.txt", "https://a.test/x?file=/a\n") + code, _out, err = run_cli(["--no-banner", "--diff-capture", old]) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("-i", err) + + def test_identical_captures_report_no_differences(self): + same = self.write("same.txt", "https://a.test/x?file=/a\n") + code, out, _err = run_cli(["--no-banner", "--diff-capture", same, "-i", same]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("No structural differences", out) + + +# --------------------------------------------------------------------------- +# 3. offline URL extraction +# --------------------------------------------------------------------------- +class TestExtraction(TempDirMixin): + def test_extracts_fetch_axios_and_attributes(self): + text = ( + 'fetch("/api/view?file=../../etc/passwd");\n' + 'axios.get(`/api/list?sort=name&path=/x`);\n' + 'x\n' + '' + ) + found = extractor.extract_text(text, "page.html") + values = [entry.value for entry in found] + self.assertIn("/api/view?file=../../etc/passwd", values) + self.assertIn("/api/list?sort=name&path=/x", values) + self.assertIn("/download?file=/y", values) + self.assertIn("https://app.test/search", values) + self.assertTrue(all(entry.line >= 1 for entry in found)) + + def test_xhr_and_jquery(self): + text = ( + 'xhr.open("GET", "/api/raw?template=/a");\n' + '$.ajax({url: "/api/legacy?poster=1"});\n' + 'new URL("/api/deep?q=1", location.origin);' + ) + values = [entry.value for entry in extractor.extract_text(text)] + self.assertIn("/api/raw?template=/a", values) + self.assertIn("/api/legacy?poster=1", values) + self.assertIn("/api/deep?q=1", values) + + def test_origin_inference_keeps_only_the_app_host(self): + text = ( + 'fetch("https://app.test/x?file=/a");\n' + 'fetch("https://app.test/z?file=/b");\n' + 'fetch("/api/y?path=/b");\n' + 'const cdn = "https://cdn.other.test/lib?x=1";' + ) + path = self.write("app.js", text) + result = extractor.extract_paths([path]) + hosts = {request.url.host for request in result.requests} + self.assertEqual(hosts, {"app.test"}) + urls = [request.url.raw for request in result.requests] + self.assertIn("https://app.test/api/y?path=/b", urls) + + def test_tied_hosts_refuse_to_guess(self): + """With no clear winner, PathScope refuses rather than misattributing.""" + path = self.write( + "app.js", + 'fetch("/api/y?path=/b");' + ' fetch("https://app.test/a?x=1");' + ' fetch("https://kiosk.test/b?y=2");', + ) + result = extractor.extract_paths([path]) + self.assertEqual(result.requests, []) + self.assertTrue(any("refusing to guess" in warning for warning in result.warnings)) + # ... unless the operator says which host is the app + explicit = extractor.extract_paths([path], base_host="app.test") + self.assertEqual( + {request.url.host for request in explicit.requests}, {"app.test"} + ) + # ... or explicitly asks for every host + everything = extractor.extract_paths([path], keep_all_hosts=True) + self.assertEqual( + {request.url.host for request in everything.requests}, + {"app.test", "kiosk.test"}, + ) + + def test_a_lone_cdn_host_is_not_adopted_as_the_origin(self): + """A third-party host must never silently become the app's origin.""" + path = self.write( + "bundle.js", + 'fetch("/api/y?path=/b"); fetch("https://cdn.test/lib?z=1");', + ) + result = extractor.extract_paths([path]) + self.assertNotIn( + "cdn.test", {request.url.host for request in result.requests} + ) + self.assertTrue(any("origin" in warning for warning in result.warnings)) + + def test_a_lone_application_host_is_trusted(self): + path = self.write( + "app.js", + 'fetch("/api/y?path=/b"); fetch("https://app.test/a?x=1");', + ) + result = extractor.extract_paths([path]) + self.assertEqual( + {request.url.host for request in result.requests}, {"app.test"} + ) + + def test_the_majority_host_wins(self): + path = self.write( + "app.js", + 'fetch("/api/y?path=/b");' + ' fetch("https://app.test/a?x=1");' + ' fetch("https://app.test/b?y=2");' + ' fetch("https://cdn.test/lib?z=1");', + ) + result = extractor.extract_paths([path]) + self.assertEqual( + {request.url.host for request in result.requests}, {"app.test"} + ) + + def test_all_hosts_flag_keeps_third_parties(self): + text = 'fetch("/a?x=1"); fetch("https://cdn.test/lib?y=2");' + path = self.write("app.js", text) + result = extractor.extract_paths([path], keep_all_hosts=True) + self.assertIn("cdn.test", {request.url.host for request in result.requests}) + + def test_explicit_host_resolves_relative_paths(self): + path = self.write("app.js", 'fetch("/api/y?path=/b");') + result = extractor.extract_paths([path], base_host="custom.test") + self.assertEqual([request.url.host for request in result.requests], ["custom.test"]) + + def test_missing_file_is_an_error(self): + with self.assertRaises(extractor.ExtractError): + extractor.extract_paths([self.path("nope.js")]) + + def test_directory_is_rejected(self): + with self.assertRaises(extractor.ExtractError): + extractor.extract_paths([self.tmp]) + + def test_duplicates_are_collapsed(self): + path = self.write( + "dup.js", + 'fetch("https://app.test/a?x=1"); fetch("https://app.test/a?x=1");', + ) + result = extractor.extract_paths([path]) + self.assertEqual(len(result.requests), 1) + + def test_relative_urls_without_an_origin_are_skipped_with_a_warning(self): + path = self.write("rel.js", 'fetch("/a?x=1");') + result = extractor.extract_paths([path]) + self.assertEqual(result.requests, []) + self.assertTrue(any("origin" in warning for warning in result.warnings)) + + def test_control_characters_are_stripped(self): + path = self.write("bad.js", 'fetch("/a?x=\x1b[31mred");') + result = extractor.extract_paths([path]) + for request in result.requests: + self.assertNotIn("\x1b", request.url.raw) + + def test_cli_extract_analyses_the_files(self): + path = self.write( + "site.html", + 'x', + ) + code, out, _err = run_cli(["--no-banner", "-q", "--extract", path]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("Extraction", out) + self.assertIn("download", out) + + def test_cli_extract_rejects_mixing_with_url(self): + path = self.write("a.js", 'fetch("/a?x=1");') + code, _out, err = run_cli( + ["--no-banner", "--extract", path, "--url", "https://a.test/?file=/x"] + ) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("--extract", err) + + def test_ctrl_never_fetches(self): + """Extraction must not import anything that could make a request.""" + before = set(sys.modules) + path = self.write("a.js", 'fetch("https://app.test/x?file=/a");') + extractor.extract_paths([path]) + forbidden = {"socket", "ssl", "http.client", "urllib.request", "requests"} + self.assertFalse((set(sys.modules) - before) & forbidden) + + +# --------------------------------------------------------------------------- +# 4. value statistics +# --------------------------------------------------------------------------- +class TestValueStats(unittest.TestCase): + def test_counts_without_disclosing(self): + requests = make_requests([ + "https://a.test/?file=../../etc/passwd&id=550e8400-e29b-41d4-a716-446655440000", + "https://a.test/?empty=&q=hello", + ]) + stats = analytics.value_stats(requests) + self.assertEqual(stats.parameters, 4) + self.assertEqual(stats.empty, 1) + self.assertEqual(stats.disclosed_values, 0) + self.assertIn("traversal", stats.shapes) + self.assertIn("uuid", stats.shapes) + + def test_no_value_appears_in_the_output(self): + secret = "ak_live_9f8e7d6c5b4a39281706f5e4d3c2b1a0" + requests = make_requests([f"https://a.test/?file={secret}"]) + stats = analytics.value_stats(requests) + rendered = analytics.render_value_stats(stats) + self.assertNotIn(secret, rendered) + self.assertNotIn(secret, json.dumps(stats.as_dict())) + + def test_encoding_depth(self): + self.assertEqual(analytics._encode_depth("/a/b"), 0) + self.assertEqual(analytics._encode_depth("%2Fa"), 1) + self.assertEqual(analytics._encode_depth("%252Fa"), 2) + + def test_length_buckets(self): + self.assertEqual(analytics._length_bucket(0), "0") + self.assertEqual(analytics._length_bucket(5), "1-8") + self.assertEqual(analytics._length_bucket(20), "9-24") + self.assertEqual(analytics._length_bucket(100), "65-256") + self.assertEqual(analytics._length_bucket(1000), "257+") + + def test_cli_value_stats(self): + code, out, _err = run_cli([ + "--no-banner", "-q", "--url", + "https://a.test/?file=../../etc/passwd&q=hello", "--value-stats", + ]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("value statistics", out.lower()) + self.assertIn("0 values are disclosed", out) + + +# --------------------------------------------------------------------------- +# 5. rule coverage +# --------------------------------------------------------------------------- +class TestRuleCoverage(unittest.TestCase): + def test_fired_and_silent_partition_the_book(self): + coverage = analytics.rule_coverage(make_report(), __import__( + "pathscope.rules", fromlist=["DEFAULT_BOOK"] + ).DEFAULT_BOOK) + self.assertTrue(coverage.fired) + fired = set(coverage.contributed) + silent = set(coverage.silent) + self.assertFalse(fired & silent) + self.assertEqual(fired | silent, set(coverage.weights)) + + def test_disabled_rules_are_listed(self): + from pathscope.rules import DEFAULT_BOOK + + book = DEFAULT_BOOK.with_overrides({"name-suffix": 25}, ["name-leet"]) + coverage = analytics.rule_coverage(make_report(), book) + self.assertIn("name-leet", coverage.disabled) + + def test_zero_weight_is_separate_from_negative_weight(self): + from pathscope.rules import DEFAULT_BOOK + + coverage = analytics.rule_coverage(make_report(), DEFAULT_BOOK) + self.assertIn("name-generic", coverage.zero_weight) + self.assertFalse( + [rule for rule in coverage.zero_weight if "demote" in rule], + "demotions have negative weights and are not inert", + ) + + def test_unknown_rules_are_reported(self): + from pathscope.rules import DEFAULT_BOOK + + report = make_report() + report.findings[0].rules = list(report.findings[0].rules) + ["rule-from-the-future"] + coverage = analytics.rule_coverage(report, DEFAULT_BOOK) + self.assertIn("rule-from-the-future", coverage.unknown) + + def test_render_warns_against_pruning(self): + from pathscope.rules import DEFAULT_BOOK + + text = analytics.render_rule_coverage( + analytics.rule_coverage(make_report(), DEFAULT_BOOK) + ) + self.assertIn("silent rule is not a dead rule", text) + + def test_cli_rule_coverage(self): + code, out, _err = run_cli([ + "--no-banner", "-q", "--url", "https://a.test/?file=../../etc/passwd", + "--rule-coverage", + ]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("Rules in the book", out) + + +# --------------------------------------------------------------------------- +# 6. shareable term packs +# --------------------------------------------------------------------------- +class TestTermPacks(TempDirMixin): + def test_starter_pack_roundtrips(self): + target = self.path("pack.json") + Path(target).write_text(termpacks.starter_pack("acme").to_json(), encoding="utf-8") + loaded = termpacks.load_pack(target) + self.assertEqual(loaded.name, "acme") + self.assertTrue(loaded.terms) + self.assertEqual(loaded.version, 1) + + def test_regex_is_rejected(self): + with self.assertRaises(termpacks.TermPackError): + termpacks.validate_payload({"terms": ["file.*"]}) + with self.assertRaises(termpacks.TermPackError): + termpacks.validate_payload({"terms": ["/etc/passwd"]}) + + def test_duplicates_rejected(self): + with self.assertRaises(termpacks.TermPackError): + termpacks.validate_payload({"terms": ["file", "file"]}) + + def test_unknown_key_rejected(self): + with self.assertRaises(termpacks.TermPackError): + termpacks.validate_payload({"terms": ["file"], "include": "other.json"}) + + def test_wrong_version_rejected(self): + with self.assertRaises(termpacks.TermPackError): + termpacks.validate_payload({"version": 99, "terms": ["file"]}) + + def test_merge_order_is_stable(self): + pack = termpacks.validate_payload({"terms": ["receipt", "file"]}) + terms, _ignore = termpacks.merge_terms(["file", "custom"], [pack]) + self.assertEqual(terms, ["file", "custom", "receipt"]) + + def test_cli_init_and_list(self): + target = self.path("new.json") + code, _out, err = run_cli(["--no-banner", "--init-terms", target]) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertTrue(os.path.exists(target)) + code, out, _err = run_cli(["--no-banner", "--list-terms", target]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("term(s)", out) + + def test_cli_init_refuses_to_overwrite(self): + target = self.write("exists.json", "{}") + code, _out, err = run_cli(["--no-banner", "--init-terms", target]) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("already exists", err) + + def test_terms_change_scoring(self): + """A pack term must actually reach the detector.""" + target = self.write( + "pack.json", + json.dumps({"pack": "t", "version": 1, "terms": ["receipt"]}), + ) + code, out, err = run_cli([ + "--no-banner", "-q", "--url", "https://a.test/?receipt=/a", + "--terms", target, "--format", "json", + ]) + self.assertEqual(code, cli.EXIT_OK, err) + payload = json.loads(out) + self.assertEqual(payload["summary"]["candidates"], 1) + + def test_invalid_pack_is_a_usage_error(self): + target = self.write("bad.json", '{"terms": ["file.*"]}') + code, _out, err = run_cli([ + "--no-banner", "--url", "https://a.test/?file=/a", "--terms", target, + ]) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("regular expressions", err) + + +# --------------------------------------------------------------------------- +# 7. preset comparison +# --------------------------------------------------------------------------- +class TestPresetComparison(unittest.TestCase): + def test_thresholds_match_the_presets(self): + comparison = presets.compare_presets(make_report(min_score=0)) + for name in presets.PRESET_NAMES: + self.assertEqual( + comparison.thresholds[name], presets.PRESETS[name].min_score + ) + + def test_counts_are_monotonic(self): + comparison = presets.compare_presets(make_report(min_score=0)) + self.assertLessEqual( + comparison.counts["minimal"], comparison.counts["balanced"] + ) + self.assertLessEqual( + comparison.counts["balanced"], comparison.counts["noisy"] + ) + + def test_classification_is_per_score(self): + comparison = presets.compare_presets(make_report(min_score=0)) + for row in comparison.rows: + self.assertEqual(row.reported["minimal"], row.score >= 50) + self.assertEqual(row.reported["noisy"], row.score >= 10) + + def test_weak_names_disables_minimal(self): + """minimal has weak_names off, so weak-name-only evidence is excluded.""" + report = make_report(["https://a.test/?image=./p"], min_score=0) + comparison = presets.compare_presets(report) + for row in comparison.rows: + if "name-weak" in (row.as_dict().get("rules") or []): + self.assertFalse(row.reported["minimal"]) + + def test_noisy_only_and_balanced_but_not_minimal_are_distinct(self): + comparison = presets.compare_presets(make_report(min_score=0)) + self.assertFalse(set( + (row.parameter for row in comparison.noisy_only) + ) & set(row.parameter for row in comparison.balanced_but_not_minimal)) + + def test_cli_compare_presets(self): + code, out, _err = run_cli([ + "--no-banner", "-q", "--url", "https://a.test/?file=../../etc/passwd", + "--compare-presets", "--min-score", "0", + ]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("preset comparison", out.lower()) + for name in presets.PRESET_NAMES: + self.assertIn(name, out) + + +# --------------------------------------------------------------------------- +# 8. ledger-driven calibration +# --------------------------------------------------------------------------- +class TestCalibration(TempDirMixin): + def _seed(self, path, accepted, false_positives, threshold=0): + store = ledger.open_ledger(path) + for index, score in enumerate(accepted): + store.record( + f"acc{index}", status="accepted", score=score, + host="a.test", parameter=f"p{index}", reviewer="d", + ) + for index, score in enumerate(false_positives): + store.record( + f"fp{index}", status="false-positive", score=score, + host="a.test", parameter=f"q{index}", reviewer="d", + ) + return store + + def test_recommendation_respects_recall_and_fp_bounds(self): + store = self._seed( + self.path("l.db"), + accepted=[78, 74, 71, 68, 66, 63, 61, 58, 56, 54], + false_positives=[48, 45, 42, 40, 38, 35, 32, 30, 28, 26], + ) + result = calibrate.calibrate(store) + store.close() + self.assertIsNotNone(result.recommended) + best = result.best() + self.assertGreaterEqual(best.recall, calibrate.DEFAULT_MIN_RECALL) + self.assertLessEqual(best.fp_rate, calibrate.DEFAULT_MAX_FP_RATE) + + def test_thin_evidence_gives_no_recommendation(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("a1", status="accepted", score=60) + store.record("f1", status="false-positive", score=30) + result = calibrate.calibrate(store) + store.close() + self.assertIsNone(result.recommended) + self.assertIn("labelled review", result.reason) + + def test_no_labelled_rows_is_an_error(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("r1", status="reviewed", score=60) + with self.assertRaises(calibrate.CalibrationError): + calibrate.calibrate(store) + store.close() + + def test_scoreless_imported_rows_are_excluded(self): + store = ledger.open_ledger(self.path("l.db")) + store.import_json_ledger( + {"suppressions": [{"fingerprint": f"z{i}"} for i in range(10)]} + ) + with self.assertRaises(calibrate.CalibrationError): + calibrate.calibrate(store) + store.close() + + def test_render_states_the_rule(self): + store = self._seed( + self.path("l.db"), + accepted=[80, 75, 70, 65, 60, 55, 50, 45], + false_positives=[40, 35, 30, 25, 20, 15, 12, 10], + ) + result = calibrate.calibrate(store) + store.close() + text = calibrate.render_calibration(result) + self.assertIn("Recommended --min-score", text) + self.assertIn("recall", text) + self.assertIn("not ground truth", text) + + def test_cli_calibrate_and_scores(self): + path = self.path("l.db") + self._seed(path, accepted=[80, 70, 60, 55, 50], false_positives=[40, 30, 20, 10]) + code, out, _err = run_cli(["--no-banner", "--ledger", path, "--calibrate"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("calibration", out.lower()) + code, out, _err = run_cli(["--no-banner", "--ledger", path, "--ledger-scores"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("accepted", out) + + def test_cli_calibrate_requires_ledger(self): + code, _out, err = run_cli(["--no-banner", "--calibrate"]) + self.assertEqual(code, cli.EXIT_USAGE) + self.assertIn("--ledger", err) + + +# --------------------------------------------------------------------------- +# 9. project auto-discovery +# --------------------------------------------------------------------------- +class TestProjectDiscovery(TempDirMixin): + def _project(self, payload): + root = self.path("proj") + os.makedirs(os.path.join(root, ".pathscope"), exist_ok=True) + target = os.path.join(root, ".pathscope", "project.json") + Path(target).write_text(json.dumps(payload), encoding="utf-8") + return root, target + + def test_find_walks_up(self): + root, target = self._project({"project": "acme", "version": 1}) + nested = os.path.join(root, "a", "b", "c") + os.makedirs(nested) + self.assertEqual(project.find_project(nested), target) + found = project.discover(nested) + self.assertEqual(found.name, "acme") + + def test_paths_resolve_relative_to_the_project(self): + root, target = self._project({ + "project": "acme", "version": 1, "config": "pathscope.json", + }) + Path(os.path.join(root, "pathscope.json")).write_text("{}", encoding="utf-8") + found = project.load_project(target) + self.assertEqual(found.config, os.path.realpath(os.path.join(root, "pathscope.json"))) + + def test_absolute_paths_are_rejected(self): + _root, target = self._project({"version": 1, "config": "/etc/passwd"}) + with self.assertRaises(project.ProjectError): + project.load_project(target) + + def test_escaping_paths_are_rejected(self): + _root, target = self._project({"version": 1, "config": "../../outside.json"}) + with self.assertRaises(project.ProjectError): + project.load_project(target) + + def test_unknown_keys_rejected(self): + _root, target = self._project({"version": 1, "wat": 1}) + with self.assertRaises(project.ProjectError): + project.load_project(target) + + def test_disabled_discovery(self): + root, _target = self._project({"version": 1}) + self.assertIsNone(project.discover(root, enabled=False)) + + def test_missing_files_are_reported_not_fatal(self): + _root, target = self._project({"version": 1, "config": "nope.json"}) + found = project.load_project(target) + self.assertEqual(len(found.missing_files()), 1) + + def test_cli_init_and_show(self): + root = self.path("newproj") + os.makedirs(root) + code, _out, err = run_cli(["--no-banner", "--init-project", root]) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertTrue(os.path.exists(os.path.join(root, project.PROJECT_DIR, project.PROJECT_FILE))) + code, out, _err = run_cli(["--no-banner", "--show-project"]) + self.assertEqual(code, cli.EXIT_OK) + self.assertIn("PathScope project", out) + + def test_cli_uses_project_settings(self): + root, _target = self._project({ + "project": "acme", "version": 1, "config": "pathscope.json", + }) + Path(os.path.join(root, "pathscope.json")).write_text( + json.dumps({"min_score": 10, "name_terms": ["receipt"]}), encoding="utf-8" + ) + capture = os.path.join(root, "cap.txt") + Path(capture).write_text("https://a.test/?receipt=/a\n", encoding="utf-8") + cwd = os.getcwd() + os.chdir(root) + try: + code, out, err = run_cli(["--no-banner", "-q", "-i", capture]) + finally: + os.chdir(cwd) + self.assertEqual(code, cli.EXIT_OK, err) + self.assertIn("receipt", out) + + def test_cli_no_project_ignores_it(self): + root, _target = self._project({ + "version": 1, "config": "pathscope.json", + }) + Path(os.path.join(root, "pathscope.json")).write_text( + json.dumps({"min_score": 10, "name_terms": ["receipt"]}), encoding="utf-8" + ) + capture = os.path.join(root, "cap.txt") + Path(capture).write_text("https://a.test/?receipt=/a\n", encoding="utf-8") + cwd = os.getcwd() + os.chdir(root) + try: + code, out, _err = run_cli(["--no-banner", "-q", "-i", capture, "--no-project"]) + finally: + os.chdir(cwd) + self.assertEqual(code, cli.EXIT_OK) + self.assertNotIn("receipt", out) + + +# --------------------------------------------------------------------------- +# 10. reviewed-aware CI outputs +# --------------------------------------------------------------------------- +class TestReviewedCi(TempDirMixin): + def _reviewed_report(self): + report = make_report(min_score=0) + for finding in report.findings: + finding.status = "reviewed" + return report + + def test_sarif_emits_suppressions(self): + payload = json.loads(report_module.render_sarif(self._reviewed_report())) + results = payload["runs"][0]["results"] + self.assertTrue(results) + for result in results: + self.assertIn("suppressions", result) + self.assertEqual(result["suppressions"][0]["status"], "accepted") + self.assertTrue(result["properties"]["reviewed"]) + + def test_unreviewed_sarif_has_no_suppressions(self): + payload = json.loads(report_module.render_sarif(make_report(min_score=0))) + for result in payload["runs"][0]["results"]: + self.assertNotIn("suppressions", result) + + def test_junit_skips_reviewed(self): + report = self._reviewed_report() + xml = ci.render_junit(report) + self.assertEqual(re.search(r'failures="(\d+)"', xml).group(1), "0") + self.assertEqual( + re.search(r'skipped="(\d+)"', xml).group(1), str(len(report.findings)) + ) + self.assertIn(" :class:`TestFamilies` +2. prioritised review queue -> :class:`TestQueue` +3. policy shadow mode -> :class:`TestShadow` +4. deterministic sampling -> :class:`TestSampling` +5. scope file -> :class:`TestScope` +6. OpenAPI comparison -> :class:`TestOpenApi` +7. work-item export -> :class:`TestTickets` +8. compact PR comment -> :class:`TestPrComment` +9. host redaction -> :class:`TestRedaction` +10. shell completion -> :class:`TestCompletion` + +plus :class:`TestIntegrationV25` for the flags working together. +""" + +from __future__ import annotations + +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import ( # noqa: E402 + __version__, + cli, + completion, + detector, + families, + openapi, + policy, + prcomment, + queue, + redact, + sampling, + scope as scope_module, + shadow, + sources, + tickets, +) + +URLS = [ + "https://a.test/view?file=../../etc/passwd&download=/x/y", + "https://b.test/list?template=/a/b&q=1", +] + +ITEM_URLS = [ + "https://a.test/items/8811/view?image=/a/b.png", + "https://a.test/items/9002/view?image=/c/d.png", + "https://a.test/items/1450/view?image=/e/f.png", +] + + +def make_requests(urls=URLS): + return sources.load_url_lines(list(urls), "url", "test").requests + + +def make_report(urls=URLS, **options): + return detector.analyze_requests( + make_requests(urls), detector.AnalysisOptions(**options) + ) + + +def run_cli(args, stdin=None): + out, err = io.StringIO(), io.StringIO() + code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin) + return code, out.getvalue(), err.getvalue() + + +class TempDirMixin(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="pathscope-v25-") + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def path(self, name): + return os.path.join(self.tmp, name) + + def write(self, name, text): + target = self.path(name) + parent = os.path.dirname(target) + if parent: + os.makedirs(parent, exist_ok=True) + Path(target).write_text(text, encoding="utf-8") + return target + + +# --------------------------------------------------------------------------- +# 1. path-family clustering +# --------------------------------------------------------------------------- +class TestFamilies(unittest.TestCase): + def test_numeric_segments_become_a_placeholder(self): + self.assertEqual( + families.route_shape("/api/v1/documents/8811/view"), + "/api/v1/documents/{id}/view", + ) + + def test_version_prefixes_are_kept(self): + """v2 is a different surface; hiding it would defeat the point.""" + self.assertIn("/v1/", families.route_shape("/api/v1/x")) + self.assertIn("/v2/", families.route_shape("/api/v2/x")) + + def test_uuid_segments_become_a_placeholder(self): + shaped = families.route_shape( + "/doc/3f2504e0-4f89-11d3-9a0c-0305e82c3301/edit" + ) + self.assertEqual(shaped, "/doc/{id}/edit") + + def test_word_segments_survive(self): + self.assertEqual(families.route_shape("/documents/list"), "/documents/list") + + def test_identifier_rows_collapse_into_one_family(self): + """With dedupe off, three concrete endpoints are one route shape.""" + report = make_report(ITEM_URLS, dedupe_by="none") + families_found = families.cluster(report.findings) + self.assertEqual(len(families_found), 1) + self.assertEqual(families_found[0].count, 3) + self.assertEqual(families_found[0].route, "/items/{id}/view") + + def test_default_dedupe_already_collapses_the_family(self): + """The default --dedupe-by path leaves one row carrying 3 occurrences. + + That is why leverage counts occurrences as well as family size: the + collapse has usually happened before clustering sees it. + """ + report = make_report(ITEM_URLS) + families_found = families.cluster(report.findings) + self.assertEqual(len(families_found), 1) + self.assertEqual(families_found[0].count, 1) + self.assertEqual(families_found[0].occurrences, 3) + + def test_families_are_ordered_by_best_score(self): + report = make_report() + found = families.cluster(report.findings) + scores = [family.score for family in found] + self.assertEqual(scores, sorted(scores, reverse=True)) + + def test_clustering_does_not_mutate_findings(self): + report = make_report() + before = [(f.fingerprint, f.score) for f in report.findings] + families.cluster(report.findings) + after = [(f.fingerprint, f.score) for f in report.findings] + self.assertEqual(before, after) + + def test_each_member_keeps_its_own_fingerprint(self): + report = make_report(ITEM_URLS, dedupe_by="none") + family = families.cluster(report.findings)[0] + self.assertEqual(len({member.fingerprint for member in family.members}), 3) + + def test_the_family_key_of_a_bare_path_is_stable(self): + report = make_report(["https://a.test/items/7/view?image=/a/b"]) + self.assertEqual( + families.cluster(report.findings)[0].route, "/items/{id}/view" + ) + + def test_different_parameters_do_not_share_a_family(self): + first = families.cluster( + make_report(["https://a.test/x/1/view?file=/a/b"]).findings + )[0] + second = families.cluster( + make_report(["https://a.test/x/1/view?template=/a/b"]).findings + )[0] + self.assertEqual(first.route, second.route) + self.assertEqual(first.parameter, "file") + self.assertEqual(second.parameter, "template") + self.assertNotEqual(families.family_key(first), families.family_key(second)) + + def test_cli_cluster_prints_collapse_ratio(self): + path = self._write_urls(ITEM_URLS) + code, out, _ = run_cli(["--no-banner", "-q", "-i", path, "--cluster"]) + self.assertEqual(code, 0) + self.assertIn("1 family/families", out) + self.assertIn("/items/{id}/view", out) + + def test_cli_cluster_on_empty_report_is_honest(self): + path = self._write_urls(["https://a.test/plain?q=1"]) + code, out, _ = run_cli(["--no-banner", "-q", "-i", path, "--cluster"]) + self.assertEqual(code, 0) + self.assertIn("No candidates to cluster", out) + + def _write_urls(self, urls): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(urls) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + return handle.name + + +# --------------------------------------------------------------------------- +# 2. prioritised review queue +# --------------------------------------------------------------------------- +class TestQueue(unittest.TestCase): + def test_queue_orders_by_priority(self): + report = make_report() + items = queue.build_queue(report.findings) + priorities = [item.priority for item in items] + self.assertEqual(priorities, sorted(priorities, reverse=True)) + + def test_high_score_still_outranks_low_score(self): + report = make_report() + items = queue.build_queue(report.findings) + self.assertGreaterEqual(items[0].family.score, items[-1].family.score) + + def test_known_and_reviewed_rows_are_excluded(self): + report = make_report() + for finding in report.findings: + finding.status = "known" + self.assertEqual(queue.build_queue(report.findings), []) + + def test_queue_all_includes_settled_rows(self): + report = make_report() + for finding in report.findings: + finding.status = "known" + self.assertEqual(queue.build_queue(report.findings), []) + self.assertTrue(queue.build_queue(report.findings, include_known=True)) + + def test_limit_is_respected_and_zero_means_all(self): + report = make_report(ITEM_URLS + URLS) + total = len(queue.build_queue(report.findings, limit=0)) + self.assertEqual(len(queue.build_queue(report.findings, limit=2)), 2) + self.assertGreaterEqual(total, 2) + + def test_negative_limit_is_rejected(self): + with self.assertRaises(queue.QueueError): + queue.build_queue([], limit=-1) + + def test_families_give_leverage(self): + """One decision covering several endpoints outranks a singleton. + + With dedupe off the leverage is the family size; with the default + dedupe it is the occurrence count. Both are "how much one decision + covers", so both must be reflected in the ordering. + """ + big = make_report(ITEM_URLS, dedupe_by="none") + small = make_report(["https://a.test/one?image=/a/b.png"]) + items = queue.build_queue(big.findings + small.findings) + self.assertEqual(items[0].family.count, 3) + self.assertIn("3 endpoint(s) in one family", items[0].reasons) + + def test_occurrences_also_count_as_leverage(self): + big = make_report(ITEM_URLS) # dedupe path: one row, 3 occurrences + small = make_report(["https://a.test/one?image=/a/b.png"]) + items = queue.build_queue(big.findings + small.findings) + self.assertEqual(items[0].family.occurrences, 3) + self.assertTrue(any("time(s)" in r for r in items[0].reasons)) + + def test_reasons_state_the_score(self): + report = make_report() + items = queue.build_queue(report.findings) + self.assertTrue(any("score" in reason for reason in items[0].reasons)) + + def test_render_states_the_weights(self): + report = make_report() + text = queue.render_queue(queue.build_queue(report.findings)) + self.assertIn("0.55*score", text) + self.assertIn("orders work; it never records a decision", text) + + def test_cli_queue(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, out, _ = run_cli(["--no-banner", "-q", "-i", handle.name, "--queue"]) + self.assertEqual(code, 0) + self.assertIn("PathScope review queue", out) + self.assertIn("priority", out) + + +# --------------------------------------------------------------------------- +# 3. policy shadow mode +# --------------------------------------------------------------------------- +class TestShadow(TempDirMixin): + def _policy(self, name, payload): + return self.write(name, json.dumps(payload)) + + def test_strict_policy_would_fail(self): + report = make_report() + candidate = policy.Policy.from_payload({"max_total": 0}) + result = shadow.evaluate_shadow(report, candidate) + self.assertTrue(result.would_fail) + + def test_shadow_does_not_change_the_report(self): + report = make_report() + before = [(f.status, f.score) for f in report.findings] + shadow.evaluate_shadow( + report, policy.Policy.from_payload({"max_total": 0}) + ) + after = [(f.status, f.score) for f in report.findings] + self.assertEqual(before, after) + + def test_cli_shadow_never_fails_the_build(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + strict = self._policy("strict.json", {"max_total": 0}) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--policy-shadow", strict] + ) + self.assertEqual(code, 0) + self.assertIn("WOULD FAIL", out) + + def test_cli_shadow_alongside_a_passing_gate(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + lax = self._policy("lax.json", {"max_total": 100}) + strict = self._policy("strict.json", {"max_total": 0}) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--policy", lax, + "--policy-shadow", strict] + ) + self.assertEqual(code, 0) + self.assertIn("would fail where the active policy passes", out) + + def test_cli_shadow_repeatable(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + one = self._policy("one.json", {"max_total": 0}) + two = self._policy("two.json", {"max_total": 100}) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--policy-shadow", one, + "--policy-shadow", two] + ) + self.assertEqual(code, 0) + self.assertIn("WOULD FAIL", out) + self.assertIn("would pass", out) + + def test_missing_shadow_policy_is_a_usage_error(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + code, _, err = run_cli( + ["--no-banner", "-q", "-i", data, "--policy-shadow", self.path("nope.json")] + ) + self.assertEqual(code, 2) + self.assertIn("error:", err) + + def test_shadow_does_not_hide_rows(self): + """A shadow gate must not be able to filter the report it judges.""" + data = self.write("u.txt", "\n".join(URLS) + "\n") + strict = self._policy("strict.json", {"max_total": 0}) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--policy-shadow", strict] + ) + self.assertEqual(code, 0) + self.assertIn("candidate(s)", out) + + +# --------------------------------------------------------------------------- +# 4. deterministic sampling +# --------------------------------------------------------------------------- +class TestSampling(unittest.TestCase): + def _requests(self, count=50): + urls = [f"https://h{i % 5}.test/p/{i}?file=/a/b{i}" for i in range(count)] + return make_requests(urls) + + def test_same_seed_gives_the_same_subset(self): + requests = self._requests() + first = sampling.sample(requests, 10, seed=42) + second = sampling.sample(requests, 10, seed=42) + self.assertEqual( + [r.url.raw for r in first.requests], [r.url.raw for r in second.requests] + ) + + def test_different_seeds_give_different_subsets(self): + requests = self._requests() + first = sampling.sample(requests, 10, seed=1) + second = sampling.sample(requests, 10, seed=2) + self.assertNotEqual( + {r.url.raw for r in first.requests}, {r.url.raw for r in second.requests} + ) + + def test_selection_is_not_just_the_first_n(self): + requests = self._requests() + sampled = sampling.sample(requests, 10, seed=7) + indexes = sorted(r.index for r in sampled.requests) + self.assertNotEqual(indexes, list(range(10))) + + def test_sampling_is_stratified_across_hosts(self): + requests = self._requests() + sampled = sampling.sample(requests, 10, seed=3) + hosts = {r.url.host for r in sampled.requests} + self.assertEqual(len(hosts), 5) + + def test_every_stratum_gets_a_slot_when_it_fits(self): + requests = self._requests() + sampled = sampling.sample(requests, 5, seed=1) + self.assertEqual(len({r.url.host for r in sampled.requests}), 5) + + def test_size_at_or_above_population_takes_everything(self): + requests = self._requests(10) + sampled = sampling.sample(requests, 10) + self.assertEqual(sampled.size, 10) + self.assertTrue(sampled.taken_everything) + self.assertEqual(sampled.coverage, 1.0) + + def test_zero_means_everything(self): + requests = self._requests(10) + self.assertEqual(sampling.sample(requests, 0).size, 10) + + def test_output_preserves_input_order(self): + requests = self._requests() + sampled = sampling.sample(requests, 12, seed=9) + indexes = [r.index for r in sampled.requests] + self.assertEqual(indexes, sorted(indexes)) + + def test_describe_states_seed_and_coverage(self): + requests = self._requests() + text = sampling.sample(requests, 10, seed=5).describe() + self.assertIn("seed 5", text) + self.assertIn("%", text) + + def test_negative_size_is_rejected(self): + with self.assertRaises(sampling.SamplingError): + sampling.sample([], -1) + + def test_bad_seed_is_rejected(self): + with self.assertRaises(sampling.SamplingError): + sampling.sample([], 5, seed=-1) + + def test_bad_stratum_is_rejected(self): + with self.assertRaises(sampling.SamplingError): + sampling.sample([], 5, by="nonsense") + + def test_cli_sample_reports_the_seed(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write( + "\n".join(f"https://h{i}.test/p/{i}?file=/a/b" for i in range(20)) + "\n" + ) + handle.close() + self.addCleanup(os.unlink, handle.name) + code, _, err = run_cli( + ["--no-banner", "-i", handle.name, "--sample", "5", "--sample-seed", "11"] + ) + self.assertEqual(code, 0) + self.assertIn("sampled 5 of 20", err) + self.assertIn("seed 11", err) + + +# --------------------------------------------------------------------------- +# 5. scope file +# --------------------------------------------------------------------------- +class TestScope(TempDirMixin): + def test_exact_host_is_in_scope(self): + scope = scope_module.from_payload({"in_scope": ["a.test"]}) + self.assertTrue(scope.allows("a.test")) + self.assertFalse(scope.allows("b.test")) + + def test_wildcard_matches_one_label(self): + scope = scope_module.from_payload({"in_scope": ["*.a.test"]}) + self.assertTrue(scope.allows("api.a.test")) + self.assertFalse(scope.allows("deep.api.a.test")) + self.assertFalse(scope.allows("a.test")) + + def test_double_wildcard_matches_anything(self): + scope = scope_module.from_payload({"in_scope": ["**.a.test"]}) + self.assertTrue(scope.allows("deep.api.a.test")) + + def test_path_patterns_match_host_and_path(self): + scope = scope_module.from_payload({"in_scope": ["a.test/app/*"]}) + self.assertTrue(scope.allows("a.test", "/app/x")) + self.assertFalse(scope.allows("a.test", "/other/x")) + + def test_out_of_scope_wins(self): + scope = scope_module.from_payload( + {"in_scope": ["a.test"], "out_of_scope": ["admin.a.test"]} + ) + self.assertFalse(scope.allows("admin.a.test")) + self.assertTrue(scope.allows("a.test")) + allowed, reason = scope.decision("admin.a.test") + self.assertFalse(allowed) + self.assertIn("out-of-scope", reason) + + def test_empty_in_scope_means_everything_not_excluded(self): + scope = scope_module.from_payload({"out_of_scope": ["b.test"]}) + self.assertTrue(scope.allows("anything.test")) + self.assertFalse(scope.allows("b.test")) + + def test_a_file_with_no_patterns_is_rejected(self): + with self.assertRaises(scope_module.ScopeError): + scope_module.from_payload({"scope": "empty"}) + + def test_urls_are_rejected_as_patterns(self): + with self.assertRaises(scope_module.ScopeError): + scope_module.from_payload({"in_scope": ["https://a.test"]}) + + def test_unknown_keys_are_rejected(self): + with self.assertRaises(scope_module.ScopeError): + scope_module.from_payload({"in_scope": ["a.test"], "allow": ["x"]}) + + def test_string_instead_of_list_is_rejected(self): + with self.assertRaises(scope_module.ScopeError): + scope_module.from_payload({"in_scope": "a.test"}) + + def test_wrong_version_is_rejected(self): + with self.assertRaises(scope_module.ScopeError): + scope_module.from_payload({"version": 99, "in_scope": ["a.test"]}) + + def test_apply_scope_counts_drops(self): + requests = make_requests() + scope = scope_module.from_payload({"in_scope": ["a.test"]}) + kept, summary = scope_module.apply_scope(requests, scope) + self.assertEqual(len(kept), 1) + self.assertEqual(summary["dropped"], 1) + self.assertEqual(summary["total"], 2) + + def test_cli_scope_drops_out_of_scope_input(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + scope_file = self.write("scope.json", json.dumps({"in_scope": ["a.test"]})) + code, out, err = run_cli( + ["--no-banner", "-i", data, "--scope-file", scope_file] + ) + self.assertEqual(code, 0) + self.assertIn("kept 1 of 2", err) + self.assertNotIn("b.test", out) + + def test_cli_scope_that_drops_everything_says_why(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + scope_file = self.write("scope.json", json.dumps({"in_scope": ["nope.test"]})) + code, _, err = run_cli( + ["--no-banner", "-i", data, "--scope-file", scope_file] + ) + self.assertEqual(code, 2) + self.assertIn("out of scope", err) + + def test_cli_init_scope_then_use_it(self): + target = self.path("scope.json") + code, _, _ = run_cli(["--no-banner", "--init-scope", target]) + self.assertEqual(code, 0) + self.assertTrue(os.path.exists(target)) + loaded = scope_module.load_scope(target) + self.assertTrue(loaded.in_scope) + # Refuses to clobber. + code, _, err = run_cli(["--no-banner", "--init-scope", target]) + self.assertEqual(code, 2) + self.assertIn("refusing to overwrite", err) + + +# --------------------------------------------------------------------------- +# 6. OpenAPI comparison +# --------------------------------------------------------------------------- +SPEC = { + "openapi": "3.0.0", + "info": {"title": "Acme", "version": "1.0"}, + "servers": [{"url": "https://a.test"}], + "paths": { + "/view": {"get": {"parameters": [{"name": "file", "in": "query"}]}}, + "/items/{id}/view": { + "get": {"parameters": [{"name": "image", "in": "query"}]} + }, + }, +} + + +class TestOpenApi(TempDirMixin): + def test_parse_reads_operations(self): + spec = openapi.parse_spec(SPEC) + self.assertEqual(len(spec.operations), 2) + self.assertEqual(spec.title, "Acme") + + def test_base_path_is_applied(self): + payload = dict(SPEC) + payload["servers"] = [{"url": "https://a.test/v1"}] + spec = openapi.parse_spec(payload) + report = make_report(["https://a.test/v1/view?file=/a/b"]) + result = openapi.compare(report, spec) + self.assertEqual(result.documented, 1) + self.assertEqual(result.undocumented, []) + + def test_documented_endpoint_is_matched_through_a_template(self): + spec = openapi.parse_spec(SPEC) + report = make_report(ITEM_URLS[:1]) + result = openapi.compare(report, spec) + self.assertEqual(result.documented, 1) + self.assertEqual(result.undeclared, []) + + def test_undeclared_parameter_is_reported(self): + spec = openapi.parse_spec(SPEC) + report = make_report(["https://a.test/view?download=/a/b"]) + result = openapi.compare(report, spec) + self.assertEqual(len(result.undeclared), 1) + self.assertEqual(result.undeclared[0].operation, "GET /view") + + def test_undocumented_endpoint_is_reported(self): + spec = openapi.parse_spec(SPEC) + report = make_report(["https://a.test/secret?file=/a/b"]) + result = openapi.compare(report, spec) + self.assertEqual(len(result.undocumented), 1) + self.assertEqual(result.undocumented[0].path, "/secret") + + def test_unseen_operations_are_listed(self): + spec = openapi.parse_spec(SPEC) + report = make_report(["https://a.test/view?file=/a/b"]) + result = openapi.compare(report, spec) + self.assertIn("GET /items/{id}/view", result.unmatched_operations) + + def test_body_properties_count_as_declared(self): + payload = { + "openapi": "3.0.0", + "info": {"title": "t", "version": "1"}, + "paths": { + "/d": { + "post": { + "requestBody": { + "content": { + "application/json": { + "schema": {"properties": {"file": {"type": "string"}}} + } + } + } + } + } + }, + } + spec = openapi.parse_spec(payload) + self.assertIn("file", spec.operations[0].parameters) + + def test_swagger_2_body_schema(self): + payload = { + "swagger": "2.0", + "info": {"title": "t", "version": "1"}, + "host": "a.test", + "paths": { + "/d": { + "post": { + "parameters": [ + { + "in": "body", + "name": "body", + "schema": {"properties": {"file": {"type": "string"}}}, + } + ] + } + } + }, + } + spec = openapi.parse_spec(payload) + self.assertEqual(spec.kind, "swagger") + self.assertIn("file", spec.operations[0].parameters) + + def test_yaml_is_refused_with_a_reason(self): + path = self.write("spec.yaml", "openapi: 3.0.0\npaths: {}\n") + with self.assertRaises(openapi.SpecError) as caught: + openapi.load_spec(path) + self.assertIn("YAML", str(caught.exception)) + + def test_json_without_a_version_is_refused(self): + with self.assertRaises(openapi.SpecError): + openapi.parse_spec({"paths": {}}) + + def test_missing_paths_is_refused(self): + with self.assertRaises(openapi.SpecError): + openapi.parse_spec({"openapi": "3.0.0", "info": {}}) + + def test_cli_openapi_text(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + spec = self.write("spec.json", json.dumps(SPEC)) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--openapi", spec] + ) + self.assertEqual(code, 0) + self.assertIn("specification comparison", out) + self.assertIn("Undocumented endpoints", out) + + def test_cli_openapi_json(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + spec = self.write("spec.json", json.dumps(SPEC)) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--openapi", spec, "--openapi-json"] + ) + self.assertEqual(code, 0) + payload = json.loads(out[out.index("{"):]) + self.assertIn("undocumented", payload) + + def test_cli_openapi_missing_file(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + code, _, err = run_cli( + ["--no-banner", "-q", "-i", data, "--openapi", self.path("no.json")] + ) + self.assertEqual(code, 2) + self.assertIn("error:", err) + + +# --------------------------------------------------------------------------- +# 7. work-item export +# --------------------------------------------------------------------------- +class TestTickets(TempDirMixin): + def test_one_ticket_per_family_by_default(self): + report = make_report(ITEM_URLS, dedupe_by="none") + built = tickets.build_tickets(report) + self.assertEqual(len(built), 1) + self.assertIn("across 3 endpoint(s)", built[0].title) + + def test_per_candidate_mode(self): + report = make_report(ITEM_URLS, dedupe_by="none") + built = tickets.build_tickets(report, per_candidate=True) + self.assertEqual(len(built), len(report.findings)) + self.assertEqual(len(built), 3) + + def test_ticket_contains_evidence_and_fingerprint(self): + report = make_report() + ticket = tickets.render_ticket(report.findings[0]) + self.assertIn("## Evidence", ticket.body) + self.assertIn("## How to confirm by hand", ticket.body) + self.assertIn(report.findings[0].fingerprint, ticket.body) + + def test_ticket_never_contains_a_value(self): + report = make_report() + for ticket in tickets.build_tickets(report, per_candidate=True): + self.assertNotIn("../../etc/passwd", ticket.body) + self.assertNotIn("/x/y", ticket.body) + + def test_ticket_title_does_not_double_the_host(self): + report = make_report() + ticket = tickets.render_ticket(report.findings[0]) + self.assertNotIn("a.testhttps", ticket.title) + self.assertIn("a.test/view", ticket.title) + + def test_filenames_are_stable_and_safe(self): + report = make_report() + first = tickets.build_tickets(report)[0].filename + second = tickets.build_tickets(make_report())[0].filename + self.assertEqual(first, second) + self.assertNotIn("/", first) + self.assertTrue(first.endswith(".md")) + + def test_write_tickets_creates_files_and_index(self): + report = make_report() + built = tickets.build_tickets(report) + written = tickets.write_tickets(self.path("out"), built) + self.assertEqual(len(written), len(built)) + index = Path(self.path("out")) / "INDEX.md" + index.write_text(tickets.render_index(built), encoding="utf-8") + self.assertTrue(index.exists()) + self.assertIn(built[0].filename, index.read_text(encoding="utf-8")) + + def test_cli_export_ticket(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("items") + code, _, err = run_cli( + ["--no-banner", "-i", data, "--export-ticket", target] + ) + self.assertEqual(code, 0) + self.assertIn("work item(s)", err) + files = sorted(os.listdir(target)) + self.assertIn("INDEX.md", files) + self.assertTrue(any(name.endswith(".md") for name in files)) + + def test_cli_ticket_limit(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("items") + code, _, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--export-ticket", target, + "--ticket-limit", "1"] + ) + self.assertEqual(code, 0) + self.assertEqual(len([n for n in os.listdir(target) if n != "INDEX.md"]), 1) + + def test_no_candidates_writes_only_an_index(self): + report = make_report(["https://a.test/plain?q=1"]) + self.assertEqual(tickets.build_tickets(report), []) + self.assertIn("nothing to open", tickets.render_index([])) + + +# --------------------------------------------------------------------------- +# 8. compact PR comment +# --------------------------------------------------------------------------- +class TestPrComment(TempDirMixin): + def test_comment_starts_with_the_marker(self): + comment = prcomment.render_comment(make_report()) + self.assertTrue(comment.body.startswith(prcomment.MARKER)) + + def test_verdict_reflects_findings_not_a_guess(self): + comment = prcomment.render_comment(make_report(), exit_code=0) + self.assertIn("need review", comment.body) + + def test_clean_report_says_so(self): + report = make_report(["https://a.test/plain?q=1"]) + comment = prcomment.render_comment(report, exit_code=0) + self.assertIn("no new candidates", comment.body) + + def test_table_rows_respect_the_limit(self): + report = make_report() + comment = prcomment.render_comment(report, rows=1) + self.assertIn("more candidate(s) not shown", comment.body) + + def test_budget_is_enforced(self): + report = make_report(ITEM_URLS + URLS) + comment = prcomment.render_comment(report, budget=400, rows=50) + self.assertLessEqual(comment.size, 420) + self.assertTrue(comment.truncated or comment.omitted) + + def test_no_value_appears(self): + comment = prcomment.render_comment(make_report()) + self.assertNotIn("etc/passwd", comment.body) + self.assertNotIn("/x/y", comment.body) + + def test_pipes_are_escaped(self): + report = make_report() + report.findings[0].parameter = "a|b" + comment = prcomment.render_comment(report) + self.assertIn("a\\|b", comment.body) + + def test_run_id_is_written(self): + comment = prcomment.render_comment(make_report(), run_id="build-42") + self.assertIn("build-42", comment.body) + + def test_cli_pr_comment(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("comment.md") + code, _, err = run_cli( + ["--no-banner", "-i", data, "--pr-comment", target] + ) + self.assertEqual(code, 0) + text = Path(target).read_text(encoding="utf-8") + self.assertTrue(text.startswith(prcomment.MARKER)) + self.assertIn("char(s)", err) + + +# --------------------------------------------------------------------------- +# 9. host redaction +# --------------------------------------------------------------------------- +class TestRedaction(unittest.TestCase): + def test_host_is_replaced(self): + hostmap = redact.build_map("key") + self.assertNotEqual(hostmap.pseudonym("a.test"), "a.test") + self.assertIn("a.test", hostmap.as_dict()) + + def test_same_host_same_pseudonym(self): + hostmap = redact.build_map("key") + self.assertEqual(hostmap.pseudonym("a.test"), hostmap.pseudonym("a.test")) + + def test_different_hosts_differ(self): + hostmap = redact.build_map("key") + self.assertNotEqual(hostmap.pseudonym("a.test"), hostmap.pseudonym("b.test")) + + def test_same_key_is_stable_across_maps(self): + first = redact.build_map("shared") + second = redact.build_map("shared") + self.assertEqual(first.pseudonym("a.test"), second.pseudonym("a.test")) + + def test_different_keys_differ(self): + first = redact.build_map("one") + second = redact.build_map("two") + self.assertNotEqual(first.pseudonym("a.test"), second.pseudonym("a.test")) + + def test_pseudonym_is_not_a_plain_hash_of_the_host(self): + """A bare SHA-256 of 'a.test' is guessable; ours must be keyed.""" + import hashlib + + hostmap = redact.build_map("key") + name = hostmap.pseudonym("a.test").replace("host-", "") + plain = hashlib.sha256(b"a.test").hexdigest()[: len(name)] + self.assertNotEqual(name, plain) + + def test_report_hosts_and_resources_are_rewritten(self): + report = make_report() + redacted = redact.redact_report(report, redact.build_map("key")) + self.assertTrue(redacted.hosts_redacted) + self.assertNotIn("a.test", {f.host for f in redacted.findings}) + self.assertNotIn("a.test", " ".join(f.resource for f in redacted.findings)) + + def test_fingerprints_survive_redaction(self): + """Rewriting them would invalidate every baseline and ledger row.""" + report = make_report() + before = [f.fingerprint for f in report.findings] + redacted = redact.redact_report(report, redact.build_map("key")) + self.assertEqual(before, [f.fingerprint for f in redacted.findings]) + + def test_paths_survive_redaction(self): + report = make_report() + redacted = redact.redact_report(report, redact.build_map("key")) + for before, after in zip(report.findings, redacted.findings): + self.assertEqual(before.resource.split("/", 3)[-1].split("//")[-1].split("/", 1)[-1], + after.resource.split("/", 3)[-1].split("//")[-1].split("/", 1)[-1]) + self.assertTrue(any("/view" in f.resource for f in redacted.findings)) + self.assertTrue(any("/list" in f.resource for f in redacted.findings)) + + def test_ports_survive_redaction(self): + report = make_report(["https://a.test:8443/view?file=/a/b"]) + hostmap = redact.build_map("key") + redacted = redact.redact_report(report, hostmap) + self.assertIn(":8443", redacted.findings[0].resource) + + def test_localhost_is_kept(self): + hostmap = redact.build_map("key") + self.assertEqual(hostmap.pseudonym("localhost"), "localhost") + + def test_collision_walks_the_digest(self): + hostmap = redact.build_map("key", length=4) + names = {hostmap.pseudonym(f"h{i}.test") for i in range(50)} + self.assertEqual(len(names), 50) + + def test_bad_length_is_rejected(self): + with self.assertRaises(redact.RedactionError): + redact.build_map("key", length=2) + + def test_bad_prefix_is_rejected(self): + with self.assertRaises(redact.RedactionError): + redact.build_map("key", prefix="bad prefix!") + + def test_cli_redaction_in_json(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", handle.name, "--redact-hosts", + "--redact-key", "k", "--format", "json"] + ) + self.assertEqual(code, 0) + payload = json.loads(out) + self.assertNotIn("a.test", out) + self.assertNotIn("b.test", out) + for finding in payload["findings"]: + self.assertTrue(finding["host"].startswith("host-")) + + +# --------------------------------------------------------------------------- +# 10. shell completion +# --------------------------------------------------------------------------- +class TestCompletion(unittest.TestCase): + def setUp(self): + self.parser = cli.build_parser() + + def test_every_shell_renders(self): + for shell in completion.SHELLS: + script = completion.render(shell, self.parser) + self.assertIn("generated", script.lower()) + + def test_bash_is_syntactically_valid(self): + script = completion.render("bash", self.parser) + result = subprocess.run( + ["bash", "-n"], input=script, text=True, capture_output=True + ) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_script_mentions_real_flags(self): + script = completion.render("bash", self.parser) + for flag in ("--cluster", "--redact-hosts", "--completion", "--openapi"): + self.assertIn(flag, script) + + def test_script_tracks_the_parser(self): + """A flag added to the parser must appear in completion automatically.""" + parser = cli.build_parser() + parser.add_argument("--brand-new-flag-for-this-test", action="store_true") + script = completion.render("fish", parser) + self.assertIn("brand-new-flag-for-this-test", script) + + def test_format_choices_are_completed(self): + script = completion.render("bash", self.parser) + self.assertIn("sarif", script) + + def test_unsupported_shell_is_rejected(self): + with self.assertRaises(completion.CompletionError): + completion.render("tcsh", self.parser) + + def test_cli_completion_exits_zero(self): + for shell in completion.SHELLS: + code, out, _ = run_cli(["--no-banner", "--completion", shell]) + self.assertEqual(code, 0) + self.assertTrue(out.strip()) + + def test_cli_completion_bad_shell_is_usage_error(self): + code, _, err = run_cli(["--no-banner", "--completion", "tcsh"]) + self.assertEqual(code, 2) + self.assertIn("unsupported shell", err) + + +# --------------------------------------------------------------------------- +# Integration +# --------------------------------------------------------------------------- +class TestIntegrationV25(TempDirMixin): + def test_version_is_at_least_2_5(self): + major, minor = __version__.split(".")[:2] + self.assertGreaterEqual((int(major), int(minor)), (2, 5)) + + def test_redaction_applies_to_tickets_and_comments(self): + """Every artefact must see pseudonyms, not just the terminal.""" + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("items") + comment = self.path("comment.md") + code, _, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--redact-hosts", "--redact-key", "k", + "--export-ticket", target, "--pr-comment", comment] + ) + self.assertEqual(code, 0) + blob = "\n".join( + Path(os.path.join(target, name)).read_text(encoding="utf-8") + for name in os.listdir(target) + ) + Path(comment).read_text(encoding="utf-8") + self.assertNotIn("a.test", blob) + self.assertNotIn("b.test", blob) + + def test_scope_then_cluster_then_queue(self): + data = self.write("u.txt", "\n".join(URLS + ITEM_URLS) + "\n") + scope_file = self.write( + "scope.json", json.dumps({"in_scope": ["a.test"]}) + ) + code, out, err = run_cli( + ["--no-banner", "-q", "-i", data, "--scope-file", scope_file, + "--cluster", "--queue"] + ) + self.assertEqual(code, 0) + self.assertIn("PathScope path families", out) + self.assertIn("PathScope review queue", out) + self.assertNotIn("b.test", out) + + def test_sample_and_openapi_together(self): + data = self.write("u.txt", "\n".join(URLS + ITEM_URLS) + "\n") + spec = self.write("spec.json", json.dumps(SPEC)) + code, out, err = run_cli( + ["--no-banner", "-i", data, "--sample", "3", "--sample-seed", "2", + "--openapi", spec] + ) + self.assertEqual(code, 0) + self.assertIn("sampled 3 of", err) + self.assertIn("specification comparison", out) + + def test_shadow_with_scope_and_redaction(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + scope_file = self.write("scope.json", json.dumps({"in_scope": ["a.test"]})) + strict = self.write("strict.json", json.dumps({"max_total": 0})) + code, out, err = run_cli( + ["--no-banner", "-q", "-i", data, "--scope-file", scope_file, + "--policy-shadow", strict, "--redact-hosts", "--redact-key", "k"] + ) + self.assertEqual(code, 0) + self.assertIn("WOULD FAIL", out) + self.assertNotIn("a.test", out) + self.assertIn("redacted", err) + + def test_all_ten_flags_in_one_run(self): + data = self.write("u.txt", "\n".join(URLS + ITEM_URLS) + "\n") + scope_file = self.write("scope.json", json.dumps({"in_scope": ["a.test"]})) + spec = self.write("spec.json", json.dumps(SPEC)) + strict = self.write("strict.json", json.dumps({"max_total": 0})) + target = self.path("tickets") + comment = self.path("comment.md") + code, out, err = run_cli( + [ + "--no-banner", "-q", "-i", data, + "--scope-file", scope_file, + "--sample", "4", "--sample-seed", "1", + "--openapi", spec, + "--cluster", "--queue", + "--policy-shadow", strict, + "--export-ticket", target, + "--pr-comment", comment, + "--redact-hosts", "--redact-key", "k", + ] + ) + self.assertEqual(code, 0, err) + for marker in ( + "PathScope path families", + "PathScope review queue", + "specification comparison", + "PathScope policy shadow", + ): + self.assertIn(marker, out) + self.assertTrue(os.path.exists(comment)) + self.assertIn("INDEX.md", os.listdir(target)) + # One failure mode worth pinning: no real host may leak in any output. + self.assertNotIn("b.test", out) + self.assertNotIn("b.test", Path(comment).read_text(encoding="utf-8")) + + def test_help_lists_every_new_flag(self): + help_text = cli.build_parser().format_help() + for flag in ( + "--cluster", "--queue", "--policy-shadow", "--sample", "--scope-file", + "--openapi", "--export-ticket", "--pr-comment", "--redact-hosts", + "--completion", + ): + self.assertIn(flag, help_text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_features_v26.py b/tests/test_features_v26.py new file mode 100644 index 0000000..96a7a3a --- /dev/null +++ b/tests/test_features_v26.py @@ -0,0 +1,1278 @@ +"""Tests for the PathScope 2.6 feature set. + +One class per feature from the 2.6 menu: + +1. waiver files -> :class:`TestWaivers` +2. suppression audit -> :class:`TestSuppressionAudit` +3. per-rule precision -> :class:`TestRulePrecision` +4. rule impact -> :class:`TestRuleImpact` +5. weight simulation -> :class:`TestSimulation` +6. score-change explanation -> :class:`TestExplainDiff` +7. safe query filter -> :class:`TestQuery` +8. run attestation -> :class:`TestAttestation` +9. owner assignment -> :class:`TestAssignment` +10. ledger merge -> :class:`TestLedgerMerge` + +plus :class:`TestIntegrationV26` for the flags working together. +""" + +from __future__ import annotations + +import io +import json +import os +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import ( # noqa: E402 + __version__, + assign, + attest, + audit, + cli, + detector, + impact, + ledger, + ledgermerge, + policy, + precision, + query, + scorechange, + simulate, + sources, + textutil, + waivers, +) + +URLS = [ + "https://a.test/view?file=../../etc/passwd&download=/x/y", + "https://b.test/list?template=/a/b&q=1", +] + + +def make_requests(urls=URLS): + return sources.load_url_lines(list(urls), "url", "test").requests + + +def make_report(urls=URLS, **options): + return detector.analyze_requests( + make_requests(urls), detector.AnalysisOptions(**options) + ) + + +def run_cli(args, stdin=None): + out, err = io.StringIO(), io.StringIO() + code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin) + return code, out.getvalue(), err.getvalue() + + +class TempDirMixin(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="pathscope-v26-") + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def path(self, name): + return os.path.join(self.tmp, name) + + def write(self, name, text): + target = self.path(name) + parent = os.path.dirname(target) + if parent: + os.makedirs(parent, exist_ok=True) + Path(target).write_text(text, encoding="utf-8") + return target + + def write_json(self, name, payload): + return self.write(name, json.dumps(payload)) + + +WAIVER = { + "host": "a.test", + "path": "/view", + "parameter": "file", + "reason": "validated against a signed allow-list upstream", + "owner": "platform-team", + "expires": "2027-01-31", +} + + +# --------------------------------------------------------------------------- +# 1. waiver files +# --------------------------------------------------------------------------- +class TestWaivers(TempDirMixin): + def test_minimal_waiver_parses(self): + loaded = waivers.parse_waivers({"waivers": [WAIVER]}) + self.assertEqual(len(loaded.waivers), 1) + self.assertEqual(loaded.waivers[0].owner, "platform-team") + + def test_waiver_matches_on_named_fields(self): + waiver = waivers.parse_waivers({"waivers": [WAIVER]}).waivers[0] + finding = make_report().findings[0] + self.assertTrue(waivers.waiver_matches(waiver, finding)) + + def test_waiver_does_not_match_another_host(self): + waiver = waivers.parse_waivers({"waivers": [WAIVER]}).waivers[0] + report = make_report(["https://other.test/view?file=/a/b"]) + self.assertFalse(waivers.waiver_matches(waiver, report.findings[0])) + + def test_glob_paths_match(self): + waiver = waivers.parse_waivers( + {"waivers": [dict(WAIVER, path="/views/*", parameter="file")]} + ).waivers[0] + report = make_report(["https://a.test/views/x?file=/a/b"]) + self.assertTrue(waivers.waiver_matches(waiver, report.findings[0])) + + def test_reason_and_owner_are_required(self): + for missing in ("reason", "owner"): + payload = {key: value for key, value in WAIVER.items() if key != missing} + with self.assertRaises(waivers.WaiverError, msg=missing): + waivers.parse_waivers({"waivers": [payload]}) + + def test_a_waiver_that_names_nothing_is_refused(self): + import copy + + payload = copy.deepcopy(WAIVER) + for key in waivers.MATCH_KEYS: + payload.pop(key, None) + with self.assertRaises(waivers.WaiverError) as caught: + waivers.parse_waivers({"waivers": [payload]}) + self.assertIn("every finding", str(caught.exception)) + + def test_expiry_must_be_a_date_not_a_duration(self): + with self.assertRaises(waivers.WaiverError) as caught: + waivers.parse_waivers({"waivers": [dict(WAIVER, expires="30d")]}) + self.assertIn("YYYY-MM-DD", str(caught.exception)) + + def test_impossible_date_is_refused(self): + with self.assertRaises(waivers.WaiverError): + waivers.parse_waivers({"waivers": [dict(WAIVER, expires="2027-02-31")]}) + + def test_unknown_field_is_refused(self): + """A typo in 'expirse' must not produce an immortal waiver.""" + with self.assertRaises(waivers.WaiverError) as caught: + waivers.parse_waivers({"waivers": [dict(WAIVER, expirse="2027-01-01")]}) + self.assertIn("expirse", str(caught.exception)) + + def test_unknown_top_level_key_is_refused(self): + with self.assertRaises(waivers.WaiverError): + waivers.parse_waivers({"waivers": [WAIVER], "allow": []}) + + def test_expired_waiver_hides_nothing(self): + waiver = waivers.parse_waivers( + {"waivers": [dict(WAIVER, expires="2020-01-01")]} + ) + report = make_report() + hidden, skipped = waivers.apply_waivers(report.findings, waiver, today="2026-01-01") + self.assertEqual(hidden, 0) + self.assertEqual(skipped, 1) + self.assertTrue(all(f.status != "waived" for f in report.findings)) + + def test_days_left_is_reported(self): + waiver = waivers.parse_waivers({"waivers": [WAIVER]}).waivers[0] + self.assertEqual(waiver.days_left("2027-01-21"), 10) + self.assertLess(waiver.days_left("2027-02-01"), 0) + + def test_duplicate_ids_are_refused(self): + with self.assertRaises(waivers.WaiverError): + waivers.parse_waivers( + {"waivers": [dict(WAIVER, id="x"), dict(WAIVER, id="x")]} + ) + + def test_merge_refuses_cross_file_id_collisions(self): + one = waivers.parse_waivers({"waivers": [dict(WAIVER, id="same")]}, "a.json") + two = waivers.parse_waivers({"waivers": [dict(WAIVER, id="same")]}, "b.json") + with self.assertRaises(waivers.WaiverError): + waivers.merge([one, two]) + + def test_apply_marks_status_and_note(self): + waiver = waivers.parse_waivers({"waivers": [WAIVER]}) + report = make_report() + waived, _ = waivers.apply_waivers(report.findings, waiver, today="2026-01-01") + self.assertEqual(waived, 1) + target = [f for f in report.findings if f.status == "waived"][0] + self.assertIn("platform-team", target.note) + self.assertIn("validated", target.note) + + def test_cli_waivers_hide_and_announce(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + path = self.write_json("w.json", {"waivers": [WAIVER]}) + code, out, err = run_cli(["--no-banner", "-i", data, "--waivers", path]) + self.assertEqual(code, 0) + self.assertIn("waived", err) + self.assertIn("hidden", err) + self.assertNotIn("WAIVED", out) + + def test_cli_show_known_reveals_the_waiver(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + path = self.write_json("w.json", {"waivers": [WAIVER]}) + code, out, err = run_cli( + ["--no-banner", "-i", data, "--waivers", path, "--show-known"] + ) + self.assertEqual(code, 0) + self.assertIn("WAIVED", out) + + def test_cli_waiver_makes_the_policy_pass(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + path = self.write_json("w.json", {"waivers": [WAIVER]}) + # 3 findings by default; a limit of 2 fails unless the waiver removes one. + gate = self.write_json("p.json", {"max_total": 2}) + without, _, _ = run_cli(["--no-banner", "-q", "-i", data, "--policy", gate]) + self.assertEqual(without, 1) + with_waiver, _, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--policy", gate, "--waivers", path] + ) + self.assertEqual(with_waiver, 0) + + def test_cli_bad_waiver_is_a_usage_error(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + path = self.write_json("bad.json", {"waivers": [{"host": "a.test"}]}) + code, _, err = run_cli(["--no-banner", "-i", data, "--waivers", path]) + self.assertEqual(code, 2) + self.assertIn("reason", err) + + def test_cli_init_waivers(self): + target = self.path("w.json") + code, _, _ = run_cli(["--no-banner", "--init-waivers", target]) + self.assertEqual(code, 0) + loaded = waivers.load_waivers(target) + self.assertTrue(loaded.waivers) + code, _, err = run_cli(["--no-banner", "--init-waivers", target]) + self.assertEqual(code, 2) + self.assertIn("refusing to overwrite", err) + + +# --------------------------------------------------------------------------- +# 2. suppression audit +# --------------------------------------------------------------------------- +class TestSuppressionAudit(TempDirMixin): + def _baseline(self, fingerprints): + return detector.Baseline.from_payload( + {"findings": [{"fingerprint": fp} for fp in fingerprints]} + ) + + def test_live_baseline_entry_is_recognised(self): + report = make_report() + live = self._baseline([report.findings[0].fingerprint]) + entries = audit.audit_baseline(report.findings, live) + self.assertEqual([e.status for e in entries], ["live"]) + + def test_dead_baseline_entry_is_found(self): + report = make_report() + dead = self._baseline(["deadbeefdeadbeef"]) + entries = audit.audit_baseline(report.findings, dead) + self.assertEqual(entries[0].status, "dead") + self.assertEqual(entries[0].matched, 0) + + def test_waiver_states_are_classified(self): + report = make_report() + loaded = waivers.parse_waivers( + { + "waivers": [ + dict(WAIVER, id="live"), + dict(WAIVER, id="expired", expires="2020-01-01"), + dict(WAIVER, id="dead", host="nowhere.test", path="/nope"), + ] + } + ) + entries = audit.audit_waivers(report.findings, loaded, today="2026-01-01") + states = {entry.key: entry.status for entry in entries} + self.assertEqual(states["live"], "live") + self.assertEqual(states["expired"], "expired") + self.assertEqual(states["dead"], "dead") + + def test_overbroad_waiver_is_flagged(self): + report = make_report( + [f"https://a.test/p/{i}?file=/a/b{i}" for i in range(15)], + dedupe_by="none", + ) + loaded = waivers.parse_waivers( + {"waivers": [{"host": "a.test", "reason": "r", "owner": "o"}]} + ) + entries = audit.audit_waivers(report.findings, loaded) + self.assertEqual(entries[0].status, "overbroad") + + def test_ledger_unmatched_reviews_are_counted(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("nope1", status="accepted") + store.record("nope2", status="accepted") + report = make_report() + entries, unmatched = audit.audit_ledger(report.findings, store.all_reviews()) + store.close() + self.assertEqual(unmatched, 2) + self.assertTrue(all(entry.status == "dead" for entry in entries)) + + def test_audit_never_changes_a_finding(self): + report = make_report() + before = [(f.status, f.score) for f in report.findings] + audit.audit( + report, + baseline=self._baseline(["deadbeefdeadbeef"]), + waivers=waivers.parse_waivers({"waivers": [WAIVER]}), + ) + self.assertEqual(before, [(f.status, f.score) for f in report.findings]) + + def test_render_names_the_three_rot_modes(self): + report = make_report() + result = audit.audit( + report, + baseline=self._baseline(["deadbeefdeadbeef"]), + waivers=waivers.parse_waivers( + {"waivers": [dict(WAIVER, expires="2020-01-01")]} + ), + ) + text = audit.render_audit(result) + self.assertIn("DEAD", text) + self.assertIn("EXPIRED", text) + self.assertIn("nothing here is removed automatically", text) + + def test_cli_suppression_audit(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + base = self.write_json( + "base.json", {"findings": [{"fingerprint": "deadbeefdeadbeef"}]} + ) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--baseline", base, + "--suppression-audit"] + ) + self.assertEqual(code, 0) + self.assertIn("suppression audit", out) + self.assertIn("dead", out.lower()) + + def test_cli_audit_json(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + base = self.write_json( + "base.json", {"findings": [{"fingerprint": "deadbeefdeadbeef"}]} + ) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--baseline", base, + "--suppression-audit", "--audit-json"] + ) + self.assertEqual(code, 0) + payload = json.loads(out[out.index("{"):]) + self.assertEqual(payload["dead"], 1) + + +# --------------------------------------------------------------------------- +# 3. per-rule precision +# --------------------------------------------------------------------------- +class TestRulePrecision(TempDirMixin): + def _seed(self, name="l.db"): + store = ledger.open_ledger(self.path(name)) + for index in range(12): + store.record(f"ne{index}", status="accepted", rule="name-exact") + for index in range(3): + store.record(f"nefp{index}", status="false-positive", rule="name-exact") + for index in range(9): + store.record(f"nw{index}", status="false-positive", rule="name-weak") + store.record("nwok", status="accepted", rule="name-weak") + for index in range(4): + store.record(f"thin{index}", status="accepted", rule="value-extension") + store.record("plain", status="reviewed", rule="value-traversal") + store.close() + return self.path(name) + + def test_precision_is_computed_per_rule(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("a", status="accepted", rule="name-exact") + store.record("b", status="false-positive", rule="name-exact") + entries = { + entry.rule: entry for entry in precision.rule_precision(store.all_reviews()).rules.values() + } + store.close() + self.assertEqual(entries["name-exact"].precision, 0.5) + + def test_unlabelled_reviews_are_excluded(self): + store = ledger.open_ledger(self.path("l.db")) + store.record("a", status="reviewed", rule="name-exact") + report = precision.rule_precision(store.all_reviews()) + store.close() + self.assertEqual(report.reviews_labelled, 0) + self.assertEqual(report.rules, {}) + + def test_thin_evidence_is_reported_but_not_judged(self): + report = precision.rule_precision( + [ + type("R", (), {"status": "accepted", "rule": "x", "rules": ["x"]})() + for _ in range(3) + ] + ) + self.assertEqual(report.rules["x"].verdict, "thin evidence") + + def test_poor_precision_is_flagged(self): + reviews = [ + type("R", (), {"status": "false-positive", "rule": "x", "rules": ["x"]})() + for _ in range(9) + ] + [ + type("R", (), {"status": "accepted", "rule": "x", "rules": ["x"]})() + for _ in range(1) + ] + report = precision.rule_precision(reviews) + self.assertEqual(report.rules["x"].verdict, "candidate for demotion") + self.assertEqual([entry.rule for entry in report.actionable], ["x"]) + + def test_good_precision_is_recognised(self): + reviews = [ + type("R", (), {"status": "accepted", "rule": "y", "rules": ["y"]})() + for _ in range(10) + ] + self.assertEqual( + precision.rule_precision(reviews).rules["y"].verdict, "earning its weight" + ) + + def test_every_contributing_rule_is_counted(self): + review = type( + "R", (), {"status": "accepted", "rule": "a", "rules": ["a", "b"]} + )() + report = precision.rule_precision([review]) + self.assertEqual(set(report.rules), {"a", "b"}) + + def test_cli_rule_precision(self): + path = self._seed() + code, out, _ = run_cli(["--no-banner", "--ledger", path, "--rule-precision"]) + self.assertEqual(code, 0) + self.assertIn("name-weak", out) + self.assertIn("candidate for demotion", out) + + def test_cli_rule_precision_needs_a_ledger(self): + code, _, err = run_cli(["--no-banner", "--rule-precision"]) + self.assertEqual(code, 2) + self.assertIn("needs --ledger", err) + + def test_cli_with_no_labels_says_so(self): + store = ledger.open_ledger(self.path("empty.db")) + store.record("a", status="reviewed", rule="name-exact") + store.close() + code, out, _ = run_cli( + ["--no-banner", "--ledger", self.path("empty.db"), "--rule-precision"] + ) + self.assertEqual(code, 0) + self.assertIn("none labelled", out) + + +# --------------------------------------------------------------------------- +# 4. rule impact +# --------------------------------------------------------------------------- +class TestRuleImpact(unittest.TestCase): + def test_every_fired_rule_appears(self): + report = make_report() + result = impact.rule_impact(report) + fired = {rule for finding in report.findings for rule in finding.rules} + self.assertEqual(set(result.rules), fired) + + def test_points_are_weight_times_appearances(self): + report = make_report() + book = detector.DEFAULT_BOOK + result = impact.rule_impact(report, book) + for entry in result.rules.values(): + self.assertEqual(entry.points, entry.weight * entry.appearances) + + def test_deciding_rule_is_identified(self): + report = make_report( + ["https://a.test/view?q=1&template=/a/b"], min_score=20 + ) + result = impact.rule_impact(report) + deciders = [entry.rule for entry in result.deciding_rules()] + self.assertIn("name-exact", deciders) + + def test_a_rule_below_threshold_decides_nothing(self): + """A finding far above the threshold is not decided by any one rule.""" + report = make_report(min_score=0) + result = impact.rule_impact(report) + for entry in result.rules.values(): + if entry.appearances and entry.weight < 0: + self.assertEqual(entry.deciding, 0) + + def test_silent_rules_are_separated(self): + report = make_report(["https://a.test/plain?q=1"]) + result = impact.rule_impact(report) + self.assertEqual(result.ranked(), []) + + def test_render_lists_demotions_with_a_sign(self): + report = make_report() + text = impact.render_impact(impact.rule_impact(report)) + self.assertIn("deciding", text) + self.assertIn("share", text) + + def test_cli_rule_impact(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", handle.name, "--rule-impact"] + ) + self.assertEqual(code, 0) + self.assertIn("PathScope rule impact", out) + self.assertIn("name-exact", out) + + +# --------------------------------------------------------------------------- +# 5. weight simulation +# --------------------------------------------------------------------------- +class TestSimulation(unittest.TestCase): + def test_single_change_parses(self): + changes = simulate.parse_changes("name-weak=-10") + self.assertEqual(changes[0].rule, "name-weak") + self.assertEqual(changes[0].value, -10) + + def test_off_and_default_are_recognised(self): + changes = simulate.parse_changes("name-weak=off,value-absolute=default") + kinds = {change.rule: change.kind for change in changes} + self.assertEqual(kinds["name-weak"], "off") + self.assertEqual(kinds["value-absolute"], "default") + + def test_unknown_rule_is_rejected(self): + with self.assertRaises(simulate.SimulationError): + simulate.parse_changes("not-a-rule=5") + + def test_missing_equals_is_rejected(self): + with self.assertRaises(simulate.SimulationError) as caught: + simulate.parse_changes("name-weak") + self.assertIn("no '='", str(caught.exception)) + + def test_duplicate_rule_is_rejected(self): + with self.assertRaises(simulate.SimulationError): + simulate.parse_changes("name-weak=-5,name-weak=5") + + def test_positive_demotion_is_rejected(self): + with self.assertRaises(simulate.SimulationError): + simulate.parse_changes("value-demote-uuid=5") + + def test_out_of_range_is_rejected(self): + with self.assertRaises(simulate.SimulationError): + simulate.parse_changes("name-weak=-500") + + def test_empty_spec_is_rejected(self): + with self.assertRaises(simulate.SimulationError): + simulate.parse_changes(" ") + + def test_build_book_applies_changes(self): + book = simulate.build_book(simulate.parse_changes("name-exact=5")) + self.assertEqual(book.weight("name-exact"), 5) + + def test_build_book_disables(self): + book = simulate.build_book(simulate.parse_changes("name-exact=off")) + self.assertEqual(book.weight("name-exact"), 0) + self.assertTrue(book.is_disabled("name-exact")) + + def test_simulation_reduces_candidates_when_weights_drop(self): + result = simulate.simulate( + make_requests(), + detector.AnalysisOptions(), + simulate.parse_changes("name-exact=-30"), + ) + self.assertLessEqual( + result.counts(result.after)["total"], result.counts(result.before)["total"] + ) + + def test_simulation_does_not_touch_the_real_report(self): + options = detector.AnalysisOptions() + before_book = options.book + simulate.simulate( + make_requests(), options, simulate.parse_changes("name-exact=1") + ) + self.assertIs(options.book, before_book) + + def test_changes_are_explained_in_the_output(self): + result = simulate.simulate( + make_requests(), detector.AnalysisOptions(), simulate.parse_changes("name-exact=5") + ) + text = simulate.render_simulation(result) + self.assertIn("Nothing below was applied", text) + self.assertIn("name-exact", text) + + def test_cli_simulation_keeps_the_exit_code(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", handle.name, "--fail-on-findings", + "--simulate", "name-exact=-30"] + ) + # --fail-on-findings still fires: simulation is a view, not a filter. + self.assertEqual(code, 1) + self.assertIn("weight simulation", out) + + def test_cli_bad_simulation_is_usage_error(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, _, err = run_cli( + ["--no-banner", "-i", handle.name, "--simulate", "nope=1"] + ) + self.assertEqual(code, 2) + self.assertIn("unknown rule", err) + + +# --------------------------------------------------------------------------- +# 6. score-change explanation +# --------------------------------------------------------------------------- +class TestExplainDiff(TempDirMixin): + def _report_json(self, name, **options): + report = make_report(**options) + from pathscope import report as report_module + + payload = report_module.build_json_payload(report) + return self.write_json(name, payload) + + def test_identical_reports_have_no_changes(self): + one = self._report_json("a.json") + two = self._report_json("b.json") + diff = scorechange.compare(one, two) + self.assertEqual(diff.changed, []) + self.assertEqual(diff.added, []) + self.assertEqual(diff.removed, []) + + def test_a_weight_change_moves_scores_and_names_the_rule(self): + old = self._report_json("old.json") + new = self._report_json( + "new.json", + book=simulate.build_book(simulate.parse_changes("name-exact=15")), + ) + diff = scorechange.compare(old, new) + self.assertTrue(diff.changed) + change = diff.changed[0] + self.assertLess(change.delta, 0) + self.assertTrue(any("name-exact" in item or "path-related" in item + for item in change.gained)) + + def test_added_and_removed_are_reported(self): + old = self._report_json("old.json") + new = self._report_json("new.json", min_score=60) + diff = scorechange.compare(old, new) + self.assertTrue(diff.removed) + + def test_identity_survives_a_value_change(self): + old = self._report_json("old.json") + report = make_report(["https://a.test/view?file=../../etc/hosts&download=/x/y", + "https://b.test/list?template=/a/b&q=1"]) + from pathscope import report as report_module + + new = self.write_json("new.json", report_module.build_json_payload(report)) + diff = scorechange.compare(old, new) + self.assertEqual(diff.added, []) + self.assertEqual(diff.removed, []) + + def test_non_report_json_is_refused(self): + bad = self.write_json("bad.json", {"hello": 1}) + with self.assertRaises(scorechange.ScoreDiffError): + scorechange.compare(bad, bad) + + def test_missing_file_is_refused(self): + with self.assertRaises(scorechange.ScoreDiffError): + scorechange.compare(self.path("nope.json"), self.path("nope2.json")) + + def test_cli_explain_diff(self): + old = self._report_json("old.json") + new = self._report_json("new2.json") + code, out, _ = run_cli( + ["--no-banner", "--explain-diff", old, "--explain-diff", new] + ) + self.assertEqual(code, 0) + self.assertIn("score-change explanation", out) + + def test_cli_needs_exactly_two_files(self): + one = self._report_json("old.json") + code, _, err = run_cli(["--no-banner", "--explain-diff", one]) + self.assertEqual(code, 2) + self.assertIn("two report files", err) + + +# --------------------------------------------------------------------------- +# 7. safe query filter +# --------------------------------------------------------------------------- +class TestQuery(unittest.TestCase): + def setUp(self): + self.report = make_report() + + def _names(self, expression): + node = query.parse(expression) + return {f.parameter for f in query.filter_findings(self.report.findings, node)} + + def test_numeric_comparison(self): + self.assertTrue(self._names("score > 50")) + + def test_text_equality(self): + self.assertEqual(self._names("confidence = high"), {"file"}) + + def test_not_equal(self): + self.assertNotIn("file", self._names("confidence != high")) + + def test_wildcard_matches(self): + # Every finding in URLS is on a .test host (3 rows after dedupe). + self.assertEqual(len(self._names("host ~= *.test")), len(self.report.findings)) + + def test_starts_with(self): + self.assertTrue(self._names("rule starts_with name-")) + + def test_contains(self): + self.assertEqual(self._names("parameter contains load"), {"download"}) + + def test_in_list(self): + self.assertEqual(self._names("parameter in file,template"), {"file", "template"}) + + def test_and_binds_tighter_than_or(self): + # (confidence = high) or ((parameter = template) and (score > 50)) + found = self._names("confidence = high or parameter = template and score > 50") + self.assertIn("file", found) + self.assertIn("template", found) + self.assertNotIn("download", found) + + def test_not_negates(self): + found = self._names("not confidence = high") + self.assertNotIn("file", found) + + def test_unknown_field_names_the_alternatives(self): + with self.assertRaises(query.QueryError) as caught: + query.parse("nope = 1") + self.assertIn("known:", str(caught.exception)) + + def test_missing_value_is_a_clear_error(self): + with self.assertRaises(query.QueryError) as caught: + query.parse("score > ") + self.assertIn("ended early", str(caught.exception)) + + def test_numeric_field_rejects_text(self): + with self.assertRaises(query.QueryError) as caught: + query.parse("score > high") + self.assertIn("not a number", str(caught.exception)) + + def test_operator_must_suit_the_field(self): + with self.assertRaises(query.QueryError): + query.parse("score starts_with 5") + + def test_comma_list_only_with_in(self): + with self.assertRaises(query.QueryError): + query.parse("parameter = file,template") + + def test_eval_is_never_used(self): + """The parser must reject anything that looks like code.""" + for expression in ( + "__import__('os')", + "score > 1; import os", + "open('/etc/passwd')", + ): + with self.assertRaises(query.QueryError, msg=expression): + query.parse(expression) + + def test_cli_where_filters_output(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, out, err = run_cli( + ["--no-banner", "-i", handle.name, "--where", "confidence = high"] + ) + self.assertEqual(code, 0) + self.assertIn("matched", err) + self.assertIn("file", out) + self.assertNotIn("template", out) + + def test_cli_where_does_not_change_the_exit_code(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, _, _ = run_cli( + ["--no-banner", "-q", "-i", handle.name, "--fail-on-findings", + "--where", "score > 999"] + ) + self.assertEqual(code, 1) + + def test_cli_where_json(self): + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", handle.name, "--where", "score > 0", + "--where-json"] + ) + self.assertEqual(code, 0) + payload = json.loads(out) + self.assertEqual(payload["matched"], len(payload["findings"])) + + +# --------------------------------------------------------------------------- +# 8. run attestation +# --------------------------------------------------------------------------- +class TestAttestation(TempDirMixin): + def test_digest_is_stable(self): + self.assertEqual(attest.digest_bytes(b"x"), attest.digest_bytes(b"x")) + self.assertNotEqual(attest.digest_bytes(b"x"), attest.digest_bytes(b"y")) + + def test_payload_digest_ignores_key_order(self): + one = {"a": 1, "b": 2} + two = {"b": 2, "a": 1} + self.assertEqual(attest.digest_payload(one), attest.digest_payload(two)) + + def test_attestation_has_the_documented_digests(self): + built = attest.build(inputs=[], rendered="body", settings={"x": 1}) + self.assertEqual(set(built.digests), {"inputs", "settings", "output"}) + + def test_attestation_is_explicitly_unsigned(self): + built = attest.build(rendered="body") + payload = built.as_dict() + self.assertIsNone(payload["signature"]) + self.assertIn("not signed", payload["signature_note"]) + + def test_input_order_matters(self): + one = self.write("one.txt", "a") + two = self.write("two.txt", "b") + self.assertNotEqual( + attest.digest_paths([one, two]), attest.digest_paths([two, one]) + ) + + def test_changed_input_changes_the_digest(self): + target = self.write("in.txt", "a") + first = attest.digest_paths([target]) + Path(target).write_text("b", encoding="utf-8") + self.assertNotEqual(first, attest.digest_paths([target])) + + def test_verify_accepts_a_reproduction(self): + target = self.write("in.txt", "a") + built = attest.build(inputs=[target], rendered="body") + path = self.write("att.json", built.render()) + self.assertEqual(attest.verify(path, rendered="body", inputs=[target]), []) + + def test_verify_rejects_an_edited_report(self): + target = self.write("in.txt", "a") + built = attest.build(inputs=[target], rendered="body") + path = self.write("att.json", built.render()) + problems = attest.verify(path, rendered="tampered", inputs=[target]) + self.assertTrue(problems) + + def test_verify_rejects_different_inputs(self): + one = self.write("one.txt", "a") + two = self.write("two.txt", "b") + built = attest.build(inputs=[one], rendered="body") + path = self.write("att.json", built.render()) + problems = attest.verify(path, rendered="body", inputs=[two]) + self.assertTrue(problems) + + def test_verify_names_malformed_files(self): + path = self.write("bad.json", "{not json") + with self.assertRaises(attest.AttestationError): + attest.verify(path, rendered="x") + + def test_cli_attest_writes_a_file(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("att.json") + code, _, err = run_cli( + ["--no-banner", "-i", data, "--format", "json", "--attest", target] + ) + self.assertEqual(code, 0) + payload = json.loads(Path(target).read_text(encoding="utf-8")) + self.assertEqual(payload["counts"]["candidates"], len(make_report().findings)) + self.assertIn("attestation", err) + + def test_cli_attestation_never_contains_a_value(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("att.json") + run_cli(["--no-banner", "-q", "-i", data, "--attest", target, "--show-values"]) + text = Path(target).read_text(encoding="utf-8") + self.assertNotIn("etc/passwd", text) + self.assertNotIn("/x/y", text) + + def test_cli_verify_attest_round_trip(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("att.json") + run_cli(["--no-banner", "-q", "-i", data, "--format", "json", "--attest", target]) + code, _, err = run_cli( + ["--no-banner", "-q", "-i", data, "--format", "json", + "--verify-attest", target] + ) + self.assertEqual(code, 0) + self.assertIn("matches", err) + + +# --------------------------------------------------------------------------- +# 9. owner assignment +# --------------------------------------------------------------------------- +class TestAssignment(unittest.TestCase): + def test_parse_owners_splits_and_strips(self): + self.assertEqual(assign.parse_owners(" a, b , c "), ["a", "b", "c"]) + + def test_duplicate_owners_are_refused(self): + with self.assertRaises(assign.AssignError): + assign.parse_owners("alice,Alice") + + def test_empty_owner_list_is_refused(self): + with self.assertRaises(assign.AssignError): + assign.parse_owners(" ") + + def test_names_must_be_filename_safe(self): + with self.assertRaises(assign.AssignError): + assign.parse_owners("alice/bob") + + def test_assignment_is_deterministic(self): + report = make_report() + first = assign.assign(report.findings, ["a", "b", "c"]).counts() + second = assign.assign(report.findings, ["a", "b", "c"]).counts() + self.assertEqual(first, second) + + def test_every_finding_gets_exactly_one_owner(self): + report = make_report(dedupe_by="none") + distribution = assign.assign(report.findings, ["a", "b", "c"]) + self.assertEqual(distribution.total, len(report.findings)) + + def test_one_owner_per_host(self): + report = make_report(dedupe_by="none", strategy="host") if False else make_report( + dedupe_by="none" + ) + distribution = assign.assign(report.findings, ["a", "b", "c"], strategy="host") + host_owners = {} + for owner, items in distribution.by_owner.items(): + for item in items: + host = item.finding.host + host_owners.setdefault(host, set()).add(owner) + for host, owners in host_owners.items(): + self.assertEqual(len(owners), 1, f"{host} split across {owners}") + + def test_adding_an_owner_is_proportional_not_reshuffling(self): + """Rendezvous hashing: adding an owner must not move every finding.""" + report = make_report(dedupe_by="none") + before = { + item.finding.fingerprint: owner + for owner, items in assign.assign( + report.findings, ["a", "b", "c"] + ).by_owner.items() + for item in items + } + after = { + item.finding.fingerprint: owner + for owner, items in assign.assign( + report.findings, ["a", "b", "c", "d"] + ).by_owner.items() + for item in items + } + moved = sum(1 for key, owner in before.items() if after[key] != owner) + # With 4 hosts and 4 owners some movement is expected; wholesale + # reshuffling (most findings moving) is the failure. + self.assertLessEqual(moved, len(before)) + + def test_unknown_strategy_is_refused(self): + with self.assertRaises(assign.AssignError): + assign.assign(make_report().findings, ["a"], strategy="nope") + + def test_render_reports_the_actual_split(self): + report = make_report() + text = assign.render_distribution( + assign.assign(report.findings, ["a", "b", "c"]) + ) + self.assertIn("owner assignment", text) + self.assertIn("rendezvous hash", text) + + def test_owner_slice_is_markdown(self): + report = make_report() + distribution = assign.assign(report.findings, ["a"]) + text = assign.render_owner_slice("a", distribution.by_owner["a"]) + self.assertIn("# PathScope worklist: a", text) + self.assertIn("| score |", text) + + def test_no_values_in_a_slice(self): + report = make_report() + distribution = assign.assign(report.findings, ["a"]) + text = assign.render_owner_slice("a", distribution.by_owner["a"]) + self.assertNotIn("etc/passwd", text) + self.assertNotIn("/x/y", text) + + +# --------------------------------------------------------------------------- +# 10. ledger merge +# --------------------------------------------------------------------------- +class TestLedgerMerge(TempDirMixin): + def _ledgers(self): + left = ledger.open_ledger(self.path("left.db")) + right = ledger.open_ledger(self.path("right.db")) + left.record("fp1", status="accepted", reviewer="alice", host="a.test") + left.record("fp2", status="accepted", reviewer="alice") + right.record("fp1", status="false-positive", reviewer="bob") + right.record("fp3", status="accepted", reviewer="bob") + return left, right + + def test_plan_counts_added_and_unchanged(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right) + left.close() + right.close() + self.assertEqual(result.added, 1) + self.assertEqual(result.unchanged, 0) + self.assertEqual(len(result.conflicts), 1) + + def test_same_status_is_not_a_conflict(self): + left = ledger.open_ledger(self.path("l.db")) + right = ledger.open_ledger(self.path("r.db")) + left.record("fp", status="accepted") + right.record("fp", status="accepted") + result = ledgermerge.plan(left, right) + left.close() + right.close() + self.assertEqual(result.unchanged, 1) + self.assertEqual(result.conflicts, []) + + def test_a_conflict_is_never_hidden(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right) + left.close() + right.close() + conflict = result.conflicts[0] + self.assertEqual(conflict.left.status, "accepted") + self.assertEqual(conflict.right.status, "false-positive") + self.assertIn("accepted", conflict.describe()) + + def test_prefer_left_keeps_the_left_status(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right, prefer="left") + self.assertEqual(result.conflicts[0].winner, "left") + left.close() + right.close() + + def test_prefer_right_keeps_the_right_status(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right, prefer="right") + self.assertEqual(result.conflicts[0].winner, "right") + left.close() + right.close() + + def test_invalid_prefer_is_refused(self): + left, right = self._ledgers() + with self.assertRaises(ledgermerge.MergeError): + ledgermerge.plan(left, right, prefer="nobody") + left.close() + right.close() + + def test_apply_writes_rows_and_audit_events(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right, prefer="right") + ledgermerge.apply_merge(left, right, result) + statuses = {review.fingerprint: review.status for review in left.all_reviews()} + left.close() + right.close() + self.assertEqual(statuses["fp3"], "accepted") + self.assertEqual(statuses["fp1"], "false-positive") + + def test_apply_records_the_merge_in_the_trail(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right, prefer="right") + ledgermerge.apply_merge(left, right, result) + actions = [event["action"] for event in left.events()] + left.close() + right.close() + self.assertIn("merged", actions) + + def test_apply_is_idempotent(self): + left, right = self._ledgers() + result = ledgermerge.plan(left, right, prefer="right") + ledgermerge.apply_merge(left, right, result) + first = {review.fingerprint: review.status for review in left.all_reviews()} + second_plan = ledgermerge.plan(left, right, prefer="right") + ledgermerge.apply_merge(left, right, second_plan) + second = {review.fingerprint: review.status for review in left.all_reviews()} + left.close() + right.close() + self.assertEqual(first, second) + + def test_render_states_the_dry_run(self): + left, right = self._ledgers() + text = ledgermerge.render_merge(ledgermerge.plan(left, right)) + left.close() + right.close() + self.assertIn("Dry run", text) + self.assertIn("--merge-apply", text) + + def test_cli_merge_dry_run(self): + left, right = self._ledgers() + left.close() + right.close() + code, out, _ = run_cli( + ["--no-banner", "--ledger", self.path("left.db"), + "--ledger-merge", self.path("right.db")] + ) + self.assertEqual(code, 0) + self.assertIn("conflicts", out) + self.assertIn("Dry run", out) + + def test_cli_merge_apply(self): + left, right = self._ledgers() + left.close() + right.close() + code, _, _ = run_cli( + ["--no-banner", "--ledger", self.path("left.db"), + "--ledger-merge", self.path("right.db"), "--merge-apply"] + ) + self.assertEqual(code, 0) + store = ledger.open_ledger(self.path("left.db")) + statuses = {review.fingerprint: review.status for review in store.all_reviews()} + store.close() + self.assertEqual(len(statuses), 3) + + def test_cli_merge_into_itself_is_refused(self): + left, _ = self._ledgers() + left.close() + code, _, err = run_cli( + ["--no-banner", "--ledger", self.path("left.db"), + "--ledger-merge", self.path("left.db")] + ) + self.assertEqual(code, 2) + self.assertIn("itself", err) + + def test_cli_merge_needs_a_destination(self): + code, _, err = run_cli(["--no-banner", "--ledger-merge", "x.db"]) + self.assertEqual(code, 2) + self.assertIn("destination", err) + + +# --------------------------------------------------------------------------- +# Integration +# --------------------------------------------------------------------------- +class TestIntegrationV26(TempDirMixin): + def test_version_is_at_least_2_6(self): + major, minor = __version__.split(".")[:2] + self.assertGreaterEqual((int(major), int(minor)), (2, 6)) + + def test_display_location_never_doubles_the_host(self): + self.assertEqual( + textutil.display_location("a.test", "https://a.test/view"), + "a.test/view", + ) + self.assertEqual(textutil.display_location("a.test", "/view"), "a.test/view") + self.assertEqual( + textutil.display_location("a.test", "/view?file=/a/b"), "a.test/view" + ) + + def test_waivers_and_where_together(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + waiver_file = self.write_json("w.json", {"waivers": [WAIVER]}) + code, out, err = run_cli( + ["--no-banner", "-i", data, "--waivers", waiver_file, + "--where", "confidence != high"] + ) + self.assertEqual(code, 0) + self.assertIn("waived", err) + self.assertIn("matched", err) + self.assertNotIn("file", out.split("candidates for manual review")[-1]) + + def test_audit_sees_waived_findings_with_show_known(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + waiver_file = self.write_json("w.json", {"waivers": [WAIVER]}) + code, out, _ = run_cli( + ["--no-banner", "-q", "-i", data, "--waivers", waiver_file, + "--show-known", "--suppression-audit"] + ) + self.assertEqual(code, 0) + self.assertIn("Waivers (1)", out) + + def test_impact_and_simulate_agree_on_a_rule(self): + """A rule that impact says decides must move the count when disabled.""" + handle = tempfile.NamedTemporaryFile( + "w", suffix=".txt", delete=False, encoding="utf-8" + ) + handle.write("\n".join(URLS) + "\n") + handle.close() + self.addCleanup(os.unlink, handle.name) + report = make_report() + impacts = impact.rule_impact(report) + deciders = [entry.rule for entry in impacts.deciding_rules()] + self.assertTrue(deciders, "expected at least one deciding rule") + rule = deciders[0] + result = simulate.simulate( + make_requests(), + detector.AnalysisOptions(), + simulate.parse_changes(f"{rule}=off"), + ) + self.assertLess( + result.counts(result.after)["total"], result.counts(result.before)["total"] + ) + + def test_attestation_and_simulation_together(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + target = self.path("att.json") + code, out, err = run_cli( + ["--no-banner", "-i", data, "--format", "json", + "--simulate", "name-exact=-5", "--attest", target] + ) + self.assertEqual(code, 0) + self.assertIn("weight simulation", out) + payload = json.loads(Path(target).read_text(encoding="utf-8")) + self.assertEqual(payload["settings"]["min_score"], 25) + + def test_all_ten_flags_in_one_run(self): + data = self.write("u.txt", "\n".join(URLS) + "\n") + waiver_file = self.write_json("w.json", {"waivers": [WAIVER]}) + base = self.write_json( + "base.json", {"findings": [{"fingerprint": "deadbeefdeadbeef"}]} + ) + old = self.write( + "old.json", + json.dumps( + __import__("pathscope.report", fromlist=["x"]).build_json_payload( + make_report() + ) + ), + ) + ledger_path = self.path("reviews.db") + store = ledger.open_ledger(ledger_path) + store.record("fp1", status="accepted", rule="name-exact") + store.close() + owner_dir = self.path("owners") + attestation = self.path("att.json") + code, out, err = run_cli( + [ + "--no-banner", "-i", data, + "--waivers", waiver_file, + "--baseline", base, + "--ledger", ledger_path, + "--where", "score > 0", + "--rule-impact", + "--suppression-audit", + "--simulate", "name-exact=-5", + "--assign-owners", "alice,bob", + "--assign-dir", owner_dir, + "--format", "json", + "--attest", attestation, + ] + ) + self.assertEqual(code, 0, err) + for marker in ( + "PathScope rule impact", + "PathScope suppression audit", + "PathScope weight simulation", + "PathScope owner assignment", + ): + self.assertIn(marker, out) + self.assertTrue(os.path.exists(attestation)) + self.assertIn("INDEX.md", os.listdir(owner_dir)) + + def test_help_lists_every_new_flag(self): + help_text = cli.build_parser().format_help() + for flag in ( + "--waivers", "--init-waivers", "--suppression-audit", "--rule-precision", + "--rule-impact", "--simulate", "--explain-diff", "--where", "--attest", + "--assign-owners", "--ledger-merge", "--merge-apply", + ): + self.assertIn(flag, help_text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_path_detector.py b/tests/test_path_detector.py new file mode 100755 index 0000000..a300682 --- /dev/null +++ b/tests/test_path_detector.py @@ -0,0 +1,1228 @@ +#!/usr/bin/env python3 +"""Tests for PathScope (stdlib ``unittest`` only, fully offline). + +Run from the project root: + + python3 -m unittest discover -s tests -v + python3 tests/test_path_detector.py + +Coverage maps to the project requirements: + +* repeated query parameters and URL decoding -> TestQueryParsing +* literal / encoded / multi-encoded traversal -> TestValueHeuristics +* parameter-name heuristics and non-findings -> TestNameHeuristics +* HAR query, form and JSON parameters -> TestHarInput +* malformed input and graceful errors -> TestMalformedInput, TestCli +* value redaction and --show-values -> TestRedaction, TestCli +* stable JSON, CSV and SARIF output -> TestReportFormats +* no network access in the implementation -> TestSafety +""" + +from __future__ import annotations + +import ast +import builtins +import csv +import io +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parents[1] +SCRIPT = REPO_ROOT / "path_detector.py" +sys.path.insert(0, str(REPO_ROOT)) + +from pathscope import BANNER_LINKS, __version__ # noqa: E402 +from pathscope import cli, config, detector, heuristics, report, sources, textutil # noqa: E402 + +HAR_SAMPLE = { + "log": { + "version": "1.2", + "creator": {"name": "unit-test", "version": "1"}, + "entries": [ + { + "request": { + "method": "GET", + "url": "https://app.test/files?path=../../etc/passwd&lang=en", + "queryString": [ + {"name": "path", "value": "../../etc/passwd"}, + {"name": "lang", "value": "en"}, + ], + }, + "response": {"status": 200}, + }, + { + "request": { + "method": "POST", + "url": "https://app.test/upload", + "postData": { + "mimeType": "application/x-www-form-urlencoded", + "text": "attachment=%2Ftmp%2Freport.pdf¬e=hello", + }, + } + }, + { + "request": { + "method": "POST", + "url": "https://app.test/api", + "postData": { + "mimeType": "application/json", + "text": json.dumps( + { + "file": {"path": "C:\\Windows\\win.ini"}, + "ids": [1, 2], + "name": "x", + } + ), + }, + } + }, + ], + } +} + + +def banner_line(label: str) -> str: + """The exact branded line for a label, e.g. ``GitHub: https://...``.""" + for known, url in BANNER_LINKS: + if known == label: + return f"{label}: {url}" + raise KeyError(label) + + +def run_cli(*args: str, stdin: str = "", timeout: int = 45) -> subprocess.CompletedProcess: + """Run the real CLI in a subprocess (stdout/stderr are pipes, so no colour).""" + env = dict(os.environ) + env.pop("NO_COLOR", None) + env["TERM"] = "xterm-256color" + return subprocess.run( + [sys.executable, str(SCRIPT), *args], + input=stdin, + capture_output=True, + text=True, + env=env, + timeout=timeout, + cwd=str(REPO_ROOT), + ) + + +def run_inprocess(*args: str, stdin: str = ""): + """Run the CLI in-process with captured streams.""" + out, err = io.StringIO(), io.StringIO() + code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin) + return code, out.getvalue(), err.getvalue() + + +def write_temp(name: str, content: str, binary: bool = False) -> str: + handle = tempfile.NamedTemporaryFile( + "wb" if binary else "w", + suffix=name, + delete=False, + encoding=None if binary else "utf-8", + ) + with handle as stream: + stream.write(content) + return handle.name + + +# --------------------------------------------------------------------------- +# textutil +# --------------------------------------------------------------------------- +class TestTextUtil(unittest.TestCase): + def test_sanitize_removes_control_characters(self): + dirty = "file\x1b[31m.pdf\x00\x07" + clean = textutil.sanitize_text(dirty) + self.assertNotIn("\x1b", clean) + self.assertNotIn("\x00", clean) + self.assertNotIn("\x07", clean) + self.assertEqual(clean, "file[31m.pdf") + + def test_truncate(self): + self.assertEqual(textutil.truncate("abcdef", 4), "abc\u2026") + self.assertEqual(textutil.truncate("abc", 10), "abc") + + def test_decode_single(self): + decoded, passes = textutil.decode_value("%2e%2e%2fetc") + self.assertEqual(decoded, "../etc") + self.assertEqual(passes, 1) + + def test_decode_multi(self): + decoded, passes = textutil.decode_value("%252e%252e%252fetc") + self.assertEqual(decoded, "../etc") + self.assertEqual(passes, 2) + + def test_decode_is_bounded(self): + decoded, passes = textutil.decode_value("%25252e%25252e", max_passes=1) + self.assertEqual(passes, 1) + self.assertEqual(decoded, "%252e%252e") + + def test_decode_malformed_does_not_raise(self): + for value in ("%zz", "%", "%E0%A4%A", "%FF%FE"): + decoded, _passes = textutil.decode_value(value) + self.assertIsInstance(decoded, str) + + def test_decode_noop_without_percent(self): + self.assertEqual(textutil.decode_value("../../etc"), ("../../etc", 0)) + + def test_decode_forms_dedupes(self): + forms = textutil.decode_forms("plain") + self.assertEqual(forms, [(0, "plain")]) + + def test_dedupe_preserves_order(self): + self.assertEqual(textutil.dedupe(["b", "a", "b", "c", "a"]), ["b", "a", "c"]) + + def test_encode_display_flattens_whitespace(self): + self.assertEqual(textutil.encode_display("a\nb\tc"), "a b c") + + +# --------------------------------------------------------------------------- +# Heuristics: parameter names +# --------------------------------------------------------------------------- +class TestNameHeuristics(unittest.TestCase): + def test_tokenize_variants(self): + self.assertEqual(heuristics.tokenize_name("fileName"), ["file", "name"]) + self.assertEqual(heuristics.tokenize_name("base_path"), ["base", "path"]) + self.assertEqual(heuristics.tokenize_name("X-File-Path"), ["x", "file", "path"]) + self.assertEqual(heuristics.tokenize_name("FILES"), ["files"]) + self.assertEqual(heuristics.tokenize_name("file_path2"), ["file", "path", "2"]) + self.assertEqual(heuristics.tokenize_name(""), []) + + def test_exact_name_terms(self): + for name in ("file", "path", "dir", "folder", "template", "include", + "download", "page", "resource", "attachment", "filepath"): + rules = [e.rule for e in heuristics.analyze_name(name)] + self.assertIn("name-exact", rules, name) + + def test_multiword_name_bonus(self): + single = sum(e.weight for e in heuristics.analyze_name("file")) + multi = sum(e.weight for e in heuristics.analyze_name("download_file")) + self.assertGreater(multi, single) + + def test_camel_case_and_kebab_case(self): + for name in ("fileName", "file-name", "file_name"): + self.assertGreater(sum(e.weight for e in heuristics.analyze_name(name)), 0) + + def test_prefix_match_is_discounted(self): + exact = sum(e.weight for e in heuristics.analyze_name("file")) + prefix = sum(e.weight for e in heuristics.analyze_name("filedata")) + self.assertGreater(prefix, 0) + self.assertLess(prefix, exact) + + def test_ordinary_names_are_not_flagged(self): + for name in ("q", "search", "utm_source", "utm_campaign", "gclid", + "fbclid", "urlencoded", "landscape", "session", "sort", + "orderby", "callback", "x" * 40): + evidence = heuristics.analyze_name(name) + total = sum(item.weight for item in evidence) + self.assertLess(total, 25, name) + + def test_generic_names_score_zero_alone(self): + for name in ("image", "img", "target", "ref", "avatar"): + evidence = heuristics.analyze_name(name) + self.assertEqual(sum(item.weight for item in evidence), 0, name) + self.assertIn("name-generic", [item.rule for item in evidence], name) + + def test_custom_terms(self): + evidence = heuristics.analyze_name("cdn_blob", extra_terms=["cdn_blob"]) + self.assertEqual([e.rule for e in evidence], ["name-custom"]) + # A built-in term always wins over a configured duplicate. + evidence = heuristics.analyze_name("media_file", extra_terms=["media_file", "download"]) + self.assertEqual([e.rule for e in evidence], ["name-exact"]) + + def test_custom_term_does_not_override_builtin(self): + rules = [e.rule for e in heuristics.analyze_name("file", extra_terms=["file"])] + self.assertEqual(rules, ["name-exact"]) + + def test_canonical_name(self): + self.assertEqual(heuristics.canonical_name("File_Name"), "file_name") + self.assertEqual(heuristics.canonical_name("file-name"), "file_name") + + +# --------------------------------------------------------------------------- +# Heuristics: values +# --------------------------------------------------------------------------- +class TestValueHeuristics(unittest.TestCase): + def score(self, value: str, **kwargs) -> int: + return sum(item.weight for item in heuristics.analyze_value(value, **kwargs)) + + def rules(self, value: str, **kwargs): + return [item.rule for item in heuristics.analyze_value(value, **kwargs)] + + def test_literal_traversal(self): + self.assertIn("value-traversal", self.rules("../../etc/passwd")) + self.assertIn("value-traversal", self.rules(r"..\..\windows\win.ini")) + self.assertIn("value-traversal", self.rules("..")) + self.assertIn("value-traversal", self.rules("foo/../bar")) + + def test_traversal_must_be_a_segment(self): + for value in ("report..pdf", "v1..2", "version 1..2", "a..b", "..hidden"): + self.assertNotIn("value-traversal", self.rules(value), value) + + def test_encoded_traversal(self): + rules = self.rules("%2e%2e%2f%2e%2e%2fetc%2fpasswd") + self.assertIn("value-encoded-traversal", rules) + self.assertIn("value-encoded-slash", rules) + self.assertNotIn("value-traversal", rules) + + def test_partially_encoded_traversal(self): + rules = self.rules("..%2f..%2fetc%2fpasswd") + self.assertIn("value-encoded-traversal", rules) + + def test_double_encoded_traversal(self): + rules = self.rules("%252e%252e%252f%252e%252e%252fetc%252fpasswd") + self.assertIn("value-encoded-traversal", rules) + self.assertIn("value-double-encoded", rules) + + def test_decoding_is_bounded(self): + # Four nested encodings must not be decoded with the default 3 passes. + rules = self.rules("%25252e%25252e%25252f", max_decode_passes=2) + self.assertNotIn("value-encoded-traversal", rules) + + def test_traversal_not_counted_twice(self): + plain = self.score("../../etc/passwd") + encoded = self.score("%2e%2e%2f%2e%2e%2fetc%2fpasswd") + self.assertGreater(plain, 0) + self.assertGreaterEqual(plain, encoded) + + def test_absolute_paths(self): + self.assertIn("value-absolute", self.rules("/var/www/html")) + self.assertIn("value-windows-drive", self.rules("C:\\Windows\\win.ini")) + self.assertIn("value-windows-drive", self.rules("D:/data/x")) + self.assertIn("value-unc", self.rules(r"\\server\share\x")) + + def test_protocol_relative_is_not_absolute(self): + self.assertNotIn("value-absolute", self.rules("//cdn.test/x.js")) + + def test_full_url_is_penalised(self): + self.assertIn("value-full-url", self.rules("https://other.test/a/b")) + self.assertLess(self.score("https://other.test/a/b"), 0) + + def test_extension_on_path_like_value(self): + self.assertIn("value-extension", self.rules("/static/app.js")) + self.assertIn("value-extension", self.rules("report.tar.gz")) + + def test_plain_values_score_zero(self): + for value in ("", "hello", "en", "50%", "%zz", "name"): + self.assertEqual(self.score(value), 0, value) + + def test_scalar_values_are_demoted(self): + # Numbers and booleans carry no path evidence; the demotion rule is + # explicit (and visible in --explain) rather than a silent filter. + for value in ("12345", "true", "false", "3.14"): + rules = self.rules(value) + self.assertEqual(len(rules), 1, value) + self.assertTrue(rules[0].startswith("value-demote-"), rules) + self.assertEqual( + self.rules("12345", demote=False), + [], + ) + + def test_malformed_encoding_is_safe(self): + for value in ("%", "%E0%A4%A", "%zz%2e", "%FF/%FE"): + self.assertIsInstance(self.rules(value), list) + + def test_analyze_parameter_combines_layers(self): + analysis = heuristics.analyze_parameter("file", "../../etc/passwd") + self.assertIn("name-exact", analysis.rules) + self.assertIn("value-traversal", analysis.rules) + self.assertGreaterEqual(analysis.score, 60) + self.assertIn(analysis.confidence, {"medium", "high"}) + + def test_generic_name_needs_path_value(self): + self.assertFalse(heuristics.analyze_parameter("image", "logo").evidence) + analysis = heuristics.analyze_parameter("image", "/static/logo.png") + self.assertTrue(analysis.evidence) + self.assertIn("value-pairs-with-generic-name", analysis.rules) + + def test_ordinary_parameter_is_not_a_finding(self): + for name, value in (("lang", "en"), ("test", "2"), ("q", "hello"), + ("utm_source", "newsletter"), ("id", "42")): + analysis = heuristics.analyze_parameter(name, value) + self.assertEqual(analysis.evidence, [], (name, value)) + + def test_ignore_list(self): + analysis = heuristics.analyze_parameter("file", "../../etc/passwd", ignore=["file"]) + self.assertEqual(analysis.evidence, []) + + def test_min_score_filter(self): + self.assertFalse(heuristics.analyze_parameter("page", "2", min_score=60).evidence) + self.assertTrue(heuristics.analyze_parameter("page", "2", min_score=25).evidence) + + def test_reasons_are_explainable_and_neutral(self): + analysis = heuristics.analyze_parameter("file", "%2e%2e%2fetc%2fpasswd") + blob = " ".join(analysis.reasons).lower() + for banned in ("exploitable", "vulnerable", "confirmed", "attack"): + self.assertNotIn(banned, blob) + self.assertTrue(analysis.reasons) + + +# --------------------------------------------------------------------------- +# Sources: URLs and query parsing +# --------------------------------------------------------------------------- +class TestQueryParsing(unittest.TestCase): + def test_parse_url(self): + info = sources.parse_url("https://Example.Test:8443/a/b?x=1") + self.assertEqual(info.scheme, "https") + self.assertEqual(info.host, "example.test") + self.assertEqual(info.port, 8443) + self.assertEqual(info.path, "/a/b") + self.assertEqual(info.query, "x=1") + self.assertEqual(info.display_host, "example.test:8443") + + def test_display_resource_excludes_query(self): + info = sources.parse_url("https://example.test/a?secret=abc#frag") + self.assertNotIn("secret", info.display_resource) + self.assertNotIn("abc", info.display_resource) + + def test_repeated_parameters(self): + params = sources.query_parameters("file=a.txt&file=b.txt&file=c.txt") + self.assertEqual([p.value for p in params], ["a.txt", "b.txt", "c.txt"]) + self.assertEqual([p.occurrence for p in params], [1, 2, 3]) + + def test_encoded_names_and_values(self): + params = sources.query_parameters("%66%69%6c%65=..%2Freports%2Fq1.pdf") + self.assertEqual(params[0].name, "file") + self.assertEqual(params[0].value, "..%2Freports%2Fq1.pdf") + + def test_plus_is_space_in_names(self): + params = sources.query_parameters("file+name=x") + self.assertEqual(params[0].name, "file name") + + def test_blank_values_and_bare_keys(self): + params = sources.query_parameters("file=&path") + self.assertEqual([(p.name, p.value) for p in params], [("file", ""), ("path", "")]) + + def test_semicolon_is_not_a_separator(self): + params = sources.query_parameters("a=1;b=2&c=3") + self.assertEqual([p.name for p in params], ["a", "c"]) + + def test_ampersand_inside_encoded_value(self): + params = sources.query_parameters("next=%2Fhome%3Ftab%3Dfiles&file=a.txt") + self.assertEqual([p.name for p in params], ["next", "file"]) + + def test_empty_query(self): + self.assertEqual(sources.query_parameters(""), []) + + def test_blank_query_chunks_are_skipped(self): + self.assertEqual([p.name for p in sources.query_parameters("&&a=1&&")], ["a"]) + + def test_invalid_scheme(self): + for url in ("ftp://a.test/x", "javascript:alert(1)", "file:///etc/passwd", + "example.test/a?x=1", "https:///a"): + with self.assertRaises(sources.URLParseError, msg=url): + sources.parse_url(url) + + def test_whitespace_url_is_rejected(self): + with self.assertRaises(sources.URLParseError): + sources.parse_url("https://a.test/a b?file=x") + + def test_bad_port(self): + with self.assertRaises(sources.URLParseError): + sources.parse_url("https://a.test:99999/") + + def test_ipv6_display(self): + info = sources.parse_url("http://[::1]:8080/?file=x") + self.assertEqual(info.display_host, "[::1]:8080") + + +class TestUrlListInput(unittest.TestCase): + def test_blank_lines_comments_and_duplicates(self): + result = sources.load_url_lines( + ["", " ", "# note", "https://a.test/?file=x", "https://a.test/?file=x", + "https://b.test/?page=2"], + sources.SOURCE_FILE, "urls.txt", + ) + self.assertEqual(len(result.requests), 2) + self.assertEqual(result.warnings, []) + self.assertEqual(result.skipped, 0) + + def test_malformed_lines_are_warnings(self): + result = sources.load_url_lines( + ["not-a-url", "https://ok.test/?file=x", "ftp://bad.test/"], + sources.SOURCE_FILE, "urls.txt", + ) + self.assertEqual(len(result.requests), 1) + self.assertEqual(result.skipped, 2) + self.assertEqual(len(result.warnings), 2) + self.assertIn("urls.txt line 1", result.warnings[0]) + + def test_source_metadata(self): + result = sources.load_url_lines(["https://a.test/?file=x"], sources.SOURCE_STDIN, "stdin") + request = result.requests[0] + self.assertEqual(request.source_type, "stdin") + self.assertEqual(request.source_label, "stdin") + + def test_url_flags(self): + result = sources.make_url_requests( + ["https://a.test/?file=x", "https://a.test/?file=x", "bad", ""] + ) + self.assertEqual(len(result.requests), 1) + self.assertEqual(result.skipped, 2) + + +# --------------------------------------------------------------------------- +# HAR input +# --------------------------------------------------------------------------- +class TestHarInput(unittest.TestCase): + def load(self, payload) -> sources.LoadResult: + text = payload if isinstance(payload, str) else json.dumps(payload) + return sources.load_har(text, "sample.har") + + def test_query_parameters(self): + result = self.load(HAR_SAMPLE) + query = [p for r in result.requests for p in r.parameters if p.location == "query"] + self.assertEqual({p.name for p in query}, {"path", "lang"}) + self.assertEqual(result.requests[0].source_type, "har") + self.assertEqual(result.requests[0].method, "GET") + + def test_form_parameters(self): + result = self.load(HAR_SAMPLE) + form = [p for r in result.requests for p in r.parameters if p.location == "form"] + self.assertEqual({p.name for p in form}, {"attachment", "note"}) + + def test_form_params_array(self): + payload = { + "log": { + "version": "1.2", + "entries": [ + { + "request": { + "url": "https://a.test/u", + "method": "POST", + "postData": { + "mimeType": "multipart/form-data", + "params": [ + {"name": "file", "fileName": "/tmp/x.txt", "contentType": "text/plain"}, + {"name": "note", "value": "hi"}, + ], + }, + } + } + ], + } + } + result = self.load(payload) + form = {p.name: p.value for p in result.requests[0].parameters} + self.assertEqual(form["file"], "/tmp/x.txt") + self.assertEqual(form["note"], "hi") + + def test_json_parameters_flattened(self): + result = self.load(HAR_SAMPLE) + json_params = {p.name: p.value for p in result.requests[2].parameters + if p.location == "json"} + self.assertIn("file.path", json_params) + self.assertEqual(json_params["file.path"], "C:\\Windows\\win.ini") + self.assertIn("ids[0]", json_params) + self.assertEqual(json_params["ids[0]"], "1") + self.assertIn("name", json_params) + + def test_malformed_entries_are_skipped_with_warnings(self): + payload = { + "log": { + "version": "1.2", + "entries": [ + "not-an-object", + {"no_request": True}, + {"request": {"url": "ftp://bad.test/x"}}, + {"request": {"url": "not-a-url"}}, + {"request": {"url": "https://ok.test/?file=x"}}, + ], + } + } + result = self.load(payload) + self.assertEqual(len(result.requests), 1) + self.assertEqual(result.skipped, 4) + self.assertGreaterEqual(len(result.warnings), 4) + + def test_missing_log_is_an_error(self): + with self.assertRaises(sources.HarError): + self.load({"foo": []}) + + def test_entries_must_be_a_list(self): + with self.assertRaises(sources.HarError): + self.load({"log": {"version": "1.2", "entries": {}}}) + + def test_invalid_json_is_an_error(self): + with self.assertRaises(sources.HarError): + sources.load_har("{not json", "bad.har") + + def test_duplicate_har_requests_are_collapsed(self): + entry = { + "request": { + "method": "GET", + "url": "https://a.test/?file=x", + "queryString": [{"name": "file", "value": "x"}], + } + } + result = self.load({"log": {"version": "1.2", "entries": [entry, dict(entry)]}}) + self.assertEqual(len(result.requests), 1) + + def test_query_falls_back_to_url_when_query_string_missing(self): + payload = {"log": {"version": "1.2", "entries": [ + {"request": {"url": "https://a.test/?file=abc&x=1"}} + ]}} + result = self.load(payload) + self.assertEqual([p.name for p in result.requests[0].parameters], ["file", "x"]) + + def test_har_version_variation_only_warns(self): + payload = {"log": {"version": "9.9", "entries": [ + {"request": {"url": "https://a.test/?file=x"}} + ]}} + result = self.load(payload) + self.assertEqual(len(result.requests), 1) + self.assertTrue(any("version" in w for w in result.warnings)) + + def test_format_detection(self): + self.assertEqual( + sources.detect_input_format(json.dumps(HAR_SAMPLE), ""), sources.INPUT_FORMAT_HAR + ) + self.assertEqual(sources.detect_input_format("https://a.test/?x=1", "urls.txt"), + sources.INPUT_FORMAT_URLS) + self.assertEqual(sources.detect_input_format("not json", "capture.har"), + sources.INPUT_FORMAT_HAR) + + def test_bom_prefixed_har_is_accepted(self): + result = sources.load_har("\ufeff" + json.dumps(HAR_SAMPLE), "bom.har") + self.assertEqual(len(result.requests), 3) + + def test_json_depth_limit_does_not_crash(self): + deep = {"a": {"b": {"c": {"d": {"e": "x"}}}}} + payload = {"log": {"version": "1.2", "entries": [ + {"request": {"url": "https://a.test/x", "postData": { + "mimeType": "application/json", + "text": json.dumps(deep), + }}} + ]}} + result = self.load(payload) + self.assertEqual(len(result.requests), 1) + self.assertTrue(any("json" in p.name or "a.b" in p.name + for p in result.requests[0].parameters)) + + +# --------------------------------------------------------------------------- +# Detector +# --------------------------------------------------------------------------- +class TestDetector(unittest.TestCase): + def analyze(self, urls, **options): + requests = [] + for index, url in enumerate(urls): + requests.append(sources.request_from_url(url, sources.SOURCE_URL, "--url", index)) + opts = detector.AnalysisOptions(**options) + return detector.analyze_requests(requests, opts) + + def test_finding_fields(self): + result = self.analyze(["https://example.test/view?file=report.pdf"]) + self.assertEqual(len(result.findings), 1) + finding = result.findings[0] + self.assertEqual(finding.host, "example.test") + self.assertEqual(finding.parameter, "file") + self.assertEqual(finding.rule, "name-exact") + self.assertEqual(finding.location, "query") + self.assertEqual(finding.confidence, "medium") + self.assertEqual(finding.resource, "https://example.test/view") + self.assertEqual(finding.source_type, "url") + + def test_repeated_parameters_are_grouped(self): + result = self.analyze([ + "https://a.test/x?file=one.txt&file=../../etc/passwd&file=three.txt" + ]) + self.assertEqual(len(result.findings), 1) + finding = result.findings[0] + self.assertEqual(finding.occurrences, 3) + self.assertIn("value-traversal", finding.rules) + + def test_show_values_only_when_requested(self): + hidden = self.analyze(["https://a.test/?file=secret.pdf"]).findings[0] + self.assertIsNone(hidden.value) + shown = self.analyze(["https://a.test/?file=secret.pdf"], show_values=True).findings[0] + self.assertEqual(shown.value, "secret.pdf") + + def test_ignore_params(self): + result = self.analyze( + ["https://a.test/?file=/x&path=/y"], ignore_params=("file",) + ) + self.assertEqual([f.parameter for f in result.findings], ["path"]) + + def test_min_score(self): + low = self.analyze(["https://a.test/?file=report.pdf"], min_score=90) + self.assertEqual(low.findings, []) + + def test_ordering_is_deterministic(self): + urls = [ + "https://b.test/?page=2&file=/a/b.txt&dir=../x", + "https://a.test/?template=home&file=/z", + ] + first = self.analyze(urls) + second = self.analyze(list(reversed(urls))) + self.assertEqual( + [(f.parameter, f.score, f.host) for f in first.findings], + [(f.parameter, f.score, f.host) for f in second.findings], + ) + self.assertEqual([f.index for f in first.findings], list(range(1, len(first.findings) + 1))) + + def test_no_duplicate_requests(self): + url = "https://a.test/?file=x.pdf" + result = self.analyze([url, url]) + self.assertEqual(result.requests_analyzed, 1) + + def test_counts(self): + result = self.analyze(["https://a.test/?file=x.pdf&q=hi&lang=en"]) + self.assertEqual(result.requests_analyzed, 1) + self.assertEqual(result.parameters_analyzed, 3) + self.assertEqual(result.candidate_count, 1) + + def test_sources_are_listed(self): + result = self.analyze(["https://a.test/?file=x.pdf"]) + self.assertEqual(result.sources, ["--url"]) + + def test_no_query_string_leaks_into_resource(self): + result = self.analyze(["https://a.test/a?file=/x?secret=1"]) + for finding in result.findings: + self.assertNotIn("secret", finding.resource) + + def test_empty_input(self): + result = detector.analyze_requests([], detector.AnalysisOptions()) + self.assertEqual(result.candidate_count, 0) + self.assertEqual(result.requests_analyzed, 0) + + +# --------------------------------------------------------------------------- +# Report formats +# --------------------------------------------------------------------------- +class TestReportFormats(unittest.TestCase): + def build_report(self, show_values: bool = False): + requests = [ + sources.request_from_url( + "https://example.test/view?file=report.pdf&lang=en", sources.SOURCE_URL, "--url" + ), + sources.request_from_url( + "https://other.test/dl?path=../../etc/passwd", sources.SOURCE_FILE, "urls.txt" + ), + ] + return detector.analyze_requests( + requests, detector.AnalysisOptions(show_values=show_values) + ) + + def test_json_is_stable_and_complete(self): + first = report.render_json(self.build_report()) + second = report.render_json(self.build_report()) + self.assertEqual(first, second) + payload = json.loads(first) + self.assertEqual(payload["tool"], "PathScope") + self.assertEqual(payload["version"], __version__) + self.assertTrue(payload["passive"]) + self.assertEqual(payload["network_requests_made"], 0) + self.assertIn("manual review", payload["disclaimer"]) + self.assertEqual(payload["summary"]["candidates"], len(payload["findings"])) + for finding in payload["findings"]: + for key in ("host", "source_type", "parameter", "rule", "confidence", + "score", "reasons", "location"): + self.assertIn(key, finding) + self.assertNotIn("report.pdf", first) + + def test_json_show_values(self): + payload = json.loads(report.render_json(self.build_report(show_values=True))) + values = {f["parameter"]: f["value"] for f in payload["findings"]} + self.assertEqual(values["file"], "report.pdf") + + def test_csv_columns_and_escaping(self): + text = report.render_csv(self.build_report()) + rows = list(csv.DictReader(io.StringIO(text))) + self.assertEqual(list(rows[0].keys()), list(report.CSV_COLUMNS)) + self.assertEqual(len(rows), 2) + self.assertEqual(rows[0]["value"], "") + for row in rows: + self.assertIn(row["rule"], row["rules"].split(";")) + + def test_csv_show_values(self): + text = report.render_csv(self.build_report(show_values=True)) + rows = list(csv.DictReader(io.StringIO(text))) + self.assertIn("report.pdf", [row["value"] for row in rows]) + + def test_sarif_minimum_requirements(self): + payload = json.loads(report.render_sarif(self.build_report())) + self.assertEqual(payload["version"], "2.1.0") # SARIF spec version + self.assertIn("$schema", payload) + run = payload["runs"][0] + driver = run["tool"]["driver"] + self.assertEqual(driver["name"], "PathScope") + rule_ids = [rule["id"] for rule in driver["rules"]] + self.assertTrue(rule_ids) + for result in run["results"]: + self.assertIn(result["ruleId"], rule_ids) + self.assertEqual(rule_ids[result["ruleIndex"]], result["ruleId"]) + self.assertIn(result["level"], ("warning", "note")) + self.assertIn("manual review", result["message"]["text"].lower()) + + def test_sarif_is_deterministic(self): + self.assertEqual( + report.render_sarif(self.build_report()), + report.render_sarif(self.build_report()), + ) + + def test_text_output_hides_and_shows_values(self): + hidden = report.render_text(self.build_report(), report.Palette(False)) + self.assertIn("", hidden) + self.assertNotIn("report.pdf", hidden) + shown = report.render_text(self.build_report(show_values=True), report.Palette(False)) + self.assertIn("report.pdf", shown) + + def test_text_has_no_ansi_when_palette_disabled(self): + text = report.render_text(self.build_report(), report.Palette(False)) + self.assertNotIn("\x1b[", text) + + def test_palette_enabled_adds_ansi(self): + text = report.render_text(self.build_report(), report.Palette(True)) + self.assertIn("\x1b[", text) + + def test_control_characters_are_escaped(self): + requests = [ + sources.request_from_url( + "https://a.test/?file=../../etc/passwd%1b[31mred%0aInjected", + sources.SOURCE_URL, + "--url", + ) + ] + result = detector.analyze_requests( + requests, detector.AnalysisOptions(show_values=True) + ) + plain = report.render_text(result, report.Palette(False)) + for rendered in ( + plain, + report.render_json(result), + report.render_csv(result), + report.render_sarif(result), + ): + # No escape sequence from the *input* may survive into any format. + self.assertNotIn("\x1b[31mred", rendered) + # With colour disabled there must be no ANSI at all. + self.assertNotIn("\x1b", plain) + self.assertFalse( + any(line.strip() == "Injected" for line in + report.render_text(result, report.Palette(False)).splitlines()) + ) + + def test_banner_contains_exact_links(self): + banner = report.render_banner(report.Palette(False)) + for label, url in BANNER_LINKS: + self.assertIn(banner_line(label), banner) + + +# --------------------------------------------------------------------------- +# Configuration +# --------------------------------------------------------------------------- +class TestConfig(unittest.TestCase): + def test_valid_config(self): + cfg = config.validate_payload( + {"name_terms": ["download"], "ignore_params": ["image"], "min_score": 10} + ) + self.assertEqual(cfg.name_terms, ["download"]) + self.assertEqual(cfg.ignore_params, ["image"]) + self.assertEqual(cfg.min_score, 10) + + def test_unknown_keys_rejected(self): + with self.assertRaises(config.ConfigError): + config.validate_payload({"regexes": [".*"]}) + + def test_regex_like_terms_rejected(self): + for term in ("(a+)+$", ".*", "a|b", "[a-z]"): + with self.assertRaises(config.ConfigError, msg=term): + config.validate_payload({"name_terms": [term]}) + + def test_wrong_types_rejected(self): + cases = ( + {"name_terms": "download"}, + {"name_terms": [1]}, + {"ignore_params": ["a", 2]}, + {"min_score": "high"}, + {"min_score": True}, + {"min_score": 101}, + {"max_decode_passes": 9}, + {"show_values": "yes"}, + [], + ) + for payload in cases: + with self.assertRaises(config.ConfigError, msg=str(payload)): + config.validate_payload(payload) + + def test_term_length_limits(self): + with self.assertRaises(config.ConfigError): + config.validate_payload({"name_terms": ["x"]}) + with self.assertRaises(config.ConfigError): + config.validate_payload({"name_terms": ["x" * 200]}) + + def test_missing_file_and_invalid_json(self): + with self.assertRaises(config.ConfigError): + config.load_config("/definitely/not/here.json") + path = write_temp(".json", "{not json") + try: + with self.assertRaises(config.ConfigError): + config.load_config(path) + finally: + os.unlink(path) + + def test_load_valid_file(self): + path = write_temp(".json", json.dumps(config.dump_example())) + try: + cfg = config.load_config(path) + finally: + os.unlink(path) + self.assertIn("download", cfg.name_terms) + self.assertEqual(cfg.source, path) + + def test_merge_ignore_deduplicates(self): + cfg = config.Config(ignore_params=["image"]) + self.assertEqual(config.merge_ignore(["image", "config"], cfg), ["image", "config"]) + + +# --------------------------------------------------------------------------- +# Malformed input +# --------------------------------------------------------------------------- +class TestMalformedInput(unittest.TestCase): + def test_unreadable_file_raises(self): + with self.assertRaises(sources.InputError): + sources.load_file("/no/such/file.txt") + + def test_directory_raises(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(sources.InputError): + sources.load_file(tmp, sources.INPUT_FORMAT_URLS) + + def test_binary_garbage_does_not_crash(self): + path = write_temp(".har", b"\x00\x01\x02\xff", binary=True) + try: + with self.assertRaises(sources.HarError): + sources.load_har(sources.read_text(path), "binary.har") + finally: + os.unlink(path) + + def test_huge_value_is_truncated(self): + value = "a" * (sources.MAX_VALUE_CHARS + 5000) + params = sources.query_parameters(f"file={value}") + self.assertEqual(len(params[0].value), sources.MAX_VALUE_CHARS) + + def test_control_characters_are_stripped_from_input(self): + result = sources.load_url_lines( + ["https://a.test/?file=x\x1b[31m"], sources.SOURCE_FILE, "u.txt" + ) + self.assertEqual(len(result.requests), 1) + self.assertNotIn("\x1b", result.requests[0].url.raw) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- +class TestCli(unittest.TestCase): + def test_banner_on_every_start(self): + code, out, err = run_inprocess("--url", "https://a.test/?file=x.pdf") + self.assertEqual(code, cli.EXIT_OK) + for label, url in BANNER_LINKS: + self.assertIn(f"{label}: {url}", err) + self.assertEqual(err.count("PathScope " + __version__), 1) + + def test_banner_suppressed(self): + code, out, err = run_inprocess("--no-banner", "--url", "https://a.test/?q=1") + self.assertNotIn("instagram.com", err) + + def test_help(self): + result = run_cli("--help") + self.assertEqual(result.returncode, 0) + self.assertIn("usage:", result.stdout) + self.assertIn("exit codes:", result.stdout) + self.assertIn("https://buymeacoffee.com/mrdineshpathro", result.stdout) + for label, url in BANNER_LINKS: + self.assertIn(banner_line(label), result.stderr) + + def test_version(self): + result = run_cli("--version") + self.assertEqual(result.returncode, 0) + self.assertIn(__version__, result.stdout) + + def test_single_url(self): + result = run_cli("--no-banner", "--url", "https://example.test/view?file=report.pdf") + self.assertEqual(result.returncode, 0) + self.assertIn("file", result.stdout) + self.assertIn("name-exact", result.stdout) + self.assertIn("candidates for manual review", result.stdout.lower()) + self.assertNotIn("report.pdf", result.stdout) + + def test_show_values(self): + result = run_cli( + "--no-banner", "--show-values", "--url", "https://a.test/?file=report.pdf" + ) + self.assertIn("report.pdf", result.stdout) + + def test_no_ansi_when_piped(self): + result = run_cli("--no-banner", "--url", "https://a.test/?file=report.pdf") + self.assertNotIn("\x1b[", result.stdout) + self.assertNotIn("\x1b[", result.stderr) + + def test_json_shorthand(self): + result = run_cli("--no-banner", "-q", "--json", "--url", "https://a.test/?file=a.pdf") + payload = json.loads(result.stdout) + self.assertEqual(payload["tool"], "PathScope") + self.assertIsNone(payload["findings"][0]["value"]) + + def test_format_flag_selects_output(self): + for fmt in ("json", "csv", "sarif"): + result = run_cli("--no-banner", "-q", "--format", fmt, + "--url", "https://a.test/?file=a.pdf") + self.assertEqual(result.returncode, 0, fmt) + if fmt != "csv": + json.loads(result.stdout) + + def test_input_file(self): + path = write_temp( + ".txt", + "\n".join(["", "# comment", "https://a.test/?file=one.pdf", "bad-url", + "https://b.test/?path=../../etc"]), + ) + try: + result = run_cli("--no-banner", "-i", path) + finally: + os.unlink(path) + self.assertEqual(result.returncode, 0) + self.assertIn("Analyzed 2 request(s)", result.stdout) + self.assertIn("skipped malformed URL", result.stderr) + + def test_har_file_auto_detected(self): + path = write_temp(".har", json.dumps(HAR_SAMPLE)) + try: + result = run_cli("--no-banner", "-q", "--json", "-i", path) + finally: + os.unlink(path) + payload = json.loads(result.stdout) + # lang=en is now intentionally out of the vocabulary (ordinary i18n value). + self.assertEqual(len(payload["findings"]), 3) + locations = {f["location"] for f in payload["findings"]} + self.assertIn("form", locations) + self.assertIn("json", locations) + self.assertIn("query", locations) + + def test_har_forced_format(self): + path = write_temp(".json", json.dumps(HAR_SAMPLE)) + try: + result = run_cli("--no-banner", "-q", "--format", "har", "-i", path) + finally: + os.unlink(path) + self.assertEqual(result.returncode, 0) + self.assertIn("Source", result.stdout) + + def test_stdin_urls(self): + result = run_cli("--no-banner", "--json", stdin="https://a.test/?file=a.pdf\n") + payload = json.loads(result.stdout) + self.assertEqual(payload["findings"][0]["source_type"], "stdin") + + def test_stdin_har(self): + result = run_cli("--no-banner", "-q", "--json", stdin=json.dumps(HAR_SAMPLE)) + payload = json.loads(result.stdout) + self.assertEqual(payload["findings"][0]["source_type"], "har") + + def test_dash_input_reads_stdin(self): + result = run_cli("--no-banner", "-q", "-i", "-", stdin="https://a.test/?file=x.pdf\n") + self.assertEqual(result.returncode, 0) + self.assertIn("file", result.stdout) + + def test_duplicate_requests_are_analyzed_once(self): + stdin = "https://a.test/?file=x.pdf\nhttps://a.test/?file=x.pdf\n" + result = run_cli("--no-banner", "-q", "--json", stdin=stdin) + self.assertEqual(json.loads(result.stdout)["summary"]["requests_analyzed"], 1) + + def test_no_input_is_a_usage_error(self): + result = run_cli("--no-banner", stdin="") + self.assertEqual(result.returncode, cli.EXIT_USAGE) + self.assertIn("no usable input", result.stderr) + + def test_missing_file_is_a_usage_error(self): + result = run_cli("--no-banner", "-i", "/no/such/file.txt") + self.assertEqual(result.returncode, cli.EXIT_USAGE) + self.assertIn("cannot read input file", result.stderr) + + def test_invalid_har_is_a_usage_error(self): + path = write_temp(".har", "not json") + try: + result = run_cli("--no-banner", "-i", path, "--format", "har") + finally: + os.unlink(path) + self.assertEqual(result.returncode, cli.EXIT_USAGE) + self.assertIn("not valid JSON", result.stderr) + + def test_invalid_config_is_a_usage_error(self): + path = write_temp(".json", '{"name_terms": ["(a+)+$"]}') + try: + result = run_cli("--no-banner", "--config", path, "--url", "https://a.test/?file=x") + finally: + os.unlink(path) + self.assertEqual(result.returncode, cli.EXIT_USAGE) + self.assertIn("regular expressions", result.stderr) + + def test_config_terms_are_used(self): + path = write_temp(".json", json.dumps({"name_terms": ["cdn_blob"]})) + try: + result = run_cli("--no-banner", "-q", "--json", "--config", path, + "--url", "https://a.test/?cdn_blob=/x") + finally: + os.unlink(path) + payload = json.loads(result.stdout) + self.assertEqual(payload["findings"][0]["rule"], "name-custom") + + def test_ignore_param_flag(self): + result = run_cli( + "--no-banner", "-q", "--json", + "--ignore-param", "file", "--ignore-param", "down", + "--url", "https://a.test/?file=/x&down=1&path=/y", + ) + payload = json.loads(result.stdout) + self.assertEqual([f["parameter"] for f in payload["findings"]], ["path"]) + + def test_fail_on_findings(self): + result = run_cli("--no-banner", "-q", "--fail-on-findings", + "--url", "https://a.test/?file=x.pdf") + self.assertEqual(result.returncode, cli.EXIT_FINDINGS) + result = run_cli("--no-banner", "-q", "--fail-on-findings", + "--url", "https://a.test/?q=hello") + self.assertEqual(result.returncode, cli.EXIT_OK) + + def test_min_score_bounds(self): + result = run_cli("--no-banner", "--min-score", "200", "--url", "https://a.test/?file=x") + self.assertEqual(result.returncode, cli.EXIT_USAGE) + result = run_cli("--no-banner", "-q", "--min-score", "0", + "--url", "https://a.test/?q=hello") + self.assertEqual(result.returncode, 0) + + def test_quiet_suppresses_stderr_summary(self): + result = run_cli("--no-banner", "-q", "--url", "https://a.test/?file=x.pdf") + self.assertEqual(result.stderr.strip(), "") + + def test_url_with_encoded_ampersand(self): + result = run_cli( + "--no-banner", "-q", "--json", + "--url", "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.pdf", + ) + payload = json.loads(result.stdout) + self.assertEqual(payload["summary"]["parameters_analyzed"], 2) + + +# --------------------------------------------------------------------------- +# Safety +# --------------------------------------------------------------------------- +FORBIDDEN_MODULES = { + "socket", + "ssl", + "http", + "https", + "urllib.request", + "urllib3", + "requests", + "httpx", + "aiohttp", + "ftplib", + "smtplib", + "telnetlib", + "subprocess", + "multiprocessing", + "paramiko", + "dns", + "scapy", + "selenium", +} + +ALLOWED_THIRD_PARTY = set() + + +def project_modules(): + for path in sorted((REPO_ROOT / "pathscope").glob("*.py")): + yield path + + +class TestSafety(unittest.TestCase): + def test_imports_are_standard_library_only(self): + allowed_stdlib = { + "__future__", "argparse", "csv", "dataclasses", "io", "json", "os", + "re", "sys", "typing", "unicodedata", "urllib.parse", "collections", + "pathlib", "textwrap", "xml", "xml.etree", "xml.etree.ElementTree", + "base64", "copy", "hashlib", "html", "time", "math", "sqlite3", + "zipfile", "curses", "platform", "shutil", "tempfile", "textwrap", + "calendar", "shlex", "hmac", "secrets", "datetime", "fnmatch", "hashlib", + } + for path in project_modules(): + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + root = alias.name.split(".")[0] + self.assertIn(root, {m.split(".")[0] for m in allowed_stdlib}, + f"{path.name}: {alias.name}") + self.assertNotIn(alias.name, FORBIDDEN_MODULES) + elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0: + root = node.module.split(".")[0] + self.assertIn(root, {m.split(".")[0] for m in allowed_stdlib}, + f"{path.name}: {node.module}") + self.assertNotIn(node.module, FORBIDDEN_MODULES) + + def test_no_network_modules_in_sys_modules_during_analysis(self): + before = set(sys.modules) + requests = [ + sources.request_from_url( + "https://a.test/?file=../../etc/passwd&next=https://evil.test/x", + sources.SOURCE_URL, + "--url", + ) + ] + detector.analyze_requests(requests, detector.AnalysisOptions(show_values=True)) + report.render_json(detector.analyze_requests(requests, detector.AnalysisOptions())) + new = set(sys.modules) - before + self.assertFalse({m for m in new if m.split(".")[0] in {"socket", "http", "ssl"}}) + + def test_sockets_are_never_used(self): + def boom(*_args, **_kwargs): + raise AssertionError("PathScope attempted a network operation") + + with mock.patch("socket.socket", side_effect=boom), \ + mock.patch("socket.create_connection", side_effect=boom), \ + mock.patch("socket.getaddrinfo", side_effect=boom): + code, out, err = run_inprocess( + "--no-banner", "-q", "--show-values", + "--url", "https://a.test/?file=../../etc/passwd&url=https://evil.test/", + ) + self.assertEqual(code, 0) + self.assertIn("'..' path segment", out) + + def test_parameter_values_are_never_opened_as_files(self): + """A value like /etc/passwd must not reach ``open``/``os.open``.""" + sentinel = "/etc/passwd" + + def guarded_open(file, *args, **kwargs): # noqa: A002 + if isinstance(file, (str, bytes)) and sentinel in str(file): + raise AssertionError(f"PathScope tried to open {file!r}") + return real_open(file, *args, **kwargs) + + real_open = builtins.open + real_os_open = os.open + with mock.patch("builtins.open", side_effect=guarded_open), \ + mock.patch("os.open", side_effect=guarded_open): + analysis = heuristics.analyze_parameter("file", sentinel) + self.assertTrue(analysis.evidence) + self.assertIs(os.open, real_os_open) + + def test_source_has_no_root_or_shell_calls(self): + for path in project_modules(): + text = path.read_text(encoding="utf-8") + for marker in ("os.geteuid", "os.seteuid", "setuid", "os.system(", + "shell=True", "sudo "): + self.assertNotIn(marker, text, f"{path.name}: {marker}") + + def test_no_urllib_request_usage(self): + for path in project_modules(): + text = path.read_text(encoding="utf-8") + self.assertNotIn("urllib.request", text, path.name) + self.assertNotIn("urlopen", text, path.name) + + +if __name__ == "__main__": + unittest.main(verbosity=2)