Files
flexly-cms/tests/test_auth.py
T
2026-11-09 15:42:27 +03:00

227 lines
9.3 KiB
Python

import json
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from site_engine.services import auth as auth_mod
from site_engine.services.auth import (
AuthConfig, AuthError, AuthService, ConfigError, LoginThrottle, hash_password, is_same_origin,
verify_password,
)
PASSWORD = "correct horse battery"
FAST = dict(n=2**10) # быстрый scrypt для тестов; в проде параметры по умолчанию
class Clock:
def __init__(self, t=1_800_000_000.0):
self.t = t
def __call__(self):
return self.t
def make_cfg(**kw):
base = dict(login="admin", password_hash=hash_password(PASSWORD, **FAST), secret=b"k" * 40)
base.update(kw)
return AuthConfig(**base)
class PasswordTest(unittest.TestCase):
def test_hash_and_verify(self):
h = hash_password(PASSWORD, **FAST)
self.assertTrue(h.startswith("scrypt$1024$8$1$"))
self.assertTrue(verify_password(PASSWORD, h))
self.assertFalse(verify_password(PASSWORD + "x", h))
def test_salts_differ(self):
self.assertNotEqual(hash_password(PASSWORD, **FAST), hash_password(PASSWORD, **FAST))
def test_short_password_rejected(self):
with self.assertRaises(ValueError):
hash_password("short", **FAST)
def test_malformed_hash_is_just_false(self):
for bad in ("", "x", "scrypt$1$2$3$4", "bcrypt$1024$8$1$aa$bb", "scrypt$99999999$8$1$aa$bb",
"scrypt$abc$8$1$aa$bb"):
self.assertFalse(verify_password(PASSWORD, bad), bad)
def test_default_parameters_are_strong(self):
self.assertGreaterEqual(auth_mod.SCRYPT_N, 2**15)
class ConfigTest(unittest.TestCase):
ENV = {"SITE_ADMIN_PASSWORD_HASH": "scrypt$1024$8$1$aa$bb", "SITE_SECRET_KEY": "s" * 32}
def test_defaults(self):
cfg = AuthConfig.from_env(self.ENV)
self.assertEqual((cfg.login, cfg.session_hours, cfg.cookie_secure), ("admin", 8.0, True))
def test_missing_or_weak_values_fail_closed(self):
for patch in ({"SITE_ADMIN_PASSWORD_HASH": ""}, {"SITE_ADMIN_PASSWORD_HASH": "plain-password"},
{"SITE_SECRET_KEY": "short"}, {"SITE_SESSION_HOURS": "abc"},
{"SITE_SESSION_HOURS": "0"}, {"SITE_ADMIN_LOGIN": " "}):
with self.assertRaises(ConfigError, msg=str(patch)):
AuthConfig.from_env({**self.ENV, **patch})
def test_cookie_secure_can_be_disabled_for_local_dev(self):
self.assertFalse(AuthConfig.from_env({**self.ENV, "SITE_COOKIE_SECURE": "0"}).cookie_secure)
class AuthServiceTest(unittest.TestCase):
def setUp(self):
self._tmp = TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.state = Path(self._tmp.name)
self.clock = Clock()
self.svc = AuthService(make_cfg(), self.state, clock=self.clock)
def login(self, ip="1.1.1.1"):
return self.svc.login("admin", PASSWORD, ip)
def test_login_roundtrip(self):
principal = self.svc.authenticate(self.login())
self.assertEqual((principal.login, principal.role), ("admin", "admin"))
def test_wrong_login_and_wrong_password_are_indistinguishable(self):
errors = []
for login, password in (("root", PASSWORD), ("admin", "wrong password!!")):
with self.assertRaises(AuthError) as ctx:
self.svc.login(login, password, "2.2.2.2")
errors.append((ctx.exception.code, ctx.exception.retry_after))
self.assertEqual(errors[0], errors[1])
def test_password_is_verified_even_for_unknown_login(self):
calls = []
original = auth_mod.verify_password
auth_mod.verify_password = lambda *a, **k: calls.append(1) or original(*a, **k)
try:
with self.assertRaises(AuthError):
self.svc.login("nobody", PASSWORD, "3.3.3.3")
finally:
auth_mod.verify_password = original
self.assertEqual(len(calls), 1)
def test_tampered_cookie_is_rejected(self):
version, payload, sig = self.login().split(".")
for bad in (f"{version}.{payload}.{sig[:-2]}AA", f"{version}.{payload}x.{sig}", "v1.a.b", "garbage", "", None):
self.assertIsNone(self.svc.authenticate(bad), bad)
def test_cookie_from_another_secret_is_rejected(self):
other = AuthService(make_cfg(secret=b"z" * 40), self.state, clock=self.clock)
self.assertIsNone(other.authenticate(self.login()))
def test_expiry(self):
cookie = self.login()
self.clock.t += 8 * 3600 - 1
self.assertIsNotNone(self.svc.authenticate(cookie))
self.clock.t += 2
self.assertIsNone(self.svc.authenticate(cookie))
def test_logout_revokes_every_issued_cookie_and_survives_restart(self):
first, second = self.login("1.1.1.1"), self.login("4.4.4.4")
principal = self.svc.authenticate(first)
self.svc.logout(principal)
self.assertIsNone(self.svc.authenticate(first))
self.assertIsNone(self.svc.authenticate(second))
restarted = AuthService(make_cfg(), self.state, clock=self.clock)
self.assertIsNone(restarted.authenticate(first))
self.assertIsNotNone(restarted.authenticate(restarted.login("admin", PASSWORD, "5.5.5.5")))
def test_csrf_is_bound_to_session(self):
a = self.svc.authenticate(self.login())
b = self.svc.authenticate(self.login())
token = self.svc.csrf_token(a)
self.assertTrue(self.svc.verify_csrf(a, token))
self.assertFalse(self.svc.verify_csrf(b, token))
self.assertFalse(self.svc.verify_csrf(a, ""))
self.assertFalse(self.svc.verify_csrf(a, None))
self.assertFalse(self.svc.verify_csrf(a, token + "x"))
def test_session_and_csrf_keys_are_separated(self):
principal = self.svc.authenticate(self.login())
self.assertNotIn(self.svc.csrf_token(principal), self.login())
def test_audit_has_events_but_no_secrets(self):
with self.assertRaises(AuthError):
self.svc.login("admin-guess-xyz", "hunter2hunter2", "9.9.9.9")
principal = self.svc.authenticate(self.login())
self.svc.logout(principal, "1.1.1.1")
raw = (self.state / "audit.jsonl").read_text(encoding="utf-8")
events = [json.loads(line)["event"] for line in raw.splitlines()]
self.assertEqual(events, ["login_fail", "login_ok", "logout"])
for secret in ("hunter2hunter2", "admin-guess-xyz", PASSWORD):
self.assertNotIn(secret, raw)
self.assertEqual(oct((self.state / "audit.jsonl").stat().st_mode & 0o777), "0o600")
class ThrottleTest(unittest.TestCase):
def setUp(self):
self._tmp = TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.clock = Clock()
self.svc = AuthService(make_cfg(), Path(self._tmp.name), clock=self.clock)
def fail(self, ip, times):
for _ in range(times):
with self.assertRaises(AuthError):
self.svc.login("admin", "wrong password!!", ip)
def test_blocks_after_max_failures_even_with_correct_password(self):
self.fail("7.7.7.7", 5)
with self.assertRaises(AuthError) as ctx:
self.svc.login("admin", PASSWORD, "7.7.7.7")
self.assertEqual(ctx.exception.code, "throttled")
self.assertGreater(ctx.exception.retry_after, 0)
def test_block_expires_with_the_window(self):
self.fail("7.7.7.7", 5)
self.clock.t += 901
self.assertIsNotNone(self.svc.login("admin", PASSWORD, "7.7.7.7"))
def test_other_ips_are_not_affected(self):
self.fail("7.7.7.7", 5)
self.assertIsNotNone(self.svc.login("admin", PASSWORD, "8.8.8.8"))
def test_global_limit_stops_distributed_guessing(self):
for i in range(30):
with self.assertRaises(AuthError):
self.svc.login("admin", "wrong password!!", f"10.0.0.{i}")
with self.assertRaises(AuthError) as ctx:
self.svc.login("admin", PASSWORD, "10.9.9.9")
self.assertEqual(ctx.exception.code, "throttled")
def test_success_resets_ip_counter(self):
self.fail("7.7.7.7", 4)
self.svc.login("admin", PASSWORD, "7.7.7.7")
self.fail("7.7.7.7", 4) # снова четыре, блокировки нет
def test_throttle_unit(self):
c = Clock()
t = LoginThrottle(2, 60, 10, c)
t.fail("a")
self.assertIsNone(t.blocked("a"))
t.fail("a")
self.assertEqual(t.blocked("a"), 61)
c.t += 61
self.assertIsNone(t.blocked("a"))
class OriginTest(unittest.TestCase):
def test_same_origin(self):
self.assertTrue(is_same_origin({"Host": "admin.example", "Origin": "https://admin.example"}))
self.assertTrue(is_same_origin({"host": "admin.example", "referer": "https://admin.example/admin/login"}))
def test_cross_origin_and_missing_headers_rejected(self):
self.assertFalse(is_same_origin({"Host": "admin.example", "Origin": "https://evil.example"}))
self.assertFalse(is_same_origin({"Host": "admin.example", "Origin": "null"}))
self.assertFalse(is_same_origin({"Host": "admin.example"}))
self.assertFalse(is_same_origin({"Origin": "https://admin.example"}))
def test_public_host_override_for_proxy(self):
self.assertTrue(is_same_origin({"Host": "127.0.0.1:8000", "Origin": "https://admin.example"}, "admin.example"))
if __name__ == "__main__":
unittest.main()