From e40b9ee1361c75ef367c5fe3317ef3309c8bef18 Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:16:01 +0000 Subject: [PATCH 1/8] Add PathScope passive URL-parameter triage tool - path_detector.py: stdlib-only CLI, local-only parsing, no network/DNS, name + existing-value heuristics, hidden values by default, JSON output, terminal-aware colour, banner links, strict exit codes - tests/test_path_detector.py: 97 unittest cases incl. safety assertions - assets/logo.svg: original route + magnifier repository icon - README.md: Kali usage, scoring model, limitations, authorization notice Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .gitignore | 4 + README.md | 466 ++++++++++++++ assets/logo.svg | 78 +++ path_detector.py | 1201 +++++++++++++++++++++++++++++++++++ tests/test_path_detector.py | 666 +++++++++++++++++++ 5 files changed, 2415 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 assets/logo.svg create mode 100755 path_detector.py create mode 100755 tests/test_path_detector.py 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/README.md b/README.md new file mode 100644 index 0000000..77eebb4 --- /dev/null +++ b/README.md @@ -0,0 +1,466 @@ +
+ +PathScope logo + +# PathScope + +**Passive URL-parameter triage for path-like parameters.** +Point it at URLs you are allowed to review, and it tells you which query parameters *look* like they might be about files or paths — so you can decide what deserves a manual look. + +[![Python](https://img.shields.io/badge/python-3.7%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 results are candidates for manual review — never confirmed vulnerabilities.** +> A flag means "the wording or existing value of this parameter looks path-related". +> It does **not** mean a parameter is exploitable, reachable, or even used by the application. + +--- + +## Why this exists + +URL parameters such as `?file=`, `?page=`, `?template=` or `?download=` are the usual starting +points when reviewing an application for path-handling issues. Most of the noise in that review +comes from deciding *which* parameters are worth looking at first. + +PathScope does that first pass for you — **statically, offline, and without touching the target.** +It reads URLs you already have, parses them locally, and produces a short, ranked list of +parameters that mention paths/files in their names, or whose *existing* values already contain +path-like patterns. + +It is deliberately boring: no payloads, no requests, no clever stuff. + +--- + +## Safety statement + +PathScope is **passive by design**. It: + +- ✅ only analyzes URLs **you explicitly provide** (`--url`, `-i/--input`, or stdin); +- ✅ parses everything **locally** with `urllib.parse` and regular expressions; +- ❌ makes **no HTTP/HTTPS requests**, and **no DNS lookups**; +- ❌ does **not crawl**, scan, fingerprint, or enumerate anything; +- ❌ does **not generate, inject, or send test values**; +- ❌ does **not open, read, or resolve any file or resource named in a URL parameter**; +- ❌ does **not require root** (or `sudo`, or any elevated capability); +- ❌ has **no third-party dependencies**, so nothing is installed from PyPI. + +> **Authorization:** Only analyze URLs you are authorized to review (your own applications, an +> engagement with signed scope, a lab, a CTF you are permitted to work on, or a bug-bounty +> program that allows it). If you are not sure, ask the asset owner first. Analyzing a URL is +> harmless, but acting on what you find may not be — check your scope before testing anything. + +--- + +## Features + +- **Three input modes** — a single URL, a file of URLs, or piped stdin. Sources can be combined. +- **Robust local parsing** — repeated parameters (`?file=a&file=b`), URL-encoded names + (`?%66%69%6c%65=`) and values, blank values, keys without `=`, IPv6 hosts and custom ports. +- **Transparent heuristics** — readable keyword tables and weighted rules in a single file, easy + to tune for your application or threat model. +- **Values hidden by default** — output shows `file=`, and any `user:pass@` in a URL is + masked as `@`; use `--show-values` only when you want values on screen (or in logs). +- **Plain-text output that works when piped** — ANSI colour is used only when stdout is a real + terminal. `NO_COLOR` and `--no-color` are honoured. +- **JSON output** (`--json`) for pipelines, reports and dashboards. +- **Graceful failure** — unreadable files, malformed URLs and malformed lines are reported, not + fatal; duplicates are de-duplicated; blank lines and `#` comments are skipped. +- **Useful exit codes** and a complete `--help`. +- **Tests included** — 97 unit and end-to-end tests, including checks that prove no network + modules are imported and no sockets are used. + +--- + +## Requirements + +| Requirement | Detail | +|---|---| +| Python | 3.7 or newer (tested on 3.11; Kali ships 3.11+) | +| Packages | **none** — standard library only | +| Privileges | ordinary user; **root is not required** | +| Network | not used | + +PathScope is developed and tested on Kali Linux and runs on any Linux, macOS or Windows system +with Python 3.7+ (the test suite is executed on Python 3.11). + +--- + +## Installation (Kali Linux) + +Kali already ships Python 3.11, so there is nothing to install. Clone or copy the files and go: + +```bash +# 1. Get the files (git clone, or copy the folder over) +git clone https://github.com/mrdineshpathro/pathscope.git +cd pathscope + +# 2. Confirm Python +python3 --version + +# 3. Make it executable (optional) and run it +chmod +x path_detector.py +./path_detector.py --help +``` + +Prefer a command on your `PATH`? + +```bash +# Option A: a symlink (no sudo needed if ~/.local/bin is on your PATH) +mkdir -p ~/.local/bin +ln -sf "$PWD/path_detector.py" ~/.local/bin/pathscope +pathscope --url 'https://example.test/view?file=report.pdf' + +# Option B: an alias for the current shell +echo "alias pathscope='python3 $PWD/path_detector.py'" >> ~/.zshrc +source ~/.zshrc # Kali's default shell is zsh; use ~/.bashrc for bash +``` + +> Kali's default user is `kali`. Nothing here needs `sudo`; if a command fails, fix permissions +> in your home directory rather than escalating. + +--- + +## Quick start + +```bash +# Analyse one URL +python3 path_detector.py --url 'https://example.test/view?file=report.pdf' + +# Analyse a file of URLs (one per line) +python3 path_detector.py -i urls.txt + +# Analyse URLs piped on stdin +cat urls.txt | python3 path_detector.py + +# See the existing values too (hidden by default) +python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values + +# Machine-readable output for a report pipeline +python3 path_detector.py -i urls.txt --json > findings.json + +# Combine several URL files +python3 path_detector.py -i day1.txt -i day2.txt + +# Lower the threshold to surface weaker signals +python3 path_detector.py -i urls.txt --min-score 20 +``` + +> **Quote your URLs** when they contain `&`, otherwise your shell will split them into background +> jobs. Single quotes are safest: `--url 'https://host/p?a=1&b=2'`. + +### Example session + +```console +$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf&lang=en&page=2' +PathScope 1.0.0 - passive URL-parameter triage +---------------------------------------------------------------- +GitHub: https://github.com/mrdineshpathro +Instagram: https://www.instagram.com/mr_dineshpatro +Support: https://buymeacoffee.com/mrdineshpathro +Candidates for manual review only: this tool never proves a vulnerability. +No network requests are made. Only analyze URLs you are authorized to review. + +Candidates for manual review +================================================================ +Analyzed 1 URL(s) and 3 distinct parameter(s); 2 candidate(s) at score >= 30. + +#1 file [MEDIUM score 55/100] + Host example.test + URL https://example.test/view?file=&lang=&page= + Parameter file + Value + Why flagged + - name contains path-related keyword 'file' (name score +35) + - value ends with a file-like extension '.pdf' (+20) + +#2 page [LOW score 30/100] + Host example.test + URL https://example.test/view?file=&lang=&page= + Parameter page + Value + Why flagged + - name contains path-related keyword 'page' (name score +30) + +Reminder: candidates for manual review, not confirmed vulnerabilities. No requests were sent and no input was injected. +Values are hidden by default (use --show-values to display them). + +Done: 1 URL(s), 2 candidate(s), 0 line(s) skipped. +``` + +*(At the default `--min-score 30` both entries are reported; raise it, e.g. `--min-score 50`, +if you only want stronger signals such as `file` here.)* + +--- + +## Command-line reference + +``` +python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--json] + [--show-values] [--no-color] [--no-banner] + [--min-score N] [--strict] [--fail-on-none] +``` + +### Input (sources are merged and de-duplicated) + +| Option | Description | +|---|---| +| `--url URL` | Analyze one URL. Repeat the flag to add more. Values starting with `-` are safe. | +| `-i, --input FILE` | Read one URL per line from `FILE`; repeat the flag to read several files. Blank lines and lines starting with `#` are skipped. Use `-` to read stdin explicitly. | +| *(stdin)* | Used automatically when neither `--url` nor `--input` is given, e.g. `cat urls.txt \| python3 path_detector.py`. | + +### Output + +| Option | Description | +|---|---| +| `--json` | Print a single JSON document on stdout. The banner and warnings go to stderr, so `> out.json` stays clean. | +| `--show-values` | Reveal the existing parameter values. Off by default; URLs are shown with `=` masking. | +| `--no-color` | Disable ANSI colour even on a terminal. Colour is automatically off when piped, and `NO_COLOR` is respected. | +| `--no-banner` | Suppress the startup banner (the banner is printed to **stderr**, not stdout). | + +### Heuristics and behaviour + +| Option | Description | +|---|---| +| `--min-score N` | Report parameters with a combined score of at least `N` (0–100, default **30**). | +| `--strict` | Exit `1` if any input line was skipped (malformed URL etc.). | +| `--fail-on-none` | Exit `3` when no candidates were flagged — handy in CI. | +| `-h, --help` | Full help, including examples, exit codes and the project links. | +| `--version` | Print `PathScope ` and exit. | + +### Exit codes + +| Code | Meaning | +|---|---| +| `0` | Analysis completed. Malformed input lines are reported as warnings but are not fatal. | +| `1` | `--strict` was given and at least one input line was malformed/skipped. | +| `2` | Usage error (bad flags), no usable URLs, or an unreadable input file. | +| `3` | No candidates were flagged (only with `--fail-on-none`). | +| `130` | Interrupted with `Ctrl-C`. | + +--- + +## How scoring works + +PathScope combines two independent signals, then clamps the result to **0–100**: + +``` +score = clamp(name_score + value_score + generic_bonus, 0, 100) +``` + +### 1. Name score — 0–50 + +The parameter name is split into lowercase tokens (`fileName` → `file`,`name`; +`user-file_path` → `user`,`file`,`path`), and each token is looked up in `NAME_KEYWORDS` +in [`path_detector.py`](path_detector.py): + +| Weight | Example keywords | +|---|---| +| 30–35 | `file`, `filename`, `filepath`, `path`, `download`, `dir`, `folder`, `template`, `include`, `page`, `basedir` | +| 20–29 | `view`, `layout`, `theme`, `src`, `url`, `uri`, `document`, `config`, `log`, `render`, `doc`, `pg` | +| 10–19 | `dl`, `link`, `inc`, `data`, `mount`, `root`, `action` | + +- **Exact token** → full weight, plus `+5` when the name has multiple tokens + (e.g. `download_file`). +- **Prefix/suffix of the joined name** → discounted weight, so `filedata` still scores but + `profile` (ends in `file`) does not. +- **Weak shapes only** → `+10` for a multi-word name with no keyword, `+5` for a very long name. +- **Generic names** (`image`, `target`, `ref`, `site`, `avatar`, …) score **0 alone** and can only + contribute through the rule below. + +### 2. Value score — 0–50 + +Only values that are **already present** in the URL are inspected — PathScope never generates +one. Each piece of evidence is counted once, even if the value is encoded and decoded forms +overlap. + +| Weight | Evidence in the existing value | +|---|---| +| +25 | Parent-directory sequence `../` or `..\` | +| +20 | URL-encoded `..` (`%2e%2e`), or a known file extension (`.pdf`, `.log`, `.tar.gz`, …) | +| +15 | Encoded slash/backslash (`%2f`, `%5c`), null byte (`%00`), or `/etc` reference | +| +12–15 | Two or more path separators | +| +8–10 | One separator, Windows drive path (`C:\…`), `..` / `./` segment, double encoding | +| +5 | Value starts with `/` (absolute-looking) | +| −10 | Value is a full URL (`https://…`), which is usually a redirect target, not a path | + +### 3. Generic bonus — 0–10 + +Names like `image`, `avatar` or `target` are only interesting when the existing value is +path-like (e.g. `?image=/static/logo.png`). In that case `+10` is added; otherwise the +parameter is ignored entirely. This keeps ordinary tracking parameters out of the report. + +### Interpretation bands + +| Score | Band | Suggested reading | +|---|---|---| +| 70–100 | `HIGH` | Strong textual match — review this parameter first. | +| 50–69 | `MEDIUM` | Likely relevant; confirm it is actually used by the app. | +| 30–49 | `LOW` | Weak signal; review only if time allows or scope demands it. | + +**None of these bands imply exploitability.** They rank reading order, nothing more. + +### Tuning + +All tables and weights live at the top of `path_detector.py` (`NAME_KEYWORDS`, +`GENERIC_NAMES`, `FILE_EXTENSIONS`, and the weights inside `analyze_name` / `analyze_value`). +Add your application's own vocabulary (`?shop=`, `?cms_module=`, `?f=`) or drop keywords +that are noisy for you — it is a single editable file, and the tests still apply. + +--- + +## JSON output + +```json +{ + "tool": "PathScope", + "version": "1.0.0", + "disclaimer": "Candidates for manual review only. PathScope is passive: it makes no network requests, injects no values, and never confirms vulnerabilities.", + "min_score": 30, + "show_values": false, + "summary": { + "urls_analyzed": 1, + "parameters_analyzed": 3, + "candidates": 1, + "skipped_lines": 0 + }, + "findings": [ + { + "index": 1, + "host": "example.test", + "parameter": "file", + "url": "https://example.test/view?file=&lang=", + "value": null, + "occurrences": 1, + "score": 55, + "band": "MEDIUM", + "reasons": [ + "name contains path-related keyword 'file' (name score +35)", + "value ends with a file-like extension '.pdf' (+20)" + ] + } + ], + "links": { + "github": "https://github.com/mrdineshpathro", + "instagram": "https://www.instagram.com/mr_dineshpatro", + "support": "https://buymeacoffee.com/mrdineshpathro" + } +} +``` + +With `--show-values`, `value` contains the existing value and `url` is left unmasked. + +--- + +## Tests + +The suite uses only `unittest` (standard library) and runs fully offline: + +```bash +# From the repository root +python3 -m unittest discover -s tests -v + +# Or run the file directly +python3 tests/test_path_detector.py +``` + +What is covered: + +- tokenising names (`snake_case`, `kebab-case`, `camelCase`, `PascalCase`); +- keyword, prefix/suffix and weak-name scoring; generic-name rules; +- value scoring: extensions, traversal, encoded and double-encoded forms, Windows paths, + absolute paths, full-URL penalty, and the "count each evidence once" rule; +- URL validation (schemes, ports, IPv6, whitespace, malformed input); +- repeated and encoded parameters, merging, sorting, masking; +- input handling: blank lines, comments, duplicates, BOM, unreadable files; +- CLI end-to-end: banner links, `--help`, `--version`, `--json`, `--show-values`, + `--strict`, `--fail-on-none`, exit codes, no ANSI codes when piped; +- **safety:** the module imports only an allow-list of standard-library modules, defines no + root-related calls, and performs no socket operations while analysing URLs. + +--- + +## Limitations (read these) + +- **It is a triage aid, not a scanner.** PathScope reads strings. It cannot tell whether a + parameter is used by the server, validated, ignored, or routed through a WAF. +- **Names and values can lie.** A parameter called `file` may be a harmless enum; a parameter + called `x` may be the actual file handler. Treat the output as a reading order, not an answer. +- **Only query parameters are analysed.** Path segments, JSON bodies, headers and cookies are + out of scope by design. +- **Encodings beyond normal URL encoding** (e.g. UTF-16 percent-encoding, overlong UTF-8) are + not decoded, because decoding them would mean guessing at values. +- **No persistence.** PathScope writes nothing to disk; redirect stdout if you need a report. +- **Not a vulnerability verdict.** A human must verify anything before it is called a finding. + +--- + +## Project layout + +``` +pathscope/ +├── path_detector.py # the tool (standard library only) +├── tests/ +│ └── test_path_detector.py # unittest suite (offline) +├── assets/ +│ └── logo.svg # original repository icon (route + magnifier) +├── README.md +└── LICENSE +``` + +--- + +## FAQ + +**Does PathScope send anything to the URLs?** +No. There is no socket code in the tool. A test asserts that no network modules are imported and +that analysis works with socket functions patched to raise. + +**Why are values hidden by default?** +URLs in bug-bounty reports, tickets and shell history routinely contain tokens, session IDs and +personal data. Masking by default makes it hard to leak them by accident; `--show-values` +is an explicit decision. + +**Can I use it in CI?** +Yes: `python3 path_detector.py -i urls.txt --json --fail-on-none` exits `3` when nothing +path-like is found, which you can map to a warning, and `--strict` exits `1` on malformed input. + +**Does it need root on Kali?** +No. Every code path runs as your normal user; nothing binds a port, changes interface state, or +reads privileged files. + +**Will it find all path-like parameters?** +No. It finds parameters whose names or existing values match the heuristics. Parameters that +never carry a path-like value and have neutral names will not be flagged — that is by design, +to keep the report readable. + +--- + +## Legal + +PathScope is provided for **authorized security review, education and defensive engineering**. +Only analyze URLs you have permission to review, and always confirm scope in writing for +third-party systems. The results are heuristic candidates for manual review, not a statement +about the security of any system. See [LICENSE](LICENSE) (MIT) — the software is provided +"as is", without warranty of any kind. + +--- + +
+ +**GitHub:** https://github.com/mrdineshpathro · +**Instagram:** https://www.instagram.com/mr_dineshpatro · +**Support:** https://buymeacoffee.com/mrdineshpathro + +Built for Kali Linux · Python 3 · standard library only + +
diff --git a/assets/logo.svg b/assets/logo.svg new file mode 100644 index 0000000..bd8256f --- /dev/null +++ b/assets/logo.svg @@ -0,0 +1,78 @@ + + PathScope + A square icon showing a winding route that leads into a magnifying glass, representing passive inspection of path-like URL parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/path_detector.py b/path_detector.py new file mode 100755 index 0000000..85823b5 --- /dev/null +++ b/path_detector.py @@ -0,0 +1,1201 @@ +#!/usr/bin/env python3 +"""PathScope - passive URL-parameter triage for path-like parameters. + +PathScope reads URLs that *you* provide and highlights query parameters whose +names or existing values look as though they might relate to file paths. +Every result is a **candidate for manual review**, never a confirmed +vulnerability. + +Safety model (by design, not by configuration): + * No HTTP requests, no DNS lookups, no crawling, no scanning. + * No test payloads are generated and nothing is sent anywhere. + * No file or resource named in a parameter is opened or resolved. + * No root privileges are used or required. + * Standard library only, so there is nothing to install with pip. + +Exit codes: + 0 analysis completed normally (malformed lines are warned about) + 1 --strict was given and at least one input line was skipped + 2 usage error, unreadable input file, or no usable URLs + 3 no candidates were flagged (only with --fail-on-none) + 130 interrupted with Ctrl-C + +Usage: + python3 path_detector.py --url 'https://example.test/view?file=report.pdf' + python3 path_detector.py -i urls.txt + cat urls.txt | python3 path_detector.py +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +import unicodedata +from collections import OrderedDict +from dataclasses import dataclass, field +from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple +from urllib.parse import unquote, unquote_plus, urlsplit, urlunsplit + +__version__ = "1.0.0" +PROGRAM = "PathScope" + +# --------------------------------------------------------------------------- +# Banner. These links are printed exactly as given. They are never opened and +# never contacted; PathScope makes no network requests of any kind. +# --------------------------------------------------------------------------- +GITHUB_URL = "https://github.com/mrdineshpathro" +INSTAGRAM_URL = "https://www.instagram.com/mr_dineshpatro" +SUPPORT_URL = "https://buymeacoffee.com/mrdineshpathro" + +BANNER_LINKS: Tuple[Tuple[str, str], ...] = ( + ("GitHub", GITHUB_URL), + ("Instagram", INSTAGRAM_URL), + ("Support", SUPPORT_URL), +) +BANNER_DISCLAIMER = ( + "Candidates for manual review only: this tool never proves a vulnerability.", + "No network requests are made. Only analyze URLs you are authorized to review.", +) + +EXIT_OK = 0 +EXIT_STRICT_SKIPS = 1 +EXIT_USAGE = 2 +EXIT_NO_CANDIDATES = 3 +EXIT_INTERRUPTED = 130 + +# --------------------------------------------------------------------------- +# Heuristics. Everything below is deliberately plain and easy to edit. +# +# Final score = clamp(name_score + value_score + generic_bonus, 0, 100) +# * name_score 0-50 from NAME_KEYWORDS / weak name shapes +# * value_score 0-50 from existing values only (never generated) +# * generic_bonus 0-10 for generic names (image, target, ...) whose value +# is path-like; generic names never score alone. +# A parameter is reported when the final score >= --min-score (default 30). +# --------------------------------------------------------------------------- + +NAME_KEYWORDS: Dict[str, int] = { + # files / downloads + "file": 35, + "filename": 35, + "file_name": 35, + "filepath": 35, + "file_path": 35, + "document": 25, + "doc": 20, + "download": 35, + "dl": 15, + "attachment": 30, + "upload": 25, + "export": 25, + "import": 15, + "archive": 20, + "backup": 20, + # paths / directories + "path": 35, + "dir": 30, + "directory": 30, + "folder": 30, + "root": 15, + "base": 15, + "basedir": 30, + "base_dir": 30, + "basepath": 30, + "base_path": 30, + "uri": 20, + "url": 20, + "link": 15, + "dest": 20, + "destination": 20, + "source": 20, + "src": 20, + "resource": 20, + "asset": 20, + "media": 20, + "storage": 20, + "mount": 15, + # pages / templates / includes / views + "page": 30, + "pg": 20, + "view": 20, + "display": 15, + "screen": 10, + "layout": 20, + "theme": 20, + "tpl": 30, + "template": 30, + "include": 30, + "inc": 15, + "viewfile": 30, + "view_file": 30, + "load": 20, + "action": 15, + "module": 15, + # code / config / logs / data files + "script": 25, + "lang": 20, + "language": 15, + "locale": 15, + "translation": 15, + "config": 20, + "conf": 20, + "settings": 15, + "log": 20, + "logfile": 30, + "log_file": 30, + "stylesheet": 30, + "css": 15, + "js": 15, + "style": 15, + "data": 10, + "db": 15, + "database": 15, + "report": 20, + "render": 20, +} + +PREFIX_DISCOUNT = 7 +SUFFIX_DISCOUNT = 12 +NAME_CAP = 50 +VALUE_CAP = 50 +GENERIC_BONUS = 10 + +# Generic names: by themselves they are not path-related, but a path-like +# existing value makes them worth a look (e.g. image=/static/logo.png). +GENERIC_NAMES = frozenset( + { + "image", + "img", + "photo", + "avatar", + "target", + "ref", + "referer", + "referrer", + "site", + "key", + "callback", + "filetarget", + } +) + +FILE_EXTENSIONS = 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 = ("tar.gz", "tar.bz2", "tar.xz") + +WINDOWS_PATH_RE = re.compile(r"^[A-Za-z]:[/\\].+") + +COLOR_CODES = { + "bold": "1", + "dim": "2", + "red": "31", + "green": "32", + "yellow": "33", + "blue": "34", + "magenta": "35", + "cyan": "36", + "grey": "90", +} + + +# --------------------------------------------------------------------------- +# Small utilities +# --------------------------------------------------------------------------- +def sanitize_text(value: str) -> str: + """NFC-normalise text and drop control characters (keeps output terminal-safe).""" + 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: + if len(text) <= limit: + return text + return text[: max(0, limit - 1)] + "\u2026" + + +def normalize_name(name: str) -> str: + """Lowercase a parameter name and unify separators: 'userId' stays camel-ish.""" + return name.strip().lower().replace("-", "_").replace(" ", "_") + + +def tokenize_name(name: str) -> List[str]: + """Split a parameter name into lowercase tokens. + + 'fileName' -> ['file', 'name'] + 'user-file_path' -> ['user', 'file', 'path'] + 'FILES' -> ['files'] + """ + parts: List[str] = [] + current = "" + for char in name: + if char.isupper() and current and not current[-1].isupper(): + parts.append(current) + current = char + else: + current += char + if current: + parts.append(current) + + tokens: List[str] = [] + for part in parts: + for piece in normalize_name(part).split("_"): + if piece: + tokens.append(piece) + return tokens + + +def extension_of(text: str) -> Optional[str]: + """Return a known file extension at the end of the value, if any.""" + cleaned = text.strip().rstrip(".,;:!?") + last = re.split(r"[/\\]", cleaned)[-1] + lowered = last.lower() + for multi in MULTI_EXTENSIONS: + if lowered.endswith("." + multi): + return multi + if "." not in lowered: + return None + candidate = lowered.rsplit(".", 1)[1] + if candidate in FILE_EXTENSIONS: + return candidate + return None + + +# --------------------------------------------------------------------------- +# Name heuristic +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class NameAnalysis: + """Outcome of analysing a parameter name.""" + + score: int = 0 + reason: Optional[str] = None + keyword: Optional[str] = None + generic: bool = False + weak: bool = False + + +def analyze_name(name: str) -> NameAnalysis: + """Score a parameter name for path-related meaning (0-50).""" + tokens = tokenize_name(name) + joined = "".join(tokens) + + best_weight = 0 + best_keyword: Optional[str] = None + + # Exact token matches: "file", "path", "dir", ... + for token in tokens: + weight = NAME_KEYWORDS.get(token, 0) + if weight > best_weight: + best_weight, best_keyword = weight, token + + # Compound key matches: "basepath", "viewfile", ... + if best_weight == 0 and joined: + weight = NAME_KEYWORDS.get(joined, 0) + if weight: + best_weight, best_keyword = weight, joined + + # Prefix / suffix matches get a discount: "filedata" yes, "hotfile" only + # weakly (and not at all at the default threshold). + if best_weight == 0 and joined: + for keyword, weight in NAME_KEYWORDS.items(): + if len(keyword) < 4: + continue + if joined.startswith(keyword) and weight > PREFIX_DISCOUNT: + candidate = weight - PREFIX_DISCOUNT + if candidate > best_weight: + best_weight, best_keyword = candidate, keyword + elif joined.endswith(keyword) and weight > SUFFIX_DISCOUNT: + candidate = weight - SUFFIX_DISCOUNT + if candidate > best_weight: + best_weight, best_keyword = candidate, keyword + + if best_keyword is not None: + bonus = 5 if len(tokens) > 1 else 0 + reason = ( + f"name contains path-related keyword '{best_keyword}' " + f"(name score +{best_weight}{f', +{bonus} for multi-word name' if bonus else ''})" + ) + return NameAnalysis( + score=min(NAME_CAP, best_weight + bonus), + reason=reason, + keyword=best_keyword, + ) + + lowered = normalize_name(name) + if lowered in GENERIC_NAMES: + return NameAnalysis(generic=True) + + if "_" in lowered or "-" in name: + return NameAnalysis( + score=10, + reason="multi-word name with no obvious path keyword (weak signal, +10)", + weak=True, + ) + if len(lowered) > 24: + return NameAnalysis( + score=5, + reason="unusually long parameter name (weak signal, +5)", + weak=True, + ) + return NameAnalysis() + + +# --------------------------------------------------------------------------- +# Value heuristic (existing values only - PathScope never generates input) +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class ValueAnalysis: + """Outcome of analysing an existing parameter value.""" + + score: int = 0 + reasons: Tuple[str, ...] = () + + +ENCODED_PATH_MARKERS = ("%2e%2e", "%2f", "%5c", "%252e", "%252f") + + +def analyze_value(raw_value: str, decoded: Optional[str] = None) -> ValueAnalysis: + """Score an existing value for path-like or encoded path-like content (0-50). + + ``raw_value`` is exactly what appeared in the URL; ``decoded`` is the + single-decoded form (passed in by the caller to avoid decoding twice). + Each piece of evidence is counted once: when the raw value already shows + encoded path markers, the structural layer is skipped so the same pattern + is not credited twice. + """ + if not raw_value and not decoded: + return ValueAnalysis() + + if decoded is None: + decoded = unquote(raw_value) + raw_value = raw_value or "" + decoded = decoded or "" + lowered_raw = raw_value.lower() + encoded_path = any(marker in lowered_raw for marker in ENCODED_PATH_MARKERS) + + score = 0 + reasons: List[str] = [] + seen = set() + + def add(key: str, weight: int, reason: str) -> None: + nonlocal score + if key in seen: + return + seen.add(key) + score += weight + reasons.append(reason) + + # 1. Encoding and traversal indicators, evaluated on raw and decoded forms. + if not encoded_path and ("../" in decoded or "..\\" in decoded): + add( + "traversal", + 25, + "value contains a parent-directory sequence ('../' or '..\\') (+25)", + ) + if "%2e%2e" in lowered_raw: + add("pct-dotdot", 20, "value contains URL-encoded '..' (%2e%2e) (+20)") + if "%2f" in lowered_raw: + add("pct-slash", 15, "value contains URL-encoded slash (%2f) (+15)") + if "%5c" in lowered_raw: + add("pct-backslash", 15, "value contains URL-encoded backslash (%5c) (+15)") + if "%00" in lowered_raw: + add("nul-byte", 15, "value contains a null-byte encoding (%00) (+15)") + if "%252e" in lowered_raw or "%252f" in lowered_raw: + add("double-encoded", 10, "value contains double-encoded path characters (+10)") + if lowered_raw.startswith("/etc") or "/etc/" in lowered_raw: + add("system-path", 15, "value references a common system path (/etc) (+15)") + if "\\windows\\" in lowered_raw: + add("windows-dir", 10, "value references a Windows system directory (+10)") + + # 2. Structural shape of the decoded value. + structure = decoded + is_full_url = "://" in structure + if is_full_url: + add("full-url", -10, "value is a full URL rather than a local path (-10)") + + if not encoded_path: + if WINDOWS_PATH_RE.match(structure): + add("windows-drive", 10, "value looks like a Windows drive path (+10)") + + normalized = structure.replace("\\", "/") + if normalized in {"..", "../"} or normalized.startswith("../") or "/../" in normalized: + add( + "dotdot", + 10, + "value is or contains a parent-directory ('..') sequence (+10)", + ) + elif normalized in {".", "./"} or normalized.startswith("./"): + add( + "dot", + 5, + "value is or starts with a current-directory ('./') sequence (+5)", + ) + + if not is_full_url: + separators = normalized.count("/") + if separators == 1: + add("depth-1", 8, "value contains a relative path segment (+8)") + elif separators == 2: + add("depth-2", 12, "value contains two path separators (+12)") + elif separators >= 3: + add("depth-3", 15, "value contains three or more path separators (+15)") + if normalized.startswith("/") and len(normalized) > 1: + add( + "absolute", + 5, + "value starts with a path separator (absolute-looking path) (+5)", + ) + + ext = extension_of(structure) + if ext: + add("extension", 20, f"value ends with a file-like extension '.{ext}' (+20)") + + return ValueAnalysis(score=max(0, min(VALUE_CAP, score)), reasons=tuple(reasons)) + + +# --------------------------------------------------------------------------- +# URL parsing and analysis +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class URLTarget: + """Locally parsed URL metadata (no network activity involved).""" + + raw: str + scheme: str + host: str + port: Optional[int] + path: str + + +class URLParseError(ValueError): + """Raised when a line is not a usable HTTP(S) URL.""" + + +def parse_target(raw: str) -> URLTarget: + """Validate a URL string locally. Never resolves or contacts the host.""" + text = sanitize_text(raw).strip() + if not text: + raise URLParseError("blank input") + if any(char.isspace() for char in text): + raise URLParseError("contains whitespace") + if any(ord(char) < 32 or ord(char) == 127 for char in raw): + 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 URLTarget( + raw=text, + scheme=scheme, + host=host, + port=port, + path=parts.path or "/", + ) + + +def display_host(target: URLTarget) -> str: + if target.port and target.port not in (80, 443): + return f"{target.host}:{target.port}" + return target.host + + +def split_query(query: str) -> List[Tuple[str, str, str]]: + """Split a raw query string into (decoded name, raw value, decoded value). + + Kept deliberately literal (manual split on '&' and '=') so that: + * repeated parameters are preserved, + * URL-encoded names/values are visible both raw and decoded, + * PathScope never guesses at values it was not given. + """ + pairs: List[Tuple[str, str, str]] = [] + if not query: + return pairs + for chunk in query.split("&"): + if not chunk: + continue + raw_name, separator, raw_value = chunk.partition("=") + try: + name = unquote_plus(raw_name) + value = unquote_plus(raw_value) + except (UnicodeError, ValueError): + name, value = raw_name, raw_value + pairs.append((sanitize_text(name), raw_value, sanitize_text(value))) + return pairs + + +def mask_credentials(netloc: str) -> str: + """Replace 'user:pass@' with '@' so secrets are not displayed.""" + if "@" not in netloc: + return netloc + host = netloc.rsplit("@", 1)[1] + return f"@{host}" + + +def mask_url(raw: str) -> str: + """Return the URL with query/fragment values and credentials hidden.""" + parts = urlsplit(raw) + pairs: List[str] = [] + for chunk in parts.query.split("&"): + if not chunk: + continue + if "=" in chunk: + name = chunk.split("=", 1)[0] + pairs.append(f"{name}=") + else: + pairs.append(chunk) + fragment = "" if parts.fragment else "" + return urlunsplit( + ( + parts.scheme, + mask_credentials(parts.netloc), + parts.path, + "&".join(pairs), + fragment, + ) + ) + + +@dataclass +class ParameterFinding: + """One parameter that passed the heuristic threshold.""" + + url: str + host: str + parameter: str + value: Optional[str] + reasons: Tuple[str, ...] + score: int + occurrences: int = 1 + index: int = 0 + + @property + def band(self) -> str: + return score_band(self.score) + + +@dataclass +class _ParameterGroup: + parameter: str + occurrences: int = 0 + values: List[str] = field(default_factory=list) + raw_values: List[str] = field(default_factory=list) + + +def analyze_url(raw: str, min_score: int = 30) -> List[ParameterFinding]: + """Analyse one URL and return its flagged parameters (best first). + + This is purely local string analysis: nothing is requested, resolved, + opened or injected. + """ + raw = sanitize_text(raw).strip() + target = parse_target(raw) + parts = urlsplit(raw) + + groups: "OrderedDict[str, _ParameterGroup]" = OrderedDict() + for name, raw_value, value in split_query(parts.query): + if not name: + continue + canonical = "_".join(tokenize_name(name)) or name.lower() + group = groups.get(canonical) + if group is None: + group = groups[canonical] = _ParameterGroup(parameter=name) + group.occurrences += 1 + group.values.append(value) + group.raw_values.append(raw_value) + + findings: List[ParameterFinding] = [] + host = display_host(target) + # Show URL credentials as masked, even when parameter values are shown. + safe_url = mask_credentials(parts.netloc) + if safe_url != parts.netloc: + safe_url = urlunsplit( + (parts.scheme, safe_url, parts.path, parts.query, parts.fragment) + ) + else: + safe_url = raw + + for group in groups.values(): + name_analysis = analyze_name(group.parameter) + value_analyses = [ + analyze_value(raw_value, decoded=group.values[index]) + for index, raw_value in enumerate(group.raw_values) + ] + + best_index = 0 + for index, analysis in enumerate(value_analyses): + if analysis.score > value_analyses[best_index].score: + best_index = index + best_value_analysis = value_analyses[best_index] + best_value = group.values[best_index] + + generic_bonus = 0 + reasons: List[str] = [] + if name_analysis.reason: + reasons.append(name_analysis.reason) + if name_analysis.generic: + if best_value_analysis.score >= 20: + generic_bonus = GENERIC_BONUS + reasons.append( + f"generic name '{group.parameter}' becomes relevant because its " + f"value is path-like (+{GENERIC_BONUS})" + ) + else: + continue # generic names never stand alone + reasons.extend(best_value_analysis.reasons) + + score = name_analysis.score + best_value_analysis.score + generic_bonus + score = max(0, min(100, score)) + if score <= 0 or score < min_score: + continue + + findings.append( + ParameterFinding( + url=safe_url, + host=host, + parameter=group.parameter, + value=best_value, + reasons=tuple(reasons) or (f"combined heuristic score {score}",), + score=score, + occurrences=group.occurrences, + ) + ) + + findings.sort(key=lambda finding: (-finding.score, finding.parameter.lower())) + for index, finding in enumerate(findings, start=1): + finding.index = index + return findings + + +def count_parameters(raw: str) -> int: + """Count distinct, non-empty parameter names in a URL (locally).""" + parts = urlsplit(raw) + return len({name for name, _raw, _decoded in split_query(parts.query) if name}) + + +# --------------------------------------------------------------------------- +# Input handling +# --------------------------------------------------------------------------- +class InputError(RuntimeError): + """Raised for unreadable input files.""" + + +def read_input_file(path: str) -> List[str]: + try: + with open(path, "r", encoding="utf-8-sig", errors="replace") as handle: + return handle.read().splitlines() + except OSError as exc: + raise InputError( + f"cannot read input file '{path}': {exc.strerror or exc}" + ) from exc + + +def clean_input_lines( + lines: Iterable[str], label: str = "line" +) -> Tuple[List[str], List[str]]: + """Drop blanks/comments/duplicates, validate URLs. Returns (urls, warnings).""" + urls: List[str] = [] + warnings: List[str] = [] + seen = 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: + parse_target(candidate) + except URLParseError as exc: + warnings.append( + f"{label} {line_number}: skipped malformed URL ({exc}): " + f"{truncate(candidate, 100)}" + ) + continue + seen.add(candidate) + urls.append(candidate) + return urls, warnings + + +def dedupe(items: Iterable[str]) -> List[str]: + result: List[str] = [] + seen = set() + for item in items: + if item not in seen: + seen.add(item) + result.append(item) + return result + + +def stdin_has_data() -> bool: + try: + return sys.stdin is not None and not sys.stdin.isatty() + except Exception: # pragma: no cover - defensive only + return False + + +def read_stdin_lines() -> List[str]: + try: + return sys.stdin.read().splitlines() + except (OSError, ValueError): + return [] + + +# --------------------------------------------------------------------------- +# Rendering +# --------------------------------------------------------------------------- +def stream_supports_color(stream, disabled: bool = False) -> bool: + if disabled or os.environ.get("NO_COLOR"): + return False + if os.environ.get("TERM", "") == "dumb": + return False + try: + return bool(stream.isatty()) + except Exception: # pragma: no cover - defensive only + return False + + +class Palette: + """ANSI colours, used only when the target stream is an interactive terminal.""" + + def __init__(self, enabled: bool) -> None: + self.enabled = enabled + + def paint(self, style: str, text: str) -> str: + if not self.enabled: + return text + code = COLOR_CODES[style] + return f"\x1b[{code}m{text}\x1b[0m" + + def __getattr__(self, style: str) -> Callable[[str], str]: + if style not in COLOR_CODES: + raise AttributeError(style) + + def apply(text: str) -> str: + return self.paint(style, text) + + return apply + + +def render_banner(colors: Palette) -> str: + title = colors.bold(colors.cyan(f"{PROGRAM} {__version__} - passive URL-parameter triage")) + lines = [title, colors.grey("-" * 64)] + for label, url in BANNER_LINKS: + lines.append(f"{colors.bold(label + ':')} {colors.blue(url)}") + for line in BANNER_DISCLAIMER: + lines.append(colors.yellow(line)) + return "\n".join(lines) + + +def score_band(score: int) -> str: + if score >= 70: + return "HIGH" + if score >= 50: + return "MEDIUM" + return "LOW" + + +def render_report( + findings: Sequence[ParameterFinding], + *, + colors: Palette, + show_values: bool, + urls_analyzed: int, + parameters_analyzed: int, + min_score: int, + skipped: int, +) -> str: + lines: List[str] = [] + lines.append(colors.bold("Candidates for manual review")) + lines.append(colors.grey("=" * 64)) + lines.append( + f"Analyzed {urls_analyzed} URL(s) and {parameters_analyzed} distinct " + f"parameter(s); {len(findings)} candidate(s) at score >= {min_score}." + ) + if skipped: + lines.append(colors.yellow(f"Skipped {skipped} malformed input line(s).")) + lines.append("") + + if not findings: + lines.append( + colors.green( + "No path-like parameter candidates were flagged. " + "This is not proof that the application is safe." + ) + ) + else: + band_colors = {"HIGH": colors.red, "MEDIUM": colors.yellow, "LOW": colors.cyan} + for finding in findings: + band = finding.band + heading = ( + f"#{finding.index} {colors.bold(finding.parameter)} " + f"{band_colors[band](f'[{band} score {finding.score}/100]')}" + ) + lines.append(heading) + lines.append(f" {colors.grey('Host')} {finding.host}") + shown_url = finding.url if show_values else mask_url(finding.url) + lines.append(f" {colors.grey('URL')} {truncate(shown_url, 160)}") + if show_values: + value_text = truncate(finding.value or "", 120) or "" + else: + value_text = colors.grey("") + lines.append(f" {colors.grey('Parameter')} {finding.parameter}") + lines.append(f" {colors.grey('Value')} {value_text}") + if finding.occurrences > 1: + lines.append( + f" {colors.grey('Repeated')} x{finding.occurrences} " + "(best-scoring existing value shown)" + ) + lines.append(f" {colors.grey('Why flagged')}") + for reason in finding.reasons: + lines.append(f" - {reason}") + lines.append("") + + lines.append( + colors.grey( + "Reminder: candidates for manual review, not confirmed vulnerabilities. " + "No requests were sent and no input was injected." + ) + ) + if not show_values: + lines.append( + colors.grey( + "Values are hidden by default (use --show-values to display them)." + ) + ) + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- +@dataclass +class RunConfig: + urls: List[str] + skipped: List[str] + json: bool = False + show_values: bool = False + no_banner: bool = False + no_color: bool = False + min_score: int = 30 + strict: bool = False + fail_on_none: bool = False + banner_printed: bool = False + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="path_detector.py", + description=( + "PathScope: passive triage of URL query parameters whose names or " + "existing values look path-like. Results are candidates for manual " + "review, never confirmed vulnerabilities. PathScope makes no network " + "requests and injects no test values." + ), + epilog=( + "examples:\n" + " python3 path_detector.py --url 'https://example.test/view?file=report.pdf'\n" + " python3 path_detector.py -i urls.txt\n" + " cat urls.txt | python3 path_detector.py\n" + " python3 path_detector.py -i urls.txt --json --show-values\n" + "\n" + "exit codes:\n" + " 0 completed 1 skipped lines with --strict 2 usage/input error\n" + " 3 no candidates with --fail-on-none 130 interrupted\n" + "\n" + "links (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 (merged and de-duplicated)") + source.add_argument( + "--url", + action="append", + default=[], + metavar="URL", + help="URL to analyze; may be repeated. Quote URLs containing '&'.", + ) + source.add_argument( + "-i", + "--input", + action="append", + default=[], + metavar="FILE", + help="read URLs from FILE (one per line); may be repeated. '-' reads " + "stdin. Blank lines and lines starting with '#' are skipped.", + ) + + output = parser.add_argument_group("output") + output.add_argument( + "--json", + action="store_true", + help="print machine-readable JSON on stdout (banner stays on stderr)", + ) + output.add_argument( + "--show-values", + action="store_true", + help="reveal existing parameter values; hidden/masked by default", + ) + output.add_argument( + "--no-color", + action="store_true", + help="disable ANSI colour even on a terminal", + ) + output.add_argument( + "--no-banner", + action="store_true", + help="do not print the startup banner and links", + ) + + heuristic = parser.add_argument_group("heuristics") + heuristic.add_argument( + "--min-score", + type=int, + default=30, + metavar="N", + help="report parameters scoring at least N (0-100, default: 30)", + ) + + behaviour = parser.add_argument_group("behaviour") + behaviour.add_argument( + "--strict", + action="store_true", + help="exit 1 if any input line was malformed or skipped", + ) + behaviour.add_argument( + "--fail-on-none", + action="store_true", + help="exit 3 when no candidates are flagged", + ) + return parser + + +def collect_inputs(parser: argparse.ArgumentParser, args: argparse.Namespace + ) -> Tuple[List[str], List[str]]: + """Merge --url, -i/--input and (when no source is given) piped stdin. + + Stdin is auto-detected only when neither --url nor -i/--input is present, + so an explicit source never blocks waiting for piped data. + """ + urls: List[str] = [] + warnings: List[str] = [] + stdin_consumed = False + + for path in args.input: + if path == "-": + if not stdin_has_data(): + parser.error("--input '-' was given but stdin is a terminal") + stdin_urls, stdin_warnings = clean_input_lines( + read_stdin_lines(), label="stdin" + ) + stdin_consumed = True + urls.extend(stdin_urls) + warnings.extend(stdin_warnings) + continue + try: + file_lines = read_input_file(path) + except InputError as exc: + parser.error(str(exc)) + file_urls, file_warnings = clean_input_lines(file_lines, label=path) + urls.extend(file_urls) + warnings.extend(file_warnings) + + url_values, url_warnings = clean_input_lines(args.url, label="--url") + urls.extend(url_values) + warnings.extend(url_warnings) + + if not stdin_consumed and not args.url and not args.input and stdin_has_data(): + piped_urls, piped_warnings = clean_input_lines(read_stdin_lines(), label="stdin") + urls.extend(piped_urls) + warnings.extend(piped_warnings) + + return dedupe(urls), warnings + + +def make_payload(config: RunConfig, findings: Sequence[ParameterFinding], + urls_analyzed: int, parameters_analyzed: int) -> dict: + return { + "tool": PROGRAM, + "version": __version__, + "disclaimer": ( + "Candidates for manual review only. PathScope is passive: it makes no " + "network requests, injects no values, and never confirms vulnerabilities." + ), + "min_score": config.min_score, + "show_values": config.show_values, + "summary": { + "urls_analyzed": urls_analyzed, + "parameters_analyzed": parameters_analyzed, + "candidates": len(findings), + "skipped_lines": len(config.skipped), + }, + "findings": [ + { + "index": finding.index, + "host": finding.host, + "parameter": finding.parameter, + "url": finding.url if config.show_values else mask_url(finding.url), + "value": finding.value if config.show_values else None, + "occurrences": finding.occurrences, + "score": finding.score, + "band": finding.band, + "reasons": list(finding.reasons), + } + for finding in findings + ], + "links": { + "github": GITHUB_URL, + "instagram": INSTAGRAM_URL, + "support": SUPPORT_URL, + }, + } + + +def run(config: RunConfig, stdout=None, stderr=None) -> int: + stdout = stdout if stdout is not None else sys.stdout + stderr = stderr if stderr is not None else sys.stderr + + if not config.no_banner and not config.banner_printed: + print( + render_banner(Palette(stream_supports_color(stderr, disabled=config.no_color))), + file=stderr, + ) + print("", file=stderr) + config.banner_printed = True + + out_colors = Palette(stream_supports_color(stdout, disabled=config.no_color)) + + for warning in config.skipped: + print(f"warning: {warning}", file=stderr) + + if not config.urls: + print("error: no usable URLs to analyze.", file=stderr) + print( + " Use --url URL, -i/--input FILE, or pipe URLs on stdin.", + file=stderr, + ) + print(" Try: python3 path_detector.py --help", file=stderr) + return EXIT_USAGE + + findings: List[ParameterFinding] = [] + urls_analyzed = 0 + parameters_analyzed = 0 + for url in config.urls: + try: + url_findings = analyze_url(url, min_score=config.min_score) + except URLParseError as exc: # defensive: validated earlier + print(f"warning: skipped URL ({exc})", file=stderr) + continue + urls_analyzed += 1 + parameters_analyzed += count_parameters(url) + findings.extend(url_findings) + + findings.sort(key=lambda finding: (-finding.score, finding.host, finding.parameter)) + for index, finding in enumerate(findings, start=1): + finding.index = index + + if config.json: + payload = make_payload(config, findings, urls_analyzed, parameters_analyzed) + json.dump(payload, stdout, indent=2, ensure_ascii=False) + stdout.write("\n") + else: + report = render_report( + findings, + colors=out_colors, + show_values=config.show_values, + urls_analyzed=urls_analyzed, + parameters_analyzed=parameters_analyzed, + min_score=config.min_score, + skipped=len(config.skipped), + ) + print(report, file=stdout) + print( + out_colors.grey( + f"\nDone: {urls_analyzed} URL(s), {len(findings)} candidate(s), " + f"{len(config.skipped)} line(s) skipped." + ), + file=stdout, + ) + + if config.strict and config.skipped: + return EXIT_STRICT_SKIPS + if config.fail_on_none and not findings: + return EXIT_NO_CANDIDATES + return EXIT_OK + + +def main(argv: Optional[Sequence[str]] = None, stdout=None, stderr=None) -> int: + parser = build_parser() + stderr = stderr if stderr is not None else sys.stderr + argv_list = list(sys.argv[1:] if argv is None else argv) + + # The banner is part of every invocation (including --help/--version). + if "--no-banner" not in argv_list: + banner_colors = Palette( + stream_supports_color(stderr, disabled="--no-color" in argv_list) + ) + print(render_banner(banner_colors), file=stderr) + print("", file=stderr) + banner_printed = "--no-banner" not in argv_list + + args = parser.parse_args(argv_list) + + if not 0 <= args.min_score <= 100: + parser.error("--min-score must be between 0 and 100") + + config = RunConfig(urls=[], skipped=[]) + config.json = args.json + config.show_values = args.show_values + config.no_banner = args.no_banner + config.no_color = args.no_color + config.min_score = args.min_score + config.strict = args.strict + config.fail_on_none = args.fail_on_none + config.banner_printed = banner_printed + + try: + config.urls, config.skipped = collect_inputs(parser, args) + except KeyboardInterrupt: + print("\ninterrupted", file=stderr) + return EXIT_INTERRUPTED + + try: + return run(config, stdout=stdout, stderr=stderr) + except KeyboardInterrupt: + print("\ninterrupted", file=stderr) + return EXIT_INTERRUPTED + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_path_detector.py b/tests/test_path_detector.py new file mode 100755 index 0000000..5b68a90 --- /dev/null +++ b/tests/test_path_detector.py @@ -0,0 +1,666 @@ +#!/usr/bin/env python3 +"""Unit tests for PathScope. + +Run with: + python3 -m unittest discover -s tests -v +or: + python3 tests/test_path_detector.py + +The tests are split into four groups: + 1. heuristic unit tests (names, values, extensions), + 2. URL parsing / analysis tests (repeats, encoding, masking), + 3. input handling tests (files, blank lines, duplicates), + 4. end-to-end CLI tests, including safety guarantees. + +Everything runs offline: PathScope never opens a socket, and one test proves it. +""" + +from __future__ import annotations + +import ast +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)) + +import path_detector as pd # noqa: E402 (path setup must happen first) + +BANNER_LINKS = ( + ("GitHub", "https://github.com/mrdineshpathro"), + ("Instagram", "https://www.instagram.com/mr_dineshpatro"), + ("Support", "https://buymeacoffee.com/mrdineshpathro"), +) + + +def run_cli(*args: str, stdin: str = "", timeout: int = 30) -> subprocess.CompletedProcess: + """Run the real CLI as a subprocess (no TTY, 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), + ) + + +# --------------------------------------------------------------------------- +# 1. Heuristic unit tests +# --------------------------------------------------------------------------- +class TestTokenizeName(unittest.TestCase): + def test_snake_case(self): + self.assertEqual(pd.tokenize_name("file_path"), ["file", "path"]) + + def test_kebab_case(self): + self.assertEqual(pd.tokenize_name("user-file-name"), ["user", "file", "name"]) + + def test_camel_case(self): + self.assertEqual(pd.tokenize_name("fileName"), ["file", "name"]) + + def test_pascal_case(self): + self.assertEqual(pd.tokenize_name("DownloadFile"), ["download", "file"]) + + def test_mixed_noise(self): + self.assertEqual(pd.tokenize_name(" TEMPLATE__id "), ["template", "id"]) + + def test_empty(self): + self.assertEqual(pd.tokenize_name(""), []) + + +class TestAnalyzeName(unittest.TestCase): + def test_strong_keyword(self): + analysis = pd.analyze_name("file") + self.assertGreaterEqual(analysis.score, 30) + self.assertEqual(analysis.keyword, "file") + + def test_compound_keyword(self): + analysis = pd.analyze_name("basepath") + self.assertGreaterEqual(analysis.score, 25) + + def test_camel_compound(self): + analysis = pd.analyze_name("downloadFile") + self.assertGreaterEqual(analysis.score, 35) + + def test_prefix_match(self): + analysis = pd.analyze_name("filedata") + self.assertIsNotNone(analysis.reason) + self.assertGreater(analysis.score, 0) + + def test_generic_name_is_not_a_keyword(self): + analysis = pd.analyze_name("image") + self.assertTrue(analysis.generic) + self.assertEqual(analysis.score, 0) + self.assertIsNone(analysis.reason) + + def test_unrelated_simple_name(self): + analysis = pd.analyze_name("q") + self.assertEqual(analysis.score, 0) + + def test_weak_multipart_name(self): + analysis = pd.analyze_name("some_thing") + self.assertTrue(analysis.weak) + self.assertLess(analysis.score, 15) + + def test_unrelated_name_does_not_mention_exploit(self): + analysis = pd.analyze_name("path") + self.assertNotIn("exploit", (analysis.reason or "").lower()) + + +class TestExtensionOf(unittest.TestCase): + def test_common_extension(self): + self.assertEqual(pd.extension_of("report.pdf"), "pdf") + + def test_path_extension(self): + self.assertEqual(pd.extension_of("../../etc/shadow.txt"), "txt") + + def test_multi_extension(self): + self.assertEqual(pd.extension_of("backup.tar.gz"), "tar.gz") + + def test_no_extension(self): + self.assertIsNone(pd.extension_of("justwords")) + + def test_unknown_extension(self): + self.assertIsNone(pd.extension_of("malware.xyzzy")) + + +class TestAnalyzeValue(unittest.TestCase): + def test_file_name(self): + analysis = pd.analyze_value("report.pdf") + self.assertGreaterEqual(analysis.score, 20) + self.assertTrue(any("pdf" in reason for reason in analysis.reasons)) + + def test_plain_word(self): + self.assertEqual(pd.analyze_value("hello").score, 0) + + def test_empty_value(self): + self.assertEqual(pd.analyze_value("").score, 0) + + def test_traversal(self): + analysis = pd.analyze_value("../../etc/passwd") + self.assertGreaterEqual(analysis.score, 40) + self.assertTrue(any("parent-directory" in reason for reason in analysis.reasons)) + + def test_encoded_traversal_counts_once(self): + encoded = pd.analyze_value("%2e%2e%2f%2e%2e%2fetc%2fpasswd") + decoded = pd.analyze_value("../../etc/passwd") + self.assertGreaterEqual(encoded.score, 30) + self.assertLessEqual(encoded.score, decoded.score) + + def test_encoded_slash(self): + analysis = pd.analyze_value("%2fadmin%2fpanel") + self.assertGreater(analysis.score, 0) + self.assertTrue(any("%2f" in reason for reason in analysis.reasons)) + + def test_double_encoded(self): + analysis = pd.analyze_value("%252e%252e%252f") + self.assertTrue(any("double-encoded" in reason for reason in analysis.reasons)) + + def test_absolute_path(self): + analysis = pd.analyze_value("/var/log/app.log") + self.assertGreaterEqual(analysis.score, 30) + + def test_windows_path(self): + analysis = pd.analyze_value(r"C:\Windows\win.ini") + self.assertGreaterEqual(analysis.score, 30) + + def test_current_directory(self): + analysis = pd.analyze_value("./") + self.assertGreaterEqual(analysis.score, 5) + + def test_full_url_is_penalised(self): + url = pd.analyze_value("https://example.test/a/b/c.txt") + path = pd.analyze_value("/a/b/c.txt") + self.assertLess(url.score, path.score) + + def test_reasons_are_strings(self): + analysis = pd.analyze_value("../../etc/passwd") + self.assertTrue(all(isinstance(reason, str) for reason in analysis.reasons)) + + +# --------------------------------------------------------------------------- +# 2. URL parsing and analysis +# --------------------------------------------------------------------------- +class TestParseTarget(unittest.TestCase): + def test_valid_https(self): + target = pd.parse_target("https://example.test/path?file=a.txt") + self.assertEqual(target.scheme, "https") + self.assertEqual(target.host, "example.test") + self.assertEqual(target.path, "/path") + + def test_uppercase_scheme_and_host(self): + target = pd.parse_target("HTTPS://Example.Test/x") + self.assertEqual(target.scheme, "https") + self.assertEqual(target.host, "example.test") + + def test_custom_port_display(self): + target = pd.parse_target("http://example.test:8080/") + self.assertEqual(pd.display_host(target), "example.test:8080") + + def test_ipv6_is_accepted(self): + target = pd.parse_target("http://[::1]:8080/?path=/tmp") + self.assertIn("::1", target.host) + + def test_missing_scheme(self): + with self.assertRaises(pd.URLParseError): + pd.parse_target("example.test/view?file=a.txt") + + def test_unsupported_scheme(self): + with self.assertRaises(pd.URLParseError): + pd.parse_target("ftp://example.test/file.txt") + + def test_javascript_scheme_rejected(self): + with self.assertRaises(pd.URLParseError): + pd.parse_target("javascript:alert(1)") + + def test_missing_host(self): + with self.assertRaises(pd.URLParseError): + pd.parse_target("https:///path") + + def test_whitespace_rejected(self): + with self.assertRaises(pd.URLParseError): + pd.parse_target("https://example.test/a b?file=x") + + def test_bad_port_rejected(self): + with self.assertRaises(pd.URLParseError): + pd.parse_target("https://example.test:99999/") + + +class TestSplitQuery(unittest.TestCase): + def test_pairs(self): + pairs = pd.split_query("a=1&b=2") + self.assertEqual([(name, raw, value) for name, raw, value in pairs], + [("a", "1", "1"), ("b", "2", "2")]) + + def test_blank_value_is_kept(self): + pairs = pd.split_query("file=") + self.assertEqual(len(pairs), 1) + self.assertEqual(pairs[0][2], "") + + def test_repeated_names_are_kept(self): + pairs = pd.split_query("file=a&file=b") + self.assertEqual([pair[2] for pair in pairs], ["a", "b"]) + + def test_encoded_name_and_value_are_decoded_once(self): + pairs = pd.split_query("%66%69%6c%65=..%2Freport.pdf") + self.assertEqual(pairs[0][0], "file") + self.assertEqual(pairs[0][1], "..%2Freport.pdf") + self.assertEqual(pairs[0][2], "../report.pdf") + + def test_empty_query(self): + self.assertEqual(pd.split_query(""), []) + + +class TestAnalyzeURL(unittest.TestCase): + def test_flags_file_parameter(self): + findings = pd.analyze_url("https://example.test/view?file=report.pdf") + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0].parameter, "file") + self.assertEqual(findings[0].host, "example.test") + self.assertGreaterEqual(findings[0].score, 30) + + def test_never_uses_vulnerability_language(self): + findings = pd.analyze_url("https://example.test/get?doc=../../etc/passwd") + text = " ".join(reason for finding in findings for reason in finding.reasons) + for word in ("vulnerable", "exploitable", "confirmed", "LFI found"): + self.assertNotIn(word.lower(), text.lower()) + + def test_unrelated_parameter_is_not_flagged(self): + self.assertEqual(pd.analyze_url("https://example.test/?q=hello&utm_source=news"), []) + + def test_page_is_a_keyword_but_requires_the_default_threshold(self): + findings = pd.analyze_url("https://example.test/?page=2") + self.assertEqual([finding.parameter for finding in findings], ["page"]) + self.assertLess(pd.analyze_url("https://example.test/?page=2")[0].score, 50) + + def test_encoded_parameter_name_is_decoded(self): + findings = pd.analyze_url("https://example.test/?%66%69%6c%65=report.pdf") + self.assertEqual([finding.parameter for finding in findings], ["file"]) + + def test_repeated_parameters_are_merged(self): + findings = pd.analyze_url( + "https://example.test/?file=one.txt&file=two.txt&file=three.pdf" + ) + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0].occurrences, 3) + # All occurrences score equally, so the first existing value is kept. + self.assertEqual(findings[0].value, "one.txt") + + def test_repeated_parameters_keep_best_scoring_value(self): + findings = pd.analyze_url( + "https://example.test/?file=one.txt&file=../../etc/passwd" + ) + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0].occurrences, 2) + self.assertEqual(findings[0].value, "../../etc/passwd") + + def test_generic_name_requires_path_like_value(self): + self.assertEqual(pd.analyze_url("https://example.test/?image=logo"), []) + flagged = pd.analyze_url("https://example.test/?image=/static/logo.png") + self.assertEqual([finding.parameter for finding in flagged], ["image"]) + + def test_generic_name_never_stands_alone(self): + findings = pd.analyze_url("https://example.test/?target=homepage") + self.assertEqual(findings, []) + + def test_results_are_sorted_by_score(self): + findings = pd.analyze_url( + "https://example.test/?page=2&file=report.pdf&dir=../../etc" + ) + scores = [finding.score for finding in findings] + self.assertEqual(scores, sorted(scores, reverse=True)) + self.assertEqual([finding.index for finding in findings], + list(range(1, len(findings) + 1))) + + def test_min_score_threshold(self): + url = "https://example.test/?file=report.pdf" + self.assertTrue(pd.analyze_url(url, min_score=30)) + self.assertEqual(pd.analyze_url(url, min_score=90), []) + + def test_no_query_returns_empty(self): + self.assertEqual(pd.analyze_url("https://example.test/path"), []) + + def test_bare_key_without_value_is_tolerated(self): + findings = pd.analyze_url("https://example.test/?file") + self.assertEqual(len(findings), 1) + self.assertEqual(findings[0].occurrences, 1) + + def test_host_without_port_in_finding(self): + findings = pd.analyze_url("https://example.test:443/?file=a.txt") + self.assertEqual(findings[0].host, "example.test") + + def test_malformed_url_raises(self): + with self.assertRaises(pd.URLParseError): + pd.analyze_url("not a url") + + def test_mask_url(self): + masked = pd.mask_url("https://example.test/a?file=secret.pdf&x=1#frag") + self.assertNotIn("secret.pdf", masked) + self.assertIn("file=", masked) + self.assertIn("x=", masked) + + def test_findings_never_contain_credentials(self): + findings = pd.analyze_url("https://alice:hunter2@example.test/?file=a.txt") + self.assertEqual(len(findings), 1) + self.assertNotIn("hunter2", findings[0].url) + self.assertIn("@example.test", findings[0].url) + + def test_mask_url_hides_credentials(self): + masked = pd.mask_url("https://alice:hunter2@example.test/?file=a.txt") + self.assertNotIn("hunter2", masked) + self.assertIn("@example.test", masked) + + def test_count_parameters(self): + self.assertEqual( + pd.count_parameters("https://example.test/?a=1&b=2&a=3"), 2 + ) + + +# --------------------------------------------------------------------------- +# 3. Input handling +# --------------------------------------------------------------------------- +class TestCleanInputLines(unittest.TestCase): + def test_blank_lines_comments_and_duplicates(self): + urls, warnings = pd.clean_input_lines( + [ + "", + " ", + "# a comment", + "https://a.test/?file=x", + "https://a.test/?file=x", + "https://b.test/?page=2", + ] + ) + self.assertEqual(urls, ["https://a.test/?file=x", "https://b.test/?page=2"]) + self.assertEqual(warnings, []) + + def test_malformed_lines_are_reported_with_line_numbers(self): + urls, warnings = pd.clean_input_lines(["", "not-a-url", "https://ok.test/?a=1"]) + self.assertEqual(urls, ["https://ok.test/?a=1"]) + self.assertEqual(len(warnings), 1) + self.assertIn("line 2", warnings[0]) + + def test_custom_label_for_warnings(self): + _urls, warnings = pd.clean_input_lines(["bogus"], label="--url") + self.assertIn("--url 1", warnings[0]) + + +class TestReadInputFile(unittest.TestCase): + def test_reads_utf8_with_bom(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "urls.txt" + path.write_bytes(b"\xef\xbb\xbfhttps://a.test/?file=x\n\n") + lines = pd.read_input_file(str(path)) + self.assertIn("https://a.test/?file=x", [line.strip() for line in lines]) + + def test_missing_file_raises_input_error(self): + with self.assertRaises(pd.InputError): + pd.read_input_file("/definitely/not/here/urls.txt") + + def test_directory_raises_input_error(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(pd.InputError): + pd.read_input_file(tmp) + + +# --------------------------------------------------------------------------- +# 4. CLI behaviour (subprocess) +# --------------------------------------------------------------------------- +class TestCLI(unittest.TestCase): + def assert_links_present(self, text: str) -> None: + for label, url in BANNER_LINKS: + self.assertIn(f"{label}: {url}", text) + + def test_banner_links_are_exact(self): + result = run_cli("--no-banner", "--url", "https://a.test/?file=x") + self.assertNotIn("GitHub:", result.stderr) + self.assertNotIn("instagram.com", result.stderr) + + result = run_cli("--url", "https://a.test/?file=x") + self.assert_links_present(result.stderr) + + def test_banner_without_arguments(self): + result = run_cli() + self.assert_links_present(result.stderr) + self.assertEqual(result.returncode, pd.EXIT_USAGE) + + def test_banner_printed_once(self): + result = run_cli("--url", "https://a.test/?file=x") + self.assertEqual(result.stderr.count("PathScope " + pd.__version__), 1) + + def test_help_shows_banner_and_usage(self): + result = run_cli("--help") + self.assertEqual(result.returncode, 0) + self.assertIn("usage:", result.stdout) + self.assert_links_present(result.stderr) + self.assertIn("examples:", result.stdout) + self.assertIn("https://github.com/mrdineshpathro", result.stdout) + + def test_version(self): + result = run_cli("--version") + self.assertEqual(result.returncode, 0) + self.assertIn(pd.__version__, result.stdout) + + def test_single_url_hides_value_by_default(self): + result = run_cli("--url", "https://example.test/view?file=report.pdf") + self.assertEqual(result.returncode, 0) + self.assertIn("file", result.stdout) + self.assertIn("example.test", result.stdout) + self.assertNotIn("report.pdf", result.stdout) + self.assertIn("", result.stdout) + + def test_show_values_reveals_value(self): + result = run_cli( + "--url", "https://example.test/view?file=report.pdf", "--show-values" + ) + self.assertEqual(result.returncode, 0) + self.assertIn("report.pdf", result.stdout) + + def test_no_ansi_colour_when_piped(self): + result = run_cli("--url", "https://example.test/?file=report.pdf") + self.assertNotIn("\x1b[", result.stdout) + self.assertNotIn("\x1b[", result.stderr) + + def test_json_output_is_valid_and_hides_values(self): + result = run_cli( + "--json", "--url", "https://example.test/?file=report.pdf&q=hello" + ) + self.assertEqual(result.returncode, 0) + payload = json.loads(result.stdout) + self.assertEqual(payload["tool"], "PathScope") + self.assertEqual(payload["summary"]["urls_analyzed"], 1) + self.assertEqual(payload["summary"]["candidates"], 1) + finding = payload["findings"][0] + self.assertEqual(finding["parameter"], "file") + self.assertIsNone(finding["value"]) + self.assertNotIn("report.pdf", result.stdout) + self.assertIn("", finding["url"]) + + def test_json_show_values(self): + result = run_cli( + "--json", "--show-values", + "--url", "https://example.test/?file=report.pdf", + ) + payload = json.loads(result.stdout) + self.assertEqual(payload["findings"][0]["value"], "report.pdf") + + def test_json_has_disclaimer_and_links(self): + payload = json.loads( + run_cli("--json", "--url", "https://a.test/?file=x").stdout + ) + self.assertIn("manual review", payload["disclaimer"].lower()) + self.assertEqual(payload["links"]["github"], pd.GITHUB_URL) + self.assertEqual(payload["links"]["instagram"], pd.INSTAGRAM_URL) + self.assertEqual(payload["links"]["support"], pd.SUPPORT_URL) + + def test_input_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "urls.txt" + path.write_text( + "\n".join( + [ + "", + "# comment", + "https://a.test/?file=one.txt", + "", + "not a url", + "https://b.test/?page=2", + ] + ), + encoding="utf-8", + ) + result = run_cli("-i", str(path)) + self.assertEqual(result.returncode, 0) + self.assertIn("skipped malformed URL", result.stderr) + self.assertIn("Analyzed 2 URL(s)", result.stdout) + + def test_multiple_input_files(self): + with tempfile.TemporaryDirectory() as tmp: + first = Path(tmp) / "one.txt" + second = Path(tmp) / "two.txt" + first.write_text("https://a.test/?file=one.txt\n", encoding="utf-8") + second.write_text("https://b.test/?path=/var/log\n", encoding="utf-8") + result = run_cli( + "--no-banner", "--json", "-i", str(first), "-i", str(second) + ) + self.assertEqual(result.returncode, 0) + self.assertEqual(json.loads(result.stdout)["summary"]["urls_analyzed"], 2) + + def test_stdin_pipe(self): + result = run_cli(stdin="https://a.test/?file=one.txt\nhttps://b.test/?path=x\n") + self.assertEqual(result.returncode, 0) + self.assertIn("Analyzed 2 URL(s)", result.stdout) + + def test_dash_input_reads_stdin(self): + result = run_cli("-i", "-", stdin="https://a.test/?file=one.txt\n") + self.assertEqual(result.returncode, 0) + self.assertIn("1 candidate", result.stdout) + + def test_duplicate_urls_counted_once(self): + result = run_cli( + "--json", + stdin="https://a.test/?file=one.txt\nhttps://a.test/?file=one.txt\n", + ) + payload = json.loads(result.stdout) + self.assertEqual(payload["summary"]["urls_analyzed"], 1) + + def test_missing_input_file_exits_2(self): + result = run_cli("--no-banner", "-i", "/no/such/file.txt") + self.assertEqual(result.returncode, pd.EXIT_USAGE) + self.assertIn("cannot read input file", result.stderr) + + def test_invalid_min_score_exits_2(self): + result = run_cli("--no-banner", "--min-score", "101", "--url", "https://a.test/") + self.assertEqual(result.returncode, pd.EXIT_USAGE) + + def test_strict_mode_exits_1_on_bad_lines(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "urls.txt" + path.write_text("bogus\nhttps://a.test/?file=x\n", encoding="utf-8") + result = run_cli("--no-banner", "--strict", "-i", str(path)) + self.assertEqual(result.returncode, pd.EXIT_STRICT_SKIPS) + + def test_fail_on_none_exits_3(self): + result = run_cli("--no-banner", "--fail-on-none", "--url", "https://a.test/?q=hi") + self.assertEqual(result.returncode, pd.EXIT_NO_CANDIDATES) + + def test_fail_on_none_is_zero_when_candidates_exist(self): + result = run_cli( + "--no-banner", "--fail-on-none", "--url", "https://a.test/?file=a.txt" + ) + self.assertEqual(result.returncode, 0) + + def test_url_with_encoded_ampersand_and_equals(self): + result = run_cli( + "--no-banner", + "--json", + "--url", + "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.txt", + ) + self.assertEqual(result.returncode, 0) + payload = json.loads(result.stdout) + self.assertEqual(payload["summary"]["parameters_analyzed"], 2) + + def test_no_usable_urls_exits_2(self): + result = run_cli("--no-banner", stdin="# only a comment\n\n") + self.assertEqual(result.returncode, pd.EXIT_USAGE) + self.assertIn("no usable URLs", result.stderr) + + +# --------------------------------------------------------------------------- +# 5. Safety guarantees +# --------------------------------------------------------------------------- +ALLOWED_IMPORTS = { + "__future__", + "argparse", + "collections", + "dataclasses", + "json", + "os", + "re", + "sys", + "typing", + "unicodedata", + "urllib", +} +FORBIDDEN_MODULES = { + "socket", + "ssl", + "http", + "urllib3", + "requests", + "httpx", + "aiohttp", + "ftplib", + "smtplib", + "telnetlib", + "subprocess", + "scapy", + "paramiko", + "dns", +} + + +class TestSafety(unittest.TestCase): + def test_only_standard_library_imports(self): + tree = ast.parse(SCRIPT.read_text(encoding="utf-8")) + imported: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.module: + imported.add(node.module.split(".")[0]) + self.assertLessEqual(imported, ALLOWED_IMPORTS) + self.assertFalse(imported & FORBIDDEN_MODULES) + + def test_no_network_calls_during_analysis(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): + findings = pd.analyze_url( + "https://example.test/?file=../../etc/passwd&next=https://evil.test/" + ) + self.assertTrue(findings) + + def test_module_has_no_root_requirement(self): + source = SCRIPT.read_text(encoding="utf-8") + for marker in ("os.geteuid", "os.seteuid", "sudo", "setuid"): + self.assertNotIn(marker, source) + + +if __name__ == "__main__": + unittest.main(verbosity=2) From 7e04fcb226b0ffc85d1b9329bdaeb9f01e9a9f41 Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:32:59 +0000 Subject: [PATCH 2/8] Upgrade PathScope to v2: modular package, HAR input, 4 report formats Restructure the monolithic v1 tool into pathscope/ modules: textutil (bounded decoding, sanitising), heuristics (name/value rules), sources (URL/list/stdin/HAR 1.2), detector (no I/O), report (text/JSON/CSV/SARIF), config (strict JSON), cli, __main__ New capabilities: - HAR 1.2 query, form (params + urlencoded) and flattened JSON parameters - auto-detection of HAR vs URL lists, --format har/urls/auto - --format text|json|csv|sarif, --json, --input-format, --output-format - bounded multi-pass percent decoding (default 3, max 5), segment-only traversal matching, malformed-escape tolerance - values hidden by default, credentials masked, query strings/body never printed, control characters stripped from every renderer - repeatable --ignore-param, strict JSON config for name terms/ignores - --fail-on-findings with documented exit codes (0/1/2/3/130) - deterministic output across runs and input order Tests: 138 unittest cases incl. HAR parsing, redaction, format stability, malformed input, and safety (import allow-list, no sockets, values never opened as files). README rewritten for Kali usage and rule tables. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 701 +++++++++------- path_detector.py | 1200 +-------------------------- pathscope/__init__.py | 43 + pathscope/__main__.py | 10 + pathscope/cli.py | 414 ++++++++++ pathscope/config.py | 183 +++++ pathscope/detector.py | 224 +++++ pathscope/heuristics.py | 540 +++++++++++++ pathscope/report.py | 349 ++++++++ pathscope/sources.py | 577 +++++++++++++ pathscope/textutil.py | 109 +++ tests/test_path_detector.py | 1527 ++++++++++++++++++++++++----------- 12 files changed, 3913 insertions(+), 1964 deletions(-) create mode 100644 pathscope/__init__.py create mode 100644 pathscope/__main__.py create mode 100644 pathscope/cli.py create mode 100644 pathscope/config.py create mode 100644 pathscope/detector.py create mode 100644 pathscope/heuristics.py create mode 100644 pathscope/report.py create mode 100644 pathscope/sources.py create mode 100644 pathscope/textutil.py diff --git a/README.md b/README.md index 77eebb4..49c04ab 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@
-PathScope logo +PathScope logo # PathScope -**Passive URL-parameter triage for path-like parameters.** -Point it at URLs you are allowed to review, and it tells you which query parameters *look* like they might be about files or paths — so you can decide what deserves a manual look. +**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.7%2B-blue)](https://www.python.org/) [![Standard library](https://img.shields.io/badge/dependencies-none-brightgreen)](#requirements) @@ -20,387 +20,481 @@ Point it at URLs you are allowed to review, and it tells you which query paramet --- -> **PathScope results are candidates for manual review — never confirmed vulnerabilities.** -> A flag means "the wording or existing value of this parameter looks path-related". -> It does **not** mean a parameter is exploitable, reachable, or even used by the application. +> **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. --- -## Why this exists - -URL parameters such as `?file=`, `?page=`, `?template=` or `?download=` are the usual starting -points when reviewing an application for path-handling issues. Most of the noise in that review -comes from deciding *which* parameters are worth looking at first. - -PathScope does that first pass for you — **statically, offline, and without touching the target.** -It reads URLs you already have, parses them locally, and produces a short, ranked list of -parameters that mention paths/files in their names, or whose *existing* values already contain -path-like patterns. - -It is deliberately boring: no payloads, no requests, no clever stuff. +## Table of contents + +1. [What it does](#what-it-does) +2. [Safety model](#safety-model) +3. [Requirements](#requirements) +4. [Installation on Kali Linux](#installation-on-kali-linux) +5. [Inputs](#inputs) +6. [Quick start](#quick-start) +7. [Reports: text, JSON, CSV, SARIF](#reports-text-json-csv-sarif) +8. [Exit codes](#exit-codes) +9. [Detection rules](#detection-rules) +10. [Configuration file](#configuration-file) +11. [Tests](#tests) +12. [Project layout](#project-layout) +13. [Limitations](#limitations) +14. [FAQ](#faq) +15. [Authorization and legal](#authorization-and-legal) --- -## Safety statement +## What it does + +Given URLs or a HAR capture **you already have**, PathScope: -PathScope is **passive by design**. It: +* 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. -- ✅ only analyzes URLs **you explicitly provide** (`--url`, `-i/--input`, or stdin); -- ✅ parses everything **locally** with `urllib.parse` and regular expressions; -- ❌ makes **no HTTP/HTTPS requests**, and **no DNS lookups**; -- ❌ does **not crawl**, scan, fingerprint, or enumerate anything; -- ❌ does **not generate, inject, or send test values**; -- ❌ does **not open, read, or resolve any file or resource named in a URL parameter**; -- ❌ does **not require root** (or `sudo`, or any elevated capability); -- ❌ has **no third-party dependencies**, so nothing is installed from PyPI. +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. -> **Authorization:** Only analyze URLs you are authorized to review (your own applications, an -> engagement with signed scope, a lab, a CTF you are permitted to work on, or a bug-bounty -> program that allows it). If you are not sure, ask the asset owner first. Analyzing a URL is -> harmless, but acting on what you find may not be — check your scope before testing anything. +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. --- -## Features - -- **Three input modes** — a single URL, a file of URLs, or piped stdin. Sources can be combined. -- **Robust local parsing** — repeated parameters (`?file=a&file=b`), URL-encoded names - (`?%66%69%6c%65=`) and values, blank values, keys without `=`, IPv6 hosts and custom ports. -- **Transparent heuristics** — readable keyword tables and weighted rules in a single file, easy - to tune for your application or threat model. -- **Values hidden by default** — output shows `file=`, and any `user:pass@` in a URL is - masked as `@`; use `--show-values` only when you want values on screen (or in logs). -- **Plain-text output that works when piped** — ANSI colour is used only when stdout is a real - terminal. `NO_COLOR` and `--no-color` are honoured. -- **JSON output** (`--json`) for pipelines, reports and dashboards. -- **Graceful failure** — unreadable files, malformed URLs and malformed lines are reported, not - fatal; duplicates are de-duplicated; blank lines and `#` comments are skipped. -- **Useful exit codes** and a complete `--help`. -- **Tests included** — 97 unit and end-to-end tests, including checks that prove no network - modules are imported and no sockets are used. +## 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 -| Requirement | Detail | +| | | |---|---| -| Python | 3.7 or newer (tested on 3.11; Kali ships 3.11+) | +| Python | 3.7 or newer (developed and tested on Python 3.11, which Kali ships) | | Packages | **none** — standard library only | | Privileges | ordinary user; **root is not required** | -| Network | not used | - -PathScope is developed and tested on Kali Linux and runs on any Linux, macOS or Windows system -with Python 3.7+ (the test suite is executed on Python 3.11). +| Network | **never used** | --- -## Installation (Kali Linux) +## Installation on Kali Linux -Kali already ships Python 3.11, so there is nothing to install. Clone or copy the files and go: +Kali ships Python 3.11; there is nothing to install. ```bash -# 1. Get the files (git clone, or copy the folder over) git clone https://github.com/mrdineshpathro/pathscope.git cd pathscope -# 2. Confirm Python -python3 --version - -# 3. Make it executable (optional) and run it +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 ``` -Prefer a command on your `PATH`? +Optional: put it on your `PATH` without root. ```bash -# Option A: a symlink (no sudo needed if ~/.local/bin is on your PATH) mkdir -p ~/.local/bin ln -sf "$PWD/path_detector.py" ~/.local/bin/pathscope -pathscope --url 'https://example.test/view?file=report.pdf' +pathscope --version +``` -# Option B: an alias for the current shell -echo "alias pathscope='python3 $PWD/path_detector.py'" >> ~/.zshrc -source ~/.zshrc # Kali's default shell is zsh; use ~/.bashrc for bash +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 ``` -> Kali's default user is `kali`. Nothing here needs `sudo`; if a command fails, fix permissions -> in your home directory rather than escalating. +> 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**. | +| stdin | `cat urls.txt \| pathscope`, `pathscope -i -` | Auto-detected when no other source is given. | + +### Input format + +* `--format auto` (default) — HAR if the file ends in `.har`/`.har.json` or the + JSON starts with a `log.entries` object; otherwise a URL list. +* `--format har` — force HAR. +* `--format urls` — force a URL list. +* `--input-format {auto,urls,har}` — same selectors under an unambiguous name. + +`--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 -# Analyse one URL +# 1. A single URL python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -# Analyse a file of URLs (one per line) +# 2. A URL list (one per line) python3 path_detector.py -i urls.txt -# Analyse URLs piped on stdin +# 3. Piped stdin cat urls.txt | python3 path_detector.py -# See the existing values too (hidden by default) -python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values +# 4. A local HAR capture (auto-detected) +python3 path_detector.py -i capture.har -# Machine-readable output for a report pipeline -python3 path_detector.py -i urls.txt --json > findings.json +# 5. HAR with JSON output for a report pipeline +python3 path_detector.py -i capture.har --format json > candidates.json -# Combine several URL files -python3 path_detector.py -i day1.txt -i day2.txt +# 6. Show existing values (they may contain secrets — be careful) +python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values -# Lower the threshold to surface weaker signals -python3 path_detector.py -i urls.txt --min-score 20 +# 7. Ignore noisy parameters, in CI +python3 path_detector.py -i urls.txt --ignore-param image --ignore-param avatar \ + --fail-on-findings ``` -> **Quote your URLs** when they contain `&`, otherwise your shell will split them into background -> jobs. Single quotes are safest: `--url 'https://host/p?a=1&b=2'`. - -### Example session +Example terminal output (values hidden): ```console -$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf&lang=en&page=2' -PathScope 1.0.0 - passive URL-parameter triage +$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' +PathScope 2.0.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: this tool never proves a vulnerability. -No network requests are made. Only analyze URLs you are authorized to review. +Candidates for manual review only. No network requests are made; only analyze data you are authorized to review. -Candidates for manual review -================================================================ -Analyzed 1 URL(s) and 3 distinct parameter(s); 2 candidate(s) at score >= 30. +PathScope candidates for manual review +==================================================================================== +Analyzed 1 request(s) and 1 parameter(s); 1 candidate(s) at score >= 25. -#1 file [MEDIUM score 55/100] - Host example.test - URL https://example.test/view?file=&lang=&page= - Parameter file - Value - Why flagged - - name contains path-related keyword 'file' (name score +35) - - value ends with a file-like extension '.pdf' (+20) - -#2 page [LOW score 30/100] +#1 file [MEDIUM score 43/100] Host example.test - URL https://example.test/view?file=&lang=&page= - Parameter page - Value - Why flagged - - name contains path-related keyword 'page' (name score +30) + Source url (--url) + Request GET https://example.test/view + Location query + Rule name-exact + Value (use --show-values to display) + Why rule(s) 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. +``` -Reminder: candidates for manual review, not confirmed vulnerabilities. No requests were sent and no input was injected. -Values are hidden by default (use --show-values to display them). +--- -Done: 1 URL(s), 2 candidate(s), 0 line(s) skipped. -``` +## Reports: text, JSON, CSV, SARIF -*(At the default `--min-score 30` both entries are reported; raise it, e.g. `--min-score 50`, -if you only want stronger signals such as `file` here.)* +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`) -## Command-line reference +```json +{ + "tool": "PathScope", + "version": "2.0.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"] + }, + "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 + } + ], + "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`: ``` -python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--json] - [--show-values] [--no-color] [--no-banner] - [--min-score N] [--strict] [--fail-on-none] +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, ``` -### Input (sources are merged and de-duplicated) +### SARIF 2.1.0 (`--format sarif`) -| Option | Description | -|---|---| -| `--url URL` | Analyze one URL. Repeat the flag to add more. Values starting with `-` are safe. | -| `-i, --input FILE` | Read one URL per line from `FILE`; repeat the flag to read several files. Blank lines and lines starting with `#` are skipped. Use `-` to read stdin explicitly. | -| *(stdin)* | Used automatically when neither `--url` nor `--input` is given, e.g. `cat urls.txt \| python3 path_detector.py`. | +Produces a valid SARIF log for GitHub code scanning or any SARIF viewer: +one `run`, a deterministic rule catalogue, `ruleIndex` values that match the +catalogue, `level` mapped from confidence (`warning`/`note`), and a `properties` +bag with the score, reasons and location. Values are omitted unless +`--show-values`. -### Output +### Text (`--format text`, default) -| Option | Description | -|---|---| -| `--json` | Print a single JSON document on stdout. The banner and warnings go to stderr, so `> out.json` stays clean. | -| `--show-values` | Reveal the existing parameter values. Off by default; URLs are shown with `=` masking. | -| `--no-color` | Disable ANSI colour even on a terminal. Colour is automatically off when piped, and `NO_COLOR` is respected. | -| `--no-banner` | Suppress the startup banner (the banner is printed to **stderr**, not stdout). | +Human-readable blocks with the rule, evidence lines and a reminder that these +are candidates. Colour (ANSI) is used **only** when stdout is an interactive +terminal; pipes, files and CI logs get plain text. `--no-color` and the +`NO_COLOR` environment variable both disable colour explicitly. -### Heuristics and behaviour +### Warnings -| Option | Description | -|---|---| -| `--min-score N` | Report parameters with a combined score of at least `N` (0–100, default **30**). | -| `--strict` | Exit `1` if any input line was skipped (malformed URL etc.). | -| `--fail-on-none` | Exit `3` when no candidates were flagged — handy in CI. | -| `-h, --help` | Full help, including examples, exit codes and the project links. | -| `--version` | Print `PathScope ` and exit. | +Recoverable input problems (malformed URL on line 7, unreadable HAR entry, +truncated JSON body) are printed to **stderr** as `warning:` lines, counted in +the summary, and never abort the run. `-q/--quiet` silences them and the +stderr summary; JSON/CSV/SARIF on stdout stay valid. + +--- -### Exit codes +## Exit codes | Code | Meaning | |---|---| -| `0` | Analysis completed. Malformed input lines are reported as warnings but are not fatal. | -| `1` | `--strict` was given and at least one input line was malformed/skipped. | -| `2` | Usage error (bad flags), no usable URLs, or an unreadable input file. | -| `3` | No candidates were flagged (only with `--fail-on-none`). | +| `0` | Analysis completed. No candidates (or candidates found without `--fail-on-findings`). | +| `1` | Analysis completed **and** candidates were found, with `--fail-on-findings`. | +| `2` | Usage error, unreadable/malformed input file, invalid configuration, or no usable input. | +| `3` | Internal error while producing a report (never a crash trace). | | `130` | Interrupted with `Ctrl-C`. | ---- - -## How scoring works +`--fail-on-findings` is designed for CI: `0` means “nothing to look at”, `1` means +“somebody should read this report”. It never redefines `2`. -PathScope combines two independent signals, then clamps the result to **0–100**: +--- -``` -score = clamp(name_score + value_score + generic_bonus, 0, 100) -``` +## Detection rules -### 1. Name score — 0–50 +A parameter’s score is the sum of the weights of the rules that fired, clamped +to `0–100`. Names and values are evaluated independently and then combined. +All rules live in `pathscope/heuristics.py` and are safe to edit. -The parameter name is split into lowercase tokens (`fileName` → `file`,`name`; -`user-file_path` → `user`,`file`,`path`), and each token is looked up in `NAME_KEYWORDS` -in [`path_detector.py`](path_detector.py): +### Name rules (`pathscope.heuristics.analyze_name`) -| Weight | Example keywords | -|---|---| -| 30–35 | `file`, `filename`, `filepath`, `path`, `download`, `dir`, `folder`, `template`, `include`, `page`, `basedir` | -| 20–29 | `view`, `layout`, `theme`, `src`, `url`, `uri`, `document`, `config`, `log`, `render`, `doc`, `pg` | -| 10–19 | `dl`, `link`, `inc`, `data`, `mount`, `root`, `action` | +| Rule | Weight | Fires when | +|---|---|---| +| `name-exact` | +35 (+5 multiword) | a token is a path term: `file`, `filepath`, `document`, `download`, `attachment`, `path`, `dir`, `folder`, `base_path`, `template`, `include`, `page`, `view`, `layout`, `config`, `log`, `script`, `resource`, `asset`, `storage`, `locale`, … | +| `name-custom` | +30 | a token matches a term from `--config` `name_terms` | +| `name-compound` | +35 | the whole name is a known compound without separators (`filepath`) | +| `name-prefix` | +28 | the name starts with a path term (`filedata`) | +| `name-suffix` | +23 | the name ends with a path term (`resolvepath`) | +| `name-weak` | +5 | multiword name without a path term — never enough on its own | +| `name-generic` | 0 | generic names (`image`, `img`, `target`, `ref`, `avatar`, …) only count *with* a path-like value | -- **Exact token** → full weight, plus `+5` when the name has multiple tokens - (e.g. `download_file`). -- **Prefix/suffix of the joined name** → discounted weight, so `filedata` still scores but - `profile` (ends in `file`) does not. -- **Weak shapes only** → `+10` for a multi-word name with no keyword, `+5` for a very long name. -- **Generic names** (`image`, `target`, `ref`, `site`, `avatar`, …) score **0 alone** and can only - contribute through the rule below. +`utm_source`, `gclid`, `page_size`, `urlencoded`, `landscape`, `sort` and similar +ordinary names do not produce findings. -### 2. Value score — 0–50 +### Value rules (`pathscope.heuristics.analyze_value`) -Only values that are **already present** in the URL are inspected — PathScope never generates -one. Each piece of evidence is counted once, even if the value is encoded and decoded forms -overlap. +Values are decoded up to `--max-decode-passes` times (default **3**, hard max **5**) +with malformed escapes left intact. Traversal is matched as a **path segment**, +so `report..pdf` or `v1..2` never match. -| Weight | Evidence in the existing value | +| Rule | Weight | Example value | +|---|---|---| +| `value-traversal` | +30 | `../../etc/passwd`, `..\..\win.ini`, bare `..` | +| `value-encoded-traversal` | +15 | `%2e%2e%2f`, `..%2f`, `%252e%252e%252f` | +| `value-encoded-slash` | +12 | `%2f`, `%5c` | +| `value-double-encoded` | +10 | value needed ≥2 decoding passes | +| `value-absolute` | +12 | `/var/www/html` (not `//cdn`) | +| `value-windows-drive` | +15 | `C:\Windows\win.ini`, `D:/data` | +| `value-unc` | +15 | `\\server\share\x` | +| `value-multi-segment` | +6 | three or more separators | +| `value-extension` | +8 | `.pdf`, `.php`, `.tar.gz` on a path-like value | +| `value-path-list` | +5 | `a.css;b.css` | +| `value-full-url` | −10 | `https://other.test/x` (usually a redirect target) | +| `value-pairs-with-generic-name` | +10 | `image=/static/logo.png` | + +### Confidence bands (heuristic, not exploitability) + +| Score | Label | |---|---| -| +25 | Parent-directory sequence `../` or `..\` | -| +20 | URL-encoded `..` (`%2e%2e`), or a known file extension (`.pdf`, `.log`, `.tar.gz`, …) | -| +15 | Encoded slash/backslash (`%2f`, `%5c`), null byte (`%00`), or `/etc` reference | -| +12–15 | Two or more path separators | -| +8–10 | One separator, Windows drive path (`C:\…`), `..` / `./` segment, double encoding | -| +5 | Value starts with `/` (absolute-looking) | -| −10 | Value is a full URL (`https://…`), which is usually a redirect target, not a path | +| 70–100 | `high` | +| 40–69 | `medium` | +| 0–39 | `low` | -### 3. Generic bonus — 0–10 +The default threshold is **25** (`--min-score`). Recommended interpretation: +read `high` and `medium` first, `low` only when you have time. A score is a +reading priority, never a risk rating. -Names like `image`, `avatar` or `target` are only interesting when the existing value is -path-like (e.g. `?image=/static/logo.png`). In that case `+10` is added; otherwise the -parameter is ignored entirely. This keeps ordinary tracking parameters out of the report. +### Tuning -### Interpretation bands +* Add project-specific vocabulary: `--config` `name_terms` (literal strings only). +* Silence known-noisy names: `--ignore-param NAME` (repeatable) or `--config` + `ignore_params`. +* Change the vocabulary permanently by editing `PATH_NAME_TERMS`, + `GENERIC_NAME_TERMS`, `FILE_EXTENSIONS` or the weights in `heuristics.py`; + the tests exercise these tables. -| Score | Band | Suggested reading | -|---|---|---| -| 70–100 | `HIGH` | Strong textual match — review this parameter first. | -| 50–69 | `MEDIUM` | Likely relevant; confirm it is actually used by the app. | -| 30–49 | `LOW` | Weak signal; review only if time allows or scope demands it. | +--- -**None of these bands imply exploitability.** They rank reading order, nothing more. +## Command-line reference -### Tuning +``` +python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] + [--format {auto,urls,har,text,json,csv,sarif}] + [--input-format {auto,urls,har}] + [--output-format {text,json,csv,sarif}] [--json] + [--show-values] [--no-color] [--no-banner] [-q] + [--ignore-param NAME] [--config FILE] + [--min-score N] [--max-decode-passes N] + [--fail-on-findings] +``` -All tables and weights live at the top of `path_detector.py` (`NAME_KEYWORDS`, -`GENERIC_NAMES`, `FILE_EXTENSIONS`, and the weights inside `analyze_name` / `analyze_value`). -Add your application's own vocabulary (`?shop=`, `?cms_module=`, `?f=`) or drop keywords -that are noisy for you — it is a single editable file, and the tests still apply. +| Option | Description | +|---|---| +| `--url URL` | URL to analyze; repeatable. | +| `-i, --input FILE` | URL list or HAR file; repeatable; `-` reads stdin. | +| `--format FMT` | Input selector (`har`, `urls`, `auto`) **or** output format (`text`, `json`, `csv`, `sarif`). | +| `--input-format FMT` | Explicit input selector when `--format` is used for output. | +| `--output-format FMT` | Report format (same as `--format json` etc.). | +| `--json` | Shorthand for `--output-format json`. | +| `--show-values` | Reveal parameter values (hidden by default). | +| `--ignore-param NAME` | Ignore a parameter name; repeatable. | +| `--config FILE` | JSON configuration (see below). | +| `--min-score N` | Reporting threshold, 0–100 (default 25). | +| `--max-decode-passes N` | Percent-decoding passes per value, 0–5 (default 3). | +| `--fail-on-findings` | Exit `1` when candidates exist. | +| `-q, --quiet` | Suppress warnings and the stderr summary. | +| `--no-color` | Disable colour on terminals. | +| `--no-banner` | Suppress the startup banner. | +| `-h, --help` / `--version` | Help / version and exit. | --- -## JSON output +## Configuration file + +A small JSON file, validated strictly. Unknown keys, wrong types, values out of +range, and anything that looks like a regular expression are rejected with a +clear error and exit code `2`. ```json { - "tool": "PathScope", - "version": "1.0.0", - "disclaimer": "Candidates for manual review only. PathScope is passive: it makes no network requests, injects no values, and never confirms vulnerabilities.", - "min_score": 30, - "show_values": false, - "summary": { - "urls_analyzed": 1, - "parameters_analyzed": 3, - "candidates": 1, - "skipped_lines": 0 - }, - "findings": [ - { - "index": 1, - "host": "example.test", - "parameter": "file", - "url": "https://example.test/view?file=&lang=", - "value": null, - "occurrences": 1, - "score": 55, - "band": "MEDIUM", - "reasons": [ - "name contains path-related keyword 'file' (name score +35)", - "value ends with a file-like extension '.pdf' (+20)" - ] - } - ], - "links": { - "github": "https://github.com/mrdineshpathro", - "instagram": "https://www.instagram.com/mr_dineshpatro", - "support": "https://buymeacoffee.com/mrdineshpathro" - } + "name_terms": ["download", "media_file", "cdn_blob"], + "ignore_params": ["image", "avatar"], + "min_score": 25, + "max_decode_passes": 3, + "show_values": false } ``` -With `--show-values`, `value` contains the existing value and `url` is left unmasked. +| Key | Type | Rules | +|---|---|---| +| `name_terms` | array of strings | 2–48 chars, letters/digits/`_`/`-` only, max 200 entries | +| `ignore_params` | array of strings | same rules | +| `min_score` | integer | 0–100 | +| `max_decode_passes` | integer | 0–5 | +| `show_values` | boolean | defaults values to visible; `--show-values` also works | + +```bash +python3 path_detector.py --config pathscope.json -i urls.txt +``` + +Regular expressions are deliberately unsupported: they add a +catastrophic-backtracking risk to a passive tool and make results harder to +explain. Literal terms keep every finding traceable to a readable rule. --- ## Tests -The suite uses only `unittest` (standard library) and runs fully offline: +The suite uses only `unittest` and runs fully offline. ```bash -# From the repository root python3 -m unittest discover -s tests -v - -# Or run the file directly +# or directly python3 tests/test_path_detector.py ``` -What is covered: - -- tokenising names (`snake_case`, `kebab-case`, `camelCase`, `PascalCase`); -- keyword, prefix/suffix and weak-name scoring; generic-name rules; -- value scoring: extensions, traversal, encoded and double-encoded forms, Windows paths, - absolute paths, full-URL penalty, and the "count each evidence once" rule; -- URL validation (schemes, ports, IPv6, whitespace, malformed input); -- repeated and encoded parameters, merging, sorting, masking; -- input handling: blank lines, comments, duplicates, BOM, unreadable files; -- CLI end-to-end: banner links, `--help`, `--version`, `--json`, `--show-values`, - `--strict`, `--fail-on-none`, exit codes, no ANSI codes when piped; -- **safety:** the module imports only an allow-list of standard-library modules, defines no - root-related calls, and performs no socket operations while analysing URLs. - ---- - -## Limitations (read these) +138 tests cover exactly the behaviours this tool promises: -- **It is a triage aid, not a scanner.** PathScope reads strings. It cannot tell whether a - parameter is used by the server, validated, ignored, or routed through a WAF. -- **Names and values can lie.** A parameter called `file` may be a harmless enum; a parameter - called `x` may be the actual file handler. Treat the output as a reading order, not an answer. -- **Only query parameters are analysed.** Path segments, JSON bodies, headers and cookies are - out of scope by design. -- **Encodings beyond normal URL encoding** (e.g. UTF-16 percent-encoding, overlong UTF-8) are - not decoded, because decoding them would mean guessing at values. -- **No persistence.** PathScope writes nothing to disk; redirect stdout if you need a report. -- **Not a vulnerability verdict.** A human must verify anything before it is called a finding. +| Area | What is asserted | +|---|---| +| Query parsing | repeated parameters, occurrence counters, encoded names/values, `+` in names, blank values, encoded `&`/`=`, IPv6 hosts | +| Value heuristics | literal/encoded/partially-encoded/double-encoded traversal, bounded decoding, segment-only matching (`report..pdf` does not match), Windows/UNC/absolute paths, full-URL penalty, malformed `%` sequences | +| Name heuristics | snake_case/kebab-case/camelCase, exact/compound/prefix/suffix/custom terms, generic names, ordinary names produce nothing | +| HAR | query, form (`postData.params` and urlencoded `text`), JSON bodies with arrays, duplicate entries, malformed entries, missing `log`, invalid JSON, BOM, version warnings | +| Malformed input | unreadable files, directories, binary data, oversized values, control characters | +| Redaction | values hidden by default in every format, `--show-values` reveals them, credentials masked | +| Formats | stable JSON/CSV/SARIF, SARIF `ruleIndex` consistency, CSV columns, deterministic ordering | +| Safety | import allow-list, no socket use (patched to raise), values never passed to `open`, no root/shell calls | --- @@ -408,50 +502,83 @@ What is covered: ``` pathscope/ -├── path_detector.py # the tool (standard library only) -├── tests/ -│ └── test_path_detector.py # unittest suite (offline) -├── assets/ -│ └── logo.svg # original repository icon (route + magnifier) +├── path_detector.py # executable entry point (thin wrapper) +├── pathscope/ +│ ├── __init__.py # name, version, branding constants +│ ├── textutil.py # decoding (bounded), sanitising, truncation +│ ├── heuristics.py # name/value rules and scoring +│ ├── sources.py # URL, list, stdin and HAR 1.2 parsing +│ ├── detector.py # request → findings (no I/O) +│ ├── report.py # text, JSON, CSV, SARIF renderers, banner +│ ├── config.py # strict JSON configuration validation +│ ├── cli.py # argument parsing, input merging, exit codes +│ └── __main__.py # enables `python3 -m pathscope` +├── tests/test_path_detector.py # unittest suite (offline) +├── assets/logo.svg # original PathScope mark (route + magnifier) ├── README.md └── LICENSE ``` +Data flow: `sources` (parse, warn) → `detector` (score, rank) → `report` +(render). The detector has no I/O and is trivially testable. + +--- + +## Limitations + +* **Heuristic only.** Names and values can be misleading; a parameter called + `file` may be an enum, and the real handler may be called `x`. +* **Query, form and JSON bodies only.** Path segments, headers, cookies and + multipart file *content* are out of scope. +* **No verification.** PathScope never checks whether the server uses, validates + or blocks the parameter. That requires an authorized, separate test. +* **Encoding depth is bounded.** Three passes by default; deeper nesting is + reported only as `value-double-encoded`. +* **No persistence.** Nothing is written to disk; redirect stdout if you need a + report file. +* **Not a risk rating.** Scores order reading, not severity. Do not publish them + as vulnerability ratings. + --- ## FAQ -**Does PathScope send anything to the URLs?** -No. There is no socket code in the tool. A test asserts that no network modules are imported and -that analysis works with socket functions patched to raise. +**Does it send anything?** +No. The package contains no networking imports; a test asserts the import +allow-list and another runs analysis with socket functions patched to raise. **Why are values hidden by default?** -URLs in bug-bounty reports, tickets and shell history routinely contain tokens, session IDs and -personal data. Masking by default makes it hard to leak them by accident; `--show-values` -is an explicit decision. +URLs and HAR captures routinely contain session tokens and personal data. +Masking by default makes accidental disclosure in tickets or CI logs much harder. +`--show-values` is a deliberate choice, and even then query strings of the URL +itself are never printed — only the specific parameter you asked to see. + +**How do I use it in CI?** +`python3 path_detector.py -i capture.har --format sarif --fail-on-findings > pathscope.sarif` +then upload the SARIF file. Exit `0` = nothing flagged, `1` = candidates found. -**Can I use it in CI?** -Yes: `python3 path_detector.py -i urls.txt --json --fail-on-none` exits `3` when nothing -path-like is found, which you can map to a warning, and `--strict` exits `1` on malformed input. +**Can HAR replay send requests?** +No. PathScope only reads `log.entries[].request.url`, `queryString` and +`postData`. No `curl`, no `requests`, no sockets. -**Does it need root on Kali?** -No. Every code path runs as your normal user; nothing binds a port, changes interface state, or -reads privileged files. +**Which Python versions work?** +3.7+. The code avoids 3.8+ syntax; CI was run on 3.11 (Kali default). -**Will it find all path-like parameters?** -No. It finds parameters whose names or existing values match the heuristics. Parameters that -never carry a path-like value and have neutral names will not be flagged — that is by design, -to keep the report readable. +**Why not regex configuration?** +ReDoS risk and explainability. Literal terms are validated and predictable. --- -## Legal +## Authorization and legal + +PathScope is a **defensive triage aid** for authorized security review, +education and engineering. Only analyze URLs, files and HAR captures you are +authorized to review. If a system is not yours, confirm scope in writing before +you analyze data from it — and remember that a finding here is a reason to look, +not a license to test. -PathScope is provided for **authorized security review, education and defensive engineering**. -Only analyze URLs you have permission to review, and always confirm scope in writing for -third-party systems. The results are heuristic candidates for manual review, not a statement -about the security of any system. See [LICENSE](LICENSE) (MIT) — the software is provided -"as is", without warranty of any kind. +Provided under the MIT License (see [LICENSE](LICENSE)), without warranty of any +kind. --- diff --git a/path_detector.py b/path_detector.py index 85823b5..fa4fbf1 100755 --- a/path_detector.py +++ b/path_detector.py @@ -1,1201 +1,27 @@ #!/usr/bin/env python3 -"""PathScope - passive URL-parameter triage for path-like parameters. +"""PathScope - convenient executable entry point. -PathScope reads URLs that *you* provide and highlights query parameters whose -names or existing values look as though they might relate to file paths. -Every result is a **candidate for manual review**, never a confirmed -vulnerability. +Examples: + python3 path_detector.py --url 'https://example.test/view?file=report.pdf' + python3 path_detector.py -i urls.txt + python3 path_detector.py -i capture.har --format json + cat urls.txt | python3 path_detector.py --format sarif -Safety model (by design, not by configuration): - * No HTTP requests, no DNS lookups, no crawling, no scanning. - * No test payloads are generated and nothing is sent anywhere. - * No file or resource named in a parameter is opened or resolved. - * No root privileges are used or required. - * Standard library only, so there is nothing to install with pip. - -Exit codes: - 0 analysis completed normally (malformed lines are warned about) - 1 --strict was given and at least one input line was skipped - 2 usage error, unreadable input file, or no usable URLs - 3 no candidates were flagged (only with --fail-on-none) - 130 interrupted with Ctrl-C - -Usage: - python3 path_detector.py --url 'https://example.test/view?file=report.pdf' - python3 path_detector.py -i urls.txt - cat urls.txt | python3 path_detector.py +This wrapper only adds the project directory to ``sys.path`` so the tool runs +from a fresh checkout without installation. All logic lives in ``pathscope/``. """ from __future__ import annotations -import argparse -import json import os -import re import sys -import unicodedata -from collections import OrderedDict -from dataclasses import dataclass, field -from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple -from urllib.parse import unquote, unquote_plus, urlsplit, urlunsplit - -__version__ = "1.0.0" -PROGRAM = "PathScope" - -# --------------------------------------------------------------------------- -# Banner. These links are printed exactly as given. They are never opened and -# never contacted; PathScope makes no network requests of any kind. -# --------------------------------------------------------------------------- -GITHUB_URL = "https://github.com/mrdineshpathro" -INSTAGRAM_URL = "https://www.instagram.com/mr_dineshpatro" -SUPPORT_URL = "https://buymeacoffee.com/mrdineshpathro" - -BANNER_LINKS: Tuple[Tuple[str, str], ...] = ( - ("GitHub", GITHUB_URL), - ("Instagram", INSTAGRAM_URL), - ("Support", SUPPORT_URL), -) -BANNER_DISCLAIMER = ( - "Candidates for manual review only: this tool never proves a vulnerability.", - "No network requests are made. Only analyze URLs you are authorized to review.", -) - -EXIT_OK = 0 -EXIT_STRICT_SKIPS = 1 -EXIT_USAGE = 2 -EXIT_NO_CANDIDATES = 3 -EXIT_INTERRUPTED = 130 - -# --------------------------------------------------------------------------- -# Heuristics. Everything below is deliberately plain and easy to edit. -# -# Final score = clamp(name_score + value_score + generic_bonus, 0, 100) -# * name_score 0-50 from NAME_KEYWORDS / weak name shapes -# * value_score 0-50 from existing values only (never generated) -# * generic_bonus 0-10 for generic names (image, target, ...) whose value -# is path-like; generic names never score alone. -# A parameter is reported when the final score >= --min-score (default 30). -# --------------------------------------------------------------------------- - -NAME_KEYWORDS: Dict[str, int] = { - # files / downloads - "file": 35, - "filename": 35, - "file_name": 35, - "filepath": 35, - "file_path": 35, - "document": 25, - "doc": 20, - "download": 35, - "dl": 15, - "attachment": 30, - "upload": 25, - "export": 25, - "import": 15, - "archive": 20, - "backup": 20, - # paths / directories - "path": 35, - "dir": 30, - "directory": 30, - "folder": 30, - "root": 15, - "base": 15, - "basedir": 30, - "base_dir": 30, - "basepath": 30, - "base_path": 30, - "uri": 20, - "url": 20, - "link": 15, - "dest": 20, - "destination": 20, - "source": 20, - "src": 20, - "resource": 20, - "asset": 20, - "media": 20, - "storage": 20, - "mount": 15, - # pages / templates / includes / views - "page": 30, - "pg": 20, - "view": 20, - "display": 15, - "screen": 10, - "layout": 20, - "theme": 20, - "tpl": 30, - "template": 30, - "include": 30, - "inc": 15, - "viewfile": 30, - "view_file": 30, - "load": 20, - "action": 15, - "module": 15, - # code / config / logs / data files - "script": 25, - "lang": 20, - "language": 15, - "locale": 15, - "translation": 15, - "config": 20, - "conf": 20, - "settings": 15, - "log": 20, - "logfile": 30, - "log_file": 30, - "stylesheet": 30, - "css": 15, - "js": 15, - "style": 15, - "data": 10, - "db": 15, - "database": 15, - "report": 20, - "render": 20, -} - -PREFIX_DISCOUNT = 7 -SUFFIX_DISCOUNT = 12 -NAME_CAP = 50 -VALUE_CAP = 50 -GENERIC_BONUS = 10 - -# Generic names: by themselves they are not path-related, but a path-like -# existing value makes them worth a look (e.g. image=/static/logo.png). -GENERIC_NAMES = frozenset( - { - "image", - "img", - "photo", - "avatar", - "target", - "ref", - "referer", - "referrer", - "site", - "key", - "callback", - "filetarget", - } -) - -FILE_EXTENSIONS = 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 = ("tar.gz", "tar.bz2", "tar.xz") - -WINDOWS_PATH_RE = re.compile(r"^[A-Za-z]:[/\\].+") - -COLOR_CODES = { - "bold": "1", - "dim": "2", - "red": "31", - "green": "32", - "yellow": "33", - "blue": "34", - "magenta": "35", - "cyan": "36", - "grey": "90", -} - - -# --------------------------------------------------------------------------- -# Small utilities -# --------------------------------------------------------------------------- -def sanitize_text(value: str) -> str: - """NFC-normalise text and drop control characters (keeps output terminal-safe).""" - 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: - if len(text) <= limit: - return text - return text[: max(0, limit - 1)] + "\u2026" - - -def normalize_name(name: str) -> str: - """Lowercase a parameter name and unify separators: 'userId' stays camel-ish.""" - return name.strip().lower().replace("-", "_").replace(" ", "_") - - -def tokenize_name(name: str) -> List[str]: - """Split a parameter name into lowercase tokens. - - 'fileName' -> ['file', 'name'] - 'user-file_path' -> ['user', 'file', 'path'] - 'FILES' -> ['files'] - """ - parts: List[str] = [] - current = "" - for char in name: - if char.isupper() and current and not current[-1].isupper(): - parts.append(current) - current = char - else: - current += char - if current: - parts.append(current) - - tokens: List[str] = [] - for part in parts: - for piece in normalize_name(part).split("_"): - if piece: - tokens.append(piece) - return tokens - - -def extension_of(text: str) -> Optional[str]: - """Return a known file extension at the end of the value, if any.""" - cleaned = text.strip().rstrip(".,;:!?") - last = re.split(r"[/\\]", cleaned)[-1] - lowered = last.lower() - for multi in MULTI_EXTENSIONS: - if lowered.endswith("." + multi): - return multi - if "." not in lowered: - return None - candidate = lowered.rsplit(".", 1)[1] - if candidate in FILE_EXTENSIONS: - return candidate - return None - - -# --------------------------------------------------------------------------- -# Name heuristic -# --------------------------------------------------------------------------- -@dataclass(frozen=True) -class NameAnalysis: - """Outcome of analysing a parameter name.""" - - score: int = 0 - reason: Optional[str] = None - keyword: Optional[str] = None - generic: bool = False - weak: bool = False - - -def analyze_name(name: str) -> NameAnalysis: - """Score a parameter name for path-related meaning (0-50).""" - tokens = tokenize_name(name) - joined = "".join(tokens) - - best_weight = 0 - best_keyword: Optional[str] = None - - # Exact token matches: "file", "path", "dir", ... - for token in tokens: - weight = NAME_KEYWORDS.get(token, 0) - if weight > best_weight: - best_weight, best_keyword = weight, token - - # Compound key matches: "basepath", "viewfile", ... - if best_weight == 0 and joined: - weight = NAME_KEYWORDS.get(joined, 0) - if weight: - best_weight, best_keyword = weight, joined - - # Prefix / suffix matches get a discount: "filedata" yes, "hotfile" only - # weakly (and not at all at the default threshold). - if best_weight == 0 and joined: - for keyword, weight in NAME_KEYWORDS.items(): - if len(keyword) < 4: - continue - if joined.startswith(keyword) and weight > PREFIX_DISCOUNT: - candidate = weight - PREFIX_DISCOUNT - if candidate > best_weight: - best_weight, best_keyword = candidate, keyword - elif joined.endswith(keyword) and weight > SUFFIX_DISCOUNT: - candidate = weight - SUFFIX_DISCOUNT - if candidate > best_weight: - best_weight, best_keyword = candidate, keyword - - if best_keyword is not None: - bonus = 5 if len(tokens) > 1 else 0 - reason = ( - f"name contains path-related keyword '{best_keyword}' " - f"(name score +{best_weight}{f', +{bonus} for multi-word name' if bonus else ''})" - ) - return NameAnalysis( - score=min(NAME_CAP, best_weight + bonus), - reason=reason, - keyword=best_keyword, - ) - - lowered = normalize_name(name) - if lowered in GENERIC_NAMES: - return NameAnalysis(generic=True) - - if "_" in lowered or "-" in name: - return NameAnalysis( - score=10, - reason="multi-word name with no obvious path keyword (weak signal, +10)", - weak=True, - ) - if len(lowered) > 24: - return NameAnalysis( - score=5, - reason="unusually long parameter name (weak signal, +5)", - weak=True, - ) - return NameAnalysis() - - -# --------------------------------------------------------------------------- -# Value heuristic (existing values only - PathScope never generates input) -# --------------------------------------------------------------------------- -@dataclass(frozen=True) -class ValueAnalysis: - """Outcome of analysing an existing parameter value.""" - - score: int = 0 - reasons: Tuple[str, ...] = () - - -ENCODED_PATH_MARKERS = ("%2e%2e", "%2f", "%5c", "%252e", "%252f") - - -def analyze_value(raw_value: str, decoded: Optional[str] = None) -> ValueAnalysis: - """Score an existing value for path-like or encoded path-like content (0-50). - - ``raw_value`` is exactly what appeared in the URL; ``decoded`` is the - single-decoded form (passed in by the caller to avoid decoding twice). - Each piece of evidence is counted once: when the raw value already shows - encoded path markers, the structural layer is skipped so the same pattern - is not credited twice. - """ - if not raw_value and not decoded: - return ValueAnalysis() - - if decoded is None: - decoded = unquote(raw_value) - raw_value = raw_value or "" - decoded = decoded or "" - lowered_raw = raw_value.lower() - encoded_path = any(marker in lowered_raw for marker in ENCODED_PATH_MARKERS) - - score = 0 - reasons: List[str] = [] - seen = set() - - def add(key: str, weight: int, reason: str) -> None: - nonlocal score - if key in seen: - return - seen.add(key) - score += weight - reasons.append(reason) - - # 1. Encoding and traversal indicators, evaluated on raw and decoded forms. - if not encoded_path and ("../" in decoded or "..\\" in decoded): - add( - "traversal", - 25, - "value contains a parent-directory sequence ('../' or '..\\') (+25)", - ) - if "%2e%2e" in lowered_raw: - add("pct-dotdot", 20, "value contains URL-encoded '..' (%2e%2e) (+20)") - if "%2f" in lowered_raw: - add("pct-slash", 15, "value contains URL-encoded slash (%2f) (+15)") - if "%5c" in lowered_raw: - add("pct-backslash", 15, "value contains URL-encoded backslash (%5c) (+15)") - if "%00" in lowered_raw: - add("nul-byte", 15, "value contains a null-byte encoding (%00) (+15)") - if "%252e" in lowered_raw or "%252f" in lowered_raw: - add("double-encoded", 10, "value contains double-encoded path characters (+10)") - if lowered_raw.startswith("/etc") or "/etc/" in lowered_raw: - add("system-path", 15, "value references a common system path (/etc) (+15)") - if "\\windows\\" in lowered_raw: - add("windows-dir", 10, "value references a Windows system directory (+10)") - - # 2. Structural shape of the decoded value. - structure = decoded - is_full_url = "://" in structure - if is_full_url: - add("full-url", -10, "value is a full URL rather than a local path (-10)") - - if not encoded_path: - if WINDOWS_PATH_RE.match(structure): - add("windows-drive", 10, "value looks like a Windows drive path (+10)") - - normalized = structure.replace("\\", "/") - if normalized in {"..", "../"} or normalized.startswith("../") or "/../" in normalized: - add( - "dotdot", - 10, - "value is or contains a parent-directory ('..') sequence (+10)", - ) - elif normalized in {".", "./"} or normalized.startswith("./"): - add( - "dot", - 5, - "value is or starts with a current-directory ('./') sequence (+5)", - ) - - if not is_full_url: - separators = normalized.count("/") - if separators == 1: - add("depth-1", 8, "value contains a relative path segment (+8)") - elif separators == 2: - add("depth-2", 12, "value contains two path separators (+12)") - elif separators >= 3: - add("depth-3", 15, "value contains three or more path separators (+15)") - if normalized.startswith("/") and len(normalized) > 1: - add( - "absolute", - 5, - "value starts with a path separator (absolute-looking path) (+5)", - ) - - ext = extension_of(structure) - if ext: - add("extension", 20, f"value ends with a file-like extension '.{ext}' (+20)") - - return ValueAnalysis(score=max(0, min(VALUE_CAP, score)), reasons=tuple(reasons)) - - -# --------------------------------------------------------------------------- -# URL parsing and analysis -# --------------------------------------------------------------------------- -@dataclass(frozen=True) -class URLTarget: - """Locally parsed URL metadata (no network activity involved).""" - - raw: str - scheme: str - host: str - port: Optional[int] - path: str - - -class URLParseError(ValueError): - """Raised when a line is not a usable HTTP(S) URL.""" - - -def parse_target(raw: str) -> URLTarget: - """Validate a URL string locally. Never resolves or contacts the host.""" - text = sanitize_text(raw).strip() - if not text: - raise URLParseError("blank input") - if any(char.isspace() for char in text): - raise URLParseError("contains whitespace") - if any(ord(char) < 32 or ord(char) == 127 for char in raw): - 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 URLTarget( - raw=text, - scheme=scheme, - host=host, - port=port, - path=parts.path or "/", - ) - - -def display_host(target: URLTarget) -> str: - if target.port and target.port not in (80, 443): - return f"{target.host}:{target.port}" - return target.host - - -def split_query(query: str) -> List[Tuple[str, str, str]]: - """Split a raw query string into (decoded name, raw value, decoded value). - - Kept deliberately literal (manual split on '&' and '=') so that: - * repeated parameters are preserved, - * URL-encoded names/values are visible both raw and decoded, - * PathScope never guesses at values it was not given. - """ - pairs: List[Tuple[str, str, str]] = [] - if not query: - return pairs - for chunk in query.split("&"): - if not chunk: - continue - raw_name, separator, raw_value = chunk.partition("=") - try: - name = unquote_plus(raw_name) - value = unquote_plus(raw_value) - except (UnicodeError, ValueError): - name, value = raw_name, raw_value - pairs.append((sanitize_text(name), raw_value, sanitize_text(value))) - return pairs - - -def mask_credentials(netloc: str) -> str: - """Replace 'user:pass@' with '@' so secrets are not displayed.""" - if "@" not in netloc: - return netloc - host = netloc.rsplit("@", 1)[1] - return f"@{host}" - - -def mask_url(raw: str) -> str: - """Return the URL with query/fragment values and credentials hidden.""" - parts = urlsplit(raw) - pairs: List[str] = [] - for chunk in parts.query.split("&"): - if not chunk: - continue - if "=" in chunk: - name = chunk.split("=", 1)[0] - pairs.append(f"{name}=") - else: - pairs.append(chunk) - fragment = "" if parts.fragment else "" - return urlunsplit( - ( - parts.scheme, - mask_credentials(parts.netloc), - parts.path, - "&".join(pairs), - fragment, - ) - ) - - -@dataclass -class ParameterFinding: - """One parameter that passed the heuristic threshold.""" - - url: str - host: str - parameter: str - value: Optional[str] - reasons: Tuple[str, ...] - score: int - occurrences: int = 1 - index: int = 0 - - @property - def band(self) -> str: - return score_band(self.score) - - -@dataclass -class _ParameterGroup: - parameter: str - occurrences: int = 0 - values: List[str] = field(default_factory=list) - raw_values: List[str] = field(default_factory=list) - - -def analyze_url(raw: str, min_score: int = 30) -> List[ParameterFinding]: - """Analyse one URL and return its flagged parameters (best first). - - This is purely local string analysis: nothing is requested, resolved, - opened or injected. - """ - raw = sanitize_text(raw).strip() - target = parse_target(raw) - parts = urlsplit(raw) - - groups: "OrderedDict[str, _ParameterGroup]" = OrderedDict() - for name, raw_value, value in split_query(parts.query): - if not name: - continue - canonical = "_".join(tokenize_name(name)) or name.lower() - group = groups.get(canonical) - if group is None: - group = groups[canonical] = _ParameterGroup(parameter=name) - group.occurrences += 1 - group.values.append(value) - group.raw_values.append(raw_value) - - findings: List[ParameterFinding] = [] - host = display_host(target) - # Show URL credentials as masked, even when parameter values are shown. - safe_url = mask_credentials(parts.netloc) - if safe_url != parts.netloc: - safe_url = urlunsplit( - (parts.scheme, safe_url, parts.path, parts.query, parts.fragment) - ) - else: - safe_url = raw - - for group in groups.values(): - name_analysis = analyze_name(group.parameter) - value_analyses = [ - analyze_value(raw_value, decoded=group.values[index]) - for index, raw_value in enumerate(group.raw_values) - ] - - best_index = 0 - for index, analysis in enumerate(value_analyses): - if analysis.score > value_analyses[best_index].score: - best_index = index - best_value_analysis = value_analyses[best_index] - best_value = group.values[best_index] - - generic_bonus = 0 - reasons: List[str] = [] - if name_analysis.reason: - reasons.append(name_analysis.reason) - if name_analysis.generic: - if best_value_analysis.score >= 20: - generic_bonus = GENERIC_BONUS - reasons.append( - f"generic name '{group.parameter}' becomes relevant because its " - f"value is path-like (+{GENERIC_BONUS})" - ) - else: - continue # generic names never stand alone - reasons.extend(best_value_analysis.reasons) - - score = name_analysis.score + best_value_analysis.score + generic_bonus - score = max(0, min(100, score)) - if score <= 0 or score < min_score: - continue - - findings.append( - ParameterFinding( - url=safe_url, - host=host, - parameter=group.parameter, - value=best_value, - reasons=tuple(reasons) or (f"combined heuristic score {score}",), - score=score, - occurrences=group.occurrences, - ) - ) - - findings.sort(key=lambda finding: (-finding.score, finding.parameter.lower())) - for index, finding in enumerate(findings, start=1): - finding.index = index - return findings - - -def count_parameters(raw: str) -> int: - """Count distinct, non-empty parameter names in a URL (locally).""" - parts = urlsplit(raw) - return len({name for name, _raw, _decoded in split_query(parts.query) if name}) - - -# --------------------------------------------------------------------------- -# Input handling -# --------------------------------------------------------------------------- -class InputError(RuntimeError): - """Raised for unreadable input files.""" - - -def read_input_file(path: str) -> List[str]: - try: - with open(path, "r", encoding="utf-8-sig", errors="replace") as handle: - return handle.read().splitlines() - except OSError as exc: - raise InputError( - f"cannot read input file '{path}': {exc.strerror or exc}" - ) from exc - - -def clean_input_lines( - lines: Iterable[str], label: str = "line" -) -> Tuple[List[str], List[str]]: - """Drop blanks/comments/duplicates, validate URLs. Returns (urls, warnings).""" - urls: List[str] = [] - warnings: List[str] = [] - seen = 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: - parse_target(candidate) - except URLParseError as exc: - warnings.append( - f"{label} {line_number}: skipped malformed URL ({exc}): " - f"{truncate(candidate, 100)}" - ) - continue - seen.add(candidate) - urls.append(candidate) - return urls, warnings - - -def dedupe(items: Iterable[str]) -> List[str]: - result: List[str] = [] - seen = set() - for item in items: - if item not in seen: - seen.add(item) - result.append(item) - return result - - -def stdin_has_data() -> bool: - try: - return sys.stdin is not None and not sys.stdin.isatty() - except Exception: # pragma: no cover - defensive only - return False - - -def read_stdin_lines() -> List[str]: - try: - return sys.stdin.read().splitlines() - except (OSError, ValueError): - return [] - - -# --------------------------------------------------------------------------- -# Rendering -# --------------------------------------------------------------------------- -def stream_supports_color(stream, disabled: bool = False) -> bool: - if disabled or os.environ.get("NO_COLOR"): - return False - if os.environ.get("TERM", "") == "dumb": - return False - try: - return bool(stream.isatty()) - except Exception: # pragma: no cover - defensive only - return False - - -class Palette: - """ANSI colours, used only when the target stream is an interactive terminal.""" - - def __init__(self, enabled: bool) -> None: - self.enabled = enabled - - def paint(self, style: str, text: str) -> str: - if not self.enabled: - return text - code = COLOR_CODES[style] - return f"\x1b[{code}m{text}\x1b[0m" - - def __getattr__(self, style: str) -> Callable[[str], str]: - if style not in COLOR_CODES: - raise AttributeError(style) - - def apply(text: str) -> str: - return self.paint(style, text) - - return apply - - -def render_banner(colors: Palette) -> str: - title = colors.bold(colors.cyan(f"{PROGRAM} {__version__} - passive URL-parameter triage")) - lines = [title, colors.grey("-" * 64)] - for label, url in BANNER_LINKS: - lines.append(f"{colors.bold(label + ':')} {colors.blue(url)}") - for line in BANNER_DISCLAIMER: - lines.append(colors.yellow(line)) - return "\n".join(lines) - - -def score_band(score: int) -> str: - if score >= 70: - return "HIGH" - if score >= 50: - return "MEDIUM" - return "LOW" - - -def render_report( - findings: Sequence[ParameterFinding], - *, - colors: Palette, - show_values: bool, - urls_analyzed: int, - parameters_analyzed: int, - min_score: int, - skipped: int, -) -> str: - lines: List[str] = [] - lines.append(colors.bold("Candidates for manual review")) - lines.append(colors.grey("=" * 64)) - lines.append( - f"Analyzed {urls_analyzed} URL(s) and {parameters_analyzed} distinct " - f"parameter(s); {len(findings)} candidate(s) at score >= {min_score}." - ) - if skipped: - lines.append(colors.yellow(f"Skipped {skipped} malformed input line(s).")) - lines.append("") - - if not findings: - lines.append( - colors.green( - "No path-like parameter candidates were flagged. " - "This is not proof that the application is safe." - ) - ) - else: - band_colors = {"HIGH": colors.red, "MEDIUM": colors.yellow, "LOW": colors.cyan} - for finding in findings: - band = finding.band - heading = ( - f"#{finding.index} {colors.bold(finding.parameter)} " - f"{band_colors[band](f'[{band} score {finding.score}/100]')}" - ) - lines.append(heading) - lines.append(f" {colors.grey('Host')} {finding.host}") - shown_url = finding.url if show_values else mask_url(finding.url) - lines.append(f" {colors.grey('URL')} {truncate(shown_url, 160)}") - if show_values: - value_text = truncate(finding.value or "", 120) or "" - else: - value_text = colors.grey("") - lines.append(f" {colors.grey('Parameter')} {finding.parameter}") - lines.append(f" {colors.grey('Value')} {value_text}") - if finding.occurrences > 1: - lines.append( - f" {colors.grey('Repeated')} x{finding.occurrences} " - "(best-scoring existing value shown)" - ) - lines.append(f" {colors.grey('Why flagged')}") - for reason in finding.reasons: - lines.append(f" - {reason}") - lines.append("") - - lines.append( - colors.grey( - "Reminder: candidates for manual review, not confirmed vulnerabilities. " - "No requests were sent and no input was injected." - ) - ) - if not show_values: - lines.append( - colors.grey( - "Values are hidden by default (use --show-values to display them)." - ) - ) - return "\n".join(lines) - - -# --------------------------------------------------------------------------- -# CLI -# --------------------------------------------------------------------------- -@dataclass -class RunConfig: - urls: List[str] - skipped: List[str] - json: bool = False - show_values: bool = False - no_banner: bool = False - no_color: bool = False - min_score: int = 30 - strict: bool = False - fail_on_none: bool = False - banner_printed: bool = False - - -def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser( - prog="path_detector.py", - description=( - "PathScope: passive triage of URL query parameters whose names or " - "existing values look path-like. Results are candidates for manual " - "review, never confirmed vulnerabilities. PathScope makes no network " - "requests and injects no test values." - ), - epilog=( - "examples:\n" - " python3 path_detector.py --url 'https://example.test/view?file=report.pdf'\n" - " python3 path_detector.py -i urls.txt\n" - " cat urls.txt | python3 path_detector.py\n" - " python3 path_detector.py -i urls.txt --json --show-values\n" - "\n" - "exit codes:\n" - " 0 completed 1 skipped lines with --strict 2 usage/input error\n" - " 3 no candidates with --fail-on-none 130 interrupted\n" - "\n" - "links (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 (merged and de-duplicated)") - source.add_argument( - "--url", - action="append", - default=[], - metavar="URL", - help="URL to analyze; may be repeated. Quote URLs containing '&'.", - ) - source.add_argument( - "-i", - "--input", - action="append", - default=[], - metavar="FILE", - help="read URLs from FILE (one per line); may be repeated. '-' reads " - "stdin. Blank lines and lines starting with '#' are skipped.", - ) - - output = parser.add_argument_group("output") - output.add_argument( - "--json", - action="store_true", - help="print machine-readable JSON on stdout (banner stays on stderr)", - ) - output.add_argument( - "--show-values", - action="store_true", - help="reveal existing parameter values; hidden/masked by default", - ) - output.add_argument( - "--no-color", - action="store_true", - help="disable ANSI colour even on a terminal", - ) - output.add_argument( - "--no-banner", - action="store_true", - help="do not print the startup banner and links", - ) - - heuristic = parser.add_argument_group("heuristics") - heuristic.add_argument( - "--min-score", - type=int, - default=30, - metavar="N", - help="report parameters scoring at least N (0-100, default: 30)", - ) - - behaviour = parser.add_argument_group("behaviour") - behaviour.add_argument( - "--strict", - action="store_true", - help="exit 1 if any input line was malformed or skipped", - ) - behaviour.add_argument( - "--fail-on-none", - action="store_true", - help="exit 3 when no candidates are flagged", - ) - return parser - - -def collect_inputs(parser: argparse.ArgumentParser, args: argparse.Namespace - ) -> Tuple[List[str], List[str]]: - """Merge --url, -i/--input and (when no source is given) piped stdin. - - Stdin is auto-detected only when neither --url nor -i/--input is present, - so an explicit source never blocks waiting for piped data. - """ - urls: List[str] = [] - warnings: List[str] = [] - stdin_consumed = False - - for path in args.input: - if path == "-": - if not stdin_has_data(): - parser.error("--input '-' was given but stdin is a terminal") - stdin_urls, stdin_warnings = clean_input_lines( - read_stdin_lines(), label="stdin" - ) - stdin_consumed = True - urls.extend(stdin_urls) - warnings.extend(stdin_warnings) - continue - try: - file_lines = read_input_file(path) - except InputError as exc: - parser.error(str(exc)) - file_urls, file_warnings = clean_input_lines(file_lines, label=path) - urls.extend(file_urls) - warnings.extend(file_warnings) - - url_values, url_warnings = clean_input_lines(args.url, label="--url") - urls.extend(url_values) - warnings.extend(url_warnings) - - if not stdin_consumed and not args.url and not args.input and stdin_has_data(): - piped_urls, piped_warnings = clean_input_lines(read_stdin_lines(), label="stdin") - urls.extend(piped_urls) - warnings.extend(piped_warnings) - - return dedupe(urls), warnings - - -def make_payload(config: RunConfig, findings: Sequence[ParameterFinding], - urls_analyzed: int, parameters_analyzed: int) -> dict: - return { - "tool": PROGRAM, - "version": __version__, - "disclaimer": ( - "Candidates for manual review only. PathScope is passive: it makes no " - "network requests, injects no values, and never confirms vulnerabilities." - ), - "min_score": config.min_score, - "show_values": config.show_values, - "summary": { - "urls_analyzed": urls_analyzed, - "parameters_analyzed": parameters_analyzed, - "candidates": len(findings), - "skipped_lines": len(config.skipped), - }, - "findings": [ - { - "index": finding.index, - "host": finding.host, - "parameter": finding.parameter, - "url": finding.url if config.show_values else mask_url(finding.url), - "value": finding.value if config.show_values else None, - "occurrences": finding.occurrences, - "score": finding.score, - "band": finding.band, - "reasons": list(finding.reasons), - } - for finding in findings - ], - "links": { - "github": GITHUB_URL, - "instagram": INSTAGRAM_URL, - "support": SUPPORT_URL, - }, - } - - -def run(config: RunConfig, stdout=None, stderr=None) -> int: - stdout = stdout if stdout is not None else sys.stdout - stderr = stderr if stderr is not None else sys.stderr - - if not config.no_banner and not config.banner_printed: - print( - render_banner(Palette(stream_supports_color(stderr, disabled=config.no_color))), - file=stderr, - ) - print("", file=stderr) - config.banner_printed = True - - out_colors = Palette(stream_supports_color(stdout, disabled=config.no_color)) - - for warning in config.skipped: - print(f"warning: {warning}", file=stderr) - - if not config.urls: - print("error: no usable URLs to analyze.", file=stderr) - print( - " Use --url URL, -i/--input FILE, or pipe URLs on stdin.", - file=stderr, - ) - print(" Try: python3 path_detector.py --help", file=stderr) - return EXIT_USAGE - - findings: List[ParameterFinding] = [] - urls_analyzed = 0 - parameters_analyzed = 0 - for url in config.urls: - try: - url_findings = analyze_url(url, min_score=config.min_score) - except URLParseError as exc: # defensive: validated earlier - print(f"warning: skipped URL ({exc})", file=stderr) - continue - urls_analyzed += 1 - parameters_analyzed += count_parameters(url) - findings.extend(url_findings) - - findings.sort(key=lambda finding: (-finding.score, finding.host, finding.parameter)) - for index, finding in enumerate(findings, start=1): - finding.index = index - - if config.json: - payload = make_payload(config, findings, urls_analyzed, parameters_analyzed) - json.dump(payload, stdout, indent=2, ensure_ascii=False) - stdout.write("\n") - else: - report = render_report( - findings, - colors=out_colors, - show_values=config.show_values, - urls_analyzed=urls_analyzed, - parameters_analyzed=parameters_analyzed, - min_score=config.min_score, - skipped=len(config.skipped), - ) - print(report, file=stdout) - print( - out_colors.grey( - f"\nDone: {urls_analyzed} URL(s), {len(findings)} candidate(s), " - f"{len(config.skipped)} line(s) skipped." - ), - file=stdout, - ) - - if config.strict and config.skipped: - return EXIT_STRICT_SKIPS - if config.fail_on_none and not findings: - return EXIT_NO_CANDIDATES - return EXIT_OK - - -def main(argv: Optional[Sequence[str]] = None, stdout=None, stderr=None) -> int: - parser = build_parser() - stderr = stderr if stderr is not None else sys.stderr - argv_list = list(sys.argv[1:] if argv is None else argv) - - # The banner is part of every invocation (including --help/--version). - if "--no-banner" not in argv_list: - banner_colors = Palette( - stream_supports_color(stderr, disabled="--no-color" in argv_list) - ) - print(render_banner(banner_colors), file=stderr) - print("", file=stderr) - banner_printed = "--no-banner" not in argv_list - - args = parser.parse_args(argv_list) - - if not 0 <= args.min_score <= 100: - parser.error("--min-score must be between 0 and 100") - - config = RunConfig(urls=[], skipped=[]) - config.json = args.json - config.show_values = args.show_values - config.no_banner = args.no_banner - config.no_color = args.no_color - config.min_score = args.min_score - config.strict = args.strict - config.fail_on_none = args.fail_on_none - config.banner_printed = banner_printed - - try: - config.urls, config.skipped = collect_inputs(parser, args) - except KeyboardInterrupt: - print("\ninterrupted", file=stderr) - return EXIT_INTERRUPTED - try: - return run(config, stdout=stdout, stderr=stderr) - except KeyboardInterrupt: - print("\ninterrupted", file=stderr) - return EXIT_INTERRUPTED +if __package__ in (None, ""): + _HERE = os.path.dirname(os.path.abspath(__file__)) + if _HERE not in sys.path: + sys.path.insert(0, _HERE) +from pathscope.cli import main # noqa: E402 (path setup must come first) if __name__ == "__main__": sys.exit(main()) diff --git a/pathscope/__init__.py b/pathscope/__init__.py new file mode 100644 index 0000000..5b0b228 --- /dev/null +++ b/pathscope/__init__.py @@ -0,0 +1,43 @@ +"""PathScope - passive, offline triage of path-like request parameters. + +Findings produced by this package are **heuristic candidates for manual +review**, not proof of any vulnerability. + +The package is deliberately conservative: + +* it only reads input the user supplies (URLs, stdin, local HAR files); +* it never imports networking or process modules (see ``tests/test_path_detector.py``); +* parameter values are treated as inert strings and are never resolved, + opened, or used as filesystem paths. +""" + +from __future__ import annotations + +PROGRAM = "PathScope" +__version__ = "2.0.0" + +# Displayed on every start. These are never opened and never requested. +GITHUB_URL = "https://github.com/mrdineshpathro" +INSTAGRAM_URL = "https://www.instagram.com/mr_dineshpatro" +SUPPORT_URL = "https://buymeacoffee.com/mrdineshpathro" + +BANNER_LINKS = ( + ("GitHub", GITHUB_URL), + ("Instagram", INSTAGRAM_URL), + ("Support", SUPPORT_URL), +) + + + +def banner_lines() -> tuple: + """The exact branding lines printed at startup (no colour applied).""" + return tuple(f"{label}: {url}" for label, url in BANNER_LINKS) + +__all__ = [ + "PROGRAM", + "__version__", + "GITHUB_URL", + "INSTAGRAM_URL", + "SUPPORT_URL", + "BANNER_LINKS", +] diff --git a/pathscope/__main__.py b/pathscope/__main__.py new file mode 100644 index 0000000..9859fbf --- /dev/null +++ b/pathscope/__main__.py @@ -0,0 +1,10 @@ +"""Allow ``python3 -m pathscope`` as well as ``python3 path_detector.py``.""" + +from __future__ import annotations + +import sys + +from .cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pathscope/cli.py b/pathscope/cli.py new file mode 100644 index 0000000..d066b04 --- /dev/null +++ b/pathscope/cli.py @@ -0,0 +1,414 @@ +"""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 sys +from typing import Optional, Sequence + +from . import ( + GITHUB_URL, + INSTAGRAM_URL, + PROGRAM, + SUPPORT_URL, + __version__, +) +from .config import Config, ConfigError, describe_schema, load_config, merge_ignore +from .detector import DEFAULT_MIN_SCORE, AnalysisOptions, analyze_requests, summarize +from .report import ( + FORMAT_JSON, + FORMAT_TEXT, + FORMATS, + Palette, + render, + render_banner, + supports_color, +) +from .sources import ( + INPUT_FORMAT_AUTO, + INPUT_FORMATS, + InputError, + LoadResult, + load_file, + load_stdin, + make_url_requests, +) +from .textutil import MAX_DECODE_PASSES + +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\n" + " 2 usage/input error 3 internal error 130 interrupted\n" + "\n" + "configuration 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}", + 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)", + ) + + output = parser.add_argument_group("output") + output.add_argument( + "--output-format", + choices=FORMATS, + default=None, + metavar="{text,json,csv,sarif}", + 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)", + ) + + tuning = parser.add_argument_group("detection and configuration") + 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", + ) + 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 _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 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 + config = Config() + if args.config: + try: + config = load_config(args.config) + except ConfigError as exc: + print(f"error: {exc}", file=stderr) + return EXIT_USAGE + + min_score = args.min_score if args.min_score is not None else config.min_score + if not 0 <= min_score <= 100: + parser.error("--min-score must be between 0 and 100") + + max_passes = ( + args.max_decode_passes + if args.max_decode_passes is not None + else config.max_decode_passes + ) + if not 0 <= max_passes <= 5: + parser.error("--max-decode-passes must be between 0 and 5") + + show_values = bool(args.show_values or config.show_values) + + 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() + + 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 + + if not quiet: + for warning in loaded.warnings: + print(f"warning: {warning}", file=stderr) + + 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, + ) + print(" Try: python3 path_detector.py --help", file=stderr) + return EXIT_USAGE + + options = AnalysisOptions( + min_score=min_score, + max_decode_passes=max_passes, + extra_terms=tuple(config.merged_terms()), + ignore_params=tuple(merge_ignore(args.ignore_param, config)), + show_values=show_values, + ) + + try: + report = analyze_requests(loaded.requests, options) + report.warnings = list(loaded.warnings) + report.skipped = loaded.skipped + colors = Palette(supports_color(stdout) and not args.no_color) + rendered = render(report, 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() + + if not quiet: + print(f"pathscope: {summarize(report)}", file=stderr) + if report.candidate_count and args.output_format == FORMAT_TEXT: + print( + "pathscope: candidates are for manual review, not confirmed vulnerabilities", + file=stderr, + ) + + if args.fail_on_findings and report.candidate_count: + return EXIT_FINDINGS + return EXIT_OK + + +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", +] diff --git a/pathscope/config.py b/pathscope/config.py new file mode 100644 index 0000000..62ec751 --- /dev/null +++ b/pathscope/config.py @@ -0,0 +1,183 @@ +"""Optional JSON configuration for PathScope. + +Schema (all keys optional, unknown keys rejected):: + + { + "name_terms": ["download", "media_file"], + "ignore_params": ["image", "avatar"], + "min_score": 25, + "max_decode_passes": 3, + "show_values": false + } + +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. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from typing import Any, Dict, List, 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 + + +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 + show_values: bool = False + source: str = "" + + 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 = { + "name_terms", + "ignore_params", + "min_score", + "max_decode_passes", + "show_values", +} + + +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() + 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 "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 + + return config + + +def load_config(path: str) -> Config: + """Read and validate ``path``. Raises :class:`ConfigError` on any problem.""" + 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 + + config = validate_payload(payload) + config.source = path + return config + + +def describe_schema() -> Tuple[str, ...]: + """Human-readable schema lines for ``--help`` and the README.""" + return ( + ' "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', + ' "show_values": false boolean', + ) + + +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, + "show_values": False, + } + + +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..b46c68a --- /dev/null +++ b/pathscope/detector.py @@ -0,0 +1,224 @@ +"""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 + +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional, Sequence, Tuple +from urllib.parse import urlsplit, urlunsplit + +from .heuristics import Analysis, analyze_parameter, canonical_name +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} + + +@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 + + +@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 + + 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, + } + + +@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 + + @property + def candidate_count(self) -> int: + return len(self.findings) + + @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}), + ) + ignored = {canonical_name(item) for item in options.ignore_params if item} + + findings: List[Finding] = [] + for request in _dedupe_requests(requests): + 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, + ) + 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 + findings.append( + Finding( + 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), + ) + ) + for index, finding in enumerate(findings, start=1): + finding.index = index + report.findings = findings + return report + + +def summarize(report: Report) -> str: + """One-line summary used by renderers and the CLI stderr trailer.""" + counts = report.confidence_counts + return ( + 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" + ) diff --git a/pathscope/heuristics.py b/pathscope/heuristics.py new file mode 100644 index 0000000..eabdb00 --- /dev/null +++ b/pathscope/heuristics.py @@ -0,0 +1,540 @@ +"""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``. ``docs/README`` documents each rule and its weight. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Dict, FrozenSet, Iterable, List, Tuple + +from .textutil import MAX_DECODE_PASSES, decode_forms, sanitize_text + +NAME_CAP = 45 +VALUE_CAP = 55 +MAX_SCORE = 100 + +#: 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 + +# --------------------------------------------------------------------------- +# 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) -> List[str]: + """Split a parameter name into lowercase tokens. + + ``fileName`` -> ``['file', 'name']`` + ``base_path`` -> ``['base', 'path']`` + ``X-File-Path`` -> ``['x', 'file', 'path']`` + """ + if not name: + return [] + text = sanitize_text(name).strip() + 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 analyze_name(name: str, extra_terms: Iterable[str] = ()) -> List[Evidence]: + """Return name-based evidence. + + Rules: + ``name-custom`` exact user-configured term, +30 + ``name-exact`` exact built-in path term, +35 (+5 multiword) + ``name-compound`` the whole name is a known compound, +35 + ``name-prefix`` name starts with a path term, +28 + ``name-suffix`` name ends with a path term, +23 + ``name-generic`` generic name (image/target/...), +0 (context only) + ``name-weak`` multiword name without a term, +5 (never alone) + """ + tokens = tokenize_name(name) + if not tokens: + return [] + joined = "".join(tokens) + lowered = sanitize_text(name).lower() + + 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"). + custom_candidates = [token for token in tokens if token in custom] + custom_candidates += [name for name in (joined, lowered, canonical_name(name)) if name 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 [ + Evidence( + "name-custom", + f"parameter name contains configured term '{term}' (+30)", + 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 "" + return [ + Evidence( + "name-exact", + f"parameter name contains path-related term '{best}' " + f"(+{STRONG_NAME_WEIGHT}{suffix})", + STRONG_NAME_WEIGHT + bonus, + "name", + ) + ] + + if "_" not in joined and joined in path_terms and len(joined) > 4: + return [ + Evidence( + "name-compound", + f"parameter name '{lowered}' is a known path compound (+{STRONG_NAME_WEIGHT})", + STRONG_NAME_WEIGHT, + "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 = STRONG_NAME_WEIGHT - PREFIX_DISCOUNT + return [ + Evidence( + "name-prefix", + f"parameter name starts with path-related term '{prefix_match}' (+{weight})", + weight, + "name", + ) + ] + if suffix_match: + weight = STRONG_NAME_WEIGHT - SUFFIX_DISCOUNT + return [ + Evidence( + "name-suffix", + f"parameter name ends with path-related term '{suffix_match}' (+{weight})", + weight, + "name", + ) + ] + + if any(token in GENERIC_NAME_TERMS for token in tokens): + return [ + Evidence( + "name-generic", + "parameter name is generic (image/target/ref/...): considered only " + "when its value is path-like (+0)", + 0, + "name", + ) + ] + + if len(tokens) > 1: + return [ + Evidence( + "name-weak", + "multiword parameter name without a path term (weak, +5)", + 5, + "name", + ) + ] + return [] + + +# --------------------------------------------------------------------------- +# Value analysis +# --------------------------------------------------------------------------- +def _is_segment_traversal(text: str) -> bool: + return bool(SEGMENT_TRAVERSAL_RE.search(text)) + + +def analyze_value( + value: str, max_decode_passes: int = MAX_DECODE_PASSES +) -> 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-full-url`` an ``scheme://`` URL, -10 + ``value-encoded`` informational only (0) + """ + 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.append( + Evidence( + "value-encoded-slash", + "value contains an encoded slash or backslash (%2f / %5c) (+12)", + 12, + "value", + ) + ) + if max_pass >= 2: + evidence.append( + Evidence( + "value-double-encoded", + f"value required {max_pass} decoding passes (nested encoding) (+10)", + 10, + "value", + ) + ) + + if _is_segment_traversal(raw): + evidence.append( + Evidence( + "value-traversal", + "value contains a '..' path segment ('../', '..\\' or bare '..') (+30)", + 30, + "value", + ) + ) + shape = raw + elif _is_segment_traversal(deepest): + evidence.append( + Evidence( + "value-encoded-traversal", + "value contains a '..' segment only after percent-decoding (+15)", + 15, + "value", + ) + ) + shape = deepest + else: + shape = deepest + + if WINDOWS_DRIVE_RE.match(shape): + evidence.append( + Evidence( + "value-windows-drive", + "value looks like a Windows drive path ('C:\\...') (+15)", + 15, + "value", + ) + ) + elif UNC_PATH_RE.match(shape): + evidence.append( + Evidence( + "value-unc", + "value looks like a Windows UNC path ('\\\\server\\share') (+15)", + 15, + "value", + ) + ) + elif ABSOLUTE_PATH_RE.match(shape): + evidence.append( + Evidence( + "value-absolute", + "value starts with a path separator (absolute-looking) (+12)", + 12, + "value", + ) + ) + + if FULL_URL_RE.match(shape): + evidence.append( + Evidence( + "value-full-url", + "value is a full URL rather than a local path (-10)", + -10, + "value", + ) + ) + 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.append( + Evidence( + "value-multi-segment", + f"value contains {separators} path separators (+6)", + 6, + "value", + ) + ) + extension = extension_of(shape) + if extension: + evidence.append( + Evidence( + "value-extension", + f"value ends with a file-like extension '.{extension}' (+8)", + 8, + "value", + ) + ) + if separators and any(sep in shape for sep in (";", ",")): + evidence.append( + Evidence( + "value-path-list", + "value looks like a semicolon/comma separated list of paths (+5)", + 5, + "value", + ) + ) + + # 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] + + +# --------------------------------------------------------------------------- +# 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, +) -> 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) + value_evidence = analyze_value(value, max_decode_passes) + + 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: + evidence.append( + Evidence( + "value-pairs-with-generic-name", + f"generic parameter name is paired with a path-like value (+{GENERIC_BONUS})", + GENERIC_BONUS, + "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/report.py b/pathscope/report.py new file mode 100644 index 0000000..c8006d5 --- /dev/null +++ b/pathscope/report.py @@ -0,0 +1,349 @@ +"""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 Report +from .textutil import encode_display, sanitize_text, truncate + +FORMAT_TEXT = "text" +FORMAT_JSON = "json" +FORMAT_CSV = "csv" +FORMAT_SARIF = "sarif" +FORMATS = (FORMAT_TEXT, FORMAT_JSON, FORMAT_CSV, FORMAT_SARIF) + +CSV_COLUMNS = ( + "index", + "host", + "source_type", + "source", + "method", + "location", + "parameter", + "rule", + "rules", + "confidence", + "score", + "reasons", + "resource", + "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 render_text(report: Report, colors: Palette) -> 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.", + ) + ) + for finding in report.findings: + 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':<10} {finding.host}") + lines.append(f" {'Source':<10} {finding.source_type}" + f" ({truncate(encode_display(finding.source_label), 60)})") + lines.append(f" {'Request':<10} {finding.method} {truncate(encode_display(finding.resource), 110)}") + lines.append(f" {'Location':<10} {finding.location}") + lines.append(f" {'Rule':<10} {finding.rule}") + if finding.occurrences > 1: + lines.append(f" {'Repeats':<10} {finding.occurrences} occurrence(s)") + if report.show_values: + shown = truncate(encode_display(finding.value or ""), 120) + lines.append(f" {'Value':<10} {shown if shown else ''}") + else: + lines.append( + f" {'Value':<10} {colors.paint('grey', '')} " + f"(use --show-values to display)" + ) + lines.append(f" {'Why':<10}rule(s) and evidence:") + for reason in finding.reasons: + lines.append(f" - {truncate(encode_display(reason), 140)}") + 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), + }, + "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.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, + "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, + }, + } + ) + + 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: + 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) + return render_text(report, colors) + + +# --------------------------------------------------------------------------- +# Banner +# --------------------------------------------------------------------------- +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/sources.py b/pathscope/sources.py new file mode 100644 index 0000000..304181b --- /dev/null +++ b/pathscope/sources.py @@ -0,0 +1,577 @@ +"""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" +INPUT_FORMATS = (INPUT_FORMAT_AUTO, INPUT_FORMAT_URLS, INPUT_FORMAT_HAR) + + +def detect_input_format(text: str, path: str = "") -> str: + """Return ``har`` or ``urls`` for a text blob and optional filename.""" + return INPUT_FORMAT_HAR if looks_like_har(text, path) else INPUT_FORMAT_URLS + + +def load_file(path: str, input_format: str = INPUT_FORMAT_AUTO) -> LoadResult: + """Load a file as URLs or HAR, honouring an explicit format when given.""" + if input_format == INPUT_FORMAT_HAR: + return load_har_file(path) + if input_format == INPUT_FORMAT_URLS: + return load_url_file(path) + text = read_text(path) + if detect_input_format(text, path) == INPUT_FORMAT_HAR: + return load_har(text, os.path.basename(path) or path, source_label=path) + return load_url_lines(text.splitlines(), SOURCE_FILE, path) + + +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 detect_input_format(text) == INPUT_FORMAT_HAR: + return load_stdin_har(text) + return load_stdin_urls(text) + + +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/textutil.py b/pathscope/textutil.py new file mode 100644 index 0000000..5231a3a --- /dev/null +++ b/pathscope/textutil.py @@ -0,0 +1,109 @@ +"""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 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/tests/test_path_detector.py b/tests/test_path_detector.py index 5b68a90..cc5f887 100755 --- a/tests/test_path_detector.py +++ b/tests/test_path_detector.py @@ -1,23 +1,29 @@ #!/usr/bin/env python3 -"""Unit tests for PathScope. +"""Tests for PathScope (stdlib ``unittest`` only, fully offline). + +Run from the project root: -Run with: python3 -m unittest discover -s tests -v -or: python3 tests/test_path_detector.py -The tests are split into four groups: - 1. heuristic unit tests (names, values, extensions), - 2. URL parsing / analysis tests (repeats, encoding, masking), - 3. input handling tests (files, blank lines, duplicates), - 4. end-to-end CLI tests, including safety guarantees. +Coverage maps to the project requirements: -Everything runs offline: PathScope never opens a socket, and one test proves it. +* 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 @@ -31,17 +37,66 @@ SCRIPT = REPO_ROOT / "path_detector.py" sys.path.insert(0, str(REPO_ROOT)) -import path_detector as pd # noqa: E402 (path setup must happen first) +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", + } + ), + }, + } + }, + ], + } +} + -BANNER_LINKS = ( - ("GitHub", "https://github.com/mrdineshpathro"), - ("Instagram", "https://www.instagram.com/mr_dineshpatro"), - ("Support", "https://buymeacoffee.com/mrdineshpathro"), -) +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 = 30) -> subprocess.CompletedProcess: - """Run the real CLI as a subprocess (no TTY, so no colour).""" +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" @@ -56,568 +111,1000 @@ def run_cli(*args: str, stdin: str = "", timeout: int = 30) -> subprocess.Comple ) +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 + + # --------------------------------------------------------------------------- -# 1. Heuristic unit tests +# textutil # --------------------------------------------------------------------------- -class TestTokenizeName(unittest.TestCase): - def test_snake_case(self): - self.assertEqual(pd.tokenize_name("file_path"), ["file", "path"]) +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_kebab_case(self): - self.assertEqual(pd.tokenize_name("user-file-name"), ["user", "file", "name"]) + def test_truncate(self): + self.assertEqual(textutil.truncate("abcdef", 4), "abc\u2026") + self.assertEqual(textutil.truncate("abc", 10), "abc") - def test_camel_case(self): - self.assertEqual(pd.tokenize_name("fileName"), ["file", "name"]) + def test_decode_single(self): + decoded, passes = textutil.decode_value("%2e%2e%2fetc") + self.assertEqual(decoded, "../etc") + self.assertEqual(passes, 1) - def test_pascal_case(self): - self.assertEqual(pd.tokenize_name("DownloadFile"), ["download", "file"]) + def test_decode_multi(self): + decoded, passes = textutil.decode_value("%252e%252e%252fetc") + self.assertEqual(decoded, "../etc") + self.assertEqual(passes, 2) - def test_mixed_noise(self): - self.assertEqual(pd.tokenize_name(" TEMPLATE__id "), ["template", "id"]) + 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_empty(self): - self.assertEqual(pd.tokenize_name(""), []) + 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)) -class TestAnalyzeName(unittest.TestCase): - def test_strong_keyword(self): - analysis = pd.analyze_name("file") - self.assertGreaterEqual(analysis.score, 30) - self.assertEqual(analysis.keyword, "file") + def test_decode_forms_dedupes(self): + forms = textutil.decode_forms("plain") + self.assertEqual(forms, [(0, "plain")]) - def test_compound_keyword(self): - analysis = pd.analyze_name("basepath") - self.assertGreaterEqual(analysis.score, 25) + def test_dedupe_preserves_order(self): + self.assertEqual(textutil.dedupe(["b", "a", "b", "c", "a"]), ["b", "a", "c"]) - def test_camel_compound(self): - analysis = pd.analyze_name("downloadFile") - self.assertGreaterEqual(analysis.score, 35) + def test_encode_display_flattens_whitespace(self): + self.assertEqual(textutil.encode_display("a\nb\tc"), "a b c") - def test_prefix_match(self): - analysis = pd.analyze_name("filedata") - self.assertIsNotNone(analysis.reason) - self.assertGreater(analysis.score, 0) - def test_generic_name_is_not_a_keyword(self): - analysis = pd.analyze_name("image") - self.assertTrue(analysis.generic) - self.assertEqual(analysis.score, 0) - self.assertIsNone(analysis.reason) +# --------------------------------------------------------------------------- +# 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") - def test_unrelated_simple_name(self): - analysis = pd.analyze_name("q") - self.assertEqual(analysis.score, 0) - def test_weak_multipart_name(self): - analysis = pd.analyze_name("some_thing") - self.assertTrue(analysis.weak) - self.assertLess(analysis.score, 15) +# --------------------------------------------------------------------------- +# 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_unrelated_name_does_not_mention_exploit(self): - analysis = pd.analyze_name("path") - self.assertNotIn("exploit", (analysis.reason or "").lower()) + 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", "12345", "true", "50%", "%zz", "name"): + self.assertEqual(self.score(value), 0, value) + + 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) -class TestExtensionOf(unittest.TestCase): - def test_common_extension(self): - self.assertEqual(pd.extension_of("report.pdf"), "pdf") +# --------------------------------------------------------------------------- +# 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_path_extension(self): - self.assertEqual(pd.extension_of("../../etc/shadow.txt"), "txt") + def test_empty_query(self): + self.assertEqual(sources.query_parameters(""), []) - def test_multi_extension(self): - self.assertEqual(pd.extension_of("backup.tar.gz"), "tar.gz") + def test_blank_query_chunks_are_skipped(self): + self.assertEqual([p.name for p in sources.query_parameters("&&a=1&&")], ["a"]) - def test_no_extension(self): - self.assertIsNone(pd.extension_of("justwords")) + 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_unknown_extension(self): - self.assertIsNone(pd.extension_of("malware.xyzzy")) + 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/") -class TestAnalyzeValue(unittest.TestCase): - def test_file_name(self): - analysis = pd.analyze_value("report.pdf") - self.assertGreaterEqual(analysis.score, 20) - self.assertTrue(any("pdf" in reason for reason in analysis.reasons)) + def test_ipv6_display(self): + info = sources.parse_url("http://[::1]:8080/?file=x") + self.assertEqual(info.display_host, "[::1]:8080") - def test_plain_word(self): - self.assertEqual(pd.analyze_value("hello").score, 0) - def test_empty_value(self): - self.assertEqual(pd.analyze_value("").score, 0) +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) - def test_traversal(self): - analysis = pd.analyze_value("../../etc/passwd") - self.assertGreaterEqual(analysis.score, 40) - self.assertTrue(any("parent-directory" in reason for reason in analysis.reasons)) - def test_encoded_traversal_counts_once(self): - encoded = pd.analyze_value("%2e%2e%2f%2e%2e%2fetc%2fpasswd") - decoded = pd.analyze_value("../../etc/passwd") - self.assertGreaterEqual(encoded.score, 30) - self.assertLessEqual(encoded.score, decoded.score) +# --------------------------------------------------------------------------- +# 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)) - def test_encoded_slash(self): - analysis = pd.analyze_value("%2fadmin%2fpanel") - self.assertGreater(analysis.score, 0) - self.assertTrue(any("%2f" in reason for reason in analysis.reasons)) - def test_double_encoded(self): - analysis = pd.analyze_value("%252e%252e%252f") - self.assertTrue(any("double-encoded" in reason for reason in analysis.reasons)) +# --------------------------------------------------------------------------- +# 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_absolute_path(self): - analysis = pd.analyze_value("/var/log/app.log") - self.assertGreaterEqual(analysis.score, 30) + 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_windows_path(self): - analysis = pd.analyze_value(r"C:\Windows\win.ini") - self.assertGreaterEqual(analysis.score, 30) + 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_current_directory(self): - analysis = pd.analyze_value("./") - self.assertGreaterEqual(analysis.score, 5) + def test_sources_are_listed(self): + result = self.analyze(["https://a.test/?file=x.pdf"]) + self.assertEqual(result.sources, ["--url"]) - def test_full_url_is_penalised(self): - url = pd.analyze_value("https://example.test/a/b/c.txt") - path = pd.analyze_value("/a/b/c.txt") - self.assertLess(url.score, path.score) + 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_reasons_are_strings(self): - analysis = pd.analyze_value("../../etc/passwd") - self.assertTrue(all(isinstance(reason, str) for reason in analysis.reasons)) + def test_empty_input(self): + result = detector.analyze_requests([], detector.AnalysisOptions()) + self.assertEqual(result.candidate_count, 0) + self.assertEqual(result.requests_analyzed, 0) # --------------------------------------------------------------------------- -# 2. URL parsing and analysis +# Report formats # --------------------------------------------------------------------------- -class TestParseTarget(unittest.TestCase): - def test_valid_https(self): - target = pd.parse_target("https://example.test/path?file=a.txt") - self.assertEqual(target.scheme, "https") - self.assertEqual(target.host, "example.test") - self.assertEqual(target.path, "/path") - - def test_uppercase_scheme_and_host(self): - target = pd.parse_target("HTTPS://Example.Test/x") - self.assertEqual(target.scheme, "https") - self.assertEqual(target.host, "example.test") - - def test_custom_port_display(self): - target = pd.parse_target("http://example.test:8080/") - self.assertEqual(pd.display_host(target), "example.test:8080") - - def test_ipv6_is_accepted(self): - target = pd.parse_target("http://[::1]:8080/?path=/tmp") - self.assertIn("::1", target.host) - - def test_missing_scheme(self): - with self.assertRaises(pd.URLParseError): - pd.parse_target("example.test/view?file=a.txt") - - def test_unsupported_scheme(self): - with self.assertRaises(pd.URLParseError): - pd.parse_target("ftp://example.test/file.txt") - - def test_javascript_scheme_rejected(self): - with self.assertRaises(pd.URLParseError): - pd.parse_target("javascript:alert(1)") - - def test_missing_host(self): - with self.assertRaises(pd.URLParseError): - pd.parse_target("https:///path") - - def test_whitespace_rejected(self): - with self.assertRaises(pd.URLParseError): - pd.parse_target("https://example.test/a b?file=x") - - def test_bad_port_rejected(self): - with self.assertRaises(pd.URLParseError): - pd.parse_target("https://example.test:99999/") - - -class TestSplitQuery(unittest.TestCase): - def test_pairs(self): - pairs = pd.split_query("a=1&b=2") - self.assertEqual([(name, raw, value) for name, raw, value in pairs], - [("a", "1", "1"), ("b", "2", "2")]) - - def test_blank_value_is_kept(self): - pairs = pd.split_query("file=") - self.assertEqual(len(pairs), 1) - self.assertEqual(pairs[0][2], "") - - def test_repeated_names_are_kept(self): - pairs = pd.split_query("file=a&file=b") - self.assertEqual([pair[2] for pair in pairs], ["a", "b"]) - - def test_encoded_name_and_value_are_decoded_once(self): - pairs = pd.split_query("%66%69%6c%65=..%2Freport.pdf") - self.assertEqual(pairs[0][0], "file") - self.assertEqual(pairs[0][1], "..%2Freport.pdf") - self.assertEqual(pairs[0][2], "../report.pdf") - - def test_empty_query(self): - self.assertEqual(pd.split_query(""), []) - - -class TestAnalyzeURL(unittest.TestCase): - def test_flags_file_parameter(self): - findings = pd.analyze_url("https://example.test/view?file=report.pdf") - self.assertEqual(len(findings), 1) - self.assertEqual(findings[0].parameter, "file") - self.assertEqual(findings[0].host, "example.test") - self.assertGreaterEqual(findings[0].score, 30) - - def test_never_uses_vulnerability_language(self): - findings = pd.analyze_url("https://example.test/get?doc=../../etc/passwd") - text = " ".join(reason for finding in findings for reason in finding.reasons) - for word in ("vulnerable", "exploitable", "confirmed", "LFI found"): - self.assertNotIn(word.lower(), text.lower()) - - def test_unrelated_parameter_is_not_flagged(self): - self.assertEqual(pd.analyze_url("https://example.test/?q=hello&utm_source=news"), []) - - def test_page_is_a_keyword_but_requires_the_default_threshold(self): - findings = pd.analyze_url("https://example.test/?page=2") - self.assertEqual([finding.parameter for finding in findings], ["page"]) - self.assertLess(pd.analyze_url("https://example.test/?page=2")[0].score, 50) - - def test_encoded_parameter_name_is_decoded(self): - findings = pd.analyze_url("https://example.test/?%66%69%6c%65=report.pdf") - self.assertEqual([finding.parameter for finding in findings], ["file"]) - - def test_repeated_parameters_are_merged(self): - findings = pd.analyze_url( - "https://example.test/?file=one.txt&file=two.txt&file=three.pdf" +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) ) - self.assertEqual(len(findings), 1) - self.assertEqual(findings[0].occurrences, 3) - # All occurrences score equally, so the first existing value is kept. - self.assertEqual(findings[0].value, "one.txt") - - def test_repeated_parameters_keep_best_scoring_value(self): - findings = pd.analyze_url( - "https://example.test/?file=one.txt&file=../../etc/passwd" + + 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") + 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()), ) - self.assertEqual(len(findings), 1) - self.assertEqual(findings[0].occurrences, 2) - self.assertEqual(findings[0].value, "../../etc/passwd") - - def test_generic_name_requires_path_like_value(self): - self.assertEqual(pd.analyze_url("https://example.test/?image=logo"), []) - flagged = pd.analyze_url("https://example.test/?image=/static/logo.png") - self.assertEqual([finding.parameter for finding in flagged], ["image"]) - - def test_generic_name_never_stands_alone(self): - findings = pd.analyze_url("https://example.test/?target=homepage") - self.assertEqual(findings, []) - - def test_results_are_sorted_by_score(self): - findings = pd.analyze_url( - "https://example.test/?page=2&file=report.pdf&dir=../../etc" + + 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) ) - scores = [finding.score for finding in findings] - self.assertEqual(scores, sorted(scores, reverse=True)) - self.assertEqual([finding.index for finding in findings], - list(range(1, len(findings) + 1))) - - def test_min_score_threshold(self): - url = "https://example.test/?file=report.pdf" - self.assertTrue(pd.analyze_url(url, min_score=30)) - self.assertEqual(pd.analyze_url(url, min_score=90), []) - - def test_no_query_returns_empty(self): - self.assertEqual(pd.analyze_url("https://example.test/path"), []) - - def test_bare_key_without_value_is_tolerated(self): - findings = pd.analyze_url("https://example.test/?file") - self.assertEqual(len(findings), 1) - self.assertEqual(findings[0].occurrences, 1) - - def test_host_without_port_in_finding(self): - findings = pd.analyze_url("https://example.test:443/?file=a.txt") - self.assertEqual(findings[0].host, "example.test") - - def test_malformed_url_raises(self): - with self.assertRaises(pd.URLParseError): - pd.analyze_url("not a url") - - def test_mask_url(self): - masked = pd.mask_url("https://example.test/a?file=secret.pdf&x=1#frag") - self.assertNotIn("secret.pdf", masked) - self.assertIn("file=", masked) - self.assertIn("x=", masked) - - def test_findings_never_contain_credentials(self): - findings = pd.analyze_url("https://alice:hunter2@example.test/?file=a.txt") - self.assertEqual(len(findings), 1) - self.assertNotIn("hunter2", findings[0].url) - self.assertIn("@example.test", findings[0].url) - - def test_mask_url_hides_credentials(self): - masked = pd.mask_url("https://alice:hunter2@example.test/?file=a.txt") - self.assertNotIn("hunter2", masked) - self.assertIn("@example.test", masked) - - def test_count_parameters(self): - self.assertEqual( - pd.count_parameters("https://example.test/?a=1&b=2&a=3"), 2 + 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) + # --------------------------------------------------------------------------- -# 3. Input handling +# Configuration # --------------------------------------------------------------------------- -class TestCleanInputLines(unittest.TestCase): - def test_blank_lines_comments_and_duplicates(self): - urls, warnings = pd.clean_input_lines( - [ - "", - " ", - "# a comment", - "https://a.test/?file=x", - "https://a.test/?file=x", - "https://b.test/?page=2", - ] +class TestConfig(unittest.TestCase): + def test_valid_config(self): + cfg = config.validate_payload( + {"name_terms": ["download"], "ignore_params": ["image"], "min_score": 10} ) - self.assertEqual(urls, ["https://a.test/?file=x", "https://b.test/?page=2"]) - self.assertEqual(warnings, []) - - def test_malformed_lines_are_reported_with_line_numbers(self): - urls, warnings = pd.clean_input_lines(["", "not-a-url", "https://ok.test/?a=1"]) - self.assertEqual(urls, ["https://ok.test/?a=1"]) - self.assertEqual(len(warnings), 1) - self.assertIn("line 2", warnings[0]) - - def test_custom_label_for_warnings(self): - _urls, warnings = pd.clean_input_lines(["bogus"], label="--url") - self.assertIn("--url 1", warnings[0]) - + 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"]) -class TestReadInputFile(unittest.TestCase): - def test_reads_utf8_with_bom(self): - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "urls.txt" - path.write_bytes(b"\xef\xbb\xbfhttps://a.test/?file=x\n\n") - lines = pd.read_input_file(str(path)) - self.assertIn("https://a.test/?file=x", [line.strip() for line in lines]) - def test_missing_file_raises_input_error(self): - with self.assertRaises(pd.InputError): - pd.read_input_file("/definitely/not/here/urls.txt") +# --------------------------------------------------------------------------- +# 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_input_error(self): + def test_directory_raises(self): with tempfile.TemporaryDirectory() as tmp: - with self.assertRaises(pd.InputError): - pd.read_input_file(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) # --------------------------------------------------------------------------- -# 4. CLI behaviour (subprocess) +# CLI # --------------------------------------------------------------------------- -class TestCLI(unittest.TestCase): - def assert_links_present(self, text: str) -> None: +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}", text) - - def test_banner_links_are_exact(self): - result = run_cli("--no-banner", "--url", "https://a.test/?file=x") - self.assertNotIn("GitHub:", result.stderr) - self.assertNotIn("instagram.com", result.stderr) - - result = run_cli("--url", "https://a.test/?file=x") - self.assert_links_present(result.stderr) + self.assertIn(f"{label}: {url}", err) + self.assertEqual(err.count("PathScope " + __version__), 1) - def test_banner_without_arguments(self): - result = run_cli() - self.assert_links_present(result.stderr) - self.assertEqual(result.returncode, pd.EXIT_USAGE) + 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_banner_printed_once(self): - result = run_cli("--url", "https://a.test/?file=x") - self.assertEqual(result.stderr.count("PathScope " + pd.__version__), 1) - - def test_help_shows_banner_and_usage(self): + def test_help(self): result = run_cli("--help") self.assertEqual(result.returncode, 0) self.assertIn("usage:", result.stdout) - self.assert_links_present(result.stderr) - self.assertIn("examples:", result.stdout) - self.assertIn("https://github.com/mrdineshpathro", 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(pd.__version__, result.stdout) + self.assertIn(__version__, result.stdout) - def test_single_url_hides_value_by_default(self): - result = run_cli("--url", "https://example.test/view?file=report.pdf") + 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("example.test", result.stdout) + self.assertIn("name-exact", result.stdout) + self.assertIn("candidates for manual review", result.stdout.lower()) self.assertNotIn("report.pdf", result.stdout) - self.assertIn("", result.stdout) - def test_show_values_reveals_value(self): + def test_show_values(self): result = run_cli( - "--url", "https://example.test/view?file=report.pdf", "--show-values" + "--no-banner", "--show-values", "--url", "https://a.test/?file=report.pdf" ) - self.assertEqual(result.returncode, 0) self.assertIn("report.pdf", result.stdout) - def test_no_ansi_colour_when_piped(self): - result = run_cli("--url", "https://example.test/?file=report.pdf") + 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_output_is_valid_and_hides_values(self): - result = run_cli( - "--json", "--url", "https://example.test/?file=report.pdf&q=hello" - ) - self.assertEqual(result.returncode, 0) + 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.assertEqual(payload["summary"]["urls_analyzed"], 1) - self.assertEqual(payload["summary"]["candidates"], 1) - finding = payload["findings"][0] - self.assertEqual(finding["parameter"], "file") - self.assertIsNone(finding["value"]) - self.assertNotIn("report.pdf", result.stdout) - self.assertIn("", finding["url"]) + self.assertIsNone(payload["findings"][0]["value"]) - def test_json_show_values(self): - result = run_cli( - "--json", "--show-values", - "--url", "https://example.test/?file=report.pdf", - ) - payload = json.loads(result.stdout) - self.assertEqual(payload["findings"][0]["value"], "report.pdf") - - def test_json_has_disclaimer_and_links(self): - payload = json.loads( - run_cli("--json", "--url", "https://a.test/?file=x").stdout - ) - self.assertIn("manual review", payload["disclaimer"].lower()) - self.assertEqual(payload["links"]["github"], pd.GITHUB_URL) - self.assertEqual(payload["links"]["instagram"], pd.INSTAGRAM_URL) - self.assertEqual(payload["links"]["support"], pd.SUPPORT_URL) + 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): - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "urls.txt" - path.write_text( - "\n".join( - [ - "", - "# comment", - "https://a.test/?file=one.txt", - "", - "not a url", - "https://b.test/?page=2", - ] - ), - encoding="utf-8", - ) - result = run_cli("-i", str(path)) + 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) - self.assertIn("Analyzed 2 URL(s)", result.stdout) - def test_multiple_input_files(self): - with tempfile.TemporaryDirectory() as tmp: - first = Path(tmp) / "one.txt" - second = Path(tmp) / "two.txt" - first.write_text("https://a.test/?file=one.txt\n", encoding="utf-8") - second.write_text("https://b.test/?path=/var/log\n", encoding="utf-8") - result = run_cli( - "--no-banner", "--json", "-i", str(first), "-i", str(second) - ) + 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.assertEqual(json.loads(result.stdout)["summary"]["urls_analyzed"], 2) + self.assertIn("Source", result.stdout) - def test_stdin_pipe(self): - result = run_cli(stdin="https://a.test/?file=one.txt\nhttps://b.test/?path=x\n") - self.assertEqual(result.returncode, 0) - self.assertIn("Analyzed 2 URL(s)", 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("-i", "-", stdin="https://a.test/?file=one.txt\n") + result = run_cli("--no-banner", "-q", "-i", "-", stdin="https://a.test/?file=x.pdf\n") self.assertEqual(result.returncode, 0) - self.assertIn("1 candidate", result.stdout) + self.assertIn("file", result.stdout) - def test_duplicate_urls_counted_once(self): - result = run_cli( - "--json", - stdin="https://a.test/?file=one.txt\nhttps://a.test/?file=one.txt\n", - ) - payload = json.loads(result.stdout) - self.assertEqual(payload["summary"]["urls_analyzed"], 1) + 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_missing_input_file_exits_2(self): + 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, pd.EXIT_USAGE) + self.assertEqual(result.returncode, cli.EXIT_USAGE) self.assertIn("cannot read input file", result.stderr) - def test_invalid_min_score_exits_2(self): - result = run_cli("--no-banner", "--min-score", "101", "--url", "https://a.test/") - self.assertEqual(result.returncode, pd.EXIT_USAGE) - - def test_strict_mode_exits_1_on_bad_lines(self): - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "urls.txt" - path.write_text("bogus\nhttps://a.test/?file=x\n", encoding="utf-8") - result = run_cli("--no-banner", "--strict", "-i", str(path)) - self.assertEqual(result.returncode, pd.EXIT_STRICT_SKIPS) - - def test_fail_on_none_exits_3(self): - result = run_cli("--no-banner", "--fail-on-none", "--url", "https://a.test/?q=hi") - self.assertEqual(result.returncode, pd.EXIT_NO_CANDIDATES) + 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_fail_on_none_is_zero_when_candidates_exist(self): + def test_ignore_param_flag(self): result = run_cli( - "--no-banner", "--fail-on-none", "--url", "https://a.test/?file=a.txt" + "--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_url_with_encoded_ampersand_and_equals(self): + 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", - "--json", - "--url", - "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.txt", + "--no-banner", "-q", "--json", + "--url", "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.pdf", ) - self.assertEqual(result.returncode, 0) payload = json.loads(result.stdout) self.assertEqual(payload["summary"]["parameters_analyzed"], 2) - def test_no_usable_urls_exits_2(self): - result = run_cli("--no-banner", stdin="# only a comment\n\n") - self.assertEqual(result.returncode, pd.EXIT_USAGE) - self.assertIn("no usable URLs", result.stderr) - # --------------------------------------------------------------------------- -# 5. Safety guarantees +# Safety # --------------------------------------------------------------------------- -ALLOWED_IMPORTS = { - "__future__", - "argparse", - "collections", - "dataclasses", - "json", - "os", - "re", - "sys", - "typing", - "unicodedata", - "urllib", -} FORBIDDEN_MODULES = { "socket", "ssl", "http", + "https", + "urllib.request", "urllib3", "requests", "httpx", @@ -626,40 +1113,100 @@ def test_no_usable_urls_exits_2(self): "smtplib", "telnetlib", "subprocess", - "scapy", + "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_only_standard_library_imports(self): - tree = ast.parse(SCRIPT.read_text(encoding="utf-8")) - imported: set[str] = set() - for node in ast.walk(tree): - if isinstance(node, ast.Import): - imported.update(alias.name.split(".")[0] for alias in node.names) - elif isinstance(node, ast.ImportFrom) and node.module: - imported.add(node.module.split(".")[0]) - self.assertLessEqual(imported, ALLOWED_IMPORTS) - self.assertFalse(imported & FORBIDDEN_MODULES) - - def test_no_network_calls_during_analysis(self): + 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", + } + 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): - findings = pd.analyze_url( - "https://example.test/?file=../../etc/passwd&next=https://evil.test/" + 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.assertTrue(findings) - - def test_module_has_no_root_requirement(self): - source = SCRIPT.read_text(encoding="utf-8") - for marker in ("os.geteuid", "os.seteuid", "sudo", "setuid"): - self.assertNotIn(marker, source) + 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__": From dfb88c48fa9f5e3c9a12b85619e2fe07b2eab0a3 Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:08:42 +0000 Subject: [PATCH 3/8] Add PathScope 2.1 feature set: presets, diff, formats, reports, UX Features - presets: minimal (>=50, weak names off), balanced (>=25), noisy (>=10), with strict/high/default/loud/broad aliases; --init-config writes a validated starter JSON and refuses to overwrite - config inheritance: validated 'extends' (preset name or relative .json), list merge, scalar override, cycle + depth (4) protection - Baselines/diff: stable 16-hex fingerprints (host+location+param+rule+path), --baseline and --suppress, --show-known, resolved list, --mark-reviewed ledger; --fail-on-findings gates on new candidates in diff mode - inputs: Burp proxy XML (base64/plain, form/JSON/multipart), OpenAPI/Swagger parameter inventory, raw HTTP requests (### separated), recon exports (httpx/ffuf/katana/nuclei lines and JSONL) with auto-detection refined so plain URL lists keep their format - outputs: Markdown and HTML reports (--save-report, --output-format), fully escaped, plus fingerprints/status in JSON, CSV and SARIF partialFingerprints - UX: --explain/--explain-value scoring trace, --top, --group-by, --summary-only compact view Tests: 209 total (71 new) covering presets, extends cycles, fingerprint stability, baseline flows and exit codes, suppression ledgers, explain output, Burp/OpenAPI/raw/recon parsing, Markdown/HTML escaping, and new report metadata. README updated with presets, diff workflow, extra inputs and CLI reference. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 154 ++++++- pathscope/__init__.py | 2 +- pathscope/cli.py | 394 ++++++++++++++-- pathscope/config.py | 128 +++++- pathscope/detector.py | 125 ++++- pathscope/extra_formats.py | 693 ++++++++++++++++++++++++++++ pathscope/heuristics.py | 9 +- pathscope/presets.py | 126 +++++ pathscope/report.py | 132 +++++- pathscope/sources.py | 78 +++- pathscope/writers.py | 274 +++++++++++ tests/test_features.py | 895 ++++++++++++++++++++++++++++++++++++ tests/test_path_detector.py | 3 +- 13 files changed, 2927 insertions(+), 86 deletions(-) create mode 100644 pathscope/extra_formats.py create mode 100644 pathscope/presets.py create mode 100644 pathscope/writers.py create mode 100644 tests/test_features.py diff --git a/README.md b/README.md index 49c04ab..397cb38 100644 --- a/README.md +++ b/README.md @@ -35,15 +35,17 @@ reviewing for path-traversal risk.** 4. [Installation on Kali Linux](#installation-on-kali-linux) 5. [Inputs](#inputs) 6. [Quick start](#quick-start) -7. [Reports: text, JSON, CSV, SARIF](#reports-text-json-csv-sarif) -8. [Exit codes](#exit-codes) -9. [Detection rules](#detection-rules) -10. [Configuration file](#configuration-file) -11. [Tests](#tests) -12. [Project layout](#project-layout) -13. [Limitations](#limitations) -14. [FAQ](#faq) -15. [Authorization and legal](#authorization-and-legal) +7. [Presets](#presets) +8. [Baselines, diff and suppression](#baselines-diff-and-suppression) +9. [Reports: text, JSON, CSV, SARIF, Markdown, HTML](#reports) +10. [Exit codes](#exit-codes) +11. [Detection rules](#detection-rules) +12. [Configuration file](#configuration-file) +13. [Tests](#tests) +14. [Project layout](#project-layout) +15. [Limitations](#limitations) +16. [FAQ](#faq) +17. [Authorization and legal](#authorization-and-legal) --- @@ -151,15 +153,21 @@ PathScope accepts three sources, which are merged and de-duplicated: | 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. | | stdin | `cat urls.txt \| pathscope`, `pathscope -i -` | Auto-detected when no other source is given. | ### Input format -* `--format auto` (default) — HAR if the file ends in `.har`/`.har.json` or the - JSON starts with a `log.entries` object; otherwise a URL list. -* `--format har` — force HAR. -* `--format urls` — force a URL list. -* `--input-format {auto,urls,har}` — same selectors under an unambiguous name. +* `--format auto` (default) — detects, in order: HAR (`.har`/`.har.json` or a + `log.entries` object), Burp XML, OpenAPI JSON, raw HTTP request, recon + output, then a plain URL list. +* `--format har|burp|openapi|raw|recon|urls` — force an input format. +* `--input-format {auto,urls,har,burp,openapi,raw,httpx,ffuf,nuclei,recon}` — + 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). @@ -208,7 +216,7 @@ Example terminal output (values hidden): ```console $ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -PathScope 2.0.0 - passive path-parameter triage +PathScope 2.1.0 - passive path-parameter triage ---------------------------------------------------------------- GitHub: https://github.com/mrdineshpathro Instagram: https://www.instagram.com/mr_dineshpatro @@ -225,8 +233,8 @@ Analyzed 1 request(s) and 1 parameter(s); 1 candidate(s) at score >= 25. Request GET https://example.test/view Location query Rule name-exact - Value (use --show-values to display) - Why rule(s) and evidence: + 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) @@ -235,7 +243,58 @@ Reminder: these are candidates for manual review, not confirmed vulnerabilities. --- -## Reports: text, JSON, CSV, SARIF +## 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`, @@ -247,7 +306,7 @@ Every format contains the same fields: `host`, `source_type`, `source`, ```json { "tool": "PathScope", - "version": "2.0.0", + "version": "2.1.0", "disclaimer": "Candidates for manual review only. ...", "passive": true, "network_requests_made": 0, @@ -259,7 +318,11 @@ Every format contains the same fields: `host`, `source_type`, `source`, "candidates": 1, "confidence": {"high": 0, "medium": 1, "low": 0}, "skipped": 0, - "sources": ["urls.txt"] + "sources": ["urls.txt"], + "mode": "scan", + "new": 1, + "known": 0, + "resolved": 0 }, "warnings": [], "findings": [ @@ -281,7 +344,10 @@ Every format contains the same fields: `host`, `source_type`, `source`, "value ends with a file-like extension '.pdf' (+8)" ], "resource": "https://example.test/view", - "value": null + "value": null, + "fingerprint": "ec274fecea647284", + "status": "new", + "note": "" } ], "links": { @@ -301,6 +367,18 @@ index,host,source_type,source,method,location,parameter,rule,rules,confidence,sc 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 `.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_path_detector.py b/tests/test_path_detector.py index cc5f887..2bb34b0 100755 --- a/tests/test_path_detector.py +++ b/tests/test_path_detector.py @@ -1133,7 +1133,8 @@ 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", + "pathlib", "textwrap", "xml", "xml.etree", "xml.etree.ElementTree", + "base64", "copy", "hashlib", "html", } for path in project_modules(): tree = ast.parse(path.read_text(encoding="utf-8")) From b714eaa4ebf4dededede4ebc2281de631ef732ca Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:32:16 +0000 Subject: [PATCH 4/8] Add PathScope 2.2: watch mode, interactive reports, rule registry, CI toolkit Eight feature groups, each with tests and README sections. 1. Live watch mode (--watch FILE --interval N) Re-reads a growing HAR/URL file and prints only candidates not reported before. Polls skip unchanged files (size+mtime), a shrunk/rotated capture starts a fresh baseline, transient read errors retry quietly, Ctrl-C stops with a summary. A missing file is a usage error instead of an endless loop. 2. Interactive HTML report (--save-report FILE.html --interactive) Self-contained page: sortable columns, text and confidence filters, reviewed-only mode, localStorage review marks, copy-fingerprint buttons and print CSS. No external assets, no network primitives in the inline script; every dynamic string is escaped exactly like the static writer. 3. Rule registry and tuning (--list-rules, --rules, --disable-rule) New pathscope/rules.py holds all 29 rules with layer, default weight and description. Weights can be overridden or rules removed at runtime; unknown ids, out-of-range weights and positive demotions are rejected. --explain now reports the effective book, folded/i18n settings and overridden weights. 4. CI toolkit (--policy, --init-policy, junit, --github-annotations, --self-test) New pathscope/policy.py evaluates max_high/medium/low/total, min_score, fail_on_known, ignore_rules and ignore_hosts against new findings, with explainable violations and exit code 1. New pathscope/ci.py renders JUnit XML, GitHub workflow annotations (escaped per the Actions spec) and the ten-check --self-test. Adds .github/workflows/pathscope.yml, .pre-commit-hooks.yaml, an example config and .pathscope/policy.json. 5. Scale helpers (--dedupe-by, --max-entries, --stats, --progress) Findings collapse by path (default), parameter or not at all; input entries can be capped with a reported truncation warning; --stats records phase timings on stderr and in JSON; --progress writes rate-limited updates to stderr only, leaving stdout machine-readable. 6. More tool exports (postman, zap, mitmproxy, graphql, cookies) New pathscope/tool_formats.py parses Postman v2.x collections (nested folders, query/urlencoded/formdata/raw bodies), ZAP JSON history and alert exports, mitmproxy flow exports and GraphQL introspection results. Cookie jars contribute names only; values are discarded before analysis. 7. Fuzzy and multilingual names (--name-lang, --no-fold) New pathscope/naming.py folds diacritics, compatibility forms, exotic separators and invisible characters, expands bounded leet spellings (f1le -> file) and ships German, Spanish, French, Portuguese, Italian and Dutch term packs. Folded matches use weaker rules (name-folded +20, name-leet +12, name-i18n-fold +21) and English tables always win. 8. Value-shape demotion (--no-demote, --disable-rule) New pathscope/valueshape.py recognises UUIDs, hex digests, JWTs, base64 blobs, e-mail addresses, IP literals and bool/number/enum values and emits explicit negative rules, visible in --explain and every report, so a shape demotion never hides a candidate silently. Config gains name_lang, fold_names and demote_shapes (validated, merged through extends, carried through the CLI merge). Version 2.2.0. Tests: 335 total (127 new) covering watch polling and rotation, interactive markup and script guarantees, rule validation and overrides, policy gates, JUnit/annotation escaping, self-test, every tool format, folding/i18n edge cases, demotion thresholds, dedupe/limits/stats/progress, README anchors and the shipped CI files. README adds eight sections and a full CLI table. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/pathscope.yml | 83 ++ .pathscope/policy.json | 10 + .pre-commit-config.example.yaml | 7 + .pre-commit-hooks.yaml | 28 + README.md | 336 ++++++- pathscope/__init__.py | 2 +- pathscope/ci.py | 300 +++++++ pathscope/cli.py | 389 +++++++- pathscope/config.py | 71 +- pathscope/detector.py | 99 +- pathscope/heuristics.py | 443 ++++++--- pathscope/naming.py | 296 ++++++ pathscope/policy.py | 252 ++++++ pathscope/presets.py | 9 + pathscope/progress.py | 108 +++ pathscope/report.py | 20 +- pathscope/rules.py | 445 +++++++++ pathscope/sources.py | 23 + pathscope/tool_formats.py | 785 ++++++++++++++++ pathscope/valueshape.py | 195 ++++ pathscope/watch.py | 220 +++++ pathscope/writers.py | 291 +++++- tests/test_features_v22.py | 1498 +++++++++++++++++++++++++++++++ tests/test_path_detector.py | 18 +- 24 files changed, 5742 insertions(+), 186 deletions(-) create mode 100644 .github/workflows/pathscope.yml create mode 100644 .pathscope/policy.json create mode 100644 .pre-commit-config.example.yaml create mode 100644 .pre-commit-hooks.yaml create mode 100644 pathscope/ci.py create mode 100644 pathscope/naming.py create mode 100644 pathscope/policy.py create mode 100644 pathscope/progress.py create mode 100644 pathscope/rules.py create mode 100644 pathscope/tool_formats.py create mode 100644 pathscope/valueshape.py create mode 100644 pathscope/watch.py create mode 100644 tests/test_features_v22.py diff --git a/.github/workflows/pathscope.yml b/.github/workflows/pathscope.yml new file mode 100644 index 0000000..52fe36f --- /dev/null +++ b/.github/workflows/pathscope.yml @@ -0,0 +1,83 @@ +# 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 + + 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/.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/README.md b/README.md index 397cb38..da022a6 100644 --- a/README.md +++ b/README.md @@ -37,15 +37,22 @@ reviewing for path-traversal risk.** 6. [Quick start](#quick-start) 7. [Presets](#presets) 8. [Baselines, diff and suppression](#baselines-diff-and-suppression) -9. [Reports: text, JSON, CSV, SARIF, Markdown, HTML](#reports) -10. [Exit codes](#exit-codes) -11. [Detection rules](#detection-rules) -12. [Configuration file](#configuration-file) -13. [Tests](#tests) -14. [Project layout](#project-layout) -15. [Limitations](#limitations) -16. [FAQ](#faq) -17. [Authorization and legal](#authorization-and-legal) +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. [Exit codes](#exit-codes) +16. [Detection rules](#detection-rules) +17. [Configuration file](#configuration-file) +18. [Tests](#tests) +19. [Project layout](#project-layout) +20. [Limitations](#limitations) +21. [FAQ](#faq) +22. [Authorization and legal](#authorization-and-legal) --- @@ -157,17 +164,23 @@ PathScope accepts three sources, which are merged and de-duplicated: | 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), Burp XML, OpenAPI JSON, raw HTTP request, recon - output, then a plain URL list. -* `--format har|burp|openapi|raw|recon|urls` — force an input format. -* `--input-format {auto,urls,har,burp,openapi,raw,httpx,ffuf,nuclei,recon}` — - the same selectors under an unambiguous name. Use `--input-format` together - with `--format json` when you want to force the input **and** choose output. + `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). @@ -216,7 +229,7 @@ Example terminal output (values hidden): ```console $ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -PathScope 2.1.0 - passive path-parameter triage +PathScope 2.2.0 - passive path-parameter triage ---------------------------------------------------------------- GitHub: https://github.com/mrdineshpathro Instagram: https://www.instagram.com/mr_dineshpatro @@ -403,12 +416,227 @@ stderr summary; JSON/CSV/SARIF on stdout stay valid. --- +## Live watch mode + +A proxy keeps appending to a capture while you work. `--watch` re-reads the +file on a timer and prints **only candidates it has not reported before**, one +line each, so a long session stays readable. + +```bash +python3 path_detector.py --watch capture.har --interval 2 +python3 path_detector.py --watch urls.txt --preset noisy --interval 5 +``` + +``` +Watching capture.har every 2s for new candidates. Press Ctrl-C to stop. No requests are sent. +[new] app.test query file HIGH 71/100 name-exact +[new] cdn.test form attachment MEDIUM 53/100 name-exact +Stopped after 42 poll(s) in 84.0s; 2 candidate(s) seen in total. +``` + +* Polling only parses the file when its size/mtime changed. +* Identity is the usual fingerprint, so the same parameter never repeats. +* A capture that shrinks (rotated/replaced) starts a fresh baseline. +* A missing file is a usage error (exit `2`); a transient read failure while a + proxy is writing is retried quietly. +* Ctrl-C stops cleanly and prints a summary. Nothing is ever requested. + +--- + +## Rule registry and tuning + +Every rule and its default weight is listed in `pathscope/rules.py` and is +visible from the command line. Rules can be reweighted, disabled and explained +without editing code. + +```bash +# What rules exist, with effective weights? +python3 path_detector.py --list-rules + +# Reweight and disable rules for this run (JSON) +cat > rules.json <<'JSON' +{ + "weights": { "name-exact": 40, "value-weak": 0 }, + "disable": ["name-weak"] +} +JSON +python3 path_detector.py -i capture.har --rules rules.json + +# One-off: remove a rule just for this run +python3 path_detector.py -i capture.har --disable-rule name-suffix + +# Why did (or didn't) this parameter fire? +python3 path_detector.py --explain base_path --explain-value ../../etc/passwd +``` + +`--explain` prints the effective threshold, the rule book in use, every rule +that fired with its layer, weight and reason, the total, and whether the result +would be reported. Overridden weights are shown as `44 (default +35)`. + +`--disable-rule` accepts a full id (`value-traversal`) or an unambiguous short +form (`traversal`, `uuid`). Unknown ids are rejected with exit `2`. Demotion +rules (`value-demote-*`) may not be given a positive weight. + +--- + +## Multilingual and folded names + +**Folding** is always on: diacritics, compatibility forms (fullwidth), exotic +separators and invisible characters are normalised before tokenisation, so +`fıle`, `file` and `F_I_L_E` are all `file`. Names that only match after +folding get the weaker `name-folded` rule (+20), never the full `name-exact` +weight. + +Leet spellings are de-obfuscated for tokens of 3+ characters (`f1le` → `file`, +`p4th` → `path`) and score `name-leet` (+12). + +**Term packs** add path vocabulary from other languages: + +| Tag | Language | Examples | +|---|---|---| +| `de` | German | `datei`, `pfad`, `ordner`, `herunterladen` | +| `es` | Spanish | `archivo`, `ruta`, `carpeta`, `descargar` | +| `fr` | French | `fichier`, `chemin`, `dossier`, `telecharger` | +| `pt` | Portuguese | `arquivo`, `caminho`, `pasta`, `baixar` | +| `it` | Italian | `percorso`, `cartella`, `allegato`, `scaricare` | +| `nl` | Dutch | `bestand`, `pad`, `map`, `bijlage` | + +```bash +python3 path_detector.py -i capture.har --name-lang de,es +python3 path_detector.py -i capture.har --name-lang auto # every pack +``` + +`--name-lang off` (default) keeps English only. In a configuration file use +`"name_lang": ["de", "es"]`, `["auto"]` or `[]`. English tables always win: a +word that is generic in English (`image`, `document`) is never re-labelled as a +foreign finding, and a folded-only match scores `name-i18n-fold` (+21) rather +than the full `name-i18n` (+25). + +`--no-fold` disables folding entirely (useful when auditing the sanitizer). + +--- + +## Value-shape demotion + +A parameter named `file` whose value is a UUID, a hash, a JWT, a base64 blob, an +e-mail address, an IP literal or a plain boolean/number is probably not a +filesystem path. PathScope adds **negative** evidence for those shapes: + +| Rule | Weight | Shape | +|---|---|---| +| `value-demote-uuid` | −20 | `550e8400-e29b-41d4-a716-446655440000` | +| `value-demote-hash` | −18 | MD5/SHA digests, `sha256:…` | +| `value-demote-jwt` | −20 | `eyJ…​.eyJ…​.…` | +| `value-demote-base64` | −12 | long base64 blobs | +| `value-demote-email` | −8 | `user@example.test` | +| `value-demote-ip` | −10 | `192.168.1.1`, `2001:db8::1` | +| `value-demote-scalar` | −10 | `true`, `42`, `3.14`, short enums | + +Demotions appear in `--explain` and in every report (`rules`, `reasons`), so a +candidate that drops below the threshold is visible rather than silently +filtered. Tune them with `--rules`, remove them with +`--disable-rule value-demote-uuid`, or turn the whole layer off with +`--no-demote` / `"demote_shapes": false`. + +--- + +## CI integration + +Four small pieces make PathScope fit a pipeline without a wrapper script. + +**Policy gate.** `--policy FILE` (or inline JSON) expresses what may not happen: + +```json +{ + "description": "no new high-confidence candidates", + "max_high": 0, + "max_medium": 10, + "max_total": 20, + "min_score": 0, + "fail_on_known": false, + "ignore_rules": ["name-weak"], + "ignore_hosts": ["static.example.test"] +} +``` + +```bash +python3 path_detector.py -i capture.har --baseline baseline.json \ + --policy pathscope-policy.json +python3 path_detector.py --init-policy pathscope-policy.json # starter file +``` + +Only *new* findings count unless `fail_on_known` is true. Exit code `1` means +the policy failed; the reasons are printed to stderr +(`policy failed: max_high=0 exceeded (1 found)`). + +**JUnit XML.** `--output-format junit` writes one `testcase` per confidence band +plus one per finding, so GitLab/Jenkins/Azure show each candidate: + +```bash +python3 path_detector.py -i capture.har --output-format junit > pathscope.xml +``` + +**GitHub annotations.** `--github-annotations` prints workflow commands on +stdout; high-confidence candidates become `::warning`, others `::notice`: + +```bash +python3 path_detector.py -i capture.har --github-annotations +``` + +**Self-test.** `--self-test` runs ten checks about the installation (banner, +parsing, scoring, privacy defaults, escaping, bounded decoding) and exits `1` if +any fail. It reads no user files and uses no network. + +Ready-made files live in the repository: `.github/workflows/pathscope.yml` +(runs the tests, scans an artifact if present, and honours a baseline) and +`.pre-commit-hooks.yaml` (blocking new high-confidence candidates in changed +captures). Both are plain YAML with no third-party actions beyond +`actions/checkout`. + +--- + +## Scale and performance + +| Option | Effect | +|---|---| +| `--dedupe-by path` | **default** — one finding per host + location + parameter; `occurrences` counts resources | +| `--dedupe-by param` | one finding per parameter name, across hosts | +| `--dedupe-by none` | every (resource, parameter) pair stays separate | +| `--max-entries N` | analyse at most N input entries; the rest are reported as truncated | +| `--stats` | parse/analyse timings and counts on stderr and in JSON | + +Analysis is single-pass and in-memory; a 20 000-entry HAR is bounded by +`MAX_HAR_ENTRIES` and the JSON body limits. Use `--preset minimal` and +`--dedupe-by path` on very large captures to keep output short, and `--top N` +when you only want the best few. `--progress` writes phase updates to stderr and +leaves stdout machine-readable. + +--- + +## Interactive HTML report + +`--save-report FILE.html --interactive` writes a single self-contained page with +sortable columns, a text filter, a confidence filter, "reviewed only" mode and +one-click fingerprint copying. Review checkboxes are stored in the browser's +`localStorage`; nothing is uploaded and there are no external assets, so the +file works offline and from `file://`. + +```bash +python3 path_detector.py -i capture.har --save-report triage.html --interactive +``` + +`--interactive` requires an `.html`/`.htm` `--save-report`; use it on a report +you plan to hand to a human reviewer, and keep the static/Markdown writers for +tickets and archives. + +--- + ## Exit codes | Code | Meaning | |---|---| | `0` | Analysis completed. No candidates (or candidates found without `--fail-on-findings`). | -| `1` | `--fail-on-findings` and at least one candidate was reported (in diff mode: at least one **new** candidate). | +| `1` | `--fail-on-findings` and at least one candidate was reported (in diff mode: at least one **new** candidate), **or** a `--policy` was violated. | | `2` | Usage error, unreadable/malformed input file, invalid configuration, or no usable input. | | `3` | Internal error while producing a report (never a crash trace). | | `130` | Interrupted with `Ctrl-C`. | @@ -434,6 +662,10 @@ All rules live in `pathscope/heuristics.py` and are safe to edit. | `name-prefix` | +28 | the name starts with a path term (`filedata`) | | `name-suffix` | +23 | the name ends with a path term (`resolvepath`) | | `name-weak` | +5 | multiword name without a path term — never enough on its own | +| `name-folded` | +20 | the term appears only after diacritic/compatibility folding | +| `name-leet` | +12 | the term appears only after leet expansion (`f1le` → `file`) | +| `name-i18n` | +25 | the term comes from an enabled language pack | +| `name-i18n-fold` | +21 | a pack term that only matches after folding | | `name-generic` | 0 | generic names (`image`, `img`, `target`, `ref`, `avatar`, …) only count *with* a path-like value | `utm_source`, `gclid`, `page_size`, `urlencoded`, `landscape`, `sort` and similar @@ -459,6 +691,7 @@ so `report..pdf` or `v1..2` never match. | `value-path-list` | +5 | `a.css;b.css` | | `value-full-url` | −10 | `https://other.test/x` (usually a redirect target) | | `value-pairs-with-generic-name` | +10 | `image=/static/logo.png` | +| `value-demote-*` | −8 … −20 | UUID, hash, JWT, base64, e-mail, IP, scalar (see [Value-shape demotion](#value-shape-demotion)) | ### Confidence bands (heuristic, not exploitability) @@ -477,9 +710,14 @@ reading priority, never a risk rating. * Add project-specific vocabulary: `--config` `name_terms` (literal strings only). * Silence known-noisy names: `--ignore-param NAME` (repeatable) or `--config` `ignore_params`. -* Change the vocabulary permanently by editing `PATH_NAME_TERMS`, - `GENERIC_NAME_TERMS`, `FILE_EXTENSIONS` or the weights in `heuristics.py`; +* Change weights at runtime with `--rules FILE` / `--disable-rule RULE`, or + permanently in `pathscope/rules.py`; `--list-rules` always reflects the + effective values. +* Change the vocabulary by editing `PATH_NAME_TERMS`, `GENERIC_NAME_TERMS`, + `FILE_EXTENSIONS` (English) or `pathscope/naming.py` (other languages); the tests exercise these tables. +* Widen the name layer with `--name-lang de,es,…` and narrow the value layer + with `--no-demote`. --- @@ -487,11 +725,20 @@ reading priority, never a risk rating. ``` python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] - [--format {auto,urls,har,text,json,csv,sarif}] - [--input-format {auto,urls,har}] - [--output-format {text,json,csv,sarif}] [--json] - [--show-values] [--no-color] [--no-banner] [-q] - [--ignore-param NAME] [--config FILE] + [--format FORMAT] [--input-format FORMAT] + [--output-format {text,json,csv,sarif,markdown,html,junit}] + [--json] [--show-values] [--no-color] [--no-banner] [-q] + [--save-report FILE] [--interactive] [--progress] [--stats] + [--github-annotations] [--top N] [--group-by FIELD] + [--summary-only] [--preset NAME] [--baseline FILE] + [--suppress FILE] [--mark-reviewed FILE] [--show-known] + [--explain PARAM] [--explain-value VALUE] + [--init-config FILE] [--init-policy FILE] + [--rules FILE] [--list-rules] [--disable-rule RULE] + [--name-lang LIST] [--no-fold] [--no-demote] + [--dedupe-by {path,param,none}] [--max-entries N] + [--policy FILE|JSON] [--watch FILE] [--interval SECONDS] + [--self-test] [--ignore-param NAME] [--config FILE] [--min-score N] [--max-decode-passes N] [--fail-on-findings] ``` @@ -522,6 +769,24 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] | `--top N` | Show only the N best text candidates. | | `--group-by FIELD` | Group text output by `host`, `rule`, `confidence`, `location`. | | `--summary-only` | Compact counts-per-host/rule view. | +| `--interactive` | Add sorting/filtering/review boxes to an HTML `--save-report`. | +| `--progress` | Phase progress on stderr (stdout stays machine-readable). | +| `--stats` | Timings and counts on stderr, and in the JSON payload. | +| `--github-annotations` | Emit GitHub Actions annotations on stdout. | +| `--output-format junit` | JUnit XML for CI test reports. | +| `--list-rules` | Print every rule, effective weight and description. | +| `--rules FILE` | JSON weight overrides (`{"weights": {...}, "disable": [...]}`). | +| `--disable-rule RULE` | Remove a rule from scoring; repeatable. | +| `--name-lang LIST` | Term packs: `de,es,fr,pt,it,nl`, `auto`, `off`. | +| `--no-fold` | Disable diacritic/compatibility folding. | +| `--no-demote` | Disable value-shape demotion. | +| `--dedupe-by MODE` | `path` (default), `param` or `none`. | +| `--max-entries N` | Analyse at most N input entries (0 = unlimited). | +| `--policy FILE\|JSON` | CI gate; exit 1 when violated. | +| `--init-policy FILE` | Write a starter policy and exit. | +| `--watch FILE` | Re-analyse a growing capture; print new candidates only. | +| `--interval SECONDS` | Polling interval for `--watch` (default 2). | +| `--self-test` | Run the built-in environment checks (exit 1 on failure). | | `-q, --quiet` | Suppress warnings and the stderr summary. | | `--no-color` | Disable colour on terminals. | | `--no-banner` | Suppress the startup banner. | @@ -555,6 +820,9 @@ clear error and exit code `2`. | `max_decode_passes` | integer | 0–5 | | `weak_names` | boolean | enables the weak `name-weak` rule (default `true`) | | `show_values` | boolean | defaults values to visible; `--show-values` also works | +| `name_lang` | array | enabled term packs (`["de","es"]`, `["auto"]` or `[]`) | +| `fold_names` | boolean | diacritic/compatibility folding (default `true`) | +| `demote_shapes` | boolean | UUID/hash/scalar demotion (default `true`) | | `extends` | string | base preset (`minimal`/`balanced`/`noisy`) or another `.json` file, relative to this file | ```bash @@ -579,7 +847,7 @@ python3 -m unittest discover -s tests -v python3 tests/test_path_detector.py ``` -209 tests cover exactly the behaviours this tool promises: +322 tests cover exactly the behaviours this tool promises: | Area | What is asserted | |---|---| @@ -596,6 +864,14 @@ python3 tests/test_path_detector.py | Extra inputs | Burp XML (base64 + plain + multipart), OpenAPI query/body inventory, raw HTTP with `###`, recon lines and JSONL | | Reports | Markdown/HTML content and escaping, `--save-report`, SARIF fingerprints | | UX | `--top`, `--group-by`, `--summary-only`, `--explain` | +| Watch mode | stable polls, new-only output, rotation, Ctrl-C, missing file | +| Rules | registry validation, overrides, disabling, `--list-rules`, `--explain` | +| i18n & folding | fullwidth/diacritic/leet names, packs, English-first precedence | +| Demotion | every shape, thresholds, `--no-demote`, disabled rules | +| CI | policy evaluation, JUnit XML, GitHub annotation escaping, self-test | +| Tool exports | Postman, ZAP, mitmproxy, GraphQL, cookie jars (names only) | +| Scale | dedupe modes, `--max-entries`, `--stats`, rate-limited progress | +| Interactive | controls, escaping, self-containment, HTML-only enforcement | --- @@ -614,7 +890,15 @@ pathscope/ │ ├── config.py # strict JSON configuration + extends │ ├── presets.py # minimal / balanced / noisy postures │ ├── extra_formats.py # Burp XML, OpenAPI, raw HTTP, recon exports -│ ├── writers.py # Markdown / HTML report files +│ ├── rules.py # rule registry, weights, overrides +│ ├── naming.py # folding, leet variants, language packs +│ ├── valueshape.py # UUID/hash/JWT/base64/email/IP/scalar demotion +│ ├── tool_formats.py # Postman, ZAP, mitmproxy, GraphQL, cookies +│ ├── policy.py # CI policy evaluation +│ ├── ci.py # JUnit, GitHub annotations, --self-test +│ ├── watch.py # live re-analysis (--watch) +│ ├── progress.py # stderr progress (--progress) +│ ├── writers.py # Markdown / HTML / interactive HTML reports │ ├── cli.py # argument parsing, input merging, exit codes │ └── __main__.py # enables `python3 -m pathscope` ├── tests/test_path_detector.py # unittest suite (offline) diff --git a/pathscope/__init__.py b/pathscope/__init__.py index 711ad8f..6b99187 100644 --- a/pathscope/__init__.py +++ b/pathscope/__init__.py @@ -14,7 +14,7 @@ from __future__ import annotations PROGRAM = "PathScope" -__version__ = "2.1.0" +__version__ = "2.2.0" # Displayed on every start. These are never opened and never requested. GITHUB_URL = "https://github.com/mrdineshpathro" diff --git a/pathscope/ci.py b/pathscope/ci.py new file mode 100644 index 0000000..772e8f8 --- /dev/null +++ b/pathscope/ci.py @@ -0,0 +1,300 @@ +"""CI helpers: JUnit XML, GitHub annotations and a ``--self-test`` runner. + +All three are pure functions over a :class:`pathscope.detector.Report`, so they +are testable without touching the network, the filesystem or a CI provider. + +JUnit XML + One ```` per confidence band plus one per finding, so a CI UI + lists every candidate. Failures carry the fingerprint, which keeps a + baseline stable across runs. + +GitHub annotations + ``::warning`` / ``::notice`` workflow commands on stdout, which the + Actions runner turns into inline PR annotations. Every dynamic field is + escaped per GitHub's documented rules, and values are never included. + +Self-test + A built-in suite of assertions about this installation: banner strings, + parsing, scoring and privacy defaults. It never reads user files. +""" + +from __future__ import annotations + +from typing import Dict, List, Sequence +from xml.sax.saxutils import escape as xml_escape, quoteattr + +from . import PROGRAM, __version__, banner_lines +from .detector import Report +from .report import DISCLAIMER + +# --------------------------------------------------------------------------- +# JUnit XML +# --------------------------------------------------------------------------- +JUNIT_BANDS = ("high", "medium", "low") + + +def _attr(value: object) -> str: + return quoteattr(str(value)) + + +def render_junit(report: Report, suite_name: str = "PathScope") -> str: + """Return a JUnit XML document describing this run.""" + counts = report.confidence_counts + failures = 0 + cases: List[str] = [] + + for band in JUNIT_BANDS: + band_count = counts.get(band, 0) + if band_count: + failures += 1 + inner = ( + f"" + + xml_escape( + f"{band_count} {band}-confidence candidate(s) for manual review.\n" + + DISCLAIMER + ) + + "" + ) + cases.append( + f' {inner}' + ) + else: + cases.append( + f' ' + ) + + for finding in report.findings: + name = f"{finding.host} {finding.location}:{finding.parameter}" + message = ( + f"score {finding.score}/100, rule {finding.rule}, " + f"fingerprint {finding.fingerprint}" + ) + inner = ( + f"" + + xml_escape("\n".join(finding.reasons) or DISCLAIMER) + + "" + ) + cases.append( + f' {inner}" + ) + + metadata = ( + f"requests={report.requests_analyzed} parameters={report.parameters_analyzed} " + f"candidates={report.candidate_count} mode={report.mode} " + f"new={report.new_count} known={report.known_count} " + f"resolved={len(report.resolved)}" + ) + lines = [ + '', + f'', + f' ', + f" " + f'' + f'' + f"", + f" ", + ] + lines.extend(cases) + lines.append(" ") + lines.append("") + return "\n".join(lines) + "\n" + + +# --------------------------------------------------------------------------- +# GitHub Actions annotations +# --------------------------------------------------------------------------- +#: GitHub workflow-command escaping (documented in the Actions toolkit). +_GH_ESCAPE = {"%": "%25", "\r": "%0D", "\n": "%0A"} +_GH_PROPERTY_ESCAPE = {":": "%3A", ",": "%2C"} + + +def _gh_escape(value: str) -> str: + for char, replacement in _GH_ESCAPE.items(): + value = value.replace(char, replacement) + return value + + +def _gh_property(value: str) -> str: + value = _gh_escape(value) + for char, replacement in _GH_PROPERTY_ESCAPE.items(): + value = value.replace(char, replacement) + return value + + +def render_github_annotations(report: Report) -> str: + """Return workflow commands (one per finding) for GitHub Actions. + + High-confidence candidates become warnings, medium/low become notices. + Known findings are annotated as notices only when they are visible in the + report (``--show-known``); resolved entries produce nothing. + """ + lines: List[str] = [ + f"::notice title=PathScope::Analyzed {report.requests_analyzed} request(s); " + f"{report.candidate_count} candidate(s) for manual review." + ] + for finding in report.findings: + level = "warning" if finding.confidence == "high" else "notice" + reason = finding.reasons[0] if finding.reasons else "heuristic match" + title = f"PathScope {finding.confidence}: {finding.parameter}" + message = ( + f"{finding.host} {finding.location} parameter '{finding.parameter}' " + f"scored {finding.score}/100 ({finding.rule}); {reason}. " + f"fingerprint {finding.fingerprint}. Candidate for manual review only." + ) + lines.append( + f"::{level} file={_gh_property(finding.resource)}," + f"title={_gh_property(title)}::{_gh_escape(message)}" + ) + if report.mode == "diff": + lines.append( + f"::notice title=PathScope diff::{report.new_count} new, " + f"{report.known_count} known, {len(report.resolved)} resolved " + f"(baseline {_gh_escape(report.baseline_source or 'unspecified')})." + ) + return "\n".join(lines) + "\n" + + +# --------------------------------------------------------------------------- +# Self-test +# --------------------------------------------------------------------------- +def _selftest_checks() -> List[tuple]: + """Assertions about this installation. Returns ``[(name, callable)]``.""" + from . import config, heuristics, sources, textutil, writers + + def banner_exact() -> None: + lines = banner_lines() + assert len(lines) == 3, "expected three banner lines" + assert any(line.startswith("GitHub: https://") for line in lines), "GitHub link" + assert all(": " in line for line in lines), "label: url format" + + def url_parse() -> None: + info = sources.parse_url("https://Example.TEST:8443/a/b?x=1") + assert info.host == "example.test", info.host + assert info.port == 8443, info.port + assert info.path == "/a/b", info.path + + def query_split() -> None: + pairs = sources.split_query("a=1&a=2&b=%2e%2e") + assert [name for name, _value in pairs] == ["a", "a", "b"], pairs + + def traversal_scores() -> None: + analysis = heuristics.analyze_parameter("file", "../../etc/passwd") + assert "value-traversal" in analysis.rules, analysis.rules + assert analysis.score >= 60, analysis.score + + def ordinary_ignored() -> None: + assert not heuristics.analyze_parameter("lang", "en").evidence, "lang/en" + assert not heuristics.analyze_parameter("q", "hello").evidence, "q/hello" + + def values_hidden() -> None: + request = sources.request_from_url( + "https://a.test/?file=secret.txt", sources.SOURCE_URL, "--self-test" + ) + from . import detector + + report = detector.analyze_requests([request], detector.AnalysisOptions()) + finding = report.findings[0] + assert finding.value is None, "values must be hidden by default" + + def config_roundtrip() -> None: + payload = config.dump_example() + parsed = config.validate_payload(payload) + assert parsed.min_score == payload["min_score"], "min_score roundtrip" + + def report_renderers() -> None: + from . import detector, report as report_module + + request = sources.request_from_url( + "https://a.test/?file=../../etc/passwd", sources.SOURCE_URL, "--self-test" + ) + report = detector.analyze_requests([request], detector.AnalysisOptions()) + from .writers import render_html, render_markdown + + palette = report_module.Palette(False) + renderers = { + "markdown": lambda: render_markdown(report), + "html": lambda: render_html(report), + "json": lambda: report_module.render_json(report), + "csv": lambda: report_module.render_csv(report), + "sarif": lambda: report_module.render_sarif(report), + "junit": lambda: render_junit(report), + "text": lambda: report_module.render_text(report, palette), + } + for name, render in renderers.items(): + text = render() + assert text and "a.test" in text, name + + def html_escapes() -> None: + from . import detector + + request = sources.request_from_url( + "https://a.test/?file=", 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 + + 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), + ] + + +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) + + +__all__ = [ + "JUNIT_BANDS", + "render_github_annotations", + "render_junit", + "render_selftest", + "run_selftest", +] diff --git a/pathscope/cli.py b/pathscope/cli.py index 5b67453..46b694d 100644 --- a/pathscope/cli.py +++ b/pathscope/cli.py @@ -33,7 +33,10 @@ describe_presets, resolve_preset, ) +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, @@ -44,9 +47,12 @@ ) from .heuristics import analyze_parameter from .report import ( + FORMAT_CSV, + FORMAT_HTML, FORMAT_JSON, + FORMAT_JUNIT, FORMAT_MARKDOWN, - FORMAT_HTML, + FORMAT_SARIF, FORMAT_TEXT, FORMATS, Palette, @@ -56,6 +62,15 @@ 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 .sources import ( INPUT_FORMAT_AUTO, INPUT_FORMATS, @@ -66,7 +81,12 @@ make_url_requests, ) from .textutil import MAX_DECODE_PASSES -from .writers import SUPPORTED_EXTENSIONS, write_report +from .writers import ( + SUPPORTED_EXTENSIONS, + render_html_interactive, + write_report, + writer_supports_interactive, +) EXIT_OK = 0 EXIT_FINDINGS = 1 @@ -102,8 +122,9 @@ def build_parser() -> argparse.ArgumentParser: " --output-format to set both in one run.\n" "\n" "exit codes:\n" - " 0 no candidates 1 candidates with --fail-on-findings\n" - " 2 usage/input error 3 internal error 130 interrupted\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()) @@ -147,15 +168,16 @@ def build_parser() -> argparse.ArgumentParser: dest="format", choices=FORMAT_CHOICES, default=None, - metavar="{auto,urls,har,text,json,csv,sarif}", + 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)", + 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") @@ -163,7 +185,7 @@ def build_parser() -> argparse.ArgumentParser: "--output-format", choices=FORMATS, default=None, - metavar="{text,json,csv,sarif}", + metavar="{text,json,csv,sarif,markdown,html,junit}", help="report format written to stdout (default: text)", ) output.add_argument( @@ -197,6 +219,27 @@ def build_parser() -> argparse.ArgumentParser: 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, @@ -293,6 +336,86 @@ def build_parser() -> argparse.ArgumentParser: 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)", + ) return parser @@ -423,9 +546,23 @@ 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 @@ -444,10 +581,17 @@ def _merge_config(base: Config, overlay: Config) -> Config: ) -def _explain(argv: argparse.Namespace, config: Config, stdout, stderr) -> int: +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 "", @@ -456,6 +600,10 @@ def _explain(argv: argparse.Namespace, config: Config, stdout, stderr) -> int: 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( @@ -463,6 +611,21 @@ def _explain(argv: argparse.Namespace, config: Config, stdout, stderr) -> int: 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.", @@ -536,6 +699,84 @@ def collect_inputs( 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 _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, *, @@ -554,9 +795,17 @@ def run( args = parser.parse_args(argv_list) resolve_formats(args) quiet = args.quiet + 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 config, error = _apply_preset_and_config(args) if error: @@ -567,12 +816,45 @@ def run( 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 + + 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) + 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: @@ -586,15 +868,35 @@ def run( if baseline is None: baseline = suppression else: - merged = Baseline( - source=f"{args.baseline} + {args.suppress}", - ) + 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 - show_values = bool(args.show_values or config.show_values) + options = _build_options(args, config, book) + + # -- 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 needs_stdin = "-" in args.input if stdin_text is None and needs_stdin: @@ -602,6 +904,7 @@ def run( 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: @@ -610,6 +913,7 @@ def run( 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: @@ -625,19 +929,20 @@ def run( print(" Try: python3 path_detector.py --help", file=stderr) return EXIT_USAGE - options = 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=show_values, - weak_names=config.weak_names, - ) - try: + progress.start("analyzing", len(loaded.requests)) report_data = analyze_requests(loaded.requests, options) - report_data.warnings = list(loaded.warnings) + 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: @@ -645,7 +950,9 @@ def run( for index, finding in enumerate(report_data.findings, start=1): finding.index = index colors = Palette(supports_color(stdout) and not args.no_color) - if args.summary_only: + if args.github_annotations: + rendered = ci_module.render_github_annotations(report_data) + 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) @@ -662,13 +969,17 @@ def run( if args.save_report: try: - kind = write_report(args.save_report, report_data) + 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 to {args.save_report}", file=stderr + f"pathscope: wrote {kind} report{extra} to {args.save_report}", + file=stderr, ) if args.mark_reviewed: @@ -682,14 +993,38 @@ def run( if code != EXIT_OK: return code + 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, ) + # -- gates: --policy first (more specific), then --fail-on-findings -- + if policy is not None: + 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 report_data.new_count: return EXIT_FINDINGS return EXIT_OK diff --git a/pathscope/config.py b/pathscope/config.py index db04497..dc855cd 100644 --- a/pathscope/config.py +++ b/pathscope/config.py @@ -9,7 +9,10 @@ "min_score": 25, "max_decode_passes": 3, "weak_names": true, - "show_values": false + "show_values": false, + "name_lang": ["de", "es"], + "fold_names": true, + "demote_shapes": true } Only literal terms are accepted. Regular expressions are deliberately not @@ -54,6 +57,12 @@ class Config: 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). @@ -77,8 +86,15 @@ def merged_ignore(self) -> List[str]: "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): @@ -155,6 +171,40 @@ def validate_payload(payload: Any) -> Config: 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 @@ -203,6 +253,19 @@ def merge_configs(base: Config, overlay: Config) -> Config: 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)), @@ -275,6 +338,9 @@ def describe_schema() -> Tuple[str, ...]: ' "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', ) @@ -287,6 +353,9 @@ def dump_example() -> Dict[str, object]: "max_decode_passes": 3, "weak_names": True, "show_values": False, + "name_lang": ["de", "es"], + "fold_names": True, + "demote_shapes": True, } diff --git a/pathscope/detector.py b/pathscope/detector.py index 1cc3cb9..14b6024 100644 --- a/pathscope/detector.py +++ b/pathscope/detector.py @@ -8,11 +8,13 @@ from __future__ import annotations import hashlib -from dataclasses import dataclass, field +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 @@ -22,6 +24,15 @@ 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.""" @@ -32,6 +43,21 @@ class AnalysisOptions: 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 @@ -99,6 +125,14 @@ class Report: 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, ...] = () @property def candidate_count(self) -> int: @@ -170,11 +204,24 @@ def analyze_requests( 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] = [] - for request in _dedupe_requests(requests): + 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): @@ -193,6 +240,10 @@ def analyze_requests( 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 @@ -240,12 +291,56 @@ def analyze_requests( 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 # --------------------------------------------------------------------------- diff --git a/pathscope/heuristics.py b/pathscope/heuristics.py index 86f0f98..e30b298 100644 --- a/pathscope/heuristics.py +++ b/pathscope/heuristics.py @@ -14,7 +14,15 @@ 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``. ``docs/README`` documents each rule and its weight. +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 @@ -23,21 +31,27 @@ 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 -#: 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 +#: Section headings used by ``--list-rules``/``--explain``. +SECTION_NAME = "name" +SECTION_VALUE = "value" +SECTION_DEMOTION = "demotion" # --------------------------------------------------------------------------- # Parameter-name vocabulary @@ -162,16 +176,18 @@ def confidence(self) -> str: _DIGIT_SPLIT_RE = re.compile(r"(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])") -def tokenize_name(name: str) -> List[str]: - """Split a parameter name into lowercase tokens. +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 [] - text = sanitize_text(name).strip() + 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): @@ -201,68 +217,206 @@ def extension_of(text: str) -> str: # --------------------------------------------------------------------------- # 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 + 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: - ``name-custom`` exact user-configured term, +30 - ``name-exact`` exact built-in path term, +35 (+5 multiword) - ``name-compound`` the whole name is a known compound, +35 - ``name-prefix`` name starts with a path term, +28 - ``name-suffix`` name ends with a path term, +23 - ``name-generic`` generic name (image/target/...), +0 (context only) - ``name-weak`` multiword name without a term, +5 (never alone) + 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) """ - tokens = tokenize_name(name) + if not name: + return [] + tokens = tokenize_name(name, fold=fold) if not tokens: return [] joined = "".join(tokens) - lowered = sanitize_text(name).lower() 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 += [name for name in (joined, lowered, canonical_name(name)) if name 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 [ - Evidence( - "name-custom", - f"parameter name contains configured term '{term}' (+30)", - 30, - "name", - ) - ] + 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}' " - f"(+{STRONG_NAME_WEIGHT}{suffix})", - STRONG_NAME_WEIGHT + bonus, + f"parameter name contains path-related term '{best}' ({weight:+d}{suffix})", + weight, "name", ) ] - if "_" not in joined and joined in path_terms and len(joined) > 4: - return [ - Evidence( - "name-compound", - f"parameter name '{lowered}' is a known path compound (+{STRONG_NAME_WEIGHT})", - STRONG_NAME_WEIGHT, + # 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". @@ -278,46 +432,37 @@ def analyze_name( suffix_match = term break if prefix_match: - weight = STRONG_NAME_WEIGHT - PREFIX_DISCOUNT - return [ - Evidence( - "name-prefix", - f"parameter name starts with path-related term '{prefix_match}' (+{weight})", - weight, - "name", - ) - ] + 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 = STRONG_NAME_WEIGHT - SUFFIX_DISCOUNT - return [ - Evidence( - "name-suffix", - f"parameter name ends with path-related term '{suffix_match}' (+{weight})", - weight, - "name", - ) - ] + 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): - return [ - Evidence( - "name-generic", - "parameter name is generic (image/target/ref/...): considered only " - "when its value is path-like (+0)", - 0, - "name", - ) - ] + if book.is_disabled("name-generic"): + return [] + return _generic_name_evidence() if len(tokens) > 1 and weak_names: - return [ - Evidence( - "name-weak", - "multiword parameter name without a path term (weak, +5)", - 5, - "name", - ) - ] + return _weak_name_evidence(book) return [] @@ -328,8 +473,26 @@ 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 + 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. @@ -343,8 +506,9 @@ def analyze_value( ``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-encoded`` informational only (0) + ``value-demote-*`` UUID/hash/JWT/base64/e-mail/IP/scalar, negative """ raw = sanitize_text(value or "") if not raw: @@ -366,41 +530,41 @@ def analyze_value( ) ) if "%2f" in lowered_raw or "%5c" in lowered_raw: - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-encoded-slash", "value contains an encoded slash or backslash (%2f / %5c) (+12)", 12, - "value", ) ) if max_pass >= 2: - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-double-encoded", f"value required {max_pass} decoding passes (nested encoding) (+10)", 10, - "value", ) ) if _is_segment_traversal(raw): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-traversal", "value contains a '..' path segment ('../', '..\\' or bare '..') (+30)", 30, - "value", ) ) shape = raw elif _is_segment_traversal(deepest): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-encoded-traversal", "value contains a '..' segment only after percent-decoding (+15)", 15, - "value", ) ) shape = deepest @@ -408,40 +572,40 @@ def analyze_value( shape = deepest if WINDOWS_DRIVE_RE.match(shape): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-windows-drive", "value looks like a Windows drive path ('C:\\...') (+15)", 15, - "value", ) ) elif UNC_PATH_RE.match(shape): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-unc", "value looks like a Windows UNC path ('\\\\server\\share') (+15)", 15, - "value", ) ) elif ABSOLUTE_PATH_RE.match(shape): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-absolute", "value starts with a path separator (absolute-looking) (+12)", 12, - "value", ) ) if FULL_URL_RE.match(shape): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-full-url", "value is a full URL rather than a local path (-10)", -10, - "value", ) ) else: @@ -451,39 +615,58 @@ def analyze_value( if _is_segment_traversal(shape): separators = max(0, separators - 1) if separators >= 2: - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-multi-segment", f"value contains {separators} path separators (+6)", 6, - "value", ) ) extension = extension_of(shape) if extension: - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-extension", f"value ends with a file-like extension '.{extension}' (+8)", 8, - "value", ) ) if separators and any(sep in shape for sep in (";", ",")): - evidence.append( - Evidence( + evidence.extend( + _value_evidence( + book, "value-path-list", "value looks like a semicolon/comma separated list of paths (+5)", 5, - "value", ) ) + 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 # --------------------------------------------------------------------------- @@ -496,6 +679,10 @@ def analyze_parameter( 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. @@ -506,8 +693,15 @@ def analyze_parameter( 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) - value_evidence = analyze_value(value, max_decode_passes) + 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) @@ -518,15 +712,18 @@ def analyze_parameter( return Analysis(name=name) evidence: List[Evidence] = list(name_evidence) + list(value_evidence) - if generic and has_path_value: - evidence.append( - Evidence( - "value-pairs-with-generic-name", - f"generic parameter name is paired with a path-like value (+{GENERIC_BONUS})", - GENERIC_BONUS, - "value", + 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): 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/policy.py b/pathscope/policy.py new file mode 100644 index 0000000..0193dc7 --- /dev/null +++ b/pathscope/policy.py @@ -0,0 +1,252 @@ +"""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", + "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 + 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"] + 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 + 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 != "known" 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/presets.py b/pathscope/presets.py index 5a4e905..4df4013 100644 --- a/pathscope/presets.py +++ b/pathscope/presets.py @@ -84,6 +84,9 @@ def apply(self, config: Config) -> Config: ' "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' ), @@ -94,6 +97,9 @@ def apply(self, config: Config) -> Config: ' "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' ), @@ -104,6 +110,9 @@ def apply(self, config: Config) -> Config: ' "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' ), 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/report.py b/pathscope/report.py index f52da6a..bb1b5e9 100644 --- a/pathscope/report.py +++ b/pathscope/report.py @@ -23,7 +23,16 @@ FORMAT_SARIF = "sarif" FORMAT_MARKDOWN = "markdown" FORMAT_HTML = "html" -FORMATS = (FORMAT_TEXT, FORMAT_JSON, FORMAT_CSV, FORMAT_SARIF, FORMAT_MARKDOWN, FORMAT_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 = { @@ -237,7 +246,12 @@ def build_json_payload(report: Report) -> Dict[str, object]: "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": { @@ -398,6 +412,10 @@ def render_sarif(report: Report) -> str: 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: 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/sources.py b/pathscope/sources.py index 0700020..31fcfef 100644 --- a/pathscope/sources.py +++ b/pathscope/sources.py @@ -536,6 +536,11 @@ def load_stdin_har(text: str) -> LoadResult: "ffuf", "nuclei", "recon", + "postman", + "zap", + "mitmproxy", + "graphql", + "cookies", ) @@ -566,6 +571,13 @@ def detect_input_format(text: str, path: str = "") -> str: 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: @@ -573,9 +585,20 @@ def detect_input_format(text: str, path: str = "") -> str: 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" 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/valueshape.py b/pathscope/valueshape.py new file mode 100644 index 0000000..393918a --- /dev/null +++ b/pathscope/valueshape.py @@ -0,0 +1,195 @@ +"""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})?$") +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", +] 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 index 4fecf52..9a26cbf 100644 --- a/pathscope/writers.py +++ b/pathscope/writers.py @@ -30,6 +30,14 @@ def writer_for_path(path: str) -> str: ) +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 "") @@ -265,10 +273,289 @@ def render_html(report: Report) -> str: """ -def write_report(path: str, report: Report) -> str: +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) - content = render_markdown(report) if kind == "markdown" else render_html(report) + 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_v22.py b/tests/test_features_v22.py new file mode 100644 index 0000000..335c033 --- /dev/null +++ b/tests/test_features_v22.py @@ -0,0 +1,1498 @@ +#!/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__", + } + 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_path_detector.py b/tests/test_path_detector.py index 2bb34b0..b457360 100755 --- a/tests/test_path_detector.py +++ b/tests/test_path_detector.py @@ -307,9 +307,21 @@ def test_extension_on_path_like_value(self): self.assertIn("value-extension", self.rules("report.tar.gz")) def test_plain_values_score_zero(self): - for value in ("", "hello", "en", "12345", "true", "50%", "%zz", "name"): + 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) @@ -734,7 +746,7 @@ def test_csv_show_values(self): def test_sarif_minimum_requirements(self): payload = json.loads(report.render_sarif(self.build_report())) - self.assertEqual(payload["version"], "2.1.0") + self.assertEqual(payload["version"], "2.1.0") # SARIF spec version self.assertIn("$schema", payload) run = payload["runs"][0] driver = run["tool"]["driver"] @@ -1134,7 +1146,7 @@ def test_imports_are_standard_library_only(self): "__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", + "base64", "copy", "hashlib", "html", "time", } for path in project_modules(): tree = ast.parse(path.read_text(encoding="utf-8")) From fd5ce868c65424492d3152e71f4ef498748e5f17 Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:46:54 +0000 Subject: [PATCH 5/8] Add PathScope 2.3: TUI reviewer, ledger, analytics, history, streaming, bundles Ten features from the 2.3 menu, all wired into the CLI: 1. --tui curses reviewer: list/details/filter/mark/save, no TTY -> clear error 2. --history append runs to JSON (values never stored); --trend shows new/known/resolved, drift and a sparkline 3. install.sh / install.cmd / Dockerfile: POSIX, Windows and container installs plus --doctor environment checks 4. --dashboard percentiles, bands, frequent rules, coverage gaps; --inventory ranks endpoints by distinct parameter count 5. --ledger SQLite reviews with a who/why/when audit trail; reviewed rows are hidden on later runs (never silently), query/export/import 6. --playbook Markdown remediation guide per fired rule; --list-playbooks 7. --stream bounded-memory stdin analysis with batching and --stream-json 8. --bundle reproducible (fixed-timestamp) zip with report/config/rules/ playbook/manifest; values are always scrubbed 9. --correlate parameter x host matrix, shared parameters, clusters, chains 10. --scrub redact credential-shaped values (vendor prefixes, high-entropy keys, sensitive names) behind a stable Also: --self-test grew from 10 to 16 checks covering the new modules. Safety properties are unchanged and tested: no networking imports, passive analysis only, values hidden by default, banner links verbatim, candidates-not- vulnerabilities wording, standard library only. Tests: 414 pass (337 + 77 new in tests/test_features_v23.py, one class per feature plus CLI integration). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .dockerignore | 9 + .github/workflows/pathscope.yml | 25 + Dockerfile | 45 ++ README.md | 490 ++++++++++++++++- install.cmd | 128 +++++ install.sh | 203 ++++++++ pathscope/__init__.py | 2 +- pathscope/analytics.py | 298 +++++++++++ pathscope/bundle.py | 262 ++++++++++ pathscope/ci.py | 209 ++++++++ pathscope/cli.py | 728 ++++++++++++++++++++++++++ pathscope/history.py | 285 ++++++++++ pathscope/ledger.py | 440 ++++++++++++++++ pathscope/playbooks.py | 394 ++++++++++++++ pathscope/scrub.py | 227 ++++++++ pathscope/stream.py | 292 +++++++++++ pathscope/tui.py | 419 +++++++++++++++ tests/test_features_v22.py | 6 +- tests/test_features_v23.py | 894 ++++++++++++++++++++++++++++++++ tests/test_path_detector.py | 3 +- 20 files changed, 5338 insertions(+), 21 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 install.cmd create mode 100755 install.sh create mode 100644 pathscope/analytics.py create mode 100644 pathscope/bundle.py create mode 100644 pathscope/history.py create mode 100644 pathscope/ledger.py create mode 100644 pathscope/playbooks.py create mode 100644 pathscope/scrub.py create mode 100644 pathscope/stream.py create mode 100644 pathscope/tui.py create mode 100644 tests/test_features_v23.py 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 index 52fe36f..918836f 100644 --- a/.github/workflows/pathscope.yml +++ b/.github/workflows/pathscope.yml @@ -32,6 +32,31 @@ jobs: 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) 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 index da022a6..cbd4d48 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ **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.7%2B-blue)](https://www.python.org/) +[![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) @@ -32,7 +32,7 @@ reviewing for path-traversal risk.** 1. [What it does](#what-it-does) 2. [Safety model](#safety-model) 3. [Requirements](#requirements) -4. [Installation on Kali Linux](#installation-on-kali-linux) +4. [Installation](#installation) 5. [Inputs](#inputs) 6. [Quick start](#quick-start) 7. [Presets](#presets) @@ -45,14 +45,23 @@ reviewing for path-traversal risk.** 14. [CI integration](#ci-integration) 15. [Scale and performance](#scale-and-performance) 16. [Interactive HTML report](#interactive-html-report) -17. [Exit codes](#exit-codes) -16. [Detection rules](#detection-rules) -17. [Configuration file](#configuration-file) -18. [Tests](#tests) -19. [Project layout](#project-layout) -20. [Limitations](#limitations) -21. [FAQ](#faq) -22. [Authorization and legal](#authorization-and-legal) +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. [Exit codes](#exit-codes) +27. [Detection rules](#detection-rules) +28. [Configuration file](#configuration-file) +29. [Tests](#tests) +30. [Project layout](#project-layout) +31. [Limitations](#limitations) +32. [FAQ](#faq) +33. [Authorization and legal](#authorization-and-legal) --- @@ -108,14 +117,82 @@ Additional hardening: | | | |---|---| -| Python | 3.7 or newer (developed and tested on Python 3.11, which Kali ships) | +| 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** | +| Privileges | ordinary user; **root is not required** (the Docker image is unprivileged too) | | Network | **never used** | --- -## Installation on Kali Linux +## 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. @@ -229,7 +306,7 @@ Example terminal output (values hidden): ```console $ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -PathScope 2.2.0 - passive path-parameter triage +PathScope 2.3.0 - passive path-parameter triage ---------------------------------------------------------------- GitHub: https://github.com/mrdineshpathro Instagram: https://www.instagram.com/mr_dineshpatro @@ -631,6 +708,319 @@ tickets and archives. --- +## Terminal reviewer + +`--tui` turns a finished scan into a full-screen reviewer, so you can work +through candidates without scrolling a terminal or opening a browser. + +```sh +pathscope -i requests.txt --tui --ledger reviews.db +``` + +``` +┌ candidates ──────────────────┬ details ─────────────────────────────┐ +│* 1 71 HIGH file a.test │ #1 file │ +│ 2 48 MED download b.test│ host a.test │ +│ 3 31 LOW template b.test│ location query │ +│ │ rule name-exact │ +│ │ score 71/100 (high) │ +│ │ fingerprint ec274fecea647284 │ +│ │ marked yes │ +└──────────────────────────────┴──────────────────────────────────────┘ + j/k move / filter c confidence m mark u unmark s save ? help q quit +``` + +| Key | Action | +|---|---| +| `j` / `k`, arrows | move down / up | +| `g` / `G` | first / last | +| `PgUp` / `PgDn` | page | +| `/` | filter by text (host, parameter, rule, fingerprint) | +| `c` | cycle confidence filter: all → high → medium → low | +| `m` / `u` | mark reviewed / unmark | +| `s` | save marked fingerprints to `--ledger` | +| `?` | help | +| `q` | quit | + +The reviewer only *reads* the report and *writes* the ledger you name with +`--ledger`. It never runs a scan, never sends a request, and refuses to start +without a real terminal: + +```console +$ pathscope --tui --url 'https://a.test/?file=/x' < /dev/null +error: --tui needs an interactive terminal (stdin and stdout must be TTYs) +``` + +Marks are stored with a status (`--ledger-status reviewed|accepted|false-positive|resolved`), +your name (`--reviewer`, default `$USER`) and an optional `--review-note`, so the +ledger doubles as a record of who decided what. + +--- + +## Review ledger + +`--ledger FILE` keeps reviews in a local SQLite database with a **full audit +trail**: every mark, unmark, import and status change appends an event +(who, what, when, why). Nothing leaves the file. + +```sh +# Mark every current candidate as reviewed, with your name and a note +pathscope -i requests.txt --ledger reviews.db --ledger-mark-all \ + --reviewer dinesh --review-note "checked 2026-11-29" + +# Later runs hide what you already reviewed (and say so on stderr) +pathscope -i requests.txt --ledger reviews.db + +# Show everything again +pathscope -i requests.txt --ledger reviews.db --show-known +``` + +| Command | Purpose | +|---|---| +| `--ledger FILE` | use (or create) the ledger; hides reviewed fingerprints | +| `--ledger-mark-all` | record every candidate currently reported | +| `--ledger-status STATUS` | `reviewed` (default), `accepted`, `false-positive`, `resolved` | +| `--reviewer NAME` | who is making the call (defaults to `$USER`) | +| `--review-note TEXT` | free-text note stored with the event | +| `--ledger-query TEXT` | search host/parameter/rule/status/reviewer/note and exit | +| `--ledger-export FILE` | write `--baseline`/`--suppress` compatible JSON and exit | +| `--import-ledger FILE` | import a 2.1 flat JSON ledger and exit | + +```console +$ pathscope --ledger reviews.db --ledger-query dinesh +PathScope ledger +==================================================================================== +status host parameter rule reviewer updated fingerprint +reviewed a.test file name-exact dinesh 2026-11-29T11:40:48Z ec274fecea647284 +``` + +Two details that matter in practice: + +* **Hiding is never silent.** Even with `-q`, a run that dropped reviews prints + `N candidate(s) already reviewed ... (use --show-known to include)` to stderr, + so a script reading stdout cannot mistake "0 candidates" for a clean result. +* **Export is lossless enough to share.** `--ledger-export` produces the same + fingerprint set `--suppress`/`--baseline` understood before 2.3, so existing + pipelines keep working. + +--- + +## Analysis dashboard + +`--dashboard` answers "what am I looking at?" before you read individual rows. + +```sh +pathscope -i requests.txt --dashboard +``` + +It prints score distribution, mean and percentiles, which locations fired, the +most frequent parameters and rules, and **coverage gaps** — hosts that produced +no candidate at all, which is often the more interesting half of a review. + +```console +PathScope dashboard +Requests analysed : 3 +Parameters analysed: 6 +Candidates : 4 + high : 1 + medium : 2 + low : 1 +Mean score : 47.5/100 +Percentiles : p50=48 p75=61 p90=66 p95=69 p99=71 +Locations : query=4 + +Most frequent candidates + download 2 + +Coverage gaps (hosts with no candidate) + clean.test +``` + +`--inventory` is the "most consuming endpoints" view: hosts and paths ranked by +how many *distinct parameter names* they accept. High fan-out usually means a +central handler worth reading first. + +```sh +pathscope -i requests.txt --inventory +``` + +--- + +## Cross-source correlation + +One request tells you what a parameter is called; many requests tell you what it +is **for**. `--correlate` builds the parameter × host matrix and derives three +views: + +* **shared parameters** — the same name on two or more hosts (a shared + component, a copied handler, or the same app on several deployments), +* **clusters** — parameters that always appear on exactly the same host set, +* **chained candidates** — a value that embeds *another* candidate, i.e. a + nested query string such as `?path=/view%3Ffile%3D%2Fa`. Both keys must be + candidates on the same host; the encoded inner key is decoded with the same + documented, bounded decode used everywhere else. + +```sh +pathscope -i requests.txt --correlate +``` + +```console +Parameter x host matrix: + download b.test x1 + file a.test x2 + +Shared across hosts (same component, different deployments?): + file a.test, b.test + +Chained candidates (a value embeds another candidate): + a.test: path -> file +``` + +Correlation reads **names only**. Values are decoded in memory to find nested +keys and are never printed. + +--- + +## Remediation playbooks + +Every rule ships with a playbook: what the signal means, how to confirm it by +hand, how to fix it, and a reminder that this is a heuristic, not a vulnerability. + +```sh +pathscope --list-playbooks # what exists +pathscope -i requests.txt --playbook fix.md # this run, as Markdown +``` + +The generated `fix.md` has one section per fired rule, ordered by best score, so +the top of the file is the most useful thing to hand to a developer or paste +into a ticket. Sections are self-contained: no server names beyond the ones you +supplied, no values. + +--- + +## Run history and trends + +`--history FILE` appends a compact record of each run — counts, bands, rules, +settings and every candidate's **fingerprint and parameter name only**. Values +are never written. + +```sh +pathscope -i monday.txt --history runs.json +pathscope -i friday.txt --history runs.json +pathscope --trend runs.json +``` + +```console +PathScope run trend +==================================================================================== +Runs : 2 +Candidates per run : 5, 3 +Sparkline : █▃ +New per run : 5, 1 +Resolved per run : 0, 3 +New in last run : upload_file +Resolved in last : file, download + +Per parameter (first -> last run, drift): + file a.test runs 1-2 (2x) drift -4 +``` + +"Resolved" means a fingerprint that was present before and is gone now. That is +a real signal (a fix, a removed parameter, or a renamed endpoint) and it is +usually worth more than the count of new rows. The file keeps the last 2 000 +runs. + +--- + +## Streaming stdin + +`--stream` is for pipelines that never end: `tail -f` a capture, a recon tool +writing URLs as it finds them, or a list too large to hold in memory. + +```sh +tail -f capture.log | pathscope --stream --stream-batch 500 +ffuf -o /dev/stdout ... | pathscope --stream +grep -E '=/' urls.txt | pathscope --stream --format json --save-report out.json +``` + +Memory stays bounded: lines are read one at a time, analysed in batches, and +only the merged report is retained. `--stream-json` emits one JSON object per +batch (plus a final `{"complete": true, ...}`) for a parent process to consume. + +| Constraint | Reason | +|---|---| +| line-oriented input only | HAR/OpenAPI need random access; using `--stream` with them is a usage error | +| one pass over stdin | a stream cannot be rewound | +| `--stream` + `--url` is rejected | otherwise the URL would be silently ignored | +| 5 000 000-line safety cap | runaway producers fail loudly instead of hanging | + +Exit codes follow the normal rules: `--stream` alone exits 0, and +`--fail-on-findings` gates as usual. Emitting JSON never implies a gate. + +--- + +## Reproducible bundles + +`--bundle FILE` writes one `.zip` you can attach to a ticket without leaking +data. **Values are scrubbed unconditionally**, even if the run used +`--show-values`. + +```sh +pathscope -i requests.txt --bundle case-1234.zip +pathscope --inspect-bundle case-1234.zip +``` + +``` +case-1234.zip +├── manifest.json tool/version/exit code/counts/settings/hashes +├── report.json the full machine-readable report +├── report.md the human-readable report +├── playbook.md remediation guide for the rules that fired +├── environment.json OS, Python, terminal-independent facts +├── rules.json effective rule weights +├── config.json the config used, when one was supplied +└── README.txt what this is and how to read it +``` + +Bundles are **byte-for-byte reproducible**: entry order, permissions and the +timestamp are fixed (1980-01-01), so two runs on the same input produce +identical archives and a hash in `manifest.json` is meaningful. + +--- + +## Secret scrubbing + +Reports hide values by default. When you *do* need to see them +(`--show-values`, usually while sharing a report), `--scrub` redacts anything +credential-shaped: + +```sh +pathscope -i requests.txt --show-values --scrub +``` + +```console +file a.test query 71 HIGH value +access_token a.test query 64 MED value +``` + +A value is redacted when **either** holds: + +* the **name** looks sensitive (`token`, `secret`, `password`, `signature`, + `session`, `api_key`, `authorization`, …), or +* the **value** looks like a credential: a known vendor prefix (`ghp_`, + `github_pat_`, `glpat-`, `sk_live_`, `AKIA`, `xoxb-`, `AIza`, `npm_`, + `-----BEGIN`, …), a long hex key, or a long high-entropy base64-ish string. + +The marker is ``: it is **stable**, so the same secret +shows the same marker in two reports (you can tell "same value" from "different +value") without the value being recoverable. Ordinary paths (`/etc/passwd`, +`report.pdf`) are not scrubbed — they are the analysis, not a secret. + +`--no-scrub` turns redaction off for the main report. Bundles still scrub; there +is no flag that makes a bundle contain a credential. + +--- + ## Exit codes | Code | Meaning | @@ -740,7 +1130,19 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--policy FILE|JSON] [--watch FILE] [--interval SECONDS] [--self-test] [--ignore-param NAME] [--config FILE] [--min-score N] [--max-decode-passes N] - [--fail-on-findings] + [--fail-on-findings] [--doctor] + [--tui] [--ledger FILE] + [--ledger-mark-all] + [--ledger-status {reviewed,accepted,false-positive,resolved}] + [--reviewer NAME] [--review-note TEXT] + [--ledger-query TEXT] [--ledger-export FILE] + [--import-ledger FILE] + [--dashboard] [--inventory] [--correlate] + [--playbook FILE] [--list-playbooks] + [--history FILE] [--trend FILE] + [--scrub | --no-scrub] [--bundle FILE] + [--inspect-bundle FILE] + [--stream] [--stream-batch N] [--stream-json] ``` | Option | Description | @@ -787,6 +1189,30 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] | `--watch FILE` | Re-analyse a growing capture; print new candidates only. | | `--interval SECONDS` | Polling interval for `--watch` (default 2). | | `--self-test` | Run the built-in environment checks (exit 1 on failure). | +| `--doctor` | Check this installation: interpreter, sqlite3, zipfile, curses, package files. | +| `--tui` | Interactive terminal reviewer (needs a TTY and `--ledger`). | +| `--ledger FILE` | SQLite review ledger; hides reviewed candidates and keeps an audit trail. | +| `--ledger-mark-all` | Record every reported candidate in the ledger. | +| `--ledger-status STATUS` | `reviewed` (default), `accepted`, `false-positive`, `resolved`. | +| `--reviewer NAME` | Who is reviewing (default: `$USER`); written to the audit trail. | +| `--review-note TEXT` | Note stored with the ledger event. | +| `--ledger-query TEXT` | Search the ledger (host/parameter/rule/status/reviewer/note) and exit. | +| `--ledger-export FILE` | Export review fingerprints in `--baseline` format and exit. | +| `--import-ledger FILE` | Import a 2.1 flat JSON ledger and exit. | +| `--dashboard` | Distribution, percentiles, frequent rules and coverage gaps. | +| `--inventory` | Endpoints ranked by distinct parameter count. | +| `--correlate` | Parameter × host matrix, shared parameters, clusters, chains. | +| `--playbook FILE` | Write a Markdown remediation guide for this run. | +| `--list-playbooks` | List the installed playbooks and exit. | +| `--history FILE` | Append this run to a JSON history file (values never stored). | +| `--trend FILE` | Analyse a history file and print the trend, then exit. | +| `--scrub` | Redact credential-shaped values when `--show-values` is used. | +| `--no-scrub` | Disable redaction in the main report (bundles always scrub). | +| `--bundle FILE` | Write a reproducible, scrubbed `.zip` support bundle. | +| `--inspect-bundle FILE` | Print a bundle's manifest and file list, then exit. | +| `--stream` | Read line-oriented input from stdin with bounded memory. | +| `--stream-batch N` | Analyse and report every N streamed requests (default 200). | +| `--stream-json` | With `--stream`, emit one JSON object per batch. | | `-q, --quiet` | Suppress warnings and the stderr summary. | | `--no-color` | Disable colour on terminals. | | `--no-banner` | Suppress the startup banner. | @@ -847,7 +1273,7 @@ python3 -m unittest discover -s tests -v python3 tests/test_path_detector.py ``` -322 tests cover exactly the behaviours this tool promises: +414 tests cover exactly the behaviours this tool promises: | Area | What is asserted | |---|---| @@ -872,6 +1298,16 @@ python3 tests/test_path_detector.py | Tool exports | Postman, ZAP, mitmproxy, GraphQL, cookie jars (names only) | | Scale | dedupe modes, `--max-entries`, `--stats`, rate-limited progress | | Interactive | controls, escaping, self-containment, HTML-only enforcement | +| Terminal reviewer | cursor/filter/mark state machine, headless curses render, no-TTY refusal | +| Review ledger | record/forget/audit events, reviewed hiding, query, export, 2.1 import | +| Dashboard | percentiles, bands, coverage gaps, inventory ranking | +| Correlation | matrix, shared parameters, host clusters, encoded chains | +| Playbooks | per-rule coverage, Markdown export, `--list-playbooks` | +| History | append/load, no values stored, new/resolved, sparkline, corrupt file | +| Streaming | batching, dedupe, comments/blanks, format rejection, line cap, JSON batches | +| Bundles | layout, scrubbing, byte reproducibility, manifest roundtrip, bad zip | +| Scrub | vendor prefixes, high-entropy values, name hints, stable markers, `--no-scrub` | +| Packaging | `install.sh` POSIX-ness, dry run, unknown option, Dockerfile, `--doctor` | --- @@ -900,8 +1336,24 @@ pathscope/ │ ├── progress.py # stderr progress (--progress) │ ├── writers.py # Markdown / HTML / interactive HTML reports │ ├── cli.py # argument parsing, input merging, exit codes +│ ├── tui.py # curses terminal reviewer (--tui) +│ ├── ledger.py # SQLite reviews + audit trail (--ledger) +│ ├── analytics.py # dashboard, inventory, correlation +│ ├── playbooks.py # per-rule remediation guidance +│ ├── history.py # run history, trends, sparklines +│ ├── stream.py # bounded-memory stdin analysis (--stream) +│ ├── bundle.py # reproducible, scrubbed support bundles +│ ├── scrub.py # credential-shaped value redaction │ └── __main__.py # enables `python3 -m pathscope` -├── tests/test_path_detector.py # unittest suite (offline) +├── tests/ +│ ├── test_path_detector.py # core suite (offline) +│ ├── test_features.py # end-to-end feature suite +│ ├── test_features_v22.py # 2.2 regression suite +│ └── test_features_v23.py # 2.3 feature suite (one class per feature) +├── install.sh # POSIX one-command installer +├── install.cmd # Windows installer +├── Dockerfile # slim, unprivileged, --self-test healthcheck +├── .dockerignore ├── assets/logo.svg # original PathScope mark (route + magnifier) ├── README.md └── LICENSE @@ -950,7 +1402,9 @@ No. PathScope only reads `log.entries[].request.url`, `queryString` and `postData`. No `curl`, no `requests`, no sockets. **Which Python versions work?** -3.7+. The code avoids 3.8+ syntax; CI was run on 3.11 (Kali default). +3.8 or newer. The installers enforce that at install time and `--doctor` +reports the version it found. CI runs on 3.11 (the Kali default) and 3.12 +(the Docker image). **Why not regex configuration?** ReDoS risk and explainability. Literal terms are validated and predictable. diff --git a/install.cmd b/install.cmd new file mode 100644 index 0000000..7999efc --- /dev/null +++ b/install.cmd @@ -0,0 +1,128 @@ +@echo off +REM PathScope installer for Windows (cmd.exe / PowerShell). +REM +REM install.cmd install into %LOCALAPPDATA%\PathScope +REM set PREFIX=D:\tools & install.cmd +REM +REM Requires Python 3.8+ on PATH (the Microsoft Store or python.org build). +REM PathScope has no third-party dependencies, so nothing is downloaded. + +setlocal EnableDelayedExpansion + +set "PROGRAM=PathScope" +if not defined PREFIX set "PREFIX=%LOCALAPPDATA%\PathScope" +set "APPDIR=%PREFIX%\app" +set "BINDIR=%PREFIX%\bin" +set "NO_PATH=0" +set "DRY_RUN=0" + +if /I "%~1"=="--help" goto :usage +if /I "%~1"=="-h" goto :usage +if /I "%~1"=="--dry-run" set "DRY_RUN=1" +if /I "%~1"=="--no-path" set "NO_PATH=1" + +echo %PROGRAM% installer - passive, offline triage of path-like parameters + +REM --- locate Python ------------------------------------------------------ +set "PYTHON=" +for %%P in (python.exe py.exe) do ( + if not defined PYTHON ( + where %%P >nul 2>nul && set "PYTHON=%%P" + ) +) +if not defined PYTHON ( + echo error: Python was not found on PATH. + echo Install Python 3.8+ from https://www.python.org/downloads/windows/ + exit /b 1 +) + +for /f "delims=" %%V in ('%PYTHON% -c "import sys;print('%%d.%%d' %% sys.version_info[:2])" 2^>nul') do set "PYVERSION=%%V" +if not defined PYVERSION ( + echo error: '%PYTHON%' is not a working interpreter. + exit /b 1 +) +for /f "tokens=1,2 delims=." %%A in ("!PYVERSION!") do ( + set "PYMAJOR=%%A" + set "PYMINOR=%%B" +) +if !PYMAJOR! LSS 3 ( + echo error: %PROGRAM% needs Python 3.8 or newer ^(found !PYVERSION!^) + exit /b 1 +) +if !PYMAJOR! EQU 3 if !PYMINOR! LSS 8 ( + echo error: %PROGRAM% needs Python 3.8 or newer ^(found !PYVERSION!^) + exit /b 1 +) +echo python : %PYTHON% ^(!PYVERSION!^) + +REM --- locate the sources ------------------------------------------------- +set "SOURCE_ROOT=" +if defined PATHSCOPE_SRC set "SOURCE_ROOT=%PATHSCOPE_SRC%" +if not defined SOURCE_ROOT if exist "%~dp0pathscope\cli.py" set "SOURCE_ROOT=%~dp0" +if not defined SOURCE_ROOT if exist "%CD%\pathscope\cli.py" set "SOURCE_ROOT=%CD%" +if not defined SOURCE_ROOT ( + echo error: no PathScope sources found next to this script. + echo Run install.cmd from the repository root. + exit /b 1 +) +echo source : %SOURCE_ROOT% + +if "%DRY_RUN%"=="1" ( + echo [dry-run] would copy sources to %APPDIR% + echo [dry-run] would write %BINDIR%\pathscope.cmd + echo dry run complete + exit /b 0 +) + +REM --- copy files --------------------------------------------------------- +if not exist "%APPDIR%" mkdir "%APPDIR%" +if not exist "%BINDIR%" mkdir "%BINDIR%" +xcopy /E /I /Y /Q "%SOURCE_ROOT%pathscope" "%APPDIR%\pathscope" >nul +copy /Y "%SOURCE_ROOT%path_detector.py" "%APPDIR%" >nul +if exist "%SOURCE_ROOT%README.md" copy /Y "%SOURCE_ROOT%README.md" "%APPDIR%" >nul +if exist "%SOURCE_ROOT%assets" xcopy /E /I /Y /Q "%SOURCE_ROOT%assets" "%APPDIR%\assets" >nul + +> "%BINDIR%\pathscope.cmd" echo @echo off +>> "%BINDIR%\pathscope.cmd" echo "%PYTHON%" "%APPDIR%\path_detector.py" %%* +echo launcher: %BINDIR%\pathscope.cmd + +REM --- add to the user PATH ---------------------------------------------- +if "%NO_PATH%"=="1" ( + echo PATH : left alone ^(--no-path^) +) else ( + echo %PATH% | findstr /I /C:"%BINDIR%" >nul + if errorlevel 1 ( + set "OLDPATH=" + for /f "tokens=2,*" %%A in ('reg query HKCU\Environment /v PATH 2^>nul') do set "OLDPATH=%%B" + setx PATH "!OLDPATH!;%BINDIR%" >nul + echo PATH : added %BINDIR% to the user PATH + echo note : open a new terminal to pick it up + ) else ( + echo PATH : already contains %BINDIR% + ) +) + +REM --- verify ------------------------------------------------------------- +"%BINDIR%\pathscope.cmd" --version >nul 2>nul +if errorlevel 1 ( + echo error: the launcher was installed but did not run. + exit /b 1 +) +echo verified: %BINDIR%\pathscope.cmd --version +echo. +echo next steps: +echo pathscope --help +echo pathscope --self-test +echo pathscope -i requests.txt --format json +exit /b 0 + +:usage +echo PathScope installer for Windows +echo. +echo Usage: install.cmd [--no-path] [--dry-run] [--help] +echo. +echo --no-path do not add the launcher to the user PATH +echo --dry-run show what would happen, change nothing +echo. +echo Environment: PREFIX ^(default %%LOCALAPPDATA%%\PathScope^) +exit /b 0 diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..90d1d2d --- /dev/null +++ b/install.sh @@ -0,0 +1,203 @@ +#!/bin/sh +# PathScope one-command installer (Kali / Debian / Ubuntu / macOS / WSL). +# +# curl -fsSL https://raw.githubusercontent.com/mrdineshpathro/pathscope/main/install.sh | sh +# +# or from a checkout: +# +# ./install.sh # install into ~/.local +# sudo PREFIX=/opt/pathscope ./install.sh +# ./install.sh --no-path # skip the shell-rc PATH edit +# +# The script is deliberately boring and auditable: +# * POSIX sh only, no bashisms, no curl inside the script, +# * no root unless you ask for a PREFIX you cannot write, +# * it never installs Python packages (PathScope is stdlib-only), +# * every step prints what it did and is safe to re-run. + +set -eu + +PROGRAM="PathScope" +VERSION="2.3.0" +PREFIX="${PREFIX:-$HOME/.local}" +BINDIR="$PREFIX/bin" +APPDIR="$PREFIX/share/pathscope" +EDIT_RC=1 +DRY_RUN=0 + +usage() { + cat <<'USAGE' +PathScope installer + +Usage: ./install.sh [options] + +Options: + --prefix DIR install under DIR (default: $HOME/.local) + --no-path do not touch ~/.profile / ~/.zshrc + --dry-run print the actions without changing anything + --uninstall remove the launcher and program files + -h, --help show this help + +Environment: + PREFIX same as --prefix + PYTHON interpreter to use (default: python3) +USAGE +} + +say() { printf '%s\n' "$*"; } +fail() { printf 'error: %s\n' "$*" >&2; exit 1; } + +run() { + if [ "$DRY_RUN" -eq 1 ]; then + printf ' [dry-run] %s\n' "$*" + else + "$@" + fi +} + +parse_args() { + while [ $# -gt 0 ]; do + case "$1" in + --prefix) [ $# -ge 2 ] || fail "--prefix needs a directory"; PREFIX="$2"; BINDIR="$PREFIX/bin"; APPDIR="$PREFIX/share/pathscope"; shift 2 ;; + --prefix=*) PREFIX="${1#*=}"; BINDIR="$PREFIX/bin"; APPDIR="$PREFIX/share/pathscope"; shift ;; + --no-path) EDIT_RC=0; shift ;; + --dry-run) DRY_RUN=1; shift ;; + --uninstall) UNINSTALL=1; shift ;; + -h|--help) usage; exit 0 ;; + *) fail "unknown option '$1' (try --help)" ;; + esac + done +} + +check_python() { + PYTHON="${PYTHON:-python3}" + command -v "$PYTHON" >/dev/null 2>&1 || fail "$PYTHON not found; install Python 3.8+ first" + version=$("$PYTHON" -c 'import sys; print("%d.%d" % sys.version_info[:2])') \ + || fail "$PYTHON is not usable" + major=$(printf '%s' "$version" | cut -d. -f1) + minor=$(printf '%s' "$version" | cut -d. -f2) + if [ "$major" -lt 3 ] || { [ "$major" -eq 3 ] && [ "$minor" -lt 8 ]; }; then + fail "$PROGRAM needs Python 3.8 or newer (found $version)" + fi + say " python : $PYTHON ($version)" + "$PYTHON" - "$SOURCE_ROOT" <<'PY' || fail "bundled sources failed their self-check" +import sys, pathlib +root = pathlib.Path(sys.argv[1]) +missing = [p for p in ("path_detector.py", "pathscope/cli.py", "pathscope/__init__.py") + if not (root / p).is_file()] +if missing: + raise SystemExit("missing files: " + ", ".join(missing)) +sys.path.insert(0, str(root)) +import pathscope +print(" version: %s" % pathscope.__version__) +PY +} + +detect_source_root() { + # The script lives either next to the checkout or is piped from curl. + if [ -n "${PATHSCOPE_SRC:-}" ]; then + SOURCE_ROOT="$PATHSCOPE_SRC" + elif [ -f "$0" ] && [ -d "$(dirname "$0")/pathscope" ]; then + SOURCE_ROOT=$(cd "$(dirname "$0")" && pwd) + elif [ -f "$PWD/path_detector.py" ] && [ -d "$PWD/pathscope" ]; then + SOURCE_ROOT="$PWD" + else + fail "no PathScope sources found. Clone the repository and run ./install.sh from it + (git clone https://github.com/mrdineshpathro/pathscope && cd pathscope)." + fi + say " source : $SOURCE_ROOT" +} + +install_files() { + say "installing into $PREFIX" + run mkdir -p "$BINDIR" "$APPDIR" + run cp -R "$SOURCE_ROOT/pathscope" "$APPDIR/" + run cp "$SOURCE_ROOT/path_detector.py" "$APPDIR/" + [ -f "$SOURCE_ROOT/README.md" ] && run cp "$SOURCE_ROOT/README.md" "$APPDIR/" + [ -d "$SOURCE_ROOT/assets" ] && run cp -R "$SOURCE_ROOT/assets" "$APPDIR/" + if [ "$DRY_RUN" -eq 1 ]; then + say " [dry-run] would write $BINDIR/pathscope" + say " [dry-run] would chmod 755 $BINDIR/pathscope" + return 0 + fi + cat > "$BINDIR/pathscope" </dev/null; then + say " PATH : $rc already updated" + continue + fi + if [ "$DRY_RUN" -eq 1 ]; then + say " [dry-run] would append $BINDIR to $rc" + continue + fi + { + printf '\n%s\n' "$block_marker" + printf 'export PATH="%s:$PATH"\n' "$BINDIR" + printf '# <<< PathScope <<<\n' + } >> "$rc" + say " PATH : appended $BINDIR to $rc" + done + case ":$PATH:" in + *":$BINDIR:"*) ;; + *) say " note : run '. ~/.profile' (or open a new shell) to pick up $BINDIR" ;; + esac +} + +verify() { + [ "$DRY_RUN" -eq 0 ] || { say "dry run complete"; return; } + if "$BINDIR/pathscope" --version >/dev/null 2>&1; then + say "verified: $BINDIR/pathscope --version" + else + fail "the launcher was installed but did not run; check '$PYTHON'" + fi +} + +uninstall() { + say "removing $PROGRAM" + run rm -f "$BINDIR/pathscope" + run rm -rf "$APPDIR" + # remove the directories this installer created, but only if now empty + if [ "$DRY_RUN" -eq 0 ]; then + rmdir "$BINDIR" 2>/dev/null || true + rmdir "$PREFIX/share" 2>/dev/null || true + rmdir "$PREFIX" 2>/dev/null || true + fi + say "done (shell-rc PATH lines are left in place; remove the" + say " '# >>> PathScope >>>' block by hand if you want them gone)" +} + +main() { + UNINSTALL=0 + parse_args "$@" + say "$PROGRAM installer - passive, offline triage of path-like parameters" + [ "$UNINSTALL" -eq 1 ] && { uninstall; return 0; } + detect_source_root + check_python + install_files + update_path + verify + say "" + say "next steps:" + say " pathscope --help" + say " pathscope --self-test" + say " pathscope -i requests.txt --format json" +} + +main "$@" diff --git a/pathscope/__init__.py b/pathscope/__init__.py index 6b99187..f405bea 100644 --- a/pathscope/__init__.py +++ b/pathscope/__init__.py @@ -14,7 +14,7 @@ from __future__ import annotations PROGRAM = "PathScope" -__version__ = "2.2.0" +__version__ = "2.3.0" # Displayed on every start. These are never opened and never requested. GITHUB_URL = "https://github.com/mrdineshpathro" diff --git a/pathscope/analytics.py b/pathscope/analytics.py new file mode 100644 index 0000000..83bbfe5 --- /dev/null +++ b/pathscope/analytics.py @@ -0,0 +1,298 @@ +"""Statistics, inventory and cross-source correlation over local captures. + +Everything here is computed from the requests PathScope already parsed. No +value is fetched, resolved or opened; names and inert value strings only. + +Three views: + +``dashboard`` + Totals, score distribution, percentile bands, parameter frequency, + coverage gaps (hosts with requests but no candidates) and the longest + parameter names seen. + +``inventory`` + "Most consuming endpoints": requests per host/path with the parameter + names (not values) that appeared on them. Useful to decide where to look + first and to spot endpoints with unusually many file-like parameters. + +``correlate`` + The parameter x source matrix, parameters shared across hosts (a classic + sign of a shared component), and chained candidates (a path-like + parameter that also names another path-like parameter, e.g. + ``?file=/a&template=/b``). +""" + +from __future__ import annotations + +import math +import re +from collections import Counter, defaultdict +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional, Sequence, Tuple + +from .detector import Report +from .heuristics import canonical_name +from .textutil import decode_forms + +#: Confidence bands in display order. +BANDS = ("high", "medium", "low") + +#: Percentiles offered by ``--percentiles``. +PERCENTILES = (50, 75, 90, 95, 99) + +#: A parameter that appears on more hosts than this is called shared. +SHARED_MIN_HOSTS = 2 + +#: How many rows the text tables print before truncating. +MAX_TABLE_ROWS = 40 + + +def percentile(values: Sequence[int], rank: int) -> Optional[float]: + """Linear-interpolated percentile (``rank`` in 0..100), or ``None``.""" + if not values: + return None + ordered = sorted(values) + if rank <= 0: + return float(ordered[0]) + if rank >= 100: + return float(ordered[-1]) + position = (len(ordered) - 1) * (rank / 100.0) + lower = math.floor(position) + upper = math.ceil(position) + if lower == upper: + return float(ordered[lower]) + fraction = position - lower + return ordered[lower] + (ordered[upper] - ordered[lower]) * fraction + + +# --------------------------------------------------------------------------- +# Dashboard +# --------------------------------------------------------------------------- +@dataclass +class Dashboard: + """Aggregate numbers about one run.""" + + requests: int = 0 + parameters: int = 0 + findings: int = 0 + bands: Dict[str, int] = field(default_factory=dict) + scores: List[int] = field(default_factory=list) + percentiles: Dict[int, Optional[float]] = field(default_factory=dict) + hosts: Dict[str, int] = field(default_factory=dict) + rules: Dict[str, int] = field(default_factory=dict) + locations: Dict[str, int] = field(default_factory=dict) + frequent: List[Tuple[str, int]] = field(default_factory=list) + coverage_gaps: List[str] = field(default_factory=list) + longest_names: List[Tuple[str, int]] = field(default_factory=list) + mean_score: float = 0.0 + + def as_dict(self) -> Dict[str, object]: + return { + "requests": self.requests, + "parameters": self.parameters, + "findings": self.findings, + "bands": dict(self.bands), + "percentiles": {str(k): v for k, v in self.percentiles.items()}, + "mean_score": round(self.mean_score, 2), + "hosts": dict(self.hosts), + "rules": dict(self.rules), + "locations": dict(self.locations), + "frequent": [{"parameter": name, "count": count} for name, count in self.frequent], + "coverage_gaps": list(self.coverage_gaps), + "longest_names": [ + {"parameter": name, "length": length} for name, length in self.longest_names + ], + } + + +def dashboard(report: Report, requests: Sequence = ()) -> Dashboard: + """Build the ``--dashboard`` analytics view for ``report``. + + ``requests`` (optional) lets the coverage-gap section list hosts that were + analysed but produced no candidate at all. + """ + view = Dashboard( + requests=report.requests_analyzed, + parameters=report.parameters_analyzed, + findings=report.candidate_count, + bands={band: report.confidence_counts.get(band, 0) for band in BANDS}, + ) + for finding in report.findings: + view.scores.append(finding.score) + view.hosts[finding.host] = view.hosts.get(finding.host, 0) + 1 + view.rules[finding.rule] = view.rules.get(finding.rule, 0) + 1 + view.locations[finding.location] = view.locations.get(finding.location, 0) + 1 + if view.scores: + view.mean_score = sum(view.scores) / len(view.scores) + view.percentiles = {rank: percentile(view.scores, rank) for rank in PERCENTILES} + + counts: Counter = Counter() + seen_hosts: Dict[str, set] = defaultdict(set) + for finding in report.findings: + name = canonical_name(finding.parameter) + counts[name] += finding.occurrences + seen_hosts[name].add(finding.host) + view.frequent = counts.most_common(10) + + if requests: + analysed_hosts = {request.url.display_host for request in requests} + view.coverage_gaps = coverage_gaps(report, analysed_hosts) + + view.longest_names = sorted( + ((canonical_name(finding.parameter), len(finding.parameter)) for finding in report.findings), + key=lambda item: (-item[1], item[0]), + )[:5] + return view + + +def coverage_gaps(report: Report, known_hosts: Iterable[str]) -> List[str]: + """Hosts (or sources) that were analysed but produced no candidates.""" + reported = {finding.host for finding in report.findings} + return sorted({host for host in known_hosts if host and host not in reported}) + + +# --------------------------------------------------------------------------- +# Inventory +# --------------------------------------------------------------------------- +@dataclass(frozen=True) +class EndpointEntry: + """One request path with the parameter names seen on it.""" + + host: str + resource: str + method: str + parameters: Tuple[str, ...] + + @property + def weight(self) -> int: + """Number of distinct parameters: a rough "consumption" score.""" + return len(self.parameters) + + +def inventory(requests: Sequence) -> List[EndpointEntry]: + """Return every request as an endpoint row, busiest first.""" + rows: Dict[Tuple[str, str, str], set] = {} + order: List[Tuple[str, str, str]] = [] + for request in requests: + resource = request.url.display_resource + key = (request.url.display_host, request.method.upper(), resource) + if key not in rows: + rows[key] = set() + order.append(key) + for parameter in request.parameters: + rows[key].add(parameter.name) + entries = [ + EndpointEntry( + host=key[0], + method=key[1], + resource=key[2], + parameters=tuple(sorted(rows[key])), + ) + for key in order + ] + entries.sort(key=lambda entry: (-entry.weight, entry.host, entry.resource)) + return entries + + +# --------------------------------------------------------------------------- +# Cross-source correlation +# --------------------------------------------------------------------------- +@dataclass +class Correlation: + """Parameter x source matrix plus derived relationships.""" + + matrix: Dict[str, Dict[str, int]] = field(default_factory=dict) + shared: List[Tuple[str, List[str]]] = field(default_factory=list) + chained: List[Tuple[str, str, str]] = field(default_factory=list) + clusters: Dict[str, List[str]] = field(default_factory=dict) + + def as_dict(self) -> Dict[str, object]: + return { + "matrix": {name: dict(row) for name, row in self.matrix.items()}, + "shared_parameters": [ + {"parameter": name, "hosts": hosts} for name, hosts in self.shared + ], + "chained": [ + {"parameter": name, "related": related, "host": host} + for name, related, host in self.chained + ], + "clusters": {name: list(members) for name, members in self.clusters.items()}, + } + + +#: Matches ``name=`` inside a parameter value (a nested query string). +_NESTED_KEY = re.compile(r"(?:^|[?&;])([A-Za-z_][A-Za-z0-9_.-]{0,60})=") + + +def correlate(report: Report, requests: Sequence = ()) -> Correlation: + """Build the parameter x host matrix and derived relationships. + + ``requests`` (optional) enables chained-candidate detection: a parameter + whose *value* embeds another query string, e.g. ``?next=/view?file=/a``. + Only the key names are read; the values themselves are not reported. + """ + view = Correlation() + for finding in report.findings: + name = canonical_name(finding.parameter) + row = view.matrix.setdefault(name, {}) + row[finding.host] = row.get(finding.host, 0) + 1 + + shared = [] + for name, row in sorted(view.matrix.items()): + if len(row) >= SHARED_MIN_HOSTS: + shared.append((name, sorted(row))) + shared.sort(key=lambda item: (-len(item[1]), item[0])) + view.shared = shared + + # Chained candidates: one parameter's value embeds another parameter that + # is itself a candidate on the same host (a nested query string). + candidate_names = {name for name in view.matrix} + seen_chains: set = set() + for request in requests: + host = request.url.display_host + names_here = {canonical_name(p.name): p for p in request.parameters} + for parameter in request.parameters: + outer = canonical_name(parameter.name) + if outer not in candidate_names: + continue + # Nested keys are usually percent-encoded inside the outer value. + candidate_text = parameter.value or "" + try: + candidate_text = decode_forms(candidate_text, 2)[-1][1] + except Exception: # pragma: no cover - malformed escapes are safe + pass + for match in _NESTED_KEY.finditer(candidate_text): + inner = canonical_name(match.group(1)) + if inner in candidate_names and inner != outer: + key = (outer, inner, host) + if key not in seen_chains: + seen_chains.add(key) + view.chained.append(key) + view.chained.sort() + + # Clusters: parameters that always appear on the same host set. + signature_hosts: Dict[Tuple[str, ...], List[str]] = defaultdict(list) + for name, row in view.matrix.items(): + signature_hosts[tuple(sorted(row))].append(name) + view.clusters = { + "|".join(signature): sorted(members) + for signature, members in signature_hosts.items() + if len(members) > 1 + } + return view + + +__all__ = [ + "BANDS", + "Correlation", + "Dashboard", + "EndpointEntry", + "MAX_TABLE_ROWS", + "PERCENTILES", + "SHARED_MIN_HOSTS", + "correlate", + "coverage_gaps", + "dashboard", + "inventory", + "percentile", +] diff --git a/pathscope/bundle.py b/pathscope/bundle.py new file mode 100644 index 0000000..b491698 --- /dev/null +++ b/pathscope/bundle.py @@ -0,0 +1,262 @@ +"""Reproducible support bundles (``--bundle FILE.zip``). + +A bundle is a single shareable archive that lets someone else reproduce a run: + + manifest.json tool/version, settings, rule weights, exit code + report.json the full JSON report (values scrubbed) + report.md a human-readable report + playbook.md the remediation guide for this run + config.json the effective configuration (if one was supplied) + rules.json effective rule weights (including overrides) + environment.json interpreter/OS details, no hostnames or usernames + README.txt what the bundle contains and what was redacted + +Two guarantees: + +* **No network is used and no input is re-read.** The bundle is built from the + report already in memory plus files the user named. +* **Secrets are scrubbed.** Values are only included when the run used + ``--show-values``, and even then :mod:`pathscope.scrub` redacts + credential-shaped ones. ``--bundle`` forces scrubbing on. + +The archive uses :mod:`zipfile` with fixed timestamps so the same run produces +the same bytes (useful for diffing bundles in a ticket). +""" + +from __future__ import annotations + +import json +import os +import platform +import sys +import zipfile +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence + +from . import PROGRAM, __version__ +from .detector import Report +from .scrub import scrub_report + +#: Fixed archive timestamp (ZIP minimum) so bundles are reproducible. +ZIP_TIMESTAMP = (1980, 1, 1, 0, 0, 0) +#: Files larger than this are refused rather than embedded. +MAX_EMBED_BYTES = 2 * 1024 * 1024 + +BUNDLE_README = """PathScope support bundle +======================== + +This archive was produced by PathScope {version} to make one analysis run +reproducible without sharing raw captures. + +Contents +-------- + manifest.json tool version, settings, rule weights, exit code + report.json full JSON report (parameter values scrubbed) + report.md human-readable report + playbook.md remediation guidance for this run's rules + config.json the effective configuration file, if one was used + rules.json effective rule weights (including overrides) + environment.json interpreter and OS details + README.txt this file + +Privacy +------- +* Findings are derived from parameter names and inert value strings only. +* Values are included only when the run used --show-values, and even then + credential-shaped values are replaced with . +* No hostnames, usernames, paths or timestamps of the analysing machine are + recorded beyond the interpreter version and platform string. +* The bundle contains no captures and cannot be replayed. + +What it does NOT contain +------------------------ +The original input (HAR/URL list/proxy export). To reproduce, re-run PathScope +on the same capture with the settings in manifest.json. +""" + + +class BundleError(RuntimeError): + """Raised when the bundle cannot be written.""" + + +@dataclass +class BundleManifest: + """Metadata stored as ``manifest.json`` inside the archive.""" + + created_with: str = f"{PROGRAM} {__version__}" + exit_code: int = 0 + mode: str = "scan" + min_score: int = 0 + show_values: bool = False + scrubbed: bool = True + rules_source: str = "defaults" + name_lang: Sequence[str] = () + settings: Dict[str, object] = field(default_factory=dict) + counts: Dict[str, int] = field(default_factory=dict) + files: List[str] = field(default_factory=list) + + def as_dict(self) -> Dict[str, object]: + return { + "tool": PROGRAM, + "version": __version__, + "created_with": self.created_with, + "passive": True, + "network_requests_made": 0, + "exit_code": self.exit_code, + "mode": self.mode, + "min_score": self.min_score, + "show_values": self.show_values, + "values_scrubbed": self.scrubbed, + "rules_source": self.rules_source, + "name_lang": list(self.name_lang), + "settings": dict(self.settings), + "counts": dict(self.counts), + "files": list(self.files), + } + + +def environment_info() -> Dict[str, object]: + """Non-identifying environment details. + + Deliberately excludes hostname, username, cwd and absolute paths. + """ + return { + "python": platform.python_version(), + "implementation": platform.python_implementation(), + "platform": platform.system(), + "release": platform.release(), + "machine": platform.machine(), + "stdlib_only": True, + "argv0": os.path.basename(sys.argv[0] or "pathscope"), + } + + +def _render_markdown(report: Report) -> str: + from .writers import render_markdown + + return render_markdown(report) + + +def _render_playbook(report: Report) -> str: + from .playbooks import render_playbook_markdown + + return render_playbook_markdown(report) + + +def _render_json(report: Report) -> str: + from .report import render_json + + return render_json(report) + + +def _read_text(path: str) -> Optional[str]: + """Read a small text file for embedding, or ``None`` when not usable.""" + try: + if os.path.getsize(path) > MAX_EMBED_BYTES: + return None + with open(path, "r", encoding="utf-8-sig", errors="replace") as handle: + return handle.read() + except OSError: + return None + + +def build_bundle( + path: str, + report: Report, + *, + exit_code: int = 0, + settings: Optional[Dict[str, object]] = None, + config_path: str = "", + rules: Optional[Dict[str, int]] = None, +) -> BundleManifest: + """Write the bundle to ``path`` and return its manifest.""" + from .report import render_json + + # Bundles are shared: always scrub, even without --show-values. + safe_report = scrub_report(report) + + manifest = BundleManifest( + exit_code=exit_code, + mode=safe_report.mode, + min_score=safe_report.min_score, + show_values=safe_report.show_values, + scrubbed=True, + rules_source=safe_report.rules_source, + name_lang=tuple(safe_report.name_lang), + settings=dict(settings or {}), + counts={ + "requests": safe_report.requests_analyzed, + "parameters": safe_report.parameters_analyzed, + "candidates": safe_report.candidate_count, + "new": safe_report.new_count, + "known": safe_report.known_count, + "resolved": len(safe_report.resolved), + }, + ) + + payloads: Dict[str, bytes] = {} + payloads["report.json"] = render_json(safe_report).encode("utf-8") + payloads["report.md"] = _render_markdown(safe_report).encode("utf-8") + payloads["playbook.md"] = _render_playbook(safe_report).encode("utf-8") + payloads["environment.json"] = ( + json.dumps(environment_info(), indent=2, sort_keys=True) + "\n" + ).encode("utf-8") + payloads["rules.json"] = ( + json.dumps(rules or safe_report.rules or {}, indent=2, sort_keys=True) + "\n" + ).encode("utf-8") + if config_path: + text = _read_text(config_path) + if text is not None: + payloads["config.json"] = text.encode("utf-8") + payloads["README.txt"] = BUNDLE_README.format(version=__version__).encode("utf-8") + + manifest.files = sorted(payloads) + ["manifest.json"] + payloads["manifest.json"] = ( + json.dumps(manifest.as_dict(), indent=2, sort_keys=True) + "\n" + ).encode("utf-8") + + directory = os.path.dirname(os.path.abspath(path)) + if directory and not os.path.isdir(directory): + raise BundleError(f"cannot write bundle '{path}': no such directory") + try: + with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for name in sorted(payloads): + info = zipfile.ZipInfo(name, date_time=ZIP_TIMESTAMP) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = 0o644 << 16 + archive.writestr(info, payloads[name]) + except (OSError, zipfile.BadZipFile) as exc: + raise BundleError(f"cannot write bundle '{path}': {exc}") from exc + return manifest + + +def read_manifest(path: str) -> Dict[str, object]: + """Read just the manifest from an existing bundle (``--inspect-bundle``).""" + try: + with zipfile.ZipFile(path, "r") as archive: + with archive.open("manifest.json") as handle: + return json.loads(handle.read().decode("utf-8")) + except (OSError, KeyError, zipfile.BadZipFile, ValueError) as exc: + raise BundleError(f"'{path}' is not a PathScope bundle: {exc}") from exc + + +def list_bundle(path: str) -> List[str]: + """Return the member names of an existing bundle.""" + try: + with zipfile.ZipFile(path, "r") as archive: + return archive.namelist() + except (OSError, zipfile.BadZipFile) as exc: + raise BundleError(f"cannot read bundle '{path}': {exc}") from exc + + +__all__ = [ + "BUNDLE_README", + "MAX_EMBED_BYTES", + "ZIP_TIMESTAMP", + "BundleError", + "BundleManifest", + "build_bundle", + "environment_info", + "list_bundle", + "read_manifest", +] diff --git a/pathscope/ci.py b/pathscope/ci.py index 772e8f8..c91fa34 100644 --- a/pathscope/ci.py +++ b/pathscope/ci.py @@ -246,6 +246,97 @@ def decode_bounded() -> None: 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) + return [ ("banner strings are exact", banner_exact), ("URLs are parsed locally", url_parse), @@ -257,6 +348,12 @@ def decode_bounded() -> None: ("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), ] @@ -291,10 +388,122 @@ def render_selftest(results: Sequence[Dict[str, object]]) -> str: 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 index 46b694d..342cb89 100644 --- a/pathscope/cli.py +++ b/pathscope/cli.py @@ -71,6 +71,14 @@ 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 .sources import ( INPUT_FORMAT_AUTO, INPUT_FORMATS, @@ -416,6 +424,137 @@ def build_parser() -> argparse.ArgumentParser: 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", + ) return parser @@ -772,6 +911,80 @@ def _handle_init_policy(args, stderr) -> int: 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") @@ -806,6 +1019,41 @@ def run( 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) config, error = _apply_preset_and_config(args) if error: @@ -876,6 +1124,30 @@ def run( 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) @@ -898,6 +1170,9 @@ def run( return EXIT_USAGE return EXIT_OK + if args.stream: + return _run_stream(args, options, stdout, stderr, stdin_text) + needs_stdin = "-" in args.input if stdin_text is None and needs_stdin: stdin_text = _read_stdin() @@ -950,6 +1225,32 @@ def run( 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 + # The TUI shows reviewed rows *marked* rather than hiding them, so the + # reviewer can see and undo a previous decision. + if ledger_store is not None and not args.show_known and not args.tui: + 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, + ) + 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) if args.github_annotations: rendered = ci_module.render_github_annotations(report_data) elif args.summary_only: @@ -967,6 +1268,17 @@ def run( 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.save_report: try: kind = write_report( @@ -982,6 +1294,69 @@ def run( 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.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.mark_reviewed: ledger = _read_mark_reviewed(args.mark_reviewed) for finding in report_data.findings: @@ -993,6 +1368,77 @@ def run( 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, + ) + 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( @@ -1016,6 +1462,9 @@ def run( file=stderr, ) + if ledger_store is not None: + ledger_store.close() + # -- gates: --policy first (more specific), then --fail-on-findings -- if policy is not None: result = evaluate_policy(report_data, policy) @@ -1085,3 +1534,282 @@ def main(argv: Optional[Sequence[str]] = None) -> int: "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 + 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/ledger.py b/pathscope/ledger.py new file mode 100644 index 0000000..a9989da --- /dev/null +++ b/pathscope/ledger.py @@ -0,0 +1,440 @@ +"""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 os +import sqlite3 +import time +from dataclasses import dataclass +from typing import Dict, Iterable, List, Optional + +from .detector import Finding + +SCHEMA_VERSION = 1 + +#: 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 '', + note 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()) + + +@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 = "" + note: str = "" + created_at: str = "" + updated_at: str = "" + + +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) + 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 = "", + note: str = "", + action: str = "marked", + ) -> Review: + """Insert or update one review and append an audit event.""" + 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() + 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, note, created_at, updated_at)" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", + ( + fingerprint, status, host, parameter, parameter.lower(), + location, rule, int(score), reviewer, note, 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)," + " note=?, updated_at=? WHERE fingerprint=?", + ( + status, host, parameter, parameter.lower(), location, rule, + int(score), reviewer, note, 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 = "", + note: 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, + note=note, + ) + 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 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) -> Dict[str, object]: + """Counts per status plus first/last activity.""" + 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() + ] + return { + "total": total, + "by_status": by_status, + "events": events, + "first": first, + "last": last, + "reviewers": reviewers, + } + + # -- 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"], + note=row["note"], + 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/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/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/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/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/tests/test_features_v22.py b/tests/test_features_v22.py index 335c033..09dba14 100644 --- a/tests/test_features_v22.py +++ b/tests/test_features_v22.py @@ -603,7 +603,8 @@ def test_github_annotations_escape_colons_commas_newlines(self): def test_self_test_passes(self): code, out, _err = run_inprocess("--no-banner", "-q", "--self-test") self.assertEqual(code, 0) - self.assertIn("All 10 checks passed", out) + # the menu grew in 2.3; assert the shape, not a hard-coded count + self.assertRegex(out, r"All \d+ checks passed") self.assertIn("[ok ]", out) def test_self_test_result_list(self): @@ -1320,6 +1321,9 @@ def test_safety_imports(self): "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", } for name in ( "rules", "naming", "valueshape", "policy", "ci", "watch", diff --git a/tests/test_features_v23.py b/tests/test_features_v23.py new file mode 100644 index 0000000..cad3330 --- /dev/null +++ b/tests/test_features_v23.py @@ -0,0 +1,894 @@ +"""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_2_3(self): + self.assertEqual(__version__, "2.3.0") + + +# --------------------------------------------------------------------------- +# 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.assertEqual(payload["version"], "2.3.0") + + 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_path_detector.py b/tests/test_path_detector.py index b457360..da68860 100755 --- a/tests/test_path_detector.py +++ b/tests/test_path_detector.py @@ -1146,7 +1146,8 @@ def test_imports_are_standard_library_only(self): "__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", + "base64", "copy", "hashlib", "html", "time", "math", "sqlite3", + "zipfile", "curses", "platform", "shutil", "tempfile", "textwrap", } for path in project_modules(): tree = ast.parse(path.read_text(encoding="utf-8")) From 8345abfa8b05891294a14599b1b749a05747e98d Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:58:49 +0000 Subject: [PATCH 6/8] v2.4.0: expiry, capture diff, extraction, term packs, calibration, projects Ten additions, all passive and stdlib-only: 1. Acceptance expiry -- --ledger-expire/--ledger-stale/--ledger-refresh. Ledger schema v2 (owner, expires_at) migrates v1 files in place. Expired reviews keep hiding candidates and are surfaced for re-review. 2. Capture-to-capture diff -- --diff-capture OLD.har against -i NEW.har. Reports added/removed/renamed parameters, endpoints and shape changes. Renames require a shared name token; shape-only pairing over-matched. 3. Offline extraction -- --extract page.html,app.js reads local HTML/JS and pulls fetch/axios/xhr/import/attribute URLs; nothing is fetched. Origin inference needs a majority host, and refuses a lone CDN-looking host rather than misattributing somebody's bundle. 4. Value statistics -- --value-stats length, encoding depth, separator and entropy bands. Counts and bands only; values are never printed. 5. Rule coverage -- --rule-coverage fired vs silent rules, and inert (weight 0, distinct from negative-weight demotions). 6. Term packs -- --init-terms/--list-terms/--terms. Literal terms only, no regex by design; validated versioned JSON, committable to a team repo. 7. Preset comparison -- --compare-presets, minimal/balanced/noisy over the same scored candidates. Re-classification only; nothing is re-scored. 8. Calibration -- --calibrate recommends --min-score from ledger decisions under a stated recall/false-positive rule; refuses under 8 labels. 9. Project files -- .pathscope/project.json discovered upward from the cwd, supplying config/policy/terms/ledger; unknown files are contained. 10. Reviewed-aware CI -- SARIF suppressions, JUnit , and --policy excluding reviewed findings unless --policy-include-reviewed. 514 tests (100 new, one class per feature) and --self-test 22/22. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 419 +++++++++++++- pathscope/__init__.py | 2 +- pathscope/analytics.py | 311 ++++++++++ pathscope/calibrate.py | 336 +++++++++++ pathscope/capturediff.py | 516 +++++++++++++++++ pathscope/ci.py | 108 +++- pathscope/cli.py | 572 ++++++++++++++++++- pathscope/extractor.py | 373 ++++++++++++ pathscope/ledger.py | 198 ++++++- pathscope/policy.py | 18 +- pathscope/presets.py | 163 +++++- pathscope/project.py | 299 ++++++++++ pathscope/report.py | 23 +- pathscope/termpacks.py | 258 +++++++++ pathscope/valueshape.py | 49 ++ tests/test_features_v22.py | 2 +- tests/test_features_v23.py | 8 +- tests/test_features_v24.py | 1058 +++++++++++++++++++++++++++++++++++ tests/test_path_detector.py | 1 + 19 files changed, 4681 insertions(+), 33 deletions(-) create mode 100644 pathscope/calibrate.py create mode 100644 pathscope/capturediff.py create mode 100644 pathscope/extractor.py create mode 100644 pathscope/project.py create mode 100644 pathscope/termpacks.py create mode 100644 tests/test_features_v24.py diff --git a/README.md b/README.md index cbd4d48..29f62e1 100644 --- a/README.md +++ b/README.md @@ -54,14 +54,24 @@ reviewing for path-traversal risk.** 23. [Streaming stdin](#streaming-stdin) 24. [Reproducible bundles](#reproducible-bundles) 25. [Secret scrubbing](#secret-scrubbing) -26. [Exit codes](#exit-codes) -27. [Detection rules](#detection-rules) -28. [Configuration file](#configuration-file) -29. [Tests](#tests) -30. [Project layout](#project-layout) -31. [Limitations](#limitations) -32. [FAQ](#faq) -33. [Authorization and legal](#authorization-and-legal) +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. [Exit codes](#exit-codes) +37. [Detection rules](#detection-rules) +38. [Configuration file](#configuration-file) +39. [Tests](#tests) +40. [Project layout](#project-layout) +41. [Limitations](#limitations) +42. [FAQ](#faq) +43. [Authorization and legal](#authorization-and-legal) --- @@ -306,7 +316,7 @@ Example terminal output (values hidden): ```console $ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -PathScope 2.3.0 - passive path-parameter triage +PathScope 2.4.0 - passive path-parameter triage ---------------------------------------------------------------- GitHub: https://github.com/mrdineshpathro Instagram: https://www.instagram.com/mr_dineshpatro @@ -1021,6 +1031,348 @@ is no flag that makes a bundle contain a credential. --- +## Capture-to-capture diff + +`--baseline` compares *reports*. `--diff-capture` compares **captures**, which +answers a different question: what changed about the application? + +```sh +pathscope --diff-capture monday.har -i friday.har +pathscope --diff-capture monday.har -i friday.har --diff-json > diff.json +``` + +``` +Endpoints only in the new capture (1) + GET https://new.test/api + +Endpoints only in the old capture (1) + GET https://old.test/api + +Renamed parameters (same endpoint, shared name token) (1) + GET https://a.test/view: file -> file_id [absolute-path] + +New parameters (1) + GET https://a.test/list: filter (query) + +Removed parameters (1) + GET https://a.test/list: sort (query) + +Value shape changes (values are never printed) (1) + GET https://a.test/doc: absolute-path -> uuid +``` + +Two deliberate choices: + +* **Renames require evidence.** A pair is called a rename only when the two + names share a token (`file` → `file_id`, `doc_path` → `file_path`). Pairing on + "the values look similar" produced confident nonsense (`q` → `file`), so + `file` → `document` is reported as one removal plus one addition instead. +* **Shapes, never values.** A changed value is described with the same + vocabulary as demotion (`absolute-path`, `uuid`, `traversal`, …). + +Exit code is `1` when anything differs, `0` when the captures match, which makes +it usable as a "did the surface change?" CI check. + +--- + +## Offline URL extraction + +`--extract` reads local HTML and JavaScript and pulls out the endpoints it finds +in `fetch()`, `axios`, `xhr.open`, `$.ajax`, `new URL`, `import()`, `href`, +`src`, `action` and `formaction`. + +```sh +pathscope --extract dist/app.js --extract index.html +pathscope --extract app.js --extract-host app.test # resolve relative paths +pathscope --extract app.js --extract-all-hosts # keep third parties +``` + +The files are **read, never fetched**. Extraction then hands the strings to the +normal analysis pipeline, so scoring, formats and exit codes are unchanged. + +Origin handling is deliberately conservative, because resolving a relative path +against the wrong host would invent an endpoint that does not exist: + +| Situation | Behaviour | +|---|---| +| one host dominates the files | that host is the origin | +| a single host that is not a known CDN/analytics domain | trusted as the origin | +| a single host that *looks* third-party (`cdn.`, `fonts.`, …) | **refused**, with a warning | +| several hosts, no clear winner | **refused**, with a warning | +| `--extract-host app.test` | used, no guessing | +| `--extract-all-hosts` | every absolute URL is kept | + +When the origin is refused, relative paths are dropped and the warning says how +to supply the host. `--extract` cannot be combined with `--url`/`-i`; run them +as separate analyses. + +--- + +## Value statistics + +`--value-stats` profiles the corpus without disclosing anything: + +```sh +pathscope -i capture.har --value-stats +``` + +``` +Parameters analysed : 412 +Empty values : 37 +Mean length : 23.4 chars +Longest value : 512 chars + +Value shapes + text 214 51.9% + absolute-path 71 17.2% + uuid 33 8.0% + traversal 12 2.9% + ... + +Encoding depth (percent layers) + 0 388 94.2% + 1 19 4.6% + 2 5 1.2% + +Entropy band + low 201 48.8% + medium 167 40.5% + high 44 10.7% + +This view contains counts and bands only: 0 values are disclosed. +``` + +It exists to answer "is this corpus full of encoded blobs?" before you read a +single row. Every field is a count or a band; `disclosed_values` is always `0`, +and the test suite asserts that no value from the input can appear in the +output. + +--- + +## Rule coverage + +`--rule-coverage` compares the rule book with the rules that actually fired: + +```sh +pathscope -i capture.har --rule-coverage +``` + +It lists rules that fired (with their weights), rules that stayed **silent**, +rules with weight `0` (present but unable to move a score), disabled rules, and +rule ids that appear in findings but not in the book. + +The wording matters and is printed with the report: + +> A silent rule is not a dead rule: it may simply be the rule that stayed quiet +> on this capture. Review against several corpora before pruning. + +Negative-weight rules are labelled as demotions, not as inert — they lower +scores when they match, which is a job. + +--- + +## Term packs + +A term pack is a project's custom path terms on their own, so they can be +committed and shared instead of living inside somebody's personal config. + +```sh +pathscope --init-terms acme.json # write a valid starter pack +pathscope --list-terms acme.json # validate and summarise +pathscope -i capture.har --terms acme.json +``` + +```json +{ + "pack": "acme-api", + "version": 1, + "description": "Literal path-like parameter names for the document service.", + "terms": ["attachment", "document", "receipt", "scan"], + "ignore": ["utm_source", "utm_medium"] +} +``` + +Packs are **strict**, on purpose: + +| Rejected | Why | +|---|---| +| `"file.*"`, `"/etc/passwd"` | terms are literals; no regex, no paths | +| duplicate terms | a shared file should not depend on which copy wins | +| unknown keys (`"include"`, `"rules"`) | a pack cannot pull in other files | +| wrong `version` | the format is versioned so it can change safely | +| over 200 terms or 256 KB | keeps scoring bounded and explained | + +Merge order is deterministic (config terms first, then packs in command-line +order, first occurrence wins), so the scoring trace is identical on every +machine that uses the same packs. + +--- + +## Preset comparison + +`--compare-presets` shows how the three postures classify the **same** scored +candidates: + +```sh +pathscope -i capture.har --min-score 0 --compare-presets +``` + +``` + preset threshold reports share + minimal 50 1 33.3% + balanced 25 2 66.7% + noisy 10 3 100.0% + + score minimal balance noisy candidate + 71 yes yes yes a.test query:file + 47 - yes yes a.test query:download + 22 - - yes a.test query:image + +minimal reports 1, balanced 2, noisy 3; 2 candidate(s) are shown by a looser +threshold than minimal. +Choosing a preset changes what is shown, never what is scored; the underlying +evidence is identical. +``` + +Use it to pick a threshold from evidence instead of taste. Run with +`--min-score 0` so every scored candidate is visible; otherwise the preset +thresholds filter the table itself. + +--- + +## Score calibration + +Once the ledger holds real decisions, it is a small test set. `--calibrate` +turns it into a threshold recommendation. + +```sh +pathscope --ledger reviews.db --ledger-scores # distribution by label +pathscope --ledger reviews.db --calibrate # threshold recommendation +``` + +``` +Accepted reviews : 10 +False-positive reviews: 10 + + threshold reported recall fp-rate + 40 13 100% 10% + 45 12 100% 0% <- recommended + 50 10 83% 0% + +Recommended --min-score 45: highest threshold keeping recall >= 90% with a +false-positive rate <= 20%. + At that threshold the ledger would report 12 of 20 reviewed candidate(s): + 12/12 accepted, 0/10 false-positive. +``` + +The rule is stated in the output so the number is auditable: + +1. discard thresholds that would hide more than 10% of accepted candidates, +2. among the rest pick the highest with a false-positive rate at or below 20%, +3. if none qualifies, pick the lowest false-positive rate and say so. + +With fewer than **8** labelled reviews nothing is recommended — a threshold +derived from four decisions is a guess wearing a lab coat. Rows imported from a +2.1 ledger carry no score and are excluded with a note. + +--- + +## Project files + +Drop a `.pathscope/project.json` in a repository and stop repeating flags: + +```json +{ + "project": "acme-api", + "version": 1, + "description": "Shared PathScope settings for this repository.", + "config": "pathscope.json", + "policy": "policy.json", + "terms": ["terms/paths.json", "terms/vendor.json"], + "ledger": "reviews.db" +} +``` + +```sh +pathscope --init-project . # write a starter file +pathscope --show-project # what was found and what it supplies +pathscope --no-project # ignore it for this run +``` + +Discovery walks **up** from the working directory to the first project file, so +running from `src/api/` uses the repository's settings. Paths inside the file +are resolved relative to the project directory and must stay inside it: an +absolute path or a `../..` escape is an error, not a warning. + +Precedence is simple and one-directional: + +``` +command-line flag > project file > config file > preset default +``` + +`--show-project` prints exactly which keys the project supplied and which were +overridden by the command line. Missing referenced files are reported and +ignored, so a fresh clone still runs. + +--- + +## Reviewed-aware CI + +The ledger is also the place where "we looked at this and decided" lives. Every +machine-readable output understands that decision: + +| Output | What a reviewed finding becomes | +|---|---| +| SARIF | a result with `suppressions: [{kind: external, status: accepted}]`, so GitHub code scanning stops re-alerting | +| JUnit | ``, counted in the `skipped` attribute, not `failures` | +| `--policy` | excluded from the gate (a human already decided) | +| text/JSON/CSV | `status: "reviewed"` | + +If you *do* want the gate to keep failing on reviewed findings: + +```sh +pathscope -i capture.har --ledger reviews.db --policy policy.json --policy-include-reviewed +# or, permanently: +{"max_total": 0, "fail_on_reviewed": true} +``` + +`--policy-include-reviewed` also stops the ledger from hiding those rows, so +the policy sees what it is being asked to judge. + +--- + +## Acceptance expiry + +An acceptance with no expiry quietly becomes permanent. `--ledger-expire` puts +a deadline on the decision itself: + +```sh +pathscope -i capture.har --ledger reviews.db --ledger-mark-all \ + --ledger-status accepted --ledger-expire 30d +pathscope --ledger reviews.db --ledger-stale # what has expired +pathscope --ledger reviews.db --ledger-refresh # clear expiry (audited) +``` + +| Spec | Meaning | +|---|---| +| `30d`, `12h`, `90m`, `2w`, `45s` | expires that long after the review is written | +| `none` | never expires (the default, and explicit) | + +Expired reviews **keep hiding their candidates** until you deal with them — the +point is to be reminded, not to have the finding reappear silently. Every +review also records an `owner` (from `--reviewer`), so a stale acceptance has a +name attached. + +`--ledger-refresh` clears the expiry on stale rows and writes an `extended` +event to the audit trail; nothing is deleted, so the history of "we kept +accepting this" survives. + +Ledgers written by 2.2/2.3 are migrated in place on first open: the new +`owner` and `expires_at` columns are added with neutral defaults, and the +schema version is bumped to 2. + +--- + ## Exit codes | Code | Meaning | @@ -1143,6 +1495,15 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--scrub | --no-scrub] [--bundle FILE] [--inspect-bundle FILE] [--stream] [--stream-batch N] [--stream-json] + [--diff-capture FILE] [--diff-json] + [--extract FILE] [--extract-host HOST] + [--extract-all-hosts] + [--value-stats] [--rule-coverage] + [--terms FILE] [--init-terms FILE] [--list-terms FILE] + [--compare-presets] [--calibrate] [--ledger-scores] + [--ledger-expire DURATION] [--ledger-stale] + [--ledger-refresh] [--policy-include-reviewed] + [--show-project] [--init-project DIR] [--no-project] ``` | Option | Description | @@ -1213,6 +1574,26 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] | `--stream` | Read line-oriented input from stdin with bounded memory. | | `--stream-batch N` | Analyse and report every N streamed requests (default 200). | | `--stream-json` | With `--stream`, emit one JSON object per batch. | +| `--diff-capture FILE` | Compare `-i` captures against an earlier one; exit 1 when they differ. | +| `--diff-json` | With `--diff-capture`, emit JSON instead of text. | +| `--extract FILE` | Extract endpoints from a local HTML/JS file and analyse them; repeatable. | +| `--extract-host HOST` | Resolve relative URLs from `--extract` against this host. | +| `--extract-all-hosts` | Keep endpoints on every host found in `--extract` files. | +| `--value-stats` | Length/encoding/entropy profile of values; no value is shown. | +| `--rule-coverage` | Which rules fired, stayed silent, are disabled or weigh zero. | +| `--terms FILE` | Load custom literal terms from a term pack; repeatable. | +| `--init-terms FILE` | Write a validated starter term pack and exit. | +| `--list-terms FILE` | Validate term pack(s) and print a summary, then exit. | +| `--compare-presets` | How minimal/balanced/noisy classify the same candidates. | +| `--calibrate` | Recommend `--min-score` from accepted vs false-positive reviews. | +| `--ledger-scores` | Score distribution of ledger reviews, by label. | +| `--ledger-expire DURATION` | Expiry for reviews written this run (`30d`, `12h`, `none`). | +| `--ledger-stale` | List expired reviews and exit. | +| `--ledger-refresh` | Clear the expiry on stale reviews (audited) and exit. | +| `--policy-include-reviewed` | Let `--policy` fail on findings already reviewed. | +| `--show-project` | Show the discovered project file and what it supplies, then exit. | +| `--init-project DIR` | Write `DIR/.pathscope/project.json` and exit. | +| `--no-project` | Ignore any `.pathscope/project.json` above the working directory. | | `-q, --quiet` | Suppress warnings and the stderr summary. | | `--no-color` | Disable colour on terminals. | | `--no-banner` | Suppress the startup banner. | @@ -1273,7 +1654,7 @@ python3 -m unittest discover -s tests -v python3 tests/test_path_detector.py ``` -414 tests cover exactly the behaviours this tool promises: +514 tests cover exactly the behaviours this tool promises: | Area | What is asserted | |---|---| @@ -1308,6 +1689,16 @@ python3 tests/test_path_detector.py | Bundles | layout, scrubbing, byte reproducibility, manifest roundtrip, bad zip | | Scrub | vendor prefixes, high-entropy values, name hints, stable markers, `--no-scrub` | | Packaging | `install.sh` POSIX-ness, dry run, unknown option, Dockerfile, `--doctor` | +| Acceptance expiry | unit parsing, stale/upcoming, refresh audit, v1→v2 migration in place | +| Capture diff | renames vs unrelated names, shape/location changes, JSON, exit codes | +| Extraction | fetch/axios/xhr/attributes, origin inference, CDN refusal, no-network | +| Value stats | buckets, encoding depth, zero disclosure in output | +| Rule coverage | fired/silent partition, disabled, inert vs demotion, unknown rules | +| Term packs | regex and duplicate rejection, merge order, CLI round trip | +| Preset comparison | thresholds, per-score classification, monotonic counts | +| Calibration | recall/fp bounds, thin-evidence guard, scoreless rows excluded | +| Project files | upward discovery, containment, precedence, `--no-project` | +| Reviewed CI | SARIF suppressions, JUnit ``, policy include/exclude | --- @@ -1344,12 +1735,18 @@ pathscope/ │ ├── stream.py # bounded-memory stdin analysis (--stream) │ ├── bundle.py # reproducible, scrubbed support bundles │ ├── scrub.py # credential-shaped value redaction +│ ├── capturediff.py # capture-to-capture structural diff +│ ├── extractor.py # offline URL extraction from HTML/JS +│ ├── termpacks.py # shareable literal term packs +│ ├── calibrate.py # ledger-driven score calibration +│ ├── project.py # .pathscope/project.json discovery │ └── __main__.py # enables `python3 -m pathscope` ├── tests/ │ ├── test_path_detector.py # core suite (offline) │ ├── test_features.py # end-to-end feature suite │ ├── test_features_v22.py # 2.2 regression suite -│ └── test_features_v23.py # 2.3 feature suite (one class per feature) +│ ├── test_features_v23.py # 2.3 feature suite (one class per feature) +│ └── test_features_v24.py # 2.4 feature suite (one class per feature) ├── install.sh # POSIX one-command installer ├── install.cmd # Windows installer ├── Dockerfile # slim, unprivileged, --self-test healthcheck diff --git a/pathscope/__init__.py b/pathscope/__init__.py index f405bea..4822a9c 100644 --- a/pathscope/__init__.py +++ b/pathscope/__init__.py @@ -14,7 +14,7 @@ from __future__ import annotations PROGRAM = "PathScope" -__version__ = "2.3.0" +__version__ = "2.4.0" # Displayed on every start. These are never opened and never requested. GITHUB_URL = "https://github.com/mrdineshpathro" diff --git a/pathscope/analytics.py b/pathscope/analytics.py index 83bbfe5..6cb7e75 100644 --- a/pathscope/analytics.py +++ b/pathscope/analytics.py @@ -296,3 +296,314 @@ def correlate(report: Report, requests: Sequence = ()) -> Correlation: "inventory", "percentile", ] + + +# --------------------------------------------------------------------------- +# 2.4: value statistics without disclosure +# --------------------------------------------------------------------------- +@dataclass +class ValueStats: + """A profile of parameter values that never contains a value. + + Every field is a count or a band. The distributions exist so an operator + can see "most of these are long encoded blobs" without the report + containing a single secret or path. + """ + + parameters: int = 0 + empty: int = 0 + #: label -> count, from :func:`pathscope.valueshape.shape_label`. + shapes: Dict[str, int] = field(default_factory=dict) + #: length bucket -> count ("0", "1-8", "9-24", "25-64", "65-256", "257+"). + lengths: Dict[str, int] = field(default_factory=dict) + #: encoding depth (0 = plain) -> count. + encodings: Dict[int, int] = field(default_factory=dict) + #: number of values containing "..", "/", "\" and "?" respectively. + separators: Dict[str, int] = field(default_factory=dict) + #: entropy band -> count ("low" < 3.0, "medium" 3.0-3.8, "high" > 3.8). + entropy: Dict[str, int] = field(default_factory=dict) + longest: int = 0 + mean_length: float = 0.0 + #: Parameters whose values are all empty. + always_empty: List[str] = field(default_factory=list) + + @property + def disclosed_values(self) -> int: + """Always zero: this view never carries a value.""" + return 0 + + def as_dict(self) -> Dict[str, object]: + return { + "parameters": self.parameters, + "empty": self.empty, + "shapes": dict(self.shapes), + "lengths": dict(self.lengths), + "encodings": {str(key): value for key, value in self.encodings.items()}, + "separators": dict(self.separators), + "entropy": dict(self.entropy), + "longest": self.longest, + "mean_length": round(self.mean_length, 1), + "always_empty": list(self.always_empty), + "disclosed_values": 0, + } + + +def _length_bucket(length: int) -> str: + if length == 0: + return "0" + if length <= 8: + return "1-8" + if length <= 24: + return "9-24" + if length <= 64: + return "25-64" + if length <= 256: + return "65-256" + return "257+" + + +def _entropy_band(text: str) -> str: + """Entropy band, using the same maths as secret scrubbing.""" + from .scrub import shannon_entropy + + score = shannon_entropy(text) + if score < 3.0: + return "low" + if score <= 3.8: + return "medium" + return "high" + + +def _encode_depth(text: str) -> int: + """How many percent-escape layers the value carries (0 when plain).""" + depth = 0 + probe = text + while depth < 5 and "%" in probe: + try: + from urllib.parse import unquote + + decoded = unquote(probe) + except Exception: # pragma: no cover - defensive + break + if decoded == probe: + break + probe = decoded + depth += 1 + return depth + + +def value_stats(requests: Sequence) -> ValueStats: + """Profile the *shape* of every parameter value across a corpus. + + Reads values only to classify them; nothing is stored on the result, and + :attr:`ValueStats.disclosed_values` is always zero. + """ + from .valueshape import shape_label + + stats = ValueStats() + lengths: List[int] = [] + per_parameter: Dict[str, List[str]] = {} + + for request in requests: + for parameter in getattr(request, "parameters", ()): + stats.parameters += 1 + value = parameter.value or "" + length = len(value) + lengths.append(length) + bucket = _length_bucket(length) + stats.lengths[bucket] = stats.lengths.get(bucket, 0) + 1 + if not value.strip(): + stats.empty += 1 + label = shape_label(value) + stats.shapes[label] = stats.shapes.get(label, 0) + 1 + if value: + depth = _encode_depth(value) + stats.encodings[depth] = stats.encodings.get(depth, 0) + 1 + if ".." in value: + stats.separators["dotdot"] = stats.separators.get("dotdot", 0) + 1 + if "/" in value: + stats.separators["slash"] = stats.separators.get("slash", 0) + 1 + if "\\" in value: + stats.separators["backslash"] = stats.separators.get("backslash", 0) + 1 + if "?" in value: + stats.separators["question"] = stats.separators.get("question", 0) + 1 + band = _entropy_band(value) + stats.entropy[band] = stats.entropy.get(band, 0) + 1 + key = canonical_name(parameter.name) + per_parameter.setdefault(key, []).append(value) + + if lengths: + stats.longest = max(lengths) + stats.mean_length = sum(lengths) / len(lengths) + stats.always_empty = sorted( + name for name, values in per_parameter.items() + if values and all(not value.strip() for value in values) + )[:50] + return stats + + +def render_value_stats(stats: ValueStats) -> str: + """Text view of :func:`value_stats`.""" + lines = ["PathScope value statistics (no values are shown)", "=" * 84] + lines.append(f"Parameters analysed : {stats.parameters}") + lines.append(f"Empty values : {stats.empty}") + lines.append(f"Mean length : {stats.mean_length:.1f} chars") + lines.append(f"Longest value : {stats.longest} chars") + + def table(title: str, mapping: Dict[object, int], order: Optional[Sequence] = None) -> None: + if not mapping: + return + lines.append("") + lines.append(title) + keys = list(order) if order else sorted(mapping, key=str) + for key in keys: + if key not in mapping: + continue + count = mapping[key] + share = (count / stats.parameters * 100) if stats.parameters else 0 + lines.append(f" {str(key):<16} {count:>6} {share:5.1f}%") + + table("Value shapes", stats.shapes) + table( + "Length buckets", + stats.lengths, + order=("0", "1-8", "9-24", "25-64", "65-256", "257+"), + ) + table("Encoding depth (percent layers)", stats.encodings, order=(0, 1, 2, 3, 4)) + table("Separators present", stats.separators) + table("Entropy band", stats.entropy, order=("low", "medium", "high")) + if stats.always_empty: + lines.append("") + lines.append("Parameters that are always empty") + for name in stats.always_empty[:20]: + lines.append(f" {name}") + lines.append("") + lines.append( + "This view contains counts and bands only: 0 values are disclosed." + ) + return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# 2.4: rule coverage +# --------------------------------------------------------------------------- +@dataclass +class RuleCoverage: + """Which rules fired, which never did, and what that implies.""" + + #: rule id -> number of findings it is the primary rule for. + fired: Dict[str, int] = field(default_factory=dict) + #: rule id -> number of findings it appears in (as any contributing rule). + contributed: Dict[str, int] = field(default_factory=dict) + #: Rules in the book that never contributed to any finding. + silent: List[str] = field(default_factory=list) + #: Rules in the book that are disabled for this run. + disabled: List[str] = field(default_factory=list) + #: Rules that are enabled but carry weight 0, so they cannot change a score. + inert: List[str] = field(default_factory=list) + #: Rule ids seen in findings that are not in the book (custom/legacy). + unknown: List[str] = field(default_factory=list) + #: rule id -> effective weight. + weights: Dict[str, int] = field(default_factory=dict) + #: Rules whose weight is 0: present but unable to affect a score. + zero_weight: List[str] = field(default_factory=list) + + @property + def active(self) -> int: + return len([rule for rule in self.weights if rule not in self.silent]) + + def as_dict(self) -> Dict[str, object]: + return { + "fired": dict(self.fired), + "contributed": dict(self.contributed), + "silent": list(self.silent), + "disabled": list(self.disabled), + "unknown": list(self.unknown), + "zero_weight": list(self.zero_weight), + "inert": list(self.zero_weight), + "weights": dict(self.weights), + } + + +def rule_coverage(report: Report, book=None) -> RuleCoverage: + """Compare the rule book with the rules that actually produced findings. + + "Silent" is deliberately *not* called "dead": a rule that does not fire on + today's capture may be exactly the rule doing its job. The report exists so + a rule book can be reviewed with evidence, and ``--rule-coverage`` says as + much in its footer. + """ + from .rules import DEFAULT_BOOK + + book = book or DEFAULT_BOOK + coverage = RuleCoverage( + weights=dict(book.as_dict()), + disabled=sorted(book.disabled), + ) + for finding in report.findings: + coverage.fired[finding.rule] = coverage.fired.get(finding.rule, 0) + 1 + for rule in set(finding.rules or (finding.rule,)): + coverage.contributed[rule] = coverage.contributed.get(rule, 0) + 1 + known = set(coverage.weights) + coverage.silent = sorted(rule for rule in known if rule not in coverage.contributed) + # Weight 0 means "cannot move a score". Negative weights are demotions and + # are perfectly functional, so they are not inert. + coverage.zero_weight = sorted( + rule for rule in known + if coverage.weights.get(rule, 0) == 0 and rule not in coverage.disabled + ) + coverage.unknown = sorted(set(coverage.contributed) - known) + return coverage + + +def render_rule_coverage(coverage: RuleCoverage) -> str: + """Text view of :func:`rule_coverage`.""" + total_book = len(coverage.weights) + lines = ["PathScope rule coverage", "=" * 84] + lines.append(f"Rules in the book : {total_book}") + lines.append(f"Rules that fired : {len(coverage.contributed)}") + lines.append(f"Rules silent here : {len(coverage.silent)}") + if coverage.disabled: + lines.append(f"Disabled this run : {', '.join(coverage.disabled)}") + + lines.append("") + lines.append("Fired (primary rule -> findings)") + if not coverage.fired: + lines.append(" none") + for rule in sorted(coverage.fired, key=lambda name: (-coverage.fired[name], name)): + lines.append( + f" {rule:<28} {coverage.fired[rule]:>4} " + f"(weight {coverage.weights.get(rule, '?')})" + ) + + if coverage.silent: + lines.append("") + lines.append("Silent rules (did not contribute on this input)") + for rule in coverage.silent: + weight = coverage.weights.get(rule, 0) + if rule in coverage.zero_weight: + note = " [weight 0: cannot affect a score]" + elif weight < 0: + note = " (demotion: lowers scores when it matches)" + else: + note = "" + lines.append(f" {rule:<28} weight {weight}{note}") + + if coverage.unknown: + lines.append("") + lines.append("Rules in findings but not in the book (custom or removed?)") + for rule in coverage.unknown: + lines.append(f" {rule}") + + if coverage.zero_weight: + lines.append("") + lines.append( + "Zero-weight rules cannot change any score; set a weight or disable them." + ) + + lines.append("") + lines.append( + "A silent rule is not a dead rule: it may simply be the rule that stayed" + ) + lines.append("quiet on this capture. Review against several corpora before pruning.") + return "\n".join(lines) diff --git a/pathscope/calibrate.py b/pathscope/calibrate.py new file mode 100644 index 0000000..aeb8cad --- /dev/null +++ b/pathscope/calibrate.py @@ -0,0 +1,336 @@ +"""Ledger-driven score calibration (``--calibrate``). + +A threshold is a guess until somebody has actually triaged with it. Once a +ledger holds real decisions, it also holds the evidence needed to check the +threshold: + +* every ``accepted`` review is a candidate a human decided was worth caring + about, and +* every ``false-positive`` review is a candidate a human decided was noise. + +Comparing those two labels against the scores PathScope assigned turns the +ledger into a small test set. For each candidate threshold this module reports +how many of each label would have been reported (recall of real decisions) and +how much noise would have been shown (false positives). It then recommends a +threshold with an explicit rule, stated in the output, so the number is +auditable rather than magic. + +Only scores and decisions are read. No value, host name inside the ledger, or +note text is printed by ``--calibrate`` unless ``--show-hosts`` is passed. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Tuple + +#: Score grid to evaluate. Every integer would be noise; 5-point steps plus the +#: preset thresholds give a readable table without missing a decision boundary. +DEFAULT_GRID: Tuple[int, ...] = ( + 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 90, 100, +) +#: A threshold must keep at least this share of accepted candidates. +DEFAULT_MIN_RECALL = 0.90 +#: ... and admit at most this share of false positives. +DEFAULT_MAX_FP_RATE = 0.20 +#: Below this many labelled reviews, a recommendation is not worth trusting. +MIN_LABELS = 8 + + +class CalibrationError(RuntimeError): + """Raised when there is nothing usable to calibrate with.""" + + +@dataclass +class Point: + """One candidate threshold and how it would have scored the ledger.""" + + threshold: int + reported: int + accepted_reported: int + false_positive_reported: int + accepted_total: int = 0 + false_positive_total: int = 0 + + @property + def recall(self) -> float: + return ( + self.accepted_reported / self.accepted_total + if self.accepted_total + else 0.0 + ) + + @property + def fp_rate(self) -> float: + return ( + self.false_positive_reported / self.false_positive_total + if self.false_positive_total + else 0.0 + ) + + def as_dict(self) -> Dict[str, object]: + return { + "threshold": self.threshold, + "reported": self.reported, + "recall": round(self.recall, 3), + "false_positive_rate": round(self.fp_rate, 3), + "accepted_reported": self.accepted_reported, + "false_positive_reported": self.false_positive_reported, + } + + +@dataclass +class Calibration: + """The full calibration table plus the recommendation.""" + + points: List[Point] = field(default_factory=list) + accepted_total: int = 0 + false_positive_total: int = 0 + other_total: int = 0 + #: Recommended threshold, or ``None`` when the evidence is too thin. + recommended: Optional[int] = None + #: Why that threshold was chosen, in one sentence. + reason: str = "" + #: What the ledger could not tell us. + notes: List[str] = field(default_factory=list) + scores_seen: int = 0 + + @property + def labelled(self) -> int: + return self.accepted_total + self.false_positive_total + + def best(self) -> Optional[Point]: + if self.recommended is None: + return None + for point in self.points: + if point.threshold == self.recommended: + return point + return None + + def as_dict(self) -> Dict[str, object]: + return { + "accepted": self.accepted_total, + "false_positive": self.false_positive_total, + "other": self.other_total, + "recommended": self.recommended, + "reason": self.reason, + "notes": list(self.notes), + "scores_seen": self.scores_seen, + "points": [point.as_dict() for point in self.points], + } + + +# --------------------------------------------------------------------------- +# construction +# --------------------------------------------------------------------------- +def _labels_from_ledger(ledger, threshold_filter: Optional[Sequence[str]] = None) -> Tuple[ + List[int], List[int], int, List[str] +]: + """Split ledger rows into (accepted scores, false-positive scores, other).""" + accepted: List[int] = [] + false_positives: List[int] = [] + other = 0 + notes: List[str] = [] + for review in ledger.all_reviews(): + if threshold_filter and review.status not in threshold_filter: + continue + score = int(review.score or 0) + if score <= 0: + # A 0 score almost always means the row was imported from a 2.1 + # ledger that never stored scores; it cannot calibrate anything. + notes.append( + f"{review.fingerprint}: no score recorded; excluded" + ) + continue + if review.status == "accepted": + accepted.append(score) + elif review.status == "false-positive": + false_positives.append(score) + else: + other += 1 + return accepted, false_positives, other, notes + + +def calibrate( + ledger, + *, + grid: Sequence[int] = DEFAULT_GRID, + min_recall: float = DEFAULT_MIN_RECALL, + max_fp_rate: float = DEFAULT_MAX_FP_RATE, + min_labels: int = MIN_LABELS, +) -> Calibration: + """Build the calibration table from a ledger. + + Recommendation rule (stated verbatim in the output): + + * discard thresholds that miss more than ``1 - min_recall`` of accepted + candidates (we must not hide what humans cared about), + * among the rest pick the highest threshold whose false-positive rate is at + most ``max_fp_rate``, + * if none satisfies the false-positive bound, pick the lowest + false-positive rate instead and say so. + + With fewer than ``min_labels`` labelled reviews nothing is recommended. + """ + accepted, false_positives, other, notes = _labels_from_ledger(ledger) + total = len(accepted) + len(false_positives) + result = Calibration( + accepted_total=len(accepted), + false_positive_total=len(false_positives), + other_total=other, + notes=notes, + scores_seen=total, + ) + if total == 0: + raise CalibrationError( + "the ledger has no accepted or false-positive reviews with scores; " + "triage some candidates first (--ledger-mark-all --ledger-status ...)" + ) + + points: List[Point] = [] + for threshold in sorted(set(int(value) for value in grid)): + point = Point( + threshold=threshold, + reported=sum(1 for score in accepted if score >= threshold) + + sum(1 for score in false_positives if score >= threshold), + accepted_reported=sum(1 for score in accepted if score >= threshold), + false_positive_reported=sum( + 1 for score in false_positives if score >= threshold + ), + accepted_total=len(accepted), + false_positive_total=len(false_positives), + ) + points.append(point) + result.points = points + + if total < min_labels: + result.reason = ( + f"only {total} labelled review(s); at least {min_labels} are needed " + "before a threshold is recommended" + ) + return result + + eligible = [point for point in points if point.recall >= min_recall] + if not eligible: + result.reason = ( + f"no threshold keeps {min_recall:.0%} of accepted candidates; " + "the lowest threshold is the only safe choice" + ) + result.recommended = points[0].threshold if points else None + return result + + within_fp = [point for point in eligible if point.fp_rate <= max_fp_rate] + if within_fp: + chosen = max(within_fp, key=lambda point: point.threshold) + result.recommended = chosen.threshold + result.reason = ( + f"highest threshold keeping recall >= {min_recall:.0%} with a " + f"false-positive rate <= {max_fp_rate:.0%}" + ) + else: + chosen = min(eligible, key=lambda point: (point.fp_rate, -point.threshold)) + result.recommended = chosen.threshold + result.reason = ( + f"no threshold met the {max_fp_rate:.0%} false-positive bound; " + "chose the one with the lowest false-positive rate" + ) + return result + + +# --------------------------------------------------------------------------- +# rendering +# --------------------------------------------------------------------------- +def render_calibration(calibration: Calibration, *, show_hosts: bool = False) -> str: + """Text table plus the recommendation and its justification.""" + lines = ["PathScope score calibration (from your review ledger)", "=" * 84] + lines.append(f"Accepted reviews : {calibration.accepted_total}") + lines.append(f"False-positive reviews: {calibration.false_positive_total}") + if calibration.other_total: + lines.append(f"Other statuses : {calibration.other_total}") + lines.append("") + if not calibration.points: + lines.append("No scores to evaluate.") + return "\n".join(lines) + + lines.append(" threshold reported recall fp-rate") + for point in calibration.points: + marker = " <- recommended" if point.threshold == calibration.recommended else "" + lines.append( + f" {point.threshold:>9} {point.reported:>8} " + f"{point.recall:>6.0%} {point.fp_rate:>7.0%}{marker}" + ) + lines.append("") + + if calibration.recommended is None: + lines.append(f"No recommendation: {calibration.reason}.") + else: + lines.append( + f"Recommended --min-score {calibration.recommended}: {calibration.reason}." + ) + best = calibration.best() + if best is not None: + lines.append( + f" At that threshold the ledger would report {best.reported} of " + f"{calibration.scores_seen} reviewed candidate(s): " + f"{best.accepted_reported}/{calibration.accepted_total} accepted, " + f"{best.false_positive_reported}/{calibration.false_positive_total} " + "false-positive." + ) + if calibration.recommended is not None and calibration.recommended != 25: + lines.append( + f" Current default is 25; apply with --min-score " + f"{calibration.recommended} or set it in your config." + ) + if calibration.notes: + lines.append("") + lines.append(f"Excluded ({len(calibration.notes)} row(s) without a score)") + lines.append("") + lines.append( + "Calibration reflects the decisions in your ledger, not ground truth." + ) + lines.append( + "A threshold is only as good as the reviews behind it; re-run after triage." + ) + return "\n".join(lines) + + +def render_ledger_scores(reviews: Sequence) -> str: + """``--ledger-scores``: score distribution of the ledger, label by label.""" + by_band: Dict[str, List[int]] = {"accepted": [], "false-positive": [], "other": []} + for review in reviews: + score = int(review.score or 0) + if review.status == "accepted": + by_band["accepted"].append(score) + elif review.status == "false-positive": + by_band["false-positive"].append(score) + else: + by_band["other"].append(score) + + lines = ["PathScope ledger scores", "=" * 84] + for label in ("accepted", "false-positive", "other"): + scores = sorted(by_band[label]) + if not scores: + lines.append(f" {label:<16} 0 review(s)") + continue + mean = sum(scores) / len(scores) + lines.append( + f" {label:<16} {len(scores):>3} review(s) " + f"mean {mean:5.1f} min {scores[0]:>3} max {scores[-1]:>3}" + ) + lines.append("") + lines.append("Run --calibrate to turn these scores into a threshold recommendation.") + return "\n".join(lines) + + +__all__ = [ + "Calibration", + "CalibrationError", + "DEFAULT_GRID", + "DEFAULT_MAX_FP_RATE", + "DEFAULT_MIN_RECALL", + "MIN_LABELS", + "Point", + "calibrate", + "render_calibration", + "render_ledger_scores", +] diff --git a/pathscope/capturediff.py b/pathscope/capturediff.py new file mode 100644 index 0000000..51644e9 --- /dev/null +++ b/pathscope/capturediff.py @@ -0,0 +1,516 @@ +"""Capture-to-capture diff (``--diff-capture OLD``). + +``--baseline`` compares a *report* with a previous report: it answers "which +candidates are new since last time?". That misses a very common case — the +endpoint changed shape. If ``?file=`` becomes ``?document=``, the old +fingerprint disappears and a brand-new one appears, so a report diff reports +"1 new, 1 resolved" when what actually happened is "the parameter was renamed". + +This module compares the **captures themselves** at the request level: + +* endpoints added, removed, and unchanged, +* parameters added, removed, and **renamed** (same endpoint, a shared name + token, optionally confirmed by a matching value shape), +* locations that moved (a query parameter that became a form field), +* value *shape* changes for a parameter that still exists (e.g. ``/a/b`` to a + UUID) — reported as a shape description, never the value. + +Everything is computed from what the operator supplied. Nothing is fetched, +resolved, or replayed, and renamed-pair detection never prints a value: it +compares value shape descriptors only. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional, Sequence, Tuple + +from .detector import fingerprint +from .sources import Request, canonical +from .textutil import decode_forms, sanitize_text +from .valueshape import shape_label + +#: How many renames to offer for one endpoint before giving up (cheap guard). +MAX_RENAME_SCAN = 40 +#: Maximum rows printed per section by the renderer. +MAX_ROWS = 60 + + +class CaptureDiffError(RuntimeError): + """Raised when the two captures cannot be compared.""" + + +@dataclass(frozen=True) +class Endpoint: + """An endpoint identity: host + path, without the query string.""" + + host: str + resource: str + method: str = "GET" + + @property + def key(self) -> str: + return f"{self.method} {self.resource}" + + def __str__(self) -> str: + return self.key + + +@dataclass +class ParameterChange: + """One parameter that differs between the two captures.""" + + parameter: str + location: str + kind: str # added | removed | renamed | shape | location + endpoint: Endpoint + previous: str = "" # old parameter name (renames) + shape_before: str = "" + shape_after: str = "" + + def describe(self) -> str: + if self.kind == "renamed": + return f"{self.previous} -> {self.parameter}" + if self.kind == "shape": + return f"{self.parameter}: {self.shape_before} -> {self.shape_after}" + if self.kind == "location": + return f"{self.parameter}: {self.shape_before} -> {self.location}" + return self.parameter + + +@dataclass +class CaptureDiff: + """The complete comparison between two captures.""" + + #: Endpoints that gained at least one parameter. + new_endpoints: List[Endpoint] = field(default_factory=list) + #: Endpoints present before and gone now. + removed_endpoints: List[Endpoint] = field(default_factory=list) + #: Endpoint count unchanged and no parameter changes. + unchanged_endpoints: int = 0 + changes: List[ParameterChange] = field(default_factory=list) + + @property + def added(self) -> List[ParameterChange]: + return [change for change in self.changes if change.kind == "added"] + + @property + def removed(self) -> List[ParameterChange]: + return [change for change in self.changes if change.kind == "removed"] + + @property + def renamed(self) -> List[ParameterChange]: + return [change for change in self.changes if change.kind == "renamed"] + + @property + def reshaped(self) -> List[ParameterChange]: + return [change for change in self.changes if change.kind == "shape"] + + @property + def moved(self) -> List[ParameterChange]: + return [change for change in self.changes if change.kind == "location"] + + @property + def has_differences(self) -> bool: + return bool( + self.new_endpoints + or self.removed_endpoints + or self.changes + ) + + def as_dict(self) -> Dict[str, object]: + return { + "new_endpoints": [str(endpoint) for endpoint in self.new_endpoints], + "removed_endpoints": [str(endpoint) for endpoint in self.removed_endpoints], + "unchanged_endpoints": self.unchanged_endpoints, + "added": [self._entry(change) for change in self.added], + "removed": [self._entry(change) for change in self.removed], + "renamed": [self._entry(change) for change in self.renamed], + "reshaped": [self._entry(change) for change in self.reshaped], + "moved": [self._entry(change) for change in self.moved], + } + + @staticmethod + def _entry(change: ParameterChange) -> Dict[str, object]: + return { + "endpoint": str(change.endpoint), + "parameter": change.parameter, + "previous": change.previous, + "location": change.location, + "kind": change.kind, + "shape_before": change.shape_before, + "shape_after": change.shape_after, + } + + +# --------------------------------------------------------------------------- +# capture model +# --------------------------------------------------------------------------- +def _endpoint_of(request: Request) -> Endpoint: + return Endpoint( + host=request.url.host.lower(), + resource=request.url.display_resource, + method=(request.method or "GET").upper(), + ) + + +def _shape_of(value: str) -> str: + """Describe a value's shape without disclosing it. + + The descriptor is the vocabulary ``valueshape`` already uses for demotion + (``uuid``, ``hash``, ``absolute-path``, ``scalar`` ...), so the diff reads + the same way everywhere else in PathScope. + """ + text = value or "" + # Values arrive percent-encoded; compare the decoded shape. + try: + text = decode_forms(text, 2)[-1][1] + except Exception: # pragma: no cover - malformed escapes + text = text + return shape_label(text) + + +@dataclass +class _Capture: + """Indexed view of one capture.""" + + parameters: Dict[Endpoint, Dict[Tuple[str, str], str]] + order: List[Endpoint] + + def keys(self, endpoint: Endpoint) -> Dict[Tuple[str, str], str]: + return self.parameters.get(endpoint, {}) + + +def _index(requests: Iterable[Request]) -> _Capture: + parameters: Dict[Endpoint, Dict[Tuple[str, str], str]] = {} + order: List[Endpoint] = [] + for request in requests: + endpoint = _endpoint_of(request) + if endpoint not in parameters: + parameters[endpoint] = {} + order.append(endpoint) + table = parameters[endpoint] + for parameter in request.parameters: + name = canonical(parameter.name) + key = (name, parameter.location) + # Keep the first non-empty value seen: enough for a shape compare, + # and stable regardless of capture ordering. + if key not in table or (not table[key] and parameter.value): + table[key] = parameter.value or "" + return _Capture(parameters=parameters, order=order) + + +# --------------------------------------------------------------------------- +# comparison +# --------------------------------------------------------------------------- +def _value_is_empty(value: str) -> bool: + return not (value or "").strip() + + +def _similar_shapes(left: str, right: str) -> bool: + """True when two value shapes are close enough to suggest a rename.""" + if not left or not right: + return False + if left == right: + return True + families = ( + {"absolute-path", "traversal", "windows-path", "path-like", "text"}, + {"uuid", "hash", "base64", "jwt"}, + {"scalar", "boolean", "number"}, + ) + for family in families: + if left in family and right in family: + return True + return False + + +def _detect_renames( + gone: List[Tuple[str, str]], + arrived: List[Tuple[str, str]], + before: Dict[Tuple[str, str], str], + after: Dict[Tuple[str, str], str], +) -> Dict[Tuple[str, str], Tuple[str, str]]: + """Pair removed and added names on the same endpoint that look renamed. + + A pair is a rename only when the two names **share a token**, optionally + confirmed by a matching value shape. Sharing a token is the part that has + evidence behind it (``file`` -> ``file_id``, ``doc_path`` -> ``file_path``); + "the values happen to look alike" is not, and pairing on shape alone + produced confident nonsense like ``q`` -> ``file`` and ``page`` -> ``offset``. + + ``file`` -> ``document`` is therefore *not* reported as a rename: the two + names have nothing in common, and guessing would be worse than saying + "one parameter went, another arrived". + """ + pairs: Dict[Tuple[str, str], Tuple[str, str]] = {} + if not gone or not arrived or len(gone) * len(arrived) > MAX_RENAME_SCAN ** 2: + return pairs + + from .heuristics import tokenize_name + + def tokens(name: str) -> set: + try: + return {token for token in tokenize_name(name) if token} + except Exception: # pragma: no cover - defensive + return {name} + + used: set = set() + for old_key in gone: + old_name, old_location = old_key + old_shape = _shape_of(before.get(old_key, "")) + best: Optional[Tuple[int, Tuple[str, str]]] = None + for new_key in arrived: + if new_key in used: + continue + new_name, new_location = new_key + if new_location != old_location: + continue + shared = tokens(old_name) & tokens(new_name) + if not shared: + continue + score = 2 + len(shared) + if _similar_shapes(old_shape, _shape_of(after.get(new_key, ""))): + score += 2 + if best is None or score > best[0]: + best = (score, new_key) + if best is not None: + used.add(best[1]) + pairs[old_key] = best[1] + return pairs + + +def compare(old: Sequence[Request], new: Sequence[Request]) -> CaptureDiff: + """Compare two captures and return the structural differences.""" + if not old and not new: + raise CaptureDiffError("both captures are empty; nothing to compare") + before = _index(old) + after = _index(new) + diff = CaptureDiff() + + before_keys = set(before.parameters) + after_keys = set(after.parameters) + + diff.removed_endpoints = sorted( + before_keys - after_keys, key=lambda endpoint: (endpoint.host, endpoint.resource) + ) + diff.new_endpoints = sorted( + after_keys - before_keys, key=lambda endpoint: (endpoint.host, endpoint.resource) + ) + + for endpoint in sorted(before_keys & after_keys, key=str): + changes_before = len(diff.changes) + old_params = before.keys(endpoint) + new_params = after.keys(endpoint) + gone = sorted(set(old_params) - set(new_params)) + arrived = sorted(set(new_params) - set(old_params)) + unchanged = set(old_params) & set(new_params) + + renames = _detect_renames(gone, arrived, old_params, new_params) + renamed_old = set(renames) + renamed_new = set(renames.values()) + + for old_key, new_key in sorted(renames.items()): + diff.changes.append( + ParameterChange( + parameter=new_key[0], + location=new_key[1], + kind="renamed", + endpoint=endpoint, + previous=old_key[0], + shape_before=_shape_of(old_params.get(old_key, "")), + shape_after=_shape_of(new_params.get(new_key, "")), + ) + ) + + for key in gone: + if key in renamed_old: + continue + # A location move (query -> body) with the same name is its own kind. + moved = [ + other for other in arrived + if other[0] == key[0] and other not in renamed_new + ] + if moved: + renamed_new.add(moved[0]) + diff.changes.append( + ParameterChange( + parameter=key[0], + location=moved[0][1], + kind="location", + endpoint=endpoint, + shape_before=key[1], + shape_after=moved[0][1], + ) + ) + continue + diff.changes.append( + ParameterChange( + parameter=key[0], + location=key[1], + kind="removed", + endpoint=endpoint, + shape_before=_shape_of(old_params.get(key, "")), + ) + ) + + for key in arrived: + if key in renamed_new: + continue + diff.changes.append( + ParameterChange( + parameter=key[0], + location=key[1], + kind="added", + endpoint=endpoint, + shape_after=_shape_of(new_params.get(key, "")), + ) + ) + + for key in sorted(unchanged): + old_shape = _shape_of(old_params.get(key, "")) + new_shape = _shape_of(new_params.get(key, "")) + if _value_is_empty(old_params.get(key, "")) or _value_is_empty( + new_params.get(key, "") + ): + continue + if old_shape and new_shape and old_shape != new_shape: + diff.changes.append( + ParameterChange( + parameter=key[0], + location=key[1], + kind="shape", + endpoint=endpoint, + shape_before=old_shape, + shape_after=new_shape, + ) + ) + + if len(diff.changes) == changes_before: + diff.unchanged_endpoints += 1 + + diff.changes.sort(key=lambda change: (str(change.endpoint), change.kind, change.parameter)) + return diff + + +# --------------------------------------------------------------------------- +# rendering +# --------------------------------------------------------------------------- +def render_diff(diff: CaptureDiff, *, old_label: str = "old", new_label: str = "new") -> str: + """Human-readable diff, values replaced by shape descriptors.""" + lines = ["PathScope capture diff", "=" * 84] + lines.append(f" before: {sanitize_text(old_label)}") + lines.append(f" after : {sanitize_text(new_label)}") + lines.append("") + if not diff.has_differences: + lines.append("No structural differences: both captures expose the same endpoints") + lines.append("and parameters.") + return "\n".join(lines) + + def section(title: str, rows: Iterable[str], empty: str = "") -> None: + rows = list(rows) + lines.append(f"{title} ({len(rows)})") + if not rows: + lines.append(f" {empty or 'none'}") + for row in rows[:MAX_ROWS]: + lines.append(f" {row}") + if len(rows) > MAX_ROWS: + lines.append(f" ... {len(rows) - MAX_ROWS} more") + lines.append("") + + section( + "Endpoints only in the new capture", + [str(endpoint) for endpoint in diff.new_endpoints], + ) + section( + "Endpoints only in the old capture", + [str(endpoint) for endpoint in diff.removed_endpoints], + ) + section( + "Renamed parameters (same endpoint, shared name token)", + [ + f"{change.endpoint}: {change.describe()}" + + (f" [{change.shape_before}]" if change.shape_before else "") + for change in diff.renamed + ], + ) + section( + "New parameters", + [f"{change.endpoint}: {change.parameter} ({change.location})" for change in diff.added], + ) + section( + "Removed parameters", + [f"{change.endpoint}: {change.parameter} ({change.location})" for change in diff.removed], + ) + section( + "Location changes (query/body/form)", + [f"{change.endpoint}: {change.describe()}" for change in diff.moved], + ) + section( + "Value shape changes (values are never printed)", + [f"{change.endpoint}: {change.describe()}" for change in diff.reshaped], + ) + lines.append(f"Unchanged endpoints: {diff.unchanged_endpoints}") + lines.append("") + lines.append("Candidates for manual review only; no requests were sent.") + return "\n".join(lines) + + +def diff_to_findings(diff: CaptureDiff) -> List[Dict[str, object]]: + """Convert renames and additions into finding-shaped dicts. + + Used by ``--diff-capture`` with ``--format json`` so the diff can feed the + same pipelines as a normal report. Scores are deliberately constant and low: + a structural change is a *review prompt*, not evidence of a problem. + """ + entries: List[Dict[str, object]] = [] + for change in diff.renamed: + entries.append( + { + "kind": "renamed", + "endpoint": str(change.endpoint), + "host": change.endpoint.host, + "parameter": change.parameter, + "previous": change.previous, + "location": change.location, + "shape_before": change.shape_before, + "shape_after": change.shape_after, + "fingerprint": fingerprint( + change.endpoint.host, + change.location, + change.parameter, + "capture-renamed", + change.endpoint.resource, + ), + } + ) + for change in diff.added: + entries.append( + { + "kind": "added", + "endpoint": str(change.endpoint), + "host": change.endpoint.host, + "parameter": change.parameter, + "location": change.location, + "shape_after": change.shape_after, + "fingerprint": fingerprint( + change.endpoint.host, + change.location, + change.parameter, + "capture-added", + change.endpoint.resource, + ), + } + ) + return entries + + +__all__ = [ + "CaptureDiff", + "CaptureDiffError", + "Endpoint", + "MAX_ROWS", + "ParameterChange", + "compare", + "diff_to_findings", + "render_diff", +] diff --git a/pathscope/ci.py b/pathscope/ci.py index c91fa34..035817d 100644 --- a/pathscope/ci.py +++ b/pathscope/ci.py @@ -39,7 +39,10 @@ def _attr(value: object) -> str: def render_junit(report: Report, suite_name: str = "PathScope") -> str: """Return a JUnit XML document describing this run.""" - counts = report.confidence_counts + counts = {"high": 0, "medium": 0, "low": 0} + for finding in report.findings: + if finding.status != "reviewed": + counts[finding.confidence] = counts.get(finding.confidence, 0) + 1 failures = 0 cases: List[str] = [] @@ -66,12 +69,25 @@ def render_junit(report: Report, suite_name: str = "PathScope") -> str: f'name={_attr(band)}/>' ) + skipped = 0 for finding in report.findings: name = f"{finding.host} {finding.location}:{finding.parameter}" message = ( f"score {finding.score}/100, rule {finding.rule}, " f"fingerprint {finding.fingerprint}" ) + if finding.status == "reviewed": + # CI should not re-alert on a decision a human already made; the + # case is kept visible as so the audit trail survives. + skipped += 1 + inner = ( + f"" + ) + cases.append( + f' {inner}" + ) + continue inner = ( f"" + xml_escape("\n".join(finding.reasons) or DISCLAIMER) @@ -92,7 +108,7 @@ def render_junit(report: Report, suite_name: str = "PathScope") -> str: '', f'', f' ', f" " f'' @@ -337,6 +353,88 @@ def history_tracks_trends() -> None: 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) + return [ ("banner strings are exact", banner_exact), ("URLs are parsed locally", url_parse), @@ -354,6 +452,12 @@ def history_tracks_trends() -> None: ("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), ] diff --git a/pathscope/cli.py b/pathscope/cli.py index 342cb89..ca13d70 100644 --- a/pathscope/cli.py +++ b/pathscope/cli.py @@ -33,6 +33,8 @@ describe_presets, resolve_preset, ) +from . import presets as presets_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 @@ -79,6 +81,11 @@ 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, @@ -555,6 +562,115 @@ def build_parser() -> argparse.ArgumentParser: 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", + ) return parser @@ -1054,12 +1170,60 @@ def run( 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.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: @@ -1170,9 +1334,15 @@ def run( 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() @@ -1233,9 +1403,28 @@ def run( 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. - if ledger_store is not None and not args.show_known and not args.tui: + # 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 @@ -1278,6 +1467,30 @@ def run( 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, + ) if args.save_report: try: @@ -1375,6 +1588,8 @@ def run( 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) @@ -1467,6 +1682,8 @@ def _save(fingerprints): # -- 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) @@ -1813,3 +2030,354 @@ def emit(batch_number, cumulative): 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_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/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/ledger.py b/pathscope/ledger.py index a9989da..6d19583 100644 --- a/pathscope/ledger.py +++ b/pathscope/ledger.py @@ -16,7 +16,9 @@ from __future__ import annotations +import calendar import os +import re import sqlite3 import time from dataclasses import dataclass @@ -24,7 +26,7 @@ from .detector import Finding -SCHEMA_VERSION = 1 +SCHEMA_VERSION = 2 #: Review statuses accepted on the command line. STATUS_REVIEWED = "reviewed" @@ -51,7 +53,9 @@ 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 ); @@ -80,6 +84,60 @@ def _now() -> str: 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.""" @@ -93,10 +151,60 @@ class Review: 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.""" @@ -116,6 +224,7 @@ def connect(self) -> sqlite3.Connection: 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),), @@ -154,10 +263,16 @@ def record( 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.""" + """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)})" @@ -166,6 +281,7 @@ def record( 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,) @@ -173,11 +289,13 @@ def record( if existing is None: connection.execute( "INSERT INTO reviews(fingerprint, status, host, parameter, leaf," - " location, rule, score, reviewer, note, created_at, updated_at)" - " VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", + " location, rule, score, reviewer, owner, note, expires_at," + " created_at, updated_at)" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", ( fingerprint, status, host, parameter, parameter.lower(), - location, rule, int(score), reviewer, note, now, now, + location, rule, int(score), reviewer, owner, note, + expires_at, now, now, ), ) action = "marked" @@ -189,10 +307,13 @@ def record( " location=COALESCE(NULLIF(?, ''), location)," " rule=COALESCE(NULLIF(?, ''), rule)," " score=?, reviewer=COALESCE(NULLIF(?, ''), reviewer)," - " note=?, updated_at=? WHERE fingerprint=?", + " 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, note, now, fingerprint, + int(score), reviewer, owner, note, expires_at, now, + fingerprint, ), ) connection.execute( @@ -213,7 +334,9 @@ def record_findings( *, 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 @@ -227,7 +350,9 @@ def record_findings( rule=finding.rule, score=finding.score, reviewer=reviewer, + owner=owner, note=note, + expire=expire, ) count += 1 return count @@ -302,6 +427,49 @@ def fingerprints(self) -> set: 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() @@ -326,8 +494,8 @@ def events(self, fingerprint: str = "", limit: int = 50) -> List[Dict[str, objec ).fetchall() return [dict(row) for row in rows] - def stats(self) -> Dict[str, object]: - """Counts per status plus first/last activity.""" + 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"] @@ -350,6 +518,14 @@ def stats(self) -> Dict[str, object]: " 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, @@ -357,6 +533,8 @@ def stats(self) -> Dict[str, object]: "first": first, "last": last, "reviewers": reviewers, + "with_expiry": with_expiry, + "stale": stale, } # -- interoperability ------------------------------------------------ @@ -409,7 +587,9 @@ def _row_to_review(row: sqlite3.Row) -> Review: 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"], ) diff --git a/pathscope/policy.py b/pathscope/policy.py index 0193dc7..8f810cf 100644 --- a/pathscope/policy.py +++ b/pathscope/policy.py @@ -37,6 +37,7 @@ "max_total", "min_score", "fail_on_known", + "fail_on_reviewed", "ignore_rules", "ignore_hosts", "description", @@ -59,6 +60,9 @@ class Policy: 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 = "" @@ -93,6 +97,10 @@ def from_payload(cls, payload: object, source: str = "") -> "Policy": 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] @@ -163,6 +171,10 @@ def _eligible(finding: Finding, policy: Policy) -> bool: 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 return True @@ -172,7 +184,11 @@ def evaluate(report: Report, policy: Policy) -> PolicyResult: ignored = 0 for finding in report.findings: if not _eligible(finding, policy): - if finding.status != "known" and policy.min_score and finding.score < policy.min_score: + 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 diff --git a/pathscope/presets.py b/pathscope/presets.py index 4df4013..0a5d894 100644 --- a/pathscope/presets.py +++ b/pathscope/presets.py @@ -10,8 +10,8 @@ from __future__ import annotations -from dataclasses import dataclass, replace -from typing import Dict, Tuple +from dataclasses import dataclass, field, replace +from typing import Dict, List, Tuple from .config import Config @@ -22,6 +22,9 @@ 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: @@ -133,3 +136,159 @@ def describe_presets() -> Tuple[str, ...]: 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/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/report.py b/pathscope/report.py index bb1b5e9..57f9961 100644 --- a/pathscope/report.py +++ b/pathscope/report.py @@ -339,7 +339,27 @@ def render_sarif(report: Report) -> str: "partialFingerprints": { "pathscope/v1": finding.fingerprint, }, - "baselineState": "unchanged" if finding.status == "known" else "new", + "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": { @@ -374,6 +394,7 @@ def render_sarif(report: Report) -> str: "valueIncluded": report.show_values, "fingerprint": finding.fingerprint, "status": finding.status, + "reviewed": finding.status == "reviewed", }, } ) 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/valueshape.py b/pathscope/valueshape.py index 393918a..0cf2f9b 100644 --- a/pathscope/valueshape.py +++ b/pathscope/valueshape.py @@ -46,6 +46,8 @@ #: 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. @@ -193,3 +195,50 @@ def describe_shapes() -> Tuple[str, ...]: "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/tests/test_features_v22.py b/tests/test_features_v22.py index 09dba14..49defd4 100644 --- a/tests/test_features_v22.py +++ b/tests/test_features_v22.py @@ -1323,7 +1323,7 @@ def test_safety_imports(self): "pathlib", "textwrap", "copy", "datetime", "__future__", # 2.3 additions "math", "sqlite3", "zipfile", "curses", "platform", "shutil", - "tempfile", + "tempfile", "calendar", } for name in ( "rules", "naming", "valueshape", "policy", "ci", "watch", diff --git a/tests/test_features_v23.py b/tests/test_features_v23.py index cad3330..1022474 100644 --- a/tests/test_features_v23.py +++ b/tests/test_features_v23.py @@ -413,8 +413,10 @@ def test_self_test_covers_the_new_features(self): self.assertIn("streaming is batched and bounded", names) self.assertTrue(all(entry["passed"] for entry in results)) - def test_version_is_2_3(self): - self.assertEqual(__version__, "2.3.0") + def test_version_is_at_least_2_3(self): + major, minor, *_ = __version__.split(".") + self.assertEqual(major, "2") + self.assertGreaterEqual(int(minor), 3) # --------------------------------------------------------------------------- @@ -869,7 +871,7 @@ def test_json_output_is_unchanged_by_scrub(self): self.assertEqual(code, cli.EXIT_OK) payload = json.loads(out) self.assertEqual(payload["tool"], "PathScope") - self.assertEqual(payload["version"], "2.3.0") + self.assertTrue(payload["version"].startswith("2.")) def test_banner_links_still_verbatim(self): _code, _out, err = run_cli(["--url", URLS[0]]) diff --git a/tests/test_features_v24.py b/tests/test_features_v24.py new file mode 100644 index 0000000..0c541d1 --- /dev/null +++ b/tests/test_features_v24.py @@ -0,0 +1,1058 @@ +"""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) + self.assertEqual(payload["version"], "2.4.0") + 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(" Date: Sun, 29 Nov 2026 12:09:44 +0000 Subject: [PATCH 7/8] v2.5.0: path families, review queue, scope, sampling, spec diff, sharing Ten additions, all passive and stdlib-only (no network module is imported): 1. Path families -- --cluster groups candidates by route shape (/api/v1/items/{id}/view). A view, never a merge: every row keeps its fingerprint, so a review still covers one endpoint. 2. Review queue -- --queue orders open work by score, novelty and leverage (how many endpoints one decision covers), with the weights printed. 3. Policy shadow mode -- --policy-shadow evaluates a proposed gate, reports WOULD FAIL, and never changes the exit code or filters the report. 4. Deterministic sampling -- --sample/--sample-seed/--sample-by. SHA-256 ranked, stratified, stable under capture growth, blind to values. 5. Scope files -- --scope-file/--init-scope. Applied before analysis; a wildcard never crosses a dot, out_of_scope wins, and a file that declares no patterns is refused rather than treated as "everything". 6. API description matching -- --openapi compares findings against a local OpenAPI/Swagger JSON document: undocumented endpoints and undeclared parameters. YAML is refused with a reason instead of half-parsed. 7. Work-item export -- --export-ticket writes per-family Markdown tickets and an index. Values are never included, even with --show-values. 8. PR comments -- --pr-comment/--run-id. Marker line for in-place updates, a verdict that follows the report rather than the caller, budgeted rows. 9. Host redaction -- --redact-hosts. Keyed HMAC pseudonyms across every output and artefact; paths and fingerprints are deliberately untouched. 10. Shell completion -- --completion bash|zsh|fish|powershell, generated from the real parser so it cannot drift. 636 tests (122 new, one class per feature) and --self-test 29/29. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 377 +++++++++++- pathscope/__init__.py | 2 +- pathscope/ci.py | 90 +++ pathscope/cli.py | 358 ++++++++++++ pathscope/completion.py | 275 +++++++++ pathscope/detector.py | 2 + pathscope/families.py | 252 ++++++++ pathscope/openapi.py | 487 ++++++++++++++++ pathscope/prcomment.py | 222 +++++++ pathscope/queue.py | 228 ++++++++ pathscope/redact.py | 233 ++++++++ pathscope/sampling.py | 215 +++++++ pathscope/scope.py | 255 ++++++++ pathscope/shadow.py | 149 +++++ pathscope/tickets.py | 269 +++++++++ tests/test_features_v22.py | 2 +- tests/test_features_v24.py | 9 +- tests/test_features_v25.py | 1089 +++++++++++++++++++++++++++++++++++ tests/test_path_detector.py | 2 +- 19 files changed, 4499 insertions(+), 17 deletions(-) create mode 100644 pathscope/completion.py create mode 100644 pathscope/families.py create mode 100644 pathscope/openapi.py create mode 100644 pathscope/prcomment.py create mode 100644 pathscope/queue.py create mode 100644 pathscope/redact.py create mode 100644 pathscope/sampling.py create mode 100644 pathscope/scope.py create mode 100644 pathscope/shadow.py create mode 100644 pathscope/tickets.py create mode 100644 tests/test_features_v25.py diff --git a/README.md b/README.md index 29f62e1..8919c94 100644 --- a/README.md +++ b/README.md @@ -64,14 +64,24 @@ reviewing for path-traversal risk.** 33. [Project files](#project-files) 34. [Reviewed-aware CI](#reviewed-aware-ci) 35. [Acceptance expiry](#acceptance-expiry) -36. [Exit codes](#exit-codes) -37. [Detection rules](#detection-rules) -38. [Configuration file](#configuration-file) -39. [Tests](#tests) -40. [Project layout](#project-layout) -41. [Limitations](#limitations) -42. [FAQ](#faq) -43. [Authorization and legal](#authorization-and-legal) +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. [Exit codes](#exit-codes) +47. [Detection rules](#detection-rules) +48. [Configuration file](#configuration-file) +49. [Tests](#tests) +50. [Project layout](#project-layout) +51. [Limitations](#limitations) +52. [FAQ](#faq) +53. [Authorization and legal](#authorization-and-legal) --- @@ -316,7 +326,7 @@ Example terminal output (values hidden): ```console $ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -PathScope 2.4.0 - passive path-parameter triage +PathScope 2.5.0 - passive path-parameter triage ---------------------------------------------------------------- GitHub: https://github.com/mrdineshpathro Instagram: https://www.instagram.com/mr_dineshpatro @@ -1373,6 +1383,296 @@ schema version is bumped to 2. --- +## Path families + +Two hundred candidates are rarely two hundred decisions. `--cluster` groups +them into **route shapes**, so you review the pattern once: + +```sh +pathscope -i capture.har --cluster +``` + +``` +4 candidate(s) collapsed into 4 family/families. + + # score conf rows family + 1 73 high 1 a.test/view [query] file + 2 53 medium 1 a.test/items/{id}/view [query] image + 3 53 medium 1 b.test/list [query] template +``` + +Identifier-looking path segments become `{id}`. Version prefixes are **kept**, +because `v2` is a different surface and hiding it would defeat the purpose. + +A family is a **view, not a merge**. Every row keeps its own fingerprint, and a +review still covers one endpoint. That is deliberate: collapsing fingerprints +would let one acceptance silently cover endpoints nobody looked at. + +Note that with the default `--dedupe-by path`, three URLs that differ only by +an identifier already collapse into one finding with `occurrences: 3` before +clustering runs. Use `--dedupe-by none` to keep them as separate rows. + +--- + +## Review queue + +`--queue` answers a different question from "what scored highest": *what should +I look at next?* It only contains work that is still open, and it accounts for +how much a single decision covers. + +```sh +pathscope -i capture.har --ledger reviews.db --queue --queue-limit 10 +``` + +``` + 1. [ 73] a.test/view [query] file (high, 1 row(s)) + priority 0.85 open -- score 73/100, seen 3 time(s), high-confidence evidence + 2. [ 53] b.test/list [query] template (medium, 1 row(s)) + priority 0.55 open -- score 53/100, primary rule name-exact + +Ordering = 0.55*score + 0.30*leverage + 0.15*confidence. +``` + +* **Novelty** — known and already-reviewed rows are excluded; `--queue-all` + puts them back. +* **Leverage** — how many endpoints one decision covers (family size, or the + occurrence count after dedupe). +* **Confidence** — high-confidence evidence ranks above low at equal score. + +The weights are printed with the queue so the ordering is auditable. The queue +only orders work; it never records a decision. + +--- + +## Scope files + +A scan is only meaningful inside a boundary somebody wrote down. `--scope-file` +declares it, and it is applied **before analysis**, so out-of-scope requests +never become findings: + +```sh +pathscope --init-scope scope.json # starter file +pathscope -i capture.har --scope-file scope.json +``` + +```json +{ + "scope": "acme-api assessment", + "version": 1, + "in_scope": ["api.acme.test", "*.acme.test", "acme.test/app/*"], + "out_of_scope": ["legacy.acme.test", "*.vendor.test"] +} +``` + +| Pattern | Matches | +|---|---| +| `api.acme.test` | that host exactly | +| `*.acme.test` | one label only (`api.` yes, `deep.api.` **no**) | +| `**.acme.test` | any number of labels | +| `acme.test/app/*` | that host, one path segment | + +Rules that matter: + +* a pattern containing `/` matches `host/path`, otherwise it matches the host; +* `out_of_scope` always wins — doubt resolves to exclusion; +* an empty `in_scope` means "everything not explicitly excluded"; +* a file with **neither** list is rejected, because an empty scope that + silently means "everything" is the one typo this must not allow; +* whitelisting is refused for URLs: write `a.test`, not `https://a.test`. + +Dropped requests are always counted out loud, even under `--quiet`, and a +scope that drops everything says so instead of reporting "no input". + +A scope file records **intent**, not permission. Holding one authorises +nothing; see [Authorization and legal](#authorization-and-legal). + +--- + +## Deterministic sampling + +Large captures take time and produce reports nobody reads. `--sample` analyses +a subset — and the same subset every time: + +```sh +pathscope -i huge.har --sample 500 --sample-seed 7 +# pathscope: sampled 500 of 41230 request(s) (1.2%) with seed 7 across 12 stratum/strata +``` + +Why it is trustworthy: + +* **Reproducible** — selection is SHA-256 over `seed + request identity`, not + Python's `hash()`, whose value changes per process. +* **Stratified** — proportional to host (default), `--sample-by source`, or + `--sample-by none`. Every non-empty stratum gets at least one slot when the + budget allows, because a rare host is exactly the one worth looking at. +* **Stable** — sampling by hash means adding entries to a capture does not + reshuffle the entries already chosen. +* **Blind to values** — the sampling key excludes parameter values and scores, + so the data cannot steer the sampler. + +The seed and coverage always appear on stderr, so a sampled run can never be +mistaken for a complete one. + +--- + +## API description matching + +If the repository already contains an OpenAPI or Swagger document, `--openapi` +compares the report against it: + +```sh +pathscope -i capture.har --openapi api/openapi.json +``` + +``` +spec : Acme 1.0 [openapi] from api/openapi.json +operations: 2 described +coverage : 3 finding(s) on described endpoints, 1 on undocumented ones (75.0% described) + +Undocumented endpoints (1) + GET b.test/list [query] template (score 53) + +Parameters the spec does not declare (1) + GET /view download [query] (score 53) +``` + +Two different questions, both useful: an endpoint nobody documented is where +undocumented behaviour lives, and a parameter the spec forgot is what the code +reads anyway. + +`server`/`basePath` prefixes are applied, `{name}` templates match one segment, +and request-body properties count as declared parameters. **JSON only** — a +YAML document is refused with an explanation rather than half-parsed, because a +partial parse of an API description produces confident nonsense. + +--- + +## Policy shadow mode + +Adopting a policy is usually a one-way door: the first red build teaches +everyone to add an exception. Shadow mode reports what a *proposed* policy would +do without letting it fail anything: + +```sh +pathscope -i capture.har --policy current.json --policy-shadow proposed.json +``` + +``` +active: current.json + verdict : would pass +proposed.json: proposed.json + verdict : WOULD FAIL + counted : 3 finding(s) (high 1, medium 2, low 0) + violated: max_high=0 exceeded (1 found) + by rule : name-exact x3 +Difference + proposed.json: would fail where the active policy passes +``` + +The exit code stays 0 whatever the shadow says, the report is never filtered by +it, and it can be repeated. Watch a candidate gate for a week, then adopt it by +moving the file to `--policy`. + +--- + +## Work-item export + +Findings only help once they land where work happens. `--export-ticket` writes +one Markdown work item per family (or per candidate): + +```sh +pathscope -i capture.har --export-ticket tickets/ +pathscope -i capture.har --export-ticket tickets/ --ticket-per-candidate +``` + +Each file carries the evidence table, the scoring reasons, the playbook's +confirm-by-hand and fix steps, the fingerprint, and the `--ledger` command that +records a decision. `INDEX.md` lists them all. + +Filenames are derived from host, route and parameter, so re-running overwrites +the same ticket instead of piling up duplicates. + +**Values are never written to a ticket**, even with `--show-values`: a ticket is +going to be pasted somewhere with different access controls than the terminal +it came from. + +--- + +## Pull-request comments + +`--pr-comment` writes a Markdown summary sized for a PR thread: + +```sh +pathscope -i capture.har --pr-comment comment.md --run-id "$GITHUB_RUN_ID" +``` + +```markdown + + +**PathScope: 4 new candidate(s) need review** (best score 73/100, high confidence). + +`5` request(s) · `7` parameter(s) · `4` candidate(s) at score ≥ 25 · ... + +| score | host | resource | parameter | location | +|---:|---|---|---|---| +| 73 | a.test | https://a.test/view | `file` | query | +``` + +* The **marker** line lets a workflow find and update its previous comment + instead of stacking a new one on every push. +* The **verdict** follows the report, never a caller's guess: a comment that + says "no new candidates" above a table of four is worse than no comment. +* The output is **budgeted** (~5.5 KB by default, well under GitHub's limit) + and truncates by whole rows, always saying how many were left out. +* Pipes are escaped so a parameter name cannot break the table. +* No timestamp in the body, so a diff shows what actually changed. + +--- + +## Host redaction + +A report names hosts and paths. That is fine on the capture machine and not +fine in a ticket, a slide, or a vendor email. + +```sh +pathscope -i capture.har --redact-hosts +python3 path_detector.py --redact-hosts --redact-key "$TEAM_SHARE_KEY" ... +``` + +Every host becomes a stable pseudonym (`host-c137d9f4`), in every format and in +every artefact written by that run — reports, tickets, PR comments and bundles. + +| Property | Behaviour | +|---|---| +| stability | the same host is the same pseudonym throughout the run | +| with `--redact-key` | stable **across** runs, so two reports still correlate | +| without a key | a random per-run key: pseudonyms are useless outside the report | +| keyed, not hashed | it is HMAC-SHA-256, so a short hostname cannot be reversed by guessing | +| paths | untouched — `/items/8811/view` still reads as a route | +| ports | preserved (`:8443` survives) | +| `localhost` | left alone | +| fingerprints | **unchanged** — they are opaque, and rewriting them would invalidate every baseline and ledger row | + +Redaction is always announced on stderr, even with `--quiet`. + +--- + +## Shell completion + +```sh +pathscope --completion bash > /etc/bash_completion.d/pathscope +pathscope --completion zsh > "${fpath[1]}/_pathscope" +pathscope --completion fish > ~/.config/fish/completions/pathscope.fish +pathscope --completion powershell >> $PROFILE +``` + +The script is **generated from the real argument parser**, not maintained by +hand, so it cannot drift: a flag added to the parser appears in completion the +moment it exists, or nowhere at all. Value choices (`--format`, `--ledger-status`, +`--sample-by`, …) are completed from the parser's own `choices`. + +--- + ## Exit codes | Code | Meaning | @@ -1504,6 +1804,17 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--ledger-expire DURATION] [--ledger-stale] [--ledger-refresh] [--policy-include-reviewed] [--show-project] [--init-project DIR] [--no-project] + [--cluster] [--queue] [--queue-limit N] [--queue-all] + [--policy-shadow FILE] [--sample N] [--sample-seed K] + [--sample-by {host,source,none}] + [--scope-file FILE] [--init-scope FILE] + [--openapi FILE] [--openapi-json] + [--export-ticket DIR] [--ticket-per-candidate] + [--ticket-limit N] + [--pr-comment FILE] [--run-id TEXT] [--pr-rows N] + [--redact-hosts] [--redact-key SECRET] + [--redact-prefix TEXT] [--redact-length N] + [--completion SHELL] ``` | Option | Description | @@ -1594,6 +1905,29 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] | `--show-project` | Show the discovered project file and what it supplies, then exit. | | `--init-project DIR` | Write `DIR/.pathscope/project.json` and exit. | | `--no-project` | Ignore any `.pathscope/project.json` above the working directory. | +| `--cluster` | Collapse candidates into path families and review once per shape. | +| `--queue` | Print unreviewed work ordered by score, novelty and leverage. | +| `--queue-limit N` | Items to show with `--queue` (default 20; 0 = all). | +| `--queue-all` | With `--queue`, include known and reviewed candidates. | +| `--policy-shadow FILE` | Evaluate a proposed policy without failing the build; repeatable. | +| `--sample N` | Analyse a deterministic subset of N requests (0 = everything). | +| `--sample-seed K` | Seed for `--sample`; the same seed always selects the same subset. | +| `--sample-by KEY` | Stratify `--sample` by `host` (default), `source` or `none`. | +| `--scope-file FILE` | JSON file declaring in-scope and out-of-scope hosts. | +| `--init-scope FILE` | Write a starter scope file and exit. | +| `--openapi FILE` | Compare findings against a local OpenAPI/Swagger JSON file. | +| `--openapi-json` | With `--openapi`, emit the comparison as JSON. | +| `--export-ticket DIR` | Write one Markdown work item per family into DIR. | +| `--ticket-per-candidate` | With `--export-ticket`, one ticket per candidate. | +| `--ticket-limit N` | With `--export-ticket`, write at most N tickets (0 = all). | +| `--pr-comment FILE` | Write a compact Markdown summary for a pull-request comment. | +| `--run-id TEXT` | Identifier written into `--pr-comment` so CI can update in place. | +| `--pr-rows N` | Table rows in `--pr-comment` (default 10). | +| `--redact-hosts` | Replace every host with a stable pseudonym in all outputs. | +| `--redact-key SECRET` | Key for `--redact-hosts` so pseudonyms are stable across runs. | +| `--redact-prefix TEXT` | Prefix for `--redact-hosts` pseudonyms (default `host-`). | +| `--redact-length N` | Hex characters in `--redact-hosts` pseudonyms (default 8). | +| `--completion SHELL` | Print a completion script generated from the parser (`bash`/`zsh`/`fish`/`powershell`). | | `-q, --quiet` | Suppress warnings and the stderr summary. | | `--no-color` | Disable colour on terminals. | | `--no-banner` | Suppress the startup banner. | @@ -1654,7 +1988,7 @@ python3 -m unittest discover -s tests -v python3 tests/test_path_detector.py ``` -514 tests cover exactly the behaviours this tool promises: +636 tests cover exactly the behaviours this tool promises: | Area | What is asserted | |---|---| @@ -1699,6 +2033,16 @@ python3 tests/test_path_detector.py | Calibration | recall/fp bounds, thin-evidence guard, scoreless rows excluded | | Project files | upward discovery, containment, precedence, `--no-project` | | Reviewed CI | SARIF suppressions, JUnit ``, policy include/exclude | +| Path families | route shapes, identifiers vs words, versions, no fingerprint merge | +| Review queue | ordering, novelty exclusion, leverage via size and occurrences | +| Scope files | wildcard breadth, exclusion precedence, empty-scope refusal | +| Sampling | reproducibility, stratification, stability, order preservation | +| API matching | templates, base paths, body properties, YAML refusal | +| Shadow mode | never fails the build, repeatable, side-effect free | +| Work items | per-family vs per-candidate, no values, stable filenames | +| PR comment | marker, honest verdict, row budget, pipe escaping | +| Redaction | keyed stability, paths preserved, fingerprints untouched | +| Completion | all four shells, bash syntax, tracks new parser flags | --- @@ -1740,13 +2084,24 @@ pathscope/ │ ├── termpacks.py # shareable literal term packs │ ├── calibrate.py # ledger-driven score calibration │ ├── project.py # .pathscope/project.json discovery +│ ├── families.py # route-shape clustering +│ ├── queue.py # prioritised review queue +│ ├── scope.py # authorisation scope files +│ ├── sampling.py # deterministic stratified sampling +│ ├── openapi.py # OpenAPI/Swagger comparison +│ ├── shadow.py # policy shadow evaluation +│ ├── tickets.py # work-item export +│ ├── prcomment.py # pull-request comment renderer +│ ├── redact.py # host pseudonymisation +│ ├── completion.py # generated shell completion │ └── __main__.py # enables `python3 -m pathscope` ├── tests/ │ ├── test_path_detector.py # core suite (offline) │ ├── test_features.py # end-to-end feature suite │ ├── test_features_v22.py # 2.2 regression suite │ ├── test_features_v23.py # 2.3 feature suite (one class per feature) -│ └── test_features_v24.py # 2.4 feature suite (one class per feature) +│ ├── test_features_v24.py # 2.4 feature suite (one class per feature) +│ └── test_features_v25.py # 2.5 feature suite (one class per feature) ├── install.sh # POSIX one-command installer ├── install.cmd # Windows installer ├── Dockerfile # slim, unprivileged, --self-test healthcheck diff --git a/pathscope/__init__.py b/pathscope/__init__.py index 4822a9c..4757b3d 100644 --- a/pathscope/__init__.py +++ b/pathscope/__init__.py @@ -14,7 +14,7 @@ from __future__ import annotations PROGRAM = "PathScope" -__version__ = "2.4.0" +__version__ = "2.5.0" # Displayed on every start. These are never opened and never requested. GITHUB_URL = "https://github.com/mrdineshpathro" diff --git a/pathscope/ci.py b/pathscope/ci.py index 035817d..b419efe 100644 --- a/pathscope/ci.py +++ b/pathscope/ci.py @@ -435,6 +435,89 @@ def calibration_uses_the_rules_it_documents() -> None: 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 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), @@ -458,6 +541,13 @@ def calibration_uses_the_rules_it_documents() -> None: ("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), ] diff --git a/pathscope/cli.py b/pathscope/cli.py index ca13d70..d33b7d5 100644 --- a/pathscope/cli.py +++ b/pathscope/cli.py @@ -34,6 +34,16 @@ resolve_preset, ) from . import presets as presets_module +from . import completion as completion_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 @@ -671,6 +681,139 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="ignore any .pathscope/project.json above the working directory", ) + + 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 @@ -1124,6 +1267,15 @@ def run( 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 ----------------------------------------------------- @@ -1176,6 +1328,8 @@ def run( 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.show_project: return _handle_show_project(args, stdout, stderr) if args.ledger_stale or args.ledger_refresh: @@ -1364,6 +1518,43 @@ def run( 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( @@ -1371,6 +1562,18 @@ def run( "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 @@ -1440,6 +1643,26 @@ def run( ) 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) if args.github_annotations: rendered = ci_module.render_github_annotations(report_data) elif args.summary_only: @@ -1491,6 +1714,52 @@ def run( ), 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.save_report: try: @@ -1520,6 +1789,56 @@ def run( 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( @@ -1680,6 +1999,25 @@ def _save(fingerprints): 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: @@ -2080,6 +2418,26 @@ def _handle_list_terms(args, stdout, stderr) -> int: 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_project(args, stderr) -> int: """``--init-project DIR``: write DIR/.pathscope/project.json.""" base = os.path.abspath(args.init_project) 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/detector.py b/pathscope/detector.py index 14b6024..36d1813 100644 --- a/pathscope/detector.py +++ b/pathscope/detector.py @@ -133,6 +133,8 @@ class Report: 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: 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/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/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/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/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/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/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/tests/test_features_v22.py b/tests/test_features_v22.py index 49defd4..f255cd9 100644 --- a/tests/test_features_v22.py +++ b/tests/test_features_v22.py @@ -1323,7 +1323,7 @@ def test_safety_imports(self): "pathlib", "textwrap", "copy", "datetime", "__future__", # 2.3 additions "math", "sqlite3", "zipfile", "curses", "platform", "shutil", - "tempfile", "calendar", + "tempfile", "calendar", "shlex", "hmac", "secrets", } for name in ( "rules", "naming", "valueshape", "policy", "ci", "watch", diff --git a/tests/test_features_v24.py b/tests/test_features_v24.py index 0c541d1..a96253f 100644 --- a/tests/test_features_v24.py +++ b/tests/test_features_v24.py @@ -317,7 +317,9 @@ def test_cli_diff_json(self): ) self.assertEqual(code, cli.EXIT_FINDINGS) payload = json.loads(out) - self.assertEqual(payload["version"], "2.4.0") + # 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"]) @@ -1008,8 +1010,9 @@ def test_all_new_flags_are_documented(self): ): self.assertIn(flag, help_text, f"{flag} missing from --help") - def test_version_is_2_4(self): - self.assertEqual(__version__, "2.4.0") + def test_version_is_at_least_2_4(self): + major, minor = __version__.split(".")[:2] + self.assertGreaterEqual((int(major), int(minor)), (2, 4)) def test_self_describing_flags_exit_cleanly(self): for args in ( diff --git a/tests/test_features_v25.py b/tests/test_features_v25.py new file mode 100644 index 0000000..783834e --- /dev/null +++ b/tests/test_features_v25.py @@ -0,0 +1,1089 @@ +"""Tests for the PathScope 2.5 feature set. + +One class per feature from the 2.5 menu: + +1. path-family clustering -> :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_path_detector.py b/tests/test_path_detector.py index 9cac408..aac80dd 100755 --- a/tests/test_path_detector.py +++ b/tests/test_path_detector.py @@ -1148,7 +1148,7 @@ def test_imports_are_standard_library_only(self): "pathlib", "textwrap", "xml", "xml.etree", "xml.etree.ElementTree", "base64", "copy", "hashlib", "html", "time", "math", "sqlite3", "zipfile", "curses", "platform", "shutil", "tempfile", "textwrap", - "calendar", + "calendar", "shlex", "hmac", "secrets", } for path in project_modules(): tree = ast.parse(path.read_text(encoding="utf-8")) From 66cee9d079dcfe11f690cc504e00bd36d2221856 Mon Sep 17 00:00:00 2001 From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:22:49 +0000 Subject: [PATCH 8/8] v2.6.0: waivers, suppression audit, rule precision/impact, simulation Ten additions, all passive and stdlib-only: 1. Waivers -- --waivers/--init-waivers/--list-waivers. Committable JSON exceptions that need a reason, an owner and (usually) an expiry. Expired waivers hide nothing; unknown keys are errors so a typo cannot create an immortal waiver. Waived findings are hidden, announced, and excluded from --policy -- that is what a waiver is for. 2. Suppression audit -- --suppression-audit. Classifies every baseline, waiver and ledger entry as live, dead, overbroad or expired. Read-only. 3. Rule precision -- --rule-precision. Accepted vs false-positive per rule; under 5 labels a rule is reported but never judged. 4. Rule impact -- --rule-impact. Points contributed, and 'deciding': findings that would fall below the threshold without the rule. 5. Weight simulation -- --simulate. Genuinely re-analyses under hypothetical weights rather than subtracting a share of a capped score. Never writes. 6. Score-change explanation -- --explain-diff. Two saved reports, tracked by (host, path, parameter, location); names the rule whose evidence moved. 7. --where. Hand-written tokenizer and parser; eval is never used. Errors carry a position. Filtering never changes the exit code: the gate still judges the unfiltered set, so a filter cannot create a false green. 8. Attestation -- --attest/--verify-attest. Digests over input bytes, effective settings and the rendered output. Explicitly unsigned. 9. Owner assignment -- --assign-owners/--assign-by/--assign-dir. Rendezvous hashing: deterministic, stable under team growth, one owner per stratum. 10. Ledger merge -- --ledger-merge/--merge-apply/--merge-prefer. Conflicts are surfaced, never silently resolved; dry run is the default; the audit trail records each merged row. Also fixes the host-doubling defect (a.testhttps://a.test/view) in a shared textutil.display_location() helper instead of a fifth local copy. 769 tests (133 new, one class per feature) and --self-test 35/35. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- README.md | 395 ++++++++++- pathscope/__init__.py | 2 +- pathscope/assign.py | 306 +++++++++ pathscope/attest.py | 229 +++++++ pathscope/audit.py | 288 ++++++++ pathscope/ci.py | 128 ++++ pathscope/cli.py | 444 +++++++++++- pathscope/impact.py | 217 ++++++ pathscope/ledgermerge.py | 235 +++++++ pathscope/policy.py | 6 + pathscope/precision.py | 203 ++++++ pathscope/query.py | 376 +++++++++++ pathscope/scorechange.py | 307 +++++++++ pathscope/simulate.py | 335 +++++++++ pathscope/textutil.py | 17 + pathscope/waivers.py | 407 +++++++++++ tests/test_features_v26.py | 1278 +++++++++++++++++++++++++++++++++++ tests/test_path_detector.py | 2 +- 18 files changed, 5161 insertions(+), 14 deletions(-) create mode 100644 pathscope/assign.py create mode 100644 pathscope/attest.py create mode 100644 pathscope/audit.py create mode 100644 pathscope/impact.py create mode 100644 pathscope/ledgermerge.py create mode 100644 pathscope/precision.py create mode 100644 pathscope/query.py create mode 100644 pathscope/scorechange.py create mode 100644 pathscope/simulate.py create mode 100644 pathscope/waivers.py create mode 100644 tests/test_features_v26.py diff --git a/README.md b/README.md index 8919c94..ecbebef 100644 --- a/README.md +++ b/README.md @@ -74,14 +74,24 @@ reviewing for path-traversal risk.** 43. [Pull-request comments](#pull-request-comments) 44. [Host redaction](#host-redaction) 45. [Shell completion](#shell-completion) -46. [Exit codes](#exit-codes) -47. [Detection rules](#detection-rules) -48. [Configuration file](#configuration-file) -49. [Tests](#tests) -50. [Project layout](#project-layout) -51. [Limitations](#limitations) -52. [FAQ](#faq) -53. [Authorization and legal](#authorization-and-legal) +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) --- @@ -326,7 +336,7 @@ Example terminal output (values hidden): ```console $ python3 path_detector.py --url 'https://example.test/view?file=report.pdf' -PathScope 2.5.0 - passive path-parameter triage +PathScope 2.6.0 - passive path-parameter triage ---------------------------------------------------------------- GitHub: https://github.com/mrdineshpathro Instagram: https://www.instagram.com/mr_dineshpatro @@ -1673,6 +1683,317 @@ moment it exists, or nowhere at all. Value choices (`--format`, `--ledger-status --- +## Waivers + +The ledger is a good review store and a bad review *artefact*: it is SQLite, it +lives beside whoever 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: + +```sh +pathscope --init-waivers waivers.json +pathscope -i capture.har --waivers waivers.json +``` + +```json +{ + "version": 1, + "waivers": [ + { + "host": "api.acme.test", + "path": "/documents/*", + "parameter": "file", + "rule": "name-exact", + "reason": "validated against a signed allow-list upstream", + "owner": "platform-team", + "expires": "2027-01-31", + "ticket": "SEC-1234" + } + ] +} +``` + +| Rule | Why it exists | +|---|---| +| `reason` and `owner` are required | an exception without either is anonymous and permanent | +| at least one of `host`/`path`/`parameter`/`rule`/`location` | `{}` would waive every finding in every future run | +| `expires` must be `YYYY-MM-DD` | a duration restarts every run, so it never expires | +| unknown keys are errors | a typo in `expirse` must not create an immortal waiver | + +Waived findings are **hidden** and announced, exactly like ledger reviews; +`--show-known` reveals them with their justification. `--waivers` also stops +`--policy` from failing on them — that is what a waiver is for. + +--- + +## Suppression audit + +Every suppression rots, and it rots silently, because suppressed rows are +removed before rendering. `--suppression-audit` reads the inputs and reports +what they are actually doing: + +```sh +pathscope -i capture.har --baseline base.json --waivers waivers.json \ + --ledger reviews.db --show-known --suppression-audit +``` + +``` +Baseline / suppression files (2) + [live ] 2cc01c9e8a375a9e -- matched 1 finding(s) + [DEAD ] deadbeefdeadbeef (old) -- matched 0 finding(s) + +Waivers (1) + [EXPIRED ] a.test /view file -- matched 1 finding(s) + +Summary + live : 1 + dead : 1 + overbroad : 0 + expired : 1 +``` + +* **dead** — matched nothing: an endpoint renamed, a parameter removed, a rule + changed. It looks like coverage in review and hides nothing in a run. +* **overbroad** — one entry hiding more than 10 findings, usually a waiver that + named only a host. +* **expired** — the acceptance outlived its date and no longer hides anything. + +The audit is read-only. Nothing is removed automatically; a human edits the file. + +--- + +## Rule precision + +The ledger records what humans decided. Comparing that with the rules that +produced each finding gives each rule a precision: + +```sh +pathscope --ledger reviews.db --rule-precision +``` + +``` + rule labelled accepted fp precision verdict + name-exact 15 12 3 80% earning its weight + name-weak 10 1 9 10% candidate for demotion + value-extension 4 4 0 100% thin evidence +``` + +Only `accepted` and `false-positive` count. `reviewed` means somebody looked, +not what they concluded, so it carries no signal. + +Under **5** labelled findings a rule is reported but never judged — a precision +from four rows is a coincidence. Every contributing rule is counted, not just +the primary one. + +--- + +## Rule impact + +`--rule-coverage` says whether a rule fired. `--rule-impact` says whether it +*decided* anything: + +```sh +pathscope -i capture.har --rule-impact +``` + +``` + rule weight seen leading deciding points share + name-exact 35 3 3 2 105 48.8% + value-absolute 12 3 1 1 36 16.7% + value-multi-segment 6 3 0 0 18 8.4% +``` + +`deciding` counts findings that would fall below the threshold without the +rule. A rule can fire 300 times and decide nothing, and another can fire twice +and decide everything. Demotions are shown with their sign rather than +pretending they have no effect. + +--- + +## Weight simulation + +Changing a weight is a guess unless you can see what it does. `--simulate` +**re-analyses** the same input under hypothetical weights: + +```sh +pathscope -i capture.har --simulate "name-weak=-10,value-absolute=off" +``` + +``` +Candidates + before after delta + total 4 -> 0 -4 + high 1 -> 0 -1 + +No longer reported (4) + - a.test/view [query] download +``` + +Syntax: `rule=-10`, `rule=off` (disable), `rule=default` (reset). Comma +separated, one change per rule. + +It re-analyses rather than subtracting the rule's share from recorded scores, +because scores are capped at 100, demotions can floor them at 0, and removing +the leading rule changes which rule is primary. Arithmetic on the recorded score +would be wrong in all three cases. + +The real report is printed unchanged and the exit code is untouched, so +`--simulate` is safe in a pipeline. Apply a change through a `--rules` file. + +--- + +## Score-change explanation + +`--baseline` answers "what is new". This answers a different question: *the +finding did not appear or disappear — why did its score move?* + +```sh +pathscope -i before.har --format json > before.json +pathscope -i after.har --format json > after.json +pathscope --explain-diff before.json --explain-diff after.json +``` + +``` +tracked 4 finding(s): 3 changed score, 1 unchanged. + + a.test/view [query] file: 73 -> 53 (-20) + confidence high -> medium + + parameter name contains path-related term 'file' (+15, was +35) +``` + +Identity is (host, path, parameter, location) — the tuple that survives new +values and different source labels — so a finding is tracked even when its +primary rule changed. + +Where the saved report has signed contributions, the diff names the exact rule +whose evidence moved. Where it does not, it says so rather than inventing a +cause. + +--- + +## Filtering with --where + +```sh +pathscope -i capture.har --where "score > 60 and confidence = high" +pathscope -i capture.har --where "host ~= *.api.test and not status = known" +pathscope -i capture.har --where "rule starts_with name- or parameter in file,template" +``` + +| Part | Supported | +|---|---| +| fields | `host`, `resource`, `parameter`, `location`, `rule`, `confidence`, `status`, `method`, `source`, `fingerprint`, `score`, `occurrences` | +| operators | `=` `!=` `>` `>=` `<` `<=` `~=` (glob) `in` `starts_with` `ends_with` `contains` | +| combining | `and` (binds tighter than) `or`, `not` | +| values | bare words, or `"quoted strings"` | + +**`eval` is never used.** The expression is tokenised, parsed into a small tree, +and applied through a fixed set of field accessors, so a crafted expression can +filter rows — it cannot execute anything. + +Errors name the position: `unknown field 'scor' at position 1 (known: ...)`. +A filter that silently matches nothing is how people decide a tool is broken. + +`--where` changes what you *see*, never the exit code: `--fail-on-findings` and +`--policy` still judge the unfiltered set, so a filter cannot create a false +green. `--where-json` writes just the matched findings. + +--- + +## Run attestation + +An attestation binds a run to its inputs and settings: + +```sh +pathscope -i capture.har --format json --attest run.attest.json > report.json +pathscope -i capture.har --format json --verify-attest run.attest.json > report2.json +``` + +```json +{ + "tool": "PathScope", + "version": "2.6.0", + "schema": 1, + "created": "2026-11-29T10:11:12Z", + "digests": { "inputs": "sha256:...", "settings": "sha256:...", "output": "sha256:..." }, + "counts": { "requests": 5, "parameters": 7, "candidates": 3 }, + "signature": null, + "signature_note": "not signed: an attestation is a digest, not proof of authorship" +} +``` + +**What it is:** a digest. Two runs with the same input bytes and the same +settings produce the same input and settings digests, and an edited report no +longer matches its output digest. + +**What it is not:** a signature. It says nothing about *who* ran it — that needs +a key, and PathScope has no keystore. The file says so in its own body rather +than implying more. + +Input digests cover **bytes**, so attesting a capture full of secrets discloses +nothing about them. Values never appear in an attestation. + +--- + +## Owner assignment + +```sh +pathscope -i capture.har --ledger reviews.db --assign-owners alice,bob,carol +pathscope -i capture.har --assign-owners alice,bob,carol --assign-dir work/ +``` + +``` + bob 1 25.0% ######## + carol 3 75.0% ###################### +``` + +Assignment uses a **rendezvous hash**: hash each finding against each owner and +give it to the highest scorer. That buys three properties round-robin cannot: + +* the same finding goes to the same owner on every machine, so re-running does + not reshuffle a half-finished review; +* adding findings never moves an existing one; +* adding an owner takes a proportional share instead of reassigning everything. + +`--assign-by host` (default) keeps all of one host's work with one person, so +two people never reach different conclusions about the same code. Also +available: `path`, `parameter`, `rule`, `foundry`. + +Shares are proportional **in expectation**, not forced equal — forcing exact +balance would break both stability properties. The real split is printed, so an +uneven result is visible rather than hidden. + +--- + +## Ledger merge + +Two reviewers, two local ledgers, both full of real decisions. + +```sh +pathscope --ledger mine.db --ledger-merge theirs.db # dry run +pathscope --ledger mine.db --ledger-merge theirs.db --merge-apply +``` + +``` + added : 1 + unchanged : 0 + conflicts : 1 +``` + +| Situation | Behaviour | +|---|---| +| same fingerprint, same status | keep the newer `updated_at`; nothing was in dispute | +| same fingerprint, **different status** | a **conflict**, both decisions shown | +| only in one ledger | carried across untouched | + +`--merge-prefer newer\|left\|right` makes the rule explicit instead of +implicit. The **dry run is the default** because a merge that runs by accident +is unrecoverable. + +Audit events are never rewritten: the destination records each merged row as a +`merged` event, so "alice accepted this on the 3rd" survives a merge that +preferred bob's later decision. + +--- + ## Exit codes | Code | Meaning | @@ -1815,6 +2136,16 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--redact-hosts] [--redact-key SECRET] [--redact-prefix TEXT] [--redact-length N] [--completion SHELL] + [--waivers FILE] [--init-waivers FILE] [--list-waivers] + [--suppression-audit] [--audit-json] + [--rule-precision] [--rule-impact] + [--simulate CHANGES] [--simulate-json] + [--explain-diff OLD.json] + [--where EXPR] [--where-json] + [--attest FILE] [--verify-attest FILE] + [--assign-owners LIST] [--assign-by KEY] [--assign-dir DIR] + [--ledger-merge OTHER] [--merge-apply] + [--merge-prefer {newer,left,right}] [--merge-json] ``` | Option | Description | @@ -1928,6 +2259,27 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] | `--redact-prefix TEXT` | Prefix for `--redact-hosts` pseudonyms (default `host-`). | | `--redact-length N` | Hex characters in `--redact-hosts` pseudonyms (default 8). | | `--completion SHELL` | Print a completion script generated from the parser (`bash`/`zsh`/`fish`/`powershell`). | +| `--waivers FILE` | Load committable JSON waivers; repeatable. | +| `--init-waivers FILE` | Write a starter waiver file and exit. | +| `--list-waivers` | Show the loaded waivers and what each matched. | +| `--suppression-audit` | Report dead, overbroad and expired suppressions. | +| `--audit-json` | With `--suppression-audit`, emit JSON. | +| `--rule-precision` | Precision per rule from labelled ledger reviews, then exit. | +| `--rule-impact` | How much each rule contributes to what is reported. | +| `--simulate CHANGES` | Re-analyse under hypothetical weights, e.g. `name-weak=-10,x=off`. | +| `--simulate-json` | With `--simulate`, emit JSON. | +| `--explain-diff OLD.json` | With a second report, explain which scores moved and why; then exit. | +| `--where EXPR` | Filter findings, e.g. `score > 60 and confidence = high`. | +| `--where-json` | With `--where`, emit the filtered findings as JSON. | +| `--attest FILE` | Write a JSON digest of inputs, settings and output. | +| `--verify-attest FILE` | Check a report against an attestation. | +| `--assign-owners LIST` | Split open work across owners. | +| `--assign-by KEY` | Stratum for `--assign-owners` (`host`/`path`/`parameter`/`rule`/`foundry`). | +| `--assign-dir DIR` | Write one Markdown worklist per owner into DIR. | +| `--ledger-merge OTHER` | Plan a merge of OTHER into `--ledger` (dry run unless `--merge-apply`). | +| `--merge-apply` | With `--ledger-merge`, actually write the merge. | +| `--merge-prefer SIDE` | Which side wins a status conflict (`newer`/`left`/`right`). | +| `--merge-json` | With `--ledger-merge`, emit the plan as JSON. | | `-q, --quiet` | Suppress warnings and the stderr summary. | | `--no-color` | Disable colour on terminals. | | `--no-banner` | Suppress the startup banner. | @@ -1988,7 +2340,7 @@ python3 -m unittest discover -s tests -v python3 tests/test_path_detector.py ``` -636 tests cover exactly the behaviours this tool promises: +769 tests cover exactly the behaviours this tool promises: | Area | What is asserted | |---|---| @@ -2043,6 +2395,16 @@ python3 tests/test_path_detector.py | PR comment | marker, honest verdict, row budget, pipe escaping | | Redaction | keyed stability, paths preserved, fingerprints untouched | | Completion | all four shells, bash syntax, tracks new parser flags | +| Waivers | required reason/owner, expiry is a date, expired hides nothing | +| Suppression audit | live/dead/overbroad/expired, read-only | +| Rule precision | per-rule precision, thin evidence unjudged, labels only | +| Rule impact | points, deciding vs appeared, demotion signs | +| Simulation | spec parsing, re-analysis, never mutates the real book | +| Explain diff | tracked identity, rule-level causes, tamper evidence | +| `--where` | operators, precedence, clear errors, no `eval` anywhere | +| Attestation | digest stability, tamper detection, unsigned by design | +| Assignment | determinism, one owner per stratum, stability under growth | +| Ledger merge | conflicts surfaced, dry run default, audit preserved | --- @@ -2094,6 +2456,16 @@ pathscope/ │ ├── prcomment.py # pull-request comment renderer │ ├── redact.py # host pseudonymisation │ ├── completion.py # generated shell completion +│ ├── waivers.py # committable JSON waivers +│ ├── audit.py # suppression rot audit +│ ├── precision.py # per-rule precision from the ledger +│ ├── impact.py # per-rule contribution to what is shown +│ ├── simulate.py # hypothetical weight re-analysis +│ ├── scorechange.py # why a score moved between two reports +│ ├── query.py # safe --where expression parser +│ ├── attest.py # run digests (deliberately unsigned) +│ ├── assign.py # rendezvous-hash owner assignment +│ ├── ledgermerge.py # conflict-surfacing ledger merge │ └── __main__.py # enables `python3 -m pathscope` ├── tests/ │ ├── test_path_detector.py # core suite (offline) @@ -2101,7 +2473,8 @@ pathscope/ │ ├── test_features_v22.py # 2.2 regression suite │ ├── test_features_v23.py # 2.3 feature suite (one class per feature) │ ├── test_features_v24.py # 2.4 feature suite (one class per feature) -│ └── test_features_v25.py # 2.5 feature suite (one class per feature) +│ ├── test_features_v25.py # 2.5 feature suite (one class per feature) +│ └── test_features_v26.py # 2.6 feature suite (one class per feature) ├── install.sh # POSIX one-command installer ├── install.cmd # Windows installer ├── Dockerfile # slim, unprivileged, --self-test healthcheck diff --git a/pathscope/__init__.py b/pathscope/__init__.py index 4757b3d..6419a69 100644 --- a/pathscope/__init__.py +++ b/pathscope/__init__.py @@ -14,7 +14,7 @@ from __future__ import annotations PROGRAM = "PathScope" -__version__ = "2.5.0" +__version__ = "2.6.0" # Displayed on every start. These are never opened and never requested. GITHUB_URL = "https://github.com/mrdineshpathro" diff --git a/pathscope/assign.py b/pathscope/assign.py new file mode 100644 index 0000000..f1cfa0f --- /dev/null +++ b/pathscope/assign.py @@ -0,0 +1,306 @@ +"""Owner assignment (``--assign-owners a,b,c`` / ``--assign-by host``). + +The review queue orders work. This says **whose** work it is, and writes one +Markdown slice per owner so a team can split a review without a meeting. + +Assignment is a **rendezvous hash**: each finding is hashed with each owner and +the owner with the highest score wins. That has three properties a round-robin +does not: + +* **deterministic** -- the same finding goes to the same owner on every machine, + so re-running does not reshuffle a review that is already half done; +* **stable under growth** -- adding findings does not move any existing one; +* **stable under team growth** -- adding an owner only takes a share of the + existing findings proportional to the new capacity, instead of reassigning + everything, which is what makes round-robin unusable in practice. + +Shares are not forced to be equal. A rendezvous hash is proportional in +expectation, not exactly, and forcing exact balance would break both of the +stability properties above. The output reports the actual split so an uneven +result visible. +""" + +from __future__ import annotations + +import hashlib +import os +import re +from dataclasses import dataclass, field +from typing import Dict, List, Sequence + +from .detector import Finding +from .textutil import display_location + +#: Guard against a runaway export. +MAX_OWNERS = 200 +MAX_ASSIGNMENTS = 20000 + +_ASSIGN_BY = ("host", "foundry", "parameter", "rule", "path") +_UNSAFE = re.compile(r"[^A-Za-z0-9._-]+") + + +class AssignError(ValueError): + """Raised when owners or the assignment strategy are not usable.""" + + +@dataclass(frozen=True) +class Assignment: + """One finding and the owner it belongs to.""" + + owner: str + finding: Finding + + @property + def label(self) -> str: + return ( + f"{display_location(self.finding.host, self.finding.resource)} " + f"[{self.finding.location}] {self.finding.parameter}" + ) + + +@dataclass +class Distribution: + """The assignment result, grouped by owner.""" + + by_owner: Dict[str, List[Assignment]] = field(default_factory=dict) + strategy: str = "host" + + @property + def owners(self) -> List[str]: + return sorted(self.by_owner) + + @property + def total(self) -> int: + return sum(len(items) for items in self.by_owner.values()) + + def counts(self) -> Dict[str, int]: + return {owner: len(self.by_owner[owner]) for owner in self.owners} + + def as_dict(self) -> Dict[str, object]: + return { + "strategy": self.strategy, + "total": self.total, + "counts": self.counts(), + "owners": { + owner: [ + { + "host": item.finding.host, + "resource": item.finding.resource, + "parameter": item.finding.parameter, + "location": item.finding.location, + "score": item.finding.score, + } + for item in items + ] + for owner, items in sorted(self.by_owner.items()) + }, + } + + +def parse_owners(spec: str) -> List[str]: + """Parse ``"a,b,c"`` into a unique, validated owner list.""" + if not spec or not spec.strip(): + raise AssignError("--assign-owners needs at least one name") + owners: List[str] = [] + for piece in spec.split(","): + name = piece.strip() + if not name: + continue + if len(name) > 64: + raise AssignError(f"owner name '{name[:20]}...' is longer than 64 characters") + if not re.match(r"^[A-Za-z0-9@._-]+$", name): + raise AssignError( + f"owner '{name}' may only contain letters, digits, @ . _ - " + "(it becomes a filename)" + ) + if name.lower() in {owner.lower() for owner in owners}: + raise AssignError(f"owner '{name}' is listed twice") + owners.append(name) + if not owners: + raise AssignError("--assign-owners contained no usable names") + if len(owners) > MAX_OWNERS: + raise AssignError(f"{len(owners)} owners (limit {MAX_OWNERS})") + return owners + + +def _key(finding: Finding, strategy: str) -> str: + if strategy == "parameter": + return finding.parameter.lower() + if strategy == "rule": + return finding.rule + if strategy == "path": + return finding.resource or "/" + return finding.host.lower() + + +def _score(owner: str, key: str, salt: str) -> int: + material = f"{salt}\x1f{owner.lower()}\x1f{key}" + return int.from_bytes( + hashlib.sha256(material.encode("utf-8", "surrogatepass")).digest()[:8], "big" + ) + + +def choose(owners: Sequence[str], key: str, salt: str = "pathscope") -> str: + """Rendezvous hash: the owner that scores highest for this key.""" + if not owners: + raise AssignError("no owners to choose from") + return max(owners, key=lambda owner: (_score(owner, key, salt), owner)) + + +def assign( + findings: Sequence[Finding], + owners: Sequence[str], + *, + strategy: str = "host", + salt: str = "pathscope", +) -> Distribution: + """Assign findings to owners, keeping each stratum on one owner.""" + if strategy not in _ASSIGN_BY: + raise AssignError( + f"unknown --assign-by '{strategy}' (choose from {', '.join(_ASSIGN_BY)})" + ) + if len(findings) > MAX_ASSIGNMENTS: + raise AssignError( + f"{len(findings)} findings (limit {MAX_ASSIGNMENTS}); use " + "--assign-limit or cluster first" + ) + # One owner per stratum, so nobody shares half of a host's review with + # somebody else who would reach a different conclusion about the same code. + stratum_owner: Dict[str, str] = {} + distribution = Distribution(strategy=strategy) + for finding in findings: + key = _key(finding, strategy) + owner = stratum_owner.get(key) + if owner is None: + owner = choose(owners, key, salt) + stratum_owner[key] = owner + distribution.by_owner.setdefault(owner, []).append(Assignment(owner, finding)) + return distribution + + +def _slug(text: str) -> str: + cleaned = _UNSAFE.sub("-", text).strip("-.") + return (cleaned or "owner")[:60] + + +def render_distribution(distribution: Distribution) -> str: + """``--assign-owners`` as text.""" + lines = ["PathScope owner assignment", "=" * 84] + if not distribution.total: + lines.append("No open candidates to assign.") + return "\n".join(lines) + lines.append( + f"{distribution.total} finding(s) across {len(distribution.owners)} " + f"owner(s), grouped by {distribution.strategy}." + ) + lines.append("") + counts = distribution.counts() + total = distribution.total or 1 + for owner in distribution.owners: + share = counts[owner] / total + bar = "#" * max(0, int(round(share * 30))) + lines.append(f" {owner:<24} {counts[owner]:>5} {share:>6.1%} {bar}") + lines.append("") + lines.append( + "Assignment uses a rendezvous hash: adding an owner takes a proportional " + "share instead of reshuffling every finding, and adding findings never " + "moves an existing one." + ) + lines.append( + "Shares are proportional in expectation, not forced equal -- exact " + "balance would break both of those properties." + ) + return "\n".join(lines) + + +def render_owner_slice(owner: str, assignments: Sequence[Assignment]) -> str: + """One owner's Markdown worklist.""" + from .report import DISCLAIMER + + lines = [f"# PathScope worklist: {owner}", ""] + lines.append(f"*{DISCLAIMER}*") + lines.append("") + if not assignments: + lines.append("Nothing assigned.") + return "\n".join(lines) + "\n" + total_score = sum(item.finding.score for item in assignments) + lines.append(f"{len(assignments)} candidate(s), total score {total_score}.") + lines.append("") + lines.append("| score | confidence | host | resource | parameter | location |") + lines.append("|---:|---|---|---|---|---|") + for item in sorted(assignments, key=lambda a: -a.finding.score): + finding = item.finding + lines.append( + f"| {finding.score} | {finding.confidence} | {finding.host} | " + f"{finding.resource} | `{finding.parameter}` | {finding.location} |" + ) + lines.append("") + lines.append("## Recording decisions") + lines.append("") + lines.append("```sh") + lines.append( + "pathscope -i capture.har --ledger reviews.db --ledger-mark-all \\\n" + f" --ledger-status accepted --reviewer {owner}" + ) + lines.append("```") + lines.append("") + lines.append(f"{len(assignments)} fingerprint(s):") + lines.append("") + for item in sorted(assignments, key=lambda a: a.finding.parameter): + lines.append(f"- `{item.finding.fingerprint}` {item.label}") + return "\n".join(lines) + "\n" + + +def write_slices(directory: str, distribution: Distribution) -> List[str]: + """Write one Markdown file per owner, plus an index.""" + try: + os.makedirs(directory, exist_ok=True) + except OSError as exc: + raise AssignError(f"cannot create '{directory}': {exc.strerror or exc}") from exc + written: List[str] = [] + for owner in distribution.owners: + target = os.path.join(directory, f"{_slug(owner)}.md") + try: + with open(target, "w", encoding="utf-8", newline="\n") as handle: + handle.write(render_owner_slice(owner, distribution.by_owner[owner])) + except OSError as exc: + raise AssignError(f"cannot write '{target}': {exc.strerror or exc}") from exc + written.append(target) + index = os.path.join(directory, "INDEX.md") + counts = distribution.counts() + lines = [ + "# PathScope assignment", + "", + f"{distribution.total} finding(s) across {len(counts)} owner(s), " + f"grouped by {distribution.strategy}.", + "", + "| owner | candidates | worklist |", + "|---|---:|---|", + ] + for owner in distribution.owners: + lines.append( + f"| {owner} | {counts[owner]} | [`{_slug(owner)}.md`]({_slug(owner)}.md) |" + ) + lines.append("") + try: + with open(index, "w", encoding="utf-8", newline="\n") as handle: + handle.write("\n".join(lines) + "\n") + except OSError as exc: + raise AssignError(f"cannot write '{index}': {exc.strerror or exc}") from exc + written.append(index) + return written + + +__all__ = [ + "Assignment", + "AssignError", + "Distribution", + "MAX_ASSIGNMENTS", + "MAX_OWNERS", + "assign", + "choose", + "parse_owners", + "render_distribution", + "render_owner_slice", + "write_slices", +] diff --git a/pathscope/attest.py b/pathscope/attest.py new file mode 100644 index 0000000..476d132 --- /dev/null +++ b/pathscope/attest.py @@ -0,0 +1,229 @@ +"""Run attestation (``--attest FILE``). + +A report is evidence only if you can say what produced it. This writes a small +JSON document that binds a run to its inputs and settings: + + { + "tool": "PathScope", + "version": "2.6.0", + "created": "2026-11-29T10:11:12Z", + "digests": { + "inputs": "sha256:...", + "config": "sha256:...", + "rules": "sha256:...", + "output": "sha256:..." + }, + "settings": {"min_score": 25, "preset": "balanced", ...}, + "counts": {"requests": 12, "candidates": 4} + } + +What it is: a **digest**, not a signature. It proves two runs used the same +input bytes and the same settings, and that a report file has not been edited +since. It proves nothing about *who* ran it -- that needs a key, and PathScope +has no keystore. Saying otherwise would be the kind of false assurance this +tool avoids elsewhere. + +Digests: + +* **inputs** -- over the raw bytes of every input file, in argument order, so a + re-ordered command line is a different run (which it is); +* **config / rules** -- the *effective* settings, not the files that produced + them, so two paths to the same configuration attest identically; +* **output** -- over the rendered report exactly as written to stdout. + +Values are never included. The digest of an input covers bytes, not content, so +attestations of a capture containing secrets disclose nothing about them. +""" + +from __future__ import annotations + +import datetime as _dt +import hashlib +import json +import os +from dataclasses import dataclass, field +from typing import Dict, Iterable, List, Optional, Sequence + +from . import PROGRAM, __version__ + +SCHEMA = 1 +#: Cap so attesting a huge file cannot exhaust memory (it streams, but a +#: pathological list of inputs should still be bounded). +MAX_INPUTS = 512 + + +class AttestationError(RuntimeError): + """Raised when an attestation cannot be produced.""" + + +def digest_bytes(data: bytes) -> str: + return "sha256:" + hashlib.sha256(data).hexdigest() + + +def _digest_file(path: str, limit: int = 512 * 1024 * 1024) -> str: + """Stream a file through SHA-256 without loading it all.""" + hasher = hashlib.sha256() + total = 0 + try: + with open(path, "rb") as handle: + while True: + chunk = handle.read(1024 * 128) + if not chunk: + break + total += len(chunk) + if total > limit: + raise AttestationError( + f"'{path}' is larger than {limit} bytes; not attesting" + ) + hasher.update(chunk) + except OSError as exc: + raise AttestationError( + f"cannot read '{path}' for attestation: {exc.strerror or exc}" + ) from exc + return "sha256:" + hasher.hexdigest() + + +def digest_paths(paths: Sequence[str]) -> str: + """Digest over an ordered list of files (and stdin markers).""" + if len(paths) > MAX_INPUTS: + raise AttestationError(f"{len(paths)} inputs (limit {MAX_INPUTS})") + hasher = hashlib.sha256() + for path in paths: + if path == "-": + hasher.update(b"stdin\x1f") + continue + name = os.path.basename(path) + hasher.update(name.encode("utf-8", "surrogatepass")) + hasher.update(b"\x1f") + hasher.update(_digest_file(path).encode("ascii")) + hasher.update(b"\x1e") + return "sha256:" + hasher.hexdigest() + + +def digest_payload(payload: object) -> str: + """Stable digest of a JSON-serialisable structure. + + ``sort_keys`` and a fixed separator make the digest independent of the + order in which a dictionary happened to be built, which is exactly the + accident this must not be sensitive to. + """ + text = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return digest_bytes(text.encode("utf-8")) + + +@dataclass +class Attestation: + """One run's binding to its inputs and settings.""" + + created: str = "" + digests: Dict[str, str] = field(default_factory=dict) + settings: Dict[str, object] = field(default_factory=dict) + counts: Dict[str, int] = field(default_factory=dict) + inputs: List[str] = field(default_factory=list) + notes: List[str] = field(default_factory=list) + + def as_dict(self) -> Dict[str, object]: + return { + "tool": PROGRAM, + "version": __version__, + "schema": SCHEMA, + "created": self.created, + "digests": dict(self.digests), + "settings": dict(self.settings), + "counts": dict(self.counts), + "inputs": list(self.inputs), + "notes": list(self.notes), + "signature": None, + "signature_note": ( + "not signed: an attestation is a digest, not proof of authorship" + ), + } + + def render(self) -> str: + return json.dumps(self.as_dict(), indent=2, ensure_ascii=False) + "\n" + + +def build( + *, + inputs: Iterable[str] = (), + rendered: str = "", + settings: Optional[Dict[str, object]] = None, + counts: Optional[Dict[str, int]] = None, + created: Optional[str] = None, + notes: Sequence[str] = (), +) -> Attestation: + """Build an attestation for one finished run.""" + paths = [path for path in inputs] + attestation = Attestation( + created=created + or _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + inputs=paths, + settings=dict(settings or {}), + counts=dict(counts or {}), + notes=list(notes), + ) + file_inputs = [path for path in paths if path != "-"] + attestation.digests["inputs"] = digest_paths(file_inputs) if file_inputs else digest_bytes(b"") + attestation.digests["settings"] = digest_payload(attestation.settings) + attestation.digests["output"] = digest_bytes(rendered.encode("utf-8")) + return attestation + + +def verify(attestation_path: str, rendered: str = "", inputs: Sequence[str] = ()) -> List[str]: + """Check an attestation against a report and inputs. + + Returns a list of problems; empty means everything matched. This is the + only honest form of verification without a key: it re-derives the digests. + """ + try: + with open(attestation_path, "r", encoding="utf-8") as handle: + payload = json.load(handle) + except OSError as exc: + raise AttestationError( + f"cannot read attestation '{attestation_path}': {exc.strerror or exc}" + ) from exc + except json.JSONDecodeError as exc: + raise AttestationError( + f"attestation '{attestation_path}' is not valid JSON: line {exc.lineno}" + ) from exc + if not isinstance(payload, dict): + raise AttestationError("an attestation must be a JSON object") + digests = payload.get("digests") + if not isinstance(digests, dict): + raise AttestationError("an attestation has no 'digests' object") + problems: List[str] = [] + if rendered: + if digests.get("output") != digest_bytes(rendered.encode("utf-8")): + problems.append("the report does not match the attested output digest") + if inputs: + file_inputs = [path for path in inputs if path != "-"] + if file_inputs and digests.get("inputs") != digest_paths(file_inputs): + problems.append("the input files do not match the attested input digest") + return problems + + +def render_verification(problems: Sequence[str], path: str) -> str: + lines = [f"PathScope attestation check: {path}"] + if not problems: + lines.append(" matches: outputs and inputs reproduce the recorded digests") + else: + for problem in problems: + lines.append(f" MISMATCH: {problem}") + lines.append( + " note: this verifies digests, not authorship -- no key was involved" + ) + return "\n".join(lines) + + +__all__ = [ + "Attestation", + "AttestationError", + "MAX_INPUTS", + "SCHEMA", + "build", + "digest_bytes", + "digest_paths", + "digest_payload", + "render_verification", + "verify", +] diff --git a/pathscope/audit.py b/pathscope/audit.py new file mode 100644 index 0000000..adbb80b --- /dev/null +++ b/pathscope/audit.py @@ -0,0 +1,288 @@ +"""Suppression audit (``--suppression-audit``). + +Every suppression mechanism in PathScope -- baselines, suppression files, +waivers, ledger acceptances -- hides something, and every hiding mechanism rots +in the same three ways: + +* **dead** -- it no longer matches anything, because the endpoint was renamed, + the parameter was removed or the finding changed rule. It is now pure noise + that looks like coverage; +* **overbroad** -- one entry hides far more than its author meant, usually + because a waiver named only a host; +* **expired** -- the acceptance outlived the date somebody attached to it. + +None of those are visible from a normal run, because a normal run is quiet by +design: suppressed rows are removed before rendering. This module reads the +suppression inputs and says what they are actually doing. + +An audit is read-only. It never removes a suppression and never un-hides a +finding; it reports, and a human edits the file. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Sequence, Set, Tuple + +from .detector import Baseline, Finding, Report +from .waivers import WaiverSet, waiver_matches + +#: One suppression hiding more than this many findings is called out. +OVERBROAD_THRESHOLD = 10 + + +@dataclass +class EntryUse: + """How much one suppression entry actually matched.""" + + key: str + label: str + matched: int = 0 + status: str = "dead" # live | dead | expired | overbroad + + @property + def dead(self) -> bool: + return self.status == "dead" + + def as_dict(self) -> Dict[str, object]: + return { + "key": self.key, + "label": self.label, + "matched": self.matched, + "status": self.status, + } + + +@dataclass +class AuditReport: + """Everything the audit found, grouped by suppression source.""" + + baseline_entries: List[EntryUse] = field(default_factory=list) + waiver_entries: List[EntryUse] = field(default_factory=list) + ledger_entries: List[EntryUse] = field(default_factory=list) + #: Fingerprints the ledger holds that this run never saw. + ledger_unmatched: int = 0 + findings_seen: int = 0 + hidden_by_status: Dict[str, int] = field(default_factory=dict) + + @property + def dead(self) -> List[EntryUse]: + return [ + entry + for entry in self.baseline_entries + self.waiver_entries + self.ledger_entries + if entry.dead + ] + + @property + def overbroad(self) -> List[EntryUse]: + return [ + entry + for entry in self.baseline_entries + self.waiver_entries + self.ledger_entries + if entry.status == "overbroad" + ] + + @property + def expired(self) -> List[EntryUse]: + return [ + entry + for entry in self.baseline_entries + self.waiver_entries + self.ledger_entries + if entry.status == "expired" + ] + + def as_dict(self) -> Dict[str, object]: + return { + "findings_seen": self.findings_seen, + "baseline": [entry.as_dict() for entry in self.baseline_entries], + "waivers": [entry.as_dict() for entry in self.waiver_entries], + "ledger": [entry.as_dict() for entry in self.ledger_entries], + "ledger_unmatched": self.ledger_unmatched, + "dead": len(self.dead), + "overbroad": len(self.overbroad), + "expired": len(self.expired), + } + + +def audit_baseline( + findings: Sequence[Finding], baseline: Baseline +) -> List[EntryUse]: + """Which baseline fingerprints still correspond to something.""" + seen: Set[str] = {finding.fingerprint for finding in findings} + entries: List[EntryUse] = [] + for fingerprint, note in sorted(baseline.fingerprints.items()): + label = f"{fingerprint}" + (f" ({note})" if note else "") + entry = EntryUse(key=fingerprint, label=label) + if fingerprint in seen: + entry.matched = 1 + entry.status = "live" + else: + entry.status = "dead" + entries.append(entry) + return entries + + +def audit_waivers( + findings: Sequence[Finding], + waivers: WaiverSet, + *, + today: Optional[str] = None, +) -> List[EntryUse]: + """How many findings each waiver hides, and what condition it is in.""" + entries: List[EntryUse] = [] + for waiver in waivers.waivers: + matched = sum(1 for finding in findings if waiver_matches(waiver, finding)) + entry = EntryUse(key=waiver.id, label=waiver.describe()) + entry.matched = matched + if waiver.expired(today): + entry.status = "expired" + elif matched == 0: + entry.status = "dead" + elif matched > OVERBROAD_THRESHOLD: + entry.status = "overbroad" + else: + entry.status = "live" + entries.append(entry) + return entries + + +def audit_ledger( + findings: Sequence[Finding], ledger_reviews: Sequence +) -> Tuple[List[EntryUse], int]: + """Which ledger reviews still match a finding, and how many match nothing. + + The ledger is keyed by fingerprint, which encodes host, location, parameter, + rule and resource -- so a renamed parameter or a rule change silently + orphans the review. + """ + seen: Set[str] = {finding.fingerprint for finding in findings} + entries: List[EntryUse] = [] + unmatched = 0 + for review in ledger_reviews: + fingerprint = getattr(review, "fingerprint", "") + status = getattr(review, "status", "reviewed") + entry = EntryUse( + key=fingerprint, + label=f"{getattr(review, 'host', '') or '?'} " + f"{getattr(review, 'parameter', '') or '?'} ({status})", + ) + if fingerprint in seen: + entry.matched = 1 + entry.status = "live" + else: + unmatched += 1 + entry.status = "dead" + entries.append(entry) + return entries, unmatched + + +def audit( + report: Report, + *, + baseline: Optional[Baseline] = None, + waivers: Optional[WaiverSet] = None, + ledger_reviews: Optional[Sequence] = None, + today: Optional[str] = None, +) -> AuditReport: + """Audit every suppression input against ``report``'s findings.""" + result = AuditReport(findings_seen=len(report.findings)) + if baseline is not None: + result.baseline_entries = audit_baseline(report.findings, baseline) + if waivers is not None: + result.waiver_entries = audit_waivers(report.findings, waivers, today=today) + if ledger_reviews is not None: + result.ledger_entries, result.ledger_unmatched = audit_ledger( + report.findings, ledger_reviews + ) + for finding in report.findings: + status = finding.status or "new" + result.hidden_by_status[status] = result.hidden_by_status.get(status, 0) + 1 + return result + + +def render_audit(result: AuditReport) -> str: + """``--suppression-audit`` as text.""" + lines = ["PathScope suppression audit", "=" * 84] + lines.append( + f"Audited against {result.findings_seen} finding(s) in this run " + f"(before any suppression is applied)." + ) + lines.append("") + + sections = ( + ("Baseline / suppression files", result.baseline_entries), + ("Waivers", result.waiver_entries), + ("Ledger reviews", result.ledger_entries), + ) + any_entries = False + for title, entries in sections: + if not entries: + continue + any_entries = True + lines.append(f"{title} ({len(entries)})") + for entry in entries: + marker = { + "live": "live ", + "dead": "DEAD ", + "expired": "EXPIRED ", + "overbroad": "OVERBROAD", + }.get(entry.status, entry.status) + lines.append( + f" [{marker}] {entry.label} -- matched {entry.matched} finding(s)" + ) + lines.append("") + + if not any_entries: + lines.append("No baselines, waivers or ledger reviews were supplied.") + lines.append("") + + dead = result.dead + overbroad = result.overbroad + expired = result.expired + + lines.append("Summary") + lines.append(f" live : {len(result.baseline_entries) + len(result.waiver_entries) + len(result.ledger_entries) - len(dead) - len(overbroad) - len(expired)}") + lines.append(f" dead : {len(dead)}") + lines.append(f" overbroad : {len(overbroad)}") + lines.append(f" expired : {len(expired)}") + lines.append("") + + if dead: + lines.append( + "Dead entries are the dangerous ones: they look like coverage in a " + "review and hide nothing in a run. Delete them, or re-point them at " + "the finding that replaced them." + ) + lines.append("") + if overbroad: + lines.append( + f"An entry matching more than {OVERBROAD_THRESHOLD} findings is " + "usually an accident (a waiver that named only a host). Narrow it " + "to a path or a parameter." + ) + lines.append("") + if expired: + lines.append( + "Expired entries no longer hide anything. Either renew them with a " + "new date and a reason, or remove them and fix the finding." + ) + lines.append("") + if not (dead or overbroad or expired): + lines.append("Every suppression still matches something it was meant to hide.") + lines.append("") + + lines.append( + "Suppressions are decisions with a shelf life. An audit is not a cleanup " + "tool: nothing here is removed automatically." + ) + return "\n".join(lines) + + +__all__ = [ + "AuditReport", + "EntryUse", + "OVERBROAD_THRESHOLD", + "audit", + "audit_baseline", + "audit_ledger", + "audit_waivers", + "render_audit", +] diff --git a/pathscope/ci.py b/pathscope/ci.py index b419efe..2ae2139 100644 --- a/pathscope/ci.py +++ b/pathscope/ci.py @@ -181,8 +181,13 @@ def render_github_annotations(report: Report) -> str: # --------------------------------------------------------------------------- def _selftest_checks() -> List[tuple]: """Assertions about this installation. Returns ``[(name, callable)]``.""" + import os as _os + from . import config, heuristics, sources, textutil, writers + def _join(*parts: str) -> str: + return _os.path.join(*parts) + def banner_exact() -> None: lines = banner_lines() assert len(lines) == 3, "expected three banner lines" @@ -508,6 +513,123 @@ def pr_comment_states_the_truth() -> None: "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 @@ -548,6 +670,12 @@ def completion_tracks_the_parser() -> None: ("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), ] diff --git a/pathscope/cli.py b/pathscope/cli.py index d33b7d5..0eb2fd0 100644 --- a/pathscope/cli.py +++ b/pathscope/cli.py @@ -34,7 +34,17 @@ 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 @@ -682,6 +692,119 @@ def build_parser() -> argparse.ArgumentParser: 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", @@ -1330,6 +1453,14 @@ def run( 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: @@ -1396,6 +1527,14 @@ def run( 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 @@ -1638,6 +1777,57 @@ def run( 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 ) @@ -1663,8 +1853,42 @@ def run( # 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: @@ -1760,6 +1984,71 @@ def run( ) 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: @@ -1889,6 +2178,57 @@ def run( 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: @@ -2029,7 +2369,7 @@ def _save(fingerprints): return EXIT_FINDINGS return EXIT_OK - if args.fail_on_findings and report_data.new_count: + if args.fail_on_findings and gate_candidate_count: return EXIT_FINDINGS return EXIT_OK @@ -2438,6 +2778,108 @@ def _handle_init_scope(args, stderr) -> int: 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) 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/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/policy.py b/pathscope/policy.py index 8f810cf..c3fdac4 100644 --- a/pathscope/policy.py +++ b/pathscope/policy.py @@ -175,6 +175,12 @@ def _eligible(finding: Finding, policy: Policy) -> bool: # 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 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/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/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/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/textutil.py b/pathscope/textutil.py index 5231a3a..f9df57e 100644 --- a/pathscope/textutil.py +++ b/pathscope/textutil.py @@ -96,6 +96,23 @@ def dedupe(items: Iterable[str]) -> List[str]: 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. 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/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 index aac80dd..a300682 100755 --- a/tests/test_path_detector.py +++ b/tests/test_path_detector.py @@ -1148,7 +1148,7 @@ def test_imports_are_standard_library_only(self): "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", + "calendar", "shlex", "hmac", "secrets", "datetime", "fnmatch", "hashlib", } for path in project_modules(): tree = ast.parse(path.read_text(encoding="utf-8"))