"""Selected-URL-only public README PDF retrieval with deterministic safety controls.""" from __future__ import annotations import hashlib import ipaddress import re import time from collections.abc import Callable, Iterable from contextlib import closing from dataclasses import dataclass from datetime import UTC, datetime from pathlib import Path from urllib.parse import parse_qsl, urljoin, urlsplit from uuid import uuid4 import httpx from gcmd_classifier.config import DatasetDocumentSettings from gcmd_classifier.datasets.errors import ( READMEDocumentError, READMEError, READMERetrievalError, READMESelectionError, ) from gcmd_classifier.datasets.models import ( DatasetIdentity, READMERetrievalRecord, RedirectRecord, SourceArtifactReference, ValidatedREADMESelection, ) from gcmd_classifier.datasets.readme_discovery import validate_selection_binding _REDIRECTS = {301, 302, 303, 307, 308} _AUTH_QUERY_NAMES = { "access_token", "api_key", "apikey", "auth", "authorization", "credential", "jwt", "password", "signature", "sig", "token", } _SAFE_HEADERS = {"content-type", "content-length", "content-disposition", "etag", "last-modified"} _PDF_HEADER = re.compile(rb"%PDF-[12]\.\d") _FILENAME = re.compile(r"filename\*?=(?:UTF-8''|\")?([^\";]+)", re.IGNORECASE) Resolver = Callable[[str], Iterable[str]] @dataclass(frozen=True) class RetrievedREADME: """Typed public result plus bounded exact bytes and internal artifact path.""" record: READMERetrievalRecord content: bytes def _retrieval_error(exc: httpx.HTTPError) -> None: if isinstance(exc, httpx.TimeoutException): raise READMERetrievalError("README_TIMEOUT", "README retrieval timed out.") from exc if isinstance(exc, httpx.TransportError): raise READMERetrievalError( "README_TRANSPORT_ERROR", "README connection, TLS, or transport failed." ) from exc raise READMERetrievalError("README_HTTP_ERROR", "README request failed.") from exc def _validated_public_url(url: str) -> tuple[str, str]: if not isinstance(url, str) or not url: raise READMERetrievalError("README_URL_INVALID", "README URL is invalid.") try: parsed = urlsplit(url) port = parsed.port except ValueError as exc: raise READMERetrievalError("README_URL_INVALID", "README URL is malformed.") from exc if parsed.scheme not in {"http", "https"}: raise READMERetrievalError("README_URL_SCHEME", "README URL scheme is not supported.") expected_port = 80 if parsed.scheme == "http" else 443 if port not in (None, expected_port): raise READMERetrievalError("README_URL_PORT", "README URL must use its default port.") if parsed.username is not None or parsed.password is not None: raise READMERetrievalError("README_URL_USERINFO", "README URL contains credentials.") if parsed.fragment: raise READMERetrievalError("README_URL_FRAGMENT", "README URL fragments are prohibited.") host = parsed.hostname if not host or any(character.isspace() for character in host): raise READMERetrievalError("README_URL_HOST", "README URL host is malformed.") try: ascii_host = host.encode("idna").decode("ascii") except UnicodeError as exc: raise READMERetrievalError("README_URL_HOST", "README URL host is malformed.") from exc try: ipaddress.ip_address(ascii_host) except ValueError: labels = ascii_host.rstrip(".").split(".") if ( len(ascii_host) > 253 or not labels or any( not label or len(label) > 63 or label.startswith("-") or label.endswith("-") or re.fullmatch(r"[A-Za-z0-9-]+", label) is None for label in labels ) ): raise READMERetrievalError("README_URL_HOST", "README URL host is malformed.") from None for name, _ in parse_qsl(parsed.query, keep_blank_values=True): normalized = name.strip().lower().replace("-", "_") if normalized in _AUTH_QUERY_NAMES or any( marker in normalized for marker in ("token", "password", "credential", "authorization") ): raise READMERetrievalError( "README_URL_AUTH_QUERY", "README URL contains authentication data." ) return url, host def _resolve_public(host: str, resolver: Resolver) -> tuple[str, ...]: try: values = tuple(str(value) for value in resolver(host)) except Exception as exc: raise READMERetrievalError("README_DNS_FAILURE", "README host resolution failed.") from exc if not values: raise READMERetrievalError("README_DNS_EMPTY", "README host resolved to no addresses.") for value in values: try: address = ipaddress.ip_address(value) except ValueError as exc: raise READMERetrievalError( "README_DNS_ADDRESS_INVALID", "README host resolved to an invalid address." ) from exc if ( not address.is_global or address.is_multicast or address.is_reserved or address.is_unspecified or address.is_loopback or address.is_link_local or address.is_private ): raise READMERetrievalError( "README_NON_PUBLIC_ADDRESS", "README destination is not globally routable." ) return values def _looks_like_login(content_type: str | None, body: bytes) -> bool: sample = body[:16384].lower() if "html" not in (content_type or "").lower() and not sample.lstrip().startswith(b"<"): return False return any( marker in sample for marker in ( b"