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
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Test the session user loader."""
from http import HTTPStatus
import pytest
from flask import Flask
from webmentions_ssg import auth, db
from webmentions_ssg.auth import (
is_safe_next_url,
load_user_from_session_id,
login_manager,
validate_new_password,
)
from webmentions_ssg.models.user import User
@pytest.mark.parametrize("character", ["\x00", "\x1f", "\x7f", "\x80", "\x9f"])
def test_validate_password_rejects_unicode_controls(character: str) -> None:
with pytest.raises(ValueError, match="control characters"):
validate_new_password(f"valid passphrase{character}")
def test_user_loader_is_registered(app: Flask) -> None:
assert login_manager._user_callback is load_user_from_session_id
def test_dummy_password_hash_is_lazily_cached(monkeypatch: pytest.MonkeyPatch) -> None:
generated_passwords: list[str] = []
def fake_generate_password_hash(password: str) -> str:
generated_passwords.append(password)
return "dummy-hash"
auth.dummy_password_hash.cache_clear()
try:
with monkeypatch.context() as patcher:
patcher.setattr(auth, "generate_password_hash", fake_generate_password_hash)
assert generated_passwords == []
assert auth.dummy_password_hash() == "dummy-hash"
assert auth.dummy_password_hash() == "dummy-hash"
assert len(generated_passwords) == 1
finally:
auth.dummy_password_hash.cache_clear()
def test_load_user_returns_matching_user(app: Flask) -> None:
with app.app_context():
user = User(username="account", password="secret")
db.session.add(user)
db.session.commit()
assert load_user_from_session_id(user.get_id()) is user
def test_load_user_returns_none_for_unknown_id(app: Flask) -> None:
with app.app_context():
assert load_user_from_session_id("99999:" + "a" * 64) is None
@pytest.mark.parametrize("identifier", [None, 123, b"1:" + b"a" * 64])
def test_load_user_rejects_non_string_sessions(app: Flask, identifier: object) -> None:
with app.app_context():
assert load_user_from_session_id(identifier) is None
def test_load_user_rejects_legacy_and_malformed_sessions(app: Flask) -> None:
with app.app_context():
user = User(username="account", password="secret")
db.session.add(user)
db.session.commit()
for identifier in (
str(user.id), # Old ID-only sessions must not bypass revocation.
"",
"not-an-id:" + "a" * 64,
f"{user.id}:invalid",
f"{user.id}:" + "é" * 64,
f"{user.id}:" + "z" * 64,
f"{user.id}:" + "0" * 64,
f"{user.id}:" + "0" * 64 + ":trailing",
"-1:" + "0" * 64,
):
assert load_user_from_session_id(identifier) is None
def test_password_change_invalidates_existing_session(app: Flask) -> None:
old_password = "a long original passphrase"
new_password = "a different long passphrase"
with app.app_context():
user = User(username="account", password=old_password)
db.session.add(user)
db.session.commit()
old_identifier = user.get_id()
client = app.test_client()
response = client.post(
"/login", data={"username": "account", "password": old_password}
)
assert response.status_code == HTTPStatus.FOUND
assert client.get("/received").status_code == HTTPStatus.OK
with client.session_transaction() as session:
assert session["_user_id"] == old_identifier
result = app.test_cli_runner().invoke(
args=["users", "set-password", "account", "--password", new_password]
)
assert result.exit_code == 0, result.output
with app.app_context():
user = db.session.get(User, int(old_identifier.split(":", 1)[0]))
assert user is not None
assert user.get_id() != old_identifier
assert load_user_from_session_id(old_identifier) is None
assert load_user_from_session_id(user.get_id()) is user
# A pre-existing, validly signed cookie no longer authenticates.
assert client.get("/received").status_code == HTTPStatus.FOUND
# Logging in with the newly chosen password still works.
response = client.post(
"/login", data={"username": "account", "password": new_password}
)
assert response.status_code == HTTPStatus.FOUND
assert client.get("/received").status_code == HTTPStatus.OK
@pytest.mark.parametrize(
("next_url", "expected"),
[
pytest.param("/", True, id="root"),
pytest.param("/received", True, id="local-path"),
pytest.param("/received?page=2", True, id="query-string"),
pytest.param("/received#details", True, id="fragment"),
pytest.param(
"/sent?next=https://evil.example", True, id="external-url-in-query"
),
pytest.param("/foo//bar", True, id="double-slash-within-path"),
pytest.param("", False, id="empty"),
pytest.param("received", False, id="relative-path"),
pytest.param(" /received", False, id="leading-space"),
pytest.param("https://evil.example/phishing", False, id="absolute-https"),
pytest.param("http://evil.example", False, id="absolute-http"),
pytest.param("javascript:alert(1)", False, id="non-http-scheme"),
pytest.param("//evil.example/phishing", False, id="scheme-relative"),
pytest.param("///evil.example/phishing", False, id="triple-slash"),
pytest.param("////evil.example", False, id="four-slashes"),
pytest.param("//", False, id="two-slashes"),
pytest.param(r"/\evil.example", False, id="slash-backslash-host"),
pytest.param(r"/received\evil.example", False, id="backslash-in-path"),
pytest.param(r"\/evil.example", False, id="backslash-slash-host"),
pytest.param("/\n/evil.example", False, id="newline-host"),
pytest.param("/\r/evil.example", False, id="carriage-return-host"),
pytest.param("/\t/evil.example", False, id="tab-host"),
],
)
def test_is_safe_next_url(next_url: str, expected: bool) -> None:
assert is_safe_next_url(next_url) is expected
|