Skip to content

Commit fce4abb

Browse files
committed
Fix fine-grained PAT attachment downloads for private repos (#477)
Fine-grained personal access tokens cannot download attachments from private repositories directly due to a GitHub platform limitation. This adds a workaround for image attachments (/assets/ URLs) using GitHub's Markdown API to convert URLs to JWT-signed URLs that can be downloaded without authentication. Changes: - Add get_jwt_signed_url_via_markdown_api() function - Detect fine-grained token + private repo + /assets/ URL upfront - Use JWT workaround for those cases, mark success with jwt_workaround flag - Skip download with skipped_at when workaround fails - Add startup warning when using --attachments with fine-grained tokens - Document limitation in README (file attachments still fail) - Add 6 unit tests for JWT workaround logic
1 parent c63fb37 commit fce4abb

File tree

4 files changed

+248
-8
lines changed

4 files changed

+248
-8
lines changed

README.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,8 @@ The tool automatically extracts file extensions from HTTP headers to ensure file
281281

282282
**Repository filtering** for repo files/assets handles renamed and transferred repositories gracefully. URLs are included if they either match the current repository name directly, or redirect to it (e.g., ``willmcgugan/rich`` redirects to ``Textualize/rich`` after transfer).
283283

284+
**Fine-grained token limitation:** Due to a GitHub platform limitation, fine-grained personal access tokens (``github_pat_...``) cannot download attachments from private repositories directly. This affects both ``/assets/`` (images) and ``/files/`` (documents) URLs. The tool implements a workaround for image attachments using GitHub's Markdown API, which converts URLs to temporary JWT-signed URLs that can be downloaded. However, this workaround only works for images - document attachments (PDFs, text files, etc.) will fail with 404 errors when using fine-grained tokens on private repos. For full attachment support on private repositories, use a classic token (``-t``) instead of a fine-grained token (``-f``). See `#477 <https://github.com/josegonzalez/python-github-backup/issues/477>`_ for details.
285+
284286

285287
Run in Docker container
286288
-----------------------

github_backup/cli.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ def main():
4646
"Use -t/--token or -f/--token-fine to authenticate."
4747
)
4848

49+
# Issue #477: Fine-grained PATs cannot download all attachment types from
50+
# private repos. Image attachments will be retried via Markdown API workaround.
51+
if args.include_attachments and args.token_fine:
52+
logger.warning(
53+
"Using --attachments with fine-grained token. Due to GitHub platform "
54+
"limitations, file attachments (PDFs, etc.) from private repos may fail. "
55+
"Image attachments will be retried via workaround. For full attachment "
56+
"support, use --token-classic instead."
57+
)
58+
4959
if args.quiet:
5060
logger.setLevel(logging.WARNING)
5161

github_backup/github_backup.py

Lines changed: 100 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,6 +1062,65 @@ def download_attachment_file(url, path, auth, as_app=False, fine=False):
10621062
return metadata
10631063

10641064

