Files
tsumugu/backend/app/access/policy.py
T
LarsandClaude Opus 5.5 15e0dc7e52
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Successful in 6m39s
Test Suite / frontend-build (push) Successful in 24s
Test Suite / smoke-dev (push) Successful in 0s
Gib verknüpfte Originale im Datenraum je Person über die eigenen Zugänge frei, damit Raummitglieder Paperless-Dokumente und E-Mails geteilter Akten lesen können.
Die Raumfreigabe allein gab die Zugänge des Owners nicht weiter. Ein Leser im Raum sah die Akte,
aber kein Original. Neu ist room_source_access: Wer im Raum teilen darf, schaltet für ein Mitglied
„Originale über meine Zugänge“ ein. Das gilt für alle eigenen, mit dem Raum geteilten Einträge.
Ausnahmen, Ende der Raumfreigabe und Verlassen des Raums schließen den Abruf. Beschluss R-01 ist
entsprechend ergänzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:19:15 +01:00

952 lines
35 KiB
Python

"""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
# Saving or opening the original outside of Tsumugu. Reading in the app does not need it.
download: bool = False
@classmethod
def full(cls) -> Rights:
return cls(True, True, True, True, True)
@classmethod
def from_row(cls, row: dict | None, download: bool = False) -> 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"]), download and bool(row["can_read"]))
def union(self, other: Rights) -> Rights:
return Rights(
self.read or other.read,
self.edit or other.edit,
self.share or other.share,
self.delete or other.delete,
self.download or other.download,
)
def without(self, blocked: Rights) -> Rights:
# An exception that takes away reading takes away downloading too.
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,
self.download and not blocked.read,
)
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, "download": self.read and self.download}
# The room share: what a room role may do with a case or matter that is shared with the room.
# Sharing, deleting and ownership never come from a room role. An unknown role gets nothing.
ROOM_RIGHTS = {
"reader": Rights(read=True),
"member": Rights(read=True, edit=True),
"manager": Rights(read=True, edit=True),
}
@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()
if row is None:
return Rights()
return Rights.from_row(row, _direct_download(conn, kind, resource_id))
def _direct_download(conn, kind: str, resource_id: UUID) -> bool:
"""Direct recipients follow the download setting `direct` of the owner of the entry."""
table = {"case": "cases", "matter": "matters", "element": "elements"}.get(kind)
if table is None:
return False
row = conn.execute(
f"""
SELECT a.download_defaults
FROM {table} r JOIN auth_accounts a ON a.id = r.owner_subject_id
WHERE r.id = %s
""",
(resource_id,),
).fetchone()
return bool(row and row["download_defaults"].get("direct", False))
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 room_default(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights:
"""Rights of the current members of the rooms a case or matter is shared with.
A room is a team. The rights of one share are the role of the person in that room,
capped by the share (`read` or `edit`). Several shares add up. Only an active room,
an active membership and an active account count. Anything unclear gives no rights.
"""
rows = conn.execute(
"""
SELECT m.role, s.access, r.download_roles
FROM room_shares s
JOIN room_memberships m ON m.room_id = s.room_id AND m.subject_id = %s AND m.status = 'active'
JOIN data_rooms r ON r.id = s.room_id AND r.kind = 'organization' AND r.status = 'active'
JOIN auth_accounts a ON a.id = m.subject_id AND a.status = 'active'
WHERE s.resource_kind = %s AND s.resource_id = %s
""",
(actor, kind, resource_id),
).fetchall()
result = Rights()
for row in rows:
rights = ROOM_RIGHTS.get(row["role"], Rights())
if row["access"] == "read":
rights = Rights(read=rights.read)
elif row["access"] != "edit":
rights = Rights()
if rights.read and row["download_roles"].get(row["role"], False):
rights = Rights(rights.read, rights.edit, rights.share, rights.delete, True)
result = result.union(rights)
return result
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"]).union(room_default(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:
if matter["owner_subject_id"] == actor:
base = Rights.full()
else:
base = _direct_grant(conn, actor, "matter", matter["id"]).union(room_default(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 room_source_access(conn, actor: UUID, kind: str, resource_id: UUID, owner_id: UUID) -> bool:
"""Whether a room the entry is shared with lets this member read the owner's linked originals.
The owner has switched it on for this person in that room. Only an active room, an active
membership with a reading role and an active account count.
"""
readers = [role for role, rights in ROOM_RIGHTS.items() if rights.read]
row = conn.execute(
"""
SELECT 1
FROM room_shares s
JOIN room_memberships m ON m.room_id = s.room_id AND m.subject_id = %s AND m.status = 'active'
JOIN data_rooms r ON r.id = s.room_id AND r.kind = 'organization' AND r.status = 'active'
JOIN auth_accounts a ON a.id = m.subject_id AND a.status = 'active'
JOIN room_source_access x ON x.room_id = s.room_id AND x.subject_id = m.subject_id AND x.owner_id = %s
WHERE s.resource_kind = %s AND s.resource_id = %s AND m.role = ANY(%s)
LIMIT 1
""",
(actor, owner_id, kind, resource_id, readers),
).fetchone()
return row is not None
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 owner allowed it, either on the personal grant or for this person in a room
the entry is shared with. Read rights and exceptions are checked first.
"""
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)
elif context.kind == "matter":
resource = get_matter(conn, context.id)
if resource is None:
return None
else:
return None
owner = resource["owner_subject_id"]
if owner == actor:
return None
grant = _source_grant(conn, actor, context.kind, resource["id"])
if grant is not None and grant["can_read"] and grant["use_owner_sources"]:
return owner
if room_source_access(conn, actor, context.kind, resource["id"], owner):
return owner
return None
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 (EXISTS (
SELECT 1 FROM room_shares sh
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
WHERE sh.resource_kind = 'case' AND sh.resource_id = c.id
))
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
)
OR (EXISTS (
SELECT 1 FROM room_shares sh
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
WHERE sh.resource_kind = 'case' AND sh.resource_id = p.id
))
)
)
)
)
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 room_shares sh
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
WHERE sh.resource_kind = 'matter' AND sh.resource_id = m.id
))
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
)
OR (EXISTS (
SELECT 1 FROM room_shares sh
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
WHERE sh.resource_kind = 'case' AND sh.resource_id = c.id
))
)
)
)
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