58 lines
2.3 KiB
Python
58 lines
2.3 KiB
Python
|
|
"""不存在的账号仍做哈希校验,但永远不能通过登录。"""
|
||
|
|
|
||
|
|
from types import SimpleNamespace
|
||
|
|
from unittest.mock import Mock
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from app.core.exceptions import BadRequestError
|
||
|
|
from app.services import auth_service
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize("exists", [True, False])
|
||
|
|
def test_凭据错误统一校验并记失败(monkeypatch, exists):
|
||
|
|
user = SimpleNamespace(id=1, password="stored-hash") if exists else None
|
||
|
|
monkeypatch.setattr(auth_service.user_repository, "get_by_username", lambda *_: user)
|
||
|
|
monkeypatch.setattr(auth_service.login_limiter, "is_locked", lambda *_: False)
|
||
|
|
monkeypatch.setattr(auth_service.captcha_service, "verify_and_consume", lambda *_: True)
|
||
|
|
verify = Mock(return_value=False)
|
||
|
|
failure = Mock()
|
||
|
|
record = Mock()
|
||
|
|
monkeypatch.setattr(auth_service, "verify_password", verify)
|
||
|
|
monkeypatch.setattr(auth_service.login_limiter, "record_failure", failure)
|
||
|
|
monkeypatch.setattr(auth_service, "_record", record)
|
||
|
|
with pytest.raises(BadRequestError, match=auth_service.INVALID_CREDENTIALS):
|
||
|
|
auth_service.login(
|
||
|
|
Mock(),
|
||
|
|
username="unknown",
|
||
|
|
password="wrong",
|
||
|
|
captcha_id="id",
|
||
|
|
captcha_code="ABCD",
|
||
|
|
ip=None,
|
||
|
|
user_agent=None,
|
||
|
|
)
|
||
|
|
verify.assert_called_once_with(
|
||
|
|
"wrong", user.password if user else auth_service._DUMMY_PASSWORD_HASH
|
||
|
|
)
|
||
|
|
failure.assert_called_once_with("unknown")
|
||
|
|
assert record.call_args.kwargs["success"] is False
|
||
|
|
|
||
|
|
|
||
|
|
def test_输入匹配假哈希也不能登录(monkeypatch):
|
||
|
|
monkeypatch.setattr(auth_service.user_repository, "get_by_username", lambda *_: None)
|
||
|
|
monkeypatch.setattr(auth_service.login_limiter, "is_locked", lambda *_: False)
|
||
|
|
monkeypatch.setattr(auth_service.captcha_service, "verify_and_consume", lambda *_: True)
|
||
|
|
monkeypatch.setattr(auth_service, "verify_password", lambda *_: True)
|
||
|
|
monkeypatch.setattr(auth_service.login_limiter, "record_failure", Mock())
|
||
|
|
monkeypatch.setattr(auth_service, "_record", Mock())
|
||
|
|
with pytest.raises(BadRequestError, match=auth_service.INVALID_CREDENTIALS):
|
||
|
|
auth_service.login(
|
||
|
|
Mock(),
|
||
|
|
username="unknown",
|
||
|
|
password="dummy",
|
||
|
|
captcha_id="id",
|
||
|
|
captcha_code="ABCD",
|
||
|
|
ip=None,
|
||
|
|
user_agent=None,
|
||
|
|
)
|