from __future__ import annotations import ipaddress from pathlib import PurePath from urllib.parse import urlparse from sakura_cloud.core.config import settings def is_safe_upload_filename(file_name: str) -> bool: name = file_name.strip() if not name: return False path = PurePath(name) return path.name == name and name not in {".", ".."} and ".." not in path.parts def is_allowed_upload_mime(mime_type: str | None) -> bool: if not mime_type: return False return mime_type.lower().strip() in {item.lower() for item in settings.allowed_upload_mime_types} def is_allowed_external_url(url: str) -> bool: parsed = urlparse(url.strip()) if parsed.scheme not in {"http", "https"} or not parsed.hostname: return False host = parsed.hostname.rstrip(".").lower() try: ip = ipaddress.ip_address(host) except ValueError: ip = None if ip is not None: return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast) if host in {"localhost"} or host.endswith(".localhost"): return False allowed = {item.lower().strip().rstrip(".") for item in settings.allowed_external_url_domains} return any(host == domain or host.endswith(f".{domain}") for domain in allowed if domain)