github-backup 0.67.0__tar.gz → 0.68.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. {github_backup-0.67.0 → github_backup-0.68.0}/CHANGES.rst +36 -1
  2. {github_backup-0.67.0/github_backup.egg-info → github_backup-0.68.0}/PKG-INFO +26 -5
  3. {github_backup-0.67.0 → github_backup-0.68.0}/README +25 -4
  4. {github_backup-0.67.0 → github_backup-0.68.0}/README.rst +25 -4
  5. github_backup-0.68.0/github_backup/__init__.py +1 -0
  6. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup/github_backup.py +153 -3
  7. {github_backup-0.67.0 → github_backup-0.68.0/github_backup.egg-info}/PKG-INFO +26 -5
  8. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup.egg-info/SOURCES.txt +1 -0
  9. {github_backup-0.67.0 → github_backup-0.68.0}/release-requirements.txt +1 -1
  10. github_backup-0.68.0/tests/test_app_auth.py +339 -0
  11. github_backup-0.67.0/github_backup/__init__.py +0 -1
  12. {github_backup-0.67.0 → github_backup-0.68.0}/LICENSE.txt +0 -0
  13. {github_backup-0.67.0 → github_backup-0.68.0}/MANIFEST.in +0 -0
  14. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup/__main__.py +0 -0
  15. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup/cli.py +0 -0
  16. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup/graphql_queries.py +0 -0
  17. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup.egg-info/dependency_links.txt +0 -0
  18. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup.egg-info/entry_points.txt +0 -0
  19. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup.egg-info/top_level.txt +0 -0
  20. {github_backup-0.67.0 → github_backup-0.68.0}/github_backup.egg-info/zip-safe +0 -0
  21. {github_backup-0.67.0 → github_backup-0.68.0}/requirements.txt +0 -0
  22. {github_backup-0.67.0 → github_backup-0.68.0}/setup.cfg +0 -0
  23. {github_backup-0.67.0 → github_backup-0.68.0}/setup.py +0 -0
  24. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_all_starred.py +0 -0
  25. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_app_repositories.py +0 -0
  26. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_attachments.py +0 -0
  27. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_auth.py +0 -0
  28. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_case_sensitivity.py +0 -0
  29. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_disabled_issues_pulls.py +0 -0
  30. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_discussions.py +0 -0
  31. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_gists.py +0 -0
  32. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_hooks.py +0 -0
  33. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_http_451.py +0 -0
  34. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_incremental_by_files.py +0 -0
  35. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_incremental_per_repository.py +0 -0
  36. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_issue_timeline.py +0 -0
  37. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_json_dump_if_changed.py +0 -0
  38. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_logging_subprocess.py +0 -0
  39. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_pagination.py +0 -0
  40. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_pull_incremental_pagination.py +0 -0
  41. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_pull_reviews.py +0 -0
  42. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_releases.py +0 -0
  43. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_retrieve_data.py +0 -0
  44. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_skip_assets_on.py +0 -0
  45. {github_backup-0.67.0 → github_backup-0.68.0}/tests/test_starred_skip_size_over.py +0 -0
@@ -1,9 +1,44 @@
1
1
  Changelog
2
2
  =========
3
3
 
4
- 0.67.0 (2026-11-04)
4
+ 0.68.0 (2026-11-09)
5
5
  -------------------
6
6
  ------------------------
