225 lines
8.7 KiB
Python
225 lines
8.7 KiB
Python
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
"""Anmeldung, zweiter Faktor, Verwaltung - durchgespielt gegen PostgreSQL (CI)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import time
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("fastapi")
|
|
pytest.importorskip("httpx")
|
|
pytest.importorskip("argon2")
|
|
|
|
from fastapi.testclient import TestClient
|
|
from helpers import (
|
|
PASSWORD,
|
|
csrf_from,
|
|
login,
|
|
make_user,
|
|
new_client,
|
|
next_totp,
|
|
token_for,
|
|
)
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from surveybox import db
|
|
from surveybox.accounts import service
|
|
from surveybox.models import AuditEvent, Role, UserAccount
|
|
from surveybox.security import totp
|
|
from surveybox.settings import Settings, get_settings
|
|
|
|
pytestmark = pytest.mark.db
|
|
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_login_logout(client: TestClient) -> None:
|
|
make_user()
|
|
resp = login(client, "Anna@Example.de")
|
|
assert resp.status_code == 303 and resp.headers["location"] == "/"
|
|
assert "surveybox_session" in client.cookies
|
|
page = client.get("/account")
|
|
assert page.status_code == 200 and "anna@example.de" in page.text
|
|
|
|
out = client.post("/logout", data={"csrf_token": csrf_from(page.text)})
|
|
assert out.status_code == 303
|
|
after = client.get("/account")
|
|
assert after.status_code == 303
|
|
assert after.headers["location"].startswith("/login?next=%2Faccount")
|
|
|
|
|
|
def test_wrong_password_and_lockout(client: TestClient) -> None:
|
|
make_user()
|
|
for _ in range(5):
|
|
resp = login(client, "anna@example.de", "falsches passwort!!")
|
|
assert resp.status_code == 400
|
|
assert "Email or password is wrong" in resp.text
|
|
# Jetzt gesperrt: auch das richtige Passwort scheitert mit derselben Meldung
|
|
resp = login(client, "anna@example.de")
|
|
assert resp.status_code == 400
|
|
with Session(db.get_engine()) as s:
|
|
user = s.scalar(select(UserAccount).where(UserAccount.email == "anna@example.de"))
|
|
assert user is not None and user.locked_until is not None
|
|
|
|
|
|
def test_unknown_user_gets_same_answer(client: TestClient) -> None:
|
|
resp = login(client, "niemand@example.de")
|
|
assert resp.status_code == 400
|
|
assert "Email or password is wrong" in resp.text
|
|
|
|
|
|
def test_csrf_protection(client: TestClient, app) -> None: # type: ignore[no-untyped-def]
|
|
make_user()
|
|
data = {"email": "anna@example.de", "password": PASSWORD, "next": "/"}
|
|
client.get("/login")
|
|
assert client.post("/login", data=data).status_code == 403 # ohne Token
|
|
token = token_for(client, "/login")
|
|
evil = client.post("/login", data={**data, "csrf_token": token},
|
|
headers={"Origin": "https://evil.example"})
|
|
assert evil.status_code == 403
|
|
# Token eines anderen Besuchers passt nicht
|
|
with new_client(app) as other:
|
|
foreign = token_for(other, "/login")
|
|
assert client.post("/login", data={**data, "csrf_token": foreign}).status_code == 403
|
|
|
|
|
|
def test_admin_must_set_up_totp_then_login_with_second_factor(client: TestClient) -> None:
|
|
make_user(Role.ADMIN, "admin@example.de")
|
|
resp = login(client, "admin@example.de")
|
|
assert resp.headers["location"] == "/account?notice=mfa_required_admin"
|
|
assert client.get("/admin/users").headers["location"].startswith("/account")
|
|
|
|
setup = client.get("/account/totp")
|
|
assert setup.status_code == 200
|
|
sealed = re.search(r'name="sealed" value="([0-9a-f]+)"', setup.text)
|
|
secret_text = re.search(r'class="secret"><code>([A-Z2-7 ]+)</code>', setup.text)
|
|
assert sealed and secret_text
|
|
secret = secret_text.group(1).replace(" ", "")
|
|
code = totp.code_at_step(secret, totp.current_step(time.time()))
|
|
done = client.post(
|
|
"/account/totp",
|
|
data={
|
|
"sealed": sealed.group(1),
|
|
"code": code,
|
|
"current_password": PASSWORD,
|
|
"csrf_token": csrf_from(setup.text),
|
|
},
|
|
)
|
|
assert done.status_code == 200
|
|
codes = re.findall(r"<code>([A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4})</code>", done.text)
|
|
assert len(codes) == 10
|
|
assert client.get("/admin/users").status_code == 200
|
|
|
|
# Abmelden, neu anmelden: jetzt mit zweitem Faktor
|
|
client.post("/logout", data={"csrf_token": csrf_from(done.text)})
|
|
resp = login(client, "admin@example.de")
|
|
assert resp.headers["location"].startswith("/login/mfa")
|
|
mfa_page = client.get("/login/mfa")
|
|
token = csrf_from(mfa_page.text)
|
|
wrong = client.post("/login/mfa", data={"code": "000000", "csrf_token": token, "next": "/"})
|
|
assert wrong.status_code == 400
|
|
# Derselbe TOTP-Code wie bei der Einrichtung zählt nicht ein zweites Mal
|
|
replay = client.post("/login/mfa", data={"code": code, "csrf_token": token, "next": "/"})
|
|
assert replay.status_code == 400
|
|
ok = client.post("/login/mfa", data={"code": codes[0], "csrf_token": token, "next": "/"})
|
|
assert ok.status_code == 303 and ok.headers["location"] == "/"
|
|
assert client.get("/admin/users").status_code == 200
|
|
|
|
# Ein Wiederherstellungscode funktioniert nur einmal
|
|
with Session(db.get_engine()) as s:
|
|
user = service.find_by_email(s, "admin@example.de")
|
|
assert user is not None
|
|
settings: Settings = get_settings()
|
|
assert service.verify_second_factor(s, settings, user, codes[0]) is None
|
|
assert service.verify_second_factor(s, settings, user, codes[1]) == "recovery"
|
|
|
|
|
|
def test_admin_invites_user_who_sets_password( # type: ignore[no-untyped-def]
|
|
client: TestClient, app
|
|
) -> None:
|
|
_, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True)
|
|
assert secret
|
|
login(client, "admin@example.de")
|
|
mfa = client.get("/login/mfa")
|
|
client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text),
|
|
"next": "/"})
|
|
form = client.get("/admin/users/new")
|
|
assert form.status_code == 200
|
|
created = client.post(
|
|
"/admin/users/new",
|
|
data={"email": "Bob@Example.de", "display_name": "Bob", "role": "creator",
|
|
"csrf_token": csrf_from(form.text)},
|
|
)
|
|
assert created.status_code == 200
|
|
link = re.search(r"http://localhost/setup/([A-Za-z0-9_-]+)", created.text)
|
|
assert link
|
|
|
|
with new_client(app) as bob:
|
|
page = bob.get(f"/setup/{link.group(1)}")
|
|
assert page.status_code == 200
|
|
mismatch = bob.post(
|
|
f"/setup/{link.group(1)}",
|
|
data={"password": PASSWORD, "password2": PASSWORD + "x",
|
|
"csrf_token": csrf_from(page.text)},
|
|
)
|
|
assert mismatch.status_code == 400
|
|
done = bob.post(
|
|
f"/setup/{link.group(1)}",
|
|
data={"password": PASSWORD, "password2": PASSWORD,
|
|
"csrf_token": csrf_from(page.text)},
|
|
)
|
|
assert done.headers["location"] == "/login?notice=setup_done"
|
|
# Link ist verbraucht
|
|
assert bob.get(f"/setup/{link.group(1)}").status_code == 410
|
|
assert login(bob, "bob@example.de").status_code == 303
|
|
|
|
|
|
def test_participant_cannot_open_admin(client: TestClient) -> None:
|
|
make_user()
|
|
login(client, "anna@example.de")
|
|
assert client.get("/admin/users").status_code == 403
|
|
assert client.get("/admin/audit").status_code == 403
|
|
|
|
|
|
def test_last_admin_cannot_remove_own_rights(client: TestClient) -> None:
|
|
admin, secret = make_user(Role.ADMIN, "admin@example.de", with_totp=True)
|
|
assert secret
|
|
login(client, "admin@example.de")
|
|
mfa = client.get("/login/mfa")
|
|
client.post("/login/mfa", data={"code": next_totp(secret), "csrf_token": csrf_from(mfa.text),
|
|
"next": "/"})
|
|
page = client.get(f"/admin/users/{admin.public_id}")
|
|
resp = client.post(
|
|
f"/admin/users/{admin.public_id}",
|
|
data={"display_name": "Admin", "role": "participant", "is_active": "on",
|
|
"csrf_token": csrf_from(page.text)},
|
|
)
|
|
assert resp.status_code == 400
|
|
with Session(db.get_engine()) as s:
|
|
assert service.count_active_admins(s) == 1
|
|
|
|
|
|
def test_audit_log_contains_no_personal_data(client: TestClient) -> None:
|
|
make_user()
|
|
login(client, "anna@example.de", "falsches passwort!!")
|
|
login(client, "anna@example.de")
|
|
with Session(db.get_engine()) as s:
|
|
events = list(s.scalars(select(AuditEvent)))
|
|
assert {e.action for e in events} >= {"auth.login_failed", "auth.login"}
|
|
for e in events:
|
|
blob = f"{e.target_id} {e.details}"
|
|
assert "@" not in blob and "anna" not in blob.lower()
|
|
|
|
|
|
def test_security_headers_on_pages(client: TestClient) -> None:
|
|
resp = client.get("/login")
|
|
assert "default-src 'self'" in resp.headers["content-security-policy"]
|
|
assert resp.headers["x-frame-options"] == "DENY"
|
|
assert resp.headers["cache-control"] == "no-store"
|
|
assert "surveybox_csrf" in client.cookies
|