feat: Use secure random tokens for authentication and password handling in tests

This commit is contained in:
2025-11-12 11:36:19 +01:00
parent 3988171b46
commit 5d6592d657
3 changed files with 35 additions and 26 deletions

View File

@@ -1,5 +1,6 @@
from __future__ import annotations
import secrets
from datetime import timedelta
import pytest
@@ -17,11 +18,18 @@ from services.security import (
)
def test_hash_password_round_trip() -> None:
hashed = hash_password("super-secret")
@pytest.fixture()
def jwt_settings() -> JWTSettings:
"""Provide a unique JWTSettings instance per test with random secret."""
return JWTSettings(secret_key=secrets.token_urlsafe(32))
assert hashed != "super-secret"
assert verify_password("super-secret", hashed)
def test_hash_password_round_trip() -> None:
password = secrets.token_urlsafe(16)
hashed = hash_password(password)
assert hashed != password
assert verify_password(password, hashed)
assert not verify_password("incorrect", hashed)
@@ -29,47 +37,42 @@ def test_verify_password_handles_malformed_hash() -> None:
assert not verify_password("secret", "not-a-valid-hash")
def test_access_token_roundtrip() -> None:
settings = JWTSettings(secret_key="unit-test-secret")
def test_access_token_roundtrip(jwt_settings: JWTSettings) -> None:
token = create_access_token(
"user-id-123",
settings,
jwt_settings,
scopes=("read", "write"),
extra_claims={"custom": "value"},
)
payload = decode_access_token(token, settings)
payload = decode_access_token(token, jwt_settings)
assert payload.sub == "user-id-123"
assert payload.type == "access"
assert payload.scopes == ["read", "write"]
def test_refresh_token_type_mismatch() -> None:
settings = JWTSettings(secret_key="unit-test-secret")
token = create_refresh_token("user-id-456", settings)
def test_refresh_token_type_mismatch(jwt_settings: JWTSettings) -> None:
token = create_refresh_token("user-id-456", jwt_settings)
with pytest.raises(TokenTypeMismatchError):
decode_access_token(token, settings)
decode_access_token(token, jwt_settings)
def test_decode_expired_token() -> None:
settings = JWTSettings(secret_key="unit-test-secret")
def test_decode_expired_token(jwt_settings: JWTSettings) -> None:
expired_token = create_access_token(
"user-id-789",
settings,
jwt_settings,
expires_delta=timedelta(seconds=-5),
)
with pytest.raises(TokenExpiredError):
decode_access_token(expired_token, settings)
decode_access_token(expired_token, jwt_settings)
def test_decode_tampered_token() -> None:
settings = JWTSettings(secret_key="unit-test-secret")
token = create_access_token("user-id-321", settings)
def test_decode_tampered_token(jwt_settings: JWTSettings) -> None:
token = create_access_token("user-id-321", jwt_settings)
tampered = token[:-1] + ("a" if token[-1] != "a" else "b")
with pytest.raises(TokenDecodeError):
decode_access_token(tampered, settings)
decode_access_token(tampered, jwt_settings)