Skip to content

Commit 098ba07

Browse files
authored
Merge pull request #541 from Iamrodos/fix/532-hooks-admin-skip
Skip hooks for repositories without admin access instead of logging a 404 error (#532)
2 parents 25bd54c + 6b7ad72 commit 098ba07

3 files changed

Lines changed: 113 additions & 5 deletions

File tree

‎README.rst‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,9 @@ If the incremental argument is used, per-resource checkpoints are only advanced
407407

408408
It's therefore recommended to only use the incremental argument if the output/result is being actively monitored, or complimented with periodic full non-incremental runs, to avoid unexpected missing data in a regular backup runs.
409409

410-
**Starred public repo hooks blocking**
410+
**Hooks need admin access**
411411

412-
Since the ``--all`` argument includes ``--hooks``, if you use ``--all`` and ``--all-starred`` together to clone a users starred public repositories, the backup will likely error and block the backup continuing.
413-
414-
This is due to needing the correct permission for ``--hooks`` on public repos.
412+
Reading a repository's hooks requires admin access to it, and fine-grained tokens also need the Webhooks read permission. Since the ``--all`` argument includes ``--hooks``, repositories you don't administer, such as starred repositories with ``--all-starred``, are skipped for hooks and the rest of the backup continues.
415413

416414

417415
"bare" is actually "mirror"

‎github_backup/github_backup.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3155,14 +3155,28 @@ def backup_hooks(args, repo_cwd, repository, repos_template):
31553155
if not auth:
31563156
logger.info("Skipping hooks since no authentication provided")
31573157
return
3158+
# Reading hooks needs admin access, and GitHub returns 404 without it.
3159+
# Skip the request when the repository listing says we aren't an admin.
3160+
if repository.get("permissions", {}).get("admin") is False:
3161+
logger.info(
3162+
"Skipping hooks for {0} since admin access is required".format(
3163+
repository["full_name"]
3164+
)
3165+
)
3166+
return
31583167
hook_cwd = os.path.join(repo_cwd, "hooks")
31593168
output_file = "{0}/hooks.json".format(hook_cwd)
31603169
template = "{0}/{1}/hooks".format(repos_template, repository["full_name"])
31613170
try:
31623171
_backup_data(args, "hooks", template, output_file, hook_cwd)
31633172
except HTTPError as e:
31643173
if e.code == 404:
3165-
logger.info("Unable to read hooks, skipping")
3174+
logger.info(
3175+
"Unable to read hooks for {0}, skipping (requires admin access, "
3176+
"or Webhooks read permission for fine-grained tokens)".format(
3177+
repository["full_name"]
3178+
)
3179+
)
31663180
else:
31673181
raise e
31683182

‎tests/test_hooks.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
"""Tests for hooks backup permissions (GitHub issue #532).
2+
3+
Reading ``/repos/{owner}/{repo}/hooks`` needs admin access to the repository.
4+
Without it GitHub responds with HTTP 404 rather than 403, which used to log an
5+
API error for every repository the user doesn't administer.
6+
"""
7+
8+
import logging
9+
from urllib.error import HTTPError
10+
11+
import pytest
12+
13+
from github_backup import github_backup
14+
15+
REPOS_TEMPLATE = "https://api.github.com/repos"
16+
17+
18+
@pytest.fixture
19+
def hook_args(create_args):
20+
return create_args(include_hooks=True, token_classic="ghp_token")
21+
22+
23+
def _repository(**fields):
24+
return {"full_name": "owner/repo", **fields}
25+
26+
27+
def test_hooks_skipped_without_request_when_not_admin(
28+
hook_args, tmp_path, monkeypatch, caplog
29+
):
30+
def fail_retrieve_data(*args, **kwargs):
31+
raise AssertionError("hooks should not be requested without admin access")
32+
33+
monkeypatch.setattr(github_backup, "retrieve_data", fail_retrieve_data)
34+
35+
with caplog.at_level(logging.INFO, logger=github_backup.logger.name):
36+
github_backup.backup_hooks(
37+
hook_args,
38+
tmp_path,
39+
_repository(permissions={"admin": False, "push": True, "pull": True}),
40+
REPOS_TEMPLATE,
41+
)
42+
43+
assert "Skipping hooks for owner/repo since admin access is required" in caplog.text
44+
assert not (tmp_path / "hooks").exists()
45+
46+
47+
@pytest.mark.parametrize(
48+
"repository",
49+
[
50+
_repository(permissions={"admin": True, "push": True, "pull": True}),
51+
_repository(),
52+
],
53+
ids=["admin", "no-permissions-field"],
54+
)
55+
def test_hooks_requested_when_admin_or_permissions_unknown(
56+
hook_args, tmp_path, monkeypatch, repository
57+
):
58+
requested = []
59+
60+
def fake_retrieve_data(passed_args, template, *args, **kwargs):
61+
requested.append(template)
62+
return [{"id": 1, "name": "web"}]
63+
64+
monkeypatch.setattr(github_backup, "retrieve_data", fake_retrieve_data)
65+
66+
github_backup.backup_hooks(hook_args, tmp_path, repository, REPOS_TEMPLATE)
67+
68+
assert requested == ["https://api.github.com/repos/owner/repo/hooks"]
69+
assert (tmp_path / "hooks" / "hooks.json").exists()
70+
71+
72+
def test_hooks_404_is_skipped_with_reason(hook_args, tmp_path, monkeypatch, caplog):
73+
def fake_retrieve_data(passed_args, template, *args, **kwargs):
74+
raise HTTPError(template, 404, "Not Found", hdrs=None, fp=None)
75+
76+
monkeypatch.setattr(github_backup, "retrieve_data", fake_retrieve_data)
77+
78+
with caplog.at_level(logging.INFO, logger=github_backup.logger.name):
79+
github_backup.backup_hooks(
80+
hook_args,
81+
tmp_path,
82+
_repository(permissions={"admin": True}),
83+
REPOS_TEMPLATE,
84+
)
85+
86+
assert "Unable to read hooks for owner/repo, skipping" in caplog.text
87+
88+
89+
def test_hooks_non_404_error_propagates(hook_args, tmp_path, monkeypatch):
90+
def fake_retrieve_data(passed_args, template, *args, **kwargs):
91+
raise HTTPError(template, 500, "Server Error", hdrs=None, fp=None)
92+
93+
monkeypatch.setattr(github_backup, "retrieve_data", fake_retrieve_data)
94+
95+
with pytest.raises(HTTPError):
96+
github_backup.backup_hooks(hook_args, tmp_path, _repository(), REPOS_TEMPLATE)

0 commit comments

Comments
 (0)