aboutsummaryrefslogtreecommitdiff
path: root/tests/test_views.py
blob: 8ac57b11efb27a10f44c704be2c35c3f314165c2 (plain) (blame)
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
# 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 DATABASE as db
from webmentions_ssg.models import (
    ReceivedWebmention,
    SentWebmention,
    SentWebmentionStatus,
    Source,
    User,
)

SOURCE_URL = "https://source.example/post"
TARGET_URL = "https://dennisfink.me/blog/example/"


@pytest.fixture
def views_module(app: Flask) -> ModuleType:
    _ = app
    from webmentions_ssg import views

    return views


def mock_endpoint_form(
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    *,
    valid: bool,
    source: str = SOURCE_URL,
    target: str = TARGET_URL,
    errors: dict[str, list[str]] | None = None,
) -> Mock:
    form = Mock()
    form.validate_on_submit.return_value = valid
    form.source.data = source
    form.target.data = target
    form.errors = errors or {}

    monkeypatch.setattr(views_module.forms, "EndpointForm", Mock(return_value=form))
    return form


def log_in(app: Flask, client: FlaskClient) -> None:
    with app.app_context():
        user = User(username="admin", password="test")

        db.session.add(user)
        db.session.commit()

        user_id = user.id

    with client.session_transaction() as session:
        session["_user_id"] = str(user_id)
        session["_fresh"] = True


def create_sent_source(app: Flask) -> uuid.UUID:
    now = datetime.now(UTC)

    with app.app_context():
        source = Source(
            path="blog/example/index.html",
            url="https://dennisfink.me/blog/example/",
            content_hash="0" * 32,
            revision=2,
            last_seen_at=now,
            revised_at=now,
        )

        source.sent_webmentions.extend(
            [
                SentWebmention(
                    target="https://example.com/b",
                    active=True,
                    desired_revision=2,
                    processed_revision=2,
                    sent_revision=2,
                    status=SentWebmentionStatus.SENT,
                    endpoint="https://example.com/webmention",
                    response_status=202,
                ),
                SentWebmention(
                    target="https://example.com/a",
                    active=True,
                    desired_revision=2,
                    processed_revision=2,
                    sent_revision=1,
                    status=SentWebmentionStatus.FAILED,
                    failure_reason="Webmention endpoint returned HTTP 400",
                    endpoint="https://example.com/webmention",
                    response_status=400,
                ),
            ]
        )

        db.session.add(source)
        db.session.commit()

        return source.uuid


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)


@pytest.mark.parametrize("path", ["/sent", f"/sent/{uuid.uuid7()}"])
def test_sent_views_require_login(client: FlaskClient, path: str) -> None:
    response = client.get(path)

    assert response.status_code == 302
    assert "/login" in response.headers["Location"]


def test_sent_lists_sources(app: Flask, client: FlaskClient) -> None:
    log_in(app, client)
    identifier = create_sent_source(app)

    response = client.get("/sent")

    assert response.status_code == 200

    html = response.get_data(as_text=True)

    assert "blog/example/index.html" in html
    assert "https://dennisfink.me/blog/example/" in html
    assert f"/sent/{identifier}" in html


def test_sent_source_lists_webmentions(app: Flask, client: FlaskClient) -> None:
    log_in(app, client)
    identifier = create_sent_source(app)

    response = client.get(f"/sent/{identifier}")

    assert response.status_code == 200

    html = response.get_data(as_text=True)

    assert "blog/example/index.html" in html
    assert "https://dennisfink.me/blog/example/" in html

    first_target = "https://example.com/a"
    second_target = "https://example.com/b"

    assert first_target in html
    assert second_target in html
    assert html.index(first_target) < html.index(second_target)

    assert "Webmention endpoint returned HTTP 400" in html
    assert "https://example.com/webmention" in html


def test_sent_source_returns_404_for_unknown_source(
    app: Flask, client: FlaskClient
) -> None:
    log_in(app, client)
    response = client.get(f"/sent/{uuid.uuid7()}")
    assert response.status_code == 404


def mock_login_form(
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    *,
    valid: bool,
    username: str = "admin",
    password: str | None = "test",
) -> Mock:
    form = Mock()
    form.validate_on_submit.return_value = valid
    form.username.data = username
    form.password.data = password

    monkeypatch.setattr(views_module.forms, "LoginForm", Mock(return_value=form))
    return form


