:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): add safe content site discovery (#91085)
Jordan Mryyanf16ffcb7223b
diff --git a/products/web_analytics/backend/content_autopilot/__init__.py b/products/web_analytics/backend/content_autopilot/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/web_analytics/backend/content_autopilot/site_discovery.py b/products/web_analytics/backend/content_autopilot/site_discovery.pynew file mode 100644index 000000000000..117f174966ce--- /dev/null+++ b/products/web_analytics/backend/content_autopilot/site_discovery.py@@ -0,0 +1,254 @@+import re+import time+from html.parser import HTMLParser+from typing import TypedDict+from urllib.parse import urljoin, urlparse, urlunparse++import defusedxml.ElementTree as ET+from defusedxml.common import DefusedXmlException+from defusedxml.ElementTree import ParseError as DefusedParseError++from posthog.dataclasses import frozen+from posthog.security.llm_prompt_sanitization import sanitize_user_text+from posthog.security.url_validation import has_authority_bypass_chars, strip_userinfo++from products.web_analytics.backend.public_url_fetch import (+ PUBLIC_URL_REDIRECT_STATUSES,+ PublicUrlFetchError,+ fetch_public_url,+)++_MAX_DISCOVERY_BYTES = 512 * 1024+_MAX_REDIRECTS = 2+_MAX_SITEMAP_CANDIDATES = 5+_MAX_DISCOVERY_REQUESTS = 12+_MAX_DISCOVERY_SECONDS = 20.0+_DEFAULT_PORTS = {"http": 80, "https": 443}+_MAX_SITE_NAME_LENGTH = 255+_CONVENTIONAL_SITEMAP_PATHS = ("/sitemap.xml", "/sitemap_index.xml", "/sitemap-index.xml")+++class SiteDiscoveryResult(TypedDict):+ name: str+ domain: str+ source_urls: list[str]+ content_boundaries: list[str]+ sitemap_detected: bool+ warnings: list[str]+++@frozen+class _FetchedText:+ text: str+ url: str+++class _RequestBudget:+ def __init__(self, limit: int) -> None:+ self.remaining = limit++ def spend(self) -> None:+ if self.remaining <= 0:+ raise PublicUrlFetchError("read", "Site discovery made too many requests.")+ self.remaining -= 1+++class _SiteNameParser(HTMLParser):+ def __init__(self) -> None:+ super().__init__()+ self.og_site_name = ""+ self.title = ""+ self._inside_title = False++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ lowered = tag.lower()+ if lowered == "title":+ self._inside_title = True+ elif lowered == "meta" and not self.og_site_name:+ values = {key.lower(): value or "" for key, value in attrs}+ if values.get("property", "").strip().lower() == "og:site_name":+ self.og_site_name = values.get("content", "")++ def handle_endtag(self, tag: str) -> None:+ if tag.lower() == "title":+ self._inside_title = False++ def handle_data(self, data: str) -> None:+ if self._inside_title:+ self.title += data+++def normalize_site_origin(raw_url: str) -> str:+ invalid = ValueError("Enter a valid http or https site URL.")+ stripped = raw_url.strip()+ if has_authority_bypass_chars(stripped):+ raise invalid+ try:+ parsed = urlparse(stripped)+ hostname = (parsed.hostname or "").lower().removesuffix(".")+ port = parsed.port+ except ValueError as error:+ raise invalid from error+ scheme = parsed.scheme.lower()+ if scheme not in _DEFAULT_PORTS or not hostname or parsed.username or parsed.password or port == 0:+ raise invalid+ netloc = f"[{hostname}]" if ":" in hostname else hostname+ if port is not None and port != _DEFAULT_PORTS[scheme]:+ netloc = f"{netloc}:{port}"+ return urlunparse((scheme, netloc, "", "", "", ""))+++def _origin_key(url: str) -> str | None:+ try:+ parsed = urlparse(url)+ scheme = parsed.scheme.lower()+ hostname = (parsed.hostname or "").lower()+ port = parsed.port+ except ValueError:+ return None+ if scheme not in _DEFAULT_PORTS or not hostname or parsed.username or parsed.password:+ return None+ return f"{scheme}://{hostname.removesuffix('.')}:{port if port is not None else _DEFAULT_PORTS[scheme]}"+++def has_same_public_origin(first_url: str, second_url: str) -> bool:+ key = _origin_key(first_url)+ return key is not None and key == _origin_key(second_url)+++def _public_host(url: str) -> str:+ try:+ parsed = urlparse(url)+ scheme = parsed.scheme.lower()+ hostname = (parsed.hostname or "").lower().removesuffix(".")+ except ValueError:+ return ""+ if scheme not in _DEFAULT_PORTS or not hostname or parsed.username or parsed.password:+ return ""+ return hostname+++def has_same_public_site(first_url: str, second_url: str) -> bool:+ first = _public_host(first_url).removeprefix("www.")+ second = _public_host(second_url).removeprefix("www.")+ if not first or not second:+ return False+ return first == second or first.endswith(f".{second}") or second.endswith(f".{first}")+++def _fetch_text(url: str, *, deadline: float, budget: _RequestBudget) -> _FetchedText:+ current_url = strip_userinfo(url)+ for _ in range(_MAX_REDIRECTS + 1):+ if time.monotonic() >= deadline:+ raise PublicUrlFetchError("deadline", "Site discovery took too long.")+ budget.spend()+ response = fetch_public_url(+ current_url,+ headers={+ "Accept": "text/html,application/xml,text/xml,text/plain;q=0.9,*/*;q=0.1",+ "User-Agent": "PostHog content site discovery",+ },+ max_bytes=_MAX_DISCOVERY_BYTES,+ deadline=deadline,+ connect_timeout_seconds=3.0,+ read_timeout_seconds=5.0,+ )+ if response.status_code in PUBLIC_URL_REDIRECT_STATUSES:+ location = response.headers.get("location")+ if not location:+ raise PublicUrlFetchError("read", "The site returned an invalid redirect.")+ target = strip_userinfo(urljoin(current_url, location))+ if not has_same_public_site(target, url):+ raise PublicUrlFetchError("blocked", "The site redirected away from its own domain.")+ current_url = target+ continue+ if response.status_code < 200 or response.status_code >= 300:+ raise PublicUrlFetchError("read", "The site response could not be used.")+ return _FetchedText(text=response.body.decode("utf-8", errors="replace"), url=current_url)+ raise PublicUrlFetchError("read", "The site returned too many redirects.")+++def _sitemaps_from_robots(robots_text: str, *, origin: str) -> list[str]:+ sitemaps: list[str] = []+ for line in robots_text.splitlines():+ key, separator, value = line.partition(":")+ if separator and key.strip().lower() == "sitemap":+ candidate = urljoin(f"{origin}/", value.strip())+ if has_same_public_origin(candidate, origin):+ sitemaps.append(candidate)+ return sitemaps+++def _is_sitemap(xml_text: str) -> bool:+ try:+ root = ET.fromstring(xml_text)+ except (DefusedParseError, DefusedXmlException):+ return False+ root_name = root.tag.rsplit("}", 1)[-1].lower()+ return root_name in {"urlset", "sitemapindex"}+++def _verified_sitemaps(candidates: list[str], *, deadline: float, budget: _RequestBudget) -> list[str]:+ verified: list[str] = []+ for candidate in candidates:+ if time.monotonic() >= deadline:+ break+ try:+ fetched = _fetch_text(candidate, deadline=deadline, budget=budget)+ except PublicUrlFetchError:+ continue+ if _is_sitemap(fetched.text):+ verified.append(fetched.url)+ return list(dict.fromkeys(verified))+++def _site_name(og_site_name: str, title: str, hostname: str) -> str:+ declared_name = sanitize_user_text(og_site_name, _MAX_SITE_NAME_LENGTH)+ if declared_name:+ return declared_name+ cleaned_title = sanitize_user_text(title, _MAX_SITE_NAME_LENGTH)+ if cleaned_title:+ return re.split(r"\s+[|–—]\s+", cleaned_title, maxsplit=1)[0]+ return hostname.removeprefix("www.")[:_MAX_SITE_NAME_LENGTH]+++def discover_site(raw_url: str) -> SiteDiscoveryResult:+ origin = normalize_site_origin(raw_url)+ deadline = time.monotonic() + _MAX_DISCOVERY_SECONDS+ budget = _RequestBudget(_MAX_DISCOVERY_REQUESTS)+ hostname = urlparse(origin).hostname or origin+ declared_sitemaps: list[str] = []+ og_site_name = ""+ title = ""++ try:+ robots = _fetch_text(f"{origin}/robots.txt", deadline=deadline, budget=budget)+ declared_sitemaps = _sitemaps_from_robots(robots.text, origin=origin)+ except PublicUrlFetchError:+ pass++ try:+ parser = _SiteNameParser()+ parser.feed(_fetch_text(f"{origin}/", deadline=deadline, budget=budget).text)+ og_site_name = parser.og_site_name+ title = parser.title+ except PublicUrlFetchError:+ pass++ detected_sitemaps = _verified_sitemaps(+ list(dict.fromkeys(declared_sitemaps))[:_MAX_SITEMAP_CANDIDATES], deadline=deadline, budget=budget+ ) or _verified_sitemaps(+ [f"{origin}{path}" for path in _CONVENTIONAL_SITEMAP_PATHS], deadline=deadline, budget=budget+ )++ sitemap_detected = bool(detected_sitemaps)+ source_urls = detected_sitemaps or [f"{origin}/sitemap.xml"]+ warnings = [] if sitemap_detected else ["We couldn't verify a sitemap. Review the suggested URL before saving."]+ return {+ "name": _site_name(og_site_name, title, hostname),+ "domain": origin,+ "source_urls": source_urls,+ "content_boundaries": ["/"],+ "sitemap_detected": sitemap_detected,+ "warnings": warnings,+ }diff --git a/products/web_analytics/backend/llms_txt.py b/products/web_analytics/backend/llms_txt.pyindex 45e7a635e74f..0ef795328ba5 100644--- a/products/web_analytics/backend/llms_txt.py+++ b/products/web_analytics/backend/llms_txt.py@@ -1,23 +1,31 @@import timeimport urllib.parse as urlparse-import requests-import structlog-from posthog.dataclasses import frozen-from posthog.security.pinned_requests import SSRFBlockedError, pinned_sessionfrom posthog.security.url_validation import strip_userinfo-logger = structlog.get_logger(__name__)+from products.web_analytics.backend.public_url_fetch import (+ PUBLIC_URL_REDIRECT_STATUSES,+ PublicUrlFetchError,+ PublicUrlFetchFailure,+ fetch_public_url,+)LLMS_TXT_MAX_BYTES = 1024 * 1024LLMS_TXT_MAX_REDIRECTS = 3LLMS_TXT_CONNECT_TIMEOUT_SECONDS = 3.05LLMS_TXT_READ_TIMEOUT_SECONDS = 10.0LLMS_TXT_TOTAL_BUDGET_SECONDS = 20.0-LLMS_TXT_READ_CHUNK_BYTES = 64 * 1024-LLMS_TXT_REDIRECT_STATUSES = {301, 302, 303, 307, 308}-LLMS_TXT_ACCEPTED_CONTENT_ENCODINGS = {"", "identity"}+LLMS_TXT_REJECTED_MEDIA_TYPES = frozenset({"text/html", "application/xhtml+xml"})+LLMS_TXT_FETCH_FAILURE_MESSAGES: dict[PublicUrlFetchFailure, str] = {+ "blocked": "Enter a publicly accessible HTTP or HTTPS URL.",+ "compressed": "The URL returned a compressed file. Serve llms.txt as plain text.",+ "deadline": "The file took too long to load.",+ "media_type": "The URL returned an HTML page instead of an llms.txt file.",+ "read": "Could not read the file.",+ "too_large": "The file is larger than 1 MB.",+ "transport": "Could not reach the URL.",+}class LlmsTxtFetchError(Exception):@@ -30,29 +38,6 @@ class FetchedLlmsTxt:url: str-def _read_once(response: requests.Response, amt: int) -> bytes:- raw = response.raw- read1 = getattr(raw, "read1", None) or getattr(getattr(raw, "_fp", None), "read1", None)- if read1 is None:- raise LlmsTxtFetchError("Could not read the file.")- return bytes(read1(amt))---def _read_response_body(response: requests.Response, deadline: float) -> bytes:- chunks: list[bytes] = []- total_bytes = 0- while True:- if time.monotonic() > deadline:- raise LlmsTxtFetchError("The file took too long to load.")- chunk = _read_once(response, LLMS_TXT_READ_CHUNK_BYTES)- if not chunk:- return b"".join(chunks)- total_bytes += len(chunk)- if total_bytes > LLMS_TXT_MAX_BYTES:- raise LlmsTxtFetchError("The file is larger than 1 MB.")- chunks.append(chunk)--def fetch_llms_txt(url: str) -> FetchedLlmsTxt:current_url = strip_userinfo(urlparse.urldefrag(url.strip())[0])# One budget for the whole chain: the read timeout bounds the gap between chunks, not the total@@ -60,57 +45,35 @@ def fetch_llms_txt(url: str) -> FetchedLlmsTxt:deadline = time.monotonic() + LLMS_TXT_TOTAL_BUDGET_SECONDSfor _redirect_count in range(LLMS_TXT_MAX_REDIRECTS + 1):- read_timeout = min(LLMS_TXT_READ_TIMEOUT_SECONDS, deadline - time.monotonic())- if read_timeout <= 0:- raise LlmsTxtFetchError("The file took too long to load.")try:- with pinned_session(current_url) as session:- response = session.get(- current_url,- headers={- "Accept": "text/plain,text/markdown;q=0.9,*/*;q=0.1",- # Undecoded, so the size cap counts what we actually read off the wire.- "Accept-Encoding": "identity",- "User-Agent": "PostHog llms.txt fetcher",- },- timeout=(LLMS_TXT_CONNECT_TIMEOUT_SECONDS, read_timeout),- allow_redirects=False,- stream=True,- )- try:- if response.status_code in LLMS_TXT_REDIRECT_STATUSES:- location = response.headers.get("Location")- if not location:- raise LlmsTxtFetchError("The URL redirected without a destination.")- current_url = strip_userinfo(urlparse.urljoin(current_url, location))- continue-- if response.status_code < 200 or response.status_code >= 300:- raise LlmsTxtFetchError(f"The URL returned HTTP {response.status_code}.")-- content_type = response.headers.get("Content-Type", "")- media_type = content_type.split(";", 1)[0].strip().lower()- if media_type in {"text/html", "application/xhtml+xml"}:- raise LlmsTxtFetchError("The URL returned an HTML page instead of an llms.txt file.")-- content_encoding = response.headers.get("Content-Encoding", "").strip().lower()- if content_encoding not in LLMS_TXT_ACCEPTED_CONTENT_ENCODINGS:- raise LlmsTxtFetchError("The URL returned a compressed file. Serve llms.txt as plain text.")-- body = _read_response_body(response, deadline)- content = body.decode("utf-8-sig", errors="replace")- if not content.strip():- raise LlmsTxtFetchError("The file is empty.")- return FetchedLlmsTxt(content=content, url=current_url)- finally:- response.close()- except SSRFBlockedError as error:- logger.info("llms_txt.url_blocked", reason=str(error))- raise LlmsTxtFetchError("Enter a publicly accessible HTTP or HTTPS URL.") from error- except requests.RequestException as error:- # Deliberately not logging the exception or the URL: both routinely echo the full target,- # and a customer-supplied URL can carry credentials or a signed token.- logger.info("llms_txt.request_failed")- raise LlmsTxtFetchError("Could not reach the URL.") from error+ response = fetch_public_url(+ current_url,+ headers={+ "Accept": "text/plain,text/markdown;q=0.9,*/*;q=0.1",+ "User-Agent": "PostHog llms.txt fetcher",+ },+ max_bytes=LLMS_TXT_MAX_BYTES,+ deadline=deadline,+ connect_timeout_seconds=LLMS_TXT_CONNECT_TIMEOUT_SECONDS,+ read_timeout_seconds=LLMS_TXT_READ_TIMEOUT_SECONDS,+ rejected_media_types=LLMS_TXT_REJECTED_MEDIA_TYPES,+ )+ except PublicUrlFetchError as error:+ raise LlmsTxtFetchError(LLMS_TXT_FETCH_FAILURE_MESSAGES[error.failure]) from error++ if response.status_code in PUBLIC_URL_REDIRECT_STATUSES:+ location = response.headers.get("location")+ if not location:+ raise LlmsTxtFetchError("The URL redirected without a destination.")+ current_url = strip_userinfo(urlparse.urljoin(current_url, location))+ continue++ if response.status_code < 200 or response.status_code >= 300:+ raise LlmsTxtFetchError(f"The URL returned HTTP {response.status_code}.")++ content = response.body.decode("utf-8-sig", errors="replace")+ if not content.strip():+ raise LlmsTxtFetchError("The file is empty.")+ return FetchedLlmsTxt(content=content, url=current_url)raise LlmsTxtFetchError("The URL redirected too many times.")diff --git a/products/web_analytics/backend/public_url_fetch.py b/products/web_analytics/backend/public_url_fetch.pynew file mode 100644index 000000000000..d58515795a9e--- /dev/null+++ b/products/web_analytics/backend/public_url_fetch.py@@ -0,0 +1,117 @@+import time+from typing import Literal++import requests+import structlog++from posthog.dataclasses import frozen+from posthog.security.pinned_requests import SSRFBlockedError, pinned_session++logger = structlog.get_logger(__name__)++PublicUrlFetchFailure = Literal["blocked", "compressed", "deadline", "media_type", "read", "too_large", "transport"]++PUBLIC_URL_READ_CHUNK_BYTES = 64 * 1024+PUBLIC_URL_ACCEPTED_CONTENT_ENCODINGS = {"", "identity"}+PUBLIC_URL_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})+++class PublicUrlFetchError(Exception):+ def __init__(self, failure: PublicUrlFetchFailure, message: str | None = None) -> None:+ self.failure = failure+ super().__init__(message or failure)+++@frozen+class FetchedPublicUrl:+ status_code: int+ headers: dict[str, str]+ body: bytes+++def _read_once(response: requests.Response, amount: int) -> bytes:+ raw = response.raw+ read_once = getattr(raw, "read1", None) or getattr(getattr(raw, "_fp", None), "read1", None)+ if read_once is None:+ raise PublicUrlFetchError("read")+ return bytes(read_once(amount))+++def _read_response_body(response: requests.Response, *, deadline: float, max_bytes: int) -> bytes:+ chunks: list[bytes] = []+ total_bytes = 0+ while True:+ if time.monotonic() > deadline:+ raise PublicUrlFetchError("deadline")+ chunk = _read_once(response, PUBLIC_URL_READ_CHUNK_BYTES)+ if time.monotonic() > deadline:+ raise PublicUrlFetchError("deadline")+ if not chunk:+ return b"".join(chunks)+ total_bytes += len(chunk)+ if total_bytes > max_bytes:+ raise PublicUrlFetchError("too_large")+ chunks.append(chunk)+++def fetch_public_url(+ url: str,+ *,+ headers: dict[str, str],+ max_bytes: int,+ deadline: float,+ connect_timeout_seconds: float,+ read_timeout_seconds: float,+ rejected_media_types: frozenset[str] = frozenset(),+) -> FetchedPublicUrl:+ if max_bytes < 1:+ raise ValueError("max_bytes must be positive")++ remaining_seconds = deadline - time.monotonic()+ if remaining_seconds <= 0:+ raise PublicUrlFetchError("deadline")++ request_headers = {**headers, "Accept-Encoding": "identity"}+ try:+ with pinned_session(url) as session:+ response = session.get(+ url,+ headers=request_headers,+ timeout=(+ min(connect_timeout_seconds, remaining_seconds),+ min(read_timeout_seconds, remaining_seconds),+ ),+ allow_redirects=False,+ stream=True,+ )+ try:+ response_headers = {name.lower(): value for name, value in response.headers.items()}+ if not 200 <= response.status_code < 300:+ return FetchedPublicUrl(status_code=response.status_code, headers=response_headers, body=b"")++ media_type = response_headers.get("content-type", "").split(";", 1)[0].strip().lower()+ if media_type in rejected_media_types:+ raise PublicUrlFetchError("media_type")++ content_encoding = response_headers.get("content-encoding", "").strip().lower()+ if content_encoding not in PUBLIC_URL_ACCEPTED_CONTENT_ENCODINGS:+ raise PublicUrlFetchError("compressed")++ declared_size = response_headers.get("content-length")+ if declared_size and declared_size.isdigit() and int(declared_size) > max_bytes:+ raise PublicUrlFetchError("too_large")++ return FetchedPublicUrl(+ status_code=response.status_code,+ headers=response_headers,+ body=_read_response_body(response, deadline=deadline, max_bytes=max_bytes),+ )+ finally:+ response.close()+ except SSRFBlockedError as error:+ logger.info("web_analytics.public_url_fetch.url_blocked", reason=str(error))+ raise PublicUrlFetchError("blocked") from error+ except requests.RequestException as error:+ # The exception and URL can contain credentials or signed query parameters, so neither is logged.+ logger.info("web_analytics.public_url_fetch.request_failed")+ raise PublicUrlFetchError("transport") from errordiff --git a/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py b/products/web_analytics/backend/test/test_content_autopilot_site_discovery.pynew file mode 100644index 000000000000..17ab5e9dc0e9--- /dev/null+++ b/products/web_analytics/backend/test/test_content_autopilot_site_discovery.py@@ -0,0 +1,186 @@+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from products.web_analytics.backend.content_autopilot.site_discovery import (+ _MAX_DISCOVERY_REQUESTS,+ discover_site,+ normalize_site_origin,+)+from products.web_analytics.backend.public_url_fetch import FetchedPublicUrl, PublicUrlFetchError+++def _response(*, status: int = 200, body: bytes = b"", location: str | None = None) -> FetchedPublicUrl:+ return FetchedPublicUrl(status_code=status, headers={"location": location} if location else {}, body=body)+++class TestContentAutopilotSiteDiscovery(SimpleTestCase):+ @parameterized.expand(+ [+ ("lowercase_host", "HTTPS://Example.COM/guides?q=1#top", "https://example.com"),+ ("default_port", "https://example.com:443/path", "https://example.com"),+ ("custom_port", "http://example.com:8080/path", "http://example.com:8080"),+ ("fully_qualified_dot", "https://example.com./path", "https://example.com"),+ ]+ )+ def test_normalizes_site_origin(self, _name: str, raw_url: str, expected: str) -> None:+ self.assertEqual(normalize_site_origin(raw_url), expected)++ @parameterized.expand(+ [+ ("unsupported_scheme", "ftp://example.com"),+ ("missing_host", "https:///guides"),+ ("credentials", "https://[email protected]"),+ ("invalid_port", "https://example.com:not-a-port"),+ ("zero_port", "https://example.com:0"),+ ("backslash_authority", "https://example.com\\@evil.example"),+ ("encoded_backslash_authority", "https://example.com%[email protected]"),+ ]+ )+ def test_rejects_invalid_site_origin(self, _name: str, raw_url: str) -> None:+ with self.assertRaises(ValueError):+ normalize_site_origin(raw_url)++ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_detects_site_defaults_and_sitemap(self, fetch_public_url: MagicMock) -> None:+ def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:+ if url.endswith("/robots.txt"):+ return _response(+ body=b"User-agent: *\nSitemap: https://example.com/content-sitemap.xml",+ )+ if url == "https://example.com/":+ return _response(body=b"<html><head><title>Example Docs | Guides</title></head></html>")+ if url.endswith("/content-sitemap.xml"):+ return _response(body=b'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />')+ return _response(status=404)++ fetch_public_url.side_effect = response_for++ result = discover_site("HTTPS://Example.com/docs")++ self.assertEqual(result["name"], "Example Docs")+ self.assertEqual(result["domain"], "https://example.com")+ self.assertEqual(result["source_urls"], ["https://example.com/content-sitemap.xml"])+ self.assertTrue(result["sitemap_detected"])+ self.assertEqual(result["warnings"], [])++ @parameterized.expand(+ [+ (+ "prefers_og_site_name",+ b'<meta property="og:site_name" content="Example"><title>Pricing | Example Docs</title>',+ "Example",+ ),+ ("falls_back_to_the_title", b"<title>Example Docs | Guides</title>", "Example Docs"),+ ("falls_back_to_the_hostname", b"<html><head></head></html>", "example.com"),+ (+ "strips_control_characters_and_bidi_marks",+ b'<meta property="og:site_name" content="Example\x00 \xe2\x80\xae Docs">',+ "Example Docs",+ ),+ ]+ )+ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_names_the_site(self, _name: str, homepage: bytes, expected: str, fetch_public_url: MagicMock) -> None:+ def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:+ if url == "https://example.com/":+ return _response(body=homepage)+ return _response(status=404)++ fetch_public_url.side_effect = response_for++ self.assertEqual(discover_site("https://example.com")["name"], expected)++ @parameterized.expand(+ [+ ("www_variant", "https://www.example.com/sitemap.xml", True),+ ("subdomain", "https://docs.example.com/sitemap.xml", True),+ ("unrelated_site", "https://cdn.other-site.example/sitemap.xml", False),+ ]+ )+ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_records_a_sitemap_redirect_only_when_it_stays_on_the_site(+ self, _name: str, redirect_target: str, stays_on_site: bool, fetch_public_url: MagicMock+ ) -> None:+ def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:+ if url == "https://example.com/sitemap.xml":+ return _response(status=301, location=redirect_target)+ if url == redirect_target:+ return _response(body=b"<urlset />")+ return _response(status=404)++ fetch_public_url.side_effect = response_for++ result = discover_site("https://example.com")++ self.assertEqual(result["sitemap_detected"], stays_on_site)+ self.assertEqual(+ result["source_urls"], [redirect_target] if stays_on_site else ["https://example.com/sitemap.xml"]+ )++ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_caps_the_requests_one_discovery_sends(self, fetch_public_url: MagicMock) -> None:+ fetch_public_url.side_effect = lambda url, **kwargs: _response(status=302, location="/redirect")++ result = discover_site("https://example.com")++ self.assertEqual(fetch_public_url.call_count, _MAX_DISCOVERY_REQUESTS)+ self.assertFalse(result["sitemap_detected"])++ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_invalid_xml_uses_an_editable_sitemap_fallback(self, fetch_public_url: MagicMock) -> None:+ fetch_public_url.side_effect = lambda url, **kwargs: _response(+ status=404 if url.endswith(("/robots.txt", "/")) else 200,+ body=b"<urlset>" if url.endswith(".xml") else b"",+ )++ result = discover_site("https://example.com")++ self.assertEqual(result["source_urls"], ["https://example.com/sitemap.xml"])+ self.assertEqual(+ result["warnings"],+ ["We couldn't verify a sitemap. Review the suggested URL before saving."],+ )++ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_caps_robots_candidates_and_still_probes_conventional_paths(self, fetch_public_url: MagicMock) -> None:+ sitemap_lines = "\n".join(f"Sitemap: https://example.com/sitemap-{index}.xml" for index in range(10))++ def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:+ if url.endswith("/robots.txt"):+ return _response(body=sitemap_lines.encode())+ if url == "https://example.com/":+ raise PublicUrlFetchError("transport")+ if url == "https://example.com/sitemap.xml":+ return _response(body=b"<urlset />")+ return _response(status=404)++ fetch_public_url.side_effect = response_for++ result = discover_site("https://example.com")++ declared = {f"https://example.com/sitemap-{index}.xml" for index in range(10)}+ declared_calls = [call.args[0] for call in fetch_public_url.call_args_list if call.args[0] in declared]+ self.assertEqual(declared_calls, [f"https://example.com/sitemap-{index}.xml" for index in range(5)])+ self.assertEqual(result["source_urls"], ["https://example.com/sitemap.xml"])+ self.assertTrue(result["sitemap_detected"])++ @patch("products.web_analytics.backend.content_autopilot.site_discovery.fetch_public_url")+ def test_skips_a_malformed_sitemap_candidate(self, fetch_public_url: MagicMock) -> None:+ def response_for(url: str, **kwargs: object) -> FetchedPublicUrl:+ if url.endswith("/robots.txt"):+ return _response(+ body=b"Sitemap: https://example.com:invalid/broken.xml\nSitemap: /sitemap.xml",+ )+ if url.endswith("/sitemap.xml"):+ return _response(body=b"<urlset />")+ return _response(status=404)++ fetch_public_url.side_effect = response_for++ result = discover_site("https://example.com")++ self.assertEqual(result["source_urls"], ["https://example.com/sitemap.xml"])+ self.assertTrue(result["sitemap_detected"])diff --git a/products/web_analytics/backend/test/test_llms_txt.py b/products/web_analytics/backend/test/test_llms_txt.pyindex 50c762c27020..689e0bc3d329 100644--- a/products/web_analytics/backend/test/test_llms_txt.py+++ b/products/web_analytics/backend/test/test_llms_txt.py@@ -56,9 +56,19 @@ def _session(response: Mock) -> Mock:return session-@patch("products.web_analytics.backend.llms_txt.pinned_session")-def test_fetch_llms_txt_revalidates_redirect_targets(pinned_session_mock: Mock) -> None:- redirect = _response(status_code=302, headers={"Location": "/llms-full.txt"})+ "redirect_headers",+ [+ {"Location": "/llms-full.txt"},+ {"Location": "/llms-full.txt", "Content-Encoding": "gzip"},+ {"Location": "/llms-full.txt", "Content-Length": str(LLMS_TXT_MAX_BYTES + 1)},+ ],+)+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")+def test_fetch_llms_txt_revalidates_redirect_targets(+ pinned_session_mock: Mock, redirect_headers: dict[str, str]+) -> None:+ redirect = _response(status_code=302, headers=redirect_headers)success = _response(chunks=[b"# Example\n", b"- https://example.com/docs"])pinned_session_mock.side_effect = [nullcontext(_session(redirect)), nullcontext(_session(success))]@@ -72,7 +82,7 @@ def test_fetch_llms_txt_revalidates_redirect_targets(pinned_session_mock: Mock)]-@patch("products.web_analytics.backend.llms_txt.pinned_session")+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")def test_fetch_llms_txt_stops_streams_over_the_size_limit(pinned_session_mock: Mock) -> None:response = _response(chunks=[b"x" * LLMS_TXT_MAX_BYTES, b"x"])pinned_session_mock.return_value = nullcontext(_session(response))@@ -81,16 +91,36 @@ def test_fetch_llms_txt_stops_streams_over_the_size_limit(pinned_session_mock: Mfetch_llms_txt("https://example.com/llms.txt")-@patch("products.web_analytics.backend.llms_txt.pinned_session")-def test_fetch_llms_txt_rejects_html_responses(pinned_session_mock: Mock) -> None:- response = _response(headers={"Content-Type": "text/html"}, chunks=[b"<html>Not found</html>"])+ ("status_code", "headers", "expected_message"),+ [+ (200, {"Content-Type": "text/html"}, "HTML page"),+ (200, {"content-type": "text/html; charset=utf-8"}, "HTML page"),+ (200, {"Content-type": "application/xhtml+xml"}, "HTML page"),+ (404, {"Content-Type": "text/plain"}, "HTTP 404"),+ (500, {"Content-Type": "text/plain"}, "HTTP 500"),+ ],+)+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")+def test_fetch_llms_txt_rejects_a_response_without_reading_its_body(+ pinned_session_mock: Mock, status_code: int, headers: dict[str, str], expected_message: str+) -> None:+ reads: list[int] = []+ response = _response(+ status_code=status_code,+ headers=headers,+ chunks=[b"x" * LLMS_TXT_MAX_BYTES],+ on_read=lambda: reads.append(1),+ )pinned_session_mock.return_value = nullcontext(_session(response))- with pytest.raises(LlmsTxtFetchError, match="HTML page"):+ with pytest.raises(LlmsTxtFetchError, match=expected_message):fetch_llms_txt("https://example.com/llms.txt")+ assert reads == []+-@patch("products.web_analytics.backend.llms_txt.pinned_session")+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")def test_fetch_llms_txt_reports_ssrf_blocked_targets_as_a_user_error(pinned_session_mock: Mock) -> None:pinned_session_mock.side_effect = SSRFBlockedError("Private IP address not allowed")@@ -98,7 +128,7 @@ def test_fetch_llms_txt_reports_ssrf_blocked_targets_as_a_user_error(pinned_sessfetch_llms_txt("https://internal.example/llms.txt")-@patch("products.web_analytics.backend.llms_txt.pinned_session")+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")def test_fetch_llms_txt_gives_up_once_the_redirect_limit_is_reached(pinned_session_mock: Mock) -> None:redirect = _response(status_code=302, headers={"Location": "/next"})pinned_session_mock.side_effect = [nullcontext(_session(redirect)) for _ in range(LLMS_TXT_MAX_REDIRECTS + 1)]@@ -109,20 +139,23 @@ def test_fetch_llms_txt_gives_up_once_the_redirect_limit_is_reached(pinned_sessiassert pinned_session_mock.call_count == LLMS_TXT_MAX_REDIRECTS + 1-@patch("products.web_analytics.backend.llms_txt.pinned_session")+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")def test_fetch_llms_txt_gives_up_on_a_host_that_trickles_bytes(pinned_session_mock: Mock) -> None:clock = _Clock()response = _response(chunks=list(repeat(b"x", 10_000)), on_read=lambda: clock.advance(1.0))pinned_session_mock.return_value = nullcontext(_session(response))- with patch("products.web_analytics.backend.llms_txt.time.monotonic", clock):+ with (+ patch("products.web_analytics.backend.llms_txt.time.monotonic", clock),+ patch("products.web_analytics.backend.public_url_fetch.time.monotonic", clock),+ ):with pytest.raises(LlmsTxtFetchError, match="took too long"):fetch_llms_txt("https://example.com/llms.txt")assert clock.now <= LLMS_TXT_TOTAL_BUDGET_SECONDS + 1.0-@patch("products.web_analytics.backend.llms_txt.pinned_session")+@patch("products.web_analytics.backend.public_url_fetch.pinned_session")def test_fetch_llms_txt_rejects_a_body_the_host_compressed_anyway(pinned_session_mock: Mock) -> None:response = _response(headers={"Content-Type": "text/plain", "Content-Encoding": "gzip"},