Validate URL format. Args: url: URL to validate require_https: Require HTTPS scheme (except localhost) allow_localhost: Allow localhost URLs Returns: Validated URL Raises: ConfigurationError: If URL is invalid
(url: str, require_https: bool = False, allow_localhost: bool = True)
| 11 | |
| 12 | |
| 13 | def validate_url(url: str, require_https: bool = False, allow_localhost: bool = True) -> str: |
| 14 | """ |
| 15 | Validate URL format. |
| 16 | |
| 17 | Args: |
| 18 | url: URL to validate |
| 19 | require_https: Require HTTPS scheme (except localhost) |
| 20 | allow_localhost: Allow localhost URLs |
| 21 | |
| 22 | Returns: |
| 23 | Validated URL |
| 24 | |
| 25 | Raises: |
| 26 | ConfigurationError: If URL is invalid |
| 27 | """ |
| 28 | try: |
| 29 | parsed = urlparse(url) |
| 30 | |
| 31 | # Check scheme |
| 32 | if not parsed.scheme: |
| 33 | raise ConfigurationError(f"Invalid URL (missing scheme): {url}") |
| 34 | |
| 35 | # Check HTTPS requirement |
| 36 | if require_https and parsed.scheme != 'https': |
| 37 | # Allow HTTP for localhost |
| 38 | if allow_localhost and parsed.hostname in ['localhost', '127.0.0.1', '::1']: |
| 39 | pass |
| 40 | else: |
| 41 | raise ConfigurationError( |
| 42 | f"URL must use HTTPS: {url}\n" |
| 43 | f"HTTP is only allowed for localhost" |
| 44 | ) |
| 45 | |
| 46 | # Check hostname |
| 47 | if not parsed.hostname: |
| 48 | raise ConfigurationError(f"Invalid URL (missing hostname): {url}") |
| 49 | |
| 50 | return url |
| 51 | except ValueError as e: |
| 52 | raise ConfigurationError(f"Invalid URL format: {url}\nError: {e}") |
| 53 | |
| 54 | |
| 55 | def validate_api_key(api_key: str, min_length: int = 10) -> str: |
no test coverage detected