aboutsummaryrefslogtreecommitdiff
path: root/server.py
diff options
context:
space:
mode:
Diffstat (limited to 'server.py')
-rw-r--r--server.py121
1 files changed, 101 insertions, 20 deletions
diff --git a/server.py b/server.py
index b6b2e20..b28db69 100644
--- a/server.py
+++ b/server.py
@@ -9,8 +9,11 @@ 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
@@ -24,7 +27,7 @@ MAX_NAME_LENGTH = 200
MAX_EMAIL_LENGTH = 254
MAX_DESCRIPTION_LENGTH = 1000
STATIC_DIR = Path(__file__).resolve().parent / "static"
-DEFAULT_TARGETS_FILE = Path(__file__).resolve().parent / "allowed-uris.txt"
+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"),
@@ -33,6 +36,23 @@ 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))
@@ -41,20 +61,80 @@ def target_from_path(path: str) -> str | None:
return match.group(1)
-def load_allowed_targets(path: Path) -> frozenset[str]:
- """Load canonical, single-segment upload targets from a text file."""
- targets: set[str] = set()
- for line_number, raw_line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
- entry = raw_line.strip()
- if not entry or entry.startswith("#"):
+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(entry)
- if target is None or entry != f"/{target}":
- raise ValueError(f"Invalid upload URI on line {line_number} of {path}: {entry!r}")
- targets.add(target)
- if not targets:
- raise ValueError(f"No upload URIs are configured in {path}")
- return frozenset(targets)
+ 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:
@@ -320,21 +400,22 @@ def main() -> None:
default=Path(os.environ.get("UPLOAD_DIR", Path(__file__).resolve().parent / "data" / "uploads")),
)
parser.add_argument(
- "--targets-file",
+ "--config-file",
type=Path,
- default=Path(os.environ.get("TARGETS_FILE", DEFAULT_TARGETS_FILE)),
- help="text file containing one allowed upload URI per line",
+ 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()
- targets_file = args.targets_file.resolve()
+ config_file = args.config_file.resolve()
try:
- allowed_targets = load_allowed_targets(targets_file)
+ 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"Allowed upload URIs were loaded from {targets_file}")
+ print(f"Upload configuration was loaded from {config_file}")
try:
server.serve_forever()
except KeyboardInterrupt: