From 7edb33c87cb1d3ad3421a6fb33247dc871828d7a Mon Sep 17 00:00:00 2001 From: Jason McCormick Date: Fri, 16 Oct 2026 17:04:19 -0400 Subject: first run --- Makefile | 3 +++ README.md | 6 ++++-- allowed-uris.txt | 2 ++ deploy/blind-uploader.service | 1 + server.py | 45 +++++++++++++++++++++++++++++++++++++++---- tests/test_server.py | 21 ++++++++++++++++++-- 6 files changed, 70 insertions(+), 8 deletions(-) create mode 100644 allowed-uris.txt diff --git a/Makefile b/Makefile index 42cdea6..411a519 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,7 @@ SHELL := /bin/sh APP_DIR := /opt/blind-uploader SYSTEMD_UNIT := /etc/systemd/system/blind-uploader.service NGINX_CONFIG := /etc/nginx/conf.d/blind-uploader.conf +TARGETS_FILE := /etc/blind-uploader/allowed-uris DOMAIN ?= upload.example.com .PHONY: help check prerequisites install @@ -26,6 +27,8 @@ install: prerequisites install -m 0755 server.py $(APP_DIR)/server.py install -m 0644 README.md $(APP_DIR)/README.md install -m 0644 static/index.html static/styles.css static/app.js $(APP_DIR)/static/ + install -d -m 0755 $$(dirname $(TARGETS_FILE)) + @test -e $(TARGETS_FILE) || install -m 0644 allowed-uris.txt $(TARGETS_FILE) install -m 0644 deploy/blind-uploader.service $(SYSTEMD_UNIT) install -d -m 0755 $$(dirname $(NGINX_CONFIG)) sed 's/upload\.example\.com/$(DOMAIN)/g' deploy/nginx-blind-uploader.conf > $(NGINX_CONFIG) diff --git a/README.md b/README.md index 473b078..8df418c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A small, dependency-free web application for anonymous single-image submissions. 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. -Upload forms are available only at named, single-segment targets 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. +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. ## Run locally @@ -12,6 +12,8 @@ python3 server.py Open a target such as . 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. + For production, choose a private directory on a persistent disk and bind to the needed interface: ```bash @@ -44,7 +46,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`, and standard Unix installation tools to already be installed. The generated nginx configuration is `/etc/nginx/conf.d/blind-uploader.conf`. +This validates the nginx configuration before starting the service and reloading nginx. It requires Python 3, systemd, nginx, `make`, and standard Unix installation tools to already be installed. The generated nginx configuration is `/etc/nginx/conf.d/blind-uploader.conf`. The URI allowlist is installed at `/etc/blind-uploader/allowed-uris`; subsequent installs preserve that file so local URI changes are not overwritten. To run the test suite without installing anything: diff --git a/allowed-uris.txt b/allowed-uris.txt new file mode 100644 index 0000000..4c7ecb0 --- /dev/null +++ b/allowed-uris.txt @@ -0,0 +1,2 @@ +# One upload URI per line. Blank lines and comments are ignored. +/logo-contest diff --git a/deploy/blind-uploader.service b/deploy/blind-uploader.service index aa5bc5d..1258131 100644 --- a/deploy/blind-uploader.service +++ b/deploy/blind-uploader.service @@ -15,6 +15,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=PYTHONDONTWRITEBYTECODE=1 EnvironmentFile=-/etc/default/blind-uploader diff --git a/server.py b/server.py index 91e657b..34169f9 100644 --- a/server.py +++ b/server.py @@ -20,6 +20,7 @@ from urllib.parse import unquote, urlsplit MAX_FILE_BYTES = 10 * 1024 * 1024 MAX_REQUEST_BYTES = MAX_FILE_BYTES + 1024 * 1024 STATIC_DIR = Path(__file__).resolve().parent / "static" +DEFAULT_TARGETS_FILE = Path(__file__).resolve().parent / "allowed-uris.txt" STATIC_FILES = { "/styles.css": ("styles.css", "text/css; charset=utf-8"), "/app.js": ("app.js", "text/javascript; charset=utf-8"), @@ -36,6 +37,22 @@ 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("#"): + 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) + + 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"): @@ -89,6 +106,10 @@ class UploadHandler(BaseHTTPRequestHandler): 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": @@ -103,7 +124,8 @@ class UploadHandler(BaseHTTPRequestHandler): if path == "/": self.send_error_response(HTTPStatus.IM_A_TEAPOT, "A valid upload target is required.") return - if target_from_path(path) is None: + 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") @@ -124,7 +146,7 @@ class UploadHandler(BaseHTTPRequestHandler): self.send_error_response(HTTPStatus.IM_A_TEAPOT, "A valid upload target is required.") return target = target_from_path(path) - if target is None: + 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 @@ -202,7 +224,9 @@ class UploadHandler(BaseHTTPRequestHandler): sys.stderr.write("%s - %s\n" % (self.address_string(), format % args)) -def make_server(host: str, port: int, upload_dir: Path) -> ThreadingHTTPServer: +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) @@ -210,6 +234,7 @@ def make_server(host: str, port: int, upload_dir: Path) -> ThreadingHTTPServer: 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 @@ -222,10 +247,22 @@ def main() -> None: type=Path, default=Path(os.environ.get("UPLOAD_DIR", Path(__file__).resolve().parent / "data" / "uploads")), ) + parser.add_argument( + "--targets-file", + type=Path, + default=Path(os.environ.get("TARGETS_FILE", DEFAULT_TARGETS_FILE)), + help="text file containing one allowed upload URI per line", + ) args = parser.parse_args() - server = make_server(args.host, args.port, args.upload_dir.resolve()) + targets_file = args.targets_file.resolve() + try: + allowed_targets = load_allowed_targets(targets_file) + except (OSError, ValueError) as error: + parser.error(str(error)) + 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}") try: server.serve_forever() except KeyboardInterrupt: diff --git a/tests/test_server.py b/tests/test_server.py index aaff61e..78b9bf8 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -4,7 +4,7 @@ import threading import unittest from pathlib import Path -from server import MAX_FILE_BYTES, detect_image_type, make_server +from server import MAX_FILE_BYTES, detect_image_type, load_allowed_targets, make_server PNG = b"\x89PNG\r\n\x1a\n" + b"test-image" @@ -23,7 +23,9 @@ class ServerTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.upload_dir = Path(self.temp.name) / "private" - self.server = make_server("127.0.0.1", 0, self.upload_dir) + self.server = make_server( + "127.0.0.1", 0, self.upload_dir, frozenset({"logo-contest", "911u19jasdl"}) + ) self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) self.thread.start() self.port = self.server.server_address[1] @@ -90,6 +92,21 @@ class ServerTests(unittest.TestCase): ) self.assertEqual(response.status, 404) + def test_unlisted_valid_target_is_rejected(self): + 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_rejects_invalid_allowlist_entry(self): + targets_file = Path(self.temp.name) / "targets.txt" + targets_file.write_text("/nested/target\n", encoding="utf-8") + with self.assertRaises(ValueError): + load_allowed_targets(targets_file) + def test_rejects_non_image_content(self): body, content_type = multipart("fake.jpg", b"not really an image") response, _ = self.request( -- cgit v1.2.3