"""Context rights for the first delivery. Provisional MVP assumptions, not final product decisions, live in docs/MVP_ANNAHMEN.md. The action context is the only rights path used here. A case link inherits that case's rights. Cross-links do not. Exceptions apply only in the context they name. """ from __future__ import annotations from dataclasses import dataclass from typing import Any from uuid import UUID from psycopg.types.json import Json from app.core.errors import conflict, forbidden, not_found, unprocessable SHARED_NOTICE = "Diese Änderung betrifft den gemeinsamen Inhalt der Notiz." @dataclass(frozen=True) class Rights: read: bool = False edit: bool = False share: bool = False delete: bool = False @classmethod def full(cls) -> Rights: return cls(True, True, True, True) @classmethod def from_row(cls, row: dict | None) -> Rights: if row is None: return cls() return cls(bool(row["can_read"]), bool(row["can_edit"]), bool(row["can_share"]), bool(row["can_delete"])) def without(self, blocked: Rights) -> Rights: return Rights( self.read and not blocked.read, self.edit and not blocked.edit, self.share and not blocked.share, self.delete and not blocked.delete, ) def allows(self, need: str) -> bool: return bool(getattr(self, need)) def as_dict(self) -> dict[str, bool]: return {"read": self.read, "edit": self.edit, "share": self.share, "delete": self.delete} @dataclass(frozen=True) class Ctx: kind: str id: UUID def as_dict(self) -> dict[str, str]: return {"kind": self.kind, "id": str(self.id)} def parse_context(payload: dict | None, *, required: bool = False) -> Ctx | None: if not payload: if required: raise unprocessable("Der Handlungskontext fehlt.") return None kind = payload.get("kind") raw = payload.get("id") if kind not in ("case", "matter") or not raw: raise unprocessable("Der Handlungskontext ist ungültig.") try: return Ctx(kind, UUID(str(raw))) except ValueError as exc: raise unprocessable("Der Handlungskontext ist ungültig.") from exc def parse_query_context(kind: str | None, raw: str | None) -> Ctx | None: if kind is None and raw is None: return None return parse_context({"kind": kind, "id": raw}, required=True) def audit( conn, actor_id: UUID | None, scope_id: UUID | None, action: str, resource_kind: str, resource_id: UUID, context: Ctx | None = None, occurred_on=None, *, result: str = "ok", detail: dict | None = None, ) -> None: conn.execute( """ INSERT INTO domain_events ( actor_subject_id, scope_id, action, resource_kind, resource_id, context_kind, context_id, occurred_on, result, detail ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( actor_id, scope_id, action, resource_kind, resource_id, context.kind if context else None, context.id if context else None, occurred_on, result, Json(detail) if detail is not None else None, ), ) def bump_version(conn, table: str, row_id: UUID, expected: int) -> int: if table not in {"cases", "matters", "elements", "tasks", "deadlines"}: raise RuntimeError("unsupported version table") row = conn.execute( f"UPDATE {table} SET version = version + 1, updated_at = now() " f"WHERE id = %s AND version = %s AND deleted_at IS NULL RETURNING version", (row_id, expected), ).fetchone() if row is None: current = conn.execute( f"SELECT version, deleted_at FROM {table} WHERE id = %s", (row_id,), ).fetchone() if current is None or current["deleted_at"] is not None: raise not_found() raise conflict() return int(row["version"]) def _get(conn, table: str, row_id: UUID) -> dict | None: if table not in {"cases", "matters", "elements", "tasks", "deadlines", "data_rooms"}: raise RuntimeError("unsupported lookup") return conn.execute(f"SELECT * FROM {table} WHERE id = %s", (row_id,)).fetchone() def get_case(conn, case_id: UUID) -> dict | None: row = _get(conn, "cases", case_id) if row is None or row["deleted_at"] is not None: return None return row def get_matter(conn, matter_id: UUID) -> dict | None: row = _get(conn, "matters", matter_id) if row is None or row["deleted_at"] is not None: return None return row def get_element(conn, element_id: UUID) -> dict | None: row = _get(conn, "elements", element_id) if row is None or row["deleted_at"] is not None: return None return row def get_task(conn, task_id: UUID) -> dict | None: row = _get(conn, "tasks", task_id) if row is None or row["deleted_at"] is not None: return None return row def get_deadline(conn, deadline_id: UUID) -> dict | None: row = _get(conn, "deadlines", deadline_id) if row is None or row["deleted_at"] is not None: return None return row def _direct_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights: row = conn.execute( """ SELECT can_read, can_edit, can_share, can_delete FROM access_grants WHERE NOT is_exception AND grantee_subject_id = %s AND resource_kind = %s AND resource_id = %s AND context_kind IS NULL """, (actor, kind, resource_id), ).fetchone() return Rights.from_row(row) def _exceptions(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx | None) -> Rights: rows = conn.execute( """ SELECT can_read, can_edit, can_share, can_delete FROM access_grants WHERE is_exception AND resource_kind = %s AND resource_id = %s AND context_kind IS NOT DISTINCT FROM %s AND context_id IS NOT DISTINCT FROM %s AND (grantee_subject_id IS NULL OR grantee_subject_id = %s) """, ( kind, resource_id, context.kind if context else None, context.id if context else None, actor, ), ).fetchall() blocked = Rights() for row in rows: blocked = Rights( blocked.read or row["can_read"], blocked.edit or row["can_edit"], blocked.share or row["can_share"], blocked.delete or row["can_delete"], ) return blocked def case_rights(conn, actor: UUID, case: dict) -> Rights: if case["parent_case_id"] is not None and case["rights_mode"] == "inherit_parent": parent = get_case(conn, case["parent_case_id"]) base = case_rights(conn, actor, parent) if parent else Rights() elif case["owner_subject_id"] == actor: base = Rights.full() else: base = _direct_grant(conn, actor, "case", case["id"]) return base.without(_exceptions(conn, actor, "case", case["id"], None)) def _linked(conn, matter_id: UUID, case_id: UUID) -> bool: row = conn.execute( "SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s", (matter_id, case_id), ).fetchone() return row is not None def matter_rights(conn, actor: UUID, matter: dict, context: Ctx | None) -> Rights: if context is None: base = Rights.full() if matter["owner_subject_id"] == actor else _direct_grant(conn, actor, "matter", matter["id"]) return base.without(_exceptions(conn, actor, "matter", matter["id"], None)) if context.kind == "case": anchor_id = matter["id"] if not _linked(conn, matter["id"], context.id) and matter["parent_matter_id"] is not None: if _linked(conn, matter["parent_matter_id"], context.id): anchor_id = matter["parent_matter_id"] else: return Rights() elif not _linked(conn, matter["id"], context.id): return Rights() case = get_case(conn, context.id) if case is None: return Rights() base = case_rights(conn, actor, case) if anchor_id != matter["id"]: parent = get_matter(conn, anchor_id) if parent is None: return Rights() base = matter_rights(conn, actor, parent, context) return base.without(_exceptions(conn, actor, "matter", matter["id"], context)) if context.kind == "matter": if matter["parent_matter_id"] != context.id: return Rights() parent = get_matter(conn, context.id) if parent is None: return Rights() base = matter_rights(conn, actor, parent, None) return base.without(_exceptions(conn, actor, "matter", matter["id"], context)) return Rights() def _bindings(conn, element_id: UUID) -> list[dict]: return conn.execute( "SELECT * FROM bindings WHERE element_id = %s ORDER BY position, created_at", (element_id,), ).fetchall() def _blocked(conn, case_id: UUID, element_id: UUID) -> bool: row = conn.execute( """ SELECT 1 FROM case_link_blocks b JOIN matter_case_links l ON l.id = b.link_id WHERE l.case_id = %s AND b.element_id = %s """, (case_id, element_id), ).fetchone() return row is not None def _matter_reaches_case(conn, matter_id: UUID, case_id: UUID) -> bool: matter = get_matter(conn, matter_id) if matter is None: return False if _linked(conn, matter_id, case_id): return True return bool(matter["parent_matter_id"] and _linked(conn, matter["parent_matter_id"], case_id)) def element_rights(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights: if context is None: base = ( Rights.full() if element["owner_subject_id"] == actor else _direct_grant(conn, actor, "element", element["id"]) ) return base.without(_exceptions(conn, actor, "element", element["id"], None)) bindings = _bindings(conn, element["id"]) if context.kind == "case": on_case = any(item["context_kind"] == "case" and item["context_id"] == context.id for item in bindings) via_matter = [ item for item in bindings if item["context_kind"] == "matter" and _matter_reaches_case(conn, item["context_id"], context.id) ] if not on_case and not via_matter: return Rights() if not on_case and _blocked(conn, context.id, element["id"]): return Rights() case = get_case(conn, context.id) if case is None: return Rights() base = case_rights(conn, actor, case) return base.without(_exceptions(conn, actor, "element", element["id"], context)) if context.kind == "matter": matter = get_matter(conn, context.id) if matter is None: return Rights() hosted = any( item["context_kind"] == "matter" and (item["context_id"] == context.id or _child_of(conn, item["context_id"], context.id)) for item in bindings ) if not hosted: return Rights() base = matter_rights(conn, actor, matter, None) return base.without(_exceptions(conn, actor, "element", element["id"], context)) return Rights() def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool: matter = get_matter(conn, matter_id) return bool(matter and matter["parent_matter_id"] == parent_id) def _rights_bearing_case(conn, case: dict) -> dict: seen: set[UUID] = set() current = case while current["parent_case_id"] is not None and current["rights_mode"] == "inherit_parent": if current["id"] in seen: break seen.add(current["id"]) parent = get_case(conn, current["parent_case_id"]) if parent is None: break current = parent return current def _source_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> dict | None: return conn.execute( """ SELECT can_read, use_owner_sources FROM access_grants WHERE NOT is_exception AND grantee_subject_id = %s AND resource_kind = %s AND resource_id = %s AND context_kind IS NULL """, (actor, kind, resource_id), ).fetchone() def mediated_source_owner(conn, actor: UUID, element: dict, context: Ctx | None) -> UUID | None: """Owner whose stored connector may serve this reader. None unless the grant allows it.""" if context is None or not element_rights(conn, actor, element, context).read: return None if context.kind == "case": resource = get_case(conn, context.id) if resource is None: return None resource = _rights_bearing_case(conn, resource) grant = _source_grant(conn, actor, "case", resource["id"]) elif context.kind == "matter": resource = get_matter(conn, context.id) if resource is None: return None grant = _source_grant(conn, actor, "matter", resource["id"]) else: return None if resource["owner_subject_id"] == actor: return None if grant is None or not grant["can_read"] or not grant["use_owner_sources"]: return None return resource["owner_subject_id"] def element_rights_via_case_or_direct(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights: """Rights for an element bound to a matter when the caller names a case path. A matter context uses direct matter rights. A case context uses that case only. """ if context is None: return element_rights(conn, actor, element, None) if context.kind == "matter": return element_rights(conn, actor, element, context) return element_rights(conn, actor, element, context) def task_rights(conn, actor: UUID, task: dict, context: Ctx | None) -> Rights: if task["assignee_subject_id"] == actor and context is None: granted = _direct_grant(conn, actor, "task", task["id"]) base = Rights(read=True, edit=granted.edit, share=False, delete=False) if task["owner_subject_id"] == actor: base = Rights.full() return base.without(_exceptions(conn, actor, "task", task["id"], None)) if context is None: base = Rights.full() if task["owner_subject_id"] == actor else _direct_grant(conn, actor, "task", task["id"]) return base.without(_exceptions(conn, actor, "task", task["id"], None)) if task["matter_id"] is None: return Rights() matter = get_matter(conn, task["matter_id"]) if matter is None: return Rights() if context.kind == "matter" and context.id == task["matter_id"]: base = matter_rights(conn, actor, matter, None) elif context.kind == "case": base = matter_rights(conn, actor, matter, context) elif context.kind == "matter" and matter["parent_matter_id"] == context.id: base = matter_rights(conn, actor, matter, context) else: return Rights() return base.without(_exceptions(conn, actor, "task", task["id"], context)) def deadline_rights(conn, actor: UUID, deadline: dict, context: Ctx | None) -> Rights: if deadline["assignee_subject_id"] == actor and context is None: base = Rights(read=True, edit=False, share=False, delete=False) if deadline["owner_subject_id"] == actor: base = Rights.full() return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None)) if context is None: base = ( Rights.full() if deadline["owner_subject_id"] == actor else _direct_grant(conn, actor, "deadline", deadline["id"]) ) return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None)) if deadline["matter_id"] is None: return Rights() matter = get_matter(conn, deadline["matter_id"]) if matter is None: return Rights() if context.kind == "matter" and context.id == deadline["matter_id"]: base = matter_rights(conn, actor, matter, None) elif context.kind == "case": base = matter_rights(conn, actor, matter, context) else: return Rights() return base.without(_exceptions(conn, actor, "deadline", deadline["id"], context)) def require_case(conn, actor: UUID, case_id: UUID, need: str) -> tuple[dict, Rights]: case = get_case(conn, case_id) if case is None: raise not_found() rights = case_rights(conn, actor, case) _require(rights, need) return case, rights def require_matter(conn, actor: UUID, matter_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]: matter = get_matter(conn, matter_id) if matter is None: raise not_found() rights = matter_rights(conn, actor, matter, context) _require(rights, need) return matter, rights def require_element(conn, actor: UUID, element_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]: element = get_element(conn, element_id) if element is None: raise not_found() rights = element_rights(conn, actor, element, context) _require(rights, need) return element, rights def _require(rights: Rights, need: str) -> None: if not rights.read: raise not_found() if need != "read" and not rights.allows(need): raise forbidden() def can_change_status(actor: UUID, row: dict, rights: Rights, assignee_key: str = "assignee_subject_id") -> bool: if rights.edit or row["owner_subject_id"] == actor: return True return row[assignee_key] == actor and rights.read def readable_matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]: found: list[dict] = [] direct = matter_rights(conn, actor, matter, None) if direct.read: found.append({"kind": "matter", "id": str(matter["id"]), "title": matter["title"], "rights": direct.as_dict()}) links = conn.execute( """ SELECT l.case_id, c.title FROM matter_case_links l JOIN cases c ON c.id = l.case_id WHERE l.matter_id = %s AND c.deleted_at IS NULL """, (matter["id"],), ).fetchall() if matter["parent_matter_id"] is not None: links = list(links) + list( conn.execute( """ SELECT l.case_id, c.title FROM matter_case_links l JOIN cases c ON c.id = l.case_id WHERE l.matter_id = %s AND c.deleted_at IS NULL """, (matter["parent_matter_id"],), ).fetchall() ) seen: set[UUID] = set() for link in links: if link["case_id"] in seen: continue seen.add(link["case_id"]) rights = matter_rights(conn, actor, matter, Ctx("case", link["case_id"])) if rights.read: found.append( { "kind": "case", "id": str(link["case_id"]), "title": link["title"], "rights": rights.as_dict(), } ) return found def list_cases(conn, actor: UUID) -> list[dict]: rows = conn.execute( """ SELECT c.* FROM cases c WHERE c.deleted_at IS NULL AND ( c.owner_subject_id = %(actor)s OR EXISTS ( SELECT 1 FROM access_grants g WHERE g.resource_kind = 'case' AND g.resource_id = c.id AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read AND g.context_id IS NULL ) OR ( c.rights_mode = 'inherit_parent' AND c.parent_case_id IS NOT NULL AND EXISTS ( SELECT 1 FROM cases p WHERE p.id = c.parent_case_id AND p.deleted_at IS NULL AND ( p.owner_subject_id = %(actor)s OR EXISTS ( SELECT 1 FROM access_grants g WHERE g.resource_kind = 'case' AND g.resource_id = p.id AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read AND g.context_id IS NULL ) ) ) ) ) ORDER BY c.updated_at DESC, c.id DESC """, {"actor": actor}, ).fetchall() visible = [] for row in rows: rights = case_rights(conn, actor, row) if rights.read: visible.append((row, rights)) return visible def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]: rows = conn.execute( """ SELECT m.* FROM matters m WHERE m.deleted_at IS NULL AND ( m.owner_subject_id = %(actor)s OR EXISTS ( SELECT 1 FROM access_grants g WHERE g.resource_kind = 'matter' AND g.resource_id = m.id AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read AND g.context_id IS NULL ) OR EXISTS ( SELECT 1 FROM matter_case_links l JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL WHERE l.matter_id = m.id AND ( c.owner_subject_id = %(actor)s OR EXISTS ( SELECT 1 FROM access_grants g WHERE g.resource_kind = 'case' AND g.resource_id = c.id AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read AND g.context_id IS NULL ) ) ) ) ORDER BY m.updated_at DESC, m.id DESC """, {"actor": actor}, ).fetchall() visible = [] for row in rows: contexts = readable_matter_contexts(conn, actor, row) if contexts: visible.append((row, contexts)) return visible def assert_scope_can_host(conn, scope_id: UUID) -> dict: room = _get(conn, "data_rooms", scope_id) if room is None or room["status"] != "active": raise forbidden("Der gewählte Datenraum ist nicht verfügbar.") return room def same_home(row: dict, scope_id: UUID) -> None: if row["home_scope_id"] != scope_id: raise unprocessable( "Unterakten, Teilvorgänge und Kapitel bleiben im Datenraum ihres Behälters. " "Wähle diesen Datenraum, wenn du dort Mitglied bist, oder lege einen Querverweis an." ) def account_by_email(conn, email: str) -> dict | None: return conn.execute( "SELECT id, email, display_name, status FROM auth_accounts WHERE email = %s", (email.strip().lower(),), ).fetchone() def display_name(conn, account_id: UUID | None) -> str | None: if account_id is None: return None row = conn.execute("SELECT display_name FROM auth_accounts WHERE id = %s", (account_id,)).fetchone() return row["display_name"] if row else None def room_name(conn, room_id: UUID) -> str | None: row = conn.execute("SELECT name FROM data_rooms WHERE id = %s", (room_id,)).fetchone() return row["name"] if row else None def visible_bindings_for_element(conn, actor: UUID, element: dict) -> list[dict]: """Names and counts only bindings the actor can actually read.""" result = [] for binding in _bindings(conn, element["id"]): if binding["context_kind"] == "case": context = Ctx("case", binding["context_id"]) rights = element_rights(conn, actor, element, context) if not rights.read: continue case = get_case(conn, binding["context_id"]) if case is None: continue title = case["title"] else: matter = get_matter(conn, binding["context_id"]) if matter is None: continue contexts = readable_matter_contexts(conn, actor, matter) if not contexts: continue direct = element_rights(conn, actor, element, Ctx("matter", matter["id"])) via_cases = [] for item in contexts: if item["kind"] != "case": continue case_rights_now = element_rights(conn, actor, element, Ctx("case", UUID(item["id"]))) if case_rights_now.read: via_cases.append(item) if not direct.read and not via_cases: continue title = matter["title"] context = Ctx("matter", matter["id"]) result.append( { "id": str(binding["id"]), "context_kind": binding["context_kind"], "context_id": str(binding["context_id"]), "context_title": title, "chapter_id": str(binding["chapter_id"]) if binding.get("chapter_id") else None, } ) return result def chapter_for(conn, chapter_id: UUID | None, kind: str, container_id: UUID) -> None: if chapter_id is None: return column = "case_id" if kind == "case" else "matter_id" row = conn.execute( f"SELECT id FROM chapters WHERE id = %s AND {column} = %s", (chapter_id, container_id), ).fetchone() if row is None: raise unprocessable("Das Kapitel gehört nicht zu diesem Kontext.") def next_position(conn, kind: str, container_id: UUID) -> int: row = conn.execute( "SELECT COALESCE(MAX(position), 0) + 1 AS pos FROM bindings WHERE context_kind = %s AND context_id = %s", (kind, container_id), ).fetchone() return int(row["pos"]) def insert_binding(conn, element_id: UUID, kind: str, container_id: UUID, chapter_id: UUID | None, actor: UUID) -> dict: existing = conn.execute( """ SELECT id FROM bindings WHERE element_id = %s AND context_kind = %s AND context_id = %s """, (element_id, kind, container_id), ).fetchone() if existing is not None: raise unprocessable("Die Notiz ist in diesem Kontext bereits eingebunden.") chapter_for(conn, chapter_id, kind, container_id) row = conn.execute( """ INSERT INTO bindings (element_id, context_kind, context_id, chapter_id, position, created_by) VALUES (%s, %s, %s, %s, %s, %s) RETURNING * """, (element_id, kind, container_id, chapter_id, next_position(conn, kind, container_id), actor), ).fetchone() return row def block_unsharable_matter_elements(conn, actor: UUID, link_id: UUID, matter: dict) -> None: """Contents the linking actor cannot share stay invisible in that case. No titles are stored.""" matter_ids = [matter["id"]] children = conn.execute( "SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL", (matter["id"],), ).fetchall() matter_ids.extend(item["id"] for item in children) for matter_id in matter_ids: bindings = conn.execute( "SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %s", (matter_id,), ).fetchall() container = get_matter(conn, matter_id) if container is None: continue for binding in bindings: element = get_element(conn, binding["element_id"]) if element is None: continue rights = element_rights(conn, actor, element, Ctx("matter", matter_id)) if matter_id != matter["id"]: parent_rights = element_rights(conn, actor, element, Ctx("matter", matter["id"])) if parent_rights.share: rights = parent_rights if rights.share: continue conn.execute( "INSERT INTO case_link_blocks (link_id, element_id) VALUES (%s, %s) ON CONFLICT DO NOTHING", (link_id, element["id"]), ) def matter_title_if_readable(conn, actor: UUID, matter_id: UUID | None) -> str | None: if matter_id is None: return None matter = get_matter(conn, matter_id) if matter is None: return None if readable_matter_contexts(conn, actor, matter): return matter["title"] return None def ensure_member_or_personal(conn, account_id: UUID, kind: str, scope_id: UUID) -> dict: room = assert_scope_can_host(conn, scope_id) if kind == "personal": if room["kind"] != "personal" or room["id"] != account_id: raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.") return room if kind != "organization" or room["kind"] != "organization": raise forbidden("Dieser Datenraum kann nicht gewählt werden.") membership = conn.execute( """ SELECT role FROM room_memberships WHERE room_id = %s AND subject_id = %s AND status = 'active' """, (scope_id, account_id), ).fetchone() if membership is None: raise forbidden("Du bist in diesem Datenraum nicht Mitglied.") return room