#!/usr/bin/env python3 """Small dependency-free HTTP server for private image submissions.""" from __future__ import annotations import argparse import json import os import re import secrets import sys import tomllib from dataclasses import dataclass, field from email.parser import BytesParser from email.policy import default from email.utils import parseaddr from http import HTTPStatus from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import unquote, urlsplit MAX_FILE_BYTES = 10 * 1024 * 1024 MAX_REQUEST_BYTES = MAX_FILE_BYTES + 1024 * 1024 MAX_CALLSIGN_LENGTH = 32 MAX_NAME_LENGTH = 200 MAX_EMAIL_LENGTH = 254 MAX_DESCRIPTION_LENGTH = 1000 STATIC_DIR = Path(__file__).resolve().parent / "static" DEFAULT_CONFIG_FILE = Path(__file__).resolve().parent / "config.toml" STATIC_FILES = { "/styles.css": ("styles.css", "text/css; charset=utf-8"), "/app.js": ("app.js", "text/javascript; charset=utf-8"), } TARGET_PATTERN = re.compile(r"^/([A-Za-z0-9][A-Za-z0-9_-]{0,63})/?$") RESERVED_TARGETS = {"healthz"} @dataclass(frozen=True) class SMTPSettings: send_as: str server: str port: int tls: bool starttls: bool @dataclass(frozen=True) class AppConfig: smtp: SMTPSettings recipients: dict[str, str] # Absolute http(s) URL, ending in "/", under which a target's stored files are viewable. view_url_prefixes: dict[str, str] = field(default_factory=dict) def target_from_path(path: str) -> str | None: """Return a safe single-segment intake target, if the path contains one.""" match = TARGET_PATTERN.fullmatch(unquote(path)) if match is None or match.group(1) in RESERVED_TARGETS: return None return match.group(1) def _validate_email(value: object, setting: str) -> str: if ( not isinstance(value, str) or len(value) > 254 or any(character.isspace() or ord(character) < 32 for character in value) or parseaddr(value)[1] != value or value.count("@") != 1 ): raise ValueError(f"{setting} must be a valid email address") return value def _validate_view_url_prefix(value: object, setting: str) -> str: if not isinstance(value, str) or any(character.isspace() or ord(character) < 32 for character in value): raise ValueError(f"{setting} must be an absolute http(s) URL") parts = urlsplit(value) if parts.scheme not in {"http", "https"} or not parts.netloc or parts.query or parts.fragment: raise ValueError(f"{setting} must be an absolute http(s) URL without a query or fragment") return value if value.endswith("/") else value + "/" def load_config(path: Path) -> AppConfig: """Load SMTP settings and URI-to-recipient mappings from TOML.""" try: with path.open("rb") as config_file: raw_config = tomllib.load(config_file) except tomllib.TOMLDecodeError as error: raise ValueError(f"Invalid TOML configuration in {path}: {error}") from error global_settings = raw_config.get("GLOBAL") required_global = {"send_as", "smtp_server", "smtp_port", "tls", "starttls"} if not isinstance(global_settings, dict) or set(global_settings) != required_global: raise ValueError(f"[GLOBAL] in {path} must define exactly: {', '.join(sorted(required_global))}") send_as = _validate_email(global_settings["send_as"], "GLOBAL.send_as") smtp_server = global_settings["smtp_server"] smtp_port = global_settings["smtp_port"] tls = global_settings["tls"] starttls = global_settings["starttls"] if not isinstance(smtp_server, str) or not smtp_server or smtp_server.strip() != smtp_server: raise ValueError("GLOBAL.smtp_server must be a non-empty hostname") if type(smtp_port) is not int or not 1 <= smtp_port <= 65535: raise ValueError("GLOBAL.smtp_port must be an integer between 1 and 65535") if type(tls) is not bool or type(starttls) is not bool: raise ValueError("GLOBAL.tls and GLOBAL.starttls must be booleans") if tls and starttls: raise ValueError("GLOBAL.tls and GLOBAL.starttls cannot both be true") recipients: dict[str, str] = {} view_url_prefixes: dict[str, str] = {} allowed_keys = {"recipient", "view_url_prefix"} for stanza, values in raw_config.items(): if stanza == "GLOBAL": continue target = target_from_path(f"/{stanza}") if target != stanza: raise ValueError(f"Invalid upload URI stanza in {path}: {stanza!r}") if not isinstance(values, dict) or "recipient" not in values or not set(values) <= allowed_keys: raise ValueError( f"[{stanza}] in {path} must define recipient and may define only view_url_prefix besides it" ) recipients[target] = _validate_email(values["recipient"], f"{stanza}.recipient") if "view_url_prefix" in values: view_url_prefixes[target] = _validate_view_url_prefix( values["view_url_prefix"], f"{stanza}.view_url_prefix" ) if not recipients: raise ValueError(f"No upload URI stanzas are configured in {path}") return AppConfig( smtp=SMTPSettings(send_as, smtp_server, smtp_port, tls, starttls), recipients=recipients, view_url_prefixes=view_url_prefixes, ) def detect_image_type(data: bytes) -> tuple[str, str] | None: """Return a safe extension and MIME type based on file signatures.""" if data.startswith(b"\xff\xd8\xff"): return ".jpg", "image/jpeg" if data.startswith(b"\x89PNG\r\n\x1a\n"): return ".png", "image/png" if len(data) >= 12 and data[4:8] == b"ftyp": brands = {data[8:12]} brands.update(data[index : index + 4] for index in range(16, min(len(data), 64), 4)) if brands & {b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"mif1", b"msf1"}: return ".heic", "image/heic" return None def parse_single_upload(content_type: str, body: bytes) -> tuple[str, bytes, dict[str, str]]: """Parse one image and its required metadata from a multipart request.""" if not content_type.lower().startswith("multipart/form-data;"): raise ValueError("Expected a multipart form upload.") message = BytesParser(policy=default).parsebytes( b"Content-Type: " + content_type.encode("latin-1") + b"\r\nMIME-Version: 1.0\r\n\r\n" + body ) if not message.is_multipart(): raise ValueError("The upload form is malformed.") file_parts = [] text_parts: dict[str, list[object]] = {} for part in message.iter_parts(): if part.get_content_disposition() != "form-data": continue field_name = part.get_param("name", header="content-disposition") filename = part.get_filename() if filename is not None: file_parts.append(part) elif isinstance(field_name, str): text_parts.setdefault(field_name, []).append(part) if len(file_parts) != 1 or file_parts[0].get_param("name", header="content-disposition") != "image": raise ValueError("Submit exactly one image.") expected_fields = {"callsign", "name", "email", "description"} if set(text_parts) != expected_fields or any(len(parts) != 1 for parts in text_parts.values()): raise ValueError("Submit callsign, name, email address, and file description exactly once.") metadata: dict[str, str] = {} for field_name, parts in text_parts.items(): part = parts[0] raw_value = part.get_payload(decode=True) if raw_value is None: raise ValueError(f"The {field_name} field is malformed.") try: value = raw_value.decode(part.get_content_charset() or "utf-8") except (LookupError, UnicodeDecodeError) as error: raise ValueError(f"The {field_name} field must contain valid text.") from error metadata[field_name] = value.strip() if not metadata["callsign"]: raise ValueError("Enter an amateur radio callsign.") if not metadata["name"]: raise ValueError("Enter your name.") if not metadata["email"]: raise ValueError("Enter your email address.") if not metadata["description"]: raise ValueError("Enter a brief description of the file.") if len(metadata["callsign"]) > MAX_CALLSIGN_LENGTH: raise ValueError(f"The callsign must be {MAX_CALLSIGN_LENGTH} characters or fewer.") if len(metadata["name"]) > MAX_NAME_LENGTH: raise ValueError(f"The name must be {MAX_NAME_LENGTH} characters or fewer.") if len(metadata["email"]) > MAX_EMAIL_LENGTH: raise ValueError(f"The email address must be {MAX_EMAIL_LENGTH} characters or fewer.") if len(metadata["description"]) > MAX_DESCRIPTION_LENGTH: raise ValueError(f"The file description must be {MAX_DESCRIPTION_LENGTH} characters or fewer.") if any(character in metadata[field] for field in ("callsign", "name", "email") for character in "\r\n\x00"): raise ValueError("Callsign, name, and email address must each fit on one line.") if "\x00" in metadata["description"]: raise ValueError("The file description contains an invalid character.") if "@" not in metadata["email"] or metadata["email"].startswith("@") or metadata["email"].endswith("@"): raise ValueError("Enter a valid email address.") part = file_parts[0] filename = Path(part.get_filename() or "image").name payload = part.get_payload(decode=True) if payload is None or not payload: raise ValueError("The selected image is empty.") if len(payload) > MAX_FILE_BYTES: raise OverflowError("The image must be 10 MB or smaller.") return filename, payload, metadata def format_metadata(metadata: dict[str, str]) -> bytes: """Return human-readable UTF-8 content for an upload's sidecar file.""" return ( f"Callsign: {metadata['callsign']}\n" f"Name: {metadata['name']}\n" f"Email: {metadata['email']}\n" "Description:\n" f"{metadata['description']}\n" ).encode("utf-8") class UploadHandler(BaseHTTPRequestHandler): server_version = "BlindUploader/1.0" @property def upload_dir(self) -> Path: return self.server.upload_dir # type: ignore[attr-defined] @property def allowed_targets(self) -> frozenset[str]: return self.server.allowed_targets # type: ignore[attr-defined] def do_GET(self) -> None: path = urlsplit(self.path).path if path == "/healthz": self.send_json(HTTPStatus.OK, {"status": "ok"}) return static_file = STATIC_FILES.get(path) if static_file is not None: filename, content_type = static_file self.send_static(filename, content_type) return if path == "/": self.send_error_response(HTTPStatus.IM_A_TEAPOT, "A valid upload target is required.") return target = target_from_path(path) if target is None or target not in self.allowed_targets: self.send_error_response(HTTPStatus.NOT_FOUND, "A valid upload target is required.") return self.send_static("index.html", "text/html; charset=utf-8") def send_static(self, filename: str, content_type: str) -> None: data = (STATIC_DIR / filename).read_bytes() self.send_response(HTTPStatus.OK) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store") self.send_security_headers() self.end_headers() self.wfile.write(data) def do_POST(self) -> None: path = urlsplit(self.path).path if path == "/": self.send_error_response(HTTPStatus.IM_A_TEAPOT, "A valid upload target is required.") return target = target_from_path(path) if target is None or target not in self.allowed_targets: self.send_error_response(HTTPStatus.NOT_FOUND, "A valid upload target is required.") return try: content_length = int(self.headers.get("Content-Length", "")) except ValueError: content_length = -1 if content_length < 0: self.send_error_response(HTTPStatus.LENGTH_REQUIRED, "A Content-Length header is required.") return if content_length > MAX_REQUEST_BYTES: self.send_error_response(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, "The image must be 10 MB or smaller.") return body = self.rfile.read(content_length) try: _original_name, payload, metadata = parse_single_upload(self.headers.get("Content-Type", ""), body) detected = detect_image_type(payload) if detected is None: raise TypeError("Only JPG, PNG, and HEIC images are accepted.") extension, _mime_type = detected storage_id = secrets.token_hex(20) receipt = storage_id[:12] target_dir = self.upload_dir / target target_dir.mkdir(mode=0o700, exist_ok=True) target_dir.chmod(0o700) destination = target_dir / f"{storage_id}{extension}" metadata_destination = target_dir / f"{storage_id}.txt" created_files: list[Path] = [] try: for path, content in ((destination, payload), (metadata_destination, format_metadata(metadata))): descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) created_files.append(path) with os.fdopen(descriptor, "wb") as output: output.write(content) except OSError: for path in created_files: try: path.unlink() except OSError: pass raise except OverflowError as error: self.send_error_response(HTTPStatus.REQUEST_ENTITY_TOO_LARGE, str(error)) return except (TypeError, ValueError) as error: self.send_error_response(HTTPStatus.BAD_REQUEST, str(error)) return except OSError: self.log_error("Unable to persist an uploaded submission") self.send_error_response( HTTPStatus.INTERNAL_SERVER_ERROR, "The submission could not be stored. Please try again." ) return self.send_json( HTTPStatus.CREATED, {"ok": True, "message": "Your image was submitted privately.", "receipt": receipt}, ) def do_HEAD(self) -> None: self.send_error_response(HTTPStatus.METHOD_NOT_ALLOWED, "Method not allowed.") def send_json(self, status: HTTPStatus, payload: dict[str, object]) -> None: body = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.send_security_headers() self.end_headers() self.wfile.write(body) def send_error_response(self, status: HTTPStatus, message: str) -> None: self.send_json(status, {"ok": False, "message": message}) def send_security_headers(self) -> None: self.send_header("X-Content-Type-Options", "nosniff") self.send_header("X-Frame-Options", "DENY") self.send_header("X-Robots-Tag", "noindex, nofollow, noarchive") self.send_header("Referrer-Policy", "no-referrer") self.send_header( "Content-Security-Policy", "default-src 'self'; img-src 'self' blob:; script-src 'self'; style-src 'self'; " "base-uri 'none'; frame-ancestors 'none'; form-action 'self'", ) def log_message(self, format: str, *args: object) -> None: sys.stderr.write("%s - %s\n" % (self.address_string(), format % args)) def make_server( host: str, port: int, upload_dir: Path, allowed_targets: frozenset[str] ) -> ThreadingHTTPServer: upload_dir.mkdir(mode=0o700, parents=True, exist_ok=True) try: upload_dir.chmod(0o700) except OSError: pass server = ThreadingHTTPServer((host, port), UploadHandler) server.upload_dir = upload_dir # type: ignore[attr-defined] server.allowed_targets = allowed_targets # type: ignore[attr-defined] return server def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--host", default=os.environ.get("HOST", "127.0.0.1")) parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "8000"))) parser.add_argument( "--upload-dir", type=Path, default=Path(os.environ.get("UPLOAD_DIR", Path(__file__).resolve().parent / "data" / "uploads")), ) parser.add_argument( "--config-file", type=Path, default=Path(os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE)), help="TOML file containing global SMTP settings and upload URI stanzas", ) args = parser.parse_args() config_file = args.config_file.resolve() try: config = load_config(config_file) except (OSError, ValueError) as error: parser.error(str(error)) allowed_targets = frozenset(config.recipients) server = make_server(args.host, args.port, args.upload_dir.resolve(), allowed_targets) print(f"Blind Uploader listening on http://{args.host}:{args.port}") print(f"Private uploads are stored in {server.upload_dir}") # type: ignore[attr-defined] print(f"Upload configuration was loaded from {config_file}") try: server.serve_forever() except KeyboardInterrupt: pass finally: server.server_close() if __name__ == "__main__": main()