7
+ - Create GitHub App installation tokens from the app's private key. [AC
8
+ Capehart, Claude Opus 5.5]
9
+
10
+ --as-app only accepts an installation token created elsewhere. Those
11
+ expire after an hour, so long backups fail part way through. With
12
+ --app-id and --app-private-key, github-backup creates the token itself
13
+ and replaces it ten minutes before it expires. The installation is
14
+ looked up from the user or organization being backed up, unless
15
+ --app-installation-id names it.
16
+
17
+ The JWT is signed by the openssl command line tool so the project keeps
18
+ zero runtime dependencies; the Docker image now installs openssl. A
19
+ missing key file or openssl is reported by parse_args before any work
20
+ starts. API requests resolve auth per request, and wiki clones rebuild
21
+ their URL, so both pick up a refreshed token mid-run.
22
+ - Chore(deps): bump flake8. [dependabot[bot]]
23
+
24
+ Bumps the python-packages group with 1 update: [flake8](https://github.com/pycqa/flake8).
25
+
26
+
27
+ Updates `flake8` from 7.4.1 to 7.5.0
28
+ - [Commits](https://github.com/pycqa/flake8/compare/7.4.1...7.5.0)
29
+
30
+ ---
31
+ updated-dependencies:
32
+ - dependency-name: flake8
33
+ dependency-version: 7.5.0
34
+ dependency-type: direct:production
35
+ update-type: version-update:semver-minor
36
+ dependency-group: python-packages
37
+ ...
38
+
39
+
40
+ 0.67.0 (2026-11-04)
41
+ -------------------
7
42
  - Drop support for Python 3.10 (end of life) [Rodos]
8
43
 
9
44
  Python 3.10 reached end of life on 2026-10-01 and no longer receives
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: github-backup
3
- Version: 0.67.0
3
+ Version: 0.68.0
4
4
  Summary: backup a github user or organization
5
5
  Home-page: http://github.com/josegonzalez/python-github-backup
6
6
  Author: Jose Diaz-Gonzalez
@@ -66,7 +66,10 @@ Show the CLI help output::
66
66
  CLI Help output::
67
67
 
68
68
  github-backup [-h] [-t TOKEN_CLASSIC] [-f TOKEN_FINE] [--token-from-gh]
69
- [-q] [--as-app] [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
69
+ [-q] [--as-app] [--app-id APP_ID]
70
+ [--app-private-key APP_PRIVATE_KEY]
71
+ [--app-installation-id APP_INSTALLATION_ID]
72
+ [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
70
73
  [--incremental-by-files]
71
74
  [--starred] [--all-starred] [--starred-skip-size-over MB]
72
75
  [--watched] [--followers] [--following] [--all]
@@ -107,6 +110,14 @@ CLI Help output::
107
110
  -q, --quiet supress log messages less severe than warning, e.g.
108
111
  info
109
112
  --as-app authenticate as github app instead of as a user.
113
+ --app-id APP_ID github app id or client id; creates and refreshes
114
+ installation tokens (implies --as-app)
115
+ --app-private-key APP_PRIVATE_KEY
116
+ path to the github app private key (.pem), optionally
117
+ as file://...
118
+ --app-installation-id APP_INSTALLATION_ID
119
+ id of the github app installation to back up
120
+ (default: looked up from the user or organization)
110
121
  -o, --output-directory OUTPUT_DIRECTORY
111
122
  directory at which to backup the repositories
112
123
  -l, --log-level LOG_LEVEL
@@ -241,9 +252,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
241
252
  7. Go to *Install App* in your app's settings
242
253
  8. Select the account/organization and which repositories to back up
243
254
 
244
- **CI/CD usage with GitHub Actions:**
255
+ **Using the app's private key:**
245
256
 
246
- Store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
257
+ Pass the App ID and private key file, and github-backup creates installation tokens itself, refreshing them before they expire so long-running backups keep working::
258
+
259
+ github-backup myorg --organization --app-id 12345 --app-private-key /path/to/app.private-key.pem -o ./backup --all
260
+
261
+ The app's installation on the user or organization being backed up is looked up automatically. To skip the lookup, pass ``--app-installation-id`` with the number at the end of the installation's settings URL (``.../settings/installations/<id>``).
262
+
263
+ ``--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).
264
+
265
+ **Using an existing installation token:**
266
+
267
+ 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``::
247
268
 
248
269
  - uses: actions/create-github-app-token@v1
249
270
  id: app-token
@@ -253,7 +274,7 @@ Store the App ID as a repository variable and the private key contents as a secr
253
274
 
254
275
  - run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
255
276
 
256
- Note: Installation tokens expire after 1 hour. For long-running backups, use a fine-grained personal access token instead.
277
+ 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.
257
278
 
258
279
 
259
280
  Prefer SSH
@@ -37,7 +37,10 @@ Show the CLI help output::
37
37
  CLI Help output::
38
38
 
39
39
  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]
41
44
  [--incremental-by-files]
42
45
  [--starred] [--all-starred] [--starred-skip-size-over MB]
43
46
  [--watched] [--followers] [--following] [--all]
@@ -78,6 +81,14 @@ CLI Help output::
78
81
  -q, --quiet supress log messages less severe than warning, e.g.
79
82
  info
80
83
  --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
91
+ (default: looked up from the user or organization)
81
92
  -o, --output-directory OUTPUT_DIRECTORY
82
93
  directory at which to backup the repositories
83
94
  -l, --log-level LOG_LEVEL
@@ -212,9 +223,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
212
223
  7. Go to *Install App* in your app's settings
213
224
  8. Select the account/organization and which repositories to back up
214
225
 
215
- **CI/CD usage with GitHub Actions:**
226
+ **Using the app's private key:**
216
227
 
217
- Store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
228
+ Pass the App ID and private key file, and github-backup creates installation tokens itself, refreshing them before they expire so long-running backups keep working::
229
+
230
+ github-backup myorg --organization --app-id 12345 --app-private-key /path/to/app.private-key.pem -o ./backup --all
231
+
232
+ The app's installation on the user or organization being backed up is looked up automatically. To skip the lookup, pass ``--app-installation-id`` with the number at the end of the installation's settings URL (``.../settings/installations/<id>``).
233
+
234
+ ``--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).
235
+
236
+ **Using an existing installation token:**
237
+
238
+ 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``::
218
239
 
219
240
  - uses: actions/create-github-app-token@v1
220
241
  id: app-token
@@ -224,7 +245,7 @@ Store the App ID as a repository variable and the private key contents as a secr
224
245
 
225
246
  - run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
226
247
 
227
- Note: Installation tokens expire after 1 hour. For long-running backups, use a fine-grained personal access token instead.
248
+ 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.
228
249
 
229
250
 
230
251
  Prefer SSH
@@ -37,7 +37,10 @@ Show the CLI help output::
37
37
  CLI Help output::
38
38
 
39
39
  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]
