|
| 1 | +#!/usr/bin/env -S uv run |
| 2 | +# /// script |
| 3 | +# requires-python = ">=3.11" |
| 4 | +# dependencies = [ |
| 5 | +# "PyJWT", |
| 6 | +# "requests", |
| 7 | +# "cryptography", |
| 8 | +# ] |
| 9 | +# /// |
| 10 | +""" |
| 11 | +GitHub App Token Generator with caching |
| 12 | +
|
| 13 | +Generates an installation access token from GitHub App credentials in environment. |
| 14 | +Caches tokens and reuses them until they expire (with 5-minute buffer). |
| 15 | +
|
| 16 | +Environment variables required: |
| 17 | +- GH_APP_ID: GitHub App ID |
| 18 | +- GH_APP_PRIVATE_KEY_PEM_B64: Base64-encoded private key |
| 19 | +
|
| 20 | +Usage: |
| 21 | + # Run with uv (automatically installs dependencies) |
| 22 | + uv run get_github_app_token.py |
| 23 | +
|
| 24 | + # Save to file |
| 25 | + uv run get_github_app_token.py > token.txt |
| 26 | +
|
| 27 | + # Use in shell |
| 28 | + export GITHUB_TOKEN=$(uv run get_github_app_token.py) |
| 29 | +""" |
| 30 | + |
| 31 | +import base64 |
| 32 | +import json |
| 33 | +import os |
| 34 | +import sys |
| 35 | +import time |
| 36 | +from datetime import datetime, timezone |
| 37 | +from pathlib import Path |
| 38 | + |
| 39 | +import jwt |
| 40 | +import requests |
| 41 | + |
| 42 | +# Cache file location |
| 43 | +CACHE_FILE = Path("/tmp/gh_app_token_cache.json") |
| 44 | +# Buffer time before expiration (5 minutes) |
| 45 | +EXPIRATION_BUFFER_SECONDS = 300 |
| 46 | + |
| 47 | + |
| 48 | +def get_cached_token(): |
| 49 | + """Get cached token if it exists and is still valid.""" |
| 50 | + if not CACHE_FILE.exists(): |
| 51 | + return None |
| 52 | + |
| 53 | + try: |
| 54 | + with open(CACHE_FILE, 'r') as f: |
| 55 | + cache_data = json.load(f) |
| 56 | + |
| 57 | + token = cache_data.get('token') |
| 58 | + expires_at_str = cache_data.get('expires_at') |
| 59 | + |
| 60 | + if not token or not expires_at_str: |
| 61 | + return None |
| 62 | + |
| 63 | + # Parse expiration time (GitHub returns ISO 8601 format) |
| 64 | + expires_at = datetime.fromisoformat(expires_at_str.replace('Z', '+00:00')) |
| 65 | + now = datetime.now(timezone.utc) |
| 66 | + |
| 67 | + # Check if token is still valid (with buffer) |
| 68 | + time_until_expiry = (expires_at - now).total_seconds() |
| 69 | + |
| 70 | + if time_until_expiry > EXPIRATION_BUFFER_SECONDS: |
| 71 | + print(f"Using cached token (expires in {int(time_until_expiry/60)} minutes)", file=sys.stderr) |
| 72 | + return token |
| 73 | + else: |
| 74 | + print("Cached token expired or expiring soon, generating new token", file=sys.stderr) |
| 75 | + return None |
| 76 | + |
| 77 | + except (json.JSONDecodeError, ValueError, KeyError) as e: |
| 78 | + print(f"Error reading cache: {e}, generating new token", file=sys.stderr) |
| 79 | + return None |
| 80 | + |
| 81 | + |
| 82 | +def save_token_to_cache(token, expires_at): |
| 83 | + """Save token and expiration to cache file.""" |
| 84 | + cache_data = { |
| 85 | + 'token': token, |
| 86 | + 'expires_at': expires_at, |
| 87 | + 'cached_at': datetime.now(timezone.utc).isoformat() |
| 88 | + } |
| 89 | + |
| 90 | + try: |
| 91 | + with open(CACHE_FILE, 'w') as f: |
| 92 | + json.dump(cache_data, f) |
| 93 | + print("Token cached successfully", file=sys.stderr) |
| 94 | + except Exception as e: |
| 95 | + print(f"Warning: Failed to cache token: {e}", file=sys.stderr) |
| 96 | + |
| 97 | + |
| 98 | +def generate_installation_token(): |
| 99 | + """Generate a new installation access token for the GitHub App.""" |
| 100 | + # Get credentials from environment |
| 101 | + app_id = os.getenv("GH_APP_ID") |
| 102 | + private_key_b64 = os.getenv("GH_APP_PRIVATE_KEY_PEM_B64") |
| 103 | + |
| 104 | + if not all([app_id, private_key_b64]): |
| 105 | + print("Error: Missing GH_APP_ID or GH_APP_PRIVATE_KEY_PEM_B64", file=sys.stderr) |
| 106 | + sys.exit(1) |
| 107 | + |
| 108 | + # Decode private key |
| 109 | + private_key = base64.b64decode(private_key_b64).decode('utf-8') |
| 110 | + |
| 111 | + # Generate JWT |
| 112 | + now = int(time.time()) |
| 113 | + payload = { |
| 114 | + "iat": now - 60, |
| 115 | + "exp": now + (10 * 60), |
| 116 | + "iss": app_id, |
| 117 | + } |
| 118 | + jwt_token = jwt.encode(payload, private_key, algorithm="RS256") |
| 119 | + |
| 120 | + # Get installations |
| 121 | + headers = { |
| 122 | + "Authorization": f"Bearer {jwt_token}", |
| 123 | + "Accept": "application/vnd.github+json", |
| 124 | + "X-GitHub-Api-Version": "2022-11-28", |
| 125 | + } |
| 126 | + |
| 127 | + response = requests.get("https://api.github.com/app/installations", headers=headers) |
| 128 | + response.raise_for_status() |
| 129 | + installations = response.json() |
| 130 | + |
| 131 | + if not installations: |
| 132 | + print("Error: No installations found for this GitHub App", file=sys.stderr) |
| 133 | + sys.exit(1) |
| 134 | + |
| 135 | + # Create installation token |
| 136 | + installation_id = installations[0]['id'] |
| 137 | + url = f"https://api.github.com/app/installations/{installation_id}/access_tokens" |
| 138 | + response = requests.post(url, headers=headers) |
| 139 | + response.raise_for_status() |
| 140 | + |
| 141 | + token_info = response.json() |
| 142 | + |
| 143 | + # Save to cache |
| 144 | + save_token_to_cache(token_info['token'], token_info['expires_at']) |
| 145 | + |
| 146 | + return token_info['token'] |
| 147 | + |
| 148 | + |
| 149 | +def get_token(): |
| 150 | + """Get a valid token, either from cache or by generating a new one.""" |
| 151 | + # Try to get cached token first |
| 152 | + cached_token = get_cached_token() |
| 153 | + if cached_token: |
| 154 | + return cached_token |
| 155 | + |
| 156 | + # Generate new token if cache miss or expired |
| 157 | + print("Generating new GitHub App token", file=sys.stderr) |
| 158 | + return generate_installation_token() |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + try: |
| 163 | + token = get_token() |
| 164 | + print(token) |
| 165 | + except Exception as e: |
| 166 | + print(f"Error: {e}", file=sys.stderr) |
| 167 | + sys.exit(1) |
0 commit comments