"""Testy obnovy zapomenutého hesla přes fake SMTP a deterministické hodiny.""" from __future__ import annotations import logging import re import sqlite3 from dataclasses import dataclass from datetime import UTC, datetime, timedelta import pytest from flask import Flask from flask.testing import FlaskClient from poznavacky.mailer import MailDeliveryError from poznavacky.password_reset import hash_reset_token from poznavacky.security import RateLimiter, hash_password _CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"') _TOKEN_URL_RE = re.compile(r"/obnova-hesla/([A-Za-z0-9_-]+)") @dataclass class SentEmail: to: str subject: str body: str class FakeMailer: """In-memory SMTP odesílač pro offline testy.""" def __init__(self, *, fail: bool = False) -> None: self.fail = fail self.sent: list[SentEmail] = [] def send_email(self, *, to: str, subject: str, body: str) -> None: if self.fail: raise MailDeliveryError("Simulovaný výpadek SMTP.") self.sent.append(SentEmail(to=to, subject=subject, body=body)) def _csrf(client: FlaskClient, path: str) -> str: resp = client.get(path) assert resp.status_code == 200 match = _CSRF_RE.search(resp.get_data(as_text=True)) assert match is not None return match.group(1) def _extract_token(body: str) -> str: match = _TOKEN_URL_RE.search(body) assert match is not None, f"Token nenalezen v těle zprávy: {body!r}" return match.group(1) def _insert_user( db: sqlite3.Connection, *, email: str, password: str, stav: str = "schvaleny", ) -> int: cur = db.execute( """ INSERT INTO uzivatele ( email, heslo_hash, jmeno, prijmeni, role, stav ) VALUES (?, ?, 'Petr', 'Ukazkovy', 'zak', ?) """, (email.lower(), hash_password(password), stav), ) db.commit() assert cur.lastrowid is not None return int(cur.lastrowid) def test_reset_request_anti_enumeration_and_hashed_storage( app: Flask, client: FlaskClient, db: sqlite3.Connection, ) -> None: fake_mailer = FakeMailer() app.extensions["mailer"] = fake_mailer now = datetime(2026, 5, 1, 12, 0, 0, tzinfo=UTC) app.extensions["utc_clock"] = lambda: now _insert_user( db, email="aktivni@example.test", password="heslo-1234", stav="schvaleny", ) _insert_user( db, email="cekajici@example.test", password="heslo-1234", stav="ceka_na_schvaleni", ) _insert_user( db, email="zamitnuty@example.test", password="heslo-1234", stav="zamitnuty", ) _insert_user( db, email="deaktivovany@example.test", password="heslo-1234", stav="deaktivovany", ) token = _csrf(client, "/obnova-hesla") resp_ok = client.post( "/obnova-hesla", data={"csrf_token": token, "email": "AKTIVNI@example.test"}, ) resp_pending = client.post( "/obnova-hesla", data={"csrf_token": token, "email": "cekajici@example.test"}, ) resp_missing = client.post( "/obnova-hesla", data={"csrf_token": token, "email": "neexistuje@example.test"}, ) resp_rejected = client.post( "/obnova-hesla", data={"csrf_token": token, "email": "zamitnuty@example.test"}, ) resp_deactivated = client.post( "/obnova-hesla", data={"csrf_token": token, "email": "deaktivovany@example.test"}, ) # Všechny odpovědi jsou identické (anti-enumerace). bodies = [ r.get_data(as_text=True) for r in ( resp_ok, resp_pending, resp_missing, resp_rejected, resp_deactivated, ) ] assert all( r.status_code == 200 for r in ( resp_ok, resp_pending, resp_missing, resp_rejected, resp_deactivated, ) ) assert len(set(bodies)) == 1 # Odeslány jen 2 e-maily (schvaleny + ceka_na_schvaleni). assert [m.to for m in fake_mailer.sent] == [ "aktivni@example.test", "cekajici@example.test", ] raw_token = _extract_token(fake_mailer.sent[0].body) rows = db.execute("SELECT * FROM tokeny_hesla ORDER BY id").fetchall() assert len(rows) == 2 assert rows[0]["token_hash"] == hash_reset_token(raw_token) assert rows[0]["token_hash"] != raw_token assert rows[0]["pouzito_at"] is None assert rows[0]["vyprsi_at"] == "2026-05-01T13:00:00Z" def test_reset_completion_invalidates_old_session_and_is_single_use( app: Flask, db: sqlite3.Connection, ) -> None: fake_mailer = FakeMailer() app.extensions["mailer"] = fake_mailer now = [datetime(2026, 5, 1, 12, 0, 0, tzinfo=UTC)] app.extensions["utc_clock"] = lambda: now[0] _insert_user( db, email="reset@example.test", password="stare-heslo-123", stav="schvaleny", ) # Uživatel je přihlášen ve staré session. old_session_client = app.test_client() login_csrf = _csrf(old_session_client, "/prihlaseni") login_resp = old_session_client.post( "/prihlaseni", data={ "csrf_token": login_csrf, "email": "reset@example.test", "heslo": "stare-heslo-123", }, ) assert login_resp.status_code == 302 assert old_session_client.get("/profil").status_code == 200 # Druhý klient požádá o reset dvakrát; první token musí být zneplatněn. reset_client = app.test_client() req_csrf = _csrf(reset_client, "/obnova-hesla") assert ( reset_client.post( "/obnova-hesla", data={"csrf_token": req_csrf, "email": "reset@example.test"}, ).status_code == 200 ) assert ( reset_client.post( "/obnova-hesla", data={"csrf_token": req_csrf, "email": "reset@example.test"}, ).status_code == 200 ) assert len(fake_mailer.sent) == 2 first_token = _extract_token(fake_mailer.sent[0].body) second_token = _extract_token(fake_mailer.sent[1].body) assert first_token != second_token # První token už nefunguje. assert reset_client.get(f"/obnova-hesla/{first_token}").status_code == 400 # Krátké heslo na druhém tokenu selže, ale token zůstane platný. confirm_csrf = _csrf(reset_client, f"/obnova-hesla/{second_token}") too_short = reset_client.post( f"/obnova-hesla/{second_token}", data={"csrf_token": confirm_csrf, "heslo": "kratke"}, ) assert too_short.status_code == 400 # Platné nové heslo úspěšně změní heslo a označí token jako použitý. done = reset_client.post( f"/obnova-hesla/{second_token}", data={"csrf_token": confirm_csrf, "heslo": "nove-heslo-456"}, ) assert done.status_code == 302 # Stará session už neplatí. assert old_session_client.get("/profil").status_code == 302 # Opakované použití téhož tokenu je odmítnuto. reuse_csrf = _csrf(reset_client, "/prihlaseni") reuse = reset_client.post( f"/obnova-hesla/{second_token}", data={"csrf_token": reuse_csrf, "heslo": "dalsi-heslo-789"}, ) assert reuse.status_code == 400 # Staré heslo nefunguje, nové heslo funguje. old_try = reset_client.post( "/prihlaseni", data={ "csrf_token": reuse_csrf, "email": "reset@example.test", "heslo": "stare-heslo-123", }, ) assert old_try.status_code == 401 new_try = reset_client.post( "/prihlaseni", data={ "csrf_token": reuse_csrf, "email": "reset@example.test", "heslo": "nove-heslo-456", }, ) assert new_try.status_code == 302 def test_expired_and_unknown_tokens_are_rejected( app: Flask, client: FlaskClient, db: sqlite3.Connection, ) -> None: fake_mailer = FakeMailer() app.extensions["mailer"] = fake_mailer now = [datetime(2026, 5, 1, 12, 0, 0, tzinfo=UTC)] app.extensions["utc_clock"] = lambda: now[0] _insert_user( db, email="expirace@example.test", password="puvodni-heslo", stav="schvaleny", ) csrf = _csrf(client, "/obnova-hesla") client.post( "/obnova-hesla", data={"csrf_token": csrf, "email": "expirace@example.test"}, ) raw_token = _extract_token(fake_mailer.sent[0].body) # Posun hodin za platnost 60 minut. now[0] = now[0] + timedelta(minutes=61) assert client.get(f"/obnova-hesla/{raw_token}").status_code == 400 post_expired = client.post( f"/obnova-hesla/{raw_token}", data={"csrf_token": csrf, "heslo": "nove-heslo-999"}, ) assert post_expired.status_code == 400 # Neznámý token. assert client.get("/obnova-hesla/neexistujici-token").status_code == 400 def test_reset_request_rate_limit_and_smtp_failure_handling( app: Flask, client: FlaskClient, db: sqlite3.Connection, caplog: pytest.LogCaptureFixture, ) -> None: mono = [50.0] app.extensions["rate_limiter"] = RateLimiter(clock=lambda: mono[0]) app.config["RATE_LIMITS"]["password_reset"] = (2, 300) app.extensions["mailer"] = FakeMailer(fail=True) _insert_user( db, email="chyba.smtp@example.test", password="heslo-1234", stav="schvaleny", ) csrf = _csrf(client, "/obnova-hesla") with caplog.at_level(logging.ERROR): first = client.post( "/obnova-hesla", data={"csrf_token": csrf, "email": "chyba.smtp@example.test"}, ) second = client.post( "/obnova-hesla", data={"csrf_token": csrf, "email": "chyba.smtp@example.test"}, ) # I při výpadku SMTP vrací neutrální 200 bez pádu a bez úniku tokenu. assert first.status_code == 200 assert second.status_code == 200 assert "/obnova-hesla/" not in caplog.text # 3. pokus narazí na rate limit 429. third = client.post( "/obnova-hesla", data={"csrf_token": csrf, "email": "chyba.smtp@example.test"}, ) assert third.status_code == 429 assert int(third.headers["Retry-After"]) >= 1