Erlaube berechtigten Konten, verknüpfte Originale über die Zugänge des Owners zu lesen.
Deploy Development / deploy (push) Successful in 26s
Test Suite / pytest-backend (push) Successful in 1m51s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 9s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-18 21:47:30 +02:00
1 parent 562c0848b1
commit 75a3949f7c
14 files changed
+815 -93

No files matched your search

+62 -2
View File
@@ -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.
+22 -2
View File
@@ -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
+1
View File
@@ -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):
+48 -67
View File
@@ -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",
},
)
+25 -7
View File
@@ -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
+40 -8
View File
@@ -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",
+138
View File
@@ -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,