diff --git a/meshterm/services/basemap.py b/meshterm/services/basemap.py index 6f7f40d..6dfd1b5 100644 --- a/meshterm/services/basemap.py +++ b/meshterm/services/basemap.py @@ -44,18 +44,73 @@ from __future__ import annotations import json import logging import os +import ssl import threading import time import urllib.error import urllib.request from collections import OrderedDict from collections.abc import Container +from functools import lru_cache from pathlib import Path from typing import NamedTuple from .. import __version__ from ..core.mvt import Layer, decode_tile, dumps_layers, loads_layers + +#: Where the operating system keeps its CA bundle, most specific first. Only consulted when +#: the default context came up empty (see :func:`_tls_context`) — macOS and Alpine put it at +#: ``/etc/ssl/cert.pem``, Debian and Ubuntu at ``ca-certificates.crt``, Fedora and RHEL under +#: ``/etc/pki``, openSUSE at ``ca-bundle.pem``. Files rather than a bundled copy on purpose: +#: these are the trust decisions the *machine's administrator* has made, kept current by the +#: OS, and shipping our own would quietly freeze a snapshot of them into every release. +_CA_BUNDLES = ( + "/etc/ssl/cert.pem", + "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/ca-bundle.pem", +) + + +@lru_cache(maxsize=1) +def _tls_context() -> ssl.SSLContext | None: + """The TLS context for tile fetches, with a CA bundle found if the default has none. + + A frozen build can have no trust store to consult. Python's default context asks + OpenSSL for one, and on macOS and Linux that is a *filesystem path baked into the + interpreter's own build* — which need not exist on a machine that never installed that + Python, which is every machine a PyInstaller bundle lands on. Every tile fetch then + fails with ``CERTIFICATE_VERIFY_FAILED``; and because a refused fetch is + indistinguishable from empty terrain, the map drew no ground under the nodes and said + nothing about why. Windows is the exception that hid it for so long: its default + context reads the OS certificate store, so the binary there always worked. + + So: keep the default when it actually loaded certificates, and otherwise point it at + the bundle the OS ships (:data:`_CA_BUNDLES`). Verification is never weakened — a map + tile is not worth teaching the app to skip certificate checks, and an unverified + fetcher here would be one import away from being reused somewhere it matters. + + Returns: + A context to pass to ``urlopen``, or ``None`` to accept urllib's default — which + is right whenever that default already works, and is never worse than the failure + it replaces. + """ + try: + context = ssl.create_default_context() + if context.get_ca_certs(): + return None # the platform store answered; leave urllib exactly as it was + for path in _CA_BUNDLES: + if os.path.isfile(path): + context.load_verify_locations(cafile=path) + _log.debug("no default CA store; verifying against %s", path) + return context + _log.debug("no CA bundle found in %s — TLS will likely fail", ", ".join(_CA_BUNDLES)) + return None + except Exception as exc: # noqa: BLE001 - a broken store must not take the map with it + _log.debug("could not build a TLS context, using urllib's default: %s", exc) + return None + #: OpenFreeMap planet TileJSON — its ``tiles`` array holds the current versioned template. DEFAULT_TILEJSON_URL = "https://tiles.openfreemap.org/planet" @@ -478,7 +533,7 @@ class BasemapSource: """ req = urllib.request.Request(url, headers={"User-Agent": _USER_AGENT}) try: - with urllib.request.urlopen(req, timeout=self._timeout) as resp: + with urllib.request.urlopen(req, timeout=self._timeout, context=_tls_context()) as resp: body = resp.read() declared = (resp.headers.get("Content-Length") or "").strip() # A flaky link can end a read early without raising. A body short of its diff --git a/tests/test_map.py b/tests/test_map.py index d7f50e0..aafabce 100644 --- a/tests/test_map.py +++ b/tests/test_map.py @@ -767,7 +767,7 @@ def test_basemap_sends_its_user_agent_on_every_fetch(tmp_path: Path) -> None: src = _offline_source(tmp_path / "cache") seen: list[urllib.request.Request] = [] - def _urlopen(req: urllib.request.Request, timeout: float | None = None): + def _urlopen(req: urllib.request.Request, timeout: float | None = None, context=None): seen.append(req) raise urllib.error.URLError("no network in tests") @@ -782,6 +782,80 @@ def test_basemap_sends_its_user_agent_on_every_fetch(tmp_path: Path) -> None: assert seen[0].get_header("User-agent") == basemap_mod._USER_AGENT +def test_basemap_keeps_the_default_tls_context_when_it_works() -> None: + """A working platform trust store is left alone — urllib's default is passed through.""" + from meshterm.services import basemap as basemap_mod + + basemap_mod._tls_context.cache_clear() + try: + assert basemap_mod._tls_context() is None + finally: + basemap_mod._tls_context.cache_clear() + + +def test_basemap_finds_a_ca_bundle_when_the_default_store_is_empty( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """An empty default store falls back to the OS CA bundle instead of failing every fetch. + + THE macOS bug: a frozen build asks OpenSSL for a trust store at a filesystem path baked + into the interpreter's own build, which need not exist on a machine that never + installed that Python — which is every machine a PyInstaller bundle lands on. Fetches + then failed with ``CERTIFICATE_VERIFY_FAILED``, and because a refused fetch is + indistinguishable from empty terrain the map drew no ground under the nodes and said + nothing. Windows hid it by reading the OS certificate store in its default context. + """ + import ssl + + from meshterm.services import basemap as basemap_mod + + # The file only has to exist: loading is recorded below rather than really parsed, + # so the test pins *which path is chosen* without depending on a PEM being around. + bundle = tmp_path / "cert.pem" + bundle.write_text("# stand-in for the OS bundle\n", encoding="utf-8") + + loaded: list[str] = [] + + class _EmptyStore(ssl.SSLContext): + def get_ca_certs(self, binary_form: bool = False): # type: ignore[override] + return [] + + def load_verify_locations(self, cafile=None, capath=None, cadata=None): # type: ignore[override] + loaded.append(cafile or "") + + monkeypatch.setattr(ssl, "create_default_context", lambda *a, **k: _EmptyStore(ssl.PROTOCOL_TLS_CLIENT)) + monkeypatch.setattr(basemap_mod, "_CA_BUNDLES", (str(tmp_path / "nope.pem"), str(bundle))) + + basemap_mod._tls_context.cache_clear() + try: + ctx = basemap_mod._tls_context() + assert ctx is not None, "no context built despite a readable bundle" + assert loaded == [str(bundle)] # skipped the missing path, used the present one + assert ctx.verify_mode == ssl.CERT_REQUIRED # never verified away to make it work + finally: + basemap_mod._tls_context.cache_clear() + + +def test_basemap_never_disables_verification(monkeypatch: pytest.MonkeyPatch) -> None: + """With no bundle anywhere, the fetch still verifies — it fails rather than trusts.""" + import ssl + + from meshterm.services import basemap as basemap_mod + + class _EmptyStore(ssl.SSLContext): + def get_ca_certs(self, binary_form: bool = False): # type: ignore[override] + return [] + + monkeypatch.setattr(ssl, "create_default_context", lambda *a, **k: _EmptyStore(ssl.PROTOCOL_TLS_CLIENT)) + monkeypatch.setattr(basemap_mod, "_CA_BUNDLES", ("/nonexistent/ca.pem",)) + + basemap_mod._tls_context.cache_clear() + try: + assert basemap_mod._tls_context() is None # urllib's default, still verifying + finally: + basemap_mod._tls_context.cache_clear() + + def test_basemap_user_agent_needs_no_installed_distribution() -> None: """Importing the module must not depend on package metadata being on disk. @@ -1127,7 +1201,7 @@ def test_basemap_http_get_separates_an_answer_from_silence(tmp_path: Path) -> No return False def _fake(result): - def _urlopen(_req, timeout=None): # noqa: ANN001 + def _urlopen(_req, timeout=None, context=None): # noqa: ANN001 if isinstance(result, Exception): raise result return result