-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathgithub_downloader.py
More file actions
2019 lines (1739 loc) · 91.7 KB
/
github_downloader.py
File metadata and controls
2019 lines (1739 loc) · 91.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""GitHub package downloader for APM dependencies."""
import os
import shutil
import stat
import sys
import tempfile
import time
from datetime import datetime
from pathlib import Path
from typing import Optional, Dict, Any, Callable
import random
import re
from typing import Union
import requests
import git
from git import Repo, RemoteProgress
from git.exc import GitCommandError, InvalidGitRepositoryError
from ..core.auth import AuthResolver
from ..models.apm_package import (
DependencyReference,
PackageInfo,
ResolvedReference,
GitReferenceType,
PackageType,
validate_apm_package,
APMPackage
)
from ..utils.github_host import (
build_https_clone_url,
build_ssh_url,
build_ado_https_clone_url,
build_ado_ssh_url,
build_ado_api_url,
build_raw_content_url,
build_artifactory_archive_url,
sanitize_token_url_in_message,
default_host,
is_azure_devops_hostname,
is_github_hostname
)
def normalize_collection_path(virtual_path: str) -> str:
"""Normalize a collection virtual path by stripping any existing extension.
This allows users to specify collection dependencies with or without the extension:
- owner/repo/collections/name (without extension)
- owner/repo/collections/name.collection.yml (with extension)
Args:
virtual_path: The virtual path from the dependency reference
Returns:
str: The normalized path without .collection.yml/.collection.yaml suffix
"""
for ext in ('.collection.yml', '.collection.yaml'):
if virtual_path.endswith(ext):
return virtual_path[:-len(ext)]
return virtual_path
def _debug(message: str) -> None:
"""Print debug message if APM_DEBUG environment variable is set."""
if os.environ.get('APM_DEBUG'):
print(f"[DEBUG] {message}", file=sys.stderr)
def _close_repo(repo) -> None:
"""Release GitPython handles so directories can be deleted on Windows."""
if repo is None:
return
try:
repo.git.clear_cache()
except Exception:
pass
try:
repo.close()
except Exception:
pass
def _rmtree(path) -> None:
"""Remove a directory tree, handling read-only files and brief Windows locks.
Git pack/index files are often read-only, and on Windows git processes may
hold brief locks even after the Repo object is closed. This wrapper uses
an onerror callback for read-only files and a single retry for lock races.
"""
def _on_readonly(func, fpath, _exc_info):
"""onerror callback: make read-only files writable and retry."""
try:
os.chmod(fpath, stat.S_IWRITE)
func(fpath)
except OSError:
pass
try:
shutil.rmtree(path, onerror=_on_readonly)
except PermissionError:
if sys.platform == 'win32':
# Single retry after a brief wait for lingering git handles
time.sleep(0.5)
shutil.rmtree(path, ignore_errors=True)
# On all platforms: don't raise from cleanup — just leave the
# temp dir behind (the OS will clean it up eventually).
class GitProgressReporter(RemoteProgress):
"""Report git clone progress to Rich Progress."""
def __init__(self, progress_task_id=None, progress_obj=None, package_name=None):
super().__init__()
self.task_id = progress_task_id
self.progress = progress_obj
self.package_name = package_name # Keep consistent name throughout download
self.last_op = None
self.disabled = False # Flag to stop updates after download completes
def update(self, op_code, cur_count, max_count=None, message=''):
"""Called by GitPython during clone operations."""
if not self.progress or self.task_id is None or self.disabled:
return
# Keep the package name consistent - don't change description to git operations
# This keeps the UI clean and scannable
# Update progress bar naturally - let it reach 100%
if max_count and max_count > 0:
# Determinate progress (we have total count)
self.progress.update(
self.task_id,
completed=cur_count,
total=max_count
# Note: We don't update description - keep the original package name
)
else:
# Indeterminate progress (just show activity)
self.progress.update(
self.task_id,
total=100, # Set fake total for indeterminate tasks
completed=min(cur_count, 100) if cur_count else 0
# Note: We don't update description - keep the original package name
)
self.last_op = cur_count
def _get_op_name(self, op_code):
"""Convert git operation code to human-readable name."""
from git import RemoteProgress
# Extract operation type from op_code
if op_code & RemoteProgress.COUNTING:
return "Counting objects"
elif op_code & RemoteProgress.COMPRESSING:
return "Compressing objects"
elif op_code & RemoteProgress.WRITING:
return "Writing objects"
elif op_code & RemoteProgress.RECEIVING:
return "Receiving objects"
elif op_code & RemoteProgress.RESOLVING:
return "Resolving deltas"
elif op_code & RemoteProgress.FINDING_SOURCES:
return "Finding sources"
elif op_code & RemoteProgress.CHECKING_OUT:
return "Checking out files"
else:
return "Cloning"
class GitHubPackageDownloader:
"""Downloads and validates APM packages from GitHub repositories."""
def __init__(self, auth_resolver=None):
"""Initialize the GitHub package downloader."""
from apm_cli.core.auth import AuthResolver
self.auth_resolver = auth_resolver or AuthResolver()
self.token_manager = self.auth_resolver._token_manager # Backward compat
self.git_env = self._setup_git_environment()
def _setup_git_environment(self) -> Dict[str, Any]:
"""Set up Git environment with authentication using centralized token manager.
Returns:
Dict containing environment variables for Git operations
"""
env = self.token_manager.setup_environment()
# Configure Git security settings
env['GIT_TERMINAL_PROMPT'] = '0'
env['GIT_ASKPASS'] = 'echo' # Prevent interactive credential prompts
env['GIT_CONFIG_NOSYSTEM'] = '1'
if sys.platform == 'win32':
# 'NUL' fails on some Windows git versions; use an empty temp file.
import tempfile
empty_cfg = os.path.join(tempfile.gettempdir(), '.apm_empty_gitconfig')
with open(empty_cfg, 'w') as f:
pass
env['GIT_CONFIG_GLOBAL'] = empty_cfg
else:
env['GIT_CONFIG_GLOBAL'] = '/dev/null'
# IMPORTANT: Do not resolve credentials via helpers at construction time.
# AuthResolver.resolve(...) can trigger OS credential helper UI. If we do
# this eagerly (host-only key) and later resolve per-dependency (host+org),
# users can see duplicate auth prompts. Keep constructor token state env-only
# and resolve lazily per dependency during clone/validate flows.
self._default_github_ctx = None
self.github_token = self.token_manager.get_token_for_purpose('modules', env)
self.has_github_token = self.github_token is not None
self._github_token_from_credential_fill = False
# Azure DevOps (env-only at init; lazy auth resolution happens per dep)
self.ado_token = self.token_manager.get_token_for_purpose('ado_modules', env)
self.has_ado_token = self.ado_token is not None
# JFrog Artifactory (not host-based, uses dedicated env var)
self.artifactory_token = self.token_manager.get_token_for_purpose('artifactory_modules', env)
self.has_artifactory_token = self.artifactory_token is not None
_debug(f"Token setup: has_github_token={self.has_github_token}, has_ado_token={self.has_ado_token}, has_artifactory_token={self.has_artifactory_token}"
f"{', source=credential_helper' if self._github_token_from_credential_fill else ''}")
return env
# --- Artifactory VCS archive download support ---
def _get_artifactory_headers(self) -> Dict[str, str]:
"""Build HTTP headers for Artifactory requests."""
headers = {}
if self.artifactory_token:
headers['Authorization'] = f'Bearer {self.artifactory_token}'
return headers
def _download_artifactory_archive(self, host: str, prefix: str, owner: str, repo: str,
ref: str, target_path: Path, scheme: str = "https") -> None:
"""Download and extract a zip archive from Artifactory VCS proxy.
Tries multiple URL patterns (GitHub-style and GitLab-style).
GitHub archives contain a single root directory named {repo}-{ref}/;
this method strips that prefix on extraction so files land directly
in *target_path*.
Raises RuntimeError on failure.
"""
import io
import zipfile
archive_urls = build_artifactory_archive_url(host, prefix, owner, repo, ref, scheme=scheme)
headers = self._get_artifactory_headers()
# Guard: reject unreasonably large archives (default 500 MB)
max_archive_bytes = int(
os.environ.get('ARTIFACTORY_MAX_ARCHIVE_MB', '500')
) * 1024 * 1024
last_error = None
for url in archive_urls:
_debug(f"Trying Artifactory archive: {url}")
try:
resp = self._resilient_get(url, headers=headers, timeout=60)
if resp.status_code == 200:
if len(resp.content) > max_archive_bytes:
last_error = f"Archive too large ({len(resp.content)} bytes) from {url}"
_debug(last_error)
continue
# Extract zip, stripping the top-level directory
target_path.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
# Identify the root prefix (e.g., "repo-main/")
names = zf.namelist()
if not names:
raise RuntimeError(f"Empty archive from {url}")
root_prefix = names[0]
if not root_prefix.endswith('/'):
# Single file archive; extract as-is
zf.extractall(target_path)
return
for member in zf.infolist():
# Strip root prefix
if member.filename == root_prefix:
continue
rel = member.filename[len(root_prefix):]
if not rel:
continue
# Guard: prevent zip path traversal (CWE-22)
dest = target_path / rel
if not dest.resolve().is_relative_to(target_path.resolve()):
_debug(f"Skipping zip entry escaping target: {member.filename}")
continue
if member.is_dir():
dest.mkdir(parents=True, exist_ok=True)
else:
dest.parent.mkdir(parents=True, exist_ok=True)
with zf.open(member) as src, open(dest, 'wb') as dst:
dst.write(src.read())
_debug(f"Extracted Artifactory archive to {target_path}")
return
else:
last_error = f"HTTP {resp.status_code} from {url}"
_debug(last_error)
except zipfile.BadZipFile:
last_error = f"Invalid zip archive from {url}"
_debug(last_error)
except requests.RequestException as e:
last_error = str(e)
_debug(f"Request failed: {last_error}")
raise RuntimeError(
f"Failed to download package {owner}/{repo}#{ref} from Artifactory "
f"({host}/{prefix}). Last error: {last_error}"
)
def _download_file_from_artifactory(self, host: str, prefix: str, owner: str,
repo: str, file_path: str, ref: str, scheme: str = "https") -> bytes:
"""Download a single file from Artifactory by fetching the full archive and extracting it."""
import io
import zipfile
archive_urls = build_artifactory_archive_url(host, prefix, owner, repo, ref, scheme=scheme)
headers = self._get_artifactory_headers()
for url in archive_urls:
try:
resp = self._resilient_get(url, headers=headers, timeout=60)
if resp.status_code != 200:
continue
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
names = zf.namelist()
root_prefix = names[0] if names else ""
target_name = root_prefix + file_path
if target_name in names:
return zf.read(target_name)
if file_path in names:
return zf.read(file_path)
except (zipfile.BadZipFile, requests.RequestException):
continue
raise RuntimeError(
f"Failed to download file '{file_path}' from Artifactory "
f"({host}/{prefix}/{owner}/{repo}#{ref})"
)
@staticmethod
def _is_artifactory_only() -> bool:
"""Return True when ARTIFACTORY_ONLY is set, blocking all direct git operations."""
return os.environ.get('ARTIFACTORY_ONLY', '').strip().lower() in ('1', 'true', 'yes')
def _should_use_artifactory_proxy(self, dep_ref: 'DependencyReference') -> bool:
"""Check if a dependency should be routed through the Artifactory transparent proxy."""
if dep_ref.is_artifactory():
return False # already explicit Artifactory
if self._is_artifactory_only():
return True
if dep_ref.is_azure_devops():
return False
host = dep_ref.host or default_host()
return is_github_hostname(host)
def _parse_artifactory_base_url(self) -> Optional[tuple]:
"""Parse ARTIFACTORY_BASE_URL into (host, prefix, scheme)."""
import urllib.parse as urlparse
base_url = os.environ.get('ARTIFACTORY_BASE_URL', '').strip().rstrip('/')
if not base_url:
return None
parsed = urlparse.urlparse(base_url)
if parsed.scheme not in ('https', 'http'):
_debug(f"ARTIFACTORY_BASE_URL has unsupported scheme: {parsed.scheme}")
return None
host = parsed.hostname
path = parsed.path.strip('/')
if not host or not path:
return None
return (host, path, parsed.scheme)
def _resilient_get(self, url: str, headers: Dict[str, str], timeout: int = 30, max_retries: int = 3) -> requests.Response:
"""HTTP GET with retry on 429/503 and rate-limit header awareness (#171).
Args:
url: Request URL
headers: HTTP headers
timeout: Request timeout in seconds
max_retries: Maximum retry attempts for transient failures
Returns:
requests.Response (caller should call .raise_for_status() as needed)
Raises:
requests.exceptions.RequestException: After all retries exhausted
"""
last_exc = None
last_response = None
for attempt in range(max_retries):
try:
response = requests.get(url, headers=headers, timeout=timeout)
# Handle rate limiting — GitHub returns 429 for secondary limits
# and 403 with X-RateLimit-Remaining: 0 for primary limits.
is_rate_limited = response.status_code in (429, 503)
if not is_rate_limited and response.status_code == 403:
try:
remaining = response.headers.get("X-RateLimit-Remaining")
if remaining is not None and int(remaining) == 0:
is_rate_limited = True
except (TypeError, ValueError):
pass
if is_rate_limited:
last_response = response
retry_after = response.headers.get("Retry-After")
reset_at = response.headers.get("X-RateLimit-Reset")
if retry_after:
try:
wait = min(float(retry_after), 60)
except (TypeError, ValueError):
# Retry-After may be an HTTP-date; fall back to exponential backoff
wait = min(2 ** attempt, 30) * (0.5 + random.random())
elif reset_at:
try:
wait = max(0, min(int(reset_at) - time.time(), 60))
except (TypeError, ValueError):
wait = min(2 ** attempt, 30) * (0.5 + random.random())
else:
wait = min(2 ** attempt, 30) * (0.5 + random.random())
_debug(f"Rate limited ({response.status_code}), retry in {wait:.1f}s (attempt {attempt + 1}/{max_retries})")
time.sleep(wait)
continue
# Log rate limit proximity
remaining = response.headers.get("X-RateLimit-Remaining")
try:
if remaining and int(remaining) < 10:
_debug(f"GitHub API rate limit low: {remaining} requests remaining")
except (TypeError, ValueError):
pass
return response
except requests.exceptions.ConnectionError as e:
last_exc = e
if attempt < max_retries - 1:
wait = min(2 ** attempt, 30) * (0.5 + random.random())
_debug(f"Connection error, retry in {wait:.1f}s (attempt {attempt + 1}/{max_retries})")
time.sleep(wait)
except requests.exceptions.Timeout as e:
last_exc = e
if attempt < max_retries - 1:
_debug(f"Timeout, retrying (attempt {attempt + 1}/{max_retries})")
# If rate limiting exhausted all retries, return the last response so
# callers can inspect headers (e.g. X-RateLimit-Remaining) and raise
# an appropriate user-facing error.
if last_response is not None:
return last_response
if last_exc:
raise last_exc
raise requests.exceptions.RequestException(f"All {max_retries} attempts failed for {url}")
def _sanitize_git_error(self, error_message: str) -> str:
"""Sanitize Git error messages to remove potentially sensitive authentication information.
Args:
error_message: Raw error message from Git operations
Returns:
str: Sanitized error message with sensitive data removed
"""
import re
# Remove any tokens that might appear in URLs for github hosts (format: https://token@host)
# Sanitize for default host and common enterprise hosts via helper
sanitized = sanitize_token_url_in_message(error_message, host=default_host())
# Sanitize Azure DevOps URLs - both cloud (dev.azure.com) and any on-prem server
# Use a generic pattern to catch https://token@anyhost format for all hosts
# This catches: dev.azure.com, ado.company.com, tfs.internal.corp, etc.
sanitized = re.sub(r'https://[^@\s]+@([^\s/]+)', r'https://***@\1', sanitized)
# Remove any tokens that might appear as standalone values
sanitized = re.sub(r'(ghp_|gho_|ghu_|ghs_|ghr_)[a-zA-Z0-9_]+', '***', sanitized)
# Remove environment variable values that might contain tokens
sanitized = re.sub(r'(GITHUB_TOKEN|GITHUB_APM_PAT|ADO_APM_PAT|GH_TOKEN|GITHUB_COPILOT_PAT)=[^\s]+', r'\1=***', sanitized)
return sanitized
def _build_repo_url(self, repo_ref: str, use_ssh: bool = False, dep_ref: DependencyReference = None, token: Optional[str] = None) -> str:
"""Build the appropriate repository URL for cloning.
Supports both GitHub and Azure DevOps URL formats:
- GitHub: https://github.com/owner/repo.git
- ADO: https://dev.azure.com/org/project/_git/repo
Args:
repo_ref: Repository reference in format "owner/repo" or "org/project/repo" for ADO
use_ssh: Whether to use SSH URL for git operations
dep_ref: Optional DependencyReference for ADO-specific URL building
token: Optional per-dependency token override
Returns:
str: Repository URL suitable for git clone operations
"""
# Use dep_ref.host if available (for ADO), otherwise fall back to instance or default
if dep_ref and dep_ref.host:
host = dep_ref.host
else:
host = getattr(self, 'github_host', None) or default_host()
# Check if this is Azure DevOps (either via dep_ref or host detection)
is_ado = (dep_ref and dep_ref.is_azure_devops()) or is_azure_devops_hostname(host)
# Use provided token or fall back to instance default
github_token = token if token is not None else self.github_token
ado_token = token if (token is not None and is_ado) else self.ado_token
_debug(f"_build_repo_url: host={host}, is_ado={is_ado}, dep_ref={'present' if dep_ref else 'None'}, "
f"ado_org={dep_ref.ado_organization if dep_ref else None}")
if is_ado and dep_ref and dep_ref.ado_organization:
# Use Azure DevOps URL builders with ADO-specific token
if use_ssh:
return build_ado_ssh_url(dep_ref.ado_organization, dep_ref.ado_project, dep_ref.ado_repo)
elif ado_token:
return build_ado_https_clone_url(
dep_ref.ado_organization,
dep_ref.ado_project,
dep_ref.ado_repo,
token=ado_token,
host=host
)
else:
return build_ado_https_clone_url(
dep_ref.ado_organization,
dep_ref.ado_project,
dep_ref.ado_repo,
host=host
)
else:
# Determine if this host should receive a GitHub token
is_github = is_github_hostname(host)
if use_ssh:
return build_ssh_url(host, repo_ref)
elif is_github and github_token:
# Only send GitHub tokens to GitHub hosts
return build_https_clone_url(host, repo_ref, token=github_token)
else:
# Generic hosts: plain HTTPS, let git credential helpers handle auth
return build_https_clone_url(host, repo_ref, token=None)
def _clone_with_fallback(self, repo_url_base: str, target_path: Path, progress_reporter=None, dep_ref: DependencyReference = None, verbose_callback=None, **clone_kwargs) -> Repo:
"""Attempt to clone a repository with fallback authentication methods.
Uses authentication patterns appropriate for the platform:
- GitHub: x-access-token format for private repos, SSH, or HTTPS
- Azure DevOps: PAT-based authentication
Args:
repo_url_base: Base repository reference (owner/repo)
target_path: Target path for cloning
progress_reporter: GitProgressReporter instance for progress updates
dep_ref: Optional DependencyReference for platform-specific URL building
verbose_callback: Optional callable for verbose logging (receives str messages)
**clone_kwargs: Additional arguments for Repo.clone_from
Returns:
Repo: Successfully cloned repository
Raises:
RuntimeError: If all authentication methods fail
"""
last_error = None
is_ado = dep_ref and dep_ref.is_azure_devops()
# Determine host type for auth decisions
dep_host = dep_ref.host if dep_ref else None
if dep_host:
is_github = is_github_hostname(dep_host)
else:
# When no host is specified, default to GitHub behavior
is_github = True
is_generic = not is_ado and not is_github
# Resolve per-dependency token via AuthResolver.
# Only use resolved token for GitHub/ADO hosts — generic hosts (GitLab,
# Bitbucket, etc.) delegate auth to git credential helpers.
if dep_ref and not is_generic:
dep_ctx = self.auth_resolver.resolve_for_dep(dep_ref)
dep_token = dep_ctx.token
elif is_generic:
dep_token = None
else:
dep_token = self.github_token # fallback
has_token = dep_token
_debug(f"_clone_with_fallback: repo={repo_url_base}, is_ado={is_ado}, is_generic={is_generic}, has_token={has_token is not None}")
# When APM has a token for this host, use the locked-down env (APM manages auth).
# When no token is available, relax the env so git credential helpers (gh auth,
# macOS Keychain, etc.) can provide credentials -- regardless of host.
if has_token:
clone_env = self.git_env
else:
clone_env = {k: v for k, v in self.git_env.items()
if k not in ('GIT_ASKPASS', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM')}
clone_env['GIT_TERMINAL_PROMPT'] = '0' # Still prevent interactive prompts
# Method 1: Try authenticated HTTPS if token is available (GitHub/ADO only)
if has_token:
try:
auth_url = self._build_repo_url(repo_url_base, use_ssh=False, dep_ref=dep_ref, token=dep_token)
_debug(f"Attempting clone with authenticated HTTPS (URL sanitized)")
repo = Repo.clone_from(auth_url, target_path, env=clone_env, progress=progress_reporter, **clone_kwargs)
if verbose_callback:
masked = self._sanitize_git_error(auth_url)
verbose_callback(f"Cloned from: {masked}")
return repo
except GitCommandError as e:
last_error = e
# Continue to next method
# Method 2: Try SSH (works with SSH keys for any host)
try:
ssh_url = self._build_repo_url(repo_url_base, use_ssh=True, dep_ref=dep_ref)
repo = Repo.clone_from(ssh_url, target_path, env=clone_env, progress=progress_reporter, **clone_kwargs)
if verbose_callback:
verbose_callback(f"Cloned from: {ssh_url}")
return repo
except GitCommandError as e:
last_error = e
# Continue to next method
# Method 3: Try standard HTTPS (public repos, or git credential helper for generic hosts)
try:
https_url = self._build_repo_url(repo_url_base, use_ssh=False, dep_ref=dep_ref)
repo = Repo.clone_from(https_url, target_path, env=clone_env, progress=progress_reporter, **clone_kwargs)
if verbose_callback:
verbose_callback(f"Cloned from: {https_url}")
return repo
except GitCommandError as e:
last_error = e
# All methods failed
error_msg = f"Failed to clone repository {repo_url_base} using all available methods. "
configured_host = os.environ.get("GITHUB_HOST", "")
if is_ado and not self.has_ado_token:
host = dep_host or "dev.azure.com"
error_msg += self.auth_resolver.build_error_context(host, "clone", org=dep_ref.ado_organization if dep_ref else None)
elif is_generic:
host_name = dep_host or "the target host"
error_msg += (
f"For private repositories on {host_name}, configure SSH keys or a git credential helper. "
f"APM delegates authentication to git for non-GitHub/ADO hosts."
)
elif configured_host and dep_host and dep_host == configured_host and configured_host != "github.com":
suggested = f"github.com/{repo_url_base}"
if dep_ref and dep_ref.virtual_path:
suggested += f"/{dep_ref.virtual_path}"
error_msg += (
f"GITHUB_HOST is set to '{configured_host}', so shorthand dependencies "
f"(without a hostname) resolve against that host. "
f"If this package lives on a different server (e.g., github.com), "
f"use the full hostname in apm.yml: {suggested}"
)
elif not self.has_github_token:
host = dep_host or default_host()
org = dep_ref.repo_url.split('/')[0] if dep_ref and dep_ref.repo_url else None
error_msg += self.auth_resolver.build_error_context(host, "clone", org=org)
else:
error_msg += "Please check repository access permissions and authentication setup."
if last_error:
sanitized_error = self._sanitize_git_error(str(last_error))
error_msg += f" Last error: {sanitized_error}"
raise RuntimeError(error_msg)
def resolve_git_reference(self, repo_ref: Union[str, "DependencyReference"]) -> ResolvedReference:
"""Resolve a Git reference (branch/tag/commit) to a specific commit SHA.
Args:
repo_ref: Repository reference — either a DependencyReference object
or a string (e.g., "user/repo#branch"). Passing the object
directly avoids a lossy parse round-trip for generic git hosts.
Returns:
ResolvedReference: Resolved reference with commit SHA
Raises:
ValueError: If the reference format is invalid
RuntimeError: If Git operations fail
"""
# Accept both string and DependencyReference to avoid lossy round-trips
if isinstance(repo_ref, DependencyReference):
dep_ref = repo_ref
else:
try:
dep_ref = DependencyReference.parse(repo_ref)
except ValueError as e:
raise ValueError(f"Invalid repository reference '{repo_ref}': {e}")
# Default to main branch if no reference specified
ref = dep_ref.reference or "main"
# Normalize to string for ResolvedReference.original_ref
original_ref_str = str(dep_ref)
# Artifactory: no git repo to query, return ref-based resolution
if dep_ref.is_artifactory() or (
self._parse_artifactory_base_url()
and self._should_use_artifactory_proxy(dep_ref)
):
is_commit = re.match(r'^[a-f0-9]{7,40}$', ref.lower()) is not None
return ResolvedReference(
original_ref=original_ref_str,
ref_type=GitReferenceType.COMMIT if is_commit else GitReferenceType.BRANCH,
resolved_commit=None,
ref_name=ref
)
# Pre-analyze the reference type to determine the best approach
is_likely_commit = re.match(r'^[a-f0-9]{7,40}$', ref.lower()) is not None
# Create a temporary directory for Git operations
temp_dir = None
try:
temp_dir = Path(tempfile.mkdtemp())
if is_likely_commit:
# For commit SHAs, clone full repository first, then checkout the commit
try:
# Ensure host is set for enterprise repos
repo = self._clone_with_fallback(dep_ref.repo_url, temp_dir, progress_reporter=None, dep_ref=dep_ref)
commit = repo.commit(ref)
ref_type = GitReferenceType.COMMIT
resolved_commit = commit.hexsha
ref_name = ref
except Exception as e:
sanitized_error = self._sanitize_git_error(str(e))
raise ValueError(f"Could not resolve commit '{ref}' in repository {dep_ref.repo_url}: {sanitized_error}")
else:
# For branches and tags, try shallow clone first
try:
# Try to clone with specific branch/tag first
repo = self._clone_with_fallback(
dep_ref.repo_url,
temp_dir,
progress_reporter=None,
dep_ref=dep_ref,
depth=1,
branch=ref
)
ref_type = GitReferenceType.BRANCH # Could be branch or tag
resolved_commit = repo.head.commit.hexsha
ref_name = ref
except GitCommandError:
# If branch/tag clone fails, try full clone and resolve reference
try:
repo = self._clone_with_fallback(dep_ref.repo_url, temp_dir, progress_reporter=None, dep_ref=dep_ref)
# Try to resolve the reference
try:
# Try as branch first
try:
branch = repo.refs[f"origin/{ref}"]
ref_type = GitReferenceType.BRANCH
resolved_commit = branch.commit.hexsha
ref_name = ref
except IndexError:
# Try as tag
try:
tag = repo.tags[ref]
ref_type = GitReferenceType.TAG
resolved_commit = tag.commit.hexsha
ref_name = ref
except IndexError:
raise ValueError(f"Reference '{ref}' not found in repository {dep_ref.repo_url}")
except Exception as e:
sanitized_error = self._sanitize_git_error(str(e))
raise ValueError(f"Could not resolve reference '{ref}' in repository {dep_ref.repo_url}: {sanitized_error}")
except GitCommandError as e:
# Check if this might be a private repository access issue
if "Authentication failed" in str(e) or "remote: Repository not found" in str(e):
error_msg = f"Failed to clone repository {dep_ref.repo_url}. "
host = dep_ref.host or default_host()
org = dep_ref.repo_url.split('/')[0] if dep_ref.repo_url else None
error_msg += self.auth_resolver.build_error_context(host, "resolve reference", org=org)
raise RuntimeError(error_msg)
else:
sanitized_error = self._sanitize_git_error(str(e))
raise RuntimeError(f"Failed to clone repository {dep_ref.repo_url}: {sanitized_error}")
finally:
if temp_dir and temp_dir.exists():
shutil.rmtree(temp_dir, ignore_errors=True)
return ResolvedReference(
original_ref=original_ref_str,
ref_type=ref_type,
resolved_commit=resolved_commit,
ref_name=ref_name
)
def download_raw_file(self, dep_ref: DependencyReference, file_path: str, ref: str = "main", verbose_callback=None) -> bytes:
"""Download a single file from repository (GitHub or Azure DevOps).
Args:
dep_ref: Parsed dependency reference
file_path: Path to file within the repository (e.g., "prompts/code-review.prompt.md")
ref: Git reference (branch, tag, or commit SHA). Defaults to "main"
verbose_callback: Optional callable for verbose logging (receives str messages)
Returns:
bytes: File content
Raises:
RuntimeError: If download fails or file not found
"""
host = dep_ref.host or default_host()
# Check if this is Artifactory (Mode 1: explicit FQDN)
if dep_ref.is_artifactory():
repo_parts = dep_ref.repo_url.split('/')
return self._download_file_from_artifactory(
dep_ref.host, dep_ref.artifactory_prefix,
repo_parts[0], repo_parts[1] if len(repo_parts) > 1 else repo_parts[0],
file_path, ref,
)
# Check if this should go through Artifactory proxy (Mode 2)
art_proxy = self._parse_artifactory_base_url()
if art_proxy and self._should_use_artifactory_proxy(dep_ref):
repo_parts = dep_ref.repo_url.split('/')
return self._download_file_from_artifactory(
art_proxy[0], art_proxy[1],
repo_parts[0], repo_parts[1] if len(repo_parts) > 1 else repo_parts[0],
file_path, ref, scheme=art_proxy[2],
)
# Check if this is Azure DevOps
if dep_ref.is_azure_devops():
return self._download_ado_file(dep_ref, file_path, ref)
# GitHub API
return self._download_github_file(dep_ref, file_path, ref, verbose_callback=verbose_callback)
def _download_ado_file(self, dep_ref: DependencyReference, file_path: str, ref: str = "main") -> bytes:
"""Download a file from Azure DevOps repository.
Args:
dep_ref: Parsed dependency reference with ADO-specific fields
file_path: Path to file within the repository
ref: Git reference (branch, tag, or commit SHA)
Returns:
bytes: File content
"""
import base64
# Validate required ADO fields before proceeding
if not all([dep_ref.ado_organization, dep_ref.ado_project, dep_ref.ado_repo]):
raise ValueError(
f"Invalid Azure DevOps dependency reference: missing organization, project, or repo. "
f"Got: org={dep_ref.ado_organization}, project={dep_ref.ado_project}, repo={dep_ref.ado_repo}"
)
host = dep_ref.host or "dev.azure.com"
api_url = build_ado_api_url(
dep_ref.ado_organization,
dep_ref.ado_project,
dep_ref.ado_repo,
file_path,
ref,
host
)
# Set up authentication headers - ADO uses Basic auth with PAT
headers = {}
if self.ado_token:
# ADO uses Basic auth: username can be empty, password is the PAT
auth = base64.b64encode(f":{self.ado_token}".encode()).decode()
headers['Authorization'] = f'Basic {auth}'
try:
response = self._resilient_get(api_url, headers=headers, timeout=30)
response.raise_for_status()
return response.content
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
# Try fallback branches
if ref not in ["main", "master"]:
raise RuntimeError(f"File not found: {file_path} at ref '{ref}' in {dep_ref.repo_url}")
fallback_ref = "master" if ref == "main" else "main"
fallback_url = build_ado_api_url(
dep_ref.ado_organization,
dep_ref.ado_project,
dep_ref.ado_repo,
file_path,
fallback_ref,
host
)
try:
response = self._resilient_get(fallback_url, headers=headers, timeout=30)
response.raise_for_status()
return response.content
except requests.exceptions.HTTPError:
raise RuntimeError(
f"File not found: {file_path} in {dep_ref.repo_url} "
f"(tried refs: {ref}, {fallback_ref})"
)
elif e.response.status_code == 401 or e.response.status_code == 403:
error_msg = f"Authentication failed for Azure DevOps {dep_ref.repo_url}. "
if not self.ado_token:
error_msg += self.auth_resolver.build_error_context(host, "download", org=dep_ref.ado_organization if dep_ref else None)
else:
error_msg += "Please check your Azure DevOps PAT permissions."
raise RuntimeError(error_msg)
else:
raise RuntimeError(f"Failed to download {file_path}: HTTP {e.response.status_code}")
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Network error downloading {file_path}: {e}")
def _try_raw_download(self, owner: str, repo: str, ref: str, file_path: str) -> Optional[bytes]:
"""Attempt to fetch a file via raw.githubusercontent.com (CDN).
Returns the raw bytes on success, or ``None`` if the file was not found
(HTTP 404) or the request failed for any reason. This is intentionally
best-effort: callers fall back to the Contents API when ``None`` is
returned.
"""
raw_url = build_raw_content_url(owner, repo, ref, file_path)
try:
response = requests.get(raw_url, timeout=30)
if response.status_code == 200:
return response.content
except requests.exceptions.RequestException:
pass
return None
def _download_github_file(self, dep_ref: DependencyReference, file_path: str, ref: str = "main", verbose_callback=None) -> bytes:
"""Download a file from GitHub repository.
For github.com without a token, tries raw.githubusercontent.com first
(CDN, no rate limit) before falling back to the Contents API. Authenticated
requests and non-github.com hosts always use the Contents API directly.
Args:
dep_ref: Parsed dependency reference
file_path: Path to file within the repository
ref: Git reference (branch, tag, or commit SHA)
verbose_callback: Optional callable for verbose logging (receives str messages)
Returns:
bytes: File content
"""
host = dep_ref.host or default_host()
# Parse owner/repo from repo_url
owner, repo = dep_ref.repo_url.split('/', 1)
# Resolve token via AuthResolver for CDN fast-path decision
org = None
if dep_ref and dep_ref.repo_url:
parts = dep_ref.repo_url.split('/')
if parts:
org = parts[0]
file_ctx = self.auth_resolver.resolve(host, org)
token = file_ctx.token
# --- CDN fast-path for github.com without a token ---
# raw.githubusercontent.com is served from GitHub's CDN and is not
# subject to the REST API rate limit (60 req/h unauthenticated).
# Only available for github.com — GHES/GHE-DR have no equivalent.
if host.lower() == "github.com" and not token:
content = self._try_raw_download(owner, repo, ref, file_path)
if content is not None:
if verbose_callback:
verbose_callback(f"Downloaded file: {host}/{dep_ref.repo_url}/{file_path}")
return content
# raw download returned 404 — could be wrong default branch.
# Try the other default branch before falling through to the API.
if ref in ("main", "master"):
fallback_ref = "master" if ref == "main" else "main"
content = self._try_raw_download(owner, repo, fallback_ref, file_path)
if content is not None:
if verbose_callback:
verbose_callback(f"Downloaded file: {host}/{dep_ref.repo_url}/{file_path}")
return content
# All raw attempts failed — fall through to API path which
# handles private repos, rate-limit messaging, and SAML errors.
# --- Contents API path (authenticated, enterprise, or raw fallback) ---
# Build GitHub API URL - format differs by host type
if host == "github.com":