Repository Public
1"""Build ``manifest.json``, the ground truth of the SPIDER fixture website.23The manifest is derived from the page registry (``spider_fixture_content``) and4from ``regions.json`` (rects measured by ``measure_regions.py``). The link graph5is recomputed here by parsing every static page, so ``depth`` and6``discovered_via`` cannot drift from the HTML, and the build fails if a page7links to a URL that the manifest does not describe.89 python tests/fixtures/site/spider_fixture_manifest.py --write # regenerate10 python tests/fixtures/site/spider_fixture_manifest.py --check # exit 1 if stale11"""1213from __future__ import annotations1415import argparse16import hashlib17import ipaddress18import json19import sys20from collections import deque21from html.parser import HTMLParser22from pathlib import Path23from urllib.parse import parse_qsl, urljoin, urlsplit2425_HERE = Path(__file__).resolve().parent26if str(_HERE) not in sys.path:27 sys.path.insert(0, str(_HERE))2829import spider_fixture_assets as assets30import spider_fixture_content as content3132MANIFEST_PATH = _HERE / "manifest.json"33REGIONS_PATH = _HERE / "regions.json"34SCHEMA_VERSION = 135REGION_TOLERANCE_PX = 23637HTTP_VIA = ("nav", "html_link", "pagination", "canonical", "hreflang", "iframe", "redirect", "sitemap", "subresource")38REQUIRES_ORDER = {"http": 0, "browser": 1, "interaction": 2}39SEEDS = ("/", "/robots.txt", "/sitemap.xml", "/favicon.ico")404142class LinkParser(HTMLParser):43 """Collect ``(url, via)`` pairs from an HTML document, the way an HTML-only crawler would."""4445 def __init__(self) -> None:46 super().__init__(convert_charrefs=True)47 self.links: list[tuple[str, str]] = []48 self._nav_depth = 04950 def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:51 attributes = {name: value or "" for name, value in attrs}52 rel = set(attributes.get("rel", "").lower().split())53 if tag == "nav":54 self._nav_depth += 155 elif tag == "a" and attributes.get("href"):56 via = "pagination" if rel & {"next", "prev"} else ("nav" if self._nav_depth else "html_link")57 self.links.append((attributes["href"], via))58 elif tag == "link" and attributes.get("href"):59 if "canonical" in rel:60 self.links.append((attributes["href"], "canonical"))61 elif "alternate" in rel and attributes.get("hreflang"):62 self.links.append((attributes["href"], "hreflang"))63 elif rel & {"next", "prev"}:64 self.links.append((attributes["href"], "pagination"))65 elif rel & {"stylesheet", "icon"}:66 self.links.append((attributes["href"], "subresource"))67 elif tag == "iframe" and attributes.get("src"):68 self.links.append((attributes["src"], "iframe"))69 elif tag in ("img", "script", "source"):70 for name in ("src", "data-src"):71 if attributes.get(name):72 self.links.append((attributes[name], "subresource"))73 for candidate in attributes.get("srcset", "").split(","):74 if candidate.strip():75 self.links.append((candidate.split()[0], "subresource"))7677 def handle_endtag(self, tag: str) -> None:78 if tag == "nav" and self._nav_depth:79 self._nav_depth -= 1808182def extract_links(html_bytes: bytes) -> list[tuple[str, str]]:83 parser = LinkParser()84 parser.feed(html_bytes.decode("utf-8"))85 return parser.links868788def _sha256(data: bytes) -> str:89 return hashlib.sha256(data).hexdigest()909192def _robots_agents(path: str) -> list[str]:93 return [94 group["user_agent"]95 for group in content.ROBOTS_GROUPS96 if any(path.startswith(rule) for rule in group["disallow"])97 ]9899100def _is_private_host(host: str) -> bool:101 try:102 address = ipaddress.ip_address(host)103 except ValueError:104 return False105 return address.is_private or address.is_loopback or address.is_link_local106107108class _Builder:109 def __init__(self) -> None:110 self.nodes: dict[str, dict] = {}111 self.unlinked: set[str] = set()112 self.non_http_links: dict[str, list[str]] = {}113114 # -- registry -----------------------------------------------------------115116 def node(self, path: str, kind: str, expected: str, status: int, content_type: str | None, **extra) -> dict:117 if path in self.nodes:118 raise ValueError(f"duplicate manifest entry {path}")119 entry = {120 "path": path,121 "expected": expected,122 "kind": kind,123 "requires": None,124 "discovered_via": None,125 "discovered_from": None,126 "depth": None,127 "status": status,128 "content_type": content_type,129 "title": None,130 "lang": None,131 "sha256": None,132 }133 entry.update(extra)134 agents = _robots_agents(path) if path.startswith("/") else []135 if agents:136 entry["expected"] = "forbidden_robots"137 entry["robots_disallowed_for"] = agents138 self.nodes[path] = entry139 return entry140141 def register(self) -> None:142 shell = content.PAGES["/spa/"]143 for path, page in content.PAGES.items():144 self.node(145 path,146 page.kind,147 "crawl" if page.kind == "page" else "asset",148 200,149 page.content_type,150 title=page.title,151 lang=page.lang,152 sha256=_sha256(page.body),153 **page.truth,154 )155 for path, route in content.SPA_ROUTES.items():156 truth = {key: value for key, value in route.items() if key != "parent"}157 truth["rendered_title"] = truth.pop("title")158 self.node(159 path,160 "page",161 "crawl",162 200,163 shell.content_type,164 title=shell.title,165 lang=shell.lang,166 sha256=_sha256(shell.body),167 served_as="spa_shell",168 ready_selector="body[data-spa-ready=true]",169 **truth,170 )171 for path, (status, location) in content.REDIRECTS.items():172 loop = path.startswith("/loop/")173 self.node(174 path,175 "redirect",176 "trap" if loop else "crawl",177 status,178 None,179 redirect_to=location,180 **({"trap_kind": "redirect_loop"} if loop else {}),181 )182 self.nodes["/wall/login"]["access_denial"] = {183 "type": "login",184 "signals": ["302 to /login?next=/wall/login", "password form"],185 }186 self._register_dynamic()187 for name in assets.IMAGES:188 if name == "favicon.png":189 continue190 extra = {"pixel_text": assets.PIXEL_TEXT[name]} if name in assets.PIXEL_TEXT else {}191 self.node(f"/img/{name}", "image", "asset", 200, "image/png", **extra)192 for name in sorted(p.name for p in (_HERE / "static").iterdir() if p.suffix in (".css", ".js")):193 data = (_HERE / "static" / name).read_bytes()194 mime = "text/css; charset=utf-8" if name.endswith(".css") else "text/javascript; charset=utf-8"195 self.node(f"/static/{name}", "static", "asset", 200, mime, sha256=_sha256(data))196197 def _register_dynamic(self) -> None:198 html, node = content.HTML_TYPE, self.node199 node("/robots.txt", "robots", "crawl", 200, "text/plain; charset=utf-8", groups=content.ROBOTS_GROUPS,200 sitemap="/sitemap.xml", note="The Sitemap line is an absolute URL built from the request Host.")201 node("/sitemap.xml", "sitemap", "crawl", 200, "application/xml", sitemap_type="index",202 children=["/sitemap-pages.xml", "/sitemap-products.xml.gz"])203 node("/sitemap-pages.xml", "sitemap", "crawl", 200, "application/xml", sitemap_type="urlset",204 urls=content.SITEMAP_PAGES)205 node("/sitemap-products.xml.gz", "sitemap", "crawl", 200, "application/gzip", sitemap_type="urlset",206 compression="gzip", urls=content.SITEMAP_PRODUCTS)207 node("/favicon.ico", "image", "asset", 200, "image/png")208 node("/blog?page=6", "page", "error", 404, html, note="Beyond the last blog page; nothing links here.")209 self.unlinked.add("/blog?page=6")210211 node("/trap/pages?page=1", "page", "trap", 200, html, trap_kind="endless_pagination",212 pattern="/trap/pages?page=N", note="Every page links to page N+1 (rel=next).")213 node("/trap/calendar/2026/12", "page", "trap", 200, html, trap_kind="calendar",214 pattern="/trap/calendar/YYYY/M", note="Every month links to the previous and the next month.")215 node("/trap/facets", "page", "trap", 200, html, trap_kind="faceted_navigation",216 pattern="/trap/facets?color=&size=&sort=&price_max=", facets=content.FACETS,217 note="Every combination is linked, with the parameters in rotating order; price_max grows without bound.")218219 for status in (403, 404, 410, 500):220 node(f"/err/{status}", "page", "error", status, html)221 node("/err/429", "page", "error", 429, html, status_sequence=[429, 429, 200], retry_after_seconds=1,222 success_text="RATE-LIMIT-PASSED-3382",223 note="First two hits per client answer 429; the client is the X-Fixture-Client header or IP + User-Agent.")224 node("/err/slow", "page", "error", 200, html, default_delay_ms=1000, max_delay_ms=30000,225 note="Waits ?ms=N milliseconds before answering.")226 node("/err/big", "binary", "error", 200, "application/octet-stream", body_bytes=50 * 1024 * 1024,227 transfer="chunked", fetch_in_tests="bounded", note="Streams 50 MiB of zero bytes (?mb=N for less).")228 node("/err/gzip-bomb", "page", "error", 200, html, content_encoding="gzip",229 inflated_bytes=assets.GZIP_BOMB_INFLATED_BYTES, fetch_in_tests="raw",230 note="About 100 kB on the wire, 100 MiB once inflated.")231 node("/err/bad-encoding", "page", "error", 200, html, actual_encoding="latin-1",232 text_snippets=[content.BAD_ENCODING_TEXT])233 node("/err/wrong-mime", "page", "error", 200, "image/png", actual_type="text/html",234 text_snippets=["WRONG-MIME-HTML-9015"])235 node("/err/truncated", "page", "error", 200, html, declared_content_length=4096, fetch_in_tests="raw",236 note="The connection closes after about 100 bytes.")237238 node("/cond/etag", "page", "crawl", 200, html, etag=content.ETAG_VALUE, text_snippets=["COND-ETAG-4407"])239 node("/cond/lastmod", "page", "crawl", 200, html, last_modified=content.LAST_MODIFIED,240 text_snippets=["COND-LASTMOD-5126"])241 node("/cond/changing", "page", "crawl", 200, html, title="Harbour bulletin",242 variants=[243 {"index": i, "changed": content.CHANGING_DIFFS[i], "etag": f'"changing-v{i}"', **variant,244 "sha256": _sha256(content.changing_page(i))}245 for i, variant in enumerate(content.CHANGING_VARIANTS)246 ],247 selectors={"text": "#status-text", "price": "#price", "availability": "#availability",248 "layout": "#changing"},249 bump="POST /__fixture/bump", active_variant="X-Fixture-Variant header, meta[name=fixture-variant], "250 "GET /__fixture/state")251 node("/mobile/ua", "page", "crawl", 200, html, vary="User-Agent",252 user_agent_variants={253 "desktop": {"text": content.DESKTOP_UA_TEXT, "title": "Timetable (desktop edition)"},254 "mobile": {"text": content.MOBILE_UA_TEXT, "title": "Timetable (mobile edition)",255 "user_agent_tokens": list(content.MOBILE_UA_TOKENS)},256 })257 node("/docs/report.pdf", "document", "crawl", 200, "application/pdf", pages=len(assets.REPORT_PAGES),258 has_text_layer=True, page_text=[list(lines) for lines in assets.REPORT_PAGES])259 node("/docs/scan.pdf", "document", "crawl", 200, "application/pdf", pages=1, has_text_layer=False,260 pixel_text="\n".join(assets.SCAN_LINES))261262 for name in ("requests", "state", "manifest"):263 node(f"/__fixture/{name}", "control", "forbidden_robots", 200, "application/json; charset=utf-8",264 method="GET")265 self.unlinked.add(f"/__fixture/{name}")266 for name in ("reset", "bump"):267 node(f"/__fixture/{name}", "control", "forbidden_robots", 200, "application/json; charset=utf-8",268 method="POST")269 self.unlinked.add(f"/__fixture/{name}")270 self.unlinked.add("/private/deeper") # only linked from a page that robots.txt forbids271272 # -- link graph ---------------------------------------------------------273274 def resolve(self, base: str, href: str) -> str | None:275 """Map a raw link to a manifest path, registering external URLs and aliases on the way."""276 parts = urlsplit(href)277 if parts.scheme and parts.scheme not in ("http", "https"):278 self.non_http_links.setdefault(base, []).append(href)279 return None280 if parts.netloc:281 url = href.split("#")[0]282 if url not in self.nodes:283 private = _is_private_host(parts.hostname or "")284 self.node(url, "external", "external", None, None, ssrf_target=private,285 **({"note": "Private or link-local address: must never be requested."} if private else {}))286 return url287 absolute = urlsplit(urljoin(base, href))288 raw = absolute.path + (f"?{absolute.query}" if absolute.query else "")289 query = dict(parse_qsl(absolute.query))290 for candidate in (raw, content.page_key(absolute.path, query), absolute.path):291 if candidate in self.nodes:292 if candidate != raw:293 aliases = self.nodes[candidate].setdefault("aliases", [])294 if raw not in aliases:295 aliases.append(raw)296 return candidate297 raise ValueError(f"{base} links to {href}, which the manifest does not describe")298299 def edges(self) -> tuple[dict[str, list[tuple[str, str, str]]], dict[str, list[tuple[str, str, str]]]]:300 http: dict[str, list[tuple[str, str, str]]] = {}301 for path, page in list(content.PAGES.items()):302 if page.kind != "page":303 continue304 for href, via in extract_links(page.body):305 target = self.resolve(path, href)306 if target and target != path:307 http.setdefault(path, []).append((target, via, "http"))308 for path, (_, location) in content.REDIRECTS.items():309 http.setdefault(path, []).append((self.resolve(path, location), "redirect", "http"))310 http["/robots.txt"] = [("/sitemap.xml", "sitemap", "http")]311 http["/sitemap.xml"] = [(child, "sitemap", "http") for child in self.nodes["/sitemap.xml"]["children"]]312 for sitemap in self.nodes["/sitemap.xml"]["children"]:313 http[sitemap] = [(self.resolve(sitemap, url), "sitemap", "http") for url in self.nodes[sitemap]["urls"]]314 script: dict[str, list[tuple[str, str, str]]] = {}315 for parent, child, via, requires in content.JS_EDGES:316 script.setdefault(parent, []).append((self.resolve(parent, child), via, requires))317 return http, script318319 def walk(self) -> None:320 http, script = self.edges()321322 def bfs(queue: deque[str], graphs: tuple[dict, ...]) -> None:323 while queue:324 current = queue.popleft()325 source = self.nodes[current]326 # A compliant crawler never reads forbidden, external, trap or error responses.327 if source["expected"] not in ("crawl", "asset") and source["kind"] != "redirect":328 continue329 for graph in graphs:330 for target, via, requires in graph.get(current, ()):331 entry = self.nodes[target]332 if entry["depth"] is not None:333 continue334 entry["depth"] = source["depth"] + 1335 entry["discovered_via"] = via336 entry["discovered_from"] = current337 entry["requires"] = max(requires, source["requires"], key=REQUIRES_ORDER.__getitem__)338 queue.append(target)339340 for seed in SEEDS:341 self.nodes[seed].update(depth=0, requires="http", discovered_via="seed")342 bfs(deque(SEEDS), (http,))343 reached = sorted((p for p, n in self.nodes.items() if n["depth"] is not None), key=lambda p: self.nodes[p]["depth"])344 bfs(deque(reached), (http, script))345346 missing = [p for p, n in self.nodes.items() if n["depth"] is None and p not in self.unlinked]347 if missing:348 raise ValueError(f"manifest entries that nothing links to: {missing}")349 for path in self.unlinked:350 self.nodes[path]["requires"] = "http"351352 # -- output -------------------------------------------------------------353354 def regions(self) -> dict:355 measured = json.loads(REGIONS_PATH.read_text("utf-8")) if REGIONS_PATH.is_file() else {"regions": {}}356 for path, selectors in content.CAPTURE_SELECTORS.items():357 rects = measured["regions"].get(path, {})358 self.nodes[path]["capture_regions"] = [359 {"selector": selector, "rect": rects.get(selector), "fixed_geometry": fixed}360 for selector, fixed in selectors361 ]362 return {key: value for key, value in measured.items() if key != "regions"}363364 def manifest(self) -> dict:365 self.register()366 self.walk()367 measurement = self.regions()368 entries = list(self.nodes.values())369 counts: dict[str, int] = {}370 for entry in entries:371 counts[entry["expected"]] = counts.get(entry["expected"], 0) + 1372 return {373 "schema_version": SCHEMA_VERSION,374 "generated_by": "tests/fixtures/site/spider_fixture_manifest.py --write",375 "viewport": content.VIEWPORT,376 "region_tolerance_px": REGION_TOLERANCE_PX,377 "region_measurement": measurement,378 "seeds": list(SEEDS),379 "robots": {"path": "/robots.txt", "groups": content.ROBOTS_GROUPS, "sitemap": "/sitemap.xml"},380 "tracking_params": content.TRACKING_PARAMS,381 "significant_params": {path: spec[0] for path, spec in content.SIGNIFICANT_PARAMS.items()},382 "trap_prefixes": ["/trap/", "/loop/"],383 "side_effect_endpoints": [{"method": "POST", "path": path} for path in content.SIDE_EFFECT_ENDPOINTS],384 "side_effect_rule": "Any request whose method is not GET, HEAD or OPTIONS, outside /__fixture/, is "385 "recorded in state.side_effects and answered with 200. The list must stay empty.",386 "control_header": "X-Fixture-Control: 1 (requests to /__fixture/ carrying it are not logged)",387 "non_http_links": self.non_http_links,388 "pixel_text_font": "system sans-serif (Arial or DejaVu Sans), see spider_fixture_assets.font_source()",389 "counts": dict(sorted(counts.items())),390 "urls": entries,391 }392393394def build_manifest() -> dict:395 """Return the manifest as a JSON-compatible dict (pure function of the code and regions.json)."""396 return json.loads(json.dumps(_Builder().manifest(), ensure_ascii=False))397398399def dump(manifest: dict) -> str:400 return json.dumps(manifest, ensure_ascii=False, indent=1) + "\n"401402403def load_manifest() -> dict:404 return json.loads(MANIFEST_PATH.read_text("utf-8"))405406407def main(argv: list[str] | None = None) -> int:408 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])409 group = parser.add_mutually_exclusive_group(required=True)410 group.add_argument("--write", action="store_true", help="regenerate manifest.json")411 group.add_argument("--check", action="store_true", help="fail if manifest.json is stale")412 args = parser.parse_args(argv)413 text = dump(build_manifest())414 if args.write:415 MANIFEST_PATH.write_text(text, "utf-8")416 print(f"wrote {MANIFEST_PATH} ({len(text)} bytes)")417 return 0418 if not MANIFEST_PATH.is_file() or MANIFEST_PATH.read_text("utf-8") != text:419 print("manifest.json is out of date: run spider_fixture_manifest.py --write", file=sys.stderr)420 return 1421 print("manifest.json is in sync")422 return 0423424425if __name__ == "__main__":426 raise SystemExit(main())427