"""Provide curl_cffi with a CA bundle path safe for native Windows curl.""" from __future__ import annotations import hashlib import os import tempfile import threading from pathlib import Path try: import certifi except ImportError: # pragma: no cover - declared in requirements.txt certifi = None # type: ignore[assignment] _cached_path = "" _cache_lock = threading.Lock() def _is_ascii_path(path: Path) -> bool: return str(path).isascii() def _source_bundle() -> Path | None: for variable in ("CURL_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"): configured = os.getenv(variable, "").strip() if not configured: continue path = Path(configured).expanduser().resolve() if not path.is_file(): raise RuntimeError(f"{variable}_NOT_FOUND: {path}") return path if certifi is None: return None path = Path(certifi.where()).resolve() if not path.is_file(): raise RuntimeError(f"CERTIFI_CA_BUNDLE_NOT_FOUND: {path}") return path def _candidate_cache_dirs() -> list[Path]: values = [ os.getenv("CURL_CA_ASCII_DIR", "").strip(), os.getenv("CURL_CA_CACHE_DIR", "").strip(), tempfile.gettempdir(), str(Path(os.getenv("LOCALAPPDATA", "")) / "Temp") if os.getenv("LOCALAPPDATA") else "", str(Path(os.getenv("SystemRoot", "")) / "Temp") if os.getenv("SystemRoot") else "", ] result: list[Path] = [] seen: set[str] = set() for value in values: if not value: continue path = Path(value).expanduser().resolve() key = os.path.normcase(str(path)) if key in seen or not _is_ascii_path(path): continue seen.add(key) result.append(path) return result def curl_ca_bundle_path() -> str: """Return an existing ASCII-only CA path, copying certifi when necessary.""" global _cached_path if _cached_path and Path(_cached_path).is_file(): return _cached_path with _cache_lock: if _cached_path and Path(_cached_path).is_file(): return _cached_path source = _source_bundle() if source is None: return "" if _is_ascii_path(source): _cached_path = str(source) return _cached_path data = source.read_bytes() if b"BEGIN CERTIFICATE" not in data: raise RuntimeError("CERTIFI_CA_BUNDLE_INVALID") digest = hashlib.sha256(data).hexdigest() filename = f"protocol-card-ca-{digest[:16]}.pem" failures: list[str] = [] for directory in _candidate_cache_dirs(): temporary: Path | None = None target = directory / filename try: directory.mkdir(parents=True, exist_ok=True) if target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == digest: _cached_path = str(target) return _cached_path temporary = directory / ( f".{filename}.{os.getpid()}.{threading.get_ident()}.tmp" ) temporary.write_bytes(data) os.replace(temporary, target) if hashlib.sha256(target.read_bytes()).hexdigest() != digest: raise RuntimeError("CA_CACHE_HASH_MISMATCH") _cached_path = str(target) return _cached_path except Exception as exc: try: if target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == digest: _cached_path = str(target) return _cached_path except Exception: pass failures.append(f"{directory}={type(exc).__name__}") if temporary is not None: try: temporary.unlink(missing_ok=True) except Exception: pass raise RuntimeError( "CURL_CA_ASCII_CACHE_UNAVAILABLE: " + "; ".join(failures) ) def curl_session_kwargs() -> dict[str, object]: path = curl_ca_bundle_path() return {"verify": path} if path else {} def is_ca_bundle_error(exc: Exception) -> bool: detail = f"{type(exc).__name__}: {exc}".lower() return any( marker in detail for marker in ( "curl: (77)", "error adding trust anchors", "curl_ca_ascii_cache_unavailable", "ca_bundle_not_found", "certifi_ca_bundle", "ca_cache_hash_mismatch", ) )