41
44
  [--incremental-by-files]
42
45
  [--starred] [--all-starred] [--starred-skip-size-over MB]
43
46
  [--watched] [--followers] [--following] [--all]
@@ -78,6 +81,14 @@ CLI Help output::
78
81
  -q, --quiet supress log messages less severe than warning, e.g.
79
82
  info
80
83
  --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
91
+ (default: looked up from the user or organization)
81
92
  -o, --output-directory OUTPUT_DIRECTORY
82
93
  directory at which to backup the repositories
83
94
  -l, --log-level LOG_LEVEL
@@ -212,9 +223,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
212
223
  7. Go to *Install App* in your app's settings
213
224
  8. Select the account/organization and which repositories to back up
214
225
 
215
- **CI/CD usage with GitHub Actions:**
226
+ **Using the app's private key:**
216
227
 
217
- Store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
228
+ Pass the App ID and private key file, and github-backup creates installation tokens itself, refreshing them before they expire so long-running backups keep working::
229
+
230
+ github-backup myorg --organization --app-id 12345 --app-private-key /path/to/app.private-key.pem -o ./backup --all
231
+
232
+ The app's installation on the user or organization being backed up is looked up automatically. To skip the lookup, pass ``--app-installation-id`` with the number at the end of the installation's settings URL (``.../settings/installations/<id>``).
233
+
234
+ ``--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).
235
+
236
+ **Using an existing installation token:**
237
+
238
+ 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``::
218
239
 
219
240
  - uses: actions/create-github-app-token@v1
220
241
  id: app-token
@@ -224,7 +245,7 @@ Store the App ID as a repository variable and the private key contents as a secr
224
245
 
225
246
  - run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
226
247
 
227
- Note: Installation tokens expire after 1 hour. For long-running backups, use a fine-grained personal access token instead.
248
+ 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.
228
249
 
229
250
 
230
251
  Prefer SSH
@@ -0,0 +1 @@
1
+ __version__ = "0.68.0"
@@ -12,6 +12,7 @@ import os
12
12
  import platform
13
13
  import random
14
14
  import re
15
+ import shutil
15
16
  import socket
16
17
  import ssl
17
18
  import subprocess
@@ -45,6 +46,7 @@ from .graphql_queries import (
45
46
  )
46
47
 
47
48
  FILE_URI_PREFIX = "file://"
49
+ APP_TOKEN_REFRESH_MARGIN = 10 * 60 # seconds
48
50
  logger = logging.getLogger(__name__)
49
51
 
50
52
 
@@ -195,6 +197,21 @@ def parse_args(args=None):
195
197
  dest="as_app",
196
198
  help="authenticate as github app instead of as a user.",
197
199
  )
200
+ parser.add_argument(
201
+ "--app-id",
202
+ dest="app_id",
203
+ help="github app id or client id; creates and refreshes installation tokens (implies --as-app)",
204
+ )
205
+ parser.add_argument(
206
+ "--app-private-key",
207
+ dest="app_private_key",
208
+ help="path to the github app private key (.pem), optionally as file://...",
209
+ )
210
+ parser.add_argument(
211
+ "--app-installation-id",
212
+ dest="app_installation_id",
213
+ help="id of the github app installation to back up (default: looked up from the user or organization)",
214
+ )
198
215
  parser.add_argument(
199
216
  "-o",
200
217
  "--output-directory",
@@ -522,12 +539,39 @@ def parse_args(args=None):
522
539
  default=5,
523
540
  help="maximum number of retries for API calls (default: 5)",
524
541
  )
525
- return parser.parse_args(args)
542
+ args = parser.parse_args(args)
543
+
544
+ if args.app_id or args.app_private_key or args.app_installation_id:
545
+ if not (args.app_id and args.app_private_key):
546
+ parser.error("--app-id and --app-private-key must be used together")
547
+ if (
548
+ args.token_classic
549
+ or args.token_fine
550
+ or args.token_from_gh
551
+ or args.osx_keychain_item_name
552
+ or args.osx_keychain_item_account
553
+ ):
554
+ parser.error(
555
+ "--app-id cannot be combined with -t, -f, --token-from-gh or keychain options"
556
+ )
557
+ args.app_private_key = args.app_private_key.removeprefix(FILE_URI_PREFIX)
558
+ if not os.path.isfile(args.app_private_key):
559
+ parser.error(
560
+ "--app-private-key file not found: {0}".format(args.app_private_key)
561
+ )
562
+ if not shutil.which("openssl"):
563
+ parser.error("--app-private-key requires the 'openssl' command on PATH")
564
+ args.as_app = True
565
+
566
+ return args
526
567
 
