diff --git a/docs/user-guide/datasets.md b/docs/user-guide/datasets.md index 4648aac..d5f2fcc 100644 --- a/docs/user-guide/datasets.md +++ b/docs/user-guide/datasets.md @@ -74,6 +74,22 @@ for ds in list_datasets(): print(ds.name, ds.task, ds.n_features, ds.n_classes) ``` +### Downloads and certificates + +`concrete` and `beijing_pm25` are downloaded on first use and then read from the +cache. eigenkit checks the certificate of the server against the CA certificates +of your system and against those of certifi, which the `datasets` extra installs. +So the download also works on the python.org build of Python for macOS, which has +no CA certificates until you run `Install Certificates.command` in its folder in +Applications. + +scikit-learn downloads `california_housing` itself, and it uses only the CA +certificates of Python. On the python.org build of Python for macOS, run +`Install Certificates.command` before you load it. + +Behind a proxy that inspects TLS traffic, set the `SSL_CERT_FILE` environment +variable to a CA bundle that holds the certificate of the proxy. + ## Synthetic generators To choose the size and the seed of a synthetic dataset, call its generator function diff --git a/pyproject.toml b/pyproject.toml index d07c061..10cae4d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -131,6 +131,9 @@ router = [ # Synthetic + real datasets and the sklearn baselines used by them. datasets = [ "scikit-learn>=1.3,<2", + # CA certificates for the downloaded datasets, which the python.org build of + # Python for macOS lacks. 2024.7.4 drops the distrusted GLOBALTRUST roots. + "certifi>=2024.7.4", ] benchmark = [ "matplotlib>=3.7", diff --git a/src/eigenkit/datasets/_cache.py b/src/eigenkit/datasets/_cache.py index 3624644..54005da 100644 --- a/src/eigenkit/datasets/_cache.py +++ b/src/eigenkit/datasets/_cache.py @@ -6,7 +6,9 @@ import hashlib import os +import ssl import tempfile +import urllib.error import urllib.request from pathlib import Path @@ -35,6 +37,23 @@ def _file_hash(filepath: Path) -> str: return h.hexdigest() +def _ssl_context() -> ssl.SSLContext: + """The system's CA certificates, plus certifi's when it is installed. + + The python.org build of Python for macOS has no CA certificates until its + `Install Certificates.command` runs, so the default context alone fails to + verify any server there. certifi's roots are added, not substituted, so a CA + trusted through the system or `SSL_CERT_FILE` still verifies. + """ + context = ssl.create_default_context() + try: + import certifi + except ImportError: + return context + context.load_verify_locations(certifi.where()) + return context + + def cached_download( url: str, filename: str, @@ -73,17 +92,36 @@ def cached_download( else: return filepath - # Download beside the target and rename into place. `urlretrieve` writes - # directly to its destination, so an interrupted download -- a dropped - # connection, a Ctrl-C -- would leave a truncated file at the cache path - # that every later call would return as valid, forever, unless the registry - # entry carries a hash to check it against. + # Download beside the target and rename into place, so an interrupted + # download -- a dropped connection, a Ctrl-C -- never leaves a truncated file + # at the cache path that every later call would return as valid, forever, + # unless the registry entry carries a hash to check it against. with tempfile.NamedTemporaryFile( dir=cache_dir, prefix=f".{filename}.", suffix=".part", delete=False ) as handle: partial = Path(handle.name) try: - urllib.request.urlretrieve(url, partial) # noqa: S310 + try: + with urllib.request.urlopen(url, context=_ssl_context()) as response: # noqa: S310 + # One unbounded read(): unlike read(n) in a loop, it raises + # IncompleteRead when the body is shorter than its Content-Length. + # The registry's datasets are a few MB, so they fit in memory. + partial.write_bytes(response.read()) + except urllib.error.URLError as exc: + if isinstance(exc.reason, ssl.SSLCertVerificationError): + # With an errno beside it, the message prints as text, not as + # the repr of a one-element tuple. + raise ssl.SSLCertVerificationError( + exc.reason.errno, + f"Could not verify the TLS certificate of {url}: {exc.reason}. " + "Python has no CA certificate that signs it. On the python.org " + "build of Python for macOS, run 'Install Certificates.command' " + "in the Python folder of Applications, or install certifi " + "(pip install certifi). Behind a proxy that inspects TLS, set " + "the SSL_CERT_FILE environment variable to a CA bundle that " + "holds the proxy's certificate.", + ) from exc + raise if expected_hash is not None: actual = _file_hash(partial) if actual != expected_hash: diff --git a/tests/datasets/test_cache.py b/tests/datasets/test_cache.py index 6f12fed..bce0a88 100644 --- a/tests/datasets/test_cache.py +++ b/tests/datasets/test_cache.py @@ -1,10 +1,15 @@ """Tests for the dataset cache system (_cache.py).""" import hashlib +import io import os +import ssl +import urllib.error from pathlib import Path from unittest.mock import patch +import pytest + from eigenkit.datasets._cache import ( DEFAULT_CACHE_DIR, cached_download, @@ -34,11 +39,11 @@ def test_cached_download_creates_file(tmp_path): url = "http://example.com/data.csv" filename = "data.csv" - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(content) + def fake_urlopen(url, context): + return io.BytesIO(content) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve) as mock_dl: + with patch("urllib.request.urlopen", side_effect=fake_urlopen) as mock_dl: path = cached_download(url, filename) assert path.exists() assert path.read_bytes() == content @@ -55,7 +60,7 @@ def test_cached_download_uses_cache(tmp_path): cached_file.write_bytes(content) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve") as mock_dl: + with patch("urllib.request.urlopen") as mock_dl: path = cached_download(url, filename) mock_dl.assert_not_called() assert path == cached_file @@ -74,11 +79,11 @@ def test_cached_download_rehashes_corrupt(tmp_path): cached_file = tmp_path / filename cached_file.write_bytes(corrupt) - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(content) + def fake_urlopen(url, context): + return io.BytesIO(content) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve) as mock_dl: + with patch("urllib.request.urlopen", side_effect=fake_urlopen) as mock_dl: path = cached_download(url, filename, expected_hash=expected_hash) mock_dl.assert_called_once() assert path.read_bytes() == content @@ -90,10 +95,43 @@ def test_cached_download_hash_verified(tmp_path): filename = "good.csv" expected_hash = hashlib.sha256(content).hexdigest() - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(content) + def fake_urlopen(url, context): + return io.BytesIO(content) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve): + with patch("urllib.request.urlopen", side_effect=fake_urlopen): path = cached_download(url, filename, expected_hash=expected_hash) assert path.exists() + + +def test_certifi_roots_are_trusted_when_python_ships_none(tmp_path, monkeypatch): + """The python.org build of Python for macOS has no CA certificates until + `Install Certificates.command` runs, so OpenSSL's default paths are empty and + every HTTPS download fails verification.""" + pytest.importorskip("certifi") + monkeypatch.setenv("EIGENKIT_DATA_DIR", str(tmp_path)) + monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "missing.pem")) + monkeypatch.setenv("SSL_CERT_DIR", str(tmp_path / "missing")) + contexts = [] + + def fake_urlopen(url, context): + contexts.append(context) + return io.BytesIO(b"a,b\n1,2\n") + + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + cached_download("https://example.com/data.csv", "data.csv") + assert contexts[0].cert_store_stats()["x509_ca"] > 0 + + +def test_a_certificate_error_says_how_to_fix_it(tmp_path, monkeypatch): + monkeypatch.setenv("EIGENKIT_DATA_DIR", str(tmp_path)) + + def fake_urlopen(url, context): + raise urllib.error.URLError(ssl.SSLCertVerificationError("verify failed")) + + monkeypatch.setattr("urllib.request.urlopen", fake_urlopen) + with pytest.raises(ssl.SSLCertVerificationError, match="Install Certificates") as e: + cached_download("https://example.com/data.csv", "data.csv") + assert str(e.value).startswith("Could not verify"), "printed as a tuple" + assert "SSL_CERT_FILE" in str(e.value) + assert list(tmp_path.iterdir()) == [], "a partial download was left cached" diff --git a/tests/datasets/test_cache_and_labels.py b/tests/datasets/test_cache_and_labels.py index 042ea69..0e63ab3 100644 --- a/tests/datasets/test_cache_and_labels.py +++ b/tests/datasets/test_cache_and_labels.py @@ -15,7 +15,7 @@ from __future__ import annotations -from pathlib import Path +import io from urllib.error import URLError import numpy as np @@ -45,13 +45,13 @@ def test_a_failed_download_caches_nothing(self, cache): def test_a_completed_download_is_cached_and_reused(self, cache, monkeypatch): calls = [] - def fake_urlretrieve(url, path): + def fake_urlopen(url, context): calls.append(url) - Path(path).write_text("a,b\n1,2\n") + return io.BytesIO(b"a,b\n1,2\n") monkeypatch.setattr( - "eigenkit.datasets._cache.urllib.request.urlretrieve", - fake_urlretrieve, + "eigenkit.datasets._cache.urllib.request.urlopen", + fake_urlopen, ) first = cached_download("http://example/x.csv", "x.csv") second = cached_download("http://example/x.csv", "x.csv") diff --git a/tests/datasets/test_loaders.py b/tests/datasets/test_loaders.py index 2b6a0d5..d1fde5f 100644 --- a/tests/datasets/test_loaders.py +++ b/tests/datasets/test_loaders.py @@ -2,7 +2,6 @@ import io import os -from pathlib import Path from unittest.mock import patch import numpy as np @@ -117,11 +116,11 @@ def _make_concrete_csv(n_rows: int = 50) -> bytes: def test_concrete_dataset_shapes(tmp_path): csv_bytes = _make_concrete_csv(50) - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(csv_bytes) + def fake_urlopen(url, context): + return io.BytesIO(csv_bytes) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve): + with patch("urllib.request.urlopen", side_effect=fake_urlopen): data = load_dataset("concrete", random_state=42) assert {"X_train", "y_train", "X_test", "y_test", "metadata"} <= data.keys() @@ -133,11 +132,11 @@ def fake_urlretrieve(url, dest): def test_concrete_dataset_y_is_float(tmp_path): csv_bytes = _make_concrete_csv(50) - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(csv_bytes) + def fake_urlopen(url, context): + return io.BytesIO(csv_bytes) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve): + with patch("urllib.request.urlopen", side_effect=fake_urlopen): data = load_dataset("concrete", random_state=42) assert data["y_train"].dtype == np.float32 @@ -158,11 +157,11 @@ def _make_beijing_csv(n_rows: int = 100) -> bytes: def test_beijing_pm25_dataset_shapes(tmp_path): csv_bytes = _make_beijing_csv(100) - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(csv_bytes) + def fake_urlopen(url, context): + return io.BytesIO(csv_bytes) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve): + with patch("urllib.request.urlopen", side_effect=fake_urlopen): data = load_dataset("beijing_pm25", random_state=42) assert {"X_train", "y_train", "X_test", "y_test", "metadata"} <= data.keys() @@ -174,11 +173,11 @@ def fake_urlretrieve(url, dest): def test_beijing_pm25_chronological_split(tmp_path): csv_bytes = _make_beijing_csv(100) - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(csv_bytes) + def fake_urlopen(url, context): + return io.BytesIO(csv_bytes) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve): + with patch("urllib.request.urlopen", side_effect=fake_urlopen): data = load_dataset("beijing_pm25", test_size=0.2, random_state=42) raw = np.loadtxt(io.BytesIO(csv_bytes), delimiter=",", skiprows=1) @@ -193,11 +192,11 @@ def fake_urlretrieve(url, dest): def test_beijing_pm25_no_split(tmp_path): csv_bytes = _make_beijing_csv(100) - def fake_urlretrieve(url, dest): - Path(dest).write_bytes(csv_bytes) + def fake_urlopen(url, context): + return io.BytesIO(csv_bytes) with patch.dict(os.environ, {"EIGENKIT_DATA_DIR": str(tmp_path)}): - with patch("urllib.request.urlretrieve", side_effect=fake_urlretrieve): + with patch("urllib.request.urlopen", side_effect=fake_urlopen): data = load_dataset("beijing_pm25", split=False) assert {"X", "y", "metadata"} <= data.keys() diff --git a/uv.lock b/uv.lock index b7e25bc..094fe75 100644 --- a/uv.lock +++ b/uv.lock @@ -1049,6 +1049,7 @@ dependencies = [ [package.optional-dependencies] all = [ { name = "amazon-braket-sdk" }, + { name = "certifi" }, { name = "cirq-core" }, { name = "cuda-quantum-cu13", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or sys_platform == 'linux'" }, { name = "cudaq", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or sys_platform == 'linux'" }, @@ -1097,6 +1098,7 @@ cudaquantum = [ { name = "cudaq", marker = "(platform_machine == 'arm64' and sys_platform == 'darwin') or sys_platform == 'linux'" }, ] datasets = [ + { name = "certifi" }, { name = "scikit-learn" }, ] iqm = [ @@ -1172,6 +1174,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "amazon-braket-sdk", marker = "extra == 'braket'", specifier = ">=1.117,<2" }, + { name = "certifi", marker = "extra == 'datasets'", specifier = ">=2024.7.4" }, { name = "cirq-core", marker = "extra == 'qsim'", specifier = ">=1.4" }, { name = "cuda-quantum-cu13", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'cudaquantum'", specifier = ">=0.14.0,!=0.16.0.post1" }, { name = "cuda-quantum-cu13", marker = "sys_platform == 'linux' and extra == 'cudaquantum'", specifier = ">=0.14.0" },