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

from types import ModuleType

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

from webmentions_ssg import DATABASE as db
from webmentions_ssg.models import User

from .helpers import log_in, mock_login_form


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

    return module


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.get_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.get_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("/")


@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_limit_uses_forwarded_client_ip_when_proxy_is_trusted(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from werkzeug.middleware.proxy_fix import ProxyFix

    app.config["LOGIN_RATE_LIMIT"] = "1/minute"
    app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
    mock_login_form(
        views_module,
        monkeypatch,
        valid=True,
        username="unknown-user",
        password="wrong-password",
    )

    def attempt(client_ip: str) -> int:
        response = client.post(
            "/login",
            environ_overrides={"REMOTE_ADDR": "192.0.2.200"},
            headers={"X-Forwarded-For": client_ip},
        )
        return response.status_code

    assert attempt("198.51.100.11") == 302
    # A forged earlier X-Forwarded-For entry cannot change the client bucket.
    assert attempt("203.0.113.99, 198.51.100.11") == 429
    assert attempt("198.51.100.12") == 302


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

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

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

        assert attempt("192.0.2.10", "Admin") == 302
        assert attempt("192.0.2.11", " admin ") == 302
        assert attempt("192.0.2.12", "ADMIN") == 429
        # An unrelated username is not locked by attempts against Admin.
        assert attempt("192.0.2.12", "another-user") == 302

    # Restore the real form: the POST-only limits must not block a GET,
    # even from the client IP that submitted the throttled attempt.
    response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.12"})
    assert response.status_code == 200


def test_login_missing_username_uses_per_ip_bucket(
    app: Flask,
    client: FlaskClient,
    views_module: ModuleType,
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    app.config["LOGIN_RATE_LIMIT"] = "100/minute"
    app.config["LOGIN_USERNAME_RATE_LIMIT"] = "1/minute"
    mock_login_form(
        views_module,
        monkeypatch,
        valid=True,
        username="unknown-user",
        password="wrong-password",
    )

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

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


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"]