Fuehre die Pflicht-Suite gegen eine Wegwerfdatenbank und lege Nutzer als Betreiber an.
Deploy Development / deploy (push) Failing after 40s
Deploy Development / deploy (push) Failing after 40s
Testdaten entstehen nur dort und werden danach entfernt, damit Dev und Produktion sie nicht behalten. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
528fc191e8
commit
4420790707
24 files changed
+1264
-26
No files matched your search
@@ -34,7 +34,9 @@ from app.access.policy import (
|
||||
from app.api.deps import Principal, get_conn, get_principal, get_session
|
||||
from app.api.schemas import (
|
||||
AcceptInviteIn,
|
||||
AccountIn,
|
||||
AnnotationIn,
|
||||
BootstrapIn,
|
||||
AssigneeIn,
|
||||
BindingIn,
|
||||
CaseIn,
|
||||
@@ -72,7 +74,7 @@ from app.auth.security import (
|
||||
verify_password,
|
||||
)
|
||||
from app.core.errors import Problem, forbidden, not_found, too_many, unprocessable
|
||||
from app.core.timeutil import utcnow
|
||||
from app.core.timeutil import dump_dt, utcnow
|
||||
from app.media.storage import content_disposition, read_bytes
|
||||
from app.media.storage import asset_path
|
||||
from app.ops import (
|
||||
@@ -140,7 +142,7 @@ def _ctx_model(value) -> Ctx | None:
|
||||
|
||||
def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf: str, epoch: int) -> dict:
|
||||
account = conn.execute(
|
||||
"SELECT id, email, display_name FROM auth_accounts WHERE id = %s",
|
||||
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
room = conn.execute("SELECT id, kind, name FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
||||
@@ -149,6 +151,7 @@ def _session_body(conn, account_id: UUID, scope_kind: str, scope_id: UUID, csrf:
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
},
|
||||
"scope": {"kind": scope_kind, "id": str(room["id"]), "name": room["name"]},
|
||||
"rooms": list_rooms(conn, account_id),
|
||||
@@ -232,6 +235,81 @@ def demo(request: Request):
|
||||
return demo_public(request.app.state.settings)
|
||||
|
||||
|
||||
def _superadmin_exists(conn: Connection) -> bool:
|
||||
return conn.execute("SELECT 1 FROM auth_accounts WHERE is_superadmin LIMIT 1").fetchone() is not None
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/bootstrap")
|
||||
def bootstrap_available(conn: Connection = Depends(get_conn)):
|
||||
if _superadmin_exists(conn):
|
||||
raise not_found()
|
||||
return {"available": True}
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/bootstrap")
|
||||
def bootstrap(body: BootstrapIn, request: Request, conn: Connection = Depends(get_conn)):
|
||||
conn.execute("LOCK TABLE auth_accounts IN EXCLUSIVE MODE")
|
||||
if _superadmin_exists(conn):
|
||||
raise not_found()
|
||||
account = create_account(conn, body.email, body.display_name, body.password, is_superadmin=True)
|
||||
settings = request.app.state.settings
|
||||
token, csrf = start_session(conn, settings, account["id"])
|
||||
payload = _session_body(conn, account["id"], "personal", account["id"], csrf, 1)
|
||||
response = JSONResponse(status_code=201, content=payload)
|
||||
set_session_cookie(response, request, settings, token)
|
||||
return response
|
||||
|
||||
|
||||
def _require_superadmin(conn: Connection, principal: Principal) -> None:
|
||||
row = conn.execute(
|
||||
"SELECT is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
(principal.account_id,),
|
||||
).fetchone()
|
||||
if row is None or not row["is_superadmin"]:
|
||||
raise forbidden("Nur der Betreiber kann Nutzer anlegen.")
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts")
|
||||
def accounts(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_superadmin(conn, principal)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, created_at
|
||||
FROM auth_accounts
|
||||
WHERE origin = 'operator' AND status = 'active'
|
||||
ORDER BY display_name, email
|
||||
"""
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"is_superadmin": row["is_superadmin"],
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
"next_cursor": None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts")
|
||||
def post_account(body: AccountIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
_require_superadmin(conn, principal)
|
||||
account = create_account(conn, body.email, body.display_name, body.password)
|
||||
return _created(
|
||||
f"/api/v1/accounts/{account['id']}",
|
||||
{
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/invitations")
|
||||
def invite(
|
||||
body: InvitationIn,
|
||||
|
||||
@@ -20,6 +20,18 @@ class LoginIn(APIModel):
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class BootstrapIn(APIModel):
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class AccountIn(APIModel):
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class ScopeIn(APIModel):
|
||||
kind: Literal["personal", "organization"]
|
||||
id: UUID
|
||||
|
||||
@@ -13,19 +13,29 @@ def normalize_email(email: str) -> str:
|
||||
return email.strip().lower()
|
||||
|
||||
|
||||
def create_account(conn, email: str, display_name: str, password: str) -> dict:
|
||||
def create_account(
|
||||
conn,
|
||||
email: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
*,
|
||||
is_superadmin: bool = False,
|
||||
origin: str = "operator",
|
||||
) -> dict:
|
||||
email = normalize_email(email)
|
||||
display_name = display_name.strip()
|
||||
if origin not in {"operator", "fixture"}:
|
||||
raise unprocessable("Die Kontenherkunft ist ungültig.")
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone():
|
||||
raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.")
|
||||
account_id = uuid4()
|
||||
password_hash = hash_password(password)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash, is_superadmin, origin)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(account_id, email, display_name, password_hash),
|
||||
(account_id, email, display_name, password_hash, is_superadmin, origin),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -35,7 +45,7 @@ def create_account(conn, email: str, display_name: str, password: str) -> dict:
|
||||
(account_id, account_id),
|
||||
)
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name FROM auth_accounts WHERE id = %s",
|
||||
"SELECT id, email, display_name, is_superadmin FROM auth_accounts WHERE id = %s",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
+4
-6
@@ -1,4 +1,4 @@
|
||||
"""Operator commands: migrate, seed demo data, create the first account."""
|
||||
"""Operator commands: migrate and create an account. Demo seed stays in the test suite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,6 @@ import argparse
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
@@ -29,13 +28,12 @@ def main() -> None:
|
||||
print("applied" if applied else "up to date")
|
||||
return
|
||||
if args.command == "seed-demo":
|
||||
created = seed_demo(settings)
|
||||
print("seeded" if created else "unchanged")
|
||||
return
|
||||
raise SystemExit("Testdaten legt nur die Test-Suite an und entfernt sie wieder.")
|
||||
if len(args.password) < 10:
|
||||
raise SystemExit("password must be at least 10 characters")
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
account = create_account(conn, args.email, args.name, args.password)
|
||||
has_admin = conn.execute("SELECT 1 FROM auth_accounts WHERE is_superadmin LIMIT 1").fetchone()
|
||||
account = create_account(conn, args.email, args.name, args.password, is_superadmin=has_admin is None)
|
||||
conn.commit()
|
||||
print(account["id"])
|
||||
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
"""Migrate, optionally seed development data, then serve."""
|
||||
"""Migrate, drop leftover fixtures, then serve. Demo seed never runs here."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
from app.fixtures import purge_fixture_data
|
||||
|
||||
|
||||
def prepare(settings: Settings | None = None) -> None:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env == "production" and settings.seed_demo:
|
||||
raise SystemExit("SEED_DEMO darf in der Produktion nicht aktiv sein.")
|
||||
migrate(settings)
|
||||
purge_fixture_data(settings)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
migrate()
|
||||
seed_demo()
|
||||
prepare()
|
||||
os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"])
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Remove fixture accounts and everything that belongs only to them.
|
||||
|
||||
Operator accounts and their cases stay. The test suite calls this after seeding
|
||||
the ephemeral database. Every environment also calls it at startup, so a copied
|
||||
development database cannot carry Ada and Ben into production.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
|
||||
_PURGE = (
|
||||
"""
|
||||
DELETE FROM context_annotations
|
||||
WHERE author_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR binding_id IN (
|
||||
SELECT b.id FROM bindings b
|
||||
JOIN elements e ON e.id = b.element_id
|
||||
WHERE e.owner_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR b.created_by IN (SELECT id FROM fixture_accounts)
|
||||
)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM bindings
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM correspondence_dates
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM note_bodies
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM external_references
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM media_operations
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR asset_id IN (SELECT id FROM media_assets WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM media_assets
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM task_deadline_links
|
||||
WHERE task_id IN (SELECT id FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR deadline_id IN (SELECT id FROM deadlines WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE tasks SET assignee_subject_id = NULL
|
||||
WHERE assignee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET assignee_subject_id = NULL
|
||||
WHERE assignee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE tasks SET matter_id = NULL
|
||||
WHERE matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET matter_id = NULL
|
||||
WHERE matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET element_id = NULL
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"DELETE FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM deadlines WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
DELETE FROM matter_case_links
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM matter_cross_links
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR from_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR to_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM chapters
|
||||
WHERE case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
UPDATE matters SET parent_matter_id = NULL
|
||||
WHERE parent_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM matters
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts) AND parent_matter_id IS NOT NULL
|
||||
""",
|
||||
"DELETE FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
UPDATE cases SET parent_case_id = NULL
|
||||
WHERE parent_case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM cases
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts) AND parent_case_id IS NOT NULL
|
||||
""",
|
||||
"DELETE FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
DELETE FROM access_grants
|
||||
WHERE grantee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"DELETE FROM auth_invitations WHERE invited_by IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM auth_sessions WHERE account_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM room_memberships WHERE subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM connectors WHERE owner_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM domain_events WHERE actor_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
UPDATE data_rooms
|
||||
SET created_by = (
|
||||
SELECT m.subject_id FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
ORDER BY m.created_at
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM data_rooms
|
||||
WHERE id IN (SELECT id FROM fixture_accounts)
|
||||
OR (
|
||||
created_by IN (SELECT id FROM fixture_accounts)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
)
|
||||
)
|
||||
""",
|
||||
"DELETE FROM auth_accounts WHERE id IN (SELECT id FROM fixture_accounts)",
|
||||
)
|
||||
|
||||
|
||||
def purge_fixture_data(settings: Settings | None = None) -> int:
|
||||
settings = settings or get_settings()
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
fixtures = conn.execute("SELECT id FROM auth_accounts WHERE origin = 'fixture'").fetchall()
|
||||
if not fixtures:
|
||||
conn.rollback()
|
||||
return 0
|
||||
conn.execute("CREATE TEMP TABLE fixture_accounts (id uuid PRIMARY KEY) ON COMMIT DROP")
|
||||
conn.executemany("INSERT INTO fixture_accounts (id) VALUES (%s)", [(row["id"],) for row in fixtures])
|
||||
assets = conn.execute(
|
||||
"SELECT id FROM media_assets WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)"
|
||||
).fetchall()
|
||||
for statement in _PURGE:
|
||||
conn.execute(statement)
|
||||
conn.commit()
|
||||
root = Path(settings.media_root)
|
||||
for asset in assets:
|
||||
(root / str(asset["id"])).unlink(missing_ok=True)
|
||||
return len(fixtures)
|
||||
+9
-5
@@ -1,4 +1,4 @@
|
||||
"""Synthetic development accounts and a rental matter. Never runs in production."""
|
||||
"""Synthetic rental case for the ephemeral test database. Never persists on dev or prod."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -47,8 +47,12 @@ trailer<</Root 1 0 R>>
|
||||
"""
|
||||
|
||||
|
||||
def demo_allowed(settings: Settings) -> bool:
|
||||
return settings.tsumugu_env == "development" and settings.db_name == "tsumugu_pytest" and settings.seed_demo
|
||||
|
||||
|
||||
def demo_public(settings: Settings) -> dict:
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
if not demo_allowed(settings):
|
||||
raise not_found()
|
||||
return {
|
||||
"accounts": [
|
||||
@@ -60,15 +64,15 @@ def demo_public(settings: Settings) -> dict:
|
||||
|
||||
def seed_demo(settings: Settings | None = None) -> bool:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
if not demo_allowed(settings):
|
||||
return False
|
||||
cleanup: list[Path] = []
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
try:
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone():
|
||||
return False
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD)
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD)
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD, origin="fixture")
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD, origin="fixture")
|
||||
room = conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
|
||||
Reference in new issue
Block a user