import re import time from pathlib import Path import pytest from fastapi.testclient import TestClient from estimator.api.app import create_app from estimator.config.settings import Settings from estimator.domain.enums import Role from estimator.passwords import hash_password from tests.fakes import AutoGateway from tests.unit.agent.conftest import ( DOC_WBS, clarify_out, decompose_out, estimate_out, q, ) PW = {"alex": "alex-password-1", "bob": "bob-password-22"} TOKEN_RE = re.compile(r'name="csrf_token" value="([^"]+)"') SECRET = "s" * 48 ROOT = Path(__file__).resolve().parents[3] def users_env() -> str: return ",".join(f"{u}:{hash_password(p, iterations=1000)}" for u, p in PW.items()) def make_ui(monkeypatch, dsn, gateway=None, **env): base = { "EST_DATABASE__DSN": dsn, "EST_LLM__ANTHROPIC__API_KEY": "sk-test", "EST_API__KEYS": "bot:botkey", "EST_WEB__ENABLED": "true", "EST_WEB__SESSION_SECRET": SECRET, "EST_WEB__USERS": users_env(), } base.update(env) for k, v in base.items(): monkeypatch.setenv(k, v) # Secure cookies are only sent back over https, so that test client talks https base = "https://testserver" if env.get("EST_WEB__COOKIE_SECURE") == "true" else "http://testserver" return TestClient( create_app(Settings(), gateway=gateway or AutoGateway()), base_url=base, follow_redirects=False ) def token(client, path="/ui/login") -> str: r = client.get(path) found = TOKEN_RE.search(r.text) assert found, f"no csrf token on {path}: {r.status_code}" return found.group(1) def login(client, user="alex", next_="/ui/estimates/new"): t = token(client) r = client.post("/ui/login", data={"username": user, "password": PW[user], "csrf_token": t, "next": next_}) assert r.status_code == 303, r.text return r def page_token(client, path="/ui/estimates/new") -> str: return token(client, path) def create_via_ui(client, text="Бот для Telegram с ИИ", **extra): t = page_token(client) r = client.post("/ui/estimates", data={"requirements": text, "csrf_token": t, **extra}) assert r.status_code == 303, r.text return r.headers["location"].rsplit("/", 1)[-1].split("?")[0] def wait_done(client, eid, timeout=8.0, until=("done", "failed", "needs_input")): deadline = time.time() + timeout while time.time() < deadline: html = client.get(f"/ui/estimates/{eid}/panel").text for s in until: if 'class="badge' in html and _status_label(s) in html.split("")[0]: return html time.sleep(0.03) raise AssertionError("timeout waiting for the panel") def _status_label(status): return {"done": "Готово", "failed": "Ошибка", "needs_input": "Нужны ответы", "running": "Считается", "pending": "В очереди"}[status] @pytest.fixture def ui(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: login(c) yield c # ================================================================== authentication def test_anonymous_is_sent_to_login_with_a_safe_next(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: r = c.get("/ui/estimates?status=done") assert r.status_code == 303 assert r.headers["location"] == "/ui/login?next=%2Fui%2Festimates%3Fstatus%3Ddone" assert c.get("/ui/estimates/new").status_code == 303 assert c.get("/ui/").status_code == 303 and "/login" in c.get("/ui/").headers["location"] def test_htmx_request_without_session_gets_hx_redirect_not_a_fragment(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: r = c.get("/ui/estimates/x/panel", headers={"HX-Request": "true"}) assert r.status_code == 200 and r.headers["HX-Redirect"].startswith("/ui/login") assert r.text == "" def test_login_page_is_public_and_has_no_nav(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: r = c.get("/ui/login") assert r.status_code == 200 and "Пароль" in r.text and "Новая оценка" not in r.text def test_login_requires_csrf(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: r = c.post("/ui/login", data={"username": "alex", "password": PW["alex"]}) assert r.status_code == 403 c.get("/ui/login") # session now has a token, but the form did not send it assert c.post("/ui/login", data={"username": "alex", "password": PW["alex"], "csrf_token": "forged"}).status_code == 403 def test_successful_login_sets_a_hardened_cookie(monkeypatch, dsn): with make_ui(monkeypatch, dsn, EST_WEB__COOKIE_SECURE="true") as c: t = token(c) r = c.post("/ui/login", data={"username": "alex", "password": PW["alex"], "csrf_token": t}) assert r.status_code == 303 and r.headers["location"] == "/ui/estimates/new" cookie = r.headers["set-cookie"].lower() assert "est_session=" in cookie and "httponly" in cookie and "samesite=lax" in cookie and "secure" in cookie assert "max-age=28800" in cookie def test_login_follows_safe_next_and_ignores_evil_next(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: r = login(c, next_="/ui/market") assert r.headers["location"] == "/ui/market" with make_ui(monkeypatch, dsn) as c: r = login(c, next_="https://evil.example/") assert r.headers["location"] == "/ui/estimates/new" def test_wrong_password_and_unknown_user_look_the_same(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c: t = token(c) a = c.post("/ui/login", data={"username": "alex", "password": "nope", "csrf_token": t}) b = c.post("/ui/login", data={"username": "ghost", "password": "nope", "csrf_token": t}) assert a.status_code == b.status_code == 401 assert "Неверное имя пользователя или пароль" in a.text and "Неверное имя пользователя или пароль" in b.text assert "est_session" not in (a.headers.get("set-cookie", "").replace("est_session=;", "")) or "user" not in a.text def test_brute_force_is_throttled(monkeypatch, dsn): with make_ui(monkeypatch, dsn, EST_WEB__LOGIN_MAX_ATTEMPTS="3") as c: t = token(c) for _ in range(3): assert c.post("/ui/login", data={"username": "alex", "password": "bad", "csrf_token": t}).status_code == 401 r = c.post("/ui/login", data={"username": "alex", "password": PW["alex"], "csrf_token": t}) assert r.status_code == 429 and int(r.headers["Retry-After"]) > 0 assert "Слишком много попыток" in r.text # even the right password is refused while blocked def test_logout_ends_the_session(ui): t = page_token(ui) assert ui.get("/ui/estimates/new").status_code == 200 assert ui.post("/ui/logout", data={}).status_code == 403 # needs CSRF too assert ui.post("/ui/logout", data={"csrf_token": t}).status_code == 303 assert ui.get("/ui/estimates/new").status_code == 303 def test_login_page_redirects_when_already_signed_in(ui): assert ui.get("/ui/login").status_code == 303 def test_tampered_cookie_is_anonymous(ui): ui.cookies.set("est_session", "garbage.value.here", domain="testserver.local") ui.cookies.clear() assert ui.get("/ui/estimates/new").status_code == 303 def test_removed_user_loses_access_even_with_a_valid_cookie(monkeypatch, dsn): with make_ui(monkeypatch, dsn) as c1: login(c1) cookie = c1.cookies.get("est_session") only_bob = f"bob:{hash_password(PW['bob'], iterations=1000)}" with make_ui(monkeypatch, dsn, EST_WEB__USERS=only_bob) as c2: c2.cookies.set("est_session", cookie) assert c2.get("/ui/estimates/new").status_code == 303 # ================================================================== CSRF everywhere @pytest.mark.parametrize( "path", [ "/ui/estimates", "/ui/estimates/abc/answers", "/ui/estimates/abc/recalculate", "/ui/estimates/abc/tasks/t1", "/ui/logout", ], ) def test_state_changing_routes_reject_missing_or_wrong_csrf(ui, path): assert ui.post(path, data={"requirements": "x"}).status_code == 403 assert ui.post(path, data={"requirements": "x", "csrf_token": "wrong"}).status_code == 403 assert ui.post(path, headers={"X-CSRF-Token": "wrong"}).status_code == 403 def test_csrf_error_for_htmx_is_an_alert_in_the_flash_area(ui): r = ui.post("/ui/estimates/abc/recalculate", headers={"HX-Request": "true"}) assert r.status_code == 403 and r.headers["HX-Retarget"] == "#flash" assert "Обновите страницу" in r.text # ================================================================== the main flow def test_new_page_and_create_redirects_to_the_detail_page(ui): page = ui.get("/ui/estimates/new") assert page.status_code == 200 and "Описание задачи" in page.text and "Новая оценка" in page.text eid = create_via_ui(ui) assert len(eid) == 32 def test_result_page_shows_the_numbers_from_the_doc_example(ui): eid = create_via_ui(ui, "Бот Telegram, MAX и VK с ИИ и amoCRM") html = wait_done(ui, eid) assert "370\u202f000\u00a0₽" in html # the fixed price, reserve included assert "336\u202f000\u00a0₽" in html # without the reserve assert "397\u202f000" not in html # the old double-counted figure assert "144,7\u00a0ч" in html and "16,7%" in html # hours and the margin implied by a 20% markup assert "минимальный резерв" in html and "Фиксированная цена" in html assert "В границах рынка" in html and "badge ok" in html assert html.count('