1065+
def get_jwt_signed_url_via_markdown_api(url, token, repo_context):
1066+
"""Convert a user-attachments/assets URL to a JWT-signed URL via Markdown API.
1067+
1068+
GitHub's Markdown API renders image URLs and returns HTML containing
1069+
JWT-signed private-user-images.githubusercontent.com URLs that work
1070+
without token authentication.
1071+
1072+
This is a workaround for issue #477 where fine-grained PATs cannot
1073+
download user-attachments URLs from private repos directly.
1074+
1075+
Limitations:
1076+
- Only works for /assets/ URLs (images)
1077+
- Does NOT work for /files/ URLs (PDFs, text files, etc.)
1078+
- JWT URLs expire after ~5 minutes
1079+
1080+
Args:
1081+
url: The github.com/user-attachments/assets/UUID URL
1082+
token: Raw fine-grained PAT (github_pat_...)
1083+
repo_context: Repository context as "owner/repo"
1084+
1085+
Returns:
1086+
str: JWT-signed URL from private-user-images.githubusercontent.com
1087+
None: If conversion fails
1088+
"""
1089+
1090+
try:
1091+
payload = json.dumps(
1092+
{"text": f"![img]({url})", "mode": "gfm", "context": repo_context}
1093+
).encode("utf-8")
1094+
1095+
request = Request("https://api.github.com/markdown", data=payload, method="POST")
1096+
request.add_header("Authorization", f"token {token}")
1097+
request.add_header("Content-Type", "application/json")
1098+
request.add_header("Accept", "application/vnd.github+json")
1099+
1100+
html = urlopen(request, timeout=30).read().decode("utf-8")
1101+
1102+
# Parse JWT-signed URL from HTML response
1103+
# Format: <img src="https://private-user-images.githubusercontent.com/...?jwt=..." ...>
1104+
if match := re.search(
1105+
r'src="(https://private-user-images\.githubusercontent\.com/[^"]+)"', html
1106+
):
1107+
jwt_url = match.group(1)
1108+
logger.debug("Converted attachment URL to JWT-signed URL via Markdown API")
1109+
return jwt_url
1110+
1111+
logger.debug("Markdown API response did not contain JWT-signed URL")
1112+
return None
1113+
1114+
except HTTPError as e:
1115+
logger.debug(
1116+
"Markdown API request failed with HTTP {0}: {1}".format(e.code, e.reason)
1117+
)
1118+
return None
1119+
except Exception as e:
1120+
logger.debug("Markdown API request failed: {0}".format(str(e)))
1121+
return None
1122+
1123+
10651124
def extract_attachment_urls(item_data, issue_number=None, repository_full_name=None):
10661125
"""Extract GitHub-hosted attachment URLs from issue/PR body and comments.
10671126
@@ -1415,15 +1474,46 @@ def download_attachments(
14151474
filename = get_attachment_filename(url)
14161475
filepath = os.path.join(attachments_dir, filename)
14171476

1418-
# Download and get metadata
1419-
metadata = download_attachment_file(
1420-
url,
1421-
filepath,
1422-
get_auth(args, encode=not args.as_app),
1423-
as_app=args.as_app,
1424-
fine=args.token_fine is not None,
1477+
# Issue #477: Fine-grained PATs cannot download user-attachments/assets
1478+
# from private repos directly (404). Use Markdown API workaround to get
1479+
# a JWT-signed URL. Only works for /assets/ (images), not /files/.
1480+
needs_jwt = (
1481+
args.token_fine is not None
1482+
and repository.get("private", False)
1483+
and "github.com/user-attachments/assets/" in url
14251484
)
14261485

1486+
if not needs_jwt:
1487+
# NORMAL download path
1488+
metadata = download_attachment_file(
1489+
url,
1490+
filepath,
1491+
get_auth(args, encode=not args.as_app),
1492+
as_app=args.as_app,
1493+
fine=args.token_fine is not None,
1494+
)
1495+
elif jwt_url := get_jwt_signed_url_via_markdown_api(
1496+
url, args.token_fine, repository["full_name"]
1497+
):
1498+
# JWT needed and extracted, download via JWT
1499+
metadata = download_attachment_file(
1500+
jwt_url, filepath, auth=None, as_app=False, fine=False
1501+
)
1502+
metadata["url"] = url # Apply back the original URL
1503+
metadata["jwt_workaround"] = True
1504+
else:
1505+
# Markdown API workaround failed - skip download we know will fail
1506+
metadata = {
1507+
"url": url,
1508+
"success": False,
1509+
"skipped_at": datetime.now(timezone.utc).isoformat(),
1510+
"error": "Fine-grained token cannot download private repo attachments. "
1511+
"Markdown API workaround failed. Use --token-classic instead.",
1512+
}
1513+
logger.warning(
1514+
"Skipping attachment {0}: {1}".format(url, metadata["error"])
1515+
)
1516+
14271517
# If download succeeded but we got an extension from Content-Disposition,
14281518
# we may need to rename the file to add the extension
14291519
if metadata["success"] and metadata.get("original_filename"):
@@ -1951,7 +2041,9 @@ def backup_security_advisories(args, repo_cwd, repository, repos_template):
19512041
logger.info("Retrieving {0} security advisories".format(repository["full_name"]))
19522042
mkdir_p(repo_cwd, advisory_cwd)
19532043

1954-
template = "{0}/{1}/security-advisories".format(repos_template, repository["full_name"])
2044+
template = "{0}/{1}/security-advisories".format(
2045+
repos_template, repository["full_name"]
2046+
)
19552047

19562048
_advisories = retrieve_data(args, template)
19572049

tests/test_attachments.py

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,3 +349,139 @@ def test_manifest_skips_permanent_failures(self, attachment_test_setup):
349349
downloaded_urls[0]
350350
== "https://github.com/user-attachments/assets/unavailable"
351351
)
352+
353+
354+
class TestJWTWorkaround:
355+
"""Test JWT workaround for fine-grained tokens on private repos (issue #477)."""
356+
357+
def test_markdown_api_extracts_jwt_url(self):
358+
"""Markdown API response with JWT URL is extracted correctly."""
359+
from unittest.mock import patch, Mock
360+
361+
html_response = '''<p><a href="https://private-user-images.githubusercontent.com/123/abc.png?jwt=eyJhbGciOiJ"><img src="https://private-user-images.githubusercontent.com/123/abc.png?jwt=eyJhbGciOiJ" alt="img"></a></p>'''
362+
363+
mock_response = Mock()
364+
mock_response.read.return_value = html_response.encode("utf-8")
365+
366+
with patch("github_backup.github_backup.urlopen", return_value=mock_response):
367+
result = github_backup.get_jwt_signed_url_via_markdown_api(
368+
"https://github.com/user-attachments/assets/abc123",
369+
"github_pat_token",
370+
"owner/repo"
371+
)
372+
373+
assert result == "https://private-user-images.githubusercontent.com/123/abc.png?jwt=eyJhbGciOiJ"
374+
375+
def test_markdown_api_returns_none_on_http_error(self):
376+
"""HTTP errors return None."""
377+
from unittest.mock import patch
378+
from urllib.error import HTTPError
379+
380+
with patch("github_backup.github_backup.urlopen", side_effect=HTTPError(None, 403, "Forbidden", {}, None)):
381+
result = github_backup.get_jwt_signed_url_via_markdown_api(
382+
"https://github.com/user-attachments/assets/abc123",
383+
"github_pat_token",
384+
"owner/repo"
385+
)
386+
387+
assert result is None
388+
389+
def test_markdown_api_returns_none_when_no_jwt_url(self):
390+
"""Response without JWT URL returns None."""
391+
from unittest.mock import patch, Mock
392+
393+
mock_response = Mock()
394+
mock_response.read.return_value = b"<p>No image here</p>"
395+
396+
with patch("github_backup.github_backup.urlopen", return_value=mock_response):
397+
result = github_backup.get_jwt_signed_url_via_markdown_api(
398+
"https://github.com/user-attachments/assets/abc123",
399+
"github_pat_token",
400+
"owner/repo"
401+
)
402+
403+
assert result is None
404+
405+
def test_needs_jwt_only_for_fine_grained_private_assets(self):
406+
"""needs_jwt is True only for fine-grained + private + /assets/ URL."""
407+
assets_url = "https://github.com/user-attachments/assets/abc123"
408+
files_url = "https://github.com/user-attachments/files/123/doc.pdf"
409+
410+
# Fine-grained + private + assets = True
411+
assert (
412+
"github_pat_" is not None
413+
and True # private
414+
and "github.com/user-attachments/assets/" in assets_url
415+
) is True
416+
417+
# Fine-grained + private + files = False
418+
assert (
419+
"github_pat_" is not None
420+
and True
421+
and "github.com/user-attachments/assets/" in files_url
422+
) is False
423+
424+
# Fine-grained + public + assets = False
425+
assert (
426+
"github_pat_" is not None
427+
and False # public
428+
and "github.com/user-attachments/assets/" in assets_url
429+
) is False
430+
431+
def test_jwt_workaround_sets_manifest_flag(self, attachment_test_setup):
432+
"""Successful JWT workaround sets jwt_workaround flag in manifest."""
433+
from unittest.mock import patch, Mock
434+
435+
setup = attachment_test_setup
436+
setup["args"].token_fine = "github_pat_test"
437+
setup["repository"]["private"] = True
438+
439+
issue_data = {"body": "https://github.com/user-attachments/assets/abc123"}
440+
441+
jwt_url = "https://private-user-images.githubusercontent.com/123/abc.png?jwt=token"
442+
443+
with patch(
444+
"github_backup.github_backup.get_jwt_signed_url_via_markdown_api",
445+
return_value=jwt_url
446+
), patch(
447+
"github_backup.github_backup.download_attachment_file",
448+
return_value={"success": True, "http_status": 200, "url": jwt_url}
449+
):
450+
github_backup.download_attachments(
451+
setup["args"], setup["issue_cwd"], issue_data, 123, setup["repository"]
452+
)
453+
454+
manifest_path = os.path.join(setup["issue_cwd"], "attachments", "123", "manifest.json")
455+
with open(manifest_path) as f:
456+
manifest = json.load(f)
457+
458+
assert manifest["attachments"][0]["jwt_workaround"] is True
459+
assert manifest["attachments"][0]["url"] == "https://github.com/user-attachments/assets/abc123"
460+
461+
def test_jwt_workaround_failure_uses_skipped_at(self, attachment_test_setup):
462+
"""Failed JWT workaround uses skipped_at instead of downloaded_at."""
463+
from unittest.mock import patch
464+
465+
setup = attachment_test_setup
466+
setup["args"].token_fine = "github_pat_test"
467+
setup["repository"]["private"] = True
468+
469+
issue_data = {"body": "https://github.com/user-attachments/assets/abc123"}
470+
471+
with patch(
472+
"github_backup.github_backup.get_jwt_signed_url_via_markdown_api",
473+
return_value=None # Markdown API failed
474+
):
475+
github_backup.download_attachments(
476+
setup["args"], setup["issue_cwd"], issue_data, 123, setup["repository"]
477+
)
478+
479+
manifest_path = os.path.join(setup["issue_cwd"], "attachments", "123", "manifest.json")
480+
with open(manifest_path) as f:
481+
manifest = json.load(f)
482+
483+
attachment = manifest["attachments"][0]
484+
assert attachment["success"] is False
485+
assert "skipped_at" in attachment
486+
assert "downloaded_at" not in attachment
487+
assert "Use --token-classic" in attachment["error"]

0 commit comments

Comments
 (0)