mirror of
https://github.com/IgorAherne/Spellcast3d.git
synced 2026-12-01 08:06:27 -10:00
277 lines
16 KiB
Python
277 lines
16 KiB
Python
"""Whose certificates Spellcast3D's HTTPS trusts (spellcast/certs.py): the system's plus the list that ships with
|
|
Python's packages - for its own downloads, and for the Python programs it starts on Windows - and what the artist is
|
|
told when a certificate is refused all the same. No test here uses the network."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import urllib.error
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from spellcast import certs, paths
|
|
from spellcast.install import components, models, preflight
|
|
from spellcast.install.runner import Ctx, InstallError, Output
|
|
|
|
REFUSAL = ("[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get issuer certificate "
|
|
"(_ssl.c:1006)")
|
|
# An authority of this file's own (its key was thrown away): in no store and in no shipped list.
|
|
TEST_AUTHORITY = """-----BEGIN CERTIFICATE-----
|
|
MIIBojCCAUegAwIBAgIUd0gLS2YS681/2Fey1spnNvfoaYYwCgYIKoZIzj0EAwIw
|
|
JTEjMCEGA1UEAwwaU3BlbGxjYXN0M0QgdGVzdCBhdXRob3JpdHkwIBcNMjYxMTMw
|
|
MTkzNjQyWhgPMjEyNjExMDYxOTM2NDJaMCUxIzAhBgNVBAMMGlNwZWxsY2FzdDNE
|
|
IHRlc3QgYXV0aG9yaXR5MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAESfeK1txp
|
|
S3ysWEE5dQsZMGKlxW2H/U3EVtwGZ16Q1UAtCbNBFtgkOleNRAiyqXAtsp44jIq3
|
|
mv3inPDtDY+UCKNTMFEwHQYDVR0OBBYEFAKfnrBjIZVRJLDHJh4ofmsYZITgMB8G
|
|
A1UdIwQYMBaAFAKfnrBjIZVRJLDHJh4ofmsYZITgMA8GA1UdEwEB/wQFMAMBAf8w
|
|
CgYIKoZIzj0EAwIDSQAwRgIhAJ3JiRs3K/uwD6BAE5LRELiVVGsd1Xt2Mbc8jTPw
|
|
ZTh9AiEAxtmCAIQjmMVCalnYT8KVfpdtc6Ee/T/7lWQuMo7J5lI=
|
|
-----END CERTIFICATE-----
|
|
"""
|
|
TRUSTS_IT = ("import ssl; print(any('Spellcast3D test authority' in str(found.get('subject')) "
|
|
"for found in ssl.create_default_context().get_ca_certs()))")
|
|
|
|
|
|
def _site_packages(home: Path) -> Path:
|
|
if os.name == "nt":
|
|
return home / "Lib" / "site-packages"
|
|
return home / "lib" / f"python{sys.version_info[0]}.{sys.version_info[1]}" / "site-packages"
|
|
|
|
|
|
def _list(home: Path, package: str, text: str = "# a list\n") -> Path:
|
|
path = _site_packages(home) / package / "cacert.pem"
|
|
path.parent.mkdir(parents=True)
|
|
path.write_text(text, encoding="utf-8")
|
|
return path
|
|
|
|
|
|
def test_an_environments_list_is_certifis_else_its_pips(tmp_path: Path) -> None:
|
|
assert certs.bundle(tmp_path / "none") is None
|
|
pips = _list(tmp_path / "venv", "pip/_vendor/certifi")
|
|
assert certs.bundle(tmp_path / "venv") == pips
|
|
own = _list(tmp_path / "venv", "certifi")
|
|
assert certs.bundle(tmp_path / "venv") == own, "the file the venv's requests and httpx read"
|
|
|
|
|
|
def test_the_own_downloads_trust_the_system_and_the_newest_shipped_list(tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch) -> None:
|
|
shipped = certs.shipped()
|
|
assert shipped is not None and shipped.is_file(), "the hub's venv has certifi (requirements-hub.txt)"
|
|
certs.context.cache_clear()
|
|
made = certs.context()
|
|
assert made.verify_mode == ssl.CERT_REQUIRED and made.check_hostname
|
|
assert len(made.get_ca_certs()) > 100
|
|
assert certs.context() is made, "made once a process"
|
|
# ONE list, the newest there is (an authority a newer list dropped is not trusted on from an older one): the
|
|
# hub venv's, and the running Python's while there is no hub venv yet (the installer's first run)
|
|
monkeypatch.setattr(paths, "VENVS", tmp_path)
|
|
assert certs.shipped() == certs.bundle(Path(sys.prefix))
|
|
hubs = _list(tmp_path / paths.HUB, "certifi")
|
|
assert certs.shipped() == hubs
|
|
# a list that cannot be read costs nothing: the system's certificates are what there was before
|
|
monkeypatch.setattr(certs, "shipped", lambda: Path(__file__))
|
|
certs.context.cache_clear()
|
|
assert certs.context().verify_mode == ssl.CERT_REQUIRED
|
|
monkeypatch.setattr(certs, "shipped", lambda: None)
|
|
certs.context.cache_clear()
|
|
assert certs.context().verify_mode == ssl.CERT_REQUIRED
|
|
certs.context.cache_clear()
|
|
|
|
|
|
@pytest.mark.skipif(os.name != "nt", reason="Windows' certificate stores")
|
|
def test_of_windows_stores_the_authorities_count_and_no_cached_intermediate(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Python's own default takes Windows' cached intermediates for trusted, and then looks no further than the
|
|
stores for what stands above one - which Windows may never have fetched. The package's downloads take the
|
|
intermediates from the server, as every other system does."""
|
|
cached = ssl.PEM_cert_to_DER_cert(TEST_AUTHORITY)
|
|
names = lambda made: str([found.get("subject") for found in made.get_ca_certs()]) # noqa: E731
|
|
monkeypatch.setattr(ssl, "enum_certificates", lambda store: [(cached, "x509_asn", True)] if store == "CA" else [])
|
|
certs.context.cache_clear()
|
|
assert "Spellcast3D test authority" in names(ssl.create_default_context()), "what Python does by itself"
|
|
assert "Spellcast3D test authority" not in names(certs.context()) and len(certs.context().get_ca_certs()) > 100
|
|
# an authority of Windows' own counts, when it is one for web sites
|
|
for trust, counts in ((True, True), ({ssl.Purpose.SERVER_AUTH.oid}, True), ({ssl.Purpose.CLIENT_AUTH.oid}, False)):
|
|
monkeypatch.setattr(ssl, "enum_certificates",
|
|
lambda store, trust=trust: [(cached, "x509_asn", trust)] if store == "ROOT" else [])
|
|
certs.context.cache_clear()
|
|
assert ("Spellcast3D test authority" in names(certs.context())) is counts, trust
|
|
certs.context.cache_clear()
|
|
|
|
|
|
def test_the_installers_downloads_go_through_that_context(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
asked: list[object] = []
|
|
|
|
def opened(request: object, timeout: float, context: object = None) -> object:
|
|
asked.append(context)
|
|
raise urllib.error.URLError(REFUSAL)
|
|
|
|
monkeypatch.setattr(certs.urllib.request, "urlopen", opened)
|
|
assert certs.refused(preflight._reachable("https://github.com/"))
|
|
assert asked == [certs.context()]
|
|
for module in ("install/models.py", "install/preflight.py"):
|
|
source = (paths.PACKAGE / module).read_text(encoding="utf-8")
|
|
assert "urllib.request.urlopen(" not in source, f"{module} opens a URL without certs.urlopen"
|
|
|
|
|
|
def test_a_python_program_started_on_windows_trusts_its_venvs_list_too(tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr(paths, "VENVS", tmp_path)
|
|
for name in ("SSL_CERT_FILE", "SSL_CERT_DIR"):
|
|
monkeypatch.delenv(name, raising=False)
|
|
assert certs.child_env(None, {}) == {} and certs.child_env("tool", {}) == {}, "no venv, or a venv without a list"
|
|
own = _list(tmp_path / "tool", "certifi")
|
|
if os.name != "nt":
|
|
# elsewhere the variable would stand in for the system's own file of certificates
|
|
assert certs.child_env("tool", {}) == {} and "SSL_CERT_FILE" not in paths.clean_env("tool")
|
|
return
|
|
assert certs.child_env("tool", {}) == {"SSL_CERT_FILE": str(own), "OPENSSL_WIN32_UTF8": "1"}
|
|
env = paths.clean_env("tool")
|
|
assert (env["SSL_CERT_FILE"], env["OPENSSL_WIN32_UTF8"]) == (str(own), "1")
|
|
assert "SSL_CERT_FILE" not in paths.clean_env(None)
|
|
# the artist's own stand, either of the two (OpenSSL reads both) ...
|
|
(tmp_path / "company").mkdir()
|
|
(tmp_path / "company" / "roots.pem").write_text("# theirs\n", encoding="utf-8")
|
|
theirs = {"SSL_CERT_FILE": str(tmp_path / "company" / "roots.pem"), "SSL_CERT_DIR": str(tmp_path / "company")}
|
|
for name, value in theirs.items():
|
|
assert certs.child_env("tool", {name: value}) == {}
|
|
monkeypatch.setenv(name, value)
|
|
env = paths.clean_env("tool")
|
|
assert env[name] == value and "OPENSSL_WIN32_UTF8" not in env
|
|
assert all(env.get(other) is None for other in theirs if other != name)
|
|
monkeypatch.delenv(name)
|
|
# ... unless it names nothing that is there (a leftover of another program): OpenSSL would read no list at all
|
|
monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "gone" / "roots.pem"))
|
|
assert paths.clean_env("tool")["SSL_CERT_FILE"] == str(own)
|
|
|
|
|
|
@pytest.mark.skipif(os.name != "nt", reason="Windows alone gets the variable")
|
|
def test_the_list_is_read_in_a_folder_with_any_letters(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""OpenSSL reads SSL_CERT_FILE itself - in the PC's ANSI code page unless OPENSSL_WIN32_UTF8 says otherwise, and
|
|
then silently finds no file where the folder has other letters."""
|
|
monkeypatch.setattr(paths, "VENVS", tmp_path / "Игорь 模型 José")
|
|
_list(paths.VENVS / "tool", "certifi", TEST_AUTHORITY)
|
|
env = {name: value for name, value in os.environ.items()
|
|
if name not in ("SSL_CERT_FILE", "SSL_CERT_DIR", "OPENSSL_WIN32_UTF8")}
|
|
|
|
def trusts_it() -> str:
|
|
done = subprocess.run([sys.executable, "-c", TRUSTS_IT], env=env, capture_output=True, text=True, timeout=120)
|
|
return done.stdout.strip() or done.stderr
|
|
|
|
assert trusts_it() == "False"
|
|
env.update(certs.child_env("tool", env))
|
|
assert trusts_it() == "True"
|
|
|
|
|
|
def test_a_refused_certificate_is_not_called_a_connection_problem(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
assert certs.refused(REFUSAL) and certs.refused(urllib.error.URLError(REFUSAL)) and not certs.refused("timed out")
|
|
# pip's words, and git's with either of its two HTTPS backends
|
|
for said in ("There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443)",
|
|
"fatal: unable to access 'https://github.com/a/b/': SSL certificate problem: unable to get local "
|
|
"issuer certificate",
|
|
"schannel: next InitializeSecurityContext failed: SEC_E_UNTRUSTED_ROOT (0x80090325)"):
|
|
assert certs.refused(said), said
|
|
assert "the security certificate of github.com," in certs.refused_words("github.com")
|
|
assert paths.log_file("install").name in certs.refused_words(), "no site known: the log names it"
|
|
assert preflight._advice(REFUSAL, "github.com") == certs.refused_words("github.com")
|
|
assert preflight._advice("timed out", "github.com") == "Check your connection, VPN or firewall and start again."
|
|
monkeypatch.setattr(preflight, "_reachable", lambda url: REFUSAL if "pypi" in url else None)
|
|
report = preflight.Report()
|
|
preflight._check_internet(report, [])
|
|
assert len(report.fatal) == 1 and "unable to get issuer certificate" in report.fatal[0]
|
|
assert "certificate of pypi.org" in report.fatal[0] and "antivirus" in report.fatal[0]
|
|
assert "Check your connection" not in report.fatal[0]
|
|
|
|
|
|
def test_a_download_of_the_installers_own_stops_at_a_refused_certificate_and_says_so(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Not six tries and "check your internet connection": no other try changes a refused certificate."""
|
|
tries: list[object] = []
|
|
|
|
def opened(request: object, timeout: float, context: object = None) -> object:
|
|
tries.append(request)
|
|
raise urllib.error.URLError(ssl.SSLCertVerificationError(1, REFUSAL))
|
|
|
|
monkeypatch.setattr(certs.urllib.request, "urlopen", opened)
|
|
monkeypatch.setattr(models.time, "sleep", lambda seconds: pytest.fail("it waited for another try"))
|
|
said: list[str] = []
|
|
with pytest.raises(certs.Refused) as failed:
|
|
models._fetch("https://github.com/a/b/releases/download/x/file.zip", tmp_path / "file.part", 10, said.append,
|
|
"file.zip")
|
|
assert len(tries) == 1 and str(failed.value) == certs.refused_words("github.com")
|
|
with pytest.raises(certs.Refused) as failed:
|
|
models.download_code("https://github.com/a/b/archive/c.zip", "b-c/", "0" * 64, tmp_path / "code", "b's code",
|
|
said.append)
|
|
assert len(tries) == 2 and str(failed.value) == certs.refused_words("github.com")
|
|
# the installer's words for it: the certificate's own, not a connection's
|
|
assert components._download_error(failed.value, "Check your internet connection.").reason == str(failed.value)
|
|
assert components._download_error(OSError("timed out"), "Check your internet connection.").reason \
|
|
== "Check your internet connection."
|
|
# anything else is tried again as before
|
|
monkeypatch.setattr(certs.urllib.request, "urlopen",
|
|
lambda request, timeout, context=None: (_ for _ in ()).throw(urllib.error.URLError("timed out")))
|
|
monkeypatch.setattr(models.time, "sleep", lambda seconds: None)
|
|
with pytest.raises(OSError) as failed:
|
|
models._fetch("https://github.com/a/file.zip", tmp_path / "other.part", 10, said.append, "file.zip")
|
|
assert not isinstance(failed.value, certs.Refused) and "timed out" in str(failed.value)
|
|
assert sum("trying again" in line for line in said) == models.DOWNLOAD_ATTEMPTS - 1
|
|
|
|
|
|
def _ctx(tmp_path: Path) -> tuple[Ctx, list[str]]:
|
|
said: list[str] = []
|
|
out = Output(transient=False)
|
|
out.line = said.append # type: ignore[method-assign]
|
|
out.log_only = lambda text: None # type: ignore[method-assign]
|
|
return Ctx(out=out, dry_run=False, base_python=Path(sys.executable)), said
|
|
|
|
|
|
def test_a_command_that_ends_on_a_refused_certificate_says_so(tmp_path: Path) -> None:
|
|
"""Not "a download was interrupted, start again": starting again changes nothing about a certificate. What a
|
|
command ENDS on counts: a refusal far above was overcome (a second address served the file)."""
|
|
ctx, _said = _ctx(tmp_path)
|
|
|
|
def reason(program: str) -> str:
|
|
with pytest.raises(InstallError) as failed:
|
|
ctx.run([sys.executable, "-c", program], cwd=tmp_path, env=dict(os.environ), fail="generic words")
|
|
return failed.value.reason
|
|
|
|
refused = f"print('Download failed: <urlopen error {REFUSAL}>')\n"
|
|
assert reason(refused + "print('No other address is left.')\nraise SystemExit(1)") == certs.refused_words()
|
|
overcome = "print('\\n'.join('Downloaded from the other address.' for _ in range(80)))\nraise SystemExit(1)"
|
|
assert reason(refused + overcome) == "generic words"
|
|
assert reason("raise SystemExit(1)") == "generic words", "the mark of one command does not stay for the next"
|
|
ctx.run([sys.executable, "-c", f"print({REFUSAL!r})"], cwd=tmp_path, env=dict(os.environ), fail="generic words")
|
|
|
|
|
|
def test_pixal3d_names_the_servers_its_installer_cannot_do_without(monkeypatch: pytest.MonkeyPatch,
|
|
tmp_path: Path) -> None:
|
|
pixal3d = next(c for c in components.COMPONENTS if c.id == paths.PIXAL3D)
|
|
there = tmp_path / "python.exe"
|
|
there.write_text("", encoding="utf-8")
|
|
monkeypatch.setattr(paths, "venv_python", lambda venv_id: there)
|
|
looked_in: list[Path] = []
|
|
|
|
def lacking(*names: str) -> set[str]:
|
|
def missing_in(folder: Path) -> list[str]:
|
|
looked_in.append(folder)
|
|
return list(names)
|
|
|
|
monkeypatch.setattr(type(pixal3d), "_missing_in", staticmethod(missing_in))
|
|
return pixal3d.download_hosts()
|
|
|
|
assert lacking() == set(), "installed and whole: nothing to reach"
|
|
assert lacking("MoGe-2") == {"huggingface.co"}
|
|
assert lacking("DINOv3", "RMBG-2.0") == set(), "these two have a second address elsewhere"
|
|
assert lacking("NAF", "Pixal3D") == {"github.com", "huggingface.co"}
|
|
monkeypatch.setattr(paths, "venv_python", lambda venv_id: tmp_path / "no-venv" / "python.exe")
|
|
assert lacking() == {"github.com"}, "a new venv: the big wheels that are not kept in git"
|
|
assert pixal3d.download_hosts() <= set(components.PROBE_URLS)
|
|
# a link to models/pixal3d that is merely missing is no download: the models are looked for behind it
|
|
monkeypatch.setattr(components, "PIXAL3D_MODELS", tmp_path / "no-link")
|
|
monkeypatch.setattr(paths, "MODELS_PIXAL3D", tmp_path / "models")
|
|
lacking()
|
|
assert looked_in[-1] == tmp_path / "models"
|