File size: 4,693 Bytes
3ec0f02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""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",
        )
    )