1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
|
#!/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
MAX_CALLSIGN_LENGTH = 32
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"
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 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"):
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(
"--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()
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:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()
|