aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJason McCormick <jason@mfamily.org>2026-11-05 18:20:34 -0500
committerJason McCormick <jason@mfamily.org>2026-11-05 18:20:34 -0500
commit75719aa37f7317f3a8feeb516f1444edb4274410 (patch)
tree36e7e0454ad0044ebc72a253935790afc389843c
parent67383e6863fcff8b49e680b5b861b3154f8cb518 (diff)
feat: TOML config and upload notification watcher
Replace allowed-uris.txt with config.toml: [GLOBAL] holds SMTP settings (send_as, smtp_server, smtp_port, tls, starttls) and every other stanza is an upload URI with a recipient and optional view_url_prefix. Add watcher.py, run every 5 minutes by a systemd timer, which emails each drop's recipient once per run when new images appeared in the last slot. The email links each image under view_url_prefix and includes its .txt submission details. Fix the service unit and Makefile to use CONFIG_FILE, install the watcher and its units, and validate the config before restarting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--Makefile22
-rw-r--r--README.md41
-rw-r--r--allowed-uris.txt2
-rw-r--r--config.toml12
-rw-r--r--deploy/blind-uploader-watcher.service39
-rw-r--r--deploy/blind-uploader-watcher.timer12
-rw-r--r--deploy/blind-uploader.service2
-rw-r--r--server.py121
-rw-r--r--tests/test_server.py216
-rw-r--r--watcher.py136
10 files changed, 562 insertions, 41 deletions
diff --git a/Makefile b/Makefile
index 436587b..dd8db60 100644
--- a/Makefile
+++ b/Makefile
@@ -2,7 +2,10 @@ SHELL := /bin/sh
APP_DIR := /opt/blind-uploader
SYSTEMD_UNIT := /etc/systemd/system/blind-uploader.service
-TARGETS_FILE := /etc/blind-uploader/allowed-uris
+WATCHER_UNIT := /etc/systemd/system/blind-uploader-watcher.service
+WATCHER_TIMER := /etc/systemd/system/blind-uploader-watcher.timer
+CONFIG_FILE := /etc/blind-uploader/config.toml
+LEGACY_TARGETS_FILE := /etc/blind-uploader/allowed-uris
UPLOAD_STATE_DIR := /var/lib/blind-uploader/uploads
DOMAIN ?= upload.example.com
NGINX_CONFIG := /etc/nginx/sites-available/$(DOMAIN)
@@ -27,14 +30,21 @@ prerequisites:
install: prerequisites
install -d -o root -g root -m 0755 $(APP_DIR) $(APP_DIR)/static
install -o root -g root -m 0755 server.py $(APP_DIR)/server.py
+ install -o root -g root -m 0755 watcher.py $(APP_DIR)/watcher.py
install -o root -g root -m 0644 README.md $(APP_DIR)/README.md
install -o root -g root -m 0644 static/index.html static/styles.css static/app.js $(APP_DIR)/static/
- install -d -o root -g www-data -m 0750 $$(dirname $(TARGETS_FILE))
- @test -e $(TARGETS_FILE) || install -o root -g www-data -m 0640 allowed-uris.txt $(TARGETS_FILE)
- chown root:www-data $(TARGETS_FILE)
- chmod 0640 $(TARGETS_FILE)
+ install -d -o root -g www-data -m 0750 $$(dirname $(CONFIG_FILE))
+ @test -e $(CONFIG_FILE) || install -o root -g www-data -m 0640 config.toml $(CONFIG_FILE)
+ chown root:www-data $(CONFIG_FILE)
+ chmod 0640 $(CONFIG_FILE)
+ @if test -e $(LEGACY_TARGETS_FILE); then \
+ echo "WARNING: $(LEGACY_TARGETS_FILE) is no longer used; move its URIs into $(CONFIG_FILE) as stanzas." >&2; \
+ fi
+ python3 -B -c 'import sys; sys.path.insert(0, "$(APP_DIR)"); from server import load_config; from pathlib import Path; load_config(Path("$(CONFIG_FILE)"))'
install -d -o www-data -g www-data -m 0700 /var/lib/blind-uploader $(UPLOAD_STATE_DIR)
install -o root -g root -m 0644 deploy/blind-uploader.service $(SYSTEMD_UNIT)
+ install -o root -g root -m 0644 deploy/blind-uploader-watcher.service $(WATCHER_UNIT)
+ install -o root -g root -m 0644 deploy/blind-uploader-watcher.timer $(WATCHER_TIMER)
@if test ! -e $(NGINX_CONFIG); then \
sed 's/upload\.example\.com/$(DOMAIN)/g' deploy/nginx-blind-uploader.conf > $(NGINX_CONFIG); \
chown root:root $(NGINX_CONFIG); \
@@ -44,6 +54,8 @@ install: prerequisites
systemctl daemon-reload
systemctl enable blind-uploader.service
systemctl restart blind-uploader.service
+ systemctl enable --now blind-uploader-watcher.timer
systemctl reload nginx
@echo "Private Drop installed for http://$(DOMAIN)"
@echo "Uploads will be stored privately under /var/lib/blind-uploader/uploads"
+ @echo "Edit $(CONFIG_FILE) for SMTP settings and upload URIs, then: systemctl restart blind-uploader.service"
diff --git a/README.md b/README.md
index 47bdfc7..9945aae 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
A small, dependency-free web application for private single-image submissions. It collects the submitter's amateur radio callsign, name, email address, and a brief file description. It accepts JPG, PNG, and HEIC files up to 10 MiB, verifies the file signature, replaces the original filename, and stores the image outside the HTTP-served directory. The submission details are stored in a UTF-8 `.txt` sidecar with the same private basename as the image.
-Upload forms are available only at named, single-segment targets listed in `allowed-uris.txt`, such as `/logo-contest` or `/911u19jasdl`. Blank lines and lines beginning with `#` are ignored. The bare `/` path is rejected with HTTP 418. Each target stores its submissions in a separate private directory beneath the configured upload directory.
+Upload forms are available only at named, single-segment targets configured in `config.toml`, such as `/logo-contest` or `/911u19jasdl`. The bare `/` path is rejected with HTTP 418. Each target stores its submissions in a separate private directory beneath the configured upload directory.
## Run locally
@@ -12,7 +12,40 @@ python3 server.py
Open a target such as <http://127.0.0.1:8000/logo-contest>. By default, its uploads are written to `data/uploads/logo-contest/`, while the server only exposes allow-listed frontend assets. Uploaded files therefore have no HTTP route.
-For local use, edit `allowed-uris.txt` and restart the server after making changes. URI entries must contain exactly one segment composed of letters, numbers, underscores, or hyphens, with a maximum length of 64 characters.
+## Configuration
+
+`config.toml` holds one `[GLOBAL]` stanza for outgoing mail. Every other stanza is an upload URI, and its `recipient` is the address that gets notified about new uploads there:
+
+```toml
+[GLOBAL]
+send_as = "uploads@example.com" # From address
+smtp_server = "smtp.example.com"
+smtp_port = 587
+tls = false # implicit TLS (typically port 465)
+starttls = true # STARTTLS upgrade (typically port 587)
+
+[logo-contest]
+recipient = "reviewer@example.com"
+view_url_prefix = "https://review.example.com/logo-contest/" # optional
+
+["911u19jasdl"] # quote names that TOML would not accept bare
+recipient = "other@example.com"
+```
+
+Stanza names must be a single segment made of letters, numbers, underscores, or hyphens, at most 64 characters long. `tls` and `starttls` cannot both be `true`. Restart the server after changing the URI stanzas. The watcher re-reads the file on every run.
+
+## Upload notifications
+
+`watcher.py` is run every 5 minutes by `blind-uploader-watcher.timer`, which fires at :00, :05, :10, and so on. It checks each configured drop for an image modified during the last 5-minute slot. If it finds one, it sends a single email to that drop's recipient. The email has no attachment. It includes the submission details (callsign, name, email, and description) from each new image's `.txt` sidecar. If the stanza sets `view_url_prefix`, the email links to each new image as `<view_url_prefix><stored filename>`, for example `https://review.example.com/logo-contest/3f9c…a1.png`. The prefix must be an absolute `http`/`https` URL, and a trailing `/` is added if missing. It should point at the separately protected nginx location that serves this drop's upload directory. Without a prefix, the email contains only the generic message. Nothing is stored between runs. If the system is down or the timer is stopped during a slot, uploads from that slot are never reported.
+
+If your SMTP server requires authentication, put the credentials in `/etc/default/blind-uploader-watcher` and make the file `root:root` mode `0600`:
+
+```ini
+SMTP_USERNAME=uploads@example.com
+SMTP_PASSWORD=...
+```
+
+To check that it works, run `sudo systemctl start blind-uploader-watcher.service` and `journalctl -u blind-uploader-watcher.service`.
For production, choose a private directory on a persistent disk and bind to the needed interface:
@@ -46,7 +79,7 @@ To install the application, systemd unit, and nginx configuration in one step, r
sudo make install DOMAIN=upload.example.com
```
-This validates the nginx configuration before starting the service and reloading nginx. It requires Python 3, systemd, nginx, `make`, Debian's `www-data` account, and standard Unix installation tools to already be installed. For `DOMAIN=upload.example.com`, the generated nginx configuration is `/etc/nginx/sites-available/upload.example.com`. Subsequent installs preserve both that nginx configuration and the URI allowlist at `/etc/blind-uploader/allowed-uris`, so local changes are not overwritten.
+This validates the nginx configuration before starting the service and reloading nginx. It requires Python 3, systemd, nginx, `make`, Debian's `www-data` account, and standard Unix installation tools to already be installed. For `DOMAIN=upload.example.com`, the generated nginx configuration is `/etc/nginx/sites-available/upload.example.com`. Subsequent installs preserve both that nginx configuration and `/etc/blind-uploader/config.toml`, so local changes are not overwritten. The installer validates the config, installs both units, and enables the notification timer. An existing `/etc/blind-uploader/allowed-uris` from an earlier install is no longer read, and the installer prints a warning if it finds one.
Re-running the installer restarts the service so updated server code takes effect.
To run the test suite without installing anything:
@@ -64,7 +97,7 @@ sudo systemctl enable --now blind-uploader.service
sudo systemctl status blind-uploader.service
```
-The unit runs as Debian's existing `www-data:www-data` account and uses systemd's `StateDirectory` feature for private writable storage. Application files remain root-owned and read-only to the daemon. The URI allowlist is root-owned, group-readable by `www-data`, and otherwise private. Optional overrides can be placed in Debian's standard `/etc/default/blind-uploader` environment file, for example:
+The unit runs as Debian's existing `www-data:www-data` account and uses systemd's `StateDirectory` feature for private writable storage. Application files remain root-owned and read-only to the daemon. The configuration file is root-owned, group-readable by `www-data`, and otherwise private. Optional overrides can be placed in Debian's standard `/etc/default/blind-uploader` environment file, for example:
```ini
PORT=8080
diff --git a/allowed-uris.txt b/allowed-uris.txt
deleted file mode 100644
index 4c7ecb0..0000000
--- a/allowed-uris.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-# One upload URI per line. Blank lines and comments are ignored.
-/logo-contest
diff --git a/config.toml b/config.toml
new file mode 100644
index 0000000..c373438
--- /dev/null
+++ b/config.toml
@@ -0,0 +1,12 @@
+[GLOBAL]
+send_as = "uploads@example.com"
+smtp_server = "localhost"
+smtp_port = 587
+tls = false
+starttls = true
+
+[logo-contest]
+recipient = "reviewer@example.com"
+# Optional: where nginx serves this drop's files for viewing. Each notification
+# links to <view_url_prefix><stored filename>.
+view_url_prefix = "https://review.example.com/logo-contest/"
diff --git a/deploy/blind-uploader-watcher.service b/deploy/blind-uploader-watcher.service
new file mode 100644
index 0000000..7d08e31
--- /dev/null
+++ b/deploy/blind-uploader-watcher.service
@@ -0,0 +1,39 @@
+[Unit]
+Description=Private Drop upload notifier
+Documentation=file:/opt/blind-uploader/README.md
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=oneshot
+User=www-data
+Group=www-data
+WorkingDirectory=/opt/blind-uploader
+ExecStart=/usr/bin/python3 /opt/blind-uploader/watcher.py
+
+Environment=UPLOAD_DIR=/var/lib/blind-uploader/uploads
+Environment=CONFIG_FILE=/etc/blind-uploader/config.toml
+Environment=PYTHONDONTWRITEBYTECODE=1
+EnvironmentFile=-/etc/default/blind-uploader
+# Optional SMTP_USERNAME / SMTP_PASSWORD (keep this file root:root 0600).
+EnvironmentFile=-/etc/default/blind-uploader-watcher
+
+# The notifier only reads uploads and opens outbound SMTP connections.
+UMask=0077
+NoNewPrivileges=yes
+PrivateTmp=yes
+PrivateDevices=yes
+ProtectSystem=strict
+ProtectHome=yes
+ReadOnlyPaths=/var/lib/blind-uploader
+ProtectClock=yes
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectKernelLogs=yes
+ProtectControlGroups=yes
+RestrictSUIDSGID=yes
+RestrictRealtime=yes
+LockPersonality=yes
+CapabilityBoundingSet=
+AmbientCapabilities=
+RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
diff --git a/deploy/blind-uploader-watcher.timer b/deploy/blind-uploader-watcher.timer
new file mode 100644
index 0000000..d076334
--- /dev/null
+++ b/deploy/blind-uploader-watcher.timer
@@ -0,0 +1,12 @@
+[Unit]
+Description=Run the Private Drop upload notifier every 5 minutes
+
+[Timer]
+# Fixed wall-clock slots keep consecutive 5-minute scan windows aligned, so an
+# upload is reported once. Keep this in sync with SCAN_INTERVAL_SECONDS.
+OnCalendar=*:0/5
+AccuracySec=1s
+Persistent=false
+
+[Install]
+WantedBy=timers.target
diff --git a/deploy/blind-uploader.service b/deploy/blind-uploader.service
index 8bbba05..5c03feb 100644
--- a/deploy/blind-uploader.service
+++ b/deploy/blind-uploader.service
@@ -16,7 +16,7 @@ RestartSec=3s
Environment=HOST=127.0.0.1
Environment=PORT=8000
Environment=UPLOAD_DIR=/var/lib/blind-uploader/uploads
-Environment=TARGETS_FILE=/etc/blind-uploader/allowed-uris
+Environment=CONFIG_FILE=/etc/blind-uploader/config.toml
Environment=PYTHONDONTWRITEBYTECODE=1
EnvironmentFile=-/etc/default/blind-uploader
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:
diff --git a/tests/test_server.py b/tests/test_server.py
index ca6d748..4644ecc 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -1,10 +1,13 @@
import http.client
+import os
import tempfile
import threading
import unittest
+from unittest.mock import MagicMock, patch
from pathlib import Path
-from server import MAX_FILE_BYTES, detect_image_type, load_allowed_targets, make_server
+from server import MAX_FILE_BYTES, detect_image_type, load_config, make_server
+from watcher import send_recent_upload_notifications
PNG = b"\x89PNG\r\n\x1a\n" + b"test-image"
@@ -127,16 +130,211 @@ class ServerTests(unittest.TestCase):
response, _ = self.request("GET", "/invented-target")
self.assertEqual(response.status, 404)
- def test_loads_target_allowlist(self):
- targets_file = Path(self.temp.name) / "targets.txt"
- targets_file.write_text("# campaigns\n/logo-contest\n\n/911u19jasdl\n", encoding="utf-8")
- self.assertEqual(load_allowed_targets(targets_file), {"logo-contest", "911u19jasdl"})
+ def test_loads_toml_configuration(self):
+ config_file = Path(self.temp.name) / "config.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 587\ntls = false\nstarttls = true\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n\n'
+ '["911u19jasdl"]\nrecipient = "second@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ self.assertEqual(config.recipients, {
+ "logo-contest": "reviewer@example.com",
+ "911u19jasdl": "second@example.com",
+ })
+ self.assertEqual(config.smtp.send_as, "uploads@example.com")
+ self.assertEqual(config.smtp.server, "localhost")
+ self.assertEqual(config.smtp.port, 587)
+ self.assertFalse(config.smtp.tls)
+ self.assertTrue(config.smtp.starttls)
+
+ def test_rejects_invalid_uri_stanza(self):
+ config_file = Path(self.temp.name) / "config.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 587\ntls = false\nstarttls = true\n\n"
+ '["nested/target"]\nrecipient = "reviewer@example.com"\n',
+ encoding="utf-8",
+ )
+ with self.assertRaises(ValueError):
+ load_config(config_file)
+
+ def test_rejects_conflicting_smtp_tls_modes(self):
+ config_file = Path(self.temp.name) / "config.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 587\ntls = true\nstarttls = true\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n',
+ encoding="utf-8",
+ )
+ with self.assertRaises(ValueError):
+ load_config(config_file)
+
+ def test_watcher_sends_one_generic_email_for_recent_images_only(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 587\ntls = false\nstarttls = true\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ target_dir = self.upload_dir / "logo-contest"
+ target_dir.mkdir(parents=True)
+ # Two recent images in the same drop must yield a single email.
+ for name in ("recent.png", "recent2.heic"):
+ (target_dir / name).write_bytes(PNG)
+ os.utime(target_dir / name, (1980, 1980))
+ old_image = target_dir / "old.jpg"
+ old_image.write_bytes(b"old")
+ os.utime(old_image, (1600, 1600))
+ sidecar = target_dir / "recent.txt"
+ sidecar.write_text("metadata", encoding="utf-8")
+ os.utime(sidecar, (1980, 1980))
+ smtp_context = MagicMock()
+ with patch("watcher.smtplib.SMTP", return_value=smtp_context) as smtp_factory:
+ sent = send_recent_upload_notifications(config, self.upload_dir, now=2000)
+
+ self.assertEqual(sent, 1)
+ smtp_factory.assert_called_once_with("localhost", 587, timeout=30)
+ self.assertEqual(smtp_context.__enter__.return_value.ehlo.call_count, 2)
+ smtp_context.__enter__.return_value.starttls.assert_called_once_with()
+ smtp_context.__enter__.return_value.send_message.assert_called_once()
+ message = smtp_context.__enter__.return_value.send_message.call_args.args[0]
+ self.assertEqual(message["To"], "reviewer@example.com")
+ self.assertEqual(message["Subject"], "New upload received")
+ body = message.get_content()
+ self.assertTrue(body.startswith("A new file has been uploaded to your private drop."))
+ self.assertIn("File: recent.png\n\nmetadata", body)
+ self.assertIn("File: recent2.heic\n\n(Submission details are not available.)", body)
+ self.assertNotIn("old.jpg", body)
+ self.assertFalse(message.is_multipart())
+ self.assertIsNotNone(message["Date"])
+ self.assertIsNotNone(message["Message-ID"])
+
+ def test_watcher_emails_each_drop_recipient_and_skips_quiet_drops(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ '[alpha]\nrecipient = "a@example.com"\n\n'
+ '[beta]\nrecipient = "b@example.com"\n\n'
+ '[gamma]\nrecipient = "c@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ for target, mtime in (("alpha", 1990), ("beta", 1700), ("gamma", 2000)):
+ directory = self.upload_dir / target
+ directory.mkdir(parents=True)
+ (directory / "x.png").write_bytes(PNG)
+ os.utime(directory / "x.png", (mtime, mtime))
+ # beta's file sits exactly on the previous window's end, so it belongs to that run.
+ smtp_context = MagicMock()
+ with patch("watcher.smtplib.SMTP", return_value=smtp_context):
+ sent = send_recent_upload_notifications(config, self.upload_dir, now=2000)
+
+ connection = smtp_context.__enter__.return_value
+ recipients = [call.args[0]["To"] for call in connection.send_message.call_args_list]
+ self.assertEqual(sent, 2)
+ self.assertEqual(recipients, ["a@example.com", "c@example.com"])
+ connection.starttls.assert_not_called()
+
+ def test_watcher_links_new_files_under_view_url_prefix(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n'
+ 'view_url_prefix = "https://review.example.com/logo-contest"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ self.assertEqual(config.view_url_prefixes, {"logo-contest": "https://review.example.com/logo-contest/"})
+ target_dir = self.upload_dir / "logo-contest"
+ target_dir.mkdir(parents=True)
+ for name in ("bbb.png", "aaa.jpg"):
+ (target_dir / name).write_bytes(PNG)
+ os.utime(target_dir / name, (1990, 1990))
+ (target_dir / "aaa.txt").write_bytes(
+ b"Callsign: W8WKY\nName: Pat\x1b[2J\nEmail: pat@example.com\nDescription:\nLine one\nLine two\n"
+ )
+ smtp_context = MagicMock()
+ with patch("watcher.smtplib.SMTP", return_value=smtp_context):
+ send_recent_upload_notifications(config, self.upload_dir, now=2000)
+
+ body = smtp_context.__enter__.return_value.send_message.call_args.args[0].get_content()
+ self.assertIn(
+ "https://review.example.com/logo-contest/aaa.jpg\n\n"
+ "Callsign: W8WKY\nName: Pat[2J\nEmail: pat@example.com\nDescription:\nLine one\nLine two",
+ body,
+ )
+ self.assertIn("https://review.example.com/logo-contest/bbb.png\n\n(Submission details are not available.)", body)
+ self.assertLess(body.index("aaa.jpg"), body.index("bbb.png"))
+ self.assertNotIn("aaa.txt", body)
+ self.assertNotIn("\x1b", body)
+
+ def test_rejects_invalid_view_url_prefix(self):
+ config_file = Path(self.temp.name) / "config.toml"
+ for prefix in ("/relative/path", "ftp://x.example.com/", "https://x.example.com/?a=1"):
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ f'[logo-contest]\nrecipient = "reviewer@example.com"\nview_url_prefix = "{prefix}"\n',
+ encoding="utf-8",
+ )
+ with self.subTest(prefix=prefix), self.assertRaises(ValueError):
+ load_config(config_file)
- def test_rejects_invalid_allowlist_entry(self):
- targets_file = Path(self.temp.name) / "targets.txt"
- targets_file.write_text("/nested/target\n", encoding="utf-8")
+ def test_watcher_skips_smtp_when_nothing_is_new(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ with patch("watcher.smtplib.SMTP") as smtp_factory:
+ sent = send_recent_upload_notifications(config, self.upload_dir, now=2000)
+ self.assertEqual(sent, 0)
+ smtp_factory.assert_not_called()
+
+ def test_watcher_uses_implicit_tls_and_optional_credentials(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 465\ntls = true\nstarttls = false\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
+ target_dir = self.upload_dir / "logo-contest"
+ target_dir.mkdir(parents=True)
+ (target_dir / "recent.png").write_bytes(PNG)
+ smtp_context = MagicMock()
+ with patch("watcher.smtplib.SMTP_SSL", return_value=smtp_context) as smtp_factory:
+ sent = send_recent_upload_notifications(
+ config, self.upload_dir, now=None, smtp_username="user", smtp_password="secret"
+ )
+
+ self.assertEqual(sent, 1)
+ smtp_factory.assert_called_once_with("localhost", 465, timeout=30)
+ smtp_context.__enter__.return_value.login.assert_called_once_with("user", "secret")
+ smtp_context.__enter__.return_value.starttls.assert_not_called()
+
+ def test_watcher_requires_both_credentials(self):
+ config_file = Path(self.temp.name) / "watcher.toml"
+ config_file.write_text(
+ '[GLOBAL]\nsend_as = "uploads@example.com"\nsmtp_server = "localhost"\n'
+ "smtp_port = 25\ntls = false\nstarttls = false\n\n"
+ '[logo-contest]\nrecipient = "reviewer@example.com"\n',
+ encoding="utf-8",
+ )
+ config = load_config(config_file)
with self.assertRaises(ValueError):
- load_allowed_targets(targets_file)
+ send_recent_upload_notifications(config, self.upload_dir, now=2000, smtp_username="user")
def test_rejects_non_image_content(self):
body, content_type = multipart("fake.jpg", b"not really an image")
diff --git a/watcher.py b/watcher.py
new file mode 100644
index 0000000..9799bae
--- /dev/null
+++ b/watcher.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""Email a generic notification for each drop that received an upload recently.
+
+Intended to be run by a systemd timer every SCAN_INTERVAL_SECONDS. There is no
+state tracking: a drop is reported when it contains an image whose modification
+time falls within the last interval.
+"""
+
+from __future__ import annotations
+
+import os
+import smtplib
+import stat
+import time
+from email.message import EmailMessage
+from email.utils import formatdate, make_msgid
+from pathlib import Path
+from urllib.parse import quote
+
+from server import DEFAULT_CONFIG_FILE, AppConfig, load_config
+
+
+SCAN_INTERVAL_SECONDS = 5 * 60
+IMAGE_SUFFIXES = {".jpg", ".png", ".heic"}
+SUBJECT = "New upload received"
+BODY = "A new file has been uploaded to your private drop."
+SEPARATOR = "-" * 40
+MAX_SIDECAR_BYTES = 16 * 1024
+
+
+def recent_uploads(config: AppConfig, upload_dir: Path, now: float) -> dict[str, list[str]]:
+ """Map each configured target to its image filenames modified in (now - interval, now]."""
+ window_start = now - SCAN_INTERVAL_SECONDS
+ recent: dict[str, list[str]] = {}
+ for target in config.recipients:
+ target_dir = upload_dir / target
+ if not target_dir.is_dir():
+ continue
+ names: list[str] = []
+ for candidate in target_dir.iterdir():
+ if candidate.suffix.lower() not in IMAGE_SUFFIXES:
+ continue
+ try:
+ file_stat = candidate.stat(follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ if stat.S_ISREG(file_stat.st_mode) and window_start < file_stat.st_mtime <= now:
+ names.append(candidate.name)
+ if names:
+ recent[target] = sorted(names)
+ return recent
+
+
+def read_sidecar(image_path: Path) -> str:
+ """Return an image's submission details, or a placeholder if they cannot be read."""
+ sidecar = image_path.with_suffix(".txt")
+ try:
+ if sidecar.is_symlink() or not sidecar.is_file():
+ return "(Submission details are not available.)"
+ with sidecar.open("rb") as handle:
+ raw = handle.read(MAX_SIDECAR_BYTES)
+ except OSError:
+ return "(Submission details could not be read.)"
+ text = raw.decode("utf-8", errors="replace")
+ # Submitter-supplied text: keep newlines and tabs, drop other control characters.
+ text = "".join(c for c in text if c in "\n\t" or (ord(c) >= 32 and ord(c) != 127))
+ return text.strip() or "(Submission details are empty.)"
+
+
+def build_message(config: AppConfig, target: str, target_dir: Path, filenames: list[str]) -> EmailMessage:
+ message = EmailMessage()
+ message["From"] = config.smtp.send_as
+ message["To"] = config.recipients[target]
+ message["Subject"] = SUBJECT
+ message["Date"] = formatdate(localtime=True)
+ message["Message-ID"] = make_msgid(domain=config.smtp.send_as.rsplit("@", 1)[1])
+ prefix = config.view_url_prefixes.get(target)
+ sections = [BODY]
+ for name in filenames:
+ # Stored names are server-generated hex plus an extension, so they are URL-safe.
+ heading = prefix + quote(name) if prefix else f"File: {name}"
+ sections.append(f"{SEPARATOR}\n{heading}\n\n{read_sidecar(target_dir / name)}")
+ message.set_content("\n\n".join(sections) + "\n")
+ return message
+
+
+def send_recent_upload_notifications(
+ config: AppConfig,
+ upload_dir: Path,
+ now: float | None = None,
+ smtp_username: str | None = None,
+ smtp_password: str | None = None,
+) -> int:
+ """Send one generic email per drop with recent uploads. Returns the number sent."""
+ if bool(smtp_username) != bool(smtp_password):
+ raise ValueError("SMTP_USERNAME and SMTP_PASSWORD must be set together")
+
+ uploads = recent_uploads(config, upload_dir, time.time() if now is None else now)
+ if not uploads:
+ return 0
+
+ connection_type = smtplib.SMTP_SSL if config.smtp.tls else smtplib.SMTP
+ with connection_type(config.smtp.server, config.smtp.port, timeout=30) as connection:
+ if config.smtp.starttls:
+ connection.ehlo()
+ connection.starttls()
+ connection.ehlo()
+ if smtp_username and smtp_password:
+ connection.login(smtp_username, smtp_password)
+ for target, filenames in uploads.items():
+ connection.send_message(build_message(config, target, upload_dir / target, filenames))
+ return len(uploads)
+
+
+def main() -> None:
+ config_path = Path(os.environ.get("CONFIG_FILE", DEFAULT_CONFIG_FILE))
+ upload_dir = Path(os.environ.get("UPLOAD_DIR", Path(__file__).resolve().parent / "data" / "uploads"))
+ # Snap to the timer's slot boundary so consecutive windows tile exactly,
+ # regardless of how long after the boundary this process actually started.
+ now = time.time() // SCAN_INTERVAL_SECONDS * SCAN_INTERVAL_SECONDS
+ try:
+ config = load_config(config_path)
+ sent = send_recent_upload_notifications(
+ config,
+ upload_dir,
+ now=now,
+ smtp_username=os.environ.get("SMTP_USERNAME") or None,
+ smtp_password=os.environ.get("SMTP_PASSWORD") or None,
+ )
+ except (OSError, ValueError, smtplib.SMTPException) as error:
+ raise SystemExit(f"Upload notification failed: {error}") from error
+ print(f"Sent {sent} upload notification(s)")
+
+
+if __name__ == "__main__":
+ main()