Skip to content

Commit 6f9ad3c

Browse files
capehartclaude
andcommitted
Create GitHub App installation tokens from the app's private key
--as-app only accepts an installation token created elsewhere. Those expire after an hour, so long backups fail part way through. With --app-id, --app-private-key and --app-installation-id, github-backup creates the token itself and replaces it ten minutes before it expires. The JWT is signed by the openssl command line tool so the project keeps zero runtime dependencies; the Docker image now installs openssl. API requests resolve auth per request, and wiki clones rebuild their URL, so both pick up a refreshed token mid-run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent dd1a637 commit 6f9ad3c

4 files changed

Lines changed: 402 additions & 7 deletions

File tree

‎Dockerfile‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ RUN apk add --no-cache \
2424
ca-certificates \
2525
git \
2626
git-lfs \
27+
openssl \
2728
&& addgroup -g 1000 appuser \
2829
&& adduser -D -u 1000 -G appuser appuser
2930

‎README.rst‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ Show the CLI help output::
3737
CLI Help output::
3838

3939
github-backup [-h] [-t TOKEN_CLASSIC] [-f TOKEN_FINE] [--token-from-gh]
40-
[-q] [--as-app] [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
40+
[-q] [--as-app] [--app-id APP_ID]
41+
[--app-private-key APP_PRIVATE_KEY]
42+
[--app-installation-id APP_INSTALLATION_ID]
43+
[-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
4144
[--incremental-by-files]
4245
[--starred] [--all-starred] [--starred-skip-size-over MB]
4346
[--watched] [--followers] [--following] [--all]
@@ -78,6 +81,13 @@ CLI Help output::
7881
-q, --quiet supress log messages less severe than warning, e.g.
7982
info
8083
--as-app authenticate as github app instead of as a user.
84+
--app-id APP_ID github app id or client id; creates and refreshes
85+
installation tokens (implies --as-app)
86+
--app-private-key APP_PRIVATE_KEY
87+
path to the github app private key (.pem), optionally
88+
as file://...
89+
--app-installation-id APP_INSTALLATION_ID
90+
id of the github app installation to back up
8191
-o, --output-directory OUTPUT_DIRECTORY
8292
directory at which to backup the repositories
8393
-l, --log-level LOG_LEVEL
@@ -209,10 +219,19 @@ GitHub Apps are ideal for organization backups in CI/CD. Tokens are scoped to sp
209219
6. Under "Private keys", click "Generate a private key" and save the downloaded file
210220
7. Go to *Install App* in your app's settings
211221
8. Select the account/organization and which repositories to back up
222+
9. Note the **installation ID**: the number at the end of the installation's settings URL (``.../settings/installations/<id>``)
212223

213-
**CI/CD usage with GitHub Actions:**
224+
**Using the app's private key:**
214225

215-
Store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
226+
Pass the App ID, private key file and installation ID, and github-backup creates installation tokens itself, refreshing them before they expire so long-running backups keep working::
227+
228+
github-backup myorg --app-id 12345 --app-private-key /path/to/app.private-key.pem --app-installation-id 67890 -o ./backup --all
229+
230+
``--app-id`` implies ``--as-app`` and cannot be combined with ``-t``, ``-f``, ``--token-from-gh`` or the keychain options. The ``iss`` claim of the signed JWT is set to the value of ``--app-id``, so the app's client ID works there too. The JWT is signed by the ``openssl`` command line tool, which must be on your ``PATH`` (the Docker image includes it).
231+
232+
**Using an existing installation token:**
233+
234+
If something else already creates the installation token, pass it with ``-t`` and ``--as-app``. In GitHub Actions, store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
216235

217236
- uses: actions/create-github-app-token@v1
218237
id: app-token
@@ -222,7 +241,7 @@ Store the App ID as a repository variable and the private key contents as a secr
222241

223242
- run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
224243

225-
Note: Installation tokens expire after 1 hour. For long-running backups, use a fine-grained personal access token instead.
244+
Note: Installation tokens passed with ``-t`` expire after 1 hour and are not refreshed. For backups that may run longer, use ``--app-private-key`` instead.
226245

227246

228247
Prefer SSH

‎github_backup/github_backup.py‎

Lines changed: 123 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
)
4646

4747
FILE_URI_PREFIX = "file://"
48+
APP_TOKEN_REFRESH_MARGIN = 10 * 60 # seconds
4849
logger = logging.getLogger(__name__)
4950

5051

@@ -195,6 +196,21 @@ def parse_args(args=None):
195196
dest="as_app",
196197
help="authenticate as github app instead of as a user.",
197198
)
199+
parser.add_argument(
200+
"--app-id",
201+
dest="app_id",
202+
help="github app id or client id; creates and refreshes installation tokens (implies --as-app)",
203+
)
204+
parser.add_argument(
205+
"--app-private-key",
206+
dest="app_private_key",
207+
help="path to the github app private key (.pem), optionally as file://...",
208+
)
209+
parser.add_argument(
210+
"--app-installation-id",
211+
dest="app_installation_id",
212+
help="id of the github app installation to back up",
213+
)
198214
parser.add_argument(
199215
"-o",
200216
"--output-directory",
@@ -522,12 +538,35 @@ def parse_args(args=None):
522538
default=5,
523539
help="maximum number of retries for API calls (default: 5)",
524540
)
525-
return parser.parse_args(args)
541+
args = parser.parse_args(args)
542+
543+
app_args = (args.app_id, args.app_private_key, args.app_installation_id)
544+
if any(app_args):
545+
if not all(app_args):
546+
parser.error(
547+
"--app-id, --app-private-key and --app-installation-id must be used together"
548+
)
549+
if (
550+
args.token_classic
551+
or args.token_fine
552+
or args.token_from_gh
553+
or args.osx_keychain_item_name
554+
or args.osx_keychain_item_account
555+
):
556+
parser.error(
557+
"--app-id cannot be combined with -t, -f, --token-from-gh or keychain options"
558+
)
559+
args.as_app = True
560+
561+
return args
526562

527563

528564
def get_auth(args, encode=True, for_git_cli=False):
529565
auth = None
530566

567+
if args.app_id:
568+
args.token_classic = get_app_installation_token(args)
569+
531570
if args.osx_keychain_item_name:
532571
if not args.osx_keychain_item_account:
533572
raise Exception(
@@ -676,6 +715,85 @@ def read_token_from_gh_cli(args):
676715
return token
677716

678717

718+
def build_app_jwt(private_key_path, claims):
719+
"""Build an RS256 JWT for authenticating as a GitHub App.
720+
721+
Signs with the openssl CLI so the project keeps no runtime dependencies.
722+
"""
723+
724+
def b64url(data):
725+
return base64.urlsafe_b64encode(data).rstrip(b"=")
726+
727+
header = b64url(json.dumps({"alg": "RS256", "typ": "JWT"}).encode("ascii"))
728+
signing_input = header + b"." + b64url(json.dumps(claims).encode("ascii"))
729+
730+
try:
731+
signature = subprocess.run(
732+
["openssl", "dgst", "-sha256", "-sign", private_key_path],
733+
input=signing_input,
734+
capture_output=True,
735+
check=True,
736+
).stdout
737+
except FileNotFoundError:
738+
raise Exception("Unable to sign GitHub App JWT: 'openssl' executable not found")
739+
except subprocess.CalledProcessError as e:
740+
stderr = e.stderr.decode("utf-8", errors="replace").strip()
741+
raise Exception("Unable to sign GitHub App JWT: {0}".format(stderr))
742+
743+
return (signing_input + b"." + b64url(signature)).decode("ascii")
744+
745+
746+
def get_app_installation_token(args):
747+
"""Return a GitHub App installation token, creating a new one when needed.
748+
749+
Installation tokens expire after an hour, so a new one is created once the
750+
cached token is within APP_TOKEN_REFRESH_MARGIN seconds of expiring.
751+
"""
752+
cached_token = getattr(args, "_app_token_value", None)
753+
if cached_token and time.time() < (
754+
args._app_token_expires_at - APP_TOKEN_REFRESH_MARGIN
755+
):
756+
return cached_token
757+
758+
# GitHub rejects an exp more than 10 minutes out; backdate iat to tolerate
759+
# clock drift.
760+
now = int(time.time())
761+
app_jwt = build_app_jwt(
762+
args.app_private_key.removeprefix(FILE_URI_PREFIX),
763+
{"iat": now - 60, "exp": now + 540, "iss": args.app_id},
764+
)
765+
request = Request(
766+
"https://{0}/app/installations/{1}/access_tokens".format(
767+
get_github_api_host(args), args.app_installation_id
768+
),
769+
data=b"",
770+
method="POST",
771+
)
772+
request.add_header("Accept", "application/vnd.github+json")
773+
request.add_header("Authorization", "Bearer " + app_jwt)
774+
775+
try:
776+
http_response = make_request_with_retry(request, app_jwt, args.max_retries)
777+
except HTTPError as exc:
778+
raise Exception(
779+
"Unable to create GitHub App installation token: HTTP {0} {1}: {2}".format(
780+
exc.code, exc.reason, exc.read().decode("utf-8", errors="replace")
781+
)
782+
)
783+
response = json.loads(http_response.read().decode("utf-8"))
784+
785+
args._app_token_value = response["token"]
786+
args._app_token_expires_at = calendar.timegm(
787+
time.strptime(response["expires_at"], "%Y-%m-%dT%H:%M:%SZ")
788+
)
789+
logger.info(
790+
"Created GitHub App installation token (expires {0})".format(
791+
response["expires_at"]
792+
)
793+
)
794+
return args._app_token_value
795+
796+
679797
def get_github_repo_url(args, repository):
680798
if repository.get("is_gist"):
681799
if args.prefer_ssh:
@@ -734,7 +852,6 @@ def retrieve_data(args, template, query_args=None, paginated=True, lazy=False):
734852
Handles throttling, retries, read errors, and DMCA takedowns.
735853
"""
736854
query_args = query_args or {}
737-
auth = get_auth(args, encode=not args.as_app)
738855
per_page = 100
739856

740857
def _extract_next_page_url(link_header):
@@ -758,6 +875,8 @@ def _extract_legal_url(response_body_bytes):
758875
# FIRST: Fetch response
759876

760877
for attempt in range(args.max_retries + 1):
878+
# Resolved per request so long runs pick up refreshed app tokens
879+
auth = get_auth(args, encode=not args.as_app)
761880
request = _construct_request(
762881
per_page=per_page if paginated else None,
763882
query_args=query_args,
@@ -2201,7 +2320,8 @@ def backup_repositories(args, output_directory, repositories):
22012320
if repository["has_wiki"] and download_wiki:
22022321
fetch_repository(
22032322
repository["name"],
2204-
repo_url.replace(".git", ".wiki.git"),
2323+
# Rebuilt so a long repository clone can't leave it an expired app token
2324+
get_github_repo_url(args, repository).replace(".git", ".wiki.git"),
22052325
os.path.join(repo_cwd, "wiki"),
22062326
skip_existing=args.skip_existing,
22072327
bare_clone=args.bare_clone,

0 commit comments

Comments
 (0)