|
| 1 | +"""GitHub App authentication for explicitly configured installation owners.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import base64 |
| 6 | +import json |
| 7 | +import re |
| 8 | +import subprocess |
| 9 | +import threading |
| 10 | +import time |
| 11 | +from collections.abc import Mapping |
| 12 | +from datetime import datetime |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | +from urllib.parse import quote, urlsplit |
| 16 | +from urllib.request import Request |
| 17 | + |
| 18 | +from github_backup.config import GitHubConfig, ScopeKind |
| 19 | +from github_backup.errors import ConfigurationError, GitHubAPIError |
| 20 | +from github_backup.github import GitHubClient |
| 21 | +from github_backup.models import Resource |
| 22 | + |
| 23 | + |
| 24 | +class InstallationClient(GitHubClient): |
| 25 | + def authenticated_user(self) -> str: |
| 26 | + return "installation" |
| 27 | + |
| 28 | + def repositories(self, scope: ScopeKind, organizations: tuple[str, ...]) -> list[Resource]: |
| 29 | + # Reuse the normal resource parser with installation-specific pagination. |
| 30 | + return super().repositories(scope, organizations) |
| 31 | + |
| 32 | + def _paginate( |
| 33 | + self, path: str, parameters: Mapping[str, str], *, list_key: str | None = None |
| 34 | + ) -> Any: |
| 35 | + if path == "/user/repos": |
| 36 | + path, parameters, list_key = "/installation/repositories", {}, "repositories" |
| 37 | + return super()._paginate(path, parameters, list_key=list_key) |
| 38 | + |
| 39 | + |
| 40 | +class AppClient(GitHubClient): |
| 41 | + def __init__(self, config: GitHubConfig) -> None: |
| 42 | + super().__init__(config, self._jwt) |
| 43 | + self._app = GitHubClient(config, self._jwt) |
| 44 | + self._lock = threading.RLock() |
| 45 | + self._installations: dict[str, int] = {} |
| 46 | + self._tokens: dict[str, tuple[str, float]] = {} |
| 47 | + self._clients: dict[str, InstallationClient] = {} |
| 48 | + for owner in config.app_owners: |
| 49 | + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9-]*", owner): |
| 50 | + raise ConfigurationError(f"Invalid GitHub installation owner: {owner}") |
| 51 | + |
| 52 | + def _jwt(self) -> str: |
| 53 | + def encode(value: bytes) -> str: |
| 54 | + return base64.urlsafe_b64encode(value).rstrip(b"=").decode("ascii") |
| 55 | + |
| 56 | + now = int(time.time()) |
| 57 | + header = encode(b'{"alg":"RS256","typ":"JWT"}') |
| 58 | + payload = encode( |
| 59 | + json.dumps({"iat": now - 60, "exp": now + 540, "iss": self._config.app_id}).encode() |
| 60 | + ) |
| 61 | + signing_input = f"{header}.{payload}" |
| 62 | + key = Path(self._config.app_private_key).expanduser() |
| 63 | + try: |
| 64 | + if key.stat().st_mode & 0o077: |
| 65 | + raise ConfigurationError("App private key must have permissions 0600 or 0400") |
| 66 | + result = subprocess.run( |
| 67 | + ["openssl", "dgst", "-sha256", "-sign", str(key)], |
| 68 | + input=signing_input.encode(), |
| 69 | + capture_output=True, |
| 70 | + check=True, |
| 71 | + timeout=30, |
| 72 | + ) |
| 73 | + except (OSError, subprocess.SubprocessError) as exc: |
| 74 | + raise ConfigurationError("Cannot sign App JWT; check private key and openssl") from exc |
| 75 | + return f"{signing_input}.{encode(result.stdout)}" |
| 76 | + |
| 77 | + def _client(self, owner: str) -> InstallationClient: |
| 78 | + owner = owner.casefold() |
| 79 | + with self._lock: |
| 80 | + if owner not in self._clients: |
| 81 | + try: |
| 82 | + installation = self._app.get_json(f"/users/{quote(owner)}/installation") |
| 83 | + except GitHubAPIError as exc: |
| 84 | + if exc.status_code != 404: |
| 85 | + raise |
| 86 | + installation = self._app.get_json(f"/orgs/{quote(owner)}/installation") |
| 87 | + if not isinstance(installation, dict) or "id" not in installation: |
| 88 | + raise GitHubAPIError(f"Invalid installation response for {owner}") |
| 89 | + account = installation.get("account", {}) |
| 90 | + if str(account.get("login", "")).casefold() != owner: |
| 91 | + raise GitHubAPIError("Installation account does not match configured owner") |
| 92 | + if installation.get("repository_selection") != "all": |
| 93 | + raise GitHubAPIError(f"Install the App on All repositories for {owner}") |
| 94 | + if installation.get("suspended_at"): |
| 95 | + raise GitHubAPIError(f"App installation suspended for {owner}") |
| 96 | + self._installations[owner] = int(installation["id"]) |
| 97 | + self._clients[owner] = InstallationClient( |
| 98 | + self._config, lambda: self._installation_token(owner) |
| 99 | + ) |
| 100 | + return self._clients[owner] |
| 101 | + |
| 102 | + def _installation_token(self, owner: str) -> str: |
| 103 | + with self._lock: |
| 104 | + cached = self._tokens.get(owner) |
| 105 | + if cached and cached[1] > time.time() + 300: |
| 106 | + return cached[0] |
| 107 | + url = self._absolute_api_url( |
| 108 | + f"/app/installations/{self._installations[owner]}/access_tokens" |
| 109 | + ) |
| 110 | + request = Request( |
| 111 | + url, data=b"{}", headers=self._headers("application/vnd.github+json"), method="POST" |
| 112 | + ) |
| 113 | + try: |
| 114 | + with self._open(request, timeout=self._config.timeout_seconds) as response: |
| 115 | + payload = json.loads(response.read()) |
| 116 | + token = payload["token"] |
| 117 | + expires = datetime.fromisoformat(payload["expires_at"].replace("Z", "+00:00")) |
| 118 | + if ( |
| 119 | + not isinstance(token, str) |
| 120 | + or not token |
| 121 | + or expires.timestamp() <= time.time() + 300 |
| 122 | + ): |
| 123 | + raise ValueError("invalid token") |
| 124 | + except Exception as exc: |
| 125 | + raise GitHubAPIError(f"Cannot obtain installation token for {owner}") from exc |
| 126 | + self._tokens[owner] = (token, expires.timestamp()) |
| 127 | + return token |
| 128 | + |
| 129 | + def authenticated_user(self) -> str: |
| 130 | + for owner in self._config.app_owners: |
| 131 | + self._client(owner) |
| 132 | + return ",".join(self._config.app_owners) |
| 133 | + |
| 134 | + def repositories(self, scope: ScopeKind, organizations: tuple[str, ...]) -> list[Resource]: |
| 135 | + repos: dict[str, Resource] = {} |
| 136 | + for owner in self._config.app_owners: |
| 137 | + for repo in self._client(owner).repositories(scope, organizations): |
| 138 | + repos[repo.identifier] = repo |
| 139 | + return sorted(repos.values(), key=lambda repo: repo.relative_path.casefold()) |
| 140 | + |
| 141 | + def _owner_client(self, path: str) -> InstallationClient: |
| 142 | + parsed = urlsplit(self._absolute_api_url(path)) |
| 143 | + api = urlsplit(self._config.api_url) |
| 144 | + if (parsed.scheme, parsed.netloc) != (api.scheme, api.netloc): |
| 145 | + raise GitHubAPIError("App request attempted to use a different API origin") |
| 146 | + relative = parsed.path.removeprefix(api.path.rstrip("/")) |
| 147 | + parts = relative.strip("/").split("/") |
| 148 | + if len(parts) < 2 or parts[0] not in ("repos", "orgs", "users"): |
| 149 | + raise GitHubAPIError("Cannot route App request to an installation") |
| 150 | + owner = parts[1].casefold() |
| 151 | + if owner not in {value.casefold() for value in self._config.app_owners}: |
| 152 | + raise GitHubAPIError("Request owner is outside configured installations") |
| 153 | + return self._client(owner) |
| 154 | + |
| 155 | + def _request_json(self, path_or_url: str) -> tuple[Any, Mapping[str, str]]: |
| 156 | + return self._owner_client(path_or_url)._request_json(path_or_url) |
| 157 | + |
| 158 | + def download(self, path_or_url: str, destination: Path) -> int: |
| 159 | + return self._owner_client(path_or_url).download(path_or_url, destination) |
| 160 | + |
| 161 | + def git_token(self, url: str) -> str: |
| 162 | + parsed = urlsplit(url) |
| 163 | + api_host = urlsplit(self._config.api_url).hostname |
| 164 | + git_host = "github.com" if api_host == "api.github.com" else api_host |
| 165 | + if parsed.scheme != "https" or parsed.hostname != git_host: |
| 166 | + raise GitHubAPIError("Git remote is outside the configured GitHub host") |
| 167 | + owner = parsed.path.strip("/").split("/")[0].casefold() |
| 168 | + if owner not in {value.casefold() for value in self._config.app_owners}: |
| 169 | + raise GitHubAPIError("Git owner is outside configured installations") |
| 170 | + self._client(owner) |
| 171 | + return self._installation_token(owner) |
0 commit comments