import unittest from pathlib import Path from tempfile import TemporaryDirectory from helpers import SiteTestCase from test_auth import PASSWORD, Clock, make_cfg from site_engine.services.auth import COOKIE_NAME, AuthService from site_engine.web.admin.handlers import ADMIN_HEADERS, AdminHandlers ORIGIN = {"Host": "admin.example", "Origin": "https://admin.example"} class AdminHandlersTest(SiteTestCase): def setUp(self): super().setUp() self.clock = Clock() self.auth = AuthService(make_cfg(), self.tmp / "state", clock=self.clock) self.h = AdminHandlers(self.auth, self.site, self.tmp / "dist") def cookie_value(self, result): header = result.cookies[0] return header.split(";")[0].split("=", 1)[1] def login(self, ip="1.1.1.1"): result = self.h.login_submit("admin", PASSWORD, ORIGIN, ip) self.assertEqual(result.status, 303, result.body) return self.cookie_value(result) def csrf_for(self, cookie): return self.auth.csrf_token(self.auth.authenticate(cookie)) def test_dashboard_requires_login(self): result = self.h.dashboard(None) self.assertEqual((result.status, result.headers["Location"]), (303, "/admin/login")) self.assertEqual(self.h.dashboard("v1.fake.fake").status, 303) def test_login_page_and_security_headers(self): result = self.h.login_page(None) self.assertEqual(result.status, 200) self.assertIn("name='password'", result.body) for name, value in ADMIN_HEADERS.items(): self.assertEqual(result.headers[name], value) self.assertIn("frame-ancestors 'none'", result.headers["Content-Security-Policy"]) self.assertEqual(result.headers["Cache-Control"], "no-store") def test_successful_login_sets_hardened_cookie(self): result = self.h.login_submit("admin", PASSWORD, ORIGIN, "1.1.1.1") self.assertEqual((result.status, result.headers["Location"]), (303, "/admin/")) cookie = result.cookies[0] self.assertTrue(cookie.startswith(f"{COOKIE_NAME}=")) for flag in ("HttpOnly", "SameSite=Strict", "Path=/admin", "Secure", "Max-Age=28800"): self.assertIn(flag, cookie) def test_wrong_password_gives_401_without_cookie_and_generic_message(self): result = self.h.login_submit("admin", "wrong password!!", ORIGIN, "1.1.1.1") self.assertEqual((result.status, result.cookies), (401, [])) self.assertIn("Неверный логин или пароль", result.body) other = self.h.login_submit("nobody", PASSWORD, ORIGIN, "1.1.1.2") self.assertIn("Неверный логин или пароль", other.body) def test_login_rejects_cross_origin_even_with_correct_password(self): for headers in ({"Host": "admin.example", "Origin": "https://evil.example"}, {"Host": "admin.example"}): result = self.h.login_submit("admin", PASSWORD, headers, "1.1.1.1") self.assertEqual((result.status, result.cookies), (403, [])) def test_throttled_login_returns_429_with_retry_after(self): for _ in range(5): self.h.login_submit("admin", "wrong password!!", ORIGIN, "6.6.6.6") result = self.h.login_submit("admin", PASSWORD, ORIGIN, "6.6.6.6") self.assertEqual(result.status, 429) self.assertGreater(int(result.headers["Retry-After"]), 0) self.assertEqual(result.cookies, []) def test_login_value_is_escaped_in_error_page(self): evil = "\">" result = self.h.login_submit(evil, "wrong password!!", ORIGIN, "1.1.1.1") self.assertNotIn("", result.body) self.assertIn("<script>", result.body) def test_password_is_never_echoed(self): result = self.h.login_submit("admin", "super-secret-guess!!", ORIGIN, "1.1.1.1") self.assertNotIn("super-secret-guess", result.body) def test_dashboard_lists_pages_collections_and_validation(self): result = self.h.dashboard(self.login()) self.assertEqual(result.status, 200) for text in ("Acme Studio", "Главная", "Контакты", "Черновик новой страницы", "status-draft", "опубликовано 3 из 3", "ошибок проверки: 0"): self.assertIn(text, result.body) self.assertIn("name='csrf'", result.body) self.assertIn("no-store", result.headers["Cache-Control"]) def test_dashboard_shows_the_absolute_paths_in_use(self): body = self.h.dashboard(self.login()).body for path in (self.site.resolve(), (self.tmp / "dist").resolve(), (self.tmp / "state").resolve()): self.assertIn(str(path), body) def test_missing_site_error_names_the_absolute_path(self): (self.site / "site.yaml").unlink() self.assertIn(str(self.site.resolve()), self.h.dashboard(self.login()).body) def test_dashboard_shows_broken_site_instead_of_crashing(self): (self.site / "site.yaml").unlink() result = self.h.dashboard(self.login()) self.assertEqual(result.status, 200) self.assertIn("Сайт не загружен", result.body) def test_logout_needs_csrf_and_same_origin(self): cookie = self.login() token = self.csrf_for(cookie) self.assertEqual(self.h.logout(cookie, "", ORIGIN, "1.1.1.1").status, 403) self.assertEqual(self.h.logout(cookie, "wrong", ORIGIN, "1.1.1.1").status, 403) evil = {"Host": "admin.example", "Origin": "https://evil.example"} self.assertEqual(self.h.logout(cookie, token, evil, "1.1.1.1").status, 403) self.assertEqual(self.h.dashboard(cookie).status, 200) # сессия цела def test_logout_clears_cookie_and_revokes_session(self): cookie = self.login() result = self.h.logout(cookie, self.csrf_for(cookie), ORIGIN, "1.1.1.1") self.assertEqual((result.status, result.headers["Location"]), (303, "/admin/login")) self.assertIn("Max-Age=0", result.cookies[0]) self.assertEqual(self.h.dashboard(cookie).status, 303) def test_logged_in_user_is_redirected_from_login_page(self): result = self.h.login_page(self.login()) self.assertEqual((result.status, result.headers["Location"]), (303, "/admin/")) def test_static_css_is_served(self): result = self.h.static_css() self.assertEqual(result.status, 200) self.assertTrue(result.content_type.startswith("text/css")) self.assertIn(".login", result.body) def test_no_inline_scripts_or_styles_in_templates(self): # CSP не разрешает inline: проверяем, что шаблоны её не нарушают for body in (self.h.login_page(None).body, self.h.dashboard(self.login()).body): self.assertNotIn("