def mock_admin_action_form(
    views_module: ModuleType, monkeypatch: pytest.MonkeyPatch, *, valid: bool
) -> Mock:
    form = Mock()
    form.validate_on_submit.return_value = valid

    monkeypatch.setattr(views_module.forms, "AdminActionForm", Mock(return_value=form))
    return form


def create_received_webmention(
    app: Flask,
    *,
    source: str = SOURCE_URL,
    target: str = TARGET_URL,
    status: str = "verified",
    failure_reason: str | None = None,
) -> uuid.UUID:
    with app.app_context():
        webmention = ReceivedWebmention(
            uuid=uuid.uuid7(),
            source=source,
            target=target,
            status=status,
            failure_reason=failure_reason,
        )

        db.session.add(webmention)
        db.session.commit()

        return webmention.uuid


def create_resendable_sent_webmention(app: Flask) -> tuple[uuid.UUID, uuid.UUID]:
    now = datetime.now(UTC)

    with app.app_context():
        source = Source(
            path="blog/resend/index.html",
            url="https://dennisfink.me/blog/resend/",
            content_hash="1" * 32,
            revision=3,
            last_seen_at=now,
            revised_at=now,
        )
        webmention = SentWebmention(
            target="https://example.com/resend",
            active=True,
            desired_revision=3,
            processed_revision=3,
            sent_revision=2,
            status=SentWebmentionStatus.FAILED,
            failure_reason="Previous failure",
            endpoint="https://example.com/webmention",
            response_status=500,
            status_url="https://example.com/webmention/status/123",
        )
        source.sent_webmentions.append(webmention)

        db.session.add(source)
        db.session.commit()

        return source.uuid, webmention.uuid


def test_login_renders_form(client: FlaskClient) -> None:
    response = client.get("/login")

    assert response.status_code == 200
    assert "login" in response.get_data(as_text=True).lower()


@pytest.mark.parametrize("password", ("wrong-password", None))
def test_login_rejects_invalid_credentials(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    password: str | None,
) -> None:
    with app.app_context():
        db.session.add(User(username="admin", password="test"))
        db.session.commit()

    mock_login_form(
        views_module, monkeypatch, valid=True, username="admin", password=password
    )

    response = client.post("/login")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/login")

    with client.session_transaction() as session:
        assert "_user_id" not in session
        assert ("danger", "Invalid username or password") in session["_flashes"]


@pytest.mark.parametrize(
    "next_url",
    [
        pytest.param("/", id="root"),
        pytest.param("/received", id="local-path"),
        pytest.param("/received?page=2", id="query-string"),
        pytest.param("/received#details", id="fragment"),
    ],
)
def test_login_redirects_to_local_next_page(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    next_url: str,
) -> None:
    with app.app_context():
        user = User(username="admin", password="test")
        db.session.add(user)
        db.session.commit()
        user_id = user.id

    mock_login_form(views_module, monkeypatch, valid=True)

    response = client.post("/login", query_string={"next": next_url})

    assert response.status_code == 302
    assert response.headers["Location"] == next_url

    with client.session_transaction() as session:
        assert session["_user_id"] == str(user_id)


@pytest.mark.parametrize(
    "next_url",
    [
        pytest.param(None, id="missing"),
        pytest.param("", id="empty"),
        pytest.param("received", id="relative-path"),
        pytest.param("https://evil.example/phishing", id="absolute-https"),
        pytest.param("http://evil.example", id="absolute-http"),
        pytest.param("javascript:alert(1)", id="non-http-scheme"),
        pytest.param("//evil.example/phishing", id="scheme-relative"),
        pytest.param("///evil.example/phishing", id="triple-slash"),
        pytest.param("////evil.example", id="four-slashes"),
        pytest.param(r"/\evil.example", id="slash-backslash-host"),
        pytest.param(r"/received\evil.example", id="backslash-in-path"),
        pytest.param(r"\/evil.example", id="backslash-slash-host"),
    ],
)
def test_login_rejects_unsafe_next_page(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    next_url: str | None,
) -> None:
    with app.app_context():
        user = User(username="admin", password="test")
        db.session.add(user)
        db.session.commit()
        user_id = user.id

    mock_login_form(views_module, monkeypatch, valid=True)

    query_string = {} if next_url is None else {"next": next_url}
    response = client.post("/login", query_string=query_string)

    assert response.status_code == 302
    assert response.headers["Location"] == "/"

    with client.session_transaction() as session:
        assert session["_user_id"] == str(user_id)


