Účty, schvalování žáků v /admin a obnova hesla přes SMTP (#11)
Implementuje účty, role, schvalování žáků v `/admin` a obnovu hesla přes SMTP podle OpenSpec změny `ucty-schvalovani-reset-hesla`. - Registrace žáků (`/registrace`), přihlášení (`/prihlaseni`), odhlášení (`/odhlaseni`), profil (`/profil`) a chráněný třídní pohled (`/trida`). - Hashování hesel (`scrypt`), podepsaná session cookie (`HttpOnly`, `SameSite=Lax`, za HTTPS `Secure`), okamžité zneplatnění session při změně hesla či zablokování účtu, globální CSRF kontrola, in-memory rate limiting a volitelný `ProxyFix`. - Atomická inicializace prvního účtu učitelky z `POZNAVACKY_ADMIN_EMAIL` / `POZNAVACKY_ADMIN_PASSWORD` při startu nad prázdnou tabulkou `uzivatele`. - Administrace `/admin`, `/admin/tridy` a `/admin/zaci` (správa tříd, fronta schvalování, schválení, zamítnutí, přeřazení, deaktivace/aktivace s ochranou účtů učitelky). - Obnova zapomenutého hesla (`/obnova-hesla`, `/obnova-hesla/<token>`) s jednorázovým SHA-256 hashovaným tokenem (migrace `0002_token_hash_index.sql`), anti-enumerací a SMTP odesílačem (STARTTLS / `SMTP_SSL`). - Synchronizovány specifikace `user-auth`, `student-approval`, `password-reset` do `openspec/specs/` a změna archivována. - Ověřeno offline: `.venv/bin/pytest -W error` (52 passed) a `.venv/bin/ruff check .`. Closes #2 Reviewed-on: #11 Co-authored-by: David Spáčil <spacildavi@gmail.com>
This commit was merged in pull request #11.
This commit is contained in:
1 parent
c413e884d0
commit
5fcfe72272
36 files changed
+4921
-3
No files matched your search
@@ -0,0 +1,368 @@
|
||||
"""Testy administrace tříd a schvalování žáků v /admin."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from flask import Flask
|
||||
from flask.testing import FlaskClient
|
||||
|
||||
from poznavacky.security import hash_password
|
||||
|
||||
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
||||
|
||||
|
||||
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 _insert_user(
|
||||
db: sqlite3.Connection,
|
||||
*,
|
||||
email: str,
|
||||
password: str,
|
||||
jmeno: str,
|
||||
prijmeni: str,
|
||||
role: str = "zak",
|
||||
stav: str = "ceka_na_schvaleni",
|
||||
trida_id: int | None = None,
|
||||
prezdivka: str | None = None,
|
||||
) -> int:
|
||||
cur = db.execute(
|
||||
"""
|
||||
INSERT INTO uzivatele (
|
||||
email, heslo_hash, jmeno, prijmeni, prezdivka,
|
||||
role, stav, trida_id
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
email.lower(),
|
||||
hash_password(password),
|
||||
jmeno,
|
||||
prijmeni,
|
||||
prezdivka,
|
||||
role,
|
||||
stav,
|
||||
trida_id,
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
assert cur.lastrowid is not None
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def _login(client: FlaskClient, email: str, password: str) -> None:
|
||||
token = _csrf(client, "/prihlaseni")
|
||||
resp = client.post(
|
||||
"/prihlaseni",
|
||||
data={"csrf_token": token, "email": email, "heslo": password},
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
|
||||
|
||||
def test_admin_access_restricted_to_teacher(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
_insert_user(
|
||||
db,
|
||||
email="zak@example.test",
|
||||
password="heslo-zak",
|
||||
jmeno="Petr",
|
||||
prijmeni="Ukazkovy",
|
||||
role="zak",
|
||||
stav="schvaleny",
|
||||
)
|
||||
_insert_user(
|
||||
db,
|
||||
email="ucitelka@example.test",
|
||||
password="heslo-ucitelka",
|
||||
jmeno="Jana",
|
||||
prijmeni="Testova",
|
||||
role="ucitelka",
|
||||
stav="schvaleny",
|
||||
)
|
||||
|
||||
# Nepřihlášený → přesměrování na přihlášení.
|
||||
assert client.get("/admin").status_code == 302
|
||||
assert client.get("/admin/tridy").status_code == 302
|
||||
assert client.get("/admin/zaci").status_code == 302
|
||||
|
||||
# Schválený žák → 403.
|
||||
_login(client, "zak@example.test", "heslo-zak")
|
||||
assert client.get("/admin").status_code == 403
|
||||
assert client.get("/admin/tridy").status_code == 403
|
||||
assert client.get("/admin/zaci").status_code == 403
|
||||
|
||||
# Učitelka → 200.
|
||||
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||
assert client.get("/admin").status_code == 200
|
||||
assert client.get("/admin/tridy").status_code == 200
|
||||
assert client.get("/admin/zaci").status_code == 200
|
||||
|
||||
|
||||
def test_class_crud_and_deactivation_hides_from_registration(
|
||||
app: Flask,
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
_insert_user(
|
||||
db,
|
||||
email="ucitelka@example.test",
|
||||
password="heslo-ucitelka",
|
||||
jmeno="Jana",
|
||||
prijmeni="Testova",
|
||||
role="ucitelka",
|
||||
stav="schvaleny",
|
||||
)
|
||||
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||
|
||||
# Vytvoření třídy 6.A.
|
||||
token = _csrf(client, "/admin/tridy")
|
||||
created = client.post(
|
||||
"/admin/tridy",
|
||||
data={"csrf_token": token, "nazev": "6.A", "rocnik": "6"},
|
||||
)
|
||||
assert created.status_code == 302
|
||||
|
||||
cls_row = db.execute("SELECT * FROM tridy").fetchone()
|
||||
assert cls_row is not None
|
||||
assert cls_row["nazev"] == "6.A"
|
||||
assert cls_row["rocnik"] == 6
|
||||
assert cls_row["aktivni"] == 1
|
||||
class_id = int(cls_row["id"])
|
||||
|
||||
# Přejmenování na 6.B.
|
||||
edited = client.post(
|
||||
f"/admin/tridy/{class_id}/upravit",
|
||||
data={"csrf_token": token, "nazev": "6.B", "rocnik": "6"},
|
||||
)
|
||||
assert edited.status_code == 302
|
||||
assert (
|
||||
db.execute(
|
||||
"SELECT nazev FROM tridy WHERE id = ?",
|
||||
(class_id,),
|
||||
).fetchone()["nazev"]
|
||||
== "6.B"
|
||||
)
|
||||
|
||||
# Nabízí se při registraci.
|
||||
assert "6.B" in client.get("/registrace").get_data(as_text=True)
|
||||
|
||||
# Přiřazení žáka do 6.B a následná deaktivace třídy.
|
||||
student_id = _insert_user(
|
||||
db,
|
||||
email="zak6b@example.test",
|
||||
password="heslo-zak6b",
|
||||
jmeno="Anna",
|
||||
prijmeni="Novotna",
|
||||
stav="schvaleny",
|
||||
trida_id=class_id,
|
||||
)
|
||||
toggled = client.post(
|
||||
f"/admin/tridy/{class_id}/aktivni",
|
||||
data={"csrf_token": token},
|
||||
)
|
||||
assert toggled.status_code == 302
|
||||
|
||||
cls_after = db.execute(
|
||||
"SELECT aktivni FROM tridy WHERE id = ?",
|
||||
(class_id,),
|
||||
).fetchone()
|
||||
assert cls_after["aktivni"] == 0
|
||||
|
||||
# Zmizí z registrace, ale žákovi zůstane trida_id.
|
||||
anon_client = app.test_client()
|
||||
assert "6.B" not in anon_client.get("/registrace").get_data(as_text=True)
|
||||
student_after = db.execute(
|
||||
"SELECT trida_id FROM uzivatele WHERE id = ?",
|
||||
(student_id,),
|
||||
).fetchone()
|
||||
assert student_after["trida_id"] == class_id
|
||||
|
||||
|
||||
def test_student_approval_unlocks_classroom_and_rejection_invalidates_session(
|
||||
app: Flask,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
cur = db.execute(
|
||||
"INSERT INTO tridy (nazev, rocnik) VALUES (?, ?)",
|
||||
("7.Z", 7),
|
||||
)
|
||||
class_7z = int(cur.lastrowid)
|
||||
cur = db.execute(
|
||||
"INSERT INTO tridy (nazev, rocnik) VALUES (?, ?)",
|
||||
("8.Z", 8),
|
||||
)
|
||||
class_8z = int(cur.lastrowid)
|
||||
db.commit()
|
||||
|
||||
_insert_user(
|
||||
db,
|
||||
email="ucitelka@example.test",
|
||||
password="heslo-ucitelka",
|
||||
jmeno="Jana",
|
||||
prijmeni="Testova",
|
||||
role="ucitelka",
|
||||
stav="schvaleny",
|
||||
)
|
||||
student_a_id = _insert_user(
|
||||
db,
|
||||
email="zak.a@example.test",
|
||||
password="heslo-zaka",
|
||||
jmeno="Petr",
|
||||
prijmeni="Ukazkovy",
|
||||
prezdivka="Sokolik",
|
||||
stav="ceka_na_schvaleni",
|
||||
trida_id=class_7z,
|
||||
)
|
||||
student_b_id = _insert_user(
|
||||
db,
|
||||
email="zak.b@example.test",
|
||||
password="heslo-zakb",
|
||||
jmeno="Eva",
|
||||
prijmeni="Testova",
|
||||
stav="ceka_na_schvaleni",
|
||||
trida_id=class_7z,
|
||||
)
|
||||
|
||||
teacher_client = app.test_client()
|
||||
student_a_client = app.test_client()
|
||||
student_b_client = app.test_client()
|
||||
|
||||
_login(teacher_client, "ucitelka@example.test", "heslo-ucitelka")
|
||||
_login(student_a_client, "zak.a@example.test", "heslo-zaka")
|
||||
_login(student_b_client, "zak.b@example.test", "heslo-zakb")
|
||||
|
||||
# Před schválením nemají žáci přístup do /trida.
|
||||
assert student_a_client.get("/trida").status_code == 403
|
||||
assert student_b_client.get("/profil").status_code == 200
|
||||
|
||||
# Fronta v /admin/zaci zobrazí oba čekající žáky.
|
||||
queue_html = teacher_client.get("/admin/zaci").get_data(as_text=True)
|
||||
assert "zak.a@example.test" in queue_html
|
||||
assert "zak.b@example.test" in queue_html
|
||||
assert "Petr Ukazkovy" in queue_html
|
||||
assert "Eva Testova" in queue_html
|
||||
|
||||
# Schválení žáka A do 7.Z okamžitě odemkne /trida.
|
||||
token = _csrf(teacher_client, "/admin/zaci")
|
||||
approve = teacher_client.post(
|
||||
f"/admin/zaci/{student_a_id}/schvalit",
|
||||
data={"csrf_token": token, "trida_id": str(class_7z)},
|
||||
)
|
||||
assert approve.status_code == 302
|
||||
row_a = db.execute(
|
||||
"SELECT stav, trida_id, schvaleno_at FROM uzivatele WHERE id = ?",
|
||||
(student_a_id,),
|
||||
).fetchone()
|
||||
assert row_a["stav"] == "schvaleny"
|
||||
assert row_a["trida_id"] == class_7z
|
||||
assert row_a["schvaleno_at"] is not None
|
||||
assert student_a_client.get("/trida").status_code == 200
|
||||
|
||||
# Zamítnutí žáka B zneplatní jeho aktivní session i budoucí přihlášení.
|
||||
reject = teacher_client.post(
|
||||
f"/admin/zaci/{student_b_id}/zamitnout",
|
||||
data={"csrf_token": token},
|
||||
)
|
||||
assert reject.status_code == 302
|
||||
assert student_b_client.get("/profil").status_code == 302
|
||||
|
||||
retry_token = _csrf(student_b_client, "/prihlaseni")
|
||||
relogin_b = student_b_client.post(
|
||||
"/prihlaseni",
|
||||
data={
|
||||
"csrf_token": retry_token,
|
||||
"email": "zak.b@example.test",
|
||||
"heslo": "heslo-zakb",
|
||||
},
|
||||
)
|
||||
assert relogin_b.status_code == 403
|
||||
|
||||
# Přeřazení žáka A do 8.Z zachová stav schvaleny.
|
||||
reassign = teacher_client.post(
|
||||
f"/admin/zaci/{student_a_id}/trida",
|
||||
data={"csrf_token": token, "trida_id": str(class_8z)},
|
||||
)
|
||||
assert reassign.status_code == 302
|
||||
row_a2 = db.execute(
|
||||
"SELECT stav, trida_id FROM uzivatele WHERE id = ?",
|
||||
(student_a_id,),
|
||||
).fetchone()
|
||||
assert row_a2["stav"] == "schvaleny"
|
||||
assert row_a2["trida_id"] == class_8z
|
||||
|
||||
# Filtrování v /admin/zaci podle stavu a třídy.
|
||||
only_8z = teacher_client.get(
|
||||
f"/admin/zaci?stav=schvaleny&trida_id={class_8z}"
|
||||
).get_data(as_text=True)
|
||||
assert "zak.a@example.test" in only_8z
|
||||
assert "zak.b@example.test" not in only_8z
|
||||
|
||||
# Deaktivace žáka A zneplatní session a zablokuje přihlášení.
|
||||
deact = teacher_client.post(
|
||||
f"/admin/zaci/{student_a_id}/deaktivovat",
|
||||
data={"csrf_token": token},
|
||||
)
|
||||
assert deact.status_code == 302
|
||||
assert student_a_client.get("/profil").status_code == 302
|
||||
|
||||
# Opětovná aktivace žáka A umožní nové přihlášení.
|
||||
react = teacher_client.post(
|
||||
f"/admin/zaci/{student_a_id}/aktivovat",
|
||||
data={"csrf_token": token, "trida_id": str(class_8z)},
|
||||
)
|
||||
assert react.status_code == 302
|
||||
_login(student_a_client, "zak.a@example.test", "heslo-zaka")
|
||||
assert student_a_client.get("/trida").status_code == 200
|
||||
|
||||
|
||||
def test_teacher_account_protected_from_student_management_actions(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
cur = db.execute(
|
||||
"INSERT INTO tridy (nazev, rocnik) VALUES (?, ?)",
|
||||
("6.Z", 6),
|
||||
)
|
||||
class_id = int(cur.lastrowid)
|
||||
db.commit()
|
||||
|
||||
teacher_id = _insert_user(
|
||||
db,
|
||||
email="ucitelka@example.test",
|
||||
password="heslo-ucitelka",
|
||||
jmeno="Jana",
|
||||
prijmeni="Testova",
|
||||
role="ucitelka",
|
||||
stav="schvaleny",
|
||||
)
|
||||
_login(client, "ucitelka@example.test", "heslo-ucitelka")
|
||||
token = _csrf(client, "/admin/zaci")
|
||||
|
||||
for path in (
|
||||
f"/admin/zaci/{teacher_id}/deaktivovat",
|
||||
f"/admin/zaci/{teacher_id}/zamitnout",
|
||||
f"/admin/zaci/{teacher_id}/schvalit",
|
||||
f"/admin/zaci/{teacher_id}/aktivovat",
|
||||
f"/admin/zaci/{teacher_id}/trida",
|
||||
):
|
||||
resp = client.post(
|
||||
path,
|
||||
data={"csrf_token": token, "trida_id": str(class_id)},
|
||||
)
|
||||
assert resp.status_code == 403
|
||||
|
||||
row = db.execute(
|
||||
"SELECT role, stav, trida_id FROM uzivatele WHERE id = ?",
|
||||
(teacher_id,),
|
||||
).fetchone()
|
||||
assert row["role"] == "ucitelka"
|
||||
assert row["stav"] == "schvaleny"
|
||||
assert row["trida_id"] is None
|
||||
@@ -0,0 +1,615 @@
|
||||
"""Integrační testy účtů, bootstrapu, session, CSRF, rate limitu a rolí."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Flask
|
||||
from flask.testing import FlaskClient
|
||||
|
||||
from poznavacky import auth, create_app
|
||||
from poznavacky import db as db_module
|
||||
from poznavacky.security import RateLimiter, hash_password, verify_password
|
||||
|
||||
_CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"')
|
||||
|
||||
|
||||
def _extract_csrf(html: str) -> str:
|
||||
match = _CSRF_RE.search(html)
|
||||
assert match is not None, "CSRF token nebyl nalezen v HTML formuláři."
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def _get_csrf(client: FlaskClient, path: str = "/prihlaseni") -> str:
|
||||
resp = client.get(path)
|
||||
assert resp.status_code == 200
|
||||
return _extract_csrf(resp.get_data(as_text=True))
|
||||
|
||||
|
||||
def _insert_class(
|
||||
db: sqlite3.Connection,
|
||||
nazev: str,
|
||||
rocnik: int,
|
||||
*,
|
||||
aktivni: int = 1,
|
||||
) -> int:
|
||||
cur = db.execute(
|
||||
"INSERT INTO tridy (nazev, rocnik, aktivni) VALUES (?, ?, ?)",
|
||||
(nazev, rocnik, aktivni),
|
||||
)
|
||||
db.commit()
|
||||
assert cur.lastrowid is not None
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def _insert_user(
|
||||
db: sqlite3.Connection,
|
||||
*,
|
||||
email: str,
|
||||
password: str,
|
||||
jmeno: str = "Petr",
|
||||
prijmeni: str = "Ukazkovy",
|
||||
prezdivka: str | None = None,
|
||||
role: str = "zak",
|
||||
stav: str = "ceka_na_schvaleni",
|
||||
trida_id: int | None = None,
|
||||
) -> int:
|
||||
cur = db.execute(
|
||||
"""
|
||||
INSERT INTO uzivatele (
|
||||
email, heslo_hash, jmeno, prijmeni, prezdivka,
|
||||
role, stav, trida_id
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
email.lower(),
|
||||
hash_password(password),
|
||||
jmeno,
|
||||
prijmeni,
|
||||
prezdivka,
|
||||
role,
|
||||
stav,
|
||||
trida_id,
|
||||
),
|
||||
)
|
||||
db.commit()
|
||||
assert cur.lastrowid is not None
|
||||
return int(cur.lastrowid)
|
||||
|
||||
|
||||
def _login(
|
||||
client: FlaskClient,
|
||||
email: str,
|
||||
password: str,
|
||||
*,
|
||||
follow_redirects: bool = False,
|
||||
):
|
||||
token = _get_csrf(client, "/prihlaseni")
|
||||
return client.post(
|
||||
"/prihlaseni",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": email,
|
||||
"heslo": password,
|
||||
},
|
||||
follow_redirects=follow_redirects,
|
||||
)
|
||||
|
||||
|
||||
def test_bootstrap_admin_account_runs_only_on_empty_table(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
data_dir = tmp_path / "data"
|
||||
env = {
|
||||
"POZNAVACKY_SECRET_KEY": "klic-bootstrap",
|
||||
"POZNAVACKY_DATA_DIR": str(data_dir),
|
||||
"POZNAVACKY_ADMIN_EMAIL": " Ucitelka@Example.Test ",
|
||||
"POZNAVACKY_ADMIN_PASSWORD": "silne-heslo-ucitelky",
|
||||
}
|
||||
|
||||
app1 = create_app(environ=env)
|
||||
conn = db_module.connect(app1.config["DB_PATH"])
|
||||
try:
|
||||
rows = conn.execute("SELECT * FROM uzivatele").fetchall()
|
||||
assert len(rows) == 1
|
||||
admin = rows[0]
|
||||
assert admin["email"] == "ucitelka@example.test"
|
||||
assert admin["role"] == "ucitelka"
|
||||
assert admin["stav"] == "schvaleny"
|
||||
assert admin["schvaleno_at"] is not None
|
||||
assert admin["heslo_hash"].startswith("scrypt:")
|
||||
assert verify_password(admin["heslo_hash"], "silne-heslo-ucitelky")
|
||||
|
||||
# Simulace změny hesla učitelky před dalším startem.
|
||||
new_hash = hash_password("nove-zmenene-heslo")
|
||||
conn.execute(
|
||||
"UPDATE uzivatele SET heslo_hash = ? WHERE id = ?",
|
||||
(new_hash, admin["id"]),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
# Opakovaný start nesmí vytvořit duplikát ani přepsat heslo.
|
||||
app2 = create_app(environ=env)
|
||||
conn = db_module.connect(app2.config["DB_PATH"])
|
||||
try:
|
||||
rows = conn.execute("SELECT * FROM uzivatele").fetchall()
|
||||
assert len(rows) == 1
|
||||
assert verify_password(rows[0]["heslo_hash"], "nove-zmenene-heslo")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def test_student_registration_success_and_validation(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
active_id = _insert_class(db, "6.Z", 6, aktivni=1)
|
||||
inactive_id = _insert_class(db, "9.Z", 9, aktivni=0)
|
||||
|
||||
# Deaktivovaná třída není v registračním formuláři.
|
||||
reg_page = client.get("/registrace")
|
||||
html = reg_page.get_data(as_text=True)
|
||||
assert "6.Z" in html
|
||||
assert "9.Z" not in html
|
||||
token = _extract_csrf(html)
|
||||
|
||||
# Úspěšná registrace.
|
||||
resp = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": " Zak.Novy@Example.Test ",
|
||||
"heslo": "heslo1234",
|
||||
"jmeno": "Anna",
|
||||
"prijmeni": "Novotna",
|
||||
"prezdivka": "Vrabec",
|
||||
"trida_id": str(active_id),
|
||||
},
|
||||
follow_redirects=True,
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert "čeká na schválení" in resp.get_data(as_text=True).lower()
|
||||
|
||||
row = db.execute(
|
||||
"SELECT * FROM uzivatele WHERE email = ?",
|
||||
("zak.novy@example.test",),
|
||||
).fetchone()
|
||||
assert row is not None
|
||||
assert row["role"] == "zak"
|
||||
assert row["stav"] == "ceka_na_schvaleni"
|
||||
assert row["trida_id"] == active_id
|
||||
assert row["prezdivka"] == "Vrabec"
|
||||
assert row["heslo_hash"].startswith("scrypt:")
|
||||
assert "heslo1234" not in row["heslo_hash"]
|
||||
|
||||
# Duplicitní e-mail s jinou velikostí písmen je odmítnut.
|
||||
token = _get_csrf(client, "/registrace")
|
||||
dup_resp = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "ZAK.NOVY@example.test",
|
||||
"heslo": "dalsiheslo123",
|
||||
"jmeno": "Jan",
|
||||
"prijmeni": "Test",
|
||||
"trida_id": str(active_id),
|
||||
},
|
||||
)
|
||||
assert dup_resp.status_code == 400
|
||||
assert db.execute("SELECT COUNT(*) FROM uzivatele").fetchone()[0] == 1
|
||||
|
||||
# Krátké heslo je odmítnuto.
|
||||
short_resp = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "kratky@example.test",
|
||||
"heslo": "1234567",
|
||||
"jmeno": "Jan",
|
||||
"prijmeni": "Test",
|
||||
"trida_id": str(active_id),
|
||||
},
|
||||
)
|
||||
assert short_resp.status_code == 400
|
||||
|
||||
# Neaktivní třída je odmítnuta.
|
||||
inactive_resp = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "neaktivni@example.test",
|
||||
"heslo": "dlouheheslo",
|
||||
"jmeno": "Jan",
|
||||
"prijmeni": "Test",
|
||||
"trida_id": str(inactive_id),
|
||||
},
|
||||
)
|
||||
assert inactive_resp.status_code == 400
|
||||
assert db.execute("SELECT COUNT(*) FROM uzivatele").fetchone()[0] == 1
|
||||
|
||||
|
||||
def test_registration_without_any_active_classes_sets_null_class(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
token = _get_csrf(client, "/registrace")
|
||||
resp = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "bez.tridy@example.test",
|
||||
"heslo": "heslo1234",
|
||||
"jmeno": "Karel",
|
||||
"prijmeni": "Testovy",
|
||||
"trida_id": "",
|
||||
},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
row = db.execute(
|
||||
"SELECT trida_id, stav FROM uzivatele WHERE email = ?",
|
||||
("bez.tridy@example.test",),
|
||||
).fetchone()
|
||||
assert row is not None
|
||||
assert row["trida_id"] is None
|
||||
assert row["stav"] == "ceka_na_schvaleni"
|
||||
|
||||
|
||||
def test_login_logout_cookie_attributes_and_blocked_states(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
_insert_user(
|
||||
db,
|
||||
email="cekajici@example.test",
|
||||
password="heslo-cekajici",
|
||||
stav="ceka_na_schvaleni",
|
||||
)
|
||||
_insert_user(
|
||||
db,
|
||||
email="zamitnuty@example.test",
|
||||
password="heslo-zamitnuty",
|
||||
stav="zamitnuty",
|
||||
)
|
||||
_insert_user(
|
||||
db,
|
||||
email="deaktivovany@example.test",
|
||||
password="heslo-deaktivovany",
|
||||
stav="deaktivovany",
|
||||
)
|
||||
|
||||
# Čekající žák se přihlásí a cookie má HttpOnly + SameSite=Lax.
|
||||
resp = _login(client, "cekajici@example.test", "heslo-cekajici")
|
||||
assert resp.status_code == 302
|
||||
cookies = resp.headers.getlist("Set-Cookie")
|
||||
assert any("HttpOnly" in c and "SameSite=Lax" in c for c in cookies)
|
||||
|
||||
assert client.get("/profil").status_code == 200
|
||||
|
||||
# Odhlášení vyčistí session.
|
||||
logout_token = _get_csrf(client, "/profil")
|
||||
out = client.post("/odhlaseni", data={"csrf_token": logout_token})
|
||||
assert out.status_code == 302
|
||||
assert client.get("/profil").status_code == 302
|
||||
|
||||
# Zamítnutý a deaktivovaný účet se nepřihlásí ani se správným heslem.
|
||||
for email, pwd in [
|
||||
("zamitnuty@example.test", "heslo-zamitnuty"),
|
||||
("deaktivovany@example.test", "heslo-deaktivovany"),
|
||||
]:
|
||||
denied = _login(client, email, pwd)
|
||||
assert denied.status_code == 403
|
||||
assert client.get("/profil").status_code == 302
|
||||
|
||||
# HTTPS aplikace nastavuje atribut Secure.
|
||||
https_app = create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"POZNAVACKY_SECRET_KEY": "https-klic",
|
||||
"POZNAVACKY_DATA_DIR": str(tmp_path / "https-data"),
|
||||
"POZNAVACKY_BASE_URL": "https://poznavacky.example.test",
|
||||
},
|
||||
environ={},
|
||||
)
|
||||
https_conn = db_module.connect(https_app.config["DB_PATH"])
|
||||
try:
|
||||
_insert_user(
|
||||
https_conn,
|
||||
email="https@example.test",
|
||||
password="heslo-https",
|
||||
stav="schvaleny",
|
||||
)
|
||||
finally:
|
||||
https_conn.close()
|
||||
|
||||
https_client = https_app.test_client()
|
||||
https_get = https_client.get(
|
||||
"/prihlaseni",
|
||||
base_url="https://poznavacky.example.test",
|
||||
)
|
||||
token = _extract_csrf(https_get.get_data(as_text=True))
|
||||
https_resp = https_client.post(
|
||||
"/prihlaseni",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "https@example.test",
|
||||
"heslo": "heslo-https",
|
||||
},
|
||||
base_url="https://poznavacky.example.test",
|
||||
)
|
||||
assert https_resp.status_code == 302
|
||||
https_cookies = https_resp.headers.getlist("Set-Cookie")
|
||||
assert any(
|
||||
"Secure" in c and "HttpOnly" in c and "SameSite=Lax" in c
|
||||
for c in https_cookies
|
||||
)
|
||||
|
||||
|
||||
def test_session_invalidated_on_state_or_password_change(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
user_id = _insert_user(
|
||||
db,
|
||||
email="session@example.test",
|
||||
password="puvodni-heslo",
|
||||
stav="schvaleny",
|
||||
)
|
||||
login_resp = _login(client, "session@example.test", "puvodni-heslo")
|
||||
assert login_resp.status_code == 302
|
||||
assert client.get("/profil").status_code == 200
|
||||
|
||||
# Změna hesla v DB okamžitě zneplatní existující session.
|
||||
db.execute(
|
||||
"UPDATE uzivatele SET heslo_hash = ? WHERE id = ?",
|
||||
(hash_password("jine-heslo-123"), user_id),
|
||||
)
|
||||
db.commit()
|
||||
assert client.get("/profil").status_code == 302
|
||||
|
||||
# Znovu přihlásit novým heslem a pak deaktivovat účet.
|
||||
relogin = _login(client, "session@example.test", "jine-heslo-123")
|
||||
assert relogin.status_code == 302
|
||||
assert client.get("/profil").status_code == 200
|
||||
|
||||
db.execute(
|
||||
"UPDATE uzivatele SET stav = 'deaktivovany' WHERE id = ?",
|
||||
(user_id,),
|
||||
)
|
||||
db.commit()
|
||||
assert client.get("/profil").status_code == 302
|
||||
|
||||
|
||||
def test_authorization_matrix_and_profile_nickname_update(
|
||||
app: Flask,
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
@app.get("/_test-teacher-only")
|
||||
@auth.teacher_required
|
||||
def _teacher_probe() -> str:
|
||||
return "ok-teacher"
|
||||
|
||||
cls_id = _insert_class(db, "7.Z", 7)
|
||||
_insert_user(
|
||||
db,
|
||||
email="pending@example.test",
|
||||
password="heslo-pending",
|
||||
jmeno="Anna",
|
||||
prijmeni="Novotna",
|
||||
stav="ceka_na_schvaleni",
|
||||
trida_id=cls_id,
|
||||
)
|
||||
_insert_user(
|
||||
db,
|
||||
email="approved@example.test",
|
||||
password="heslo-approved",
|
||||
jmeno="Petr",
|
||||
prijmeni="Ukazkovy",
|
||||
prezdivka="Sokolik",
|
||||
stav="schvaleny",
|
||||
trida_id=cls_id,
|
||||
)
|
||||
_insert_user(
|
||||
db,
|
||||
email="teacher@example.test",
|
||||
password="heslo-teacher",
|
||||
role="ucitelka",
|
||||
stav="schvaleny",
|
||||
)
|
||||
|
||||
# Nepřihlášený uživatel.
|
||||
assert auth.can_view_leaderboards(None) is False
|
||||
assert client.get("/profil").status_code == 302
|
||||
assert client.get("/trida").status_code == 302
|
||||
assert client.get("/_test-teacher-only").status_code == 302
|
||||
|
||||
# Neschválený žák: profil ano + úprava přezdívky, žebříček/učitelka 403.
|
||||
_login(client, "pending@example.test", "heslo-pending")
|
||||
prof = client.get("/profil")
|
||||
assert prof.status_code == 200
|
||||
body = prof.get_data(as_text=True)
|
||||
assert "Čeká na schválení" in body
|
||||
assert "Anna N." in body
|
||||
assert client.get("/trida").status_code == 403
|
||||
assert client.get("/_test-teacher-only").status_code == 403
|
||||
|
||||
csrf = _extract_csrf(body)
|
||||
upd = client.post(
|
||||
"/profil",
|
||||
data={"csrf_token": csrf, "prezdivka": "Sova"},
|
||||
follow_redirects=True,
|
||||
)
|
||||
assert upd.status_code == 200
|
||||
assert "Sova" in upd.get_data(as_text=True)
|
||||
|
||||
# Schválený žák: profil + /trida ano, učitelský endpoint 403.
|
||||
_login(client, "approved@example.test", "heslo-approved")
|
||||
assert client.get("/profil").status_code == 200
|
||||
cls_resp = client.get("/trida")
|
||||
assert cls_resp.status_code == 200
|
||||
assert "Sokolik" in cls_resp.get_data(as_text=True)
|
||||
assert client.get("/_test-teacher-only").status_code == 403
|
||||
|
||||
# Schválená učitelka: vše povoleno.
|
||||
_login(client, "teacher@example.test", "heslo-teacher")
|
||||
assert client.get("/profil").status_code == 200
|
||||
assert client.get("/trida").status_code == 200
|
||||
assert client.get("/_test-teacher-only").status_code == 200
|
||||
|
||||
|
||||
def test_csrf_protection_blocks_missing_and_allows_header_token(
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
_insert_user(
|
||||
db,
|
||||
email="csrf@example.test",
|
||||
password="heslo-csrf",
|
||||
stav="schvaleny",
|
||||
)
|
||||
|
||||
# POST bez CSRF tokenu je odmítnut 403.
|
||||
for path in ("/prihlaseni", "/registrace", "/odhlaseni"):
|
||||
resp = client.post(path, data={"email": "csrf@example.test"})
|
||||
assert resp.status_code == 403
|
||||
|
||||
# Hlavička X-CSRF-Token projde.
|
||||
token = _get_csrf(client, "/prihlaseni")
|
||||
resp = client.post(
|
||||
"/prihlaseni",
|
||||
data={"email": "csrf@example.test", "heslo": "heslo-csrf"},
|
||||
headers={"X-CSRF-Token": token},
|
||||
)
|
||||
assert resp.status_code == 302
|
||||
|
||||
|
||||
def test_rate_limiting_blocks_and_recovers_with_clock(
|
||||
app: Flask,
|
||||
client: FlaskClient,
|
||||
db: sqlite3.Connection,
|
||||
) -> None:
|
||||
now = [1000.0]
|
||||
app.extensions["rate_limiter"] = RateLimiter(clock=lambda: now[0])
|
||||
app.config["RATE_LIMITS"] = {
|
||||
"login": (2, 60),
|
||||
"register": (1, 300),
|
||||
"password_reset": (2, 300),
|
||||
}
|
||||
|
||||
_insert_user(
|
||||
db,
|
||||
email="limit@example.test",
|
||||
password="spravne-heslo",
|
||||
stav="schvaleny",
|
||||
)
|
||||
|
||||
token = _get_csrf(client, "/prihlaseni")
|
||||
for _ in range(2):
|
||||
bad = client.post(
|
||||
"/prihlaseni",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "limit@example.test",
|
||||
"heslo": "spatne-heslo",
|
||||
},
|
||||
)
|
||||
assert bad.status_code == 401
|
||||
|
||||
# 3. pokus i se správným heslem vrátí 429 a nepřihlásí.
|
||||
blocked = client.post(
|
||||
"/prihlaseni",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "limit@example.test",
|
||||
"heslo": "spravne-heslo",
|
||||
},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert int(blocked.headers["Retry-After"]) >= 1
|
||||
assert client.get("/profil").status_code == 302
|
||||
|
||||
# Po uplynutí okna je přihlášení opět povoleno.
|
||||
now[0] = 1061.0
|
||||
ok = client.post(
|
||||
"/prihlaseni",
|
||||
data={
|
||||
"csrf_token": token,
|
||||
"email": "limit@example.test",
|
||||
"heslo": "spravne-heslo",
|
||||
},
|
||||
)
|
||||
assert ok.status_code == 302
|
||||
|
||||
# Rate limit na registraci.
|
||||
reg_token = _get_csrf(client, "/registrace")
|
||||
first_reg = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": reg_token,
|
||||
"email": "prvni.reg@example.test",
|
||||
"heslo": "heslo1234",
|
||||
"jmeno": "A",
|
||||
"prijmeni": "B",
|
||||
},
|
||||
)
|
||||
assert first_reg.status_code == 302
|
||||
second_reg = client.post(
|
||||
"/registrace",
|
||||
data={
|
||||
"csrf_token": reg_token,
|
||||
"email": "druha.reg@example.test",
|
||||
"heslo": "heslo1234",
|
||||
"jmeno": "C",
|
||||
"prijmeni": "D",
|
||||
},
|
||||
)
|
||||
assert second_reg.status_code == 429
|
||||
row = db.execute(
|
||||
"SELECT id FROM uzivatele WHERE email = ?",
|
||||
("druha.reg@example.test",),
|
||||
).fetchone()
|
||||
assert row is None
|
||||
|
||||
|
||||
def test_trust_proxy_uses_forwarded_client_ip(tmp_path: Path) -> None:
|
||||
app = create_app(
|
||||
{
|
||||
"TESTING": True,
|
||||
"POZNAVACKY_SECRET_KEY": "proxy-klic",
|
||||
"POZNAVACKY_DATA_DIR": str(tmp_path / "proxy-data"),
|
||||
"POZNAVACKY_TRUST_PROXY": 1,
|
||||
},
|
||||
environ={},
|
||||
)
|
||||
app.config["RATE_LIMITS"]["login"] = (1, 60)
|
||||
client = app.test_client()
|
||||
token = _get_csrf(client, "/prihlaseni")
|
||||
|
||||
first = client.post(
|
||||
"/prihlaseni",
|
||||
data={"csrf_token": token, "email": "a@example.test", "heslo": "x"},
|
||||
headers={"X-Forwarded-For": "198.51.100.1"},
|
||||
)
|
||||
assert first.status_code == 401
|
||||
|
||||
# Stejná klientská IP přes proxy narazí na limit.
|
||||
second = client.post(
|
||||
"/prihlaseni",
|
||||
data={"csrf_token": token, "email": "a@example.test", "heslo": "x"},
|
||||
headers={"X-Forwarded-For": "198.51.100.1"},
|
||||
)
|
||||
assert second.status_code == 429
|
||||
|
||||
# Jiná klientská IP přes proxy projde.
|
||||
other = client.post(
|
||||
"/prihlaseni",
|
||||
data={"csrf_token": token, "email": "a@example.test", "heslo": "x"},
|
||||
headers={"X-Forwarded-For": "198.51.100.2"},
|
||||
)
|
||||
assert other.status_code == 401
|
||||
@@ -38,6 +38,62 @@ def test_load_config_from_environ(tmp_path: Path) -> None:
|
||||
assert cfg.smtp_port == 465
|
||||
assert cfg.smtp_tls is False
|
||||
assert cfg.testing is False
|
||||
assert cfg.session_cookie_secure is True
|
||||
assert cfg.trust_proxy == 0
|
||||
assert cfg.password_reset_ttl_minutes == 60
|
||||
|
||||
|
||||
def test_security_and_reset_config_options() -> None:
|
||||
cfg = load_config(
|
||||
environ={
|
||||
"POZNAVACKY_SECRET_KEY": "tajny-klic",
|
||||
"POZNAVACKY_BASE_URL": "http://127.0.0.1:8000",
|
||||
"POZNAVACKY_SESSION_COOKIE_SECURE": "true",
|
||||
"POZNAVACKY_TRUST_PROXY": "2",
|
||||
"POZNAVACKY_PASSWORD_RESET_TTL_MINUTES": "30",
|
||||
}
|
||||
)
|
||||
assert cfg.session_cookie_secure is True
|
||||
assert cfg.trust_proxy == 2
|
||||
assert cfg.password_reset_ttl_minutes == 30
|
||||
|
||||
cfg_http = load_config(
|
||||
environ={
|
||||
"POZNAVACKY_SECRET_KEY": "tajny-klic",
|
||||
"POZNAVACKY_BASE_URL": "http://127.0.0.1:8000",
|
||||
"PASSWORD_RESET_TTL_MINUTES": "45",
|
||||
}
|
||||
)
|
||||
assert cfg_http.session_cookie_secure is False
|
||||
assert cfg_http.password_reset_ttl_minutes == 45
|
||||
|
||||
cfg_override_false = load_config(
|
||||
environ={
|
||||
"POZNAVACKY_SECRET_KEY": "tajny-klic",
|
||||
"POZNAVACKY_BASE_URL": "https://poznavacky.example.test",
|
||||
"POZNAVACKY_SESSION_COOKIE_SECURE": "false",
|
||||
}
|
||||
)
|
||||
assert cfg_override_false.session_cookie_secure is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("env_key", "bad_value"),
|
||||
[
|
||||
("POZNAVACKY_TRUST_PROXY", "-1"),
|
||||
("POZNAVACKY_TRUST_PROXY", "abc"),
|
||||
("POZNAVACKY_PASSWORD_RESET_TTL_MINUTES", "0"),
|
||||
("POZNAVACKY_SESSION_COOKIE_SECURE", "mozna"),
|
||||
],
|
||||
)
|
||||
def test_invalid_security_config_raises(env_key: str, bad_value: str) -> None:
|
||||
with pytest.raises(ConfigError, match=env_key):
|
||||
load_config(
|
||||
environ={
|
||||
"POZNAVACKY_SECRET_KEY": "klic",
|
||||
env_key: bad_value,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret", [None, "", " "])
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Testy SMTP odesílače (STARTTLS, SMTP_SSL, chyby bez úniku tajemství)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from poznavacky.mailer import MailDeliveryError, SmtpMailer
|
||||
|
||||
|
||||
def test_smtp_mailer_starttls_and_auth() -> None:
|
||||
fake_client = MagicMock()
|
||||
fake_cm = MagicMock()
|
||||
fake_cm.__enter__.return_value = fake_client
|
||||
|
||||
with patch("poznavacky.mailer.smtplib.SMTP", return_value=fake_cm) as cls:
|
||||
mailer = SmtpMailer(
|
||||
host="mail.example.test",
|
||||
port=587,
|
||||
user="noreply@example.test",
|
||||
password="tajne-smtp-heslo",
|
||||
sender="Poznavacky <noreply@example.test>",
|
||||
use_tls=True,
|
||||
)
|
||||
mailer.send_email(
|
||||
to="zak@example.test",
|
||||
subject="Obnova hesla",
|
||||
body="Odkaz: https://poznavacky.example.test/obnova-hesla/tok123",
|
||||
)
|
||||
|
||||
cls.assert_called_once()
|
||||
assert cls.call_args.args == ("mail.example.test", 587)
|
||||
fake_client.starttls.assert_called_once()
|
||||
fake_client.login.assert_called_once_with(
|
||||
"noreply@example.test",
|
||||
"tajne-smtp-heslo",
|
||||
)
|
||||
fake_client.send_message.assert_called_once()
|
||||
sent_msg: EmailMessage = fake_client.send_message.call_args.args[0]
|
||||
assert sent_msg["From"] == "Poznavacky <noreply@example.test>"
|
||||
assert sent_msg["To"] == "zak@example.test"
|
||||
assert sent_msg["Subject"] == "Obnova hesla"
|
||||
assert "tok123" in sent_msg.get_content()
|
||||
|
||||
|
||||
def test_smtp_mailer_uses_smtp_ssl_on_port_465() -> None:
|
||||
fake_client = MagicMock()
|
||||
fake_cm = MagicMock()
|
||||
fake_cm.__enter__.return_value = fake_client
|
||||
|
||||
with patch(
|
||||
"poznavacky.mailer.smtplib.SMTP_SSL",
|
||||
return_value=fake_cm,
|
||||
) as ssl_cls:
|
||||
mailer = SmtpMailer(
|
||||
host="mail.example.test",
|
||||
port=465,
|
||||
user="",
|
||||
password="",
|
||||
sender="noreply@example.test",
|
||||
use_tls=True,
|
||||
)
|
||||
mailer.send_email(
|
||||
to="zak@example.test",
|
||||
subject="Test SSL",
|
||||
body="Obsah zprávy",
|
||||
)
|
||||
|
||||
ssl_cls.assert_called_once()
|
||||
fake_client.starttls.assert_not_called()
|
||||
fake_client.login.assert_not_called()
|
||||
fake_client.send_message.assert_called_once()
|
||||
|
||||
|
||||
def test_smtp_mailer_missing_host_raises_without_secrets(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
mailer = SmtpMailer(
|
||||
host="",
|
||||
port=587,
|
||||
user="u@example.test",
|
||||
password="SUPER-SECRET-SMTP-PASSWORD",
|
||||
sender="noreply@example.test",
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
with pytest.raises(MailDeliveryError):
|
||||
mailer.send_email(
|
||||
to="zak@example.test",
|
||||
subject="Obnova",
|
||||
body="TAJNY-RESET-TOKEN-XYZ",
|
||||
)
|
||||
|
||||
assert "SUPER-SECRET-SMTP-PASSWORD" not in caplog.text
|
||||
assert "TAJNY-RESET-TOKEN-XYZ" not in caplog.text
|
||||
|
||||
|
||||
def test_smtp_mailer_failure_logs_safely_without_password_or_token(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
secret_pass = "VELMI-TAJNE-HESLO-SMTP"
|
||||
secret_token = "SUROVY-TOKEN-123456"
|
||||
|
||||
def _boom(*args: Any, **kwargs: Any) -> Any:
|
||||
raise smtplib.SMTPAuthenticationError(
|
||||
535,
|
||||
f"Auth failed for {secret_pass}".encode(),
|
||||
)
|
||||
|
||||
with (
|
||||
patch("poznavacky.mailer.smtplib.SMTP", side_effect=_boom),
|
||||
caplog.at_level(logging.ERROR),
|
||||
):
|
||||
mailer = SmtpMailer(
|
||||
host="mail.example.test",
|
||||
port=587,
|
||||
user="u@example.test",
|
||||
password=secret_pass,
|
||||
sender="noreply@example.test",
|
||||
)
|
||||
with pytest.raises(MailDeliveryError) as exc_info:
|
||||
mailer.send_email(
|
||||
to="zak@example.test",
|
||||
subject="Obnova",
|
||||
body=f"https://example.test/obnova-hesla/{secret_token}",
|
||||
)
|
||||
|
||||
assert secret_pass not in caplog.text
|
||||
assert secret_token not in caplog.text
|
||||
assert secret_pass not in str(exc_info.value)
|
||||
assert secret_token not in str(exc_info.value)
|
||||
@@ -47,7 +47,10 @@ def test_migrations_applied_once_and_skipped_on_restart(
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
assert first_versions == ["0001_initial_schema.sql"]
|
||||
assert first_versions == [
|
||||
"0001_initial_schema.sql",
|
||||
"0002_token_hash_index.sql",
|
||||
]
|
||||
|
||||
# Opakovaný start nesmí selhat ani smazat data.
|
||||
applied_again = db_module.apply_migrations(first_app.config["DB_PATH"])
|
||||
@@ -131,3 +134,28 @@ def test_failed_migration_rolls_back_atomically(tmp_path: Path) -> None:
|
||||
assert "zaklad" in tables
|
||||
assert "docasna" not in tables
|
||||
assert versions == ["0001_ok.sql"]
|
||||
|
||||
|
||||
def test_token_hash_unique_index_enforced(
|
||||
seeded_db: dict,
|
||||
) -> None:
|
||||
conn = seeded_db["db"]
|
||||
user_id = seeded_db["zak_id"]
|
||||
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO tokeny_hesla (uzivatel_id, token_hash, vyprsi_at)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(user_id, "hash-tokenu-1", "2099-01-01T00:00:00Z"),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
with pytest.raises(sqlite3.IntegrityError):
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO tokeny_hesla (uzivatel_id, token_hash, vyprsi_at)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(user_id, "hash-tokenu-1", "2099-01-01T01:00:00Z"),
|
||||
)
|
||||
@@ -0,0 +1,350 @@
|
||||
"""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
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Jednotkové testy bezpečnostních primitiv v poznavacky.security."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
|
||||
from poznavacky.security import (
|
||||
CSRF_SESSION_KEY,
|
||||
RateLimiter,
|
||||
compute_auth_version,
|
||||
display_name,
|
||||
get_or_create_csrf_token,
|
||||
hash_password,
|
||||
normalize_email,
|
||||
rotate_csrf_token,
|
||||
validate_csrf_token,
|
||||
verify_auth_version,
|
||||
verify_password,
|
||||
)
|
||||
|
||||
|
||||
def test_scrypt_password_hashing_and_verification() -> None:
|
||||
hashed = hash_password("bezpecne-heslo-123")
|
||||
assert hashed.startswith("scrypt:")
|
||||
assert "bezpecne-heslo-123" not in hashed
|
||||
assert verify_password(hashed, "bezpecne-heslo-123") is True
|
||||
assert verify_password(hashed, "spatne-heslo") is False
|
||||
assert verify_password("", "bezpecne-heslo-123") is False
|
||||
|
||||
|
||||
def test_auth_version_changes_with_password_hash() -> None:
|
||||
hash_a = hash_password("prvni-heslo-123")
|
||||
hash_b = hash_password("druhe-heslo-456")
|
||||
|
||||
ver_a = compute_auth_version("tajny-klic", hash_a)
|
||||
assert len(ver_a) == 32
|
||||
assert verify_auth_version("tajny-klic", hash_a, ver_a) is True
|
||||
assert verify_auth_version("tajny-klic", hash_b, ver_a) is False
|
||||
assert verify_auth_version("jiny-klic", hash_a, ver_a) is False
|
||||
assert verify_auth_version("tajny-klic", hash_a, None) is False
|
||||
|
||||
|
||||
def test_csrf_token_lifecycle_and_validation() -> None:
|
||||
store: dict[str, str] = {}
|
||||
token = get_or_create_csrf_token(store)
|
||||
assert store[CSRF_SESSION_KEY] == token
|
||||
assert get_or_create_csrf_token(store) == token
|
||||
|
||||
assert validate_csrf_token(store, token) is True
|
||||
assert validate_csrf_token(store, "spatny-token") is False
|
||||
assert validate_csrf_token(store, None) is False
|
||||
assert validate_csrf_token({}, token) is False
|
||||
|
||||
rotated = rotate_csrf_token(store)
|
||||
assert rotated != token
|
||||
assert validate_csrf_token(store, token) is False
|
||||
assert validate_csrf_token(store, rotated) is True
|
||||
|
||||
|
||||
def test_rate_limiter_sliding_window_and_retry_after() -> None:
|
||||
now = [100.0]
|
||||
limiter = RateLimiter(clock=lambda: now[0])
|
||||
|
||||
for _ in range(3):
|
||||
decision = limiter.check_and_record(
|
||||
"login", "192.0.2.10", limit=3, window_seconds=60
|
||||
)
|
||||
assert decision.allowed is True
|
||||
assert decision.retry_after == 0
|
||||
|
||||
blocked = limiter.check_and_record(
|
||||
"login", "192.0.2.10", limit=3, window_seconds=60
|
||||
)
|
||||
assert blocked.allowed is False
|
||||
assert blocked.retry_after == 60
|
||||
|
||||
# Jiná IP adresa a jiný endpoint zůstávají nezávislé.
|
||||
assert (
|
||||
limiter.check_and_record(
|
||||
"login", "192.0.2.11", limit=3, window_seconds=60
|
||||
).allowed
|
||||
is True
|
||||
)
|
||||
assert (
|
||||
limiter.check_and_record(
|
||||
"register", "192.0.2.10", limit=3, window_seconds=60
|
||||
).allowed
|
||||
is True
|
||||
)
|
||||
|
||||
# Po posunu o 30 s stále blokováno, retry_after klesne na 30.
|
||||
now[0] = 130.0
|
||||
still_blocked = limiter.check_and_record(
|
||||
"login", "192.0.2.10", limit=3, window_seconds=60
|
||||
)
|
||||
assert still_blocked.allowed is False
|
||||
assert still_blocked.retry_after == 30
|
||||
|
||||
# Po uplynutí 60 s je pokus opět povolen.
|
||||
now[0] = 160.0
|
||||
unblocked = limiter.check_and_record(
|
||||
"login", "192.0.2.10", limit=3, window_seconds=60
|
||||
)
|
||||
assert unblocked.allowed is True
|
||||
|
||||
|
||||
def test_rate_limiter_thread_safety() -> None:
|
||||
limiter = RateLimiter(clock=lambda: 500.0)
|
||||
results: list[bool] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker() -> None:
|
||||
decision = limiter.check_and_record(
|
||||
"login", "192.0.2.99", limit=5, window_seconds=60
|
||||
)
|
||||
with lock:
|
||||
results.append(decision.allowed)
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(20)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
assert results.count(True) == 5
|
||||
assert results.count(False) == 15
|
||||
|
||||
|
||||
def test_display_name_and_email_normalization() -> None:
|
||||
assert (
|
||||
display_name(
|
||||
{"jmeno": "Petr", "prijmeni": "Ukazkovy", "prezdivka": "Sokolik"}
|
||||
)
|
||||
== "Sokolik"
|
||||
)
|
||||
assert (
|
||||
display_name(
|
||||
{"jmeno": "Anna", "prijmeni": "Novotna", "prezdivka": None}
|
||||
)
|
||||
== "Anna N."
|
||||
)
|
||||
assert (
|
||||
display_name(
|
||||
{"jmeno": " Anna ", "prijmeni": " Novotna ", "prezdivka": " "}
|
||||
)
|
||||
== "Anna N."
|
||||
)
|
||||
assert normalize_email(" Zak@Example.Test ") == "zak@example.test"
|
||||
Reference in new issue
Block a user