527
568
 
528
569
  def get_auth(args, encode=True, for_git_cli=False):
529
570
  auth = None
530
571
 
572
+ if args.app_id:
573
+ args.token_classic = get_app_installation_token(args)
574
+
531
575
  if args.osx_keychain_item_name:
532
576
  if not args.osx_keychain_item_account:
533
577
  raise Exception(
@@ -676,6 +720,110 @@ def read_token_from_gh_cli(args):
676
720
  return token
677
721
 
678
722
 
723
+ def build_app_jwt(private_key_path, claims):
724
+ """Build an RS256 JWT for authenticating as a GitHub App.
725
+
726
+ Signs with the openssl CLI so the project keeps no runtime dependencies.
727
+ """
728
+
729
+ def b64url(data):
730
+ return base64.urlsafe_b64encode(data).rstrip(b"=")
731
+
732
+ header = b64url(json.dumps({"alg": "RS256", "typ": "JWT"}).encode("ascii"))
733
+ signing_input = header + b"." + b64url(json.dumps(claims).encode("ascii"))
734
+
735
+ try:
736
+ signature = subprocess.run(
737
+ ["openssl", "dgst", "-sha256", "-sign", private_key_path],
738
+ input=signing_input,
739
+ capture_output=True,
740
+ check=True,
741
+ ).stdout
742
+ except subprocess.CalledProcessError as e:
743
+ stderr = e.stderr.decode("utf-8", errors="replace").strip()
744
+ raise Exception("Unable to sign GitHub App JWT: {0}".format(stderr))
745
+
746
+ return (signing_input + b"." + b64url(signature)).decode("ascii")
747
+
748
+
749
+ def get_app_installation_token(args):
750
+ """Return a GitHub App installation token, creating a new one when needed.
751
+
752
+ Installation tokens expire after an hour, so a new one is created once the
753
+ cached token is within APP_TOKEN_REFRESH_MARGIN seconds of expiring.
754
+ """
755
+ cached_token = getattr(args, "_app_token_value", None)
756
+ if cached_token and time.time() < (
757
+ args._app_token_expires_at - APP_TOKEN_REFRESH_MARGIN
758
+ ):
759
+ return cached_token
760
+
761
+ # GitHub rejects an exp more than 10 minutes out; backdate iat to tolerate
762
+ # clock drift.
763
+ now = int(time.time())
764
+ app_jwt = build_app_jwt(
765
+ args.app_private_key, {"iat": now - 60, "exp": now + 540, "iss": args.app_id}
766
+ )
767
+
768
+ if not args.app_installation_id:
769
+ owner_type = "orgs" if args.organization else "users"
770
+ installation = request_as_app(
771
+ args,
772
+ app_jwt,
773
+ "/{0}/{1}/installation".format(owner_type, args.user),
774
+ "Unable to find the GitHub App installation for {0}".format(args.user),
775
+ )
776
+ args.app_installation_id = str(installation["id"])
777
+ logger.info(
778
+ "Using GitHub App installation {0} for {1}".format(
779
+ args.app_installation_id, args.user
780
+ )
781
+ )
782
+
783
+ response = request_as_app(
784
+ args,
785
+ app_jwt,
786
+ "/app/installations/{0}/access_tokens".format(args.app_installation_id),
787
+ "Unable to create GitHub App installation token",
788
+ method="POST",
789
+ )
790
+
791
+ args._app_token_value = response["token"]
792
+ args._app_token_expires_at = calendar.timegm(
793
+ time.strptime(response["expires_at"], "%Y-%m-%dT%H:%M:%SZ")
794
+ )
795
+ logger.info(
796
+ "Created GitHub App installation token (expires {0})".format(
797
+ response["expires_at"]
798
+ )
799
+ )
800
+ return args._app_token_value
801
+
802
+
803
+ def request_as_app(args, app_jwt, path, error_message, method="GET"):
804
+ """Call the GitHub API authenticated as the app itself, with its JWT."""
805
+ request = Request(
806
+ "https://{0}{1}".format(get_github_api_host(args), path),
807
+ data=b"" if method == "POST" else None,
808
+ method=method,
809
+ )
810
+ request.add_header("Accept", "application/vnd.github+json")
811
+ request.add_header("Authorization", "Bearer " + app_jwt)
812
+
813
+ try:
814
+ http_response = make_request_with_retry(request, app_jwt, args.max_retries)
815
+ except HTTPError as exc:
816
+ raise Exception(
817
+ "{0}: HTTP {1} {2}: {3}".format(
818
+ error_message,
819
+ exc.code,
820
+ exc.reason,
821
+ exc.read().decode("utf-8", errors="replace"),
822
+ )
823
+ )
824
+ return json.loads(http_response.read().decode("utf-8"))
825
+
826
+
679
827
  def get_github_repo_url(args, repository):
680
828
  if repository.get("is_gist"):
681
829
  if args.prefer_ssh:
@@ -734,7 +882,6 @@ def retrieve_data(args, template, query_args=None, paginated=True, lazy=False):
734
882
  Handles throttling, retries, read errors, and DMCA takedowns.
735
883
  """
736
884
  query_args = query_args or {}
737
- auth = get_auth(args, encode=not args.as_app)
738
885
  per_page = 100
739
886
 
740
887
  def _extract_next_page_url(link_header):
@@ -758,6 +905,8 @@ def retrieve_data(args, template, query_args=None, paginated=True, lazy=False):
758
905
  # FIRST: Fetch response
759
906
 
760
907
  for attempt in range(args.max_retries + 1):
908
+ # Resolved per request so long runs pick up refreshed app tokens
909
+ auth = get_auth(args, encode=not args.as_app)
761
910
  request = _construct_request(
762
911
  per_page=per_page if paginated else None,
763
912
  query_args=query_args,
@@ -2210,7 +2359,8 @@ def backup_repositories(args, output_directory, repositories):
2210
2359
  if repository["has_wiki"] and download_wiki:
2211
2360
  fetch_repository(
2212
2361
  repository["name"],
2213
- repo_url.replace(".git", ".wiki.git"),
2362
+ # Rebuilt so a long repository clone can't leave it an expired app token
2363
+ get_github_repo_url(args, repository).replace(".git", ".wiki.git"),
2214
2364
  os.path.join(repo_cwd, "wiki"),
2215
2365
  skip_existing=args.skip_existing,
2216
2366
  bare_clone=args.bare_clone,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: github-backup
3
- Version: 0.67.0
3
+ Version: 0.68.0
4
4
  Summary: backup a github user or organization
5
5
  Home-page: http://github.com/josegonzalez/python-github-backup
6
6
  Author: Jose Diaz-Gonzalez
@@ -66,7 +66,10 @@ Show the CLI help output::
66
66
  CLI Help output::
67
67
 
68
68
  github-backup [-h] [-t TOKEN_CLASSIC] [-f TOKEN_FINE] [--token-from-gh]
69
- [-q] [--as-app] [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
69
+ [-q] [--as-app] [--app-id APP_ID]
70
+ [--app-private-key APP_PRIVATE_KEY]
71
+ [--app-installation-id APP_INSTALLATION_ID]
72
+ [-o OUTPUT_DIRECTORY] [-l LOG_LEVEL] [-i]
70
73
  [--incremental-by-files]
71
74
  [--starred] [--all-starred] [--starred-skip-size-over MB]
72
75
  [--watched] [--followers] [--following] [--all]
@@ -107,6 +110,14 @@ CLI Help output::
107
110
  -q, --quiet supress log messages less severe than warning, e.g.
108
111
  info
109
112
  --as-app authenticate as github app instead of as a user.
113
+ --app-id APP_ID github app id or client id; creates and refreshes
114
+ installation tokens (implies --as-app)
115
+ --app-private-key APP_PRIVATE_KEY
116
+ path to the github app private key (.pem), optionally
117
+ as file://...
118
+ --app-installation-id APP_INSTALLATION_ID
119
+ id of the github app installation to back up
120
+ (default: looked up from the user or organization)
110
121
  -o, --output-directory OUTPUT_DIRECTORY
111
122
  directory at which to backup the repositories
112
123
  -l, --log-level LOG_LEVEL
@@ -241,9 +252,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
241
252
  7. Go to *Install App* in your app's settings
242
253
  8. Select the account/organization and which repositories to back up
243
254
 
244
- **CI/CD usage with GitHub Actions:**
255
+ **Using the app's private key:**
245
256
 
246
- Store the App ID as a repository variable and the private key contents as a secret, then use ``actions/create-github-app-token``::
257
+ Pass the App ID and private key file, and github-backup creates installation tokens itself, refreshing them before they expire so long-running backups keep working::
258
+
259
+ github-backup myorg --organization --app-id 12345 --app-private-key /path/to/app.private-key.pem -o ./backup --all
260
+
261
+ The app's installation on the user or organization being backed up is looked up automatically. To skip the lookup, pass ``--app-installation-id`` with the number at the end of the installation's settings URL (``.../settings/installations/<id>``).
262
+
263
+ ``--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).
264
+
265
+ **Using an existing installation token:**
266
+
267
+ 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``::
247
268
 
248
269
  - uses: actions/create-github-app-token@v1
249
270
  id: app-token
@@ -253,7 +274,7 @@ Store the App ID as a repository variable and the private key contents as a secr
253
274
 
254
275
  - run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
255
276
 
256
- Note: Installation tokens expire after 1 hour. For long-running backups, use a fine-grained personal access token instead.
277
+ 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.
257
278
 
258
279
 
259
280
  Prefer SSH
@@ -18,6 +18,7 @@ github_backup.egg-info/entry_points.txt
18
18
  github_backup.egg-info/top_level.txt
19
19
  github_backup.egg-info/zip-safe
20
20
  tests/test_all_starred.py
21
+ tests/test_app_auth.py
21
22
  tests/test_app_repositories.py
22
23
  tests/test_attachments.py
23
24
  tests/test_auth.py
@@ -1,7 +1,7 @@
1
1
  # Linting & Formatting
2
2
  autopep8==2.3.2
3
3
  black==26.10.1
4
- flake8==7.4.1
4
+ flake8==7.5.0
5
5
 
6
6
  # Testing
7
7
  pytest==9.2.0
@@ -0,0 +1,339 @@
1
+ """Tests for GitHub App authentication with an app private key."""
2
+
3
+ import base64
4
+ import json
5
+ import shutil
6
+ import subprocess
7
+ import time
8
+ from io import BytesIO
9
+ from unittest.mock import patch
10
+ from urllib.error import HTTPError
11
+
12
+ import pytest
13
+
14
+ from github_backup import github_backup
15
+
16
+
17
+ class MockHTTPResponse:
18
+ def __init__(self, data, link_header=None):
19
+ self._content = json.dumps(data).encode("utf-8")
20
+ self.headers = {"x-ratelimit-remaining": "5000"}
21
+ if link_header:
22
+ self.headers["Link"] = link_header
23
+
24
+ def getcode(self):
25
+ return 200
26
+
27
+ def read(self):
28
+ return self._content
29
+
30
+
31
+ def b64url_decode(segment):
32
+ return base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
33
+
34
+
35
+ def expires_in(seconds):
36
+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + seconds))
37
+
38
+
39
+ @pytest.fixture
40
+ def key_file(tmp_path):
41
+ path = tmp_path / "app.pem"
42
+ path.write_text("key")
43
+ return str(path)
44
+
45
+
46
+ @pytest.fixture
47
+ def app_flags(key_file):
48
+ return ["--app-id", "12345", "--app-private-key", key_file]
49
+
50
+
51
+ @pytest.fixture
52
+ def app_args(app_flags):
53
+ return github_backup.parse_args(
54
+ app_flags + ["--app-installation-id", "678", "testorg"]
55
+ )
56
+
57
+
58
+ class TokenEndpoint:
59
+ """Stands in for GET /{users,orgs}/{owner}/installation and
60
+ POST /app/installations/{id}/access_tokens."""
61
+
62
+ def __init__(self):
63
+ self.lookups = []
64
+ self.requests = []
65
+ self.expires_at = expires_in(3600)
66
+
67
+ def __call__(self, request, *args, **kwargs):
68
+ if request.full_url.endswith("/installation"):
69
+ self.lookups.append(request)
70
+ return MockHTTPResponse({"id": 999})
71
+ self.requests.append(request)
72
+ token = "ghs_{0}".format(len(self.requests))
73
+ return MockHTTPResponse({"token": token, "expires_at": self.expires_at})
74
+
75
+
76
+ @pytest.fixture
77
+ def token_endpoint():
78
+ endpoint = TokenEndpoint()
79
+ with patch("github_backup.github_backup.build_app_jwt", return_value="app.jwt"):
80
+ with patch("github_backup.github_backup.urlopen", side_effect=endpoint):
81
+ yield endpoint
82
+
83
+
84
+ def test_app_flags_imply_as_app(app_args):
85
+ assert app_args.as_app is True
86
+ assert app_args.app_id == "12345"
87
+ assert app_args.app_installation_id == "678"
88
+
89
+
90
+ @pytest.mark.parametrize(
91
+ "flags",
92
+ [["--app-id", "12345"], ["--app-installation-id", "678"]],
93
+ )
94
+ def test_app_flags_must_be_used_together(flags, capsys):
95
+ with pytest.raises(SystemExit):
96
+ github_backup.parse_args(flags + ["testorg"])
97
+
98
+ assert "must be used together" in capsys.readouterr().err
99
+
100
+
101
+ def test_app_installation_id_is_optional(app_flags):
102
+ args = github_backup.parse_args(app_flags + ["testorg"])
103
+
104
+ assert args.as_app is True
105
+ assert args.app_installation_id is None
106
+
107
+
108
+ def test_file_uri_private_key_path(key_file):
109
+ args = github_backup.parse_args(
110
+ ["--app-id", "12345", "--app-private-key", "file://" + key_file, "testorg"]
111
+ )
112
+
113
+ assert args.app_private_key == key_file
114
+
115
+
116
+ def test_missing_private_key_fails_early(tmp_path, capsys):
117
+ missing = str(tmp_path / "missing.pem")
118
+ with pytest.raises(SystemExit):
119
+ github_backup.parse_args(
120
+ ["--app-id", "12345", "--app-private-key", missing, "testorg"]
121
+ )
122
+
123
+ assert "file not found: " + missing in capsys.readouterr().err
124
+
125
+
126
+ def test_missing_openssl_fails_early(app_flags, capsys):
127
+ with patch("github_backup.github_backup.shutil.which", return_value=None):
128
+ with pytest.raises(SystemExit):
129
+ github_backup.parse_args(app_flags + ["testorg"])
130
+
131
+ assert "requires the 'openssl' command" in capsys.readouterr().err
132
+
133
+
134
+ @pytest.mark.parametrize(
135
+ "token_args",
136
+ [
137
+ ["-t", "ghp_token"],
138
+ ["-f", "github_pat_token"],
139
+ ["--token-from-gh"],
140
+ ["--keychain-name", "name", "--keychain-account", "account"],
141
+ ],
142
+ )
143
+ def test_app_flags_reject_other_token_sources(app_flags, token_args, capsys):
144
+ with pytest.raises(SystemExit):
145
+ github_backup.parse_args(app_flags + token_args + ["testorg"])
146
+
147
+ assert "cannot be combined" in capsys.readouterr().err
148
+
149
+
150
+ @pytest.mark.skipif(shutil.which("openssl") is None, reason="openssl not installed")
151
+ def test_build_app_jwt_is_verifiable_rs256(tmp_path):
152
+ private_key = tmp_path / "app.pem"
153
+ public_key = tmp_path / "app.pub"
154
+ subprocess.run(
155
+ ["openssl", "genpkey", "-algorithm", "RSA", "-out", str(private_key)],
156
+ check=True,
157
+ capture_output=True,
158
+ )
159
+ subprocess.run(
160
+ [
161
+ "openssl",
162
+ "pkey",
163
+ "-in",
164
+ str(private_key),
165
+ "-pubout",
166
+ "-out",
167
+ str(public_key),
168
+ ],
169
+ check=True,
170
+ capture_output=True,
171
+ )
172
+
173
+ app_jwt = github_backup.build_app_jwt(str(private_key), {"iss": "12345"})
174
+
175
+ header, payload, signature = app_jwt.split(".")
176
+ assert json.loads(b64url_decode(header)) == {"alg": "RS256", "typ": "JWT"}
177
+ assert json.loads(b64url_decode(payload)) == {"iss": "12345"}
178
+ (tmp_path / "sig").write_bytes(b64url_decode(signature))
179
+ verify = subprocess.run(
180
+ ["openssl", "dgst", "-sha256", "-verify", str(public_key)]
181
+ + ["-signature", str(tmp_path / "sig")],
182
+ input="{0}.{1}".format(header, payload).encode("ascii"),
183
+ capture_output=True,
184
+ )
185
+ assert verify.returncode == 0, verify.stdout + verify.stderr
186
+
187
+
188
+ def test_build_app_jwt_reports_openssl_errors():
189
+ error = subprocess.CalledProcessError(1, "openssl", stderr=b"Could not read key")
190
+ with patch("github_backup.github_backup.subprocess.run", side_effect=error):
191
+ with pytest.raises(Exception, match="Could not read key"):
192
+ github_backup.build_app_jwt("app.pem", {})
193
+
194
+
195
+ def test_jwt_claims(app_args):
196
+ with patch(
197
+ "github_backup.github_backup.build_app_jwt", return_value="app.jwt"
198
+ ) as mock_build, patch(
199
+ "github_backup.github_backup.urlopen",
200
+ return_value=MockHTTPResponse(
201
+ {"token": "ghs_1", "expires_at": expires_in(3600)}
202
+ ),
203
+ ):
204
+ now = int(time.time())
205
+ github_backup.get_auth(app_args)
206
+
207
+ key_path, claims = mock_build.call_args.args
208
+ assert key_path == app_args.app_private_key
209
+ assert claims["iss"] == "12345"
210
+ assert now - 61 <= claims["iat"] <= now - 59
211
+ assert now + 539 <= claims["exp"] <= now + 541
212
+
213
+
214
+ def test_get_auth_creates_installation_token(app_args, token_endpoint):
215
+ assert github_backup.get_auth(app_args, encode=False) == "ghs_1"
216
+
217
+ request = token_endpoint.requests[0]
218
+ assert request.get_method() == "POST"
219
+ assert (
220
+ request.full_url == "https://api.github.com/app/installations/678/access_tokens"
221
+ )
222
+ assert request.get_header("Authorization") == "Bearer app.jwt"
223
+
224
+
225
+ def test_installation_token_on_enterprise_host(app_args, token_endpoint):
226
+ app_args.github_host = "ghe.example.com"
227
+
228
+ github_backup.get_auth(app_args)
229
+
230
+ assert token_endpoint.requests[0].full_url == (
231
+ "https://ghe.example.com/api/v3/app/installations/678/access_tokens"
232
+ )
233
+
234
+
235
+ def test_installation_token_is_cached(app_args, token_endpoint):
236
+ assert github_backup.get_auth(app_args, encode=False) == "ghs_1"
237
+ assert github_backup.get_auth(app_args, encode=False) == "ghs_1"
238
+
239
+ assert len(token_endpoint.requests) == 1
240
+
241
+
242
+ def test_installation_token_is_refreshed_before_expiry(app_args, token_endpoint):
243
+ token_endpoint.expires_at = expires_in(github_backup.APP_TOKEN_REFRESH_MARGIN - 60)
244
+
245
+ assert github_backup.get_auth(app_args, encode=False) == "ghs_1"
246
+ assert github_backup.get_auth(app_args, encode=False) == "ghs_2"
247
+
248
+
249
+ @pytest.mark.parametrize(
250
+ "owner_flags, lookup_url",
251
+ [
252
+ ([], "https://api.github.com/users/testorg/installation"),
253
+ (["--organization"], "https://api.github.com/orgs/testorg/installation"),
254
+ ],
255
+ )
256
+ def test_installation_is_looked_up_once(
257
+ app_flags, owner_flags, lookup_url, token_endpoint
258
+ ):
259
+ args = github_backup.parse_args(app_flags + owner_flags + ["testorg"])
260
+ token_endpoint.expires_at = expires_in(github_backup.APP_TOKEN_REFRESH_MARGIN - 60)
261
+
262
+ github_backup.get_auth(args)
263
+ github_backup.get_auth(args)
264
+
265
+ assert [r.full_url for r in token_endpoint.lookups] == [lookup_url]
266
+ assert token_endpoint.lookups[0].get_header("Authorization") == "Bearer app.jwt"
267
+ assert [r.full_url for r in token_endpoint.requests] == [
268
+ "https://api.github.com/app/installations/999/access_tokens"
269
+ ] * 2
270
+
271
+
272
+ def test_installation_lookup_http_error(app_flags):
273
+ args = github_backup.parse_args(app_flags + ["testorg"])
274
+ error = HTTPError(
275
+ "https://api.github.com",
276
+ 404,
277
+ "Not Found",
278
+ {},
279
+ BytesIO(b'{"message":"Not Found"}'),
280
+ )
281
+ with patch("github_backup.github_backup.build_app_jwt", return_value="app.jwt"):
282
+ with patch("github_backup.github_backup.urlopen", side_effect=error):
283
+ with pytest.raises(
284
+ Exception,
285
+ match="Unable to find the GitHub App installation for testorg: HTTP 404",
286
+ ):
287
+ github_backup.get_auth(args)
288
+
289
+
290
+ def test_git_url_uses_installation_token(app_args, token_endpoint):
291
+ repository = {"owner": {"login": "testorg"}, "name": "repo"}
292
+
293
+ assert github_backup.get_github_repo_url(app_args, repository) == (
294
+ "https://x-access-token:ghs_1@github.com/testorg/repo.git"
295
+ )
296
+
297
+
298
+ def test_installation_token_http_error(app_args):
299
+ error = HTTPError(
300
+ "https://api.github.com",
301
+ 401,
302
+ "Unauthorized",
303
+ {},
304
+ BytesIO(b'{"message":"Integration not found"}'),
305
+ )
306
+ with patch("github_backup.github_backup.build_app_jwt", return_value="app.jwt"):
307
+ with patch("github_backup.github_backup.urlopen", side_effect=error):
308
+ with pytest.raises(
309
+ Exception, match="HTTP 401 Unauthorized: .*Integration not found"
310
+ ):
311
+ github_backup.get_auth(app_args)
312
+
313
+
314
+ def test_pagination_picks_up_refreshed_token(app_args):
315
+ """A long paginated listing keeps working across a token refresh."""
316
+ pages = [
317
+ MockHTTPResponse(
318
+ [{"id": 1}],
319
+ link_header='<https://api.github.com/orgs/testorg/repos?page=2>; rel="next"',
320
+ ),
321
+ MockHTTPResponse([{"id": 2}]),
322
+ ]
323
+ tokens = iter(["ghs_1", "ghs_2"])
324
+ page_auth = []
325
+
326
+ def mock_urlopen(request, *args, **kwargs):
327
+ page_auth.append(request.get_header("Authorization"))
328
+ return pages[len(page_auth) - 1]
329
+
330
+ with patch(
331
+ "github_backup.github_backup.get_app_installation_token",
332
+ side_effect=lambda args: next(tokens),
333
+ ), patch("github_backup.github_backup.urlopen", side_effect=mock_urlopen):
334
+ results = github_backup.retrieve_data(
335
+ app_args, "https://api.github.com/orgs/testorg/repos"
336
+ )
337
+
338
+ assert results == [{"id": 1}, {"id": 2}]
339
+ assert page_auth == [b"token ghs_1", b"token ghs_2"]
@@ -1 +0,0 @@
1
- __version__ = "0.67.0"
File without changes
File without changes