aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--tests/test_auth.py9
-rw-r--r--webmentions_ssg/auth.py30
2 files changed, 24 insertions, 15 deletions
diff --git a/tests/test_auth.py b/tests/test_auth.py
index c302e8f..34df8ce 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -35,6 +35,12 @@ def test_load_user_returns_none_for_unknown_id(app: Flask) -> None:
assert load_user("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(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")
@@ -122,6 +128,9 @@ def test_password_change_invalidates_existing_session(app: Flask) -> None:
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:
diff --git a/webmentions_ssg/auth.py b/webmentions_ssg/auth.py
index 1707917..6d4fe95 100644
--- a/webmentions_ssg/auth.py
+++ b/webmentions_ssg/auth.py
@@ -44,26 +44,27 @@ def validate_password(password: str) -> None:
@AUTH.user_loader
-def load_user(session_id: str) -> User | None:
+def load_user(session_id: object) -> User | None:
"""Load a user from the database by identifier.
:param session_id: Database ID and password-hash fingerprint stored in the session.
:return: Matching user, or ``None`` if no user exists with the identifier.
"""
- try:
- user_id, fingerprint = session_id.split(":", 1)
- if (
- not user_id.isascii()
- or not user_id.isdecimal()
- or len(user_id) > 19
- or len(fingerprint) != 64
- or any(char not in "0123456789abcdef" for char in fingerprint)
- ):
- return None
- user = db.session.get(User, int(user_id))
- except AttributeError, TypeError, ValueError:
+ if not isinstance(session_id, str):
+ return None
+
+ user_id, separator, fingerprint = session_id.partition(":")
+ if (
+ not separator
+ or not user_id.isascii()
+ or not user_id.isdecimal()
+ or len(user_id) > 19
+ or len(fingerprint) != 64
+ or any(char not in "0123456789abcdef" for char in fingerprint)
+ ):
return None
+ user = db.session.get(User, int(user_id))
if user is None:
return None
@@ -90,8 +91,7 @@ def is_safe_next_url(next_url: str) -> bool:
except ValueError:
return False
return (
- not target.scheme
- and not target.netloc
+ not target.netloc
and target.path.startswith("/")
and not target.path.startswith("//")
)