From 75a3949f7c9baa95ddbbb024eb05af526b128795 Mon Sep 17 00:00:00 2001 From: Lars Date: Sun, 18 Oct 2026 21:47:30 +0200 Subject: [PATCH] =?UTF-8?q?Erlaube=20berechtigten=20Konten,=20verkn=C3=BCp?= =?UTF-8?q?fte=20Originale=20=C3=BCber=20die=20Zug=C3=A4nge=20des=20Owners?= =?UTF-8?q?=20zu=20lesen.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- AGENTS.md | 2 +- backend/app/access/policy.py | 64 ++- backend/app/api/routes.py | 24 +- backend/app/api/schemas.py | 1 + backend/app/api/sources.py | 115 ++--- backend/app/ops.py | 32 +- backend/app/present.py | 48 +- backend/app/sources.py | 138 ++++++ .../20261018T213000Z_owner_sources.sql | 8 + backend/tests/test_owner_sources.py | 451 ++++++++++++++++++ docs/architecture/TSUMUGU_TECHNICAL_SPEC.md | 2 +- frontend/src/pages/Cases.jsx | 2 +- frontend/src/pages/Matters.jsx | 2 +- frontend/src/pages/widgets.jsx | 19 +- 14 files changed, 815 insertions(+), 93 deletions(-) create mode 100644 backend/migrations/20261018T213000Z_owner_sources.sql create mode 100644 backend/tests/test_owner_sources.py diff --git a/AGENTS.md b/AGENTS.md index 5eeaf40..cca5165 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,4 +4,4 @@ Fachlich führend ist `docs/product/TSUMUGU_PRODUCT_SPEC.md`. Der technische Ent Deployment und Ports: `docs/DEPLOYMENT.md`. Gearbeitet wird auf `develop`. Ein Push dorthin startet das Development-Deploy auf dem Raspberry Pi. Production entsteht nur durch einen Merge nach `main`. -Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und externer Anwaltszugang gehören nicht in diese Lieferung. +Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und ein Anwaltszugang ohne eigenes Konto gehören nicht in diese Lieferung. Eine berechtigte Person mit Konto kann freigegebene verknüpfte Dokumente und E-Mails über die Zugänge des Owners lesen, ohne eigene Paperless- oder IMAP-Verbindungen. diff --git a/backend/app/access/policy.py b/backend/app/access/policy.py index 096b38e..b2deb9c 100644 --- a/backend/app/access/policy.py +++ b/backend/app/access/policy.py @@ -11,6 +11,8 @@ 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." @@ -87,14 +89,17 @@ def audit( 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 + context_kind, context_id, occurred_on, result, detail ) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """, ( actor_id, @@ -105,6 +110,8 @@ def audit( context.kind if context else None, context.id if context else None, occurred_on, + result, + Json(detail) if detail is not None else None, ), ) @@ -348,6 +355,59 @@ def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool: 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. diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index e4aacd3..9c8018d 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -643,7 +643,16 @@ def post_case_grant( if account is None: raise not_found() grant = grant_access( - conn, principal.account_id, "case", case_id, account["id"], body.can_read, body.can_edit, body.can_share, None + conn, + principal.account_id, + "case", + case_id, + account["id"], + body.can_read, + body.can_edit, + body.can_share, + None, + body.use_owner_sources, ) return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])}) @@ -908,7 +917,16 @@ def post_matter_grant( if account is None: raise not_found() grant = grant_access( - conn, principal.account_id, "matter", matter_id, account["id"], body.can_read, body.can_edit, body.can_share, None + conn, + principal.account_id, + "matter", + matter_id, + account["id"], + body.can_read, + body.can_edit, + body.can_share, + None, + body.use_owner_sources, ) return _created(f"/api/v1/grants/{grant['id']}", {"id": str(grant["id"])}) @@ -1785,6 +1803,8 @@ def _visible_events(conn, actor: UUID, rows: list[dict], page: Ctx) -> list[dict names: dict = {} items = [] for event in rows: + if event["result"] != "ok": + continue title = _event_title(conn, actor, event, page) if title is None: continue diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py index 628d65e..f6e6e89 100644 --- a/backend/app/api/schemas.py +++ b/backend/app/api/schemas.py @@ -167,6 +167,7 @@ class GrantIn(APIModel): can_read: bool = True can_edit: bool = False can_share: bool = False + use_owner_sources: bool = False class ExceptionIn(APIModel): diff --git a/backend/app/api/sources.py b/backend/app/api/sources.py index e74bc68..1a40e65 100644 --- a/backend/app/api/sources.py +++ b/backend/app/api/sources.py @@ -5,10 +5,10 @@ from __future__ import annotations from uuid import UUID from fastapi import APIRouter, Depends -from fastapi.responses import Response +from fastapi.responses import JSONResponse, Response from psycopg import Connection -from app.access.policy import Ctx, element_rights, get_element, parse_query_context +from app.access.policy import element_rights, get_element, parse_query_context from app.api.deps import Principal, get_conn, get_principal from app.api.routes import _created, _ctx_model from app.api.schemas import ConnectorIn, ExternalIn @@ -23,13 +23,19 @@ from app.sources import ( imap_messages, imap_preview, list_connectors, - load_imap_original, - paperless_content, paperless_documents, probe, + read_linked_mail, + read_linked_paperless, save_connector, ) +_PRIVATE = { + "Cache-Control": "private, no-store", + "Referrer-Policy": "no-referrer", + "X-Content-Type-Options": "nosniff", +} + router = APIRouter() @@ -63,27 +69,17 @@ def view_paperless( principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): - element = get_element(conn, element_id) - if element is None or element["kind"] != "external_ref": - raise not_found() - rights = element_rights(conn, principal.account_id, element, parse_query_context(context_kind, context_id)) - if not rights.read: - raise not_found() - ref = conn.execute( - "SELECT source, external_id FROM external_references WHERE element_id = %s", - (element_id,), - ).fetchone() + element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id) if ref is None or ref["source"] != "paperless": raise unprocessable("Nur ein Paperless-Dokument lässt sich hier als Datei ansehen.") - data, media_type, filename = paperless_content(conn, principal.account_id, ref["external_id"]) - safe_name = (filename or f"paperless-{ref['external_id']}.pdf").replace('"', "") + data, media_type, filename = read_linked_paperless(conn, principal.account_id, element, context, ref) + safe_name = (filename or "dokument.pdf").replace('"', "") return Response( content=data, media_type=media_type, headers={ + **_PRIVATE, "Content-Disposition": f'inline; filename="{safe_name}"', - "X-Content-Type-Options": "nosniff", - "Cache-Control": "private, no-store", }, ) @@ -96,52 +92,48 @@ def view_mail( principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): - ref = _mail_ref(conn, principal, element_id, context_kind, context_id) - parsed, _raw = _complete_mail(conn, principal, ref) - return { - "title": parsed.subject, - "message_from": parsed.sender, - "message_to": parsed.recipient, - "message_cc": parsed.copy, - "text": parsed.text, - "text_truncated": False, - "complete": True, - "attachments": [ - { - "index": index, - "filename": item.filename, - "content_type": item.media_type, - "byte_size": len(item.data), - } - for index, item in enumerate(parsed.attachments) - ], - } + element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id) + parsed, _raw = _complete_mail(conn, principal, element, context, ref) + return JSONResponse( + content={ + "title": parsed.subject, + "message_from": parsed.sender, + "message_to": parsed.recipient, + "message_cc": parsed.copy, + "text": parsed.text, + "text_truncated": False, + "complete": True, + "attachments": [ + { + "index": index, + "filename": item.filename, + "content_type": item.media_type, + "byte_size": len(item.data), + } + for index, item in enumerate(parsed.attachments) + ], + }, + headers={"Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer"}, + ) -def _mail_ref(conn, principal: Principal, element_id: UUID, context_kind: str | None, context_id: str | None): +def _opened_ref(conn, principal: Principal, element_id: UUID, context_kind: str | None, context_id: str | None): element = get_element(conn, element_id) if element is None or element["kind"] != "external_ref": raise not_found() - rights = element_rights(conn, principal.account_id, element, parse_query_context(context_kind, context_id)) + context = parse_query_context(context_kind, context_id) + rights = element_rights(conn, principal.account_id, element, context) if not rights.read: raise not_found() ref = conn.execute( "SELECT source, external_id, detail FROM external_references WHERE element_id = %s", (element_id,), ).fetchone() - return ref + return element, context, ref -def _complete_mail(conn, principal: Principal, ref): - detail = (ref or {}).get("detail") or {} - if ref is None or ref["source"] != "imap": - raise unprocessable("Das ist keine E-Mail.") - connector_id = detail.get("connector_id") - mailbox = str(detail.get("mailbox") or "").strip() - uid = _mail_uid(detail.get("uid")) - if not connector_id or not mailbox or uid is None: - raise unprocessable("Für diese E-Mail fehlt die Zuordnung zu Fach und Nachricht.") - raw = load_imap_original(conn, principal.account_id, UUID(str(connector_id)), mailbox, uid, str(ref["external_id"])) +def _complete_mail(conn, principal: Principal, element, context, ref): + raw = read_linked_mail(conn, principal.account_id, element, context, ref) parsed = parse_mail(raw) if parsed.missing: names = ", ".join(parsed.missing[:5]) @@ -149,16 +141,6 @@ def _complete_mail(conn, principal: Principal, ref): return parsed, raw -def _mail_uid(value) -> int | None: - if isinstance(value, bool): - return None - if isinstance(value, int) and value >= 1: - return value - if isinstance(value, str) and value.isdigit() and int(value) >= 1: - return int(value) - return None - - @router.get("/api/v1/external-refs/{element_id}/mail/original") def download_mail( element_id: UUID, @@ -167,8 +149,8 @@ def download_mail( principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): - ref = _mail_ref(conn, principal, element_id, context_kind, context_id) - _parsed, raw = _complete_mail(conn, principal, ref) + element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id) + _parsed, raw = _complete_mail(conn, principal, element, context, ref) return _mail_bytes(raw, "message/rfc822", "nachricht.eml") @@ -181,8 +163,8 @@ def download_mail_attachment( principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): - ref = _mail_ref(conn, principal, element_id, context_kind, context_id) - parsed, _raw = _complete_mail(conn, principal, ref) + element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id) + parsed, _raw = _complete_mail(conn, principal, element, context, ref) if index < 0 or index >= len(parsed.attachments): raise not_found() item = parsed.attachments[index] @@ -197,9 +179,8 @@ def _mail_bytes(data: bytes, media_type: str, filename: str, inline: bool = Fals content=data, media_type=media_type, headers={ + **_PRIVATE, "Content-Disposition": disposition, - "X-Content-Type-Options": "nosniff", - "Cache-Control": "private, no-store", }, ) diff --git a/backend/app/ops.py b/backend/app/ops.py index 1f57328..628a4b9 100644 --- a/backend/app/ops.py +++ b/backend/app/ops.py @@ -701,7 +701,18 @@ def _actor_rights_for(conn, actor: UUID, kind: str, resource_id: UUID, context: return rights -def grant_access(conn, actor: UUID, kind: str, resource_id: UUID, grantee_id: UUID, can_read: bool, can_edit: bool, can_share: bool, context: Ctx | None) -> dict: +def grant_access( + conn, + actor: UUID, + kind: str, + resource_id: UUID, + grantee_id: UUID, + can_read: bool, + can_edit: bool, + can_share: bool, + context: Ctx | None, + use_owner_sources: bool = False, +) -> dict: if grantee_id == actor: raise unprocessable("Die eigene Berechtigung wird nicht als Freigabe gespeichert.") if not can_read: @@ -731,33 +742,40 @@ def grant_access(conn, actor: UUID, kind: str, resource_id: UUID, grantee_id: UU raise not_found() existing = conn.execute( """ - SELECT id FROM access_grants + SELECT id, 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 """, (grantee_id, kind, resource_id), ).fetchone() + if owner: + source_access = bool(use_owner_sources) + elif existing is None: + source_access = False + else: + source_access = bool(existing["use_owner_sources"]) if existing is None: row = conn.execute( """ INSERT INTO access_grants ( grantee_subject_id, resource_kind, resource_id, - can_read, can_edit, can_share, can_delete, is_exception, created_by + can_read, can_edit, can_share, can_delete, is_exception, created_by, + use_owner_sources ) - VALUES (%s, %s, %s, %s, %s, %s, false, false, %s) + VALUES (%s, %s, %s, %s, %s, %s, false, false, %s, %s) RETURNING * """, - (grantee_id, kind, resource_id, can_read, can_edit, can_share, actor), + (grantee_id, kind, resource_id, can_read, can_edit, can_share, actor, source_access), ).fetchone() else: row = conn.execute( """ UPDATE access_grants - SET can_read = %s, can_edit = %s, can_share = %s + SET can_read = %s, can_edit = %s, can_share = %s, use_owner_sources = %s WHERE id = %s RETURNING * """, - (can_read, can_edit, can_share, existing["id"]), + (can_read, can_edit, can_share, source_access, existing["id"]), ).fetchone() audit(conn, actor, resource["home_scope_id"], "grant_created", kind, resource_id, context) return row diff --git a/backend/app/present.py b/backend/app/present.py index 8805422..b356096 100644 --- a/backend/app/present.py +++ b/backend/app/present.py @@ -126,7 +126,32 @@ def _preview_meta(kind: str, content_type: str | None, source: str | None) -> di return {"available": False, "media": "none", "source": source} -def _element_body(conn, element: dict) -> dict: +_HIDDEN_SOURCE_FIELDS = frozenset({ + "connector_id", + "mailbox", + "uid", + "host", + "username", + "port", + "password", + "secret", + "base_url", + "server", + "security", + "open_url", +}) + + +def _connector_owner(conn, raw) -> UUID | None: + try: + connector_id = UUID(str(raw)) + except (TypeError, ValueError): + return None + row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone() + return row["owner_id"] if row else None + + +def _element_body(conn, actor: UUID, element: dict) -> dict: payload = { "id": str(element["id"]), "kind": element["kind"], @@ -169,11 +194,15 @@ def _element_body(conn, element: dict) -> dict: (element["id"],), ).fetchone() if ref is not None: - payload["external"] = { - "source": ref["source"], - "external_id": ref["external_id"], - "detail": ref["detail"] or {}, - } + detail = dict(ref["detail"] or {}) + connector_owner = _connector_owner(conn, detail.get("connector_id")) + revealed = actor == element["owner_subject_id"] or (connector_owner is not None and actor == connector_owner) + if not revealed: + detail = {key: value for key, value in detail.items() if key not in _HIDDEN_SOURCE_FIELDS} + external = {"source": ref["source"], "detail": detail} + if revealed: + external["external_id"] = ref["external_id"] + payload["external"] = external payload["preview"] = _preview_meta("external_ref", None, ref["source"]) return payload @@ -280,7 +309,7 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No rights = element_rights(conn, actor, element, context) if not rights.read: return None - body = _element_body(conn, element) + body = _element_body(conn, actor, element) container = Ctx(binding["context_kind"], binding["context_id"]) _attach_references(conn, actor, element, context, container, body) payload = { @@ -300,7 +329,8 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No def _grants(conn, kind: str, resource_id: UUID) -> list[dict]: rows = conn.execute( """ - SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, a.email, a.display_name + SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, g.use_owner_sources, + a.email, a.display_name FROM access_grants g JOIN auth_accounts a ON a.id = g.grantee_subject_id WHERE NOT g.is_exception AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL @@ -317,6 +347,7 @@ def _grants(conn, kind: str, resource_id: UUID) -> list[dict]: "can_read": row["can_read"], "can_edit": row["can_edit"], "can_share": row["can_share"], + "use_owner_sources": row["use_owner_sources"], } for row in rows ] @@ -958,6 +989,7 @@ LABELS = { "deadline_fulfilled": "Frist erfüllt", "grant_created": "Freigabe erteilt", "grant_revoked": "Freigabe entzogen", + "source_read_mediated": "Verknüpftes Original gelesen", "correspondence_document": "Dokumentdatum", "correspondence_sent": "Versand", "correspondence_received": "Zugang", diff --git a/backend/app/sources.py b/backend/app/sources.py index 4fd8369..3bd7d2a 100644 --- a/backend/app/sources.py +++ b/backend/app/sources.py @@ -18,6 +18,7 @@ from uuid import UUID from psycopg.types.json import Json +from app.access.policy import Ctx, audit, mediated_source_owner from app.core.errors import Problem, not_found, unprocessable from app.core.settings import get_settings from app.mailpack import MailIdentityError, choose_message, identities_match, header_message_id @@ -207,6 +208,10 @@ def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, st ).fetchone() if row is None: raise unprocessable("Paperless ist für dieses Konto nicht verbunden.") + return _paperless_bytes(row, document_id) + + +def _paperless_bytes(row, document_id: str) -> tuple[bytes, str, str]: base = row["settings"]["base_url"].rstrip("/") token = row["secret"] misses = 0 @@ -228,6 +233,139 @@ def paperless_content(conn, owner_id: UUID, document_id: str) -> tuple[bytes, st raise unprocessable("Paperless stellt diese Datei nicht zum Ansehen bereit.") +ORIGINAL_UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar." + + +def read_linked_paperless(conn, actor_id: UUID, element: dict, context: Ctx | None, ref) -> tuple[bytes, str, str]: + """The stored document. A grantee never uses a connector of their own account.""" + detail = (ref or {}).get("detail") or {} + external_id = str((ref or {}).get("external_id") or "") + stored = _uuid(detail.get("connector_id")) + stored_owner = _connector_owner(conn, stored) + if element["owner_subject_id"] == actor_id or stored_owner == actor_id: + return paperless_content(conn, actor_id, external_id) + owner_id = mediated_source_owner(conn, actor_id, element, context) + if owner_id is None or not external_id.isdigit() or len(external_id) > 12: + raise unprocessable(ORIGINAL_UNAVAILABLE) + row = _mediated_paperless(conn, owner_id, stored, element) + if row is None: + _audit_mediated(conn, actor_id, element, context, "paperless", stored, "unavailable") + raise unprocessable(ORIGINAL_UNAVAILABLE) + try: + data, media, name = _paperless_bytes(row, external_id) + except Problem: + _audit_mediated(conn, actor_id, element, context, "paperless", row["id"], "unavailable") + raise unprocessable(ORIGINAL_UNAVAILABLE) from None + _audit_mediated(conn, actor_id, element, context, "paperless", row["id"], "ok") + if external_id and external_id in (name or ""): + name = "dokument.pdf" + return data, media, name or "dokument.pdf" + + +def read_linked_mail(conn, actor_id: UUID, element: dict, context: Ctx | None, ref) -> bytes: + """The stored message. Mailbox, UID and connector come only from the saved reference.""" + detail = (ref or {}).get("detail") or {} + if ref is None or ref["source"] != "imap": + raise unprocessable("Das ist keine E-Mail.") + connector_id = _uuid(detail.get("connector_id")) + mailbox = str(detail.get("mailbox") or "").strip() + uid = _mail_uid(detail.get("uid")) + external_id = str(ref["external_id"]) + stored_owner = _connector_owner(conn, connector_id) + if element["owner_subject_id"] == actor_id or stored_owner == actor_id: + if connector_id is None or not mailbox or uid is None: + raise unprocessable("Für diese E-Mail fehlt die Zuordnung zu Fach und Nachricht.") + return load_imap_original(conn, actor_id, connector_id, mailbox, uid, external_id) + owner_id = mediated_source_owner(conn, actor_id, element, context) + if owner_id is None or connector_id is None or not mailbox or uid is None: + raise unprocessable(ORIGINAL_UNAVAILABLE) + row = _connector_for(conn, connector_id, owner_id, "imap") + if row is None: + _audit_mediated(conn, actor_id, element, context, "imap", connector_id, "unavailable") + raise unprocessable(ORIGINAL_UNAVAILABLE) + try: + raw = load_imap_original(conn, owner_id, connector_id, mailbox, uid, external_id) + except Problem: + _audit_mediated(conn, actor_id, element, context, "imap", connector_id, "unavailable") + raise unprocessable(ORIGINAL_UNAVAILABLE) from None + _audit_mediated(conn, actor_id, element, context, "imap", connector_id, "ok") + return raw + + +def _uuid(value) -> UUID | None: + if isinstance(value, UUID): + return value + try: + return UUID(str(value)) + except (TypeError, ValueError): + return None + + +def _mail_uid(value) -> int | None: + if isinstance(value, bool): + return None + if isinstance(value, int) and value >= 1: + return value + if isinstance(value, str) and value.isdigit() and int(value) >= 1: + return int(value) + return None + + +def _connector_owner(conn, connector_id: UUID | None) -> UUID | None: + if connector_id is None: + return None + row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone() + return row["owner_id"] if row else None + + +def _connector_for(conn, connector_id: UUID, owner_id: UUID, kind: str): + return conn.execute( + """ + SELECT id, owner_id, kind, settings, secret + FROM connectors + WHERE id = %s AND owner_id = %s AND kind = %s + """, + (connector_id, owner_id, kind), + ).fetchone() + + +def _mediated_paperless(conn, owner_id: UUID, stored: UUID | None, element: dict): + if stored is not None: + return _connector_for(conn, stored, owner_id, "paperless") + if element["owner_subject_id"] != owner_id: + return None + return conn.execute( + """ + SELECT id, owner_id, kind, settings, secret + FROM connectors + WHERE owner_id = %s AND kind = 'paperless' + ORDER BY created_at DESC + LIMIT 1 + """, + (owner_id,), + ).fetchone() + + +def _audit_mediated(conn, actor_id: UUID, element: dict, context: Ctx | None, source: str, connector_id, outcome: str) -> None: + audit( + conn, + actor_id, + element["home_scope_id"], + "source_read_mediated", + "element", + element["id"], + context, + result="ok" if outcome == "ok" else "unavailable", + detail={ + "source": source, + "connector_id": str(connector_id) if connector_id else None, + "outcome": outcome, + }, + ) + if outcome != "ok": + conn.commit() + + def _paperless_file( base: str, token: str, diff --git a/backend/migrations/20261018T213000Z_owner_sources.sql b/backend/migrations/20261018T213000Z_owner_sources.sql new file mode 100644 index 0000000..f7b9ffa --- /dev/null +++ b/backend/migrations/20261018T213000Z_owner_sources.sql @@ -0,0 +1,8 @@ +-- Owner kann an einer Freigabe erlauben, verknüpfte Originale über die eigenen Zugänge zu lesen. +-- Bestehende Freigaben bleiben ohne diesen Abruf. + +ALTER TABLE access_grants + ADD COLUMN use_owner_sources boolean NOT NULL DEFAULT false; + +ALTER TABLE domain_events + ADD COLUMN detail jsonb; diff --git a/backend/tests/test_owner_sources.py b/backend/tests/test_owner_sources.py new file mode 100644 index 0000000..1f37837 --- /dev/null +++ b/backend/tests/test_owner_sources.py @@ -0,0 +1,451 @@ +"""Granted readers see linked originals only through the owner's stored connector.""" + +from __future__ import annotations + +import json + +import app.sources as sources +from tests.support import ORIGIN, Actor, register + +OWNER_TOKEN = "owner-paperless-token" +GRANTEE_TOKEN = "grantee-paperless-token" +OWNER_MAIL = "owner-postfach-geheim" +GRANTEE_MAIL = "grantee-postfach-geheim" +UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar." + + +class RecordingIMAP: + logins: list[str] = [] + fetches: list[int] = [] + + def __init__(self, *args, **kwargs): + pass + + def login(self, username, secret): + RecordingIMAP.logins.append(secret) + return "OK", [b"logged"] + + def list(self): + return "OK", [b'(\\HasNoChildren) "/" "INBOX"'] + + def select(self, mailbox, readonly=False): + return "OK", [b"5"] + + def uid(self, command, *args): + if command == "SEARCH": + return "OK", [b""] + uid = int(args[0]) + spec = " ".join(str(part) for part in args[1:]) + if "BODY.PEEK[]" in spec: + RecordingIMAP.fetches.append(uid) + raw = ( + f"From: Ada Beispiel \r\n" + f"To: Kanzlei \r\n" + f"Subject: Nachricht {uid}\r\n" + f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n" + f"Message-ID: <{uid}@example.test>\r\n" + f"MIME-Version: 1.0\r\n" + f'Content-Type: multipart/mixed; boundary="grenze"\r\n' + f"\r\n" + f"--grenze\r\n" + f"Content-Type: text/plain; charset=utf-8\r\n" + f"\r\n" + f"Bitte die Einwendung pruefen.\r\n" + f"--grenze\r\n" + f"Content-Type: application/pdf\r\n" + f'Content-Disposition: attachment; filename="einwendung.pdf"\r\n' + f"\r\n" + f"%PDF\r\n" + f"--grenze--\r\n" + ).encode() + return "OK", [(b"rfc822", raw)] + return "OK", [(b"body", b"From: Ada\r\n"), b")"] + + def logout(self): + return "BYE", [b""] + + +def _reset_imap(): + RecordingIMAP.logins = [] + RecordingIMAP.fetches = [] + + +def _paperless(actor: Actor, token: str, name: str) -> str: + return actor.request( + "POST", + "/api/v1/connectors", + json={"kind": "paperless", "name": name, "base_url": "https://paper.example.test", "token": token}, + status=201, + )["id"] + + +def _mailbox(actor: Actor, password: str, name: str) -> str: + return actor.request( + "POST", + "/api/v1/connectors", + json={ + "kind": "imap", + "name": name, + "host": "imap.example.test", + "port": 993, + "username": f"{name}@example.test", + "password": password, + "security": "ssl", + }, + status=201, + )["id"] + + +def _raw(actor: Actor, path: str): + return actor.client.get( + path, + headers={ + "Origin": ORIGIN, + "X-CSRF-Token": actor.csrf, + "X-Scope-Kind": actor.scope["kind"], + "X-Scope-Id": actor.scope["id"], + }, + ) + + +def _grant(actor: Actor, kind: str, resource_id: str, email: str, **flags): + body = {"email": email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": False} + body.update(flags) + return actor.request("POST", f"/api/v1/{kind}/{resource_id}/grants", json=body, status=201) + + +def _events(db): + return db.execute( + """ + SELECT action, result, detail + FROM domain_events + WHERE action = 'source_read_mediated' + ORDER BY occurred_at, id + """ + ).fetchall() + + +def test_owner_alone_sets_source_access_and_a_delegate_cannot_change_it(client, db): + ada = Actor(client, "ada-flag@example.test", "Ada Flag") + ben = Actor(client, "ben-flag@example.test", "Ben Flag") + cleo = Actor(client, "cleo-flag@example.test", "Cleo Flag") + register(db, ada.email, ada.name) + register(db, ben.email, ben.name) + register(db, cleo.email, cleo.name) + ada.login() + case = ada.request("POST", "/api/v1/cases", json={"title": "Streit"}, status=201) + _grant(ada, "cases", case["id"], ben.email, can_share=True, use_owner_sources=True) + ada_view = ada.request("GET", f"/api/v1/cases/{case['id']}") + ben_grant = next(item for item in ada_view["grants"] if item["email"] == ben.email) + assert ben_grant["use_owner_sources"] is True + + ben.login() + _grant(ben, "cases", case["id"], cleo.email, use_owner_sources=True) + ada.login() + after_delegate = ada.request("GET", f"/api/v1/cases/{case['id']}") + cleo_grant = next(item for item in after_delegate["grants"] if item["email"] == cleo.email) + assert cleo_grant["use_owner_sources"] is False + + _grant(ada, "cases", case["id"], cleo.email, use_owner_sources=True) + ben.login() + _grant(ben, "cases", case["id"], cleo.email, can_share=True, use_owner_sources=False) + ada.login() + kept = ada.request("GET", f"/api/v1/cases/{case['id']}") + cleo_grant = next(item for item in kept["grants"] if item["email"] == cleo.email) + assert cleo_grant["can_share"] is True + assert cleo_grant["use_owner_sources"] is True + + _grant(ada, "cases", case["id"], cleo.email, use_owner_sources=False) + cleared = ada.request("GET", f"/api/v1/cases/{case['id']}") + cleo_grant = next(item for item in cleared["grants"] if item["email"] == cleo.email) + assert cleo_grant["use_owner_sources"] is False + + +def test_grantee_reads_linked_originals_only_through_the_owner(client, db, monkeypatch): + calls = [] + + def fake_file(base, token, path, max_bytes=40 * 1024 * 1024): + calls.append({"token": token, "path": path}) + if path.endswith("/preview/"): + return (b"%PDF-1.4\nverknuepft\n", "application/pdf", "vertrag.pdf") + return None + + def fake_get(base, token, path, params): + calls.append({"token": token, "path": path, "query": params.get("query")}) + if token == OWNER_TOKEN: + return {"count": 1, "results": [{"id": 15, "title": "Geheimes Archivdokument", "created": "2026-01-01"}]} + return {"count": 0, "results": []} + + monkeypatch.setattr(sources, "_paperless_file", fake_file) + monkeypatch.setattr(sources, "_paperless_get", fake_get) + monkeypatch.setattr(sources, "_paperless_metadata", lambda *args, **kwargs: None) + monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RecordingIMAP) + _reset_imap() + + ada = Actor(client, "ada-quelle@example.test", "Ada Quelle") + ben = Actor(client, "ben-quelle@example.test", "Ben Quelle") + register(db, ada.email, ada.name) + register(db, ben.email, ben.name) + ada.login() + paper = _paperless(ada, OWNER_TOKEN, "Ada Archiv") + mailbox = _mailbox(ada, OWNER_MAIL, "Ada Post") + case = ada.request("POST", "/api/v1/cases", json={"title": "Akte"}, status=201) + matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201) + other = ada.request("POST", "/api/v1/matters", json={"title": "Fremder Vorgang"}, status=201) + document = ada.request( + "POST", + "/api/v1/external-refs", + json={ + "title": "Vertrag", + "source": "paperless", + "external_id": "15", + "context": {"kind": "case", "id": case["id"]}, + "detail": {"connector_id": paper, "correspondent": "Hausverwaltung"}, + }, + status=201, + ) + letter = ada.request( + "POST", + "/api/v1/external-refs", + json={ + "title": "Einwendung", + "source": "imap", + "external_id": "<2@example.test>", + "context": {"kind": "matter", "id": matter["id"]}, + "detail": { + "connector_id": mailbox, + "mailbox": "INBOX", + "uid": 2, + "direction": "in", + "message_from": "Hausverwaltung", + }, + }, + status=201, + ) + owner_file = _raw(ada, f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}") + assert owner_file.status_code == 200 + assert owner_file.content.startswith(b"%PDF") + assert calls[-1]["token"] == OWNER_TOKEN + assert "/api/documents/15/" in calls[-1]["path"] + owner_mail = ada.request( + "GET", + f"/api/v1/external-refs/{letter['id']}/mail", + params={"context_kind": "matter", "context_id": matter["id"]}, + ) + assert "Einwendung" in owner_mail["text"] + assert OWNER_MAIL in RecordingIMAP.logins + calls.clear() + _reset_imap() + + ben.login() + _paperless(ben, GRANTEE_TOKEN, "Ben Archiv") + _mailbox(ben, GRANTEE_MAIL, "Ben Post") + ada.login() + _grant(ada, "cases", case["id"], ben.email) + _grant(ada, "matters", matter["id"], ben.email) + _grant(ada, "matters", other["id"], ben.email, use_owner_sources=True) + + ben.login() + shown = ben.request("GET", f"/api/v1/matters/{matter['id']}") + visible = next(item for item in shown["bindings"] if item["element"]["title"] == "Einwendung") + detail = visible["element"]["external"]["detail"] + assert detail["direction"] == "in" + assert detail["message_from"] == "Hausverwaltung" + assert "connector_id" not in detail + assert "mailbox" not in detail + assert "uid" not in detail + assert "external_id" not in visible["element"]["external"] + dumped = json.dumps(shown) + assert OWNER_MAIL not in dumped + assert OWNER_TOKEN not in dumped + assert "imap.example.test" not in dumped + assert mailbox not in dumped + + hidden = ben.request( + "GET", + f"/api/v1/external-refs/{document['id']}/content", + params={"context_kind": "case", "context_id": case["id"], "document": "999"}, + status=422, + ) + assert hidden["detail"] == UNAVAILABLE + assert calls == [] + missed = ben.request( + "GET", + f"/api/v1/external-refs/{letter['id']}/mail", + params={"context_kind": "matter", "context_id": matter["id"], "uid": "9", "mailbox": "Geheim"}, + status=422, + ) + assert missed["detail"] == UNAVAILABLE + assert RecordingIMAP.logins == [] + assert RecordingIMAP.fetches == [] + + ada.login() + _grant(ada, "cases", case["id"], ben.email, use_owner_sources=True) + _grant(ada, "matters", matter["id"], ben.email, use_owner_sources=True) + ben.login() + opened = _raw( + ben, + f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}&document=999", + ) + assert opened.status_code == 200 + assert opened.content.startswith(b"%PDF") + assert opened.headers["x-content-type-options"] == "nosniff" + assert opened.headers["cache-control"] == "private, no-store" + assert opened.headers["referrer-policy"] == "no-referrer" + assert calls == [{"token": OWNER_TOKEN, "path": "/api/documents/15/preview/"}] + assert GRANTEE_TOKEN not in json.dumps(calls) + search = ben.request("GET", "/api/v1/sources/paperless/documents", params={"q": "Geheim"}) + assert "Geheimes Archivdokument" not in json.dumps(search) + assert all(item["token"] != OWNER_TOKEN for item in calls if "query" in item) + + mail = ben.request( + "GET", + f"/api/v1/external-refs/{letter['id']}/mail", + params={"context_kind": "matter", "context_id": matter["id"], "uid": "9", "connector_id": paper}, + ) + assert mail["text"] == "Bitte die Einwendung pruefen." + assert mail["attachments"][0]["filename"] == "einwendung.pdf" + assert RecordingIMAP.logins == [OWNER_MAIL] + assert RecordingIMAP.fetches == [2] + original = _raw( + ben, + f"/api/v1/external-refs/{letter['id']}/mail/original?context_kind=matter&context_id={matter['id']}", + ) + assert original.status_code == 200 + assert b"Message-ID: <2@example.test>" in original.content + attachment = _raw( + ben, + f"/api/v1/external-refs/{letter['id']}/mail/attachments/0?context_kind=matter&context_id={matter['id']}", + ) + assert attachment.status_code == 200 + assert attachment.content.startswith(b"%PDF") + assert attachment.headers["content-disposition"].startswith("inline;") + assert GRANTEE_MAIL not in RecordingIMAP.logins + page = ben.request("GET", f"/api/v1/matters/{matter['id']}/chronology") + chronology = json.dumps(page) + assert "source_read_mediated" in [item["action"] for item in page["items"]] + assert "Verknüpftes Original gelesen" in [item["label"] for item in page["items"]] + assert mailbox not in chronology + assert OWNER_MAIL not in chronology + + quiet = len(RecordingIMAP.logins) + ben.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": mailbox}, status=404) + ben.request( + "GET", + f"/api/v1/external-refs/{letter['id']}/mail", + params={"context_kind": "matter", "context_id": other["id"]}, + status=404, + ) + ada.login() + ada.request( + "PUT", + "/api/v1/exceptions", + json={ + "resource_kind": "element", + "resource_id": letter["id"], + "context": {"kind": "matter", "id": matter["id"]}, + "remove_read": True, + }, + ) + grant_id = next(item["id"] for item in ada.request("GET", f"/api/v1/cases/{case['id']}")["grants"]) + ben.login() + ben.request( + "GET", + f"/api/v1/external-refs/{letter['id']}/mail", + params={"context_kind": "matter", "context_id": matter["id"]}, + status=404, + ) + assert len(RecordingIMAP.logins) == quiet + ada.login() + ada.request("DELETE", f"/api/v1/grants/{grant_id}", status=204) + ben.login() + ben.request( + "GET", + f"/api/v1/external-refs/{document['id']}/content", + params={"context_kind": "case", "context_id": case["id"]}, + status=404, + ) + assert len(RecordingIMAP.logins) == quiet + assert [item["token"] for item in calls if "query" not in item] == [OWNER_TOKEN] + + rows = _events(db) + blob = json.dumps(rows, default=str) + assert OWNER_TOKEN not in blob + assert OWNER_MAIL not in blob + assert "Bitte die Einwendung" not in blob + assert "imap.example.test" not in blob + assert any(row["result"] == "ok" and row["detail"]["source"] == "paperless" for row in rows) + assert any(row["result"] == "ok" and row["detail"]["connector_id"] == mailbox for row in rows) + + +def test_deleted_or_foreign_connector_is_not_used(client, db, monkeypatch): + calls = [] + monkeypatch.setattr( + sources, + "_paperless_file", + lambda *args, **kwargs: calls.append("paperless") or (b"%PDF-1.4\n", "application/pdf", "x.pdf"), + ) + monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RecordingIMAP) + _reset_imap() + + ada = Actor(client, "ada-weg@example.test", "Ada Weg") + ben = Actor(client, "ben-weg@example.test", "Ben Weg") + cleo = Actor(client, "cleo-weg@example.test", "Cleo Weg") + register(db, ada.email, ada.name) + register(db, ben.email, ben.name) + register(db, cleo.email, cleo.name) + ada.login() + paper = _paperless(ada, OWNER_TOKEN, "Ada Archiv") + ben.login() + foreign = _mailbox(ben, GRANTEE_MAIL, "Ben Post") + ada.login() + matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201) + document = ada.request( + "POST", + "/api/v1/external-refs", + json={ + "title": "Scan", + "source": "paperless", + "external_id": "15", + "context": {"kind": "matter", "id": matter["id"]}, + "detail": {"connector_id": paper}, + }, + status=201, + ) + foreign_mail = ada.request( + "POST", + "/api/v1/external-refs", + json={ + "title": "Fremde Quelle", + "source": "imap", + "external_id": "<2@example.test>", + "context": {"kind": "matter", "id": matter["id"]}, + "detail": {"connector_id": foreign, "mailbox": "INBOX", "uid": 2}, + }, + status=201, + ) + _grant(ada, "matters", matter["id"], cleo.email, use_owner_sources=True) + ada.request("DELETE", f"/api/v1/connectors/{paper}", status=204) + cleo.login() + blocked = cleo.request( + "GET", + f"/api/v1/external-refs/{document['id']}/content", + params={"context_kind": "matter", "context_id": matter["id"]}, + status=422, + ) + assert blocked["detail"] == UNAVAILABLE + assert "paper.example.test" not in blocked["detail"] + assert calls == [] + refused = cleo.request( + "GET", + f"/api/v1/external-refs/{foreign_mail['id']}/mail", + params={"context_kind": "matter", "context_id": matter["id"]}, + status=422, + ) + assert refused["detail"] == UNAVAILABLE + assert RecordingIMAP.logins == [] + rows = _events(db) + assert rows + assert all(row["result"] == "unavailable" for row in rows) + assert OWNER_TOKEN not in json.dumps(rows, default=str) + assert GRANTEE_MAIL not in json.dumps(rows, default=str) diff --git a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md index 9a4f528..65b2e36 100644 --- a/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md +++ b/docs/architecture/TSUMUGU_TECHNICAL_SPEC.md @@ -378,7 +378,7 @@ Dieselbe Grenze gilt für Finanzobjekte. Eine unzugeordnete Zahlung sehen Owner ### 5.6 Anwalt und RLS -Der spätere Anwaltszugang kann ein Leserecht auf eine Zusammenstellung an ein weiteres Subjekt vergeben. Die Zugangsform bleibt offen und ist keine MVP-Funktion. Ein Exportpaket wäre ein eigenes Asset mit dem Stand zum Erzeugungszeitpunkt; auch das liegt außerhalb des MVP. +Ein registriertes Konto mit Leserecht an Akte oder Vorgang kann verknüpfte Paperless-Dokumente und E-Mails über die serverseitigen Zugänge des Owners lesen, wenn der Owner das an der Freigabe ausdrücklich einschaltet (`use_owner_sources`). Der Empfänger richtet dafür keine eigenen Quellen ein, erhält keine Secrets und kann das Archiv oder Postfach nicht durchsuchen. Ein Gastzugang ohne Konto bleibt offen und ist nicht Teil dieses Schnitts. Das Übergabepaket bleibt ein eigener Stand und nutzt weiter die Zugänge der exportierenden Person. Vertrag ADR-06 und offener Punkt O1: vertrauliche Mehrraumdaten brauchen eine ausdrückliche RLS-Prüfung. Vorschlag: ab P1 App-Policy, zusammengesetzte Fremdschlüssel und eine Runtime-Rolle ohne DDL, Owner und `BYPASSRLS`. Vor dem ersten Produktivbetrieb mit echten Daten zusätzlich RLS als zweite Linie, mit transaktionslokalem Subjekt und einem Grant-Prädikat, das datenraumübergreifende Leserechte nur über `access_grants` zulässt. Pool-Rückgabe darf diesen Kontext nicht behalten. RLS ersetzt die App-Policy nicht. Ein stiller, auf die Scope-ID beschränkter RLS-Filter wäre ein Fehler, weil er bestätigte Freigaben aussperren oder, bei zu weiter Policy, fremde Akten öffnen würde. diff --git a/frontend/src/pages/Cases.jsx b/frontend/src/pages/Cases.jsx index ec4f1f1..5c05a1d 100644 --- a/frontend/src/pages/Cases.jsx +++ b/frontend/src/pages/Cases.jsx @@ -670,7 +670,7 @@ export function CaseDetail() { /> setModal("")}> - + ); diff --git a/frontend/src/pages/Matters.jsx b/frontend/src/pages/Matters.jsx index 7748789..252e9d9 100644 --- a/frontend/src/pages/Matters.jsx +++ b/frontend/src/pages/Matters.jsx @@ -618,7 +618,7 @@ export function MatterDetail() { /> setModal("")}> - + setModal("")}> + {allowSources ? ( + + ) : null} @@ -362,7 +371,11 @@ export function ShareBox({ path, grants, onChange }) { {grants.map((grant) => (
  • {grant.display_name} · {grant.email} - {grant.can_edit ? "Bearbeiten" : "Lesen"}{grant.can_share ? ", Weitergeben" : ""} + + {grant.can_edit ? "Bearbeiten" : "Lesen"} + {grant.can_share ? ", Weitergeben" : ""} + {grant.use_owner_sources ? ", Originale über meine Zugänge" : ""} +
  • ))}