aboutsummaryrefslogtreecommitdiff
path: root/tests/views/test_admin.py
blob: 90d406b3b65fee267e378666299e185be57fd91e (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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

import uuid
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
from types import ModuleType
from unittest.mock import Mock

import pytest
from flask import Flask
from flask.testing import FlaskClient

from webmentions_ssg import db
from webmentions_ssg.models import ReceivedWebmention, SentWebmention, User

from .helpers import (
    SOURCE_URL,
    TARGET_URL,
    create_outgoing,
    create_received_webmention,
    create_resendable_sent_webmention,
    create_sent_source,
    log_in,
    mock_admin_action_form,
)


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

    return module


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

    assert response.status_code == HTTPStatus.FOUND
    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("/sources")

    assert response.status_code == HTTPStatus.OK

    html = response.get_data(as_text=True)

    assert "blog/example/index.html" in html
    assert "https://dennisfink.me/blog/example/" in html
    assert f"/sources/{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"/sources/{identifier}")

    assert response.status_code == HTTPStatus.OK

    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"/sources/{uuid.uuid7()}")
    assert response.status_code == HTTPStatus.NOT_FOUND


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

    assert response.status_code == HTTPStatus.FOUND
    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 == HTTPStatus.OK
    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 == HTTPStatus.FOUND
    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 == HTTPStatus.BAD_REQUEST
    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 == HTTPStatus.NOT_FOUND


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 == HTTPStatus.FOUND
    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"
    )
    with app.app_context():
        row = db.session.get(ReceivedWebmention, identifier)
        assert row is not None
        row.recovery_attempts = 3
        db.session.commit()
    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 == HTTPStatus.FOUND
    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
        assert webmention.recovery_attempts == 0

    verify_webmention.assert_called_once_with(identifier)


def test_rescan_sent_sources_requires_login(client: FlaskClient) -> None:
    response = client.post("/sources/rescan")

    assert response.status_code == HTTPStatus.FOUND
    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("/sources/rescan")

    assert response.status_code == (
        HTTPStatus.FOUND if valid else HTTPStatus.BAD_REQUEST
    )
    form.validate_on_submit.assert_called_once_with()

    if valid:
        assert response.headers["Location"].endswith("/sources")
        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"/sources/{uuid.uuid7()}/{uuid.uuid7()}/resend")

    assert response.status_code == HTTPStatus.FOUND
    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"/sources/{source_identifier}/{webmention_identifier}/resend"
    )

    assert response.status_code == HTTPStatus.BAD_REQUEST


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"/sources/{source_identifier}/{uuid.uuid7()}/resend")

    assert response.status_code == HTTPStatus.NOT_FOUND


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"/sources/{wrong_source_identifier}/{webmention_identifier}/resend"
    )

    assert response.status_code == HTTPStatus.NOT_FOUND


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)

    with app.app_context():
        webmention = db.session.get(SentWebmention, webmention_identifier)
        assert webmention is not None
        webmention.attempt_count = 6
        webmention.next_retry_at = datetime.now(UTC) + timedelta(hours=24)
        db.session.commit()

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

    assert response.status_code == HTTPStatus.FOUND
    assert response.headers["Location"].endswith(f"/sources/{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.attempt_count == 0
        assert webmention.next_retry_at 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)


@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.get_id()

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

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