def test_login_redirects_authenticated_user(app: Flask, client: FlaskClient) -> None:
    log_in(app, client)

    response = client.get("/login")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/")


def test_received_requires_login(client: FlaskClient) -> None:
    response = client.get("/received")

    assert response.status_code == 302
    assert "/login" in response.headers["Location"]


def test_received_lists_webmentions(app: Flask, client: FlaskClient) -> None:
    log_in(app, client)
    create_received_webmention(app)

    response = client.get("/received")

    assert response.status_code == 200
    html = response.get_data(as_text=True)
    assert SOURCE_URL in html
    assert TARGET_URL in html


@pytest.mark.parametrize("action", ["delete", "reverify"])
def test_received_admin_actions_require_login(client: FlaskClient, action: str) -> None:
    response = client.post(f"/received/{uuid.uuid7()}/{action}")

    assert response.status_code == 302
    assert "/login" in response.headers["Location"]


@pytest.mark.parametrize("action", ["delete", "reverify"])
def test_received_admin_actions_reject_invalid_form(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    action: str,
) -> None:
    log_in(app, client)
    identifier = create_received_webmention(app)
    form = mock_admin_action_form(views_module, monkeypatch, valid=False)

    response = client.post(f"/received/{identifier}/{action}")

    assert response.status_code == 400
    form.validate_on_submit.assert_called_once_with()


@pytest.mark.parametrize("action", ["delete", "reverify"])
def test_received_admin_actions_return_404_for_unknown_webmention(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    action: str,
) -> None:
    log_in(app, client)
    mock_admin_action_form(views_module, monkeypatch, valid=True)

    response = client.post(f"/received/{uuid.uuid7()}/{action}")

    assert response.status_code == 404


def test_delete_received_webmention(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    log_in(app, client)
    identifier = create_received_webmention(app)
    mock_admin_action_form(views_module, monkeypatch, valid=True)

    response = client.post(f"/received/{identifier}/delete?page=3")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/received?page=3")

    with app.app_context():
        assert db.session.get(ReceivedWebmention, identifier) is None


def test_reverify_received_webmention(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    log_in(app, client)
    identifier = create_received_webmention(
        app, status="failed", failure_reason="Previous failure"
    )
    mock_admin_action_form(views_module, monkeypatch, valid=True)
    verify_webmention = Mock()
    monkeypatch.setattr(views_module, "verify_webmention", verify_webmention)

    response = client.post(f"/received/{identifier}/reverify?page=2")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/received?page=2")

    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_rescan_sent_sources_requires_login(client: FlaskClient) -> None:
    response = client.post("/sent/rescan")

    assert response.status_code == 302
    assert "/login" in response.headers["Location"]


@pytest.mark.parametrize("valid", [False, True])
def test_rescan_sent_sources(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    valid: bool,
) -> None:
    log_in(app, client)
    form = mock_admin_action_form(views_module, monkeypatch, valid=valid)
    manual_scan_sources = Mock()
    monkeypatch.setattr(views_module, "manual_scan_sources", manual_scan_sources)

    response = client.post("/sent/rescan")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/sent")
    form.validate_on_submit.assert_called_once_with()

    if valid:
        manual_scan_sources.assert_called_once_with()
    else:
        manual_scan_sources.assert_not_called()


def test_resend_sent_webmention_requires_login(client: FlaskClient) -> None:
    response = client.post(f"/sent/{uuid.uuid7()}/{uuid.uuid7()}/resend")

    assert response.status_code == 302
    assert "/login" in response.headers["Location"]


def test_resend_sent_webmention_rejects_invalid_form(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    log_in(app, client)
    source_identifier, webmention_identifier = create_resendable_sent_webmention(app)
    mock_admin_action_form(views_module, monkeypatch, valid=False)

    response = client.post(f"/sent/{source_identifier}/{webmention_identifier}/resend")

    assert response.status_code == 400


def test_resend_sent_webmention_returns_404_for_unknown_webmention(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    log_in(app, client)
    source_identifier = create_sent_source(app)
    mock_admin_action_form(views_module, monkeypatch, valid=True)

    response = client.post(f"/sent/{source_identifier}/{uuid.uuid7()}/resend")

    assert response.status_code == 404


def test_resend_sent_webmention_rejects_wrong_source(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    log_in(app, client)
    _, webmention_identifier = create_resendable_sent_webmention(app)
    wrong_source_identifier = create_sent_source(app)
    mock_admin_action_form(views_module, monkeypatch, valid=True)

    response = client.post(
        f"/sent/{wrong_source_identifier}/{webmention_identifier}/resend"
    )

    assert response.status_code == 404


def test_resend_sent_webmention_reopens_current_revision(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    log_in(app, client)
    source_identifier, webmention_identifier = create_resendable_sent_webmention(app)
    mock_admin_action_form(views_module, monkeypatch, valid=True)
    send_webmention = Mock()
    monkeypatch.setattr(views_module, "send_webmention", send_webmention)

    response = client.post(f"/sent/{source_identifier}/{webmention_identifier}/resend")

    assert response.status_code == 302
    assert response.headers["Location"].endswith(f"/sent/{source_identifier}")

    with app.app_context():
        webmention = db.session.get(SentWebmention, webmention_identifier)
        assert webmention is not None
        assert webmention.desired_revision == 3
        assert webmention.processed_revision is None
        assert webmention.sent_revision == 2
        assert webmention.status is None
        assert webmention.failure_reason is None
        assert webmention.endpoint is None
        assert webmention.response_status is None
        assert webmention.status_url is None

    send_webmention.assert_called_once_with(webmention_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


def test_endpoint_recovers_from_concurrent_insert(
    client: FlaskClient, views_module: ModuleType, monkeypatch: pytest.MonkeyPatch
) -> 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",
    )

    initial_result = Mock()
    initial_result.scalar_one_or_none.return_value = None
    competing_result = Mock()
    competing_result.scalar_one.return_value = competing_webmention

    execute = Mock(side_effect=[initial_result, competing_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 == 2
    add.assert_called_once_with(ANY)
    rollback.assert_called_once_with()
    assert commit.call_count == 1

    assert competing_webmention.status == "failed"
    assert competing_webmention.failure_reason == "Competing request failed"
    verify_webmention.assert_not_called()


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_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",
            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

    verify.assert_called_once_with(identifier)


@pytest.mark.parametrize("username", ["admin", "unknown-user"])
def test_login_always_checks_password(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
    username: str,
) -> None:
    with app.app_context():
        db.session.add(User(username="admin", password="test"))
        db.session.commit()

    mock_login_form(
        views_module,
        monkeypatch,
        valid=True,
        username=username,
        password="wrong-password",
    )

    original_check_password = User.check_password
    checked_users: list[User] = []

    def spy_check_password(self: User, password: str) -> bool:
        checked_users.append(self)
        return original_check_password(self, password)

    monkeypatch.setattr(User, "check_password", spy_check_password)

    response = client.post("/login")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/login")
    assert len(checked_users) == 1

    if username == "admin":
        assert checked_users[0].username == "admin"
    else:
        assert checked_users[0] is views_module.DUMMY_USER

    with client.session_transaction() as session:
        assert "_user_id" not in session
        assert ("danger", "Invalid username or password") in session["_flashes"]


def test_login_rejects_dummy_user_even_if_password_matches(
    client: FlaskClient, views_module: ModuleType, monkeypatch: pytest.MonkeyPatch
) -> None:
    mock_login_form(
        views_module,
        monkeypatch,
        valid=True,
        username="unknown-user",
        password="anything",
    )

    checked_users: list[User] = []

    def mock_check_password(self: User, password: str) -> bool:
        checked_users.append(self)
        return True

    monkeypatch.setattr(User, "check_password", mock_check_password)

    response = client.post("/login")

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/login")
    assert checked_users == [views_module.DUMMY_USER]

    with client.session_transaction() as session:
        assert "_user_id" not in session


def test_login_rate_limit_is_independent_per_ip(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    app.config["LOGIN_RATE_LIMIT"] = "1/minute"

    mock_login_form(
        views_module,
        monkeypatch,
        valid=True,
        username="unknown-user",
        password="wrong-password",
    )

    def attempt(ip: str) -> int:
        response = client.post("/login", environ_overrides={"REMOTE_ADDR": ip})
        return response.status_code

    assert attempt("192.0.2.10") == 302
    assert attempt("192.0.2.10") == 429

    # Another IP still has its own allowance.
    assert attempt("192.0.2.11") == 302
    assert attempt("192.0.2.11") == 429


def test_login_rate_limits_requests_per_ip(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    app.config["LOGIN_RATE_LIMIT"] = "2/minute"

    with monkeypatch.context() as patcher:
        form = mock_login_form(
            views_module,
            patcher,
            valid=True,
            username="unknown-user",
            password="wrong-password",
        )

        responses = [
            client.post("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.10"})
            for _ in range(3)
        ]

        assert [response.status_code for response in responses] == [302, 302, 429]
        assert form.validate_on_submit.call_count == 2
        assert "Too many login attempts" in responses[-1].get_data(as_text=True)

    # The real LoginForm is restored here.
    # GET requests must remain accessible after throttling.
    response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.10"})
    assert response.status_code == 200

    with client.session_transaction() as session:
        assert "_user_id" not in session


def test_logout_rejects_get(app: Flask, client: FlaskClient) -> None:
    log_in(app, client)

    response = client.get("/logout")

    assert response.status_code == 405

    with client.session_transaction() as session:
        assert "_user_id" in session


@pytest.mark.parametrize(
    "data",
    [
        pytest.param({}, id="missing"),
        pytest.param({"csrf_token": "invalid"}, id="invalid"),
    ],
)
def test_logout_rejects_invalid_csrf(
    app: Flask, client: FlaskClient, data: dict[str, str]
) -> None:
    app.config["WTF_CSRF_ENABLED"] = True
    log_in(app, client)

    response = client.post("/logout", data=data)

    assert response.status_code == 400

    with client.session_transaction() as session:
        assert "_user_id" in session


def test_logout_ends_session(app: Flask, client: FlaskClient) -> None:
    import re

    app.config["WTF_CSRF_ENABLED"] = True
    log_in(app, client)

    page = client.get("/received")
    assert page.status_code == 200

    html = page.get_data(as_text=True)

    assert 'action="/logout"' in html
    assert 'method="post"' in html

    match = re.search(r'name="csrf_token"\s+value="([^"]+)"', html)
    assert match is not None

    response = client.post("/logout", data={"csrf_token": match.group(1)})

    assert response.status_code == 302
    assert response.headers["Location"].endswith("/")

    with client.session_transaction() as session:
        assert "_user_id" not in session

    protected_response = client.get("/received")
    assert protected_response.status_code == 302
    assert "/login" in protected_response.headers["Location"]


def create_outgoing(
    app: Flask, *, status_url: str | None = None
) -> tuple[uuid.UUID, uuid.UUID]:
    now = datetime.now(UTC)
    with app.app_context():
        source = Source(
            path="blog/post/index.html",
            url="https://source.example/blog/post",
            content_hash="0" * 32,
            revision=1,
            last_seen_at=now,
            revised_at=now,
        )
        mention = SentWebmention(
            target="https://example.com/article",
            active=True,
            desired_revision=1,
            status_url=status_url,
            response_status=201 if status_url is not None else None,
        )
        source.sent_webmentions.append(mention)
        db.session.add(source)
        db.session.commit()
        return source.uuid, mention.uuid


@pytest.mark.parametrize(
    ("status_url", "safe"),
    [
        ("https://example.com/status", True),
        ("http://example.com/status", True),
        ("javascript:alert(1)", False),
        ("data:text/html,evil", False),
        ("ftp://example.com/status", False),
    ],
)
def test_admin_only_links_safe_existing_status_urls(
    app: Flask, client: FlaskClient, status_url: str, safe: bool
) -> None:
    source_identifier, _ = create_outgoing(app, status_url=status_url)
    with app.app_context():
        user = User(username="admin", password="test")
        db.session.add(user)
        db.session.commit()
        user_id = user.id

    with client.session_transaction() as session:
        session["_user_id"] = str(user_id)
        session["_fresh"] = True

    response = client.get(f"/sent/{source_identifier}")
    assert response.status_code == 200
    html = response.get_data(as_text=True)
    assert (f'href="{status_url}"' in html) is safe
    assert status_url in html