Raise ValueError if *url* is not http or https, or targets a private/internal IP. Blocks file://, ftp://, data:, and any other scheme that could be used for SSRF or local file access. Also blocks requests to private/reserved IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata en
(url: str)
| 103 | |
| 104 | |
| 105 | def validate_url(url: str) -> str: |
| 106 | """Raise ValueError if *url* is not http or https, or targets a private/internal IP. |
| 107 | |
| 108 | Blocks file://, ftp://, data:, and any other scheme that could be used |
| 109 | for SSRF or local file access. Also blocks requests to private/reserved |
| 110 | IP ranges (127.x, 10.x, 169.254.x, etc.) and cloud metadata endpoints |
| 111 | to prevent SSRF in cloud environments. |
| 112 | """ |
| 113 | parsed = urllib.parse.urlparse(url) |
| 114 | if parsed.scheme.lower() not in _ALLOWED_SCHEMES: |
| 115 | raise ValueError( |
| 116 | f"Blocked URL scheme '{parsed.scheme}' - only http and https are allowed. " |
| 117 | f"Got: {url!r}" |
| 118 | ) |
| 119 | |
| 120 | if parsed.username is not None or parsed.password is not None: |
| 121 | raise ValueError(f"Blocked URL containing embedded credentials. Got: {url!r}") |
| 122 | |
| 123 | try: |
| 124 | port = parsed.port |
| 125 | except ValueError as exc: |
| 126 | raise ValueError(f"Blocked URL with an invalid port. Got: {url!r}") from exc |
| 127 | if port == 0: |
| 128 | raise ValueError(f"Blocked URL with port 0. Got: {url!r}") |
| 129 | |
| 130 | hostname = parsed.hostname |
| 131 | if not hostname: |
| 132 | raise ValueError(f"Blocked URL without a hostname. Got: {url!r}") |
| 133 | |
| 134 | if hostname: |
| 135 | # Block known cloud metadata hostnames |
| 136 | if hostname.lower() in _BLOCKED_HOSTS: |
| 137 | raise ValueError( |
| 138 | f"Blocked cloud metadata endpoint '{hostname}'. " |
| 139 | f"Got: {url!r}" |
| 140 | ) |
| 141 | |
| 142 | # Resolve hostname and block private/reserved IP ranges |
| 143 | try: |
| 144 | infos = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM) |
| 145 | for info in infos: |
| 146 | addr = info[4][0] |
| 147 | ip = ipaddress.ip_address(addr) |
| 148 | if _ip_is_blocked(ip): |
| 149 | raise ValueError( |
| 150 | f"Blocked private/internal IP {addr} (resolved from '{hostname}'). " |
| 151 | f"Got: {url!r}" |
| 152 | ) |
| 153 | except socket.gaierror as exc: |
| 154 | raise ValueError( |
| 155 | f"DNS resolution failed for '{hostname}': {exc}. Got: {url!r}" |
| 156 | ) from exc |
| 157 | |
| 158 | return url |
| 159 | |
| 160 | |
| 161 | # --------------------------------------------------------------------------- |