github-backup 0.67.0__py3-none-any.whl → 0.68.0__py3-none-any.whl

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.
github_backup/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.67.0"
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
@@ -0,0 +1,12 @@
1
+ github_backup/__init__.py,sha256=HxxTcUQtaiYOEEtr3P4K4pOTRoC_pmpqzV7TOSUOpSQ,23
2
+ github_backup/__main__.py,sha256=3yorCiC63maaxbjdtaeAs-G-yAAxKSO3mprhGfa1Fho,271
3
+ github_backup/cli.py,sha256=JTiXPOvB8id8LopREOEd1W_FLvuf9SOZU5buMRPFd9U,2922
4
+ github_backup/github_backup.py,sha256=8tdSyY06L-p01QX93jigaZ4cYhmlB1At0dAEZNtvpo0,133402
5
+ github_backup/graphql_queries.py,sha256=XcAQyp9nF7Ip9UzxsrXMkl2pO-W7SK8hhO2oE9HVcmA,6658
6
+ github_backup-0.68.0.dist-info/licenses/LICENSE.txt,sha256=ML-pLyn1qtAKo_DHMcQ8-p7k3f8cp-IR-mf5B49R2rk,1085
7
+ github_backup-0.68.0.dist-info/METADATA,sha256=8JWYRvjPFq6v6uUWotBGBKk1rV6CIPsqgagZVTNGVnw,37903
8
+ github_backup-0.68.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ github_backup-0.68.0.dist-info/entry_points.txt,sha256=cLPKK7MqC77QVb6HnT2mnyL_f-ciavJG_Y9vVHlCF68,57
10
+ github_backup-0.68.0.dist-info/top_level.txt,sha256=Za6fKRAlxZ0b3ZBH_osPqklLe14LetdNAkvAQANT2AA,14
11
+ github_backup-0.68.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
12
+ github_backup-0.68.0.dist-info/RECORD,,
@@ -1,12 +0,0 @@
1
- github_backup/__init__.py,sha256=DkegR91M-IkILN5EBv-0LVftxIGE60qyryEQ_lYCjdg,23
2
- github_backup/__main__.py,sha256=3yorCiC63maaxbjdtaeAs-G-yAAxKSO3mprhGfa1Fho,271
3
- github_backup/cli.py,sha256=JTiXPOvB8id8LopREOEd1W_FLvuf9SOZU5buMRPFd9U,2922
4
- github_backup/github_backup.py,sha256=5OvANlDQv06qn3awp5rbOzP8ocV88l2o0O-9ng6RywI,127852
5
- github_backup/graphql_queries.py,sha256=XcAQyp9nF7Ip9UzxsrXMkl2pO-W7SK8hhO2oE9HVcmA,6658
6
- github_backup-0.67.0.dist-info/licenses/LICENSE.txt,sha256=ML-pLyn1qtAKo_DHMcQ8-p7k3f8cp-IR-mf5B49R2rk,1085
7
- github_backup-0.67.0.dist-info/METADATA,sha256=redpeZKBK8eOJsG4nM7axcT7pz4v3jBDkeBV509NUfU,36164
8
- github_backup-0.67.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
- github_backup-0.67.0.dist-info/entry_points.txt,sha256=cLPKK7MqC77QVb6HnT2mnyL_f-ciavJG_Y9vVHlCF68,57
10
- github_backup-0.67.0.dist-info/top_level.txt,sha256=Za6fKRAlxZ0b3ZBH_osPqklLe14LetdNAkvAQANT2AA,14
11
- github_backup-0.67.0.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
12
- github_backup-0.67.0.dist-info/RECORD,,