forked from farhoodlabs/skills
feat: add github-app-token skill
This commit is contained in:
@@ -0,0 +1,105 @@
|
|||||||
|
---
|
||||||
|
name: github-app-token
|
||||||
|
description: Generate a GitHub installation access token from a GitHub App PEM key, App ID, and Installation ID, then authenticate the gh CLI with it.
|
||||||
|
---
|
||||||
|
|
||||||
|
# GitHub App Token Skill
|
||||||
|
|
||||||
|
Generate a short-lived GitHub installation access token from a GitHub App's credentials and use it to authenticate the `gh` CLI.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
The following environment variables MUST be set before invoking this skill:
|
||||||
|
|
||||||
|
| Variable | Description |
|
||||||
|
|---|---|
|
||||||
|
| `GITHUB_APP_ID` | The numeric App ID from the GitHub App settings page |
|
||||||
|
| `GITHUB_APP_INSTALLATION_ID` | The numeric Installation ID for the target org/user |
|
||||||
|
| `GITHUB_APP_PEM_FILE` | Absolute path to the GitHub App's PEM private key file |
|
||||||
|
|
||||||
|
If any variable is missing, stop and tell the user which ones are required.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
|
||||||
|
### 1. Generate a JWT
|
||||||
|
|
||||||
|
Create a JWT signed with the GitHub App's private key. You MUST use the helper script bundled with this skill:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# generates a JWT valid for 10 minutes
|
||||||
|
TOKEN=$(python3 "$(dirname "$0")/../skills/github-app-token/scripts/generate_jwt.py")
|
||||||
|
```
|
||||||
|
|
||||||
|
If `python3` is not available, fall back to the inline openssl method described in the Fallback section below.
|
||||||
|
|
||||||
|
The JWT uses:
|
||||||
|
- **Algorithm**: RS256
|
||||||
|
- **Header**: `{"alg": "RS256", "typ": "JWT"}`
|
||||||
|
- **Payload**:
|
||||||
|
- `iat`: current time minus 60 seconds (clock drift buffer)
|
||||||
|
- `exp`: current time plus 600 seconds (10 minute max)
|
||||||
|
- `iss`: the `GITHUB_APP_ID`
|
||||||
|
|
||||||
|
### 2. Exchange the JWT for an installation access token
|
||||||
|
|
||||||
|
```bash
|
||||||
|
INSTALL_TOKEN=$(curl -s -X POST \
|
||||||
|
-H "Authorization: Bearer ${TOKEN}" \
|
||||||
|
-H "Accept: application/vnd.github+json" \
|
||||||
|
-H "X-GitHub-Api-Version: 2022-11-28" \
|
||||||
|
"https://api.github.com/app/installations/${GITHUB_APP_INSTALLATION_ID}/access_tokens" \
|
||||||
|
| python3 -c "import sys,json; print(json.load(sys.stdin)['token'])")
|
||||||
|
```
|
||||||
|
|
||||||
|
If the response contains an error (e.g., `401 Unauthorized`), check:
|
||||||
|
1. The PEM key matches the App ID
|
||||||
|
2. The Installation ID is valid for this App
|
||||||
|
3. The system clock is accurate (JWT `iat`/`exp` are time-sensitive)
|
||||||
|
|
||||||
|
### 3. Authenticate the gh CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
echo "${INSTALL_TOKEN}" | gh auth login --with-token
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify it worked:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gh auth status
|
||||||
|
```
|
||||||
|
|
||||||
|
You should see authentication via `token` for `github.com`.
|
||||||
|
|
||||||
|
### 4. Cleanup
|
||||||
|
|
||||||
|
The installation access token expires after 1 hour. There is nothing to revoke unless you want to explicitly invalidate it early:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -s -X DELETE \
|
||||||
|
-H "Authorization: Bearer ${INSTALL_TOKEN}" \
|
||||||
|
-H "Accept: application/vnd.github+json" \
|
||||||
|
"https://api.github.com/installation/token"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fallback: JWT generation without Python
|
||||||
|
|
||||||
|
If `python3` is unavailable, generate the JWT using `openssl` and `bash`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
header=$(printf '{"alg":"RS256","typ":"JWT"}' | openssl base64 -e -A | tr '+/' '-_' | tr -d '=')
|
||||||
|
now=$(date +%s)
|
||||||
|
iat=$((now - 60))
|
||||||
|
exp=$((now + 600))
|
||||||
|
payload=$(printf '{"iat":%d,"exp":%d,"iss":"%s"}' "$iat" "$exp" "$GITHUB_APP_ID" | openssl base64 -e -A | tr '+/' '-_' | tr -d '=')
|
||||||
|
unsigned="${header}.${payload}"
|
||||||
|
signature=$(printf '%s' "$unsigned" | openssl dgst -sha256 -sign "${GITHUB_APP_PEM_FILE}" -binary | openssl base64 -e -A | tr '+/' '-_' | tr -d '=')
|
||||||
|
TOKEN="${unsigned}.${signature}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Then continue from Step 2.
|
||||||
|
|
||||||
|
## Security Notes
|
||||||
|
|
||||||
|
- Never log or echo the PEM key, JWT, or installation token to stdout in production.
|
||||||
|
- The JWT is valid for at most 10 minutes. The installation token is valid for 1 hour.
|
||||||
|
- Store the PEM file with restrictive permissions (`chmod 600`) and never check it into git.
|
||||||
Executable
+98
@@ -0,0 +1,98 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Generate a JWT for GitHub App authentication.
|
||||||
|
|
||||||
|
Reads from environment variables:
|
||||||
|
GITHUB_APP_ID - The GitHub App's numeric ID
|
||||||
|
GITHUB_APP_PEM_FILE - Path to the PEM-encoded private key file
|
||||||
|
|
||||||
|
Prints the signed JWT to stdout.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
try:
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||||||
|
|
||||||
|
USE_CRYPTOGRAPHY = True
|
||||||
|
except ImportError:
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
USE_CRYPTOGRAPHY = False
|
||||||
|
|
||||||
|
|
||||||
|
def b64url(data: bytes) -> str:
|
||||||
|
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def sign_with_cryptography(unsigned: str, pem_key: str) -> str:
|
||||||
|
private_key = serialization.load_pem_private_key(pem_key.encode(), password=None)
|
||||||
|
signature = private_key.sign(unsigned.encode(), padding.PKCS1v15(), hashes.SHA256())
|
||||||
|
return b64url(signature)
|
||||||
|
|
||||||
|
|
||||||
|
def sign_with_openssl(unsigned: str, pem_key: str) -> str:
|
||||||
|
result = subprocess.run(
|
||||||
|
["openssl", "dgst", "-sha256", "-sign", "/dev/stdin"],
|
||||||
|
input=pem_key.encode(),
|
||||||
|
capture_output=True,
|
||||||
|
check=True,
|
||||||
|
env={**os.environ, "OPENSSL_CONF": "/dev/null"},
|
||||||
|
)
|
||||||
|
# openssl dgst -sign reads key from stdin on some versions, but not all.
|
||||||
|
# If that fails, write to a temp file.
|
||||||
|
if result.returncode != 0:
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile(mode="w", suffix=".pem", delete=False) as f:
|
||||||
|
f.write(pem_key)
|
||||||
|
f.flush()
|
||||||
|
result = subprocess.run(
|
||||||
|
["openssl", "dgst", "-sha256", "-sign", f.name],
|
||||||
|
input=unsigned.encode(),
|
||||||
|
capture_output=True,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
os.unlink(f.name)
|
||||||
|
return b64url(result.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
app_id = os.environ.get("GITHUB_APP_ID")
|
||||||
|
pem_file = os.environ.get("GITHUB_APP_PEM_FILE")
|
||||||
|
|
||||||
|
if not app_id:
|
||||||
|
print("error: GITHUB_APP_ID is not set", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
if not pem_file:
|
||||||
|
print("error: GITHUB_APP_PEM_FILE is not set", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
if not os.path.isfile(pem_file):
|
||||||
|
print(f"error: PEM file not found: {pem_file}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
with open(pem_file, "r") as f:
|
||||||
|
pem_key = f.read()
|
||||||
|
|
||||||
|
now = int(time.time())
|
||||||
|
header = b64url(json.dumps({"alg": "RS256", "typ": "JWT"}).encode())
|
||||||
|
payload = b64url(
|
||||||
|
json.dumps({"iat": now - 60, "exp": now + 600, "iss": app_id}).encode()
|
||||||
|
)
|
||||||
|
unsigned = f"{header}.{payload}"
|
||||||
|
|
||||||
|
if USE_CRYPTOGRAPHY:
|
||||||
|
signature = sign_with_cryptography(unsigned, pem_key)
|
||||||
|
else:
|
||||||
|
signature = sign_with_openssl(unsigned, pem_key)
|
||||||
|
|
||||||
|
print(f"{unsigned}.{signature}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user