github-backup 0.66.1__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.
- {github_backup-0.66.1 → github_backup-0.68.0}/CHANGES.rst +53 -1
- {github_backup-0.66.1/github_backup.egg-info → github_backup-0.68.0}/PKG-INFO +28 -8
- {github_backup-0.66.1 → github_backup-0.68.0}/README +26 -5
- {github_backup-0.66.1 → github_backup-0.68.0}/README.rst +26 -5
- github_backup-0.68.0/github_backup/__init__.py +1 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup/github_backup.py +164 -8
- {github_backup-0.66.1 → github_backup-0.68.0/github_backup.egg-info}/PKG-INFO +28 -8
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup.egg-info/SOURCES.txt +2 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/release-requirements.txt +1 -1
- {github_backup-0.66.1 → github_backup-0.68.0}/setup.py +1 -2
- github_backup-0.68.0/tests/test_app_auth.py +339 -0
- github_backup-0.68.0/tests/test_incremental_by_files.py +130 -0
- github_backup-0.66.1/github_backup/__init__.py +0 -1
- {github_backup-0.66.1 → github_backup-0.68.0}/LICENSE.txt +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/MANIFEST.in +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup/__main__.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup/cli.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup/graphql_queries.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup.egg-info/dependency_links.txt +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup.egg-info/entry_points.txt +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup.egg-info/top_level.txt +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/github_backup.egg-info/zip-safe +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/requirements.txt +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/setup.cfg +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_all_starred.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_app_repositories.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_attachments.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_auth.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_case_sensitivity.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_disabled_issues_pulls.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_discussions.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_gists.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_hooks.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_http_451.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_incremental_per_repository.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_issue_timeline.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_json_dump_if_changed.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_logging_subprocess.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_pagination.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_pull_incremental_pagination.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_pull_reviews.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_releases.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_retrieve_data.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_skip_assets_on.py +0 -0
- {github_backup-0.66.1 → github_backup-0.68.0}/tests/test_starred_skip_size_over.py +0 -0
|
@@ -1,9 +1,61 @@
|
|
|
1
1
|
Changelog
|
|
2
2
|
=========
|
|
3
3
|
|
|
4
|
-
0.
|
|
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
|
+
-------------------
|
|
42
|
+
- Drop support for Python 3.10 (end of life) [Rodos]
|
|
43
|
+
|
|
44
|
+
Python 3.10 reached end of life on 2026-10-01 and no longer receives
|
|
45
|
+
security fixes. Require Python 3.11 or higher, and remove 3.10 from the
|
|
46
|
+
package classifiers and the CI test and lint matrices.
|
|
47
|
+
- Fix --incremental-by-files skipping updated items east of UTC. [Rodos]
|
|
48
|
+
|
|
49
|
+
The modification time of a saved issue, pull request or discussion was
|
|
50
|
+
formatted in local time but labelled UTC, then compared with GitHub's UTC
|
|
51
|
+
updated_at. East of UTC, items updated within the offset after they were saved
|
|
52
|
+
were skipped and their changes missed; west of UTC, unchanged items were
|
|
53
|
+
fetched again. The checkpoint time used when a repository has no updated_at or
|
|
54
|
+
pushed_at had the same local-time mistake.
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
0.66.1 (2026-11-03)
|
|
58
|
+
-------------------
|
|
7
59
|
- Skip hooks for repositories without admin access instead of logging a
|
|
8
60
|
404 error (#532) [Rodos]
|
|
9
61
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: github-backup
|
|
3
|
-
Version: 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
|
|
@@ -9,12 +9,11 @@ License: MIT
|
|
|
9
9
|
Classifier: Development Status :: 5 - Production/Stable
|
|
10
10
|
Classifier: Topic :: System :: Archiving :: Backup
|
|
11
11
|
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
13
12
|
Classifier: Programming Language :: Python :: 3.11
|
|
14
13
|
Classifier: Programming Language :: Python :: 3.12
|
|
15
14
|
Classifier: Programming Language :: Python :: 3.13
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
-
Requires-Python: >=3.
|
|
16
|
+
Requires-Python: >=3.11
|
|
18
17
|
Description-Content-Type: text/x-rst
|
|
19
18
|
License-File: LICENSE.txt
|
|
20
19
|
Dynamic: author
|
|
@@ -39,7 +38,7 @@ The package can be used to backup an *entire* `Github <https://github.com/>`_ or
|
|
|
39
38
|
Requirements
|
|
40
39
|
============
|
|
41
40
|
|
|
42
|
-
- Python 3.
|
|
41
|
+
- Python 3.11 or higher
|
|
43
42
|
- GIT 1.9+
|
|
44
43
|
|
|
45
44
|
Installation
|
|
@@ -67,7 +66,10 @@ Show the CLI help output::
|
|
|
67
66
|
CLI Help output::
|
|
68
67
|
|
|
69
68
|
github-backup [-h] [-t TOKEN_CLASSIC] [-f TOKEN_FINE] [--token-from-gh]
|
|
70
|
-
[-q] [--as-app] [-
|
|
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]
|
|
71
73
|
[--incremental-by-files]
|
|
72
74
|
[--starred] [--all-starred] [--starred-skip-size-over MB]
|
|
73
75
|
[--watched] [--followers] [--following] [--all]
|
|
@@ -108,6 +110,14 @@ CLI Help output::
|
|
|
108
110
|
-q, --quiet supress log messages less severe than warning, e.g.
|
|
109
111
|
info
|
|
110
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)
|
|
111
121
|
-o, --output-directory OUTPUT_DIRECTORY
|
|
112
122
|
directory at which to backup the repositories
|
|
113
123
|
-l, --log-level LOG_LEVEL
|
|
@@ -242,9 +252,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
|
|
|
242
252
|
7. Go to *Install App* in your app's settings
|
|
243
253
|
8. Select the account/organization and which repositories to back up
|
|
244
254
|
|
|
245
|
-
**
|
|
255
|
+
**Using the app's private key:**
|
|
246
256
|
|
|
247
|
-
|
|
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``::
|
|
248
268
|
|
|
249
269
|
- uses: actions/create-github-app-token@v1
|
|
250
270
|
id: app-token
|
|
@@ -254,7 +274,7 @@ Store the App ID as a repository variable and the private key contents as a secr
|
|
|
254
274
|
|
|
255
275
|
- run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
|
|
256
276
|
|
|
257
|
-
Note: Installation tokens expire after 1 hour. For
|
|
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.
|
|
258
278
|
|
|
259
279
|
|
|
260
280
|
Prefer SSH
|
|
@@ -9,7 +9,7 @@ The package can be used to backup an *entire* `Github <https://github.com/>`_ or
|
|
|
9
9
|
Requirements
|
|
10
10
|
============
|
|
11
11
|
|
|
12
|
-
- Python 3.
|
|
12
|
+
- Python 3.11 or higher
|
|
13
13
|
- GIT 1.9+
|
|
14
14
|
|
|
15
15
|
Installation
|
|
@@ -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] [-
|
|
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
|
-
**
|
|
226
|
+
**Using the app's private key:**
|
|
216
227
|
|
|
217
|
-
|
|
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
|
|
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
|
|
@@ -9,7 +9,7 @@ The package can be used to backup an *entire* `Github <https://github.com/>`_ or
|
|
|
9
9
|
Requirements
|
|
10
10
|
============
|
|
11
11
|
|
|
12
|
-
- Python 3.
|
|
12
|
+
- Python 3.11 or higher
|
|
13
13
|
- GIT 1.9+
|
|
14
14
|
|
|
15
15
|
Installation
|
|
@@ -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] [-
|
|
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
|
-
**
|
|
226
|
+
**Using the app's private key:**
|
|
216
227
|
|
|
217
|
-
|
|
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
|
|
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
|
|
@@ -20,7 +21,7 @@ import threading
|
|
|
20
21
|
import time
|
|
21
22
|
import traceback
|
|
22
23
|
from collections.abc import Generator
|
|
23
|
-
from datetime import datetime
|
|
24
|
+
from datetime import datetime, timezone
|
|
24
25
|
from http.client import IncompleteRead
|
|
25
26
|
from urllib.error import HTTPError, URLError
|
|
26
27
|
from urllib.parse import urlencode, urlparse
|
|
@@ -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
|
-
|
|
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,
|
|
@@ -2004,7 +2153,7 @@ def get_repository_checkpoint_time(repository):
|
|
|
2004
2153
|
if timestamps:
|
|
2005
2154
|
return max(timestamps)
|
|
2006
2155
|
|
|
2007
|
-
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.
|
|
2156
|
+
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
2008
2157
|
|
|
2009
2158
|
|
|
2010
2159
|
def resource_backup_exists(resource_cwd):
|
|
@@ -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
|
-
|
|
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,
|
|
@@ -2525,7 +2675,9 @@ def backup_discussions(args, repo_cwd, repository):
|
|
|
2525
2675
|
|
|
2526
2676
|
if args.incremental_by_files and os.path.isfile(discussion_file):
|
|
2527
2677
|
modified = os.path.getmtime(discussion_file)
|
|
2528
|
-
modified = datetime.fromtimestamp(modified).strftime(
|
|
2678
|
+
modified = datetime.fromtimestamp(modified, timezone.utc).strftime(
|
|
2679
|
+
"%Y-%m-%dT%H:%M:%SZ"
|
|
2680
|
+
)
|
|
2529
2681
|
if modified > summary["updatedAt"]:
|
|
2530
2682
|
logger.info(
|
|
2531
2683
|
"Skipping discussion {0} because it wasn't modified since last backup".format(
|
|
@@ -2805,7 +2957,9 @@ def backup_issues(args, repo_cwd, repository, repos_template):
|
|
|
2805
2957
|
and number not in stale_timelines
|
|
2806
2958
|
):
|
|
2807
2959
|
modified = os.path.getmtime(issue_file)
|
|
2808
|
-
modified = datetime.fromtimestamp(modified).strftime(
|
|
2960
|
+
modified = datetime.fromtimestamp(modified, timezone.utc).strftime(
|
|
2961
|
+
"%Y-%m-%dT%H:%M:%SZ"
|
|
2962
|
+
)
|
|
2809
2963
|
if modified > issue["updated_at"]:
|
|
2810
2964
|
logger.info(
|
|
2811
2965
|
"Skipping issue {0} because it wasn't modified since last backup".format(
|
|
@@ -3006,7 +3160,9 @@ def backup_pulls(args, repo_cwd, repository, repos_template):
|
|
|
3006
3160
|
|
|
3007
3161
|
if args.incremental_by_files and os.path.isfile(pull_file):
|
|
3008
3162
|
modified = os.path.getmtime(pull_file)
|
|
3009
|
-
modified = datetime.fromtimestamp(modified).strftime(
|
|
3163
|
+
modified = datetime.fromtimestamp(modified, timezone.utc).strftime(
|
|
3164
|
+
"%Y-%m-%dT%H:%M:%SZ"
|
|
3165
|
+
)
|
|
3010
3166
|
if modified > pull["updated_at"] and not needs_review_backfill:
|
|
3011
3167
|
logger.info(
|
|
3012
3168
|
"Skipping pull request {0} because it wasn't modified since last backup".format(
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: github-backup
|
|
3
|
-
Version: 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
|
|
@@ -9,12 +9,11 @@ License: MIT
|
|
|
9
9
|
Classifier: Development Status :: 5 - Production/Stable
|
|
10
10
|
Classifier: Topic :: System :: Archiving :: Backup
|
|
11
11
|
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
13
12
|
Classifier: Programming Language :: Python :: 3.11
|
|
14
13
|
Classifier: Programming Language :: Python :: 3.12
|
|
15
14
|
Classifier: Programming Language :: Python :: 3.13
|
|
16
15
|
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
-
Requires-Python: >=3.
|
|
16
|
+
Requires-Python: >=3.11
|
|
18
17
|
Description-Content-Type: text/x-rst
|
|
19
18
|
License-File: LICENSE.txt
|
|
20
19
|
Dynamic: author
|
|
@@ -39,7 +38,7 @@ The package can be used to backup an *entire* `Github <https://github.com/>`_ or
|
|
|
39
38
|
Requirements
|
|
40
39
|
============
|
|
41
40
|
|
|
42
|
-
- Python 3.
|
|
41
|
+
- Python 3.11 or higher
|
|
43
42
|
- GIT 1.9+
|
|
44
43
|
|
|
45
44
|
Installation
|
|
@@ -67,7 +66,10 @@ Show the CLI help output::
|
|
|
67
66
|
CLI Help output::
|
|
68
67
|
|
|
69
68
|
github-backup [-h] [-t TOKEN_CLASSIC] [-f TOKEN_FINE] [--token-from-gh]
|
|
70
|
-
[-q] [--as-app] [-
|
|
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]
|
|
71
73
|
[--incremental-by-files]
|
|
72
74
|
[--starred] [--all-starred] [--starred-skip-size-over MB]
|
|
73
75
|
[--watched] [--followers] [--following] [--all]
|
|
@@ -108,6 +110,14 @@ CLI Help output::
|
|
|
108
110
|
-q, --quiet supress log messages less severe than warning, e.g.
|
|
109
111
|
info
|
|
110
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)
|
|
111
121
|
-o, --output-directory OUTPUT_DIRECTORY
|
|
112
122
|
directory at which to backup the repositories
|
|
113
123
|
-l, --log-level LOG_LEVEL
|
|
@@ -242,9 +252,19 @@ For a user account (no ``--organization``), ``--as-app`` lists the repositories
|
|
|
242
252
|
7. Go to *Install App* in your app's settings
|
|
243
253
|
8. Select the account/organization and which repositories to back up
|
|
244
254
|
|
|
245
|
-
**
|
|
255
|
+
**Using the app's private key:**
|
|
246
256
|
|
|
247
|
-
|
|
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``::
|
|
248
268
|
|
|
249
269
|
- uses: actions/create-github-app-token@v1
|
|
250
270
|
id: app-token
|
|
@@ -254,7 +274,7 @@ Store the App ID as a repository variable and the private key contents as a secr
|
|
|
254
274
|
|
|
255
275
|
- run: github-backup myorg -t ${{ steps.app-token.outputs.token }} --as-app -o ./backup --all
|
|
256
276
|
|
|
257
|
-
Note: Installation tokens expire after 1 hour. For
|
|
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.
|
|
258
278
|
|
|
259
279
|
|
|
260
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
|
|
@@ -27,6 +28,7 @@ tests/test_discussions.py
|
|
|
27
28
|
tests/test_gists.py
|
|
28
29
|
tests/test_hooks.py
|
|
29
30
|
tests/test_http_451.py
|
|
31
|
+
tests/test_incremental_by_files.py
|
|
30
32
|
tests/test_incremental_per_repository.py
|
|
31
33
|
tests/test_issue_timeline.py
|
|
32
34
|
tests/test_json_dump_if_changed.py
|
|
@@ -44,7 +44,6 @@ setup(
|
|
|
44
44
|
"Development Status :: 5 - Production/Stable",
|
|
45
45
|
"Topic :: System :: Archiving :: Backup",
|
|
46
46
|
"License :: OSI Approved :: MIT License",
|
|
47
|
-
"Programming Language :: Python :: 3.10",
|
|
48
47
|
"Programming Language :: Python :: 3.11",
|
|
49
48
|
"Programming Language :: Python :: 3.12",
|
|
50
49
|
"Programming Language :: Python :: 3.13",
|
|
@@ -54,6 +53,6 @@ setup(
|
|
|
54
53
|
long_description=open_file("README.rst").read(),
|
|
55
54
|
long_description_content_type="text/x-rst",
|
|
56
55
|
install_requires=open_file("requirements.txt").readlines(),
|
|
57
|
-
python_requires=">=3.
|
|
56
|
+
python_requires=">=3.11",
|
|
58
57
|
zip_safe=True,
|
|
59
58
|
)
|
|
@@ -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"]
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Tests for --incremental-by-files timestamp comparison.
|
|
2
|
+
|
|
3
|
+
A saved file is skipped when its modification time is newer than the item's
|
|
4
|
+
``updated_at``. GitHub's timestamps are UTC, so the file's modification time
|
|
5
|
+
must be compared in UTC too, whatever the local time zone is.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import calendar
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
import pytest
|
|
14
|
+
|
|
15
|
+
from github_backup import github_backup
|
|
16
|
+
|
|
17
|
+
UPDATED_AT = "2026-07-01T12:00:00Z"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@pytest.fixture
|
|
21
|
+
def east_of_utc(monkeypatch):
|
|
22
|
+
"""Run the test with the local time zone at UTC+10 (no daylight saving)."""
|
|
23
|
+
monkeypatch.setenv("TZ", "Etc/GMT-10")
|
|
24
|
+
time.tzset()
|
|
25
|
+
yield
|
|
26
|
+
monkeypatch.undo()
|
|
27
|
+
time.tzset()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _stored(path, number, written_at):
|
|
31
|
+
"""Save an item file whose modification time is ``written_at`` (UTC)."""
|
|
32
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
item_file = path / "{0}.json".format(number)
|
|
34
|
+
item_file.write_text(json.dumps({"number": number, "title": "stored"}))
|
|
35
|
+
mtime = calendar.timegm(time.strptime(written_at, "%Y-%m-%dT%H:%M:%SZ"))
|
|
36
|
+
os.utime(item_file, (mtime, mtime))
|
|
37
|
+
return item_file
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _fake_retrieve(items):
|
|
41
|
+
def _retrieve(args, template, query_args=None, **kwargs):
|
|
42
|
+
return items if template.endswith(("/issues", "/pulls")) else []
|
|
43
|
+
|
|
44
|
+
return _retrieve
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@pytest.mark.parametrize(
|
|
48
|
+
"written_at, refetched",
|
|
49
|
+
[
|
|
50
|
+
("2026-07-01T10:00:00Z", True), # updated 2 hours after it was saved
|
|
51
|
+
("2026-07-01T14:00:00Z", False), # saved 2 hours after the update
|
|
52
|
+
],
|
|
53
|
+
)
|
|
54
|
+
def test_issue_skip_compares_in_utc(
|
|
55
|
+
create_args, tmp_path, monkeypatch, east_of_utc, written_at, refetched
|
|
56
|
+
):
|
|
57
|
+
issue_file = _stored(tmp_path / "issues", 1, written_at)
|
|
58
|
+
issue = {"number": 1, "title": "updated", "updated_at": UPDATED_AT}
|
|
59
|
+
monkeypatch.setattr(github_backup, "retrieve_data", _fake_retrieve([issue]))
|
|
60
|
+
args = create_args(include_issues=True, incremental_by_files=True, since=None)
|
|
61
|
+
|
|
62
|
+
github_backup.backup_issues(
|
|
63
|
+
args, str(tmp_path), {"full_name": "owner/repo"}, "https://api.github.com/repos"
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
title = json.loads(issue_file.read_text())["title"]
|
|
67
|
+
assert title == ("updated" if refetched else "stored")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@pytest.mark.parametrize(
|
|
71
|
+
"written_at, refetched",
|
|
72
|
+
[
|
|
73
|
+
("2026-07-01T10:00:00Z", True),
|
|
74
|
+
("2026-07-01T14:00:00Z", False),
|
|
75
|
+
],
|
|
76
|
+
)
|
|
77
|
+
def test_pull_skip_compares_in_utc(
|
|
78
|
+
create_args, tmp_path, monkeypatch, east_of_utc, written_at, refetched
|
|
79
|
+
):
|
|
80
|
+
pull_file = _stored(tmp_path / "pulls", 1, written_at)
|
|
81
|
+
pull = {"number": 1, "title": "updated", "updated_at": UPDATED_AT}
|
|
82
|
+
monkeypatch.setattr(github_backup, "retrieve_data", _fake_retrieve([pull]))
|
|
83
|
+
args = create_args(include_pulls=True, incremental_by_files=True, since=None)
|
|
84
|
+
|
|
85
|
+
github_backup.backup_pulls(
|
|
86
|
+
args, str(tmp_path), {"full_name": "owner/repo"}, "https://api.github.com/repos"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
title = json.loads(pull_file.read_text())["title"]
|
|
90
|
+
assert title == ("updated" if refetched else "stored")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@pytest.mark.parametrize(
|
|
94
|
+
"written_at, refetched",
|
|
95
|
+
[
|
|
96
|
+
("2026-07-01T10:00:00Z", True),
|
|
97
|
+
("2026-07-01T14:00:00Z", False),
|
|
98
|
+
],
|
|
99
|
+
)
|
|
100
|
+
def test_discussion_skip_compares_in_utc(
|
|
101
|
+
create_args, tmp_path, monkeypatch, east_of_utc, written_at, refetched
|
|
102
|
+
):
|
|
103
|
+
discussion_file = _stored(tmp_path / "discussions", 1, written_at)
|
|
104
|
+
summary = {"number": 1, "updatedAt": UPDATED_AT}
|
|
105
|
+
monkeypatch.setattr(
|
|
106
|
+
github_backup,
|
|
107
|
+
"retrieve_discussion_summaries",
|
|
108
|
+
lambda args, repository, since=None: ([summary], UPDATED_AT, True, 1),
|
|
109
|
+
)
|
|
110
|
+
monkeypatch.setattr(
|
|
111
|
+
github_backup,
|
|
112
|
+
"retrieve_discussion",
|
|
113
|
+
lambda args, repository, number: {"number": number, "title": "updated"},
|
|
114
|
+
)
|
|
115
|
+
args = create_args(
|
|
116
|
+
include_discussions=True, incremental_by_files=True, token_classic="ghp_test"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
github_backup.backup_discussions(args, str(tmp_path), {"full_name": "owner/repo"})
|
|
120
|
+
|
|
121
|
+
title = json.loads(discussion_file.read_text())["title"]
|
|
122
|
+
assert title == ("updated" if refetched else "stored")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_checkpoint_fallback_time_is_utc(east_of_utc):
|
|
126
|
+
before = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
127
|
+
checkpoint = github_backup.get_repository_checkpoint_time({})
|
|
128
|
+
after = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
129
|
+
|
|
130
|
+
assert before <= checkpoint <= after
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "0.66.1"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|