diff --git a/scripts/build_data.py b/scripts/build_data.py index 259b177a..2cc55c69 100644 --- a/scripts/build_data.py +++ b/scripts/build_data.py @@ -45,6 +45,9 @@ TESSDATA_LICENSE_URL = f"{TESSDATA_BASE_URL}/LICENSE" UNKNOWN_IMAGE_URL = "https://assets.tarkov.dev/unknown-item-base-image.webp" USER_AGENT = "RatScannerDataBuilder/1.0 (+https://github.com/TarkovTracker-org/RatScannerData)" +ALLOWED_SOURCE_HOSTS = frozenset( + {"assets.tarkov.dev", "json.tarkov.dev", "raw.githubusercontent.com"} +) SAFE_ITEM_ID = re.compile(r"^[A-Za-z0-9_-]+$") # Map ids are 24-character hex strings; both carried folders are keyed by them. @@ -94,6 +97,21 @@ def sha256_bytes(content: bytes) -> str: return hashlib.sha256(content).hexdigest() +def require_allowed_source(url: str) -> None: + parsed = urllib.parse.urlsplit(url) + if parsed.scheme != "https" or parsed.hostname not in ALLOWED_SOURCE_HOSTS: + raise ValueError(f"Only HTTPS sources on allowed hosts are permitted: {url}") + + +class SourceRedirectHandler(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + require_allowed_source(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +SOURCE_OPENER = urllib.request.build_opener(SourceRedirectHandler()) + + def fetch_bytes( url: str, *, @@ -103,9 +121,7 @@ def fetch_bytes( ) -> bytes: """Download a URL with bounded retry/backoff for transient failures.""" - parsed = urllib.parse.urlparse(url) - if parsed.scheme != "https": - raise ValueError(f"Only HTTPS sources are allowed: {url}") + require_allowed_source(url) request = urllib.request.Request( url, @@ -113,7 +129,7 @@ def fetch_bytes( ) for attempt in range(1, attempts + 1): try: - with urllib.request.urlopen(request, timeout=timeout_seconds) as response: + with SOURCE_OPENER.open(request, timeout=timeout_seconds) as response: return response.read() except urllib.error.HTTPError as error: retryable = error.code == 429 or 500 <= error.code < 600 @@ -981,7 +997,7 @@ def parse_arguments() -> argparse.Namespace: parser.add_argument( "--catalog-url", default=CATALOG_URL, - help="tarkov.dev item catalog URL", + help="Item catalog URL on an allowed HTTPS source host", ) parser.add_argument( "--workers", diff --git a/scripts/test_download_policy.py b/scripts/test_download_policy.py new file mode 100644 index 00000000..96e47750 --- /dev/null +++ b/scripts/test_download_policy.py @@ -0,0 +1,48 @@ +"""Offline checks for the builder's outbound source policy.""" + +import unittest +import urllib.request +from unittest.mock import patch + +from scripts import build_data + + +class DownloadPolicyTests(unittest.TestCase): + def test_configured_https_sources_are_allowed(self) -> None: + for url in ( + build_data.CATALOG_URL, + build_data.MAP_CATALOG_URL, + build_data.MAPS_URL, + build_data.UNKNOWN_IMAGE_URL, + build_data.TESSDATA_LICENSE_URL, + build_data.TARKOV_DEV_LICENSE_URL, + ): + with self.subTest(url=url): + build_data.require_allowed_source(url) + + def test_unapproved_initial_url_is_rejected_before_open(self) -> None: + with patch.object(build_data.SOURCE_OPENER, "open") as open_source: + with self.assertRaisesRegex(ValueError, "allowed hosts"): + build_data.fetch_bytes("https://example.invalid/catalog") + open_source.assert_not_called() + + def test_unapproved_redirect_is_rejected_before_request_creation(self) -> None: + handler = build_data.SourceRedirectHandler() + request = urllib.request.Request(build_data.MAPS_URL) + for url in ("https://example.invalid/map", "http://assets.tarkov.dev/map"): + with ( + self.subTest(url=url), + patch.object(urllib.request.HTTPRedirectHandler, "redirect_request") as redirect, + self.assertRaisesRegex(ValueError, "allowed hosts"), + ): + handler.redirect_request(request, None, 302, "Found", {}, url) + redirect.assert_not_called() + + def test_approved_redirect_keeps_standard_request_behavior(self) -> None: + handler = build_data.SourceRedirectHandler() + request = urllib.request.Request( + build_data.MAPS_URL, headers={"Accept": "application/json"} + ) + redirected = handler.redirect_request(request, None, 302, "Found", {}, build_data.MAPS_URL) + self.assertEqual(redirected.full_url, build_data.MAPS_URL) + self.assertEqual(redirected.get_header("Accept"), "application/json")