|
| 1 | +"""GitHub App authentication utilities.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import time |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import aiohttp |
| 8 | +import jwt |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class GitHubAppAuth: |
| 14 | + """GitHub App authentication helper.""" |
| 15 | + |
| 16 | + def __init__(self, app_id: str, private_key: str): |
| 17 | + """Initialize GitHub App authentication. |
| 18 | +
|
| 19 | + Args: |
| 20 | + app_id: GitHub App ID |
| 21 | + private_key: GitHub App private key (PEM format) |
| 22 | + """ |
| 23 | + self.app_id = app_id |
| 24 | + self.private_key = private_key |
| 25 | + |
| 26 | + def generate_jwt(self, expiration_seconds: int = 600) -> str: |
| 27 | + """Generate a JWT for GitHub App authentication. |
| 28 | +
|
| 29 | + Args: |
| 30 | + expiration_seconds: JWT expiration time in seconds (max 600) |
| 31 | +
|
| 32 | + Returns: |
| 33 | + JWT token string |
| 34 | + """ |
| 35 | + now = int(time.time()) |
| 36 | + payload = { |
| 37 | + "iat": now |
| 38 | + - 60, # Issued at time (60 seconds in the past to account for clock drift) |
| 39 | + "exp": now + expiration_seconds, # Expiration time |
| 40 | + "iss": self.app_id, # Issuer (GitHub App ID) |
| 41 | + } |
| 42 | + |
| 43 | + # Generate JWT using RS256 algorithm |
| 44 | + token = jwt.encode(payload, self.private_key, algorithm="RS256") |
| 45 | + logger.debug(f"Generated JWT for GitHub App {self.app_id}") |
| 46 | + return str(token) |
| 47 | + |
| 48 | + async def get_installation_id(self, repo: str, jwt_token: str) -> Optional[int]: |
| 49 | + """Get the installation ID for a repository. |
| 50 | +
|
| 51 | + Args: |
| 52 | + repo: Repository name in format "owner/repo" |
| 53 | + jwt_token: JWT token for authentication |
| 54 | +
|
| 55 | + Returns: |
| 56 | + Installation ID or None if not found |
| 57 | + """ |
| 58 | + url = f"https://api.github.com/repos/{repo}/installation" |
| 59 | + headers = { |
| 60 | + "Authorization": f"Bearer {jwt_token}", |
| 61 | + "Accept": "application/vnd.github+json", |
| 62 | + "X-GitHub-Api-Version": "2022-11-28", |
| 63 | + } |
| 64 | + |
| 65 | + async with aiohttp.ClientSession() as session: |
| 66 | + async with session.get(url, headers=headers) as response: |
| 67 | + if response.status == 200: |
| 68 | + data = await response.json() |
| 69 | + installation_id: Optional[int] = data.get("id") |
| 70 | + logger.info( |
| 71 | + f"Found installation ID {installation_id} for repo {repo}" |
| 72 | + ) |
| 73 | + return installation_id |
| 74 | + else: |
| 75 | + error_text = await response.text() |
| 76 | + logger.error( |
| 77 | + f"Failed to get installation ID for {repo}: HTTP {response.status}" |
| 78 | + ) |
| 79 | + logger.error(f"Response: {error_text}") |
| 80 | + return None |
| 81 | + |
| 82 | + async def get_installation_token( |
| 83 | + self, installation_id: int, jwt_token: str |
| 84 | + ) -> Optional[str]: |
| 85 | + """Get an installation access token. |
| 86 | +
|
| 87 | + Args: |
| 88 | + installation_id: GitHub App installation ID |
| 89 | + jwt_token: JWT token for authentication |
| 90 | +
|
| 91 | + Returns: |
| 92 | + Installation access token or None if failed |
| 93 | + """ |
| 94 | + url = ( |
| 95 | + f"https://api.github.com/app/installations/{installation_id}/access_tokens" |
| 96 | + ) |
| 97 | + headers = { |
| 98 | + "Authorization": f"Bearer {jwt_token}", |
| 99 | + "Accept": "application/vnd.github+json", |
| 100 | + "X-GitHub-Api-Version": "2022-11-28", |
| 101 | + } |
| 102 | + |
| 103 | + async with aiohttp.ClientSession() as session: |
| 104 | + async with session.post(url, headers=headers) as response: |
| 105 | + if response.status == 201: |
| 106 | + data = await response.json() |
| 107 | + token: Optional[str] = data.get("token") |
| 108 | + expires_at = data.get("expires_at") |
| 109 | + logger.info( |
| 110 | + f"Generated installation token (expires at {expires_at})" |
| 111 | + ) |
| 112 | + return token |
| 113 | + else: |
| 114 | + error_text = await response.text() |
| 115 | + logger.error( |
| 116 | + f"Failed to get installation token: HTTP {response.status}" |
| 117 | + ) |
| 118 | + logger.error(f"Response: {error_text}") |
| 119 | + return None |
| 120 | + |
| 121 | + async def get_token_for_repo(self, repo: str) -> Optional[str]: |
| 122 | + """Get an installation access token for a specific repository. |
| 123 | +
|
| 124 | + This is a convenience method that combines JWT generation, installation ID lookup, |
| 125 | + and installation token generation. |
| 126 | +
|
| 127 | + Args: |
| 128 | + repo: Repository name in format "owner/repo" |
| 129 | +
|
| 130 | + Returns: |
| 131 | + Installation access token or None if failed |
| 132 | + """ |
| 133 | + # Generate JWT |
| 134 | + jwt_token = self.generate_jwt() |
| 135 | + |
| 136 | + # Get installation ID |
| 137 | + installation_id = await self.get_installation_id(repo, jwt_token) |
| 138 | + if not installation_id: |
| 139 | + return None |
| 140 | + |
| 141 | + # Get installation token |
| 142 | + return await self.get_installation_token(installation_id, jwt_token) |
| 143 | + |
| 144 | + |
| 145 | +def load_private_key_from_file(file_path: str) -> str: |
| 146 | + """Load GitHub App private key from a file. |
| 147 | +
|
| 148 | + Args: |
| 149 | + file_path: Path to the private key file |
| 150 | +
|
| 151 | + Returns: |
| 152 | + Private key content as string |
| 153 | +
|
| 154 | + Raises: |
| 155 | + FileNotFoundError: If the file doesn't exist |
| 156 | + IOError: If the file can't be read |
| 157 | + """ |
| 158 | + with open(file_path, "r") as f: |
| 159 | + return f.read() |
0 commit comments