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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
|
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_config, make_server
from watcher import send_recent_upload_notifications
PNG = b"\x89PNG\r\n\x1a\n" + b"test-image"
def multipart(
filename: str,
payload: bytes,
boundary: str = "test-boundary",
metadata: dict[str, str] | None = None,
) -> tuple[bytes, str]:
fields = metadata if metadata is not None else {
"callsign": "W1AW",
"name": "Test Operator",
"email": "operator@example.com",
"description": "A test image.",
}
body = b"".join(
(
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="{name}"\r\n\r\n'
f"{value}\r\n"
).encode("utf-8")
for name, value in fields.items()
) + (
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, 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]
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), 2)
image = next(path for path in files if path.suffix == ".png")
metadata = next(path for path in files if path.suffix == ".txt")
self.assertEqual(image.read_bytes(), PNG)
self.assertEqual(metadata.stem, image.stem)
self.assertEqual(
metadata.read_text(encoding="utf-8"),
"Callsign: W1AW\nName: Test Operator\nEmail: operator@example.com\n"
"Description:\nA test image.\n",
)
self.assertNotIn("photo", image.name)
self.assertEqual(image.stat().st_mode & 0o777, 0o600)
self.assertEqual(metadata.stat().st_mode & 0o777, 0o600)
self.assertEqual(target_dir.stat().st_mode & 0o777, 0o700)
hidden_response, _ = self.request("GET", f"/logo-contest/{image.name}")
hidden_metadata_response, _ = self.request("GET", f"/logo-contest/{metadata.name}")
self.assertEqual(hidden_response.status, 404)
self.assertEqual(hidden_metadata_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"Blind Uploader", page)
self.assertLess(page.index(b'name="callsign"'), page.index(b'name="image"'))
self.assertIn(b'name="description" maxlength="1000"', 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())), 2)
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_unlisted_valid_target_is_rejected(self):
response, _ = self.request("GET", "/invented-target")
self.assertEqual(response.status, 404)
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_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):
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")
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_missing_metadata(self):
body, content_type = multipart("photo.png", PNG, metadata={})
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_description_over_1000_characters(self):
body, content_type = multipart(
"photo.png",
PNG,
metadata={
"callsign": "W1AW",
"name": "Test Operator",
"email": "operator@example.com",
"description": "x" * 1001,
},
)
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()
|