"""Whose certificates Spellcast3D's HTTPS trusts: the system's authorities, and the list of them that ships with Python's packages (certifi's: Mozilla's list). STDLIB ONLY (the installer downloads with it). Why. Python on Windows reads Windows' certificate stores as they stand: its authorities (ROOT), of which Windows fetches one only when a program of its OWN first needs it, and the intermediates it has met (CA), which stay cached. A cached intermediate counts as trusted, so a chain is built on from it inside the stores alone - and where the certificate above it was never fetched, Python alone fails with "certificate verify failed: unable to get issuer certificate", though every browser opens the site (seen with github.com). - context(), urlopen(): the downloads this package makes itself (install/models.py, install/preflight.py). They take from Windows the authorities alone, and the intermediates from the server, as every other system does: no cached intermediate can end a chain, whichever site it is of. - child_env(): the Python programs it starts (a tool's own installer, torch.hub inside a tool), through paths.clean_env. An environment cannot take Windows' cached intermediates away from them; it adds the shipped list, which helps where that list holds what stands above the cached one (github.com's does). - refused(), refused_words(), Refused: an artist's words for a certificate that is refused all the same (a program that re-signs secure connections with a certificate of its own is in no shipped list). """ from __future__ import annotations import functools import os import ssl import sys import urllib.request from pathlib import Path from typing import Any from . import paths # How a refused certificate reads, lower-cased: Python's ssl (whatever the cause), pip, and git with either of its # two HTTPS backends. _REFUSED = ("certificate_verify_failed", "problem confirming the ssl certificate", "ssl certificate problem", "sec_e_untrusted_root") class Refused(OSError): """A download of this package stopped at a refused certificate. Its text is refused_words(), ready for the artist: no other try changes it, and it is no connection problem.""" def refused(text: object) -> bool: """Does an error's text (or a line a program printed) tell of a refused certificate.""" said = str(text).lower() return any(mark in said for mark in _REFUSED) def refused_words(site: str = "") -> str: """What to tell the artist: `site` the server, when the caller knows it (the log names it otherwise).""" where = site or f"a download site ({paths.shown(paths.log_file('install'))} names it)" return (f"This computer refused the security certificate of {where}, so nothing could be downloaded from it; " f"the internet connection itself works. Mostly a program that inspects secure connections is in the " f"way (an antivirus's web or HTTPS scanning, a company proxy, a VPN): pause it, or try another network. " f"A wrong date on this computer does the same. Then start Spellcast3D again; finished downloads are " f"kept.") def bundle(python_home: Path) -> Path | None: """The list of certificate authorities in a Python environment (a venv, or the base Python): certifi's when the environment has it - the very file its requests / httpx use - else the copy inside its pip. None: neither.""" packages = (python_home / "Lib" / "site-packages" if os.name == "nt" else python_home / "lib" / f"python{sys.version_info[0]}.{sys.version_info[1]}" / "site-packages") for found in (packages / "certifi" / "cacert.pem", packages / "pip" / "_vendor" / "certifi" / "cacert.pem"): if found.is_file(): return found return None def shipped() -> Path | None: """The list this copy of Spellcast3D has for its own downloads - ONE, the newest there is, so that an authority a newer list dropped is not trusted on from an older one: the hub venv's (its pin moves with every release), else the running Python's (the installer runs on the base Python before there is a hub venv), else the portable git's.""" found = (bundle(paths.venv_dir(paths.HUB)), bundle(Path(sys.prefix)), paths.PORTABLE_GIT_DIR / "mingw64" / "etc" / "ssl" / "certs" / "ca-bundle.crt") return next((path for path in found if path is not None and path.is_file()), None) def _windows_authorities(made: ssl.SSLContext) -> None: """Windows' ROOT store into `made`, as ssl's own default does - and not its CA store (the module's words).""" try: for der, encoding, trust in ssl.enum_certificates("ROOT"): if encoding == "x509_asn" and (trust is True or ssl.Purpose.SERVER_AUTH.oid in trust): try: made.load_verify_locations(cadata=der) except ssl.SSLError: # a damaged certificate in the store pass except OSError: # the store cannot be read: shipped()'s authorities remain pass @functools.cache def context() -> ssl.SSLContext: """What the package's own downloads verify with (made once a process): the certificate and the host's name, against the system's authorities and shipped()'s. An SSL_CERT_FILE / SSL_CERT_DIR of the artist's own counts too. A list that cannot be read is left out.""" if os.name == "nt": made = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) made.set_default_verify_paths() # (the artist's SSL_CERT_FILE / SSL_CERT_DIR) _windows_authorities(made) else: made = ssl.create_default_context() path = shipped() if path is not None: try: made.load_verify_locations(cafile=str(path)) except (OSError, ssl.SSLError): pass return made def urlopen(request: urllib.request.Request | str, timeout: float) -> Any: """urllib.request.urlopen with context().""" return urllib.request.urlopen(request, timeout=timeout, context=context()) def child_env(venv_id: str | None, env: dict[str, str]) -> dict[str, str]: """What to add to `env` so that a Python program started in a venv trusts that venv's list too: SSL_CERT_FILE (Python on Windows adds the file to the Windows stores' certificates; httpx, which reads the variable in place of certifi's file, gets the same file), and OPENSSL_WIN32_UTF8, without which OpenSSL reads the variable in the PC's ANSI code page and silently finds no file in a folder with other letters. Nothing when the artist set an SSL_CERT_FILE or SSL_CERT_DIR themselves that is there (theirs stand), and Windows alone: elsewhere the variable would stand in for the system's own file.""" if os.name != "nt" or venv_id is None: return {} if os.path.isfile(env.get("SSL_CERT_FILE", "")) or os.path.isdir(env.get("SSL_CERT_DIR", "")): return {} found = bundle(paths.venv_dir(venv_id)) return {"SSL_CERT_FILE": str(found), "OPENSSL_WIN32_UTF8": "1"} if found is not None else {}