|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import ipaddress |
| 5 | +import os |
| 6 | +import re |
| 7 | +import sys |
| 8 | +from urllib.parse import urlsplit |
| 9 | + |
| 10 | + |
| 11 | +def _parse_args() -> argparse.Namespace: |
| 12 | + parser = argparse.ArgumentParser( |
| 13 | + description="Collect trusted project URLs from pyproject.toml files." |
| 14 | + ) |
| 15 | + parser.add_argument( |
| 16 | + "project_directory", help="Directory containing project pyproject.toml files." |
| 17 | + ) |
| 18 | + parser.add_argument("allowed_domains", help="Comma-separated list of allowed domains.") |
| 19 | + parser.add_argument("output_path", help="Path to write discovered URLs.") |
| 20 | + return parser.parse_args() |
| 21 | + |
| 22 | + |
| 23 | +def _is_allowed(hostname: str, allowed: set[str]) -> bool: |
| 24 | + """Check if the given hostname is allowed based on the provided set of allowed domains. |
| 25 | +
|
| 26 | + >>> _is_allowed('example.com', {'example.com'}) |
| 27 | + True |
| 28 | +
|
| 29 | + >>> _is_allowed('sub.example.com', {'example.com'}) |
| 30 | + False |
| 31 | +
|
| 32 | + >>> _is_allowed('sub.example.com', {'*.example.com'}) |
| 33 | + True |
| 34 | + """ |
| 35 | + if not hostname: |
| 36 | + return False |
| 37 | + |
| 38 | + host = hostname.lower().rstrip(".") |
| 39 | + if host == "localhost" or host.endswith(".localhost"): |
| 40 | + return False |
| 41 | + |
| 42 | + try: |
| 43 | + ip = ipaddress.ip_address(host) |
| 44 | + except ValueError: |
| 45 | + ip = None |
| 46 | + |
| 47 | + if ip is not None: |
| 48 | + return False |
| 49 | + |
| 50 | + if host in allowed: |
| 51 | + return True |
| 52 | + |
| 53 | + if any( |
| 54 | + host.endswith(f'.{domain.lstrip(".*")}') for domain in allowed if domain.startswith("*.") |
| 55 | + ): |
| 56 | + return True |
| 57 | + |
| 58 | + return False |
| 59 | + |
| 60 | + |
| 61 | +def _safe_under(base_dir: str, candidate_path: str) -> str: |
| 62 | + """Return a canonical path that stays under base_dir, or raise ValueError.""" |
| 63 | + safe_base = os.path.realpath(base_dir) |
| 64 | + safe_candidate = os.path.realpath(candidate_path) |
| 65 | + |
| 66 | + try: |
| 67 | + if os.path.commonpath([safe_base, safe_candidate]) != safe_base: |
| 68 | + raise ValueError(f"Path escapes base directory: {candidate_path!r}") |
| 69 | + except ValueError as exc: |
| 70 | + raise ValueError(f"Path escapes base directory: {candidate_path!r}") from exc |
| 71 | + |
| 72 | + return safe_candidate |
| 73 | + |
| 74 | + |
| 75 | +_URL_RE = re.compile(r'(https://.+?)(?:"|\s)') |
| 76 | + |
| 77 | + |
| 78 | +def _extract_links_from_line(line: str) -> list[str]: |
| 79 | + """Extract URLs from a single line, stopping before a quote or whitespace.""" |
| 80 | + matches: list[str] = [] |
| 81 | + for match in re.finditer(_URL_RE, line): |
| 82 | + url = match.group(1) |
| 83 | + if url: |
| 84 | + matches.append(url) |
| 85 | + return matches |
| 86 | + |
| 87 | + |
| 88 | +def _find_project_links(manifest_path: str, results: set[str], allowed: set[str]) -> None: |
| 89 | + """Find URLs within a pyproject.toml file without parsing TOML.""" |
| 90 | + try: |
| 91 | + with open(manifest_path, "r", encoding="utf-8") as manifest_file: |
| 92 | + for line in manifest_file: |
| 93 | + for url in _extract_links_from_line(line): |
| 94 | + host = urlsplit(url).hostname |
| 95 | + if host and _is_allowed(host, allowed): |
| 96 | + results.add(url) |
| 97 | + except OSError: |
| 98 | + print(f"Warning: Failed to read pyproject.toml at {manifest_path}", file=sys.stderr) |
| 99 | + |
| 100 | + |
| 101 | +def _main() -> int: |
| 102 | + args = _parse_args() |
| 103 | + safe_project_directory = _safe_under(os.getcwd(), args.project_directory) |
| 104 | + allowed_domains = args.allowed_domains |
| 105 | + output_path = args.output_path |
| 106 | + |
| 107 | + allowed: set[str] = set() |
| 108 | + for raw_domain in allowed_domains.split(","): |
| 109 | + domain = raw_domain.strip().lower().rstrip(".") |
| 110 | + if domain: |
| 111 | + allowed.add(domain) |
| 112 | + |
| 113 | + results: set[str] = set() |
| 114 | + |
| 115 | + for root, _, files in os.walk(safe_project_directory): |
| 116 | + for file_name in files: |
| 117 | + if file_name != "pyproject.toml": |
| 118 | + continue |
| 119 | + |
| 120 | + manifest_path = _safe_under(safe_project_directory, os.path.join(root, file_name)) |
| 121 | + _find_project_links(manifest_path, results, allowed) |
| 122 | + |
| 123 | + output_directory = os.path.dirname(output_path) |
| 124 | + if output_directory: |
| 125 | + os.makedirs(output_directory, exist_ok=True) |
| 126 | + |
| 127 | + with open(output_path, "w", encoding="utf-8") as output_file: |
| 128 | + for url in sorted(results): |
| 129 | + output_file.write(f"{url}\n") |
| 130 | + |
| 131 | + return 0 |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + sys.exit(_main()) |
0 commit comments