From 5cdce11cc622390137a74a2f242049be3cf97c0b Mon Sep 17 00:00:00 2001 From: Akeem King <13573860+KingAkeem@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:41:13 -0500 Subject: [PATCH] Bound crawl requests, deduplicate traversal, and upgrade Soup Sieve --- .github/workflows/flake8.yml | 2 +- .github/workflows/pytest.yml | 2 +- Dockerfile | 4 +- README.md | 4 +- pyproject.toml | 5 +- requirements.txt | 2 +- src/torbot/modules/info.py | 6 +- src/torbot/modules/linktree.py | 138 ++++++++++++++++++--------------- tests/test_crawl_limits.py | 66 ++++++++++++++++ tests/test_export_paths.py | 3 +- tests/test_linktree_tree.py | 12 +-- 11 files changed, 163 insertions(+), 81 deletions(-) create mode 100644 tests/test_crawl_limits.py diff --git a/.github/workflows/flake8.yml b/.github/workflows/flake8.yml index dd84f620..170d028e 100644 --- a/.github/workflows/flake8.yml +++ b/.github/workflows/flake8.yml @@ -15,7 +15,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.10", "3.11", "3.12"] + python-version: ["3.11", "3.12"] steps: - name: Check out repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 98347a4f..92c65e40 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -15,7 +15,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.10", "3.11", "3.12"] + python-version: ["3.11", "3.12"] steps: - name: Check out repository diff --git a/Dockerfile b/Dockerfile index 71d8f407..4bb68ffa 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ -# Use an official Python 3.11.4 image as the base -FROM python:3.11.4 +# Use an official Python 3.11 image as the base +FROM python:3.11 # Set a working directory within the container WORKDIR /app diff --git a/README.md b/README.md index 6f1fa5cb..0489cbb6 100755 --- a/README.md +++ b/README.md @@ -48,9 +48,11 @@ ### Dependencies - Tor (Optional) -- Python 3.10+ +- Python 3.11.5+ - pip +The link crawler visits up to 100 distinct pages per crawl, including the starting URL and failed requests. It accepts up to 1 MiB per response and requests uncompressed HTML. Oversized or compressed child pages are recorded as failed. + ## Quick start ### Local setup diff --git a/pyproject.toml b/pyproject.toml index c3ac6956..2a7bbded 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,10 +11,9 @@ authors = [ ] description = "TorBot is an OSINT tool for the dark web." readme = "README.md" -requires-python = ">=3.10" +requires-python = ">=3.11.5" classifiers = [ "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Operating System :: OS Independent", @@ -37,7 +36,7 @@ dependencies = [ "scikit-learn>=1.5.0", "scipy>=1.13.0", "six>=1.16.0", - "soupsieve>=2.8.4", + "soupsieve>=4.1.3", "termcolor>=2.4.0", "texttable>=1.7.0", "threadpoolctl>=3.5.0", diff --git a/requirements.txt b/requirements.txt index ffd989d1..d1600c77 100644 --- a/requirements.txt +++ b/requirements.txt @@ -31,7 +31,7 @@ setuptools==84.1.0 six==1.16.0 sniffio==1.3.1 socksio==1.0.0 -soupsieve==2.9 +soupsieve==4.1.3 tabulate==0.9.0 termcolor==2.4.0 texttable==1.7.0 diff --git a/src/torbot/modules/info.py b/src/torbot/modules/info.py index 53c84b63..02af3133 100644 --- a/src/torbot/modules/info.py +++ b/src/torbot/modules/info.py @@ -90,8 +90,10 @@ def execute_all( def fetch_html( client: httpx.Client, link: str, tree: LinkTree, save_html: bool = False ) -> None: - resp = client.get(url=link) - soup = BeautifulSoup(resp.text, "html.parser") + html = tree.root_html if link == tree.root else None + if html is None: + html = client.get(url=link).text + soup = BeautifulSoup(html, "html.parser") if save_html is False: print(f""" diff --git a/src/torbot/modules/linktree.py b/src/torbot/modules/linktree.py index 8299d348..56d5fa28 100644 --- a/src/torbot/modules/linktree.py +++ b/src/torbot/modules/linktree.py @@ -7,6 +7,7 @@ import logging import os import re +from collections import deque from datetime import datetime, timezone from time import monotonic from urllib import parse @@ -16,7 +17,7 @@ import validators from bs4 import BeautifulSoup from tabulate import tabulate -from treelib import Node, Tree, exceptions +from treelib import Node, Tree from .color import color from .config import project_root_directory @@ -52,82 +53,91 @@ def __init__( class LinkTree(Tree): + MAX_PAGES = 100 + MAX_RESPONSE_BYTES = 1024 * 1024 + def __init__(self, url: str, depth: int, client: httpx.Client) -> None: super().__init__() self._url = url self._depth = depth self._client = client + self.root_html: str | None = None self.crawl_failures: list[dict] = [] def load(self) -> None: + from torbot.crawl_result import failed_page + + if self.root is not None: + return self.crawl_started_at = datetime.now(timezone.utc) self.crawl_started_monotonic = monotonic() - self._append_node(id=self._url, parent_id=None) - self._build_tree(url=self._url, depth=self._depth) - - def _append_node(self, id: str, parent_id: str or None) -> None: - """ - Creates a node for a tree using the given ID which corresponds to a URL. - If the parent_id is None, this will be considered a root node. - """ - try: - resp = self._client.get(id) - except Exception as exc: - logging.warning("Skipping URL %s due to request error: %s", id, exc) - raise RequestError(str(exc)) from exc - - if not getattr(resp, "text", None): - logging.warning("Skipping URL %s because the response body was empty", id) - raise RequestError("empty response") - - soup = BeautifulSoup(resp.text, "html.parser") - title = ( - soup.title.text.strip() if soup.title is not None else parse_hostname(id) - ) - text = extract_visible_text(soup) - try: - [classification, accuracy] = classify(resp.text) - numbers = parse_phone_numbers(soup) - emails = parse_emails(soup) + pending = deque([(self._url, None, 0)]) + # Reserve a slot before enqueueing, including for requests that later fail. + visited = {self._request_key(self._url)} + while pending: + url, parent, depth = pending.popleft() + try: + html, status = self._fetch_page(url) + except RequestError as exc: + if parent is None: + raise + self.crawl_failures.append(failed_page(url, parent, depth, exc)) + continue + + soup = BeautifulSoup(html, "html.parser") + title = soup.title.text.strip() if soup.title else parse_hostname(url) + classification, accuracy = classify(html) + children = [] + if depth < self._depth and len(visited) < self.MAX_PAGES: + children = parse_links(soup) + text = extract_visible_text(soup) data = LinkNode( - title, - id, - resp.status_code, - classification, - accuracy, - numbers, - emails, - text, + title, url, status, classification, accuracy, + parse_phone_numbers(soup), parse_emails(soup), text, ) - self.create_node(title, identifier=id, parent=parent_id, data=data) - except exceptions.DuplicatedNodeIdError: - logging.debug(f"found a duplicate URL {id}") - - def _build_tree(self, url: str, depth: int) -> None: - """ - Builds a tree from the root to the given depth. - """ - if depth > 0: - depth -= 1 - try: - resp = self._client.get(url) - except Exception as exc: - logging.warning("Skipping subtree from %s due to request error: %s", url, exc) - return + self.create_node(title, identifier=url, parent=parent, data=data) + if parent is None: + self.root_html = html - children = parse_links(resp.text) for child in children: - try: - self._append_node(id=child, parent_id=url) - self._build_tree(url=child, depth=depth) - except RequestError as exc: - from torbot.crawl_result import failed_page - - parent_depth = self.depth(url) - self.crawl_failures.append( - failed_page(child, url, parent_depth + 1, exc) - ) + key = self._request_key(child) + if key in visited: continue + visited.add(key) + pending.append((child, url, depth + 1)) + if len(visited) >= self.MAX_PAGES: + break + + @staticmethod + def _request_key(url: str) -> httpx.URL | str: + # HTTPX normalizes host and port. raw_path preserves path escapes and + # query strings while treating an empty HTTP path as "/". + try: + target = httpx.URL(url) + except httpx.InvalidURL: + return url + return target.copy_with(fragment=None, raw_path=target.raw_path) + + def _fetch_page(self, url: str) -> tuple[str, int]: + try: + with self._client.stream( + "GET", url, headers={"Accept-Encoding": "identity"}, follow_redirects=False + ) as response: + # Reject unsolicited compression before HTTPX can inflate a chunk. + if response.headers.get("Content-Encoding", "identity").lower() != "identity": + raise RequestError("unsupported compressed response") + body = bytearray() + for chunk in response.iter_bytes(): + if len(chunk) > self.MAX_RESPONSE_BYTES - len(body): + raise RequestError("response exceeds crawl byte limit") + body.extend(chunk) + if not body: + raise RequestError("empty response") + encoding = response.encoding or "utf-8" + return body.decode(encoding, errors="replace"), response.status_code + except (httpx.HTTPError, httpx.InvalidURL) as exc: + logging.warning("Skipping URL %s due to request error: %s", url, exc) + raise RequestError(str(exc)) from exc def to_crawl_result( self, @@ -247,14 +257,14 @@ def extract_visible_text(soup: BeautifulSoup, *, limit: int = 50_000) -> str: return text[:limit] -def parse_links(html: str, base_url: str | None = None) -> list[str]: +def parse_links(html: str | BeautifulSoup, base_url: str | None = None) -> list[str]: """ Finds all anchor tags and parses the href attribute. Relative links are resolved against the page URL when a base URL is provided. Only absolute http(s) links are returned. """ - soup = BeautifulSoup(html, "html.parser") + soup = html if isinstance(html, BeautifulSoup) else BeautifulSoup(html, "html.parser") links = [] for tag in soup.find_all("a"): href = tag.get("href") diff --git a/tests/test_crawl_limits.py b/tests/test_crawl_limits.py new file mode 100644 index 00000000..a97e65a5 --- /dev/null +++ b/tests/test_crawl_limits.py @@ -0,0 +1,66 @@ +import httpx +import pytest + +from torbot.modules.linktree import LinkTree, RequestError + + +def test_page_budget_counts_failures_and_skips_cycles(monkeypatch): + root = "https://example.test" + paths = { + "/": ["/a", "/a#dup", "/missing"], + "/a": ["/#back", "/missing", "/last", "/over-budget"], + "/last": [], + } + requests = [] + + def respond(request): + path = request.url.path + requests.append(path) + if path == "/missing": + raise httpx.ConnectError("offline") + links = "".join(f'link' for p in paths[path]) + return httpx.Response(200, text="page" + links) + + monkeypatch.setattr(LinkTree, "MAX_PAGES", 4) + with httpx.Client(transport=httpx.MockTransport(respond)) as client: + tree = LinkTree(root, 10, client) + tree.load() + assert requests == ["/", "/a", "/missing", "/last"] + assert tree.size() == 3 + assert [p["url"] for p in tree.crawl_failures] == [root + "/missing"] + + +@pytest.mark.parametrize("mode", ["at_limit", "overflow", "compressed"]) +def test_stream_budget_stops_reading_and_closes_response(monkeypatch, mode): + class Body(httpx.SyncByteStream): + closed = False + + def __iter__(self): + assert mode != "compressed", "compressed body read" + yield b"1234" + yield b"5678" + if mode == "overflow": + yield b"9" + pytest.fail("continued reading after the byte limit") + + def close(self): + self.closed = True + + body = Body() + + def respond(request): + assert request.headers["Accept-Encoding"] == "identity" + headers = {"Content-Encoding": "gzip"} if mode == "compressed" else {} + return httpx.Response(200, headers=headers, stream=body) + + monkeypatch.setattr(LinkTree, "MAX_RESPONSE_BYTES", 8) + with httpx.Client(transport=httpx.MockTransport(respond)) as client: + tree = LinkTree("http://example.test", 0, client) + if mode == "at_limit": + tree.load() + assert tree.get_node(tree.root).data.text == "12345678" + else: + with pytest.raises(RequestError, match="byte limit|compressed"): + tree.load() + assert tree.size() == 0 + assert body.closed diff --git a/tests/test_export_paths.py b/tests/test_export_paths.py index 4df55412..5c2d3fcb 100644 --- a/tests/test_export_paths.py +++ b/tests/test_export_paths.py @@ -27,7 +27,8 @@ def test_exports_stay_in_output_directory(tmp_path, title): tree.load() tree.save() tree.saveJSON() - fetch_html(client, "http://example.test", tree, save_html=True) + with patch.object(client, "get", side_effect=AssertionError("root fetched twice")): + fetch_html(client, "http://example.test", tree, save_html=True) files = list(output.iterdir()) assert len(files) == 3 assert {p.suffix for p in files} == {".txt", ".json", ".html"} diff --git a/tests/test_linktree_tree.py b/tests/test_linktree_tree.py index 91ec929b..44f225ec 100644 --- a/tests/test_linktree_tree.py +++ b/tests/test_linktree_tree.py @@ -7,7 +7,9 @@ - Saving to JSON and text formats - Classification and contact extraction integration """ +from contextlib import contextmanager import json +import httpx import tempfile from pathlib import Path from unittest.mock import patch @@ -33,12 +35,12 @@ def __init__(self, responses: dict[str, FakeResponse]): self.responses = responses self.call_count = {} - def get(self, url: str) -> FakeResponse: + @contextmanager + def stream(self, method, url, **kwargs): + assert method == "GET" self.call_count[url] = self.call_count.get(url, 0) + 1 - if url in self.responses: - return self.responses[url] - # Return a minimal response for unknown URLs - return FakeResponse(url, "404", 404) + result = self.responses.get(url, FakeResponse(url, "404", 404)) + yield httpx.Response(result.status_code, text=result.text) def test_parse_hostname_extracts_domain():