|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import logging |
1 | 4 | import os |
| 5 | +from typing import TYPE_CHECKING |
| 6 | +from urllib.parse import urlparse |
| 7 | + |
| 8 | +import requests.auth |
| 9 | +from requests.utils import get_netrc_auth |
2 | 10 |
|
3 | | -from .http_retry import create_retry_session |
| 11 | +from .http_retry import RetryHTTPAdapter |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
4 | 14 |
|
5 | 15 | # Enhanced retry configuration for fromager |
6 | 16 | FROMAGER_RETRY_CONFIG = { |
|
11 | 21 | "raise_on_status": False, |
12 | 22 | } |
13 | 23 |
|
14 | | -# Create a session with enhanced retry capabilities |
15 | | -session = create_retry_session( |
16 | | - retry_config=FROMAGER_RETRY_CONFIG, |
17 | | - timeout=float(os.environ.get("FROMAGER_HTTP_TIMEOUT", "120.0")), |
18 | | -) |
| 24 | +GITHUB_API_URL = os.environ.get("GITHUB_API_URL", "https://api.github.com") |
| 25 | + |
| 26 | +GITLAB_CI_SERVER_URL = os.environ.get("CI_SERVER_URL", "https://gitlab.com") |
| 27 | +GITLAB_JOB_TOKEN_NAME = "gitlab-ci-token" |
| 28 | + |
| 29 | + |
| 30 | +if TYPE_CHECKING: |
| 31 | + from collections.abc import Callable |
| 32 | + |
| 33 | + _AuthCallback = Callable[[str, str], dict[str, str]] |
| 34 | + |
| 35 | + |
| 36 | +class SessionAuth(requests.auth.AuthBase): |
| 37 | + """Authentication handler that dispatches by ``(scheme, hostname)``. |
| 38 | +
|
| 39 | + The requests library only supports a single ``session.auth`` handler |
| 40 | + and does not provide per-host authentication on mounted adapters. |
| 41 | + This class fills that gap by mapping ``(scheme, hostname)`` keys to |
| 42 | + auth resolver callbacks. On the first request to a given host the |
| 43 | + callback is invoked and the result is cached. |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__(self) -> None: |
| 47 | + self._callbacks: dict[tuple[str, str], _AuthCallback] = {} |
| 48 | + self._cache: dict[tuple[str, str], dict[str, str]] = {} |
| 49 | + |
| 50 | + def add(self, url: str, callback: _AuthCallback) -> None: |
| 51 | + """Register a resolver *callback* for the scheme and hostname of *url*.""" |
| 52 | + parsed = urlparse(url) |
| 53 | + scheme = parsed.scheme |
| 54 | + hostname = parsed.hostname or "" |
| 55 | + if scheme not in {"http", "https"}: |
| 56 | + raise ValueError(f"Unsupported scheme {scheme!r} in URL {url!r}") |
| 57 | + if not hostname: |
| 58 | + raise ValueError(f"Missing hostname in URL {url!r}") |
| 59 | + key = (scheme, hostname) |
| 60 | + self._cache.pop(key, None) |
| 61 | + self._callbacks[key] = callback |
| 62 | + |
| 63 | + def get(self, url: str) -> dict[str, str]: |
| 64 | + """Resolve and return the auth headers for *url*. |
| 65 | +
|
| 66 | + Invokes the registered callback on first access and caches the |
| 67 | + result. Returns an empty dict when no callback is registered. |
| 68 | + """ |
| 69 | + parsed = urlparse(url) |
| 70 | + key = (parsed.scheme, parsed.hostname or "") |
| 71 | + if key not in self._cache: |
| 72 | + callback = self._callbacks.get(key) |
| 73 | + self._cache[key] = callback(*key) if callback else {} |
| 74 | + return dict(self._cache[key]) |
| 75 | + |
| 76 | + def __call__(self, r: requests.PreparedRequest) -> requests.PreparedRequest: |
| 77 | + auth_header = self.get(r.url or "") |
| 78 | + if auth_header: |
| 79 | + r.headers.update(auth_header) |
| 80 | + return r |
| 81 | + |
| 82 | + |
| 83 | +def _resolve_github_auth(scheme: str, hostname: str) -> dict[str, str]: |
| 84 | + """Resolve GitHub auth header from netrc or environment.""" |
| 85 | + url = f"{scheme}://{hostname}" |
| 86 | + netrc_auth = get_netrc_auth(url) |
| 87 | + if netrc_auth is not None: |
| 88 | + _login, password = netrc_auth |
| 89 | + logger.debug("GitHub auth: using netrc credentials for %s", url) |
| 90 | + return {"Authorization": f"token {password}"} |
| 91 | + |
| 92 | + token = os.environ.get("GITHUB_TOKEN") |
| 93 | + if token: |
| 94 | + logger.debug("GitHub auth: using GITHUB_TOKEN environment variable") |
| 95 | + return {"Authorization": f"token {token}"} |
| 96 | + return {} |
| 97 | + |
| 98 | + |
| 99 | +def _resolve_gitlab_auth(scheme: str, hostname: str) -> dict[str, str]: |
| 100 | + """Resolve GitLab auth header from netrc or environment.""" |
| 101 | + url = f"{scheme}://{hostname}" |
| 102 | + netrc_auth = get_netrc_auth(url) |
| 103 | + if netrc_auth is not None: |
| 104 | + login, password = netrc_auth |
| 105 | + header = "JOB-TOKEN" if login == GITLAB_JOB_TOKEN_NAME else "PRIVATE-TOKEN" |
| 106 | + logger.debug("GitLab auth: using netrc credentials for %s (%s)", url, header) |
| 107 | + return {header: password} |
| 108 | + |
| 109 | + token = os.environ.get("CI_JOB_TOKEN") |
| 110 | + if token: |
| 111 | + logger.debug("GitLab auth: using CI_JOB_TOKEN environment variable") |
| 112 | + return {"JOB-TOKEN": token} |
| 113 | + |
| 114 | + token = os.environ.get("GITLAB_PRIVATE_TOKEN") |
| 115 | + if token: |
| 116 | + logger.debug("GitLab auth: using GITLAB_PRIVATE_TOKEN environment variable") |
| 117 | + return {"PRIVATE-TOKEN": token} |
| 118 | + return {} |
| 119 | + |
| 120 | + |
| 121 | +def create_session() -> tuple[requests.Session, SessionAuth]: |
| 122 | + """Create a requests session with retry and authentication. |
| 123 | +
|
| 124 | + Mounts a `RetryHTTPAdapter` on ``http://`` and ``https://``. |
| 125 | + Registers lazy auth callbacks for GitHub and GitLab on a |
| 126 | + `SessionAuth` handler keyed by ``(scheme, hostname)``. |
| 127 | +
|
| 128 | + Returns the session and its `SessionAuth` so callers can |
| 129 | + register additional auth callbacks via ``auth.add()``. |
| 130 | + """ |
| 131 | + adapter = RetryHTTPAdapter( |
| 132 | + retry_config=FROMAGER_RETRY_CONFIG, |
| 133 | + timeout=float(os.environ.get("FROMAGER_HTTP_TIMEOUT", "120.0")), |
| 134 | + ) |
| 135 | + |
| 136 | + s = requests.Session() |
| 137 | + s.mount("http://", adapter) |
| 138 | + s.mount("https://", adapter) |
| 139 | + |
| 140 | + auth = SessionAuth() |
| 141 | + auth.add(GITHUB_API_URL, _resolve_github_auth) |
| 142 | + auth.add(GITLAB_CI_SERVER_URL, _resolve_gitlab_auth) |
| 143 | + s.auth = auth |
| 144 | + |
| 145 | + return s, auth |
| 146 | + |
| 147 | + |
| 148 | +session, session_auth = create_session() |
0 commit comments