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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
import uuid
from datetime import UTC, datetime, timedelta
from types import ModuleType
from unittest.mock import ANY, Mock
import pytest
import sqlalchemy as sa
from flask import Flask
from flask.testing import FlaskClient
from sqlalchemy.exc import IntegrityError
from webmentions_ssg import db
from webmentions_ssg.models import ReceivedWebmention
from .helpers import (
SOURCE_URL,
TARGET_URL,
create_received_webmention,
mock_endpoint_form,
)
@pytest.fixture
def views_module(app: Flask) -> ModuleType:
_ = app
from webmentions_ssg.views import endpoint as module
return module
def test_endpoint_only_accepts_post(client: FlaskClient) -> None:
response = client.get("/endpoint")
assert response.status_code == 405
def test_endpoint_returns_form_errors(
client: FlaskClient, views_module: ModuleType, monkeypatch: pytest.MonkeyPatch
) -> None:
errors = {"source": ["Invalid source"]}
mock_endpoint_form(views_module, monkeypatch, valid=False, errors=errors)
response = client.post("/endpoint")
assert response.status_code == 400
assert response.get_json() == errors
def test_endpoint_creates_webmention(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
form = mock_endpoint_form(views_module, monkeypatch, valid=True)
verify_webmention = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify_webmention)
response = client.post("/endpoint")
assert response.status_code == 201
form.validate_on_submit.assert_called_once_with()
with app.app_context():
webmention = db.session.scalar(sa.select(ReceivedWebmention))
assert webmention is not None
assert webmention.source == SOURCE_URL
assert webmention.target == TARGET_URL
assert webmention.status == "received"
assert webmention.failure_reason is None
identifier = webmention.uuid
assert response.headers["Location"].endswith(str(identifier))
verify_webmention.assert_called_once_with(identifier)
def test_endpoint_is_idempotent(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
mock_endpoint_form(views_module, monkeypatch, valid=True)
verify_webmention = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify_webmention)
first_response = client.post("/endpoint")
second_response = client.post("/endpoint")
assert first_response.status_code == 201
assert second_response.status_code == 201
assert first_response.headers["Location"] == second_response.headers["Location"]
with app.app_context():
webmentions = db.session.scalars(sa.select(ReceivedWebmention)).all()
assert len(webmentions) == 1
webmention = webmentions[0]
assert webmention.source == SOURCE_URL
assert webmention.target == TARGET_URL
assert webmention.status == "received"
assert webmention.failure_reason is None
identifier = webmention.uuid
verify_webmention.assert_called_once_with(identifier)
def test_resending_resets_failure_state(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
mock_endpoint_form(views_module, monkeypatch, valid=True)
verify_webmention = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify_webmention)
with app.app_context():
existing = ReceivedWebmention(
uuid=uuid.uuid7(),
source=SOURCE_URL,
target=TARGET_URL,
status="failed",
failure_reason="Previous failure",
updated_at=datetime.now(UTC) - timedelta(minutes=11),
)
db.session.add(existing)
db.session.commit()
identifier = existing.uuid
response = client.post("/endpoint")
assert response.status_code == 201
with app.app_context():
webmention = db.session.get(ReceivedWebmention, identifier)
assert webmention is not None
assert webmention.status == "received"
assert webmention.failure_reason is None
verify_webmention.assert_called_once_with(identifier)
def test_status_returns_404_for_unknown_webmention(client: FlaskClient) -> None:
response = client.get(f"/status/{uuid.uuid7()}")
assert response.status_code == 404
def test_status_displays_webmention(app: Flask, client: FlaskClient) -> None:
identifier = create_received_webmention(
app, status="failed", failure_reason="Verification failed"
)
response = client.get(f"/status/{identifier}")
assert response.status_code == 200
html = response.get_data(as_text=True)
assert SOURCE_URL in html
assert TARGET_URL in html
assert "failed" in html
assert "Verification failed" in html
@pytest.mark.parametrize(("age_minutes", "reopened"), [(0, False), (11, True)])
def test_endpoint_recovers_from_concurrent_insert(
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
age_minutes: int,
reopened: bool,
) -> None:
mock_endpoint_form(views_module, monkeypatch, valid=True)
competing_identifier = uuid.uuid7()
competing_webmention = ReceivedWebmention(
uuid=competing_identifier,
source=SOURCE_URL,
target=TARGET_URL,
status="failed",
failure_reason="Competing request failed",
updated_at=datetime.now(UTC) - timedelta(minutes=age_minutes),
)
initial_result = Mock()
initial_result.scalar_one_or_none.return_value = None
competing_result = Mock()
competing_result.scalar_one_or_none.return_value = competing_webmention
update_result = Mock(rowcount=int(reopened))
execute = Mock(side_effect=[initial_result, competing_result, update_result])
add = Mock()
rollback = Mock()
commit = Mock(
side_effect=[
IntegrityError(
"INSERT INTO received_webmention ...",
{},
Exception("duplicate source/target"),
),
None,
]
)
verify_webmention = Mock()
monkeypatch.setattr(views_module.db.session, "execute", execute)
monkeypatch.setattr(views_module.db.session, "add", add)
monkeypatch.setattr(views_module.db.session, "rollback", rollback)
monkeypatch.setattr(views_module.db.session, "commit", commit)
monkeypatch.setattr(views_module, "verify_webmention", verify_webmention)
response = client.post("/endpoint")
assert response.status_code == 201
assert response.headers["Location"].endswith(f"/status/{competing_identifier}")
assert execute.call_count == 3
add.assert_called_once_with(ANY)
rollback.assert_called_once_with()
assert commit.call_count == 2
if reopened:
verify_webmention.assert_called_once_with(competing_identifier)
else:
verify_webmention.assert_not_called()
def test_endpoint_rejects_digest_collision(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
form = mock_endpoint_form(views_module, monkeypatch, valid=True)
verify = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify)
with app.app_context():
existing = ReceivedWebmention(
uuid=uuid.uuid7(), source=SOURCE_URL, target=TARGET_URL
)
db.session.add(existing)
db.session.commit()
digest = existing.url_digest
form.source.data = "https://source.example/different"
monkeypatch.setattr(
views_module, "received_url_digest", lambda source, target: digest
)
response = client.post("/endpoint")
assert response.status_code == 409
assert response.get_json() == {"error": "Webmention URL fingerprint conflict"}
verify.assert_not_called()
with app.app_context():
assert db.session.scalar(sa.select(sa.func.count(ReceivedWebmention.uuid))) == 1
def test_endpoint_rate_limits_requests_per_ip(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
app.config["ENDPOINT_RATE_LIMIT"] = "2/minute"
form = mock_endpoint_form(views_module, monkeypatch, valid=True)
verify = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify)
responses = []
for index in range(3):
form.source.data = f"https://source.example/post-{index}"
responses.append(
client.post("/endpoint", environ_overrides={"REMOTE_ADDR": "192.0.2.10"})
)
assert [r.status_code for r in responses] == [201, 201, 429]
assert verify.call_count == 2
with app.app_context():
count = db.session.scalar(
sa.select(sa.func.count()).select_from(ReceivedWebmention)
)
assert count == 2
def test_endpoint_rate_limit_distinguishes_clients_behind_trusted_proxy(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from werkzeug.middleware.proxy_fix import ProxyFix
app.config["ENDPOINT_RATE_LIMIT"] = "1/minute"
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
form = mock_endpoint_form(views_module, monkeypatch, valid=True)
monkeypatch.setattr(views_module, "verify_webmention", Mock())
def attempt(client_ip: str, index: int) -> int:
form.source.data = f"https://source.example/proxy-post-{index}"
return client.post(
"/endpoint",
environ_overrides={"REMOTE_ADDR": "192.0.2.200"},
headers={"X-Forwarded-For": client_ip},
).status_code
assert attempt("198.51.100.11", 0) == 201
assert attempt("198.51.100.11", 1) == 429
assert attempt("198.51.100.12", 2) == 201
def test_endpoint_global_rate_limit(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
app.config["ENDPOINT_GLOBAL_RATE_LIMIT"] = "2/minute"
form = mock_endpoint_form(views_module, monkeypatch, valid=True)
verify = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify)
responses = []
for index in range(3):
form.source.data = f"https://source.example/post-{index}"
responses.append(
client.post(
"/endpoint", environ_overrides={"REMOTE_ADDR": f"192.0.2.{index + 1}"}
)
)
assert [r.status_code for r in responses] == [201, 201, 429]
assert verify.call_count == 2
def test_endpoint_recent_duplicate_does_not_reverify(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
mock_endpoint_form(views_module, monkeypatch, valid=True)
verify = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify)
with app.app_context():
webmention = ReceivedWebmention(
uuid=uuid.uuid7(),
source=SOURCE_URL,
target=TARGET_URL,
status="failed",
failure_reason="Previous failure",
)
db.session.add(webmention)
db.session.commit()
identifier = webmention.uuid
response = client.post("/endpoint")
assert response.status_code == 201
assert response.headers["Location"].endswith(str(identifier))
with app.app_context():
stored = db.session.get(ReceivedWebmention, identifier)
assert stored is not None
assert stored.status == "failed"
assert stored.failure_reason == "Previous failure"
verify.assert_not_called()
def test_endpoint_reverifies_after_cooldown(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
) -> None:
mock_endpoint_form(views_module, monkeypatch, valid=True)
verify = Mock()
monkeypatch.setattr(views_module, "verify_webmention", verify)
with app.app_context():
webmention = ReceivedWebmention(
uuid=uuid.uuid7(),
source=SOURCE_URL,
target=TARGET_URL,
status="failed",
failure_reason="Previous failure",
recovery_attempts=3,
updated_at=datetime.now(UTC) - timedelta(minutes=11),
)
db.session.add(webmention)
db.session.commit()
identifier = webmention.uuid
response = client.post("/endpoint")
assert response.status_code == 201
with app.app_context():
stored = db.session.get(ReceivedWebmention, identifier)
assert stored is not None
assert stored.status == "received"
assert stored.failure_reason is None
assert stored.recovery_attempts == 0
verify.assert_called_once_with(identifier)
def test_endpoint_rejects_request_bodies_over_configured_maximum(
app: Flask, client: FlaskClient
) -> None:
app.config["MAX_CONTENT_LENGTH"] = 128
response = client.post(
"/endpoint", data={"source": SOURCE_URL + "x" * 150, "target": TARGET_URL}
)
assert response.status_code == 413
def test_endpoint_rejects_bad_url_before_inserting_row(
app: Flask, client: FlaskClient, monkeypatch: pytest.MonkeyPatch
) -> None:
from webmentions_ssg.views import endpoint as views
verify_webmention = Mock()
monkeypatch.setattr(views, "verify_webmention", verify_webmention)
response = client.post(
"/endpoint", data={"source": "http://ex☃mple.test/", "target": TARGET_URL}
)
assert response.status_code == 400
assert "source" in response.get_json()
verify_webmention.assert_not_called()
with app.app_context():
assert (
db.session.scalar(
sa.select(sa.func.count()).select_from(ReceivedWebmention)
)
== 0
)
|