Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(security): cap redirect bodies and render_page's raw fetch

Agrici Daniela3cd53e78b5b
diff --git a/scripts/fetch_page.py b/scripts/fetch_page.py
index e4780ff..0238f9f 100755
--- a/scripts/fetch_page.py
+++ b/scripts/fetch_page.py
@@ -41,6 +41,7 @@ from url_safety import ( # noqa: E402
validate_url_strict,
)
from url_safety import DEFAULT_USER_AGENT as DEFAULT_USER_AGENT # noqa: E402,F401
+from url_safety import MAX_PAGE_BYTES as _MAX_PAGE_BYTES # noqa: E402
# DEFAULT_USER_AGENT and the header block now live in url_safety, the lower
# layer that both this script and the safe_requests_* helpers go through, so
@@ -65,9 +66,8 @@ DEFAULT_HEADERS = dict(DEFAULT_REQUEST_HEADERS)
# that fetches through the safe helpers decodes the same way (issue #314).
_decode_response_content = decode_response_text
-# Largest body read, counted after decompression. Real HTML pages are far
-# smaller; the cap stops a decompression bomb or an endless stream.
-MAX_PAGE_BYTES = 10 * 1024 * 1024
+# Largest body read, counted after decompression (shared with render_page).
+MAX_PAGE_BYTES = _MAX_PAGE_BYTES
def fetch_page(
@@ -217,6 +217,7 @@ def _as_render_result(result: dict, *, mode_used: str) -> dict:
"render_engine": None,
"render_ms": None,
"mode_used": mode_used,
+ "too_large": bool(result.get("too_large")),
"error": result.get("error"),
}
diff --git a/scripts/render_page.py b/scripts/render_page.py
index 19cea13..19062a8 100644
--- a/scripts/render_page.py
+++ b/scripts/render_page.py
@@ -46,6 +46,7 @@ A dict with::
render_engine 'playwright-chromium' or None
render_ms elapsed wall-clock for the render step
mode_used 'rendered' or 'raw'
+ too_large True when the raw body hit the size cap (MAX_PAGE_BYTES)
error str or None
SSRF
@@ -104,10 +105,12 @@ _SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
if _SCRIPTS_DIR not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
from url_safety import ( # noqa: E402 (sys.path massage above is intentional)
+ MAX_PAGE_BYTES,
URLSafetyError,
- decode_response_text,
+ decode_body,
make_safe_playwright_route_handler,
new_guarded_context,
+ read_bounded,
safe_requests_get,
validate_url_strict,
)
@@ -439,6 +442,7 @@ def render_page(
"render_engine": None,
"render_ms": None,
"mode_used": None,
+ "too_large": False,
"error": None,
}
@@ -459,8 +463,18 @@ def render_page(
# Step 1: raw fetch (always; needed for SPA detection and as a baseline).
try:
- resp = safe_requests_get(norm_url, timeout=30, allow_redirects=True)
- result["raw_content"] = decode_response_text(resp)
+ resp = safe_requests_get(norm_url, timeout=30, allow_redirects=True, stream=True)
+ # Streamed so the body is read under the cap; .content must not be
+ # read after this.
+ try:
+ raw, result["too_large"] = read_bounded(resp, MAX_PAGE_BYTES)
+ finally:
+ resp.close()
+ result["raw_content"] = decode_body(raw, resp.headers.get("Content-Type", ""))
+ if result["too_large"]:
+ result["render_diagnostics"].append(
+ "raw body exceeded the size cap; raw_content holds the part read before it"
+ )
if resp.history:
result["redirect_chain"] = [
{"url": r.url, "status_code": r.status_code} for r in resp.history
diff --git a/scripts/url_safety.py b/scripts/url_safety.py
index 6df77cd..d271dcd 100644
--- a/scripts/url_safety.py
+++ b/scripts/url_safety.py
@@ -845,6 +845,15 @@ def decode_body(raw: bytes, content_type: str = "") -> str:
return raw.decode("utf-8", errors="replace")
+# Largest page body read, counted after decompression. Real HTML pages are
+# far smaller; the cap stops a decompression bomb or an endless stream.
+MAX_PAGE_BYTES = 10 * 1024 * 1024
+
+# A redirect's own body is never used, but requests reads it in full before
+# it follows Location. This much is read; the rest is dropped unread.
+MAX_REDIRECT_BODY_BYTES = 64 * 1024
+
+
def read_bounded(response, max_bytes: int) -> tuple[bytes, bool]:
"""Read a ``stream=True`` response body, stopping past ``max_bytes``.
@@ -867,6 +876,39 @@ def read_bounded(response, max_bytes: int) -> tuple[bytes, bool]:
return b"".join(chunks), too_large
+def _bound_redirect_body(response, *args, **kwargs): # type: ignore[no-untyped-def]
+ """``response`` hook: read at most MAX_REDIRECT_BODY_BYTES of a 3xx body.
+
+ requests runs response hooks before it follows a redirect, and following
+ one reads the whole body (``resp.content``), decompressed and unbounded.
+ Filling the body here from a capped read means a redirect that carries a
+ decompression bomb is cut off; the connection is then closed rather than
+ drained. Non-redirect responses are left untouched.
+ """
+ if not response.is_redirect or response._content is not False:
+ return response
+ try:
+ body, _too_large = read_bounded(response, MAX_REDIRECT_BODY_BYTES)
+ except (requests.RequestException, RuntimeError):
+ body = b""
+ if response.raw is not None:
+ response.raw.close()
+ response._content = body
+ response._content_consumed = True
+ return response
+
+
+def _with_redirect_body_cap(kwargs: dict) -> dict:
+ """Put :func:`_bound_redirect_body` first in the call's response hooks."""
+ hooks = dict(kwargs.get("hooks") or {})
+ existing = hooks.get("response") or []
+ if callable(existing):
+ existing = [existing]
+ hooks["response"] = [_bound_redirect_body, *existing]
+ kwargs["hooks"] = hooks
+ return kwargs
+
+
def _with_default_headers(kwargs: dict) -> dict:
"""Fill in DEFAULT_REQUEST_HEADERS for header keys the caller did not set."""
headers = dict(DEFAULT_REQUEST_HEADERS)
@@ -893,7 +935,7 @@ def safe_requests_get(
parsed = urlparse(norm_url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None # validate_url_strict guarantees this
- kwargs = _with_default_headers(kwargs)
+ kwargs = _with_redirect_body_cap(_with_default_headers(kwargs))
exempt = _validated_proxy_hosts(norm_url, kwargs.get("proxies"))
with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
return requests.get(norm_url, timeout=timeout, **kwargs)
@@ -935,6 +977,9 @@ def safe_requests_session(url: str) -> Iterator[requests.Session]:
port = parsed.port or (443 if parsed.scheme == "https" else 80)
assert parsed.hostname is not None
session = requests.Session()
+ # Session hooks apply to every request made on it, including each
+ # redirect hop, unless a request passes its own response hooks.
+ session.hooks["response"].append(_bound_redirect_body)
exempt = _validated_proxy_hosts(norm_url, session.proxies)
with _pin_dns(parsed.hostname, pinned_ip, port, exempt_hosts=exempt):
try:
diff --git a/tests/test_fetch_page_cli.py b/tests/test_fetch_page_cli.py
index a1fc30e..182bf1d 100644
--- a/tests/test_fetch_page_cli.py
+++ b/tests/test_fetch_page_cli.py
@@ -53,6 +53,7 @@ RENDERED_RESULT = {
"render_engine": "playwright-chromium",
"render_ms": 12.5,
"mode_used": "rendered",
+ "too_large": False,
"error": None,
}
diff --git a/tests/test_fetch_page_decoding.py b/tests/test_fetch_page_decoding.py
index e4988ac..feb48a1 100644
--- a/tests/test_fetch_page_decoding.py
+++ b/tests/test_fetch_page_decoding.py
@@ -82,5 +82,6 @@ def test_issue_314_fetching_scripts_use_the_shared_decoder():
for name in ("render_page.py", "parse_html.py", "nlp_analyze.py", "preload_check.py",
"parasite_risk.py", "ucp_check.py", "gbp_deprecation_lint.py"):
text = (scripts / name).read_text(encoding="utf-8")
- assert "decode_response_text(" in text, name
+ # decode_body is the same shared decoder, for streamed bodies.
+ assert "decode_response_text(" in text or "decode_body(" in text, name
assert "resp.text" not in text, name
diff --git a/tests/test_redirect_body_cap.py b/tests/test_redirect_body_cap.py
new file mode 100644
index 0000000..0c23f97
--- /dev/null
+++ b/tests/test_redirect_body_cap.py
@@ -0,0 +1,127 @@
+"""Bodies are read under a cap on every safe-fetch path, redirects included.
+
+requests reads the whole body of each 3xx it follows (``resp.content`` in
+``resolve_redirects``), decompressed and unbounded, before the caller sees
+anything. url_safety caps that body with a response hook. render_page's raw
+fetch reads the final body under MAX_PAGE_BYTES the way fetch_page does.
+
+A real local server is used; it is reached through the narrow
+CLAUDE_SEO_LOCAL_TARGETS allowlist, which covers the top-level URL only, and
+the redirect stays on that host.
+"""
+
+from __future__ import annotations
+
+import gzip
+import http.server
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
+import fetch_page # noqa: E402
+import render_page # noqa: E402
+import url_safety # noqa: E402
+
+# 64 MiB of zeros compresses to about 64 KB: a small decompression bomb.
+BOMB_SIZE = 64 * 1024 * 1024
+BOMB = gzip.compress(b"\0" * BOMB_SIZE, compresslevel=9)
+FINAL_HTML = b"<html><head><title>Final</title></head><body><p>Landed.</p></body></html>"
+BIG_PAGE = b"<html><body>" + b"x" * (3 * 1024 * 1024) + b"</body></html>"
+
+
+class _Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self): # noqa: N802 (http.server API)
+ if self.path == "/bomb-redirect":
+ self.send_response(302)
+ self.send_header("Location", "/final")
+ self.send_header("Content-Type", "text/html")
+ self.send_header("Content-Encoding", "gzip")
+ self.send_header("Content-Length", str(len(BOMB)))
+ self.end_headers()
+ self.wfile.write(BOMB)
+ elif self.path == "/final":
+ self._send(200, FINAL_HTML)
+ elif self.path == "/big":
+ self._send(200, BIG_PAGE)
+ else:
+ self._send(404, b"not found")
+
+ def _send(self, status: int, body: bytes) -> None:
+ self.send_response(status)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+def server(monkeypatch):
+ httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ httpd.daemon_threads = True
+ thread = threading.Thread(target=httpd.serve_forever, daemon=True)
+ thread.start()
+ port = httpd.server_address[1]
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", f"127.0.0.1:{port}")
+ try:
+ yield f"http://127.0.0.1:{port}"
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+
+
+def test_safe_get_caps_the_body_of_a_redirect(server):
+ resp = url_safety.safe_requests_get(f"{server}/bomb-redirect", timeout=10)
+ assert resp.status_code == 200
+ assert resp.content == FINAL_HTML
+ assert [r.status_code for r in resp.history] == [302]
+ assert resp.history[0].headers["Location"] == "/final"
+ assert len(resp.history[0].content) <= url_safety.MAX_REDIRECT_BODY_BYTES
+
+
+def test_safe_session_caps_the_body_of_a_redirect(server):
+ with url_safety.safe_requests_session(f"{server}/bomb-redirect") as session:
+ resp = session.get(f"{server}/bomb-redirect", timeout=10)
+ assert resp.content == FINAL_HTML
+ assert len(resp.history[0].content) <= url_safety.MAX_REDIRECT_BODY_BYTES
+
+
+def test_fetch_page_follows_a_bomb_redirect_with_history_intact(server):
+ result = fetch_page.fetch_page(f"{server}/bomb-redirect", timeout=10)
+ assert result["error"] is None
+ assert result["status_code"] == 200
+ assert result["url"] == f"{server}/final"
+ assert result["content"] == FINAL_HTML.decode()
+ assert result["redirect_details"] == [{"url": f"{server}/bomb-redirect", "status_code": 302}]
+ assert result["too_large"] is False
+
+
+def test_redirect_cap_leaves_other_responses_and_caller_hooks_alone(server):
+ seen = []
+ resp = url_safety.safe_requests_get(
+ f"{server}/final", timeout=10, hooks={"response": lambda r, *a, **k: seen.append(r.status_code)}
+ )
+ assert resp.content == FINAL_HTML
+ assert seen == [200]
+
+
+def test_render_page_raw_fetch_is_capped(server, monkeypatch):
+ monkeypatch.setattr(render_page, "MAX_PAGE_BYTES", 1024 * 1024)
+ result = render_page.render_page(f"{server}/big", mode="never")
+ assert result["error"] is None
+ assert result["mode_used"] == "raw"
+ assert result["too_large"] is True
+ assert 0 < len(result["raw_content"]) <= 1024 * 1024
+ assert any("size cap" in d for d in result["render_diagnostics"])
+
+
+def test_render_page_raw_fetch_reads_a_normal_page_whole(server):
+ result = render_page.render_page(f"{server}/final", mode="never")
+ assert result["error"] is None
+ assert result["too_large"] is False
+ assert result["raw_content"] == FINAL_HTML.decode()
diff --git a/tests/test_render_page.py b/tests/test_render_page.py
index 4a588f3..31db07c 100644
--- a/tests/test_render_page.py
+++ b/tests/test_render_page.py
@@ -283,10 +283,14 @@ def test_render_page_never_mode_against_example_com() -> None:
def _fake_response(text: str, status: int = 200, url: str = "https://x.example/"):
+ body = text.encode("utf-8")
return SimpleNamespace(
- text=text, content=text.encode("utf-8"), status_code=status,
+ text=text, content=body, status_code=status,
headers={"Content-Type": "text/html"},
url=url, history=[],
+ # render_page streams the raw body through url_safety.read_bounded.
+ iter_content=lambda chunk_size=1: iter([body]),
+ close=lambda: None,
)
@@ -571,7 +575,7 @@ def test_render_page_result_dict_has_all_documented_fields() -> None:
"extracted_text", "publication_date", "accessibility_tree",
"accessibility_error", "accessibility_partial",
"headers", "redirect_chain", "console_errors", "render_engine",
- "render_diagnostics", "render_ms", "mode_used", "error",
+ "render_diagnostics", "render_ms", "mode_used", "too_large", "error",
}
assert set(result.keys()) == expected_fields