diff options
| author | Jason McCormick <jason@mfamily.org> | 2026-10-16 16:57:47 -0400 |
|---|---|---|
| committer | Jason McCormick <jason@mfamily.org> | 2026-10-16 16:57:47 -0400 |
| commit | 98119d8fb55e1633d7bdd79db30fd5caea9ee641 (patch) | |
| tree | 370d5aefedfc3eba4d69a6682f7d6139701a2539 | |
| -rw-r--r-- | .gitignore | 41 | ||||
| -rw-r--r-- | Makefile | 38 | ||||
| -rw-r--r-- | README.md | 78 | ||||
| -rw-r--r-- | deploy/blind-uploader.service | 45 | ||||
| -rw-r--r-- | deploy/nginx-blind-uploader.conf | 23 | ||||
| -rw-r--r-- | pyproject.toml | 8 | ||||
| -rw-r--r-- | server.py | 238 | ||||
| -rw-r--r-- | static/app.js | 108 | ||||
| -rw-r--r-- | static/index.html | 70 | ||||
| -rw-r--r-- | static/styles.css | 120 | ||||
| -rw-r--r-- | tests/test_server.py | 118 |
11 files changed, 887 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..37595a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Private runtime data +data/ + +# Python bytecode and caches +__pycache__/ +*.py[cod] +.Python +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.coverage +.coverage.* +htmlcov/ + +# Virtual environments +.venv/ +venv/ +env/ + +# Packaging and build output +build/ +dist/ +*.egg-info/ + +# Local configuration and secrets +.env +.env.* +!.env.example + +# Logs and process files +*.log +*.pid + +# Editors and operating systems +.idea/ +.vscode/ +*.swp +*.swo +*~ +.DS_Store +Thumbs.db diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..42cdea6 --- /dev/null +++ b/Makefile @@ -0,0 +1,38 @@ +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 +DOMAIN ?= upload.example.com + +.PHONY: help check prerequisites install + +help: + @echo "Targets:" + @echo " make check Run the automated tests" + @echo " sudo make install DOMAIN=... Install and start the application" + +check: + python3 -m unittest discover -s tests -v + +prerequisites: + @test "$$(id -u)" -eq 0 || { echo "Run installation as root: sudo make install DOMAIN=upload.example.com" >&2; exit 1; } + @for command in python3 install systemctl nginx sed; do \ + command -v "$$command" >/dev/null 2>&1 || { echo "Required command not found: $$command" >&2; exit 1; }; \ + done + +install: prerequisites + install -d -m 0755 $(APP_DIR) $(APP_DIR)/static + 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 -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) + chmod 0644 $(NGINX_CONFIG) + nginx -t + systemctl daemon-reload + systemctl enable --now blind-uploader.service + systemctl reload nginx + @echo "Private Drop installed for http://$(DOMAIN)" + @echo "Uploads will be stored privately under /var/lib/blind-uploader/uploads" diff --git a/README.md b/README.md new file mode 100644 index 0000000..473b078 --- /dev/null +++ b/README.md @@ -0,0 +1,78 @@ +# Private Drop + +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. + +## Run locally + +```bash +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 production, choose a private directory on a persistent disk and bind to the needed interface: + +```bash +UPLOAD_DIR=/var/lib/blind-uploader/uploads HOST=0.0.0.0 PORT=8000 python3 server.py +``` + +The service creates the upload directory with mode `0700` and each image with mode `0600`. The process user needs write access to `UPLOAD_DIR`. + +## Test + +```bash +python3 -m unittest discover -s tests -v +``` + +## Production notes + +- Put the service behind an HTTPS reverse proxy and set its request-body limit to at least 11 MiB. +- Do not configure the reverse proxy, CDN, or another static server to expose `UPLOAD_DIR`. +- Add rate limiting at the reverse proxy before exposing anonymous uploads to the public internet. +- Back up, retain, and delete submissions according to your review and privacy policy. +- Malware scanning and image re-encoding are recommended before a reviewer opens untrusted files. + +## systemd and nginx + +Example deployment files are provided in `deploy/`. They assume the application is installed at `/opt/blind-uploader`, nginx proxies to `127.0.0.1:8000`, and images are stored under `/var/lib/blind-uploader/uploads`. + +To install the application, systemd unit, and nginx configuration in one step, run: + +```bash +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`. + +To run the test suite without installing anything: + +```bash +make check +``` + +Install and start the service: + +```bash +sudo cp deploy/blind-uploader.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now blind-uploader.service +sudo systemctl status blind-uploader.service +``` + +The unit uses systemd's `DynamicUser` and `StateDirectory` features, so no permanent application user or manual data-directory setup is needed. Optional overrides can be placed in Debian's standard `/etc/default/blind-uploader` environment file, for example: + +```ini +PORT=8080 +UPLOAD_DIR=/var/lib/blind-uploader/uploads +``` + +Install the nginx configuration after replacing `upload.example.com` and adding the TLS configuration appropriate for your server: + +```bash +sudo cp deploy/nginx-blind-uploader.conf /etc/nginx/sites-available/blind-uploader +sudo ln -s /etc/nginx/sites-available/blind-uploader /etc/nginx/sites-enabled/blind-uploader +sudo nginx -t +sudo systemctl reload nginx +``` diff --git a/deploy/blind-uploader.service b/deploy/blind-uploader.service new file mode 100644 index 0000000..aa5bc5d --- /dev/null +++ b/deploy/blind-uploader.service @@ -0,0 +1,45 @@ +[Unit] +Description=Private Drop anonymous image uploader +Documentation=file:/opt/blind-uploader/README.md +After=network.target + +[Service] +Type=simple +DynamicUser=yes +WorkingDirectory=/opt/blind-uploader +ExecStart=/usr/bin/python3 /opt/blind-uploader/server.py +Restart=on-failure +RestartSec=3s + +# These defaults can be overridden using Debian's standard environment file. +Environment=HOST=127.0.0.1 +Environment=PORT=8000 +Environment=UPLOAD_DIR=/var/lib/blind-uploader/uploads +Environment=PYTHONDONTWRITEBYTECODE=1 +EnvironmentFile=-/etc/default/blind-uploader + +# systemd creates a persistent, service-owned /var/lib/blind-uploader directory. +StateDirectory=blind-uploader +StateDirectoryMode=0700 +UMask=0077 + +# Service hardening. The application only needs its state directory and TCP/IP. +NoNewPrivileges=yes +PrivateTmp=yes +PrivateDevices=yes +ProtectSystem=strict +ProtectHome=yes +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 + +[Install] +WantedBy=multi-user.target diff --git a/deploy/nginx-blind-uploader.conf b/deploy/nginx-blind-uploader.conf new file mode 100644 index 0000000..0473434 --- /dev/null +++ b/deploy/nginx-blind-uploader.conf @@ -0,0 +1,23 @@ +# Replace upload.example.com and add your TLS configuration before production use. +server { + listen 80; + listen [::]:80; + server_name upload.example.com; + + # Allows a 10 MiB image plus multipart form overhead. + client_max_body_size 11m; + + location / { + proxy_pass http://127.0.0.1:8000; + proxy_http_version 1.1; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_connect_timeout 5s; + proxy_send_timeout 60s; + proxy_read_timeout 60s; + } +} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b3ca2d0 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,8 @@ +[project] +name = "blind-uploader" +version = "0.1.0" +description = "A private, anonymous single-image upload service" +requires-python = ">=3.11" + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/server.py b/server.py new file mode 100644 index 0000000..91e657b --- /dev/null +++ b/server.py @@ -0,0 +1,238 @@ +#!/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 +from email.parser import BytesParser +from email.policy import default +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 +STATIC_DIR = Path(__file__).resolve().parent / "static" +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"} + + +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 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]: + """Parse one multipart field named image and reject ambiguous requests.""" + 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 = [] + for part in message.iter_parts(): + if part.get_content_disposition() != "form-data": + continue + filename = part.get_filename() + if filename is not None: + file_parts.append(part) + + if len(file_parts) != 1 or file_parts[0].get_param("name", header="content-disposition") != "image": + raise ValueError("Submit exactly one image.") + + 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 + + +class UploadHandler(BaseHTTPRequestHandler): + server_version = "BlindUploader/1.0" + + @property + def upload_dir(self) -> Path: + return self.server.upload_dir # 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 + if target_from_path(path) is None: + 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: + 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 = 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}" + descriptor = os.open(destination, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "wb") as output: + output.write(payload) + 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 image") + self.send_error_response(HTTPStatus.INTERNAL_SERVER_ERROR, "The image 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) -> 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] + 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")), + ) + args = parser.parse_args() + server = make_server(args.host, args.port, args.upload_dir.resolve()) + 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] + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + + +if __name__ == "__main__": + main() diff --git a/static/app.js b/static/app.js new file mode 100644 index 0000000..bb09c86 --- /dev/null +++ b/static/app.js @@ -0,0 +1,108 @@ +const MAX_BYTES = 10 * 1024 * 1024; +const ALLOWED_EXTENSIONS = /\.(jpe?g|png|heic)$/i; + +const form = document.querySelector('#upload-form'); +const input = document.querySelector('#image-input'); +const dropZone = document.querySelector('#drop-zone'); +const fileRow = document.querySelector('#file-row'); +const fileName = document.querySelector('#file-name'); +const fileSize = document.querySelector('#file-size'); +const preview = document.querySelector('#preview'); +const removeButton = document.querySelector('#remove-button'); +const submitButton = document.querySelector('#submit-button'); +const status = document.querySelector('#status'); +let previewUrl = null; + +function setStatus(message = '', type = '') { + status.textContent = message; + status.className = `status ${type}`.trim(); +} + +function clearSelection() { + input.value = ''; + fileRow.hidden = true; + dropZone.hidden = false; + submitButton.disabled = true; + if (previewUrl) URL.revokeObjectURL(previewUrl); + previewUrl = null; + preview.removeAttribute('src'); +} + +function validate(file) { + if (!file) return 'Choose an image to continue.'; + if (!ALLOWED_EXTENSIONS.test(file.name)) return 'Choose a JPG, PNG, or HEIC image.'; + if (file.size === 0) return 'The selected image is empty.'; + if (file.size > MAX_BYTES) return 'The image must be 10 MB or smaller.'; + return ''; +} + +function showFile(file) { + const error = validate(file); + if (error) { + clearSelection(); + setStatus(error, 'error'); + return; + } + setStatus(); + fileName.textContent = file.name; + fileSize.textContent = `${(file.size / 1024 / 1024).toFixed(2)} MB`; + if (previewUrl) URL.revokeObjectURL(previewUrl); + previewUrl = URL.createObjectURL(file); + preview.src = previewUrl; + fileRow.hidden = false; + dropZone.hidden = true; + submitButton.disabled = false; +} + +input.addEventListener('change', () => showFile(input.files[0])); +removeButton.addEventListener('click', () => { clearSelection(); setStatus(); }); + +for (const eventName of ['dragenter', 'dragover']) { + dropZone.addEventListener(eventName, (event) => { + event.preventDefault(); + dropZone.classList.add('is-dragging'); + }); +} +for (const eventName of ['dragleave', 'drop']) { + dropZone.addEventListener(eventName, (event) => { + event.preventDefault(); + dropZone.classList.remove('is-dragging'); + }); +} +dropZone.addEventListener('drop', (event) => { + const files = event.dataTransfer.files; + if (files.length !== 1) { + setStatus('Drop exactly one image.', 'error'); + return; + } + const transfer = new DataTransfer(); + transfer.items.add(files[0]); + input.files = transfer.files; + showFile(files[0]); +}); + +form.addEventListener('submit', async (event) => { + event.preventDefault(); + const file = input.files[0]; + const error = validate(file); + if (error) { setStatus(error, 'error'); return; } + + submitButton.disabled = true; + submitButton.querySelector('span').textContent = 'Submitting…'; + setStatus('Securely sending your image…'); + const body = new FormData(); + body.append('image', file); + + try { + const response = await fetch(window.location.pathname, { method: 'POST', body }); + const result = await response.json(); + if (!response.ok) throw new Error(result.message || 'Upload failed.'); + clearSelection(); + setStatus(`${result.message} Receipt: ${result.receipt}`, 'success'); + } catch (error) { + submitButton.disabled = false; + setStatus(error.message || 'Upload failed. Please try again.', 'error'); + } finally { + submitButton.querySelector('span').textContent = 'Submit image'; + } +}); diff --git a/static/index.html b/static/index.html new file mode 100644 index 0000000..3100128 --- /dev/null +++ b/static/index.html @@ -0,0 +1,70 @@ +<!doctype html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <meta name="description" content="Submit one image privately for review."> + <title>Private Drop</title> + <link rel="stylesheet" href="/styles.css"> + </head> + <body> + <main class="shell"> + <header class="masthead"> + <a class="brand" href="/" aria-label="Private Drop home"> + <span class="brand-mark" aria-hidden="true"></span> + Private Drop + </a> + <span class="privacy-label"><span aria-hidden="true">●</span> Private intake</span> + </header> + + <section class="intro" aria-labelledby="page-title"> + <p class="eyebrow">Secure image submission</p> + <h1 id="page-title">Send one image.<br><em>Nothing more.</em></h1> + <p class="lede">Your image is delivered directly to our private review queue. It is never published or made available through a public link.</p> + </section> + + <section class="upload-card" aria-labelledby="upload-title"> + <div class="card-heading"> + <div> + <p class="step">01 / Upload</p> + <h2 id="upload-title">Choose your image</h2> + </div> + <p class="formats">JPG · PNG · HEIC<br>10 MB maximum</p> + </div> + + <form id="upload-form" novalidate> + <input id="image-input" name="image" type="file" accept=".jpg,.jpeg,.png,.heic,image/jpeg,image/png,image/heic,image/heif" required> + <label class="drop-zone" for="image-input" id="drop-zone"> + <span class="upload-icon" aria-hidden="true"> + <svg viewBox="0 0 24 24" role="img"><path d="M12 16V4m0 0L7.5 8.5M12 4l4.5 4.5M5 14.5V19h14v-4.5"/></svg> + </span> + <span class="drop-title">Drop an image here</span> + <span class="drop-copy">or <u>browse your device</u></span> + </label> + + <div class="file-row" id="file-row" hidden> + <div class="thumb-wrap"><img id="preview" alt="Selected image preview"></div> + <div class="file-details"> + <strong id="file-name"></strong> + <span id="file-size"></span> + </div> + <button class="remove-button" type="button" id="remove-button" aria-label="Remove selected image">×</button> + </div> + + <p class="status" id="status" role="status" aria-live="polite"></p> + <button class="submit-button" type="submit" id="submit-button" disabled> + <span>Submit image</span><span aria-hidden="true">↗</span> + </button> + </form> + </section> + + <aside class="privacy-note"> + <span class="lock" aria-hidden="true">⌁</span> + <div><strong>Private by design</strong><p>Files are renamed on arrival, stored outside the public website, and available only to the review team.</p></div> + </aside> + + <footer><span>Private Drop</span><span>Confidential image intake</span></footer> + </main> + <script src="/app.js" defer></script> + </body> +</html> diff --git a/static/styles.css b/static/styles.css new file mode 100644 index 0000000..b59e7a3 --- /dev/null +++ b/static/styles.css @@ -0,0 +1,120 @@ +:root { + --ink: #191815; + --paper: #f3efe6; + --card: #fbf8f1; + --accent: #ddff4f; + --muted: #756f64; + --line: #d5cfc2; + --error: #a63b2b; + --success: #336440; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + min-width: 320px; + color: var(--ink); + background: + radial-gradient(circle at 84% 12%, rgba(221, 255, 79, .22), transparent 23rem), + var(--paper); + font-family: Arial, Helvetica, sans-serif; + min-height: 100vh; +} + +body::before { + content: ""; + position: fixed; + inset: 0; + pointer-events: none; + opacity: .24; + background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 160 160' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.8' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.14'/%3E%3C/svg%3E"); +} + +button, input { font: inherit; } + +.shell { width: min(1120px, calc(100% - 40px)); margin: 0 auto; position: relative; } + +.masthead { + height: 90px; + display: flex; + align-items: center; + justify-content: space-between; + border-bottom: 1px solid var(--ink); +} + +.brand { display: flex; align-items: center; gap: 11px; color: inherit; text-decoration: none; font-weight: 800; letter-spacing: -.03em; } +.brand-mark { width: 19px; height: 19px; background: var(--ink); border-radius: 50% 50% 2px 50%; transform: rotate(45deg); } +.privacy-label { font-size: .72rem; letter-spacing: .16em; text-transform: uppercase; } +.privacy-label span { color: #83a400; margin-right: 7px; } + +.intro { padding: 76px 0 58px; display: grid; grid-template-columns: 1.45fr .72fr; gap: 8vw; align-items: end; } +.eyebrow, .step { text-transform: uppercase; letter-spacing: .16em; font-size: .68rem; font-weight: 800; margin: 0 0 22px; } +h1 { font-family: Georgia, 'Times New Roman', serif; font-size: clamp(3.35rem, 7vw, 6.5rem); line-height: .86; letter-spacing: -.065em; font-weight: 400; margin: 0; } +h1 em { color: transparent; -webkit-text-stroke: 1.5px var(--ink); font-weight: 400; } +.lede { font-family: Georgia, 'Times New Roman', serif; font-size: 1.18rem; line-height: 1.55; margin: 0 0 3px; max-width: 29rem; } + +.upload-card { background: var(--card); border: 1px solid var(--ink); box-shadow: 10px 10px 0 var(--ink); padding: clamp(24px, 4vw, 50px); } +.card-heading { display: flex; justify-content: space-between; gap: 30px; align-items: start; margin-bottom: 34px; } +.step { margin-bottom: 8px; color: var(--muted); } +h2 { font-family: Georgia, 'Times New Roman', serif; font-size: clamp(1.85rem, 3.5vw, 2.65rem); margin: 0; font-weight: 400; letter-spacing: -.035em; } +.formats { margin: 0; text-align: right; font-size: .69rem; line-height: 1.55; letter-spacing: .13em; text-transform: uppercase; color: var(--muted); } +#image-input { position: absolute; inline-size: 1px; block-size: 1px; opacity: 0; } + +.drop-zone { + min-height: 250px; + border: 1px dashed #928b80; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + cursor: pointer; + transition: background .18s, border-color .18s, transform .18s; + background: rgba(243, 239, 230, .55); +} +.drop-zone:hover, .drop-zone.is-dragging, #image-input:focus-visible + .drop-zone { background: rgba(221, 255, 79, .16); border-color: var(--ink); outline: none; } +.drop-zone.is-dragging { transform: scale(.992); } +.upload-icon { width: 52px; height: 52px; border-radius: 50%; background: var(--accent); display: grid; place-items: center; margin-bottom: 20px; } +.upload-icon svg { width: 24px; fill: none; stroke: currentColor; stroke-width: 1.5; stroke-linecap: square; } +.drop-title { font-family: Georgia, 'Times New Roman', serif; font-size: 1.55rem; margin-bottom: 8px; } +.drop-copy { color: var(--muted); font-size: .82rem; } + +.file-row { min-height: 104px; align-items: center; border: 1px solid var(--line); padding: 12px; gap: 16px; background: white; } +.file-row:not([hidden]) { display: flex; } +.thumb-wrap { width: 78px; height: 78px; background: #e8e3d9; overflow: hidden; flex: 0 0 auto; } +.thumb-wrap img { width: 100%; height: 100%; object-fit: cover; } +.file-details { min-width: 0; display: flex; flex-direction: column; gap: 8px; flex: 1; } +.file-details strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.file-details span { font-size: .73rem; color: var(--muted); text-transform: uppercase; letter-spacing: .1em; } +.remove-button { background: transparent; border: 0; font-size: 1.8rem; cursor: pointer; width: 44px; height: 44px; } +.status { min-height: 22px; margin: 16px 0 10px; font-size: .82rem; color: var(--muted); } +.status.error { color: var(--error); } +.status.success { color: var(--success); font-weight: 700; } + +.submit-button { width: 100%; min-height: 62px; padding: 0 24px; display: flex; align-items: center; justify-content: space-between; border: 1px solid var(--ink); background: var(--accent); color: var(--ink); font-weight: 800; cursor: pointer; transition: transform .15s, box-shadow .15s, background .15s; } +.submit-button:not(:disabled):hover { transform: translate(-3px, -3px); box-shadow: 4px 4px 0 var(--ink); } +.submit-button:disabled { background: #ded9cf; color: #8d877c; border-color: #b5afa4; cursor: not-allowed; } + +.privacy-note { display: grid; grid-template-columns: 42px 1fr; gap: 16px; max-width: 600px; margin: 48px auto 88px; } +.lock { border: 1px solid var(--ink); width: 38px; height: 38px; display: grid; place-items: center; border-radius: 50%; font-size: 1.3rem; } +.privacy-note strong { font-size: .72rem; text-transform: uppercase; letter-spacing: .13em; } +.privacy-note p { margin: 7px 0 0; font-family: Georgia, 'Times New Roman', serif; color: var(--muted); line-height: 1.45; } +footer { border-top: 1px solid var(--ink); height: 80px; display: flex; justify-content: space-between; align-items: center; font-size: .65rem; letter-spacing: .13em; text-transform: uppercase; } + +@media (max-width: 720px) { + .shell { width: min(100% - 24px, 1120px); } + .masthead { height: 70px; } + .privacy-label { font-size: .61rem; } + .intro { padding: 52px 0 40px; grid-template-columns: 1fr; gap: 32px; } + .lede { font-size: 1.05rem; max-width: 34rem; } + .upload-card { box-shadow: 5px 5px 0 var(--ink); } + .card-heading { display: block; } + .formats { text-align: left; margin-top: 18px; } + .drop-zone { min-height: 220px; } + footer { align-items: start; flex-direction: column; justify-content: center; gap: 8px; } +} + +@media (prefers-reduced-motion: reduce) { + * { scroll-behavior: auto !important; transition: none !important; } +} diff --git a/tests/test_server.py b/tests/test_server.py new file mode 100644 index 0000000..aaff61e --- /dev/null +++ b/tests/test_server.py @@ -0,0 +1,118 @@ +import http.client +import tempfile +import threading +import unittest +from pathlib import Path + +from server import MAX_FILE_BYTES, detect_image_type, make_server + + +PNG = b"\x89PNG\r\n\x1a\n" + b"test-image" + + +def multipart(filename: str, payload: bytes, boundary: str = "test-boundary") -> tuple[bytes, str]: + body = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="image"; filename="{filename}"\r\n' + "Content-Type: application/octet-stream\r\n\r\n" + ).encode() + payload + f"\r\n--{boundary}--\r\n".encode() + return body, f"multipart/form-data; boundary={boundary}" + + +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.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + self.port = self.server.server_address[1] + + def tearDown(self): + self.server.shutdown() + self.server.server_close() + self.thread.join() + self.temp.cleanup() + + def request(self, method, path, body=None, headers=None): + connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=3) + connection.request(method, path, body=body, headers=headers or {}) + response = connection.getresponse() + data = response.read() + connection.close() + return response, data + + def test_accepts_png_and_stores_it_under_target(self): + body, content_type = multipart("photo.png", PNG) + response, data = self.request( + "POST", "/logo-contest", body, {"Content-Type": content_type, "Content-Length": str(len(body))} + ) + self.assertEqual(response.status, 201, data) + target_dir = self.upload_dir / "logo-contest" + files = list(target_dir.iterdir()) + self.assertEqual(len(files), 1) + self.assertEqual(files[0].read_bytes(), PNG) + self.assertNotIn("photo", files[0].name) + self.assertEqual(files[0].stat().st_mode & 0o777, 0o600) + self.assertEqual(target_dir.stat().st_mode & 0o777, 0o700) + + hidden_response, _ = self.request("GET", f"/logo-contest/{files[0].name}") + self.assertEqual(hidden_response.status, 404) + + def test_root_is_rejected_but_target_page_is_available(self): + root_response, _ = self.request("GET", "/") + target_response, page = self.request("GET", "/911u19jasdl") + self.assertEqual(root_response.status, 418) + self.assertEqual(target_response.status, 200) + self.assertIn(b"Private Drop", page) + + def test_upload_to_root_is_rejected_as_teapot(self): + body, content_type = multipart("photo.png", PNG) + response, _ = self.request( + "POST", "/", body, {"Content-Type": content_type, "Content-Length": str(len(body))} + ) + self.assertEqual(response.status, 418) + + def test_targets_are_stored_in_separate_directories(self): + for target in ("logo-contest", "911u19jasdl"): + body, content_type = multipart("photo.png", PNG) + response, _ = self.request( + "POST", f"/{target}", body, {"Content-Type": content_type, "Content-Length": str(len(body))} + ) + self.assertEqual(response.status, 201) + self.assertEqual(len(list((self.upload_dir / target).iterdir())), 1) + + def test_invalid_or_nested_targets_are_rejected(self): + for path in ("/bad.target", "/nested/target", "/%2e%2e", "/healthz"): + body, content_type = multipart("photo.png", PNG) + response, _ = self.request( + "POST", path, body, {"Content-Type": content_type, "Content-Length": str(len(body))} + ) + self.assertEqual(response.status, 404) + + def test_rejects_non_image_content(self): + body, content_type = multipart("fake.jpg", b"not really an image") + response, _ = self.request( + "POST", "/logo-contest", body, {"Content-Type": content_type, "Content-Length": str(len(body))} + ) + self.assertEqual(response.status, 400) + self.assertFalse((self.upload_dir / "logo-contest").exists()) + + def test_rejects_oversized_request_before_reading_body(self): + response, _ = self.request( + "POST", "/logo-contest", b"", {"Content-Type": "multipart/form-data; boundary=x", "Content-Length": str(MAX_FILE_BYTES + 1024 * 1024 + 1)} + ) + self.assertEqual(response.status, 413) + + def test_unknown_paths_are_not_served(self): + response, _ = self.request("GET", "/server.py") + self.assertEqual(response.status, 404) + + def test_detects_supported_signatures(self): + self.assertEqual(detect_image_type(b"\xff\xd8\xffrest"), (".jpg", "image/jpeg")) + self.assertEqual(detect_image_type(PNG), (".png", "image/png")) + self.assertEqual(detect_image_type(b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00heic"), (".heic", "image/heic")) + + +if __name__ == "__main__": + unittest.main() |
