Skip to content

armgit / bbot

Public Imported from GitHub
0

The recursive internet scanner for hackers. 🧡

Selectively Replace DeepDiff Due to Performance Issues (#3340)

Paul Mueller58fe07e43b45
diff --git a/bbot/core/helpers/diff.py b/bbot/core/helpers/diff.py
index 7017cc914..24686d580 100644
--- a/bbot/core/helpers/diff.py
+++ b/bbot/core/helpers/diff.py
@@ -1,5 +1,8 @@
+import json
import logging
import xmltodict
+from time import monotonic
+from itertools import islice
from deepdiff import DeepDiff
from contextlib import suppress
from xml.parsers.expat import ExpatError
@@ -7,6 +10,138 @@ from bbot.errors import HttpCompareError
log = logging.getLogger("bbot.core.helpers.diff")
+# Body comparisons are linear, so they should take milliseconds. Log anything
+# wildly slower than that -- it means a body shape we didn't anticipate.
+SLOW_COMPARE_THRESHOLD = 2.0
+
+# Flattening a structured body costs memory proportional to its leaf count, and a
+# baseline is held for the lifetime of the HttpCompare. Past these limits, compare as
+# lines instead -- a body this big doesn't need leaf-level precision.
+MAX_STRUCTURED_BODY_SIZE = 2_000_000
+MAX_STRUCTURED_LEAVES = 10_000
+
+# Bodies with at least this many lines compare fine as lines; structure is only
+# needed for the few-line shape (a minified JSON or XML API response).
+MAX_STRUCTURED_LINES = 20
+
+_MISSING = object()
+
+
+def _tree_leaves(node, path=()):
+ """Flatten a parsed JSON/XML tree into (path, leaf_value) pairs."""
+ if isinstance(node, dict) and node:
+ for key, value in node.items():
+ yield from _tree_leaves(value, (*path, key))
+ elif isinstance(node, list) and node:
+ for i, value in enumerate(node):
+ yield from _tree_leaves(value, (*path, i))
+ else:
+ # scalars, and empty containers -- which compare unequal to each other
+ yield path, node
+
+
+class _LineBody:
+ """A response body compared as a list of lines.
+
+ Lines are matched by content rather than position, so a line that merely
+ moves is not a difference. Positions that varied between the two baseline
+ samples are filtered out, which is how volatile content (CSRF tokens,
+ timestamps, the echoed request path) is ignored.
+
+ Only the first occurrence of each differing line counts, so a volatile line
+ repeated down the page filters one position rather than every copy of it.
+ """
+
+ __slots__ = ("lines", "line_set")
+
+ def __init__(self, lines):
+ self.lines = lines
+ self.line_set = set(lines)
+
+ def _novel_lines(self, other_set):
+ """(position, line) for the first occurrence of each line absent from `other_set`."""
+ seen = set()
+ for i, line in enumerate(self.lines):
+ if line not in other_set and line not in seen:
+ seen.add(line)
+ yield i, line
+
+ def volatile_paths(self, other):
+ """Positions of the first occurrence of each line not present anywhere in `other`."""
+ return {i for i, _ in self._novel_lines(other.line_set)}
+
+ def matches(self, other, filtered):
+ for body, other_set in ((self, other.line_set), (other, self.line_set)):
+ for i, _ in body._novel_lines(other_set):
+ if i not in filtered:
+ return False
+ return True
+
+
+class _StructuredBody:
+ """A JSON or XML response body, compared leaf-by-leaf and keyed by path.
+
+ Paths are stable across requests, so volatile leaves are filtered by path.
+ That works even for a body served on a single line -- the usual shape for a
+ JSON API -- where a line-oriented comparison sees one volatile line and then
+ considers every subsequent body a match.
+ """
+
+ __slots__ = ("leaves",)
+
+ def __init__(self, leaves):
+ self.leaves = leaves
+
+ def volatile_paths(self, other):
+ """Element paths whose leaf value differs from `other`, or is missing on either side."""
+ volatile = {path for path, value in self.leaves.items() if other.leaves.get(path, _MISSING) != value}
+ volatile.update(path for path in other.leaves if path not in self.leaves)
+ return volatile
+
+ def matches(self, other, filtered):
+ for path in self.leaves.keys() | other.leaves.keys():
+ if path in filtered:
+ continue
+ if self.leaves.get(path, _MISSING) != other.leaves.get(path, _MISSING):
+ return False
+ return True
+
+
+def _structured(tree):
+ """A `_StructuredBody` for `tree`, or None if it has too many leaves to hold."""
+ leaves = dict(islice(_tree_leaves(tree), MAX_STRUCTURED_LEAVES + 1))
+ if len(leaves) > MAX_STRUCTURED_LEAVES:
+ return None
+ return _StructuredBody(leaves)
+
+
+def parse_body(text):
+ """Parse a response body into its comparable form.
+
+ Few-line JSON and XML are compared leaf-by-leaf; everything else as a list of lines.
+ Malformed, oversized, or pathologically nested input falls back to lines.
+ """
+ lines = text.split("\n")
+ if len(lines) < MAX_STRUCTURED_LINES and len(text) <= MAX_STRUCTURED_BODY_SIZE:
+ with suppress(ExpatError, RecursionError):
+ if (body := _structured(xmltodict.parse(text))) is not None:
+ return body
+ with suppress(ValueError, RecursionError):
+ tree = json.loads(text)
+ # a bare scalar gives one leaf, which is no better than one line
+ if isinstance(tree, (dict, list)) and (body := _structured(tree)) is not None:
+ return body
+ return _LineBody(lines)
+
+
+def _as_body(content):
+ """Coerce an already-parsed body (or a raw dict / line list) into a comparable body."""
+ if isinstance(content, (_LineBody, _StructuredBody)):
+ return content
+ if isinstance(content, dict):
+ return _StructuredBody(dict(_tree_leaves(content)))
+ return _LineBody(list(content))
+
class _BaselineSnapshot:
"""Lightweight stand-in for a blasthttp Response held by HttpCompare.
@@ -96,6 +231,8 @@ class HttpCompare:
self.json = json
self.allow_redirects = allow_redirects
self._baselined = False
+ # Positions/paths in the baseline body that varied between the two samples.
+ self.body_filters = set()
self.headers = headers
self.cookies = cookies
self.timeout = 10
@@ -164,23 +301,10 @@ class HttpCompare:
log.debug("Status code not stable during baseline, aborting")
raise HttpCompareError("Can't get baseline from source URL")
- try:
- baseline_1_json = xmltodict.parse(baseline_1.text)
- baseline_2_json = xmltodict.parse(baseline_2.text)
- except ExpatError:
- baseline_1_json = baseline_1.text.split("\n")
- baseline_2_json = baseline_2.text.split("\n")
-
- ddiff = DeepDiff(
- baseline_1_json, baseline_2_json, ignore_order=True, view="tree", threshold_to_diff_deeper=0
+ # Parsing and diffing two full response bodies is CPU-bound; keep it off the event loop.
+ self.baseline_body, self.body_filters = await self.parent_helper.run_in_executor_cpu(
+ self._baseline_bodies, baseline_1.text, baseline_2.text
)
- self.ddiff_filters = []
-
- for k in ddiff.keys():
- for x in list(ddiff[k]):
- self.ddiff_filters.append(x.path())
-
- self.baseline_json = baseline_1_json
self.baseline_ignore_headers = [
h.lower()
for h in [
@@ -212,6 +336,16 @@ class HttpCompare:
store = getattr(scan, "body_spill_store", None)
self.baseline = _BaselineSnapshot(baseline_1, spill_store=store)
+ @staticmethod
+ def _baseline_bodies(text_1, text_2):
+ """Parse both baseline samples and work out which parts of the response are volatile."""
+ body_1, body_2 = parse_body(text_1), parse_body(text_2)
+ if type(body_1) is not type(body_2):
+ # the samples disagree on a representation (one was truncated, say),
+ # so compare them as lines -- that always works
+ body_1, body_2 = _LineBody(text_1.split("\n")), _LineBody(text_2.split("\n"))
+ return body_1, body_1.volatile_paths(body_2)
+
def gen_cache_buster(self):
return {self.parent_helper.rand_string(6): "1"}
@@ -235,23 +369,30 @@ class HttpCompare:
differing_headers.append(header_value)
return differing_headers
+ @staticmethod
+ def parse_body(text):
+ """Parse a response body into the form compare_body() expects."""
+ return parse_body(text)
+
def compare_body(self, content_1, content_2):
+ """Whether two bodies match, ignoring the parts observed to be volatile.
+
+ Takes bodies parsed by `parse_body`. Callers that normalize response text
+ themselves (stripping their own reflected probe values, say) may pass raw
+ strings instead, which are compared verbatim.
+ """
if content_1 == content_2:
return True
- ddiff = DeepDiff(
- content_1,
- content_2,
- ignore_order=True,
- view="tree",
- exclude_paths=self.ddiff_filters,
- threshold_to_diff_deeper=0,
- )
+ if isinstance(content_1, str) or isinstance(content_2, str):
+ # raw text, already normalized by the caller -- no volatile parts to filter
+ return False
- if len(ddiff.keys()) == 0:
- return True
- else:
+ body_1, body_2 = _as_body(content_1), _as_body(content_2)
+ if type(body_1) is not type(body_2):
+ # one body is structured and the other isn't -- that alone is a difference
return False
+ return body_1.matches(body_2, self.body_filters)
async def compare(
self,
@@ -331,18 +472,10 @@ class HttpCompare:
else:
return (False, diff_reasons, reflection, subject_response)
- @staticmethod
- def parse_body(text):
- """Parse a response body into the structure compare_body() expects. Passing raw text works
- but bypasses the ddiff_filters that mask dynamic content."""
- try:
- return xmltodict.parse(text)
- except ExpatError:
- return text.split("\n")
-
def _compare_sync(self, subject_response, subject):
"""CPU-bound comparison work offloaded from the event loop."""
- subject_json = self.parse_body(subject_response.text)
+ started = monotonic()
+ subject_body = parse_body(subject_response.text)
diff_reasons = []
@@ -353,9 +486,13 @@ class HttpCompare:
if different_headers:
diff_reasons.append("header")
- if self.compare_body(self.baseline_json, subject_json) is False:
+ if self.compare_body(self.baseline_body, subject_body) is False:
diff_reasons.append("body")
+ elapsed = monotonic() - started
+ if elapsed > SLOW_COMPARE_THRESHOLD:
+ log.debug(f"Slow body comparison ({elapsed:.1f}s, {len(subject_response.text):,} bytes) for {subject}")
+
return diff_reasons
async def canary_check(self, url, mode, rounds=3):
diff --git a/bbot/test/test_step_1/test_http_compare.py b/bbot/test/test_step_1/test_http_compare.py
new file mode 100644
index 000000000..dd3898583
--- /dev/null
+++ b/bbot/test/test_step_1/test_http_compare.py
@@ -0,0 +1,460 @@
+"""
+Tests for HTTP body comparison (``bbot.core.helpers.diff``).
+
+``HttpCompare`` answers one question: is this response body the same as the
+baseline, ignoring the parts observed to be volatile? These tests pin down that
+contract and the cost of answering it.
+
+ - ``TestLineBodyComparison``: HTML/text bodies, compared as lines.
+ - ``TestXmlBodyComparison``: XML bodies, compared leaf-by-leaf by element path.
+ - ``TestComparisonCost``: the comparison stays linear, and body parsing stays
+ off the event loop. A body comparison holds the GIL for its whole duration,
+ so a superlinear one stalls every module in the scan, not just its caller.
+"""
+
+import itertools
+import json
+import re
+import time
+from urllib.parse import urlparse
+
+import pytest
+
+from bbot.core.helpers.diff import (
+ MAX_STRUCTURED_BODY_SIZE,
+ MAX_STRUCTURED_LEAVES,
+ MAX_STRUCTURED_LINES,
+ HttpCompare,
+ _LineBody,
+ _StructuredBody,
+ parse_body,
+)
+from bbot.test.mock_blasthttp import MockResponse
+
+from ..bbot_fixtures import * # noqa: F401, F403
+
+NAV = [f' <li class="nav n{i}"><a href="/section/{i}">Section {i}</a></li>' for i in range(60)]
+
+
+def render(*, path="/x", token="tok", ts="1000", rows=20, echo_rows=10, promos=0, injected=None, rowsalt="a"):
+ """A page whose volatile parts are a CSRF token, a timestamp, and the echoed request path."""
+ lines = ["<!DOCTYPE html>", "<html lang=en>", "<head>", f' <meta name="csrf" content="{token}">']
+ lines += [" <title>Acme</title>", "</head>", "<body>", f" <!-- generated {ts} -->"]
+ lines.append(f" <p>No such page: <code>{path}</code></p>")
+ if injected:
+ lines.append(injected)
+ lines += [f' <div class="promo" data-slot="{j}">Promo {j}</div>' for j in range(promos)]
+ lines += NAV
+ lines += [f' <li class="item i{i}"><span>{rowsalt} row {i}</span></li>' for i in range(rows)]
+ lines += [f' <a class="rel" href="{path}/rel/{i}">related {i}</a>' for i in range(echo_rows)]
+ return "\n".join(lines + [" <footer>&copy; Acme</footer>", "</body>", "</html>"])
+
+
+def compare_bodies(baseline_1, baseline_2, subject):
+ """Derive the volatile-content filter from two baseline samples, then compare a subject against it."""
+ baseline_body, filters = HttpCompare._baseline_bodies(baseline_1, baseline_2)
+ comparer = HttpCompare.__new__(HttpCompare)
+ comparer.body_filters = filters
+ return comparer.compare_body(baseline_body, parse_body(subject))
+
+
+class TestLineBodyComparison:
+ def test_html_parses_as_lines(self):
+ # real-world HTML is not well-formed XML, so it lands on the line path
+ assert isinstance(parse_body(render()), _LineBody)
+
+ def test_volatile_content_is_ignored(self):
+ """A catch-all host serving the same page with a new token/timestamp/path still matches."""
+ baseline_1 = render(path="/aaaaaa/bbbb", token="t1", ts="100")
+ baseline_2 = render(path="/cccccc/dddd", token="t2", ts="200")
+ assert compare_bodies(baseline_1, baseline_2, render(path="/", token="t3", ts="300")) is True
+
+ def test_identical_body_matches(self):
+ body = render(path="/aaaaaa", token="t1", ts="100")
+ assert compare_bodies(body, render(path="/cccccc", token="t2", ts="200"), body) is True
+
+ @pytest.mark.parametrize(
+ "subject_kwargs,description",
+ [
+ ({"injected": " <div class=err>SQL syntax error near unexpected token</div>"}, "injected error line"),
+ ({"injected": " <pre>at com.acme.Handler(Handler.java:44)</pre>"}, "injected stack trace"),
+ ({"rowsalt": "z"}, "different row content"),
+ ({"rows": 40}, "extra rows"),
+ ({"rows": 5}, "missing rows"),
+ ({"promos": 4}, "extra block"),
+ ],
+ )
+ def test_real_change_is_detected(self, subject_kwargs, description):
+ """Volatile-content filtering must not swallow an actual change to the page."""
+ baseline_1 = render(path="/aaaaaa/bbbb", token="t1", ts="100")
+ baseline_2 = render(path="/cccccc/dddd", token="t2", ts="200")
+ subject = render(path="/", token="t3", ts="300", **subject_kwargs)
+ assert compare_bodies(baseline_1, baseline_2, subject) is False, f"failed to detect {description}"
+
+ def test_stable_baseline_requires_exact_match(self):
+ """With no volatile content, nothing is filtered, so a single added line is a difference."""
+ baseline = render(path="/same", token="tok", ts="1")
+ assert compare_bodies(baseline, baseline, baseline) is True
+ subject = render(path="/same", token="tok", ts="1", injected=" <div>hello</div>")
+ assert compare_bodies(baseline, baseline, subject) is False
+
+ def test_comparison_is_order_insensitive(self):
+ """Lines are matched by content, not position, so a reordered body still matches."""
+ baseline = "\n".join(["<html>", "<a>", "<b>", "<c>", "</html>"])
+ reordered = "\n".join(["<html>", "<c>", "<b>", "<a>", "</html>"])
+ assert compare_bodies(baseline, baseline, reordered) is True
+
+ def test_empty_bodies(self):
+ assert compare_bodies("", "", "") is True
+ assert compare_bodies("", "", "something") is False
+
+ @staticmethod
+ def repeated(nonce, changed=None):
+ """A page repeating one identical volatile line, optionally with one copy replaced."""
+ rows = [f'<script nonce="{nonce}">track()</script>' for _ in range(20)]
+ if changed is not None:
+ rows[changed] = "<div>admin panel</div>"
+ return "\n".join(["<html>", *(f"<p>static {i}</p>" for i in range(10)), *rows, "</html>"])
+
+ def test_repeated_volatile_line_filters_one_position(self):
+ """A volatile line repeated down the page must not hide a real change to one of its copies."""
+ assert compare_bodies(self.repeated("a"), self.repeated("b"), self.repeated("c")) is True
+ assert compare_bodies(self.repeated("a"), self.repeated("b"), self.repeated("c", changed=7)) is False
+
+ def test_change_to_first_copy_of_repeated_line_is_detected(self):
+ """Replacing the first copy moves the volatile line's first occurrence off the filtered position."""
+ assert compare_bodies(self.repeated("a"), self.repeated("b"), self.repeated("c", changed=0)) is False
+
+
+class TestRawTextComparison:
+ """``compare_body`` also takes raw response text, which is compared verbatim.
+
+ lightfuzz's crypto submodule strips its own reflected probe values out of two
+ responses and then compares what's left, so it needs an exact comparison and
+ no volatile-content filtering. Raw text must not be treated as a sequence of
+ characters, which would make anagrams compare equal.
+ """
+
+ @staticmethod
+ def comparer(filters=None):
+ comparer = HttpCompare.__new__(HttpCompare)
+ comparer.body_filters = filters if filters is not None else set()
+ return comparer
+
+ def test_identical_text_matches(self):
+ assert self.comparer().compare_body("invalid padding", "invalid padding") is True
+
+ def test_differing_text_does_not_match(self):
+ assert self.comparer().compare_body("invalid padding", "decryption failed") is False
+
+ def test_anagrams_do_not_match(self):
+ assert self.comparer().compare_body("abc", "cba") is False
+
+ def test_single_character_difference_is_detected(self):
+ """Padding-oracle detection turns on differences this small."""
+ assert self.comparer().compare_body("result: 0x41", "result: 0x42") is False
+
+ def test_filters_do_not_apply_to_raw_text(self):
+ """A filter derived from a line-based baseline must not suppress a raw-text difference."""
+ assert self.comparer(filters={0, 1, 2}).compare_body("invalid padding", "valid padding") is False
+
+
+class TestXmlBodyComparison:
+ @staticmethod
+ def xml(*, token="tok", rows=20, changed=False):
+ rows_xml = "".join(
+ f"<row id='{i}'><name>{'CHANGED' if changed and i == 5 else f'item {i}'}</name><ref>static-{i}</ref></row>"
+ for i in range(rows)
+ )
+ return f"<catalog><meta><token>{token}</token></meta>{rows_xml}</catalog>"
+
+ def test_xml_parses_structurally(self):
+ assert isinstance(parse_body(self.xml()), _StructuredBody)
+
+ def test_volatile_leaf_is_ignored(self):
+ assert compare_bodies(self.xml(token="a"), self.xml(token="b"), self.xml(token="c")) is True
+
+ def test_real_element_change_is_detected(self):
+ subject = self.xml(token="c", changed=True)
+ assert compare_bodies(self.xml(token="a"), self.xml(token="b"), subject) is False
+
+ def test_single_line_xml(self):
+ """XML is keyed by element path, so it compares correctly with no line breaks to split on.
+
+ A line-oriented comparison would see the whole document as one volatile
+ line and consider every subsequent body a match.
+ """
+ assert "\n" not in self.xml()
+ assert compare_bodies(self.xml(token="a"), self.xml(token="b"), self.xml(token="c")) is True
+ assert compare_bodies(self.xml(token="a"), self.xml(token="b"), self.xml(token="c", changed=True)) is False
+
+ def test_xml_versus_non_xml_is_a_difference(self):
+ assert compare_bodies(self.xml(token="a"), self.xml(token="b"), render()) is False
+
+ def test_multiline_xhtml_is_compared_as_lines(self):
+ """Well-formed XHTML parses as XML, but a many-line page compares fine as lines and costs far less to hold."""
+ xhtml = "\n".join(
+ ["<html><body>", *(f"<p>row {i}</p>" for i in range(MAX_STRUCTURED_LINES)), "</body></html>"]
+ )
+ assert isinstance(parse_body(xhtml), _LineBody)
+
+ def test_samples_disagreeing_on_representation_fall_back_to_lines(self):
+ """If only one sample parses as XML, both are compared as lines rather than by structure."""
+ baseline_body, _ = HttpCompare._baseline_bodies(self.xml(), render())
+ assert isinstance(baseline_body, _LineBody)
+
+
+class TestJsonBodyComparison:
+ """JSON APIs answer on a single line, so they need leaf-level comparison.
+
+ Compared as lines, such a body is one line -- and if anything in it is
+ volatile, that single line is filtered and every subsequent body matches,
+ making the comparison useless for the modules that depend on it.
+ """
+
+ @staticmethod
+ def api(*, token="tok", rows=6, changed=False, extra=None):
+ body = {
+ "meta": {"csrf": token, "page": 1},
+ "results": [
+ {"id": i, "name": "CHANGED" if changed and i == 3 else f"item {i}", "tags": ["a", "b"]}
+ for i in range(rows)
+ ],
+ }
+ if extra is not None:
+ body["error"] = extra
+ return json.dumps(body)
+
+ def test_json_parses_structurally(self):
+ assert isinstance(parse_body(self.api()), _StructuredBody)
+
+ def test_json_is_served_on_one_line(self):
+ assert "\n" not in self.api()
+
+ def test_volatile_field_is_ignored(self):
+ assert compare_bodies(self.api(token="a"), self.api(token="b"), self.api(token="c")) is True
+
+ @pytest.mark.parametrize(
+ "subject_kwargs,description",
+ [
+ ({"changed": True}, "changed value in a nested array"),
+ ({"extra": "stack trace"}, "added top-level key"),
+ ({"rows": 8}, "extra array elements"),
+ ({"rows": 2}, "missing array elements"),
+ ],
+ )
+ def test_real_change_is_detected(self, subject_kwargs, description):
+ """The regression this guards: with a volatile field present, every one of
+ these previously compared as a match, so nothing was ever detected."""
+ subject = self.api(token="c", **subject_kwargs)
+ assert compare_bodies(self.api(token="a"), self.api(token="b"), subject) is False, (
+ f"failed to detect {description}"
+ )
+
+ def test_array_reordering_is_detected(self):
+ """Leaves are keyed by path, so JSON array order is significant."""
+ forward = json.dumps({"items": [1, 2, 3]})
+ reversed_ = json.dumps({"items": [3, 2, 1]})
+ assert compare_bodies(forward, forward, reversed_) is False
+
+ def test_bare_scalar_is_compared_as_lines(self):
+ """A scalar body flattens to a single leaf, which is no better than one line."""
+ assert isinstance(parse_body("42"), _LineBody)
+ assert isinstance(parse_body('"just a string"'), _LineBody)
+ assert isinstance(parse_body("null"), _LineBody)
+
+ def test_empty_containers_are_distinguished(self):
+ assert compare_bodies('{"a": {}}', '{"a": {}}', '{"a": []}') is False
+ assert compare_bodies('{"a": {}}', '{"a": {}}', '{"a": {"b": 1}}') is False
+
+ def test_oversized_body_is_compared_as_lines(self):
+ """Flattening is bounded so a huge body can't pin a big leaf map to the baseline."""
+ oversized = json.dumps({"padding": "x" * MAX_STRUCTURED_BODY_SIZE})
+ assert len(oversized) > MAX_STRUCTURED_BODY_SIZE
+ assert isinstance(parse_body(oversized), _LineBody)
+
+ def test_body_with_too_many_leaves_is_compared_as_lines(self):
+ """The leaf map is bounded by leaf count, not just text size, since dense JSON packs many leaves per byte."""
+ dense = json.dumps(list(range(MAX_STRUCTURED_LEAVES + 1)))
+ assert len(dense) <= MAX_STRUCTURED_BODY_SIZE
+ assert isinstance(parse_body(dense), _LineBody)
+ assert isinstance(parse_body(json.dumps(list(range(MAX_STRUCTURED_LEAVES)))), _StructuredBody)
+
+ def test_pretty_printed_json_is_compared_as_lines(self):
+ """One leaf per line already gives line comparison the granularity it needs."""
+ pretty = json.loads(self.api())
+ assert isinstance(parse_body(json.dumps(pretty, indent=2)), _LineBody)
+ baseline_1, baseline_2 = (json.dumps(json.loads(self.api(token=t)), indent=2) for t in "ab")
+ assert compare_bodies(baseline_1, baseline_2, json.dumps(json.loads(self.api(token="c")), indent=2)) is True
+ changed = json.dumps(json.loads(self.api(token="c", changed=True)), indent=2)
+ assert compare_bodies(baseline_1, baseline_2, changed) is False
+
+ def test_malformed_json_is_compared_as_lines(self):
+ assert isinstance(parse_body('{"a": 1,,}'), _LineBody)
+ assert isinstance(parse_body("{unterminated"), _LineBody)
+
+ def test_deeply_nested_json_does_not_raise(self):
+ """Untrusted bodies can be nested past the recursion limit; that must degrade, not crash."""
+ nested = "[" * 5000 + "]" * 5000
+ assert isinstance(parse_body(nested), _LineBody)
+
+
+class TestBaselineIntegration:
+ """End-to-end coverage of the real baseline-then-compare flow over HTTP.
+
+ The comparisons above are driven directly. These go through ``_baseline()``
+ and ``compare()``, so response parsing, the executor hop, header comparison
+ and the diff-reason plumbing are all exercised together against a JSON API --
+ the single-line body shape those modules see most often in practice.
+ """
+
+ @staticmethod
+ def json_api(escalated_paths=()):
+ """A JSON API with a volatile request id, served on a single line."""
+ counter = itertools.count()
+
+ def callback(request):
+ path = urlparse(str(request.url)).path
+ payload = {
+ "request_id": f"req-{next(counter)}",
+ "user": {"name": "alice", "role": "admin"},
+ "items": [{"id": 1, "label": "one"}, {"id": 2, "label": "two"}],
+ }
+ if any(path.endswith(p) for p in escalated_paths):
+ payload["user"]["role"] = "superuser"
+ return MockResponse(status_code=200, text=json.dumps(payload))
+
+ return callback
+
+ @pytest.mark.asyncio
+ async def test_json_api_filters_only_the_volatile_field(self, bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner()
+ await scan._prep()
+ blasthttp_mock.add_callback(callback=self.json_api(escalated_paths=("/escalated",)))
+
+ comparer = scan.helpers.http_compare("http://jsonapi.example.com/api")
+ await comparer._baseline()
+
+ assert isinstance(comparer.baseline_body, _StructuredBody)
+ # exactly one leaf is volatile -- not the whole body
+ assert comparer.body_filters == {("request_id",)}
+
+ match, reasons, _, _ = await comparer.compare("http://jsonapi.example.com/api")
+ assert match is True, f"volatile request_id should have been filtered, got {reasons}"
+
+ match, reasons, _, _ = await comparer.compare("http://jsonapi.example.com/api/escalated")
+ assert match is False, "a changed nested field was not detected"
+ assert "body" in reasons, f"expected a body difference, got {reasons}"
+
+ await scan._cleanup()
+
+ @pytest.mark.asyncio
+ async def test_json_catchall_host_is_detected_as_wildcard(self, bbot_scanner, blasthttp_mock):
+ """Wildcard detection reaches the comparison from the web helper, on any scan."""
+ scan = bbot_scanner()
+ await scan._prep()
+ blasthttp_mock.add_callback(callback=self.json_api())
+
+ result = await scan.helpers.web.is_http_wildcard_host("http", "catchall.example.com", 80)
+
+ assert result not in (False, None), "JSON catch-all host was not detected as a wildcard responder"
+ assert isinstance(result.baseline_body, _StructuredBody)
+
+ await scan._cleanup()
+
+ @pytest.mark.asyncio
+ async def test_json_host_distinguishing_paths_is_not_a_wildcard(self, bbot_scanner, blasthttp_mock):
+ """The root serves a different payload than the random probe paths, so this host is real."""
+ scan = bbot_scanner()
+ await scan._prep()
+ blasthttp_mock.add_callback(callback=self.json_api(escalated_paths=("/",)))
+
+ result = await scan.helpers.web.is_http_wildcard_host("http", "realsite.example.com", 80)
+
+ assert result is False, f"host distinguishes responses by path but was reported as {result!r}"
+
+ await scan._cleanup()
+
+
+class TestComparisonCost:
+ @staticmethod
+ def echo_page(boilerplate_lines, echoed_lines, path):
+ """A large catch-all page that echoes the request path into many otherwise-identical lines.
+
+ This is the shape that stalls: the differing lines are numerous but each
+ is nearly identical to its counterpart, which is the worst case for
+ similarity-based diff pairing.
+ """
+ lines = ["<!DOCTYPE html>", "<html>", "<head>", "</head>", "<body>"]
+ lines += [
+ f' <li class="nav n{i}"><a href="/section/{i}">Section {i}</a></li>' for i in range(boilerplate_lines)
+ ]
+ lines += [
+ f' <li class="rel r{i}"><a href="{path}/related/{i}">related item {i}</a></li>'
+ for i in range(echoed_lines)
+ ]
+ return "\n".join(lines + ["</body>", "</html>"])
+
+ def test_large_similar_bodies_compare_quickly(self):
+ """An 8000-line catch-all page must not take minutes to compare.
+
+ Similarity-based diff pairing is quadratic in the number of differing
+ lines: this shape measured ~64s, and doubling it reached ~260s. The bound
+ below is deliberately loose -- it is here to catch a return to
+ superlinear cost, not to police small regressions.
+ """
+ baseline_1 = self.echo_page(6400, 1600, "/aaaaaaaaaaaa/bbbbbbbb")
+ baseline_2 = self.echo_page(6400, 1600, "/cccccccccccc/dddddddd")
+ subject = self.echo_page(6400, 1600, "/")
+
+ started = time.monotonic()
+ result = compare_bodies(baseline_1, baseline_2, subject)
+ elapsed = time.monotonic() - started
+
+ # same page, only the echoed path differs -- this host answers everything alike
+ assert result is True
+ assert elapsed < 10, f"comparison of an 8000-line body took {elapsed:.1f}s"
+
+ def test_cost_scales_linearly(self):
+ """Doubling the body must not quadruple the work."""
+
+ def timed(boilerplate, echoed):
+ pages = [self.echo_page(boilerplate, echoed, p) for p in ("/aaaaaaaa/bbbb", "/cccccccc/dddd", "/")]
+ started = time.monotonic()
+ compare_bodies(*pages)
+ return time.monotonic() - started
+
+ timed(400, 100) # warm up, so import/allocation costs don't skew the ratio
+ small = min(timed(1600, 400) for _ in range(3))
+ large = min(timed(6400, 1600) for _ in range(3))
+
+ # 4x the input. Linear would be ~4x; the quadratic behaviour was ~16x.
+ assert large < small * 8, f"4x the body took {large / small:.1f}x the time ({small:.3f}s -> {large:.3f}s)"
+
+ @pytest.mark.asyncio
+ async def test_baseline_body_parsing_runs_off_the_event_loop(self, bbot_scanner, blasthttp_mock):
+ """Parsing and diffing two full bodies is CPU-bound; it must not run on the event loop.
+
+ A comparison holds the GIL for its whole duration, so doing it inline
+ stalls every module in the scan.
+ """
+ scan = bbot_scanner()
+ await scan._prep()
+ blasthttp_mock.add_response(url=re.compile(r"http://cost\.example\.com.*"), text=render())
+
+ executor_calls = []
+ original = scan.helpers.run_in_executor_cpu
+
+ def recording_executor(callback, *args, **kwargs):
+ executor_calls.append(getattr(callback, "__name__", repr(callback)))
+ return original(callback, *args, **kwargs)
+
+ scan.helpers.run_in_executor_cpu = recording_executor
+
+ comparer = scan.helpers.http_compare("http://cost.example.com")
+ await comparer._baseline()
+
+ assert "_baseline_bodies" in executor_calls, f"baseline parsing ran on the event loop: {executor_calls}"
+ assert isinstance(comparer.baseline_body, _LineBody)
+
+ await scan._cleanup()