Files
surveybox/tests/test_group_scope.py
marco.morath 42dd1f2d4a
CI / audit (push) Skipped
CI / checks (push) Failing after 37s
CI / image (push) Skipped
Initial Commit: Status Testing
2026-11-25 18:46:04 +01:00

223 lines
8.9 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-or-later
"""Gruppenadministratoren, Gruppenersteller, Hierarchie (CI, PostgreSQL)."""
from __future__ import annotations
from typing import Any
import pytest
pytest.importorskip("fastapi")
from fastapi.testclient import TestClient
from helpers import csrf_from, login, make_user, new_client, next_totp, token_for
from sqlalchemy import select
from sqlalchemy.orm import Session
from test_forms import add_question, fill, form_row, set_status
from surveybox import db
from surveybox.models import (
Form,
FormAccessEntry,
GroupMember,
GroupRole,
Role,
UserAccount,
UserGroup,
)
pytestmark = pytest.mark.db
def build_tree() -> dict[str, int]:
"""Gesamtwehr > Nord > Jugend; Gesamtwehr > Süd."""
with Session(db.get_engine()) as s:
top = UserGroup(name="Gesamtwehr")
s.add(top)
s.flush()
north = UserGroup(name="Nord", parent_id=top.id)
south = UserGroup(name="Süd", parent_id=top.id)
s.add_all([north, south])
s.flush()
youth = UserGroup(name="Jugend", parent_id=north.id)
s.add(youth)
s.commit()
return {"top": top.id, "north": north.id, "south": south.id, "youth": youth.id}
def user_id(email: str) -> int:
with Session(db.get_engine()) as s:
uid = s.scalar(select(UserAccount.id).where(UserAccount.email == email))
assert uid is not None
return uid
def give(email: str, group: int, *, member: bool = True, role: str | None = None) -> None:
uid = user_id(email)
with Session(db.get_engine()) as s:
if member:
s.add(GroupMember(group_id=group, user_id=uid))
if role:
s.add(GroupRole(group_id=group, user_id=uid, role=role))
s.commit()
def public_id(group: int) -> str:
with Session(db.get_engine()) as s:
return str(s.get(UserGroup, group).public_id) # type: ignore[union-attr]
def signed_in(app: Any, email: str, secret: str | None = None) -> TestClient:
client = new_client(app)
login(client, email)
if secret:
mfa = client.get("/login/mfa")
client.post("/login/mfa", data={"code": next_totp(secret),
"csrf_token": csrf_from(mfa.text), "next": "/"})
return client
def test_group_admin_needs_second_factor(app: Any) -> None:
ids = build_tree()
make_user(Role.PARTICIPANT, "gina@example.de")
give("gina@example.de", ids["north"], role="admin")
client = signed_in(app, "gina@example.de")
resp = client.get("/admin/groups")
assert resp.status_code == 303
assert "mfa_required_admin" in resp.headers["location"]
def test_group_admin_scope(app: Any) -> None:
ids = build_tree()
_, secret = make_user(Role.PARTICIPANT, "gina@example.de", with_totp=True)
give("gina@example.de", ids["north"], role="admin")
make_user(Role.PARTICIPANT, "sven@example.de")
give("sven@example.de", ids["south"])
client = signed_in(app, "gina@example.de", secret)
listing = client.get("/admin/groups").text
assert "Nord" in listing and "Jugend" in listing
assert "Süd" not in listing and "Gesamtwehr" not in listing
assert client.get(f"/admin/groups/{public_id(ids['south'])}").status_code == 403
assert client.get("/admin/users").status_code == 403
# Neue Gruppe nur unterhalb der eigenen
csrf = token_for(client, "/admin/groups")
resp = client.post("/admin/groups", data={"name": "Oben", "csrf_token": csrf})
assert resp.status_code == 400
resp = client.post("/admin/groups", data={"name": "Kinder", "csrf_token": csrf,
"parent": public_id(ids["youth"])})
assert resp.status_code == 303
# Neues Konto direkt in der Jugend, als Teilnehmer
youth_page = f"/admin/groups/{public_id(ids['youth'])}"
csrf = token_for(client, youth_page)
resp = client.post(f"{youth_page}/new-member", data={
"csrf_token": csrf, "display_name": "Jana", "email": "jana@example.de"})
assert resp.status_code == 200 and "/setup/" in resp.text
with Session(db.get_engine()) as s:
jana = s.scalar(select(UserAccount).where(UserAccount.email == "jana@example.de"))
assert jana is not None and jana.role == Role.PARTICIPANT
assert s.get(GroupMember, (ids["youth"], jana.id)) is not None
sven_pid = str(s.scalar(select(UserAccount.public_id).where(
UserAccount.email == "sven@example.de")))
jana_pid = str(jana.public_id)
# Jana wird Gruppenerstellerin; Sven (Süd) kann nicht geholt werden
resp = client.post(f"{youth_page}/roles", data={"csrf_token": csrf, "user": jana_pid,
"role": "creator"})
assert resp.status_code == 303
resp = client.post(f"{youth_page}/members", data={"csrf_token": csrf, "user": sven_pid})
assert resp.status_code == 403
# Die eigene oberste Gruppe lässt sich nicht löschen, Untergruppen schon
north_page = f"/admin/groups/{public_id(ids['north'])}"
csrf = token_for(client, north_page)
assert client.post(f"{north_page}/delete",
data={"csrf_token": csrf, "confirm": "on"}).status_code == 403
def test_group_creator_forms_and_inheritance(app: Any) -> None:
ids = build_tree()
make_user(Role.PARTICIPANT, "carl@example.de")
give("carl@example.de", ids["north"], member=False, role="creator")
make_user(Role.PARTICIPANT, "jule@example.de")
give("jule@example.de", ids["youth"])
make_user(Role.PARTICIPANT, "sven@example.de")
give("sven@example.de", ids["south"])
carl = signed_in(app, "carl@example.de")
# Nur in eigenen Gruppen
csrf = token_for(carl, "/forms")
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug",
"group": public_id(ids["south"])})
assert resp.status_code == 400
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug"})
assert resp.status_code == 400
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Ausflug",
"group": public_id(ids["north"])})
assert resp.status_code == 303
pid = resp.headers["location"].rsplit("/", 1)[-1]
form = form_row(pid)
assert form.access == "restricted" and form.group_id == ids["north"]
with Session(db.get_engine()) as s:
entries = list(s.scalars(select(FormAccessEntry.group_id).where(
FormAccessEntry.form_id == form.id)))
assert entries == [ids["north"]]
# "Alle angemeldeten Benutzer" ist gesperrt
csrf = token_for(carl, f"/forms/{pid}/settings")
resp = carl.post(f"/forms/{pid}/settings", data={
"csrf_token": csrf, "title": "Ausflug", "access": "users", "allow_edit": "until_close",
"deletion_mode": "anonymize", "guest_email": "none", "results_visibility": "never",
"group": public_id(ids["north"])})
assert resp.status_code == 400
access_page = carl.get(f"/forms/{pid}/access").text
assert "Jugend" in access_page and "Süd" not in access_page
add_question(carl, pid, "short_text", label="Name")
assert set_status(carl, pid, "open").status_code == 303
token = form_row(pid).share_token
qid = _question_id(pid)
# Mitglied der Untergruppe Jugend darf, Süd nicht
jule = signed_in(app, "jule@example.de")
assert jule.get(f"/f/{token}").status_code == 200
assert "Ausflug" in jule.get("/").text
assert fill(jule, token, {f"q{qid}": "Jule"}).status_code == 303
sven = signed_in(app, "sven@example.de")
assert sven.get(f"/f/{token}").status_code == 403
def test_group_admin_manages_forms_below(app: Any) -> None:
ids = build_tree()
make_user(Role.PARTICIPANT, "carl@example.de")
give("carl@example.de", ids["youth"], member=False, role="creator")
_, secret = make_user(Role.PARTICIPANT, "gina@example.de", with_totp=True)
give("gina@example.de", ids["north"], member=False, role="admin")
_, secret_s = make_user(Role.PARTICIPANT, "sina@example.de", with_totp=True)
give("sina@example.de", ids["south"], member=False, role="admin")
carl = signed_in(app, "carl@example.de")
csrf = token_for(carl, "/forms")
resp = carl.post("/forms", data={"csrf_token": csrf, "title": "Zeltlager",
"group": public_id(ids["youth"])})
pid = resp.headers["location"].rsplit("/", 1)[-1]
gina = signed_in(app, "gina@example.de", secret)
assert gina.get(f"/forms/{pid}").status_code == 200
assert "Zeltlager" in gina.get("/forms").text
assert gina.get(f"/forms/{pid}/team").status_code == 200 # Verwaltung wie Eigentümer
sina = signed_in(app, "sina@example.de", secret_s)
assert sina.get(f"/forms/{pid}").status_code == 403
assert "Zeltlager" not in sina.get("/forms").text
def _question_id(pid: str) -> int:
import uuid
with Session(db.get_engine()) as s:
form = s.scalar(select(Form).where(Form.public_id == uuid.UUID(pid)))
assert form is not None
return form.questions[0].id