From 075525ee179cc070c708092efb048d2cfc1918f6 Mon Sep 17 00:00:00 2001 From: Stommer Date: Thu, 22 Oct 2026 14:22:35 +0200 Subject: [PATCH] Steuere das Herunterladen von Originalen je Rolle, benenne Dateien richtig und zeige HTML-Mails gesichert im Sandbox-Rahmen. Co-Authored-By: Claude Sonnet 5.5 --- backend/app/access/policy.py | 37 +++++++-- backend/app/api/downloads.py | 82 +++++++++++++++++++ backend/app/api/export.py | 10 ++- backend/app/api/rooms.py | 12 ++- backend/app/api/routes.py | 5 +- backend/app/api/schemas.py | 9 ++ backend/app/api/sources.py | 21 +++-- backend/app/core/errors.py | 3 + backend/app/mailpack.py | 49 ++++++++++- backend/app/main.py | 2 + backend/app/media/storage.py | 6 +- backend/app/present.py | 2 + .../20261023T090000Z_download_policy.sql | 11 +++ backend/tests/test_library.py | 48 +++++++++++ backend/tests/test_mail_html.py | 38 +++++++++ backend/tests/test_room_access.py | 6 +- docs/architecture/BENUTZERVERWALTUNG.md | 12 +++ frontend/src/admin/Account.jsx | 13 +++ frontend/src/admin/DownloadPolicy.jsx | 62 ++++++++++++++ frontend/src/api.js | 58 +++++++------ frontend/src/library/library.css | 3 + frontend/src/mail-view.jsx | 35 +++++++- frontend/src/pages/ReadingPane.jsx | 22 +++-- frontend/src/pages/Rooms.jsx | 3 + frontend/src/pages/widgets.jsx | 8 +- frontend/src/sources/builtin-views.jsx | 8 +- 26 files changed, 494 insertions(+), 71 deletions(-) create mode 100644 backend/app/api/downloads.py create mode 100644 backend/migrations/20261023T090000Z_download_policy.sql create mode 100644 backend/tests/test_mail_html.py create mode 100644 frontend/src/admin/DownloadPolicy.jsx diff --git a/backend/app/access/policy.py b/backend/app/access/policy.py index 0720120..1ce5c36 100644 --- a/backend/app/access/policy.py +++ b/backend/app/access/policy.py @@ -24,16 +24,18 @@ class Rights: 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) + return cls(True, True, True, True, True) @classmethod - def from_row(cls, row: dict | None) -> Rights: + 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"])) + 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( @@ -41,21 +43,24 @@ class Rights: 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} + 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. @@ -206,7 +211,25 @@ def _direct_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights: """, (actor, kind, resource_id), ).fetchone() - return Rights.from_row(row) + 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: @@ -249,7 +272,7 @@ def room_default(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights: """ rows = conn.execute( """ - SELECT m.role, s.access + 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' @@ -265,6 +288,8 @@ def room_default(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights: 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 diff --git a/backend/app/api/downloads.py b/backend/app/api/downloads.py new file mode 100644 index 0000000..ff85f3a --- /dev/null +++ b/backend/app/api/downloads.py @@ -0,0 +1,82 @@ +"""Download policy: which room role may save the original of a document or mail. + +Reading inside the app stays possible. The policy is a rule of use, not a copy protection: +what the screen shows has to reach the browser. +""" + +from __future__ import annotations + +from uuid import UUID + +from fastapi import APIRouter, Depends +from fastapi.responses import JSONResponse +from psycopg import Connection +from psycopg.types.json import Json + +from app.access.policy import audit +from app.access.roles import require_main_user, room_role +from app.api.deps import Principal, get_conn, get_principal +from app.api.schemas import DownloadPolicyIn +from app.core.errors import forbidden, not_found + +router = APIRouter() + +_NO_STORE = {"Cache-Control": "no-store"} +ROOM_KEYS = ("manager", "member", "reader") + + +def _policy(raw: dict, keys: tuple[str, ...]) -> dict[str, bool]: + return {key: bool(raw.get(key, True)) for key in keys} + + +def _room_of_member(conn, account_id: UUID, room_id: UUID) -> dict: + # A stranger and an unknown room answer alike. + room = conn.execute("SELECT * FROM data_rooms WHERE id = %s AND kind = 'organization'", (room_id,)).fetchone() + if room is None or room_role(conn, account_id, room_id) is None: + raise not_found() + return room + + +@router.get("/api/v1/rooms/{room_id}/download-policy") +def get_room_policy(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + room = _room_of_member(conn, principal.account_id, room_id) + return JSONResponse( + {"roles": _policy(room["download_roles"], ROOM_KEYS), "can_change": room["owner_id"] == principal.account_id}, + headers=_NO_STORE, + ) + + +@router.put("/api/v1/rooms/{room_id}/download-policy") +def put_room_policy( + room_id: UUID, + body: DownloadPolicyIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + room = _room_of_member(conn, principal.account_id, room_id) + if room["owner_id"] != principal.account_id: + raise forbidden("Das darf nur der Eigentümer des Datenraums.") + roles = {"manager": body.manager, "member": body.member, "reader": body.reader} + conn.execute("UPDATE data_rooms SET download_roles = %s WHERE id = %s", (Json(roles), room_id)) + audit(conn, principal.account_id, room_id, "room_download_policy_changed", "room", room_id, detail=roles) + return JSONResponse({"roles": roles, "can_change": True}, headers=_NO_STORE) + + +@router.get("/api/v1/auth/download-defaults") +def get_defaults(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)): + require_main_user(conn, principal.account_id) + row = conn.execute("SELECT download_defaults FROM auth_accounts WHERE id = %s", (principal.account_id,)).fetchone() + return JSONResponse({"roles": _policy(row["download_defaults"], (*ROOM_KEYS, "direct"))}, headers=_NO_STORE) + + +@router.put("/api/v1/auth/download-defaults") +def put_defaults( + body: DownloadPolicyIn, + principal: Principal = Depends(get_principal), + conn: Connection = Depends(get_conn), +): + require_main_user(conn, principal.account_id) + roles = {"manager": body.manager, "member": body.member, "reader": body.reader, "direct": True if body.direct is None else body.direct} + conn.execute("UPDATE auth_accounts SET download_defaults = %s WHERE id = %s", (Json(roles), principal.account_id)) + audit(conn, principal.account_id, None, "download_defaults_changed", "account", principal.account_id, detail=roles) + return JSONResponse({"roles": roles}, headers=_NO_STORE) diff --git a/backend/app/api/export.py b/backend/app/api/export.py index 591a17f..b48db32 100644 --- a/backend/app/api/export.py +++ b/backend/app/api/export.py @@ -8,10 +8,10 @@ from uuid import UUID from fastapi import APIRouter, Depends, Request, Response from psycopg import Connection -from app.access.policy import Ctx, parse_query_context +from app.access.policy import Ctx, get_matter, matter_rights, parse_query_context from app.api.deps import Principal, get_conn, get_principal from app.api.schemas import ExportIn -from app.core.errors import unprocessable +from app.core.errors import DOWNLOAD_REFUSED, forbidden, unprocessable from app.exporting import build_export, export_tree, review_export router = APIRouter() @@ -79,6 +79,12 @@ def post_export( conn: Connection = Depends(get_conn), ): selected, assignments = _selection(body) + matter = get_matter(conn, matter_id) + if matter is not None: + rights = matter_rights(conn, principal.account_id, matter, _context(body.context)) + # Without any right the export itself answers as before. With read but no download right: refuse. + if rights.read and not rights.download: + raise forbidden(DOWNLOAD_REFUSED) filename, payload = build_export( conn, principal.account_id, diff --git a/backend/app/api/rooms.py b/backend/app/api/rooms.py index 4e9fef5..cf4b0d5 100644 --- a/backend/app/api/rooms.py +++ b/backend/app/api/rooms.py @@ -182,10 +182,16 @@ def create_room(body: RoomIn, principal: Principal = Depends(get_principal), con name = body.name.strip() conn.execute( """ - INSERT INTO data_rooms (id, kind, name, created_by, owner_id, default_visibility) - VALUES (%s, 'organization', %s, %s, %s, %s) + INSERT INTO data_rooms (id, kind, name, created_by, owner_id, default_visibility, download_roles) + SELECT %s, 'organization', %s, %s, %s, %s, + jsonb_build_object( + 'manager', COALESCE((download_defaults ->> 'manager')::boolean, true), + 'member', COALESCE((download_defaults ->> 'member')::boolean, true), + 'reader', COALESCE((download_defaults ->> 'reader')::boolean, true) + ) + FROM auth_accounts WHERE id = %s """, - (room_id, name, principal.account_id, principal.account_id, body.default_visibility), + (room_id, name, principal.account_id, principal.account_id, body.default_visibility, principal.account_id), ) conn.execute( "INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager')", diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index e3c8e3f..0779174 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -101,7 +101,7 @@ from app.auth.security import ( verify_password, verify_unknown_account, ) -from app.core.errors import Problem, forbidden, not_found, too_many, unprocessable +from app.core.errors import DOWNLOAD_REFUSED, Problem, forbidden, not_found, too_many, unprocessable from app.core.timeutil import dump_date, dump_dt, utcnow from app.media.port import read_clear_bytes from app.media.storage import content_disposition @@ -932,6 +932,7 @@ def download_file( request: Request, context_kind: str | None = None, context_id: str | None = None, + save: bool = False, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): @@ -942,6 +943,8 @@ def download_file( rights = element_rights(conn, principal.account_id, element, context) if not rights.read: raise not_found() + if save and not rights.download: + raise forbidden(DOWNLOAD_REFUSED) asset = conn.execute( """ SELECT id, original_filename, content_type, sha256, status, diff --git a/backend/app/api/schemas.py b/backend/app/api/schemas.py index aa6ca6c..9aba820 100644 --- a/backend/app/api/schemas.py +++ b/backend/app/api/schemas.py @@ -519,3 +519,12 @@ class DispatchCorrectIn(APIModel): clear_sent_on: bool = False counterpart: str | None = Field(default=None, max_length=200) clear_counterpart: bool = False + + +class DownloadPolicyIn(APIModel): + """Who may save or open the original outside of Tsumugu. `direct` only applies to the account default.""" + + manager: bool + member: bool + reader: bool + direct: bool | None = None diff --git a/backend/app/api/sources.py b/backend/app/api/sources.py index ac06d9e..05ecba0 100644 --- a/backend/app/api/sources.py +++ b/backend/app/api/sources.py @@ -12,7 +12,7 @@ from app.access.policy import Ctx, element_rights, get_element, parse_query_cont 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, SourceAssignmentIn -from app.core.errors import not_found, unprocessable, unsupported +from app.core.errors import DOWNLOAD_REFUSED, forbidden, not_found, unprocessable, unsupported from app.mailpack import parse_mail from app.media.storage import content_disposition from app.ops import create_external @@ -94,21 +94,23 @@ def view_external_content( element_id: UUID, context_kind: str | None = None, context_id: str | None = None, + save: bool = False, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id) + if save: + _require_download(conn, principal, element, context) module = get_source(ref["source"]) if ref is not None else None if module is None or module.open_original is None: raise unprocessable("Für diese Quelle ist kein Dateiabruf vorgesehen.") data, media_type, filename = module.open_original(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}"', + "Content-Disposition": content_disposition(filename or "dokument.pdf").replace("attachment;", "inline;", 1), }, ) @@ -150,6 +152,11 @@ def view_mail( ) +def _require_download(conn, principal: Principal, element, context) -> None: + if not element_rights(conn, principal.account_id, element, context).download: + raise forbidden(DOWNLOAD_REFUSED) + + 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": @@ -192,8 +199,9 @@ def download_mail( conn: Connection = Depends(get_conn), ): 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") + _require_download(conn, principal, element, context) + parsed, raw = _complete_mail(conn, principal, element, context, ref) + return _mail_bytes(raw, "message/rfc822", f"{parsed.subject or 'nachricht'}.eml") @router.get("/api/v1/external-refs/{element_id}/mail/attachments/{index}") @@ -202,10 +210,13 @@ def download_mail_attachment( index: int, context_kind: str | None = None, context_id: str | None = None, + save: bool = False, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn), ): element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id) + if save: + _require_download(conn, principal, element, context) parsed, _raw = _complete_mail(conn, principal, element, context, ref) if index < 0 or index >= len(parsed.attachments): raise not_found() diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py index e1782d5..3c3a747 100644 --- a/backend/app/core/errors.py +++ b/backend/app/core/errors.py @@ -33,6 +33,9 @@ def forbidden(detail: str = "Diese Aktion ist im gewählten Kontext nicht erlaub return Problem(403, "Keine Berechtigung", detail, "forbidden") +DOWNLOAD_REFUSED = "Das Herunterladen ist für dich in diesem Datenraum nicht freigegeben. Du kannst das Dokument in Tsumugu lesen." + + def not_found() -> Problem: return Problem(404, "Nicht gefunden", "Der Eintrag ist nicht vorhanden.", "not_found") diff --git a/backend/app/mailpack.py b/backend/app/mailpack.py index 64ad733..3416e94 100644 --- a/backend/app/mailpack.py +++ b/backend/app/mailpack.py @@ -23,8 +23,21 @@ _ALLOWED_TAGS = { "a", "p", "br", "div", "span", "strong", "em", "b", "i", "u", "ul", "ol", "li", "table", "thead", "tbody", "tr", "th", "td", "blockquote", "pre", "code", "h1", "h2", "h3", "h4", "h5", "h6", "img", + "font", "center", "hr", "small", "sub", "sup", "s", "strike", "caption", "tfoot", "section", "article", } -_VOID_TAGS = {"br", "img"} +_VOID_TAGS = {"br", "img", "hr"} +# Formatting a mail may keep. Nothing here loads anything, positions an element or runs code. +_STYLE_PROPS = { + "color", "background-color", "font-family", "font-size", "font-weight", "font-style", "text-align", + "text-decoration", "line-height", "vertical-align", "white-space", "letter-spacing", + "margin", "margin-top", "margin-bottom", "margin-left", "margin-right", + "padding", "padding-top", "padding-bottom", "padding-left", "padding-right", + "border", "border-top", "border-bottom", "border-left", "border-right", "border-color", "border-width", + "border-style", "border-collapse", "width", "max-width", "height", "text-indent", "list-style-type", +} +_STYLE_VALUE = re.compile(r"^[#%a-z0-9 .,()\-+'\"]{1,100}$", re.IGNORECASE) +_STYLE_DENIED = re.compile(r"url|expression|var\(|attr\(|image|@|javascript|behavior|\\", re.IGNORECASE) +_COLOR = re.compile(r"^(#[0-9a-f]{3,8}|[a-z]{3,20}|rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\))$", re.IGNORECASE) _SAFE_LINK = re.compile(r"^(https?://|mailto:)", re.IGNORECASE) _DATA_IMAGE = re.compile(r"^data:image/(?:png|jpeg|gif|webp);base64,[a-z0-9+/=\s]+$", re.IGNORECASE) @@ -275,17 +288,45 @@ def sanitize_html(value: str, images: dict[str, str] | None = None) -> str: return "".join(cleaner.parts).strip() +def _safe_style(value: str) -> str: + kept = [] + for declaration in (value or "").split(";"): + prop, _, raw = declaration.partition(":") + prop, raw = prop.strip().lower(), raw.strip().replace("!important", "").strip() + if prop not in _STYLE_PROPS or not raw or _STYLE_DENIED.search(raw) or not _STYLE_VALUE.match(raw): + continue + kept.append(f"{prop}: {raw}") + return "; ".join(kept) + + def _clean_attrs(tag: str, attrs, images: dict[str, str]) -> str | None: kept: list[str] = [] for key, value in attrs: name = (key or "").lower() - if name.startswith("on") or name in {"style", "srcset"}: + if name.startswith("on") or name == "srcset": + continue + if name == "style": + style = _safe_style(value or "") + if style: + kept.append(f' style="{html.escape(style, quote=True)}"') + continue + if name in {"bgcolor", "color"} and _COLOR.match((value or "").strip()): + kept.append(f' {name}="{html.escape(value.strip(), quote=True)}"') + continue + if name in {"width", "height"} and re.fullmatch(r"\d{1,4}%?", (value or "").strip()): + kept.append(f' {name}="{value.strip()}"') + continue + if name in {"border", "cellpadding", "cellspacing", "size"} and str(value or "").strip().isdigit(): + kept.append(f' {name}="{int(value)}"') + continue + if name in {"align", "valign"} and (value or "").strip().lower() in {"left", "right", "center", "justify", "top", "middle", "bottom"}: + kept.append(f' {name}="{value.strip().lower()}"') continue if tag == "a" and name == "href": target = (value or "").strip() if not _SAFE_LINK.match(target): continue - kept.append(f' href="{html.escape(target, quote=True)}"') + kept.append(f' href="{html.escape(target, quote=True)}" title="{html.escape(target, quote=True)}"') elif tag == "img" and name == "src": source = (value or "").strip() if source.lower().startswith("cid:"): @@ -301,7 +342,7 @@ def _clean_attrs(tag: str, attrs, images: dict[str, str]) -> str | None: if tag == "img" and not any(item.startswith(" src=") for item in kept): return None if tag == "a": - kept.append(' rel="noreferrer"') + kept.append(' rel="noreferrer noopener" target="_blank"') return "".join(kept) diff --git a/backend/app/main.py b/backend/app/main.py index 073ee9d..30147bc 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -11,6 +11,7 @@ from fastapi.responses import JSONResponse from app.api.accounts import router as accounts_router from app.api.correspondence import router as correspondence_router +from app.api.downloads import router as downloads_router from app.api.export import router as export_router from app.api.library import router as library_router from app.api.rooms import router as rooms_router @@ -128,6 +129,7 @@ def create_app() -> FastAPI: app.include_router(team_router) app.include_router(sources_router) app.include_router(export_router) + app.include_router(downloads_router) app.include_router(correspondence_router) return app diff --git a/backend/app/media/storage.py b/backend/app/media/storage.py index 5002fcb..ed45d9a 100644 --- a/backend/app/media/storage.py +++ b/backend/app/media/storage.py @@ -67,5 +67,9 @@ def display_filename(name: str) -> str: def content_disposition(filename: str) -> str: + """The real name goes along in UTF-8 (RFC 5987), with a plain ASCII fallback for old clients.""" + from urllib.parse import quote + safe = display_filename(filename).replace('"', "") - return f'attachment; filename="{safe}"' + fallback = safe.encode("ascii", "replace").decode("ascii").replace("?", "_") + return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(safe, safe='')}" diff --git a/backend/app/present.py b/backend/app/present.py index 8c6419f..4bb5d1d 100644 --- a/backend/app/present.py +++ b/backend/app/present.py @@ -1080,4 +1080,6 @@ LABELS = { "person_included": "Person wieder in die Raumfreigabe aufgenommen", "room_owner_changed": "Eigentümer des Datenraums gewechselt", "room_default_changed": "Voreinstellung des Datenraums geändert", + "room_download_policy_changed": "Download-Regel des Datenraums geändert", + "download_defaults_changed": "Standard für Downloads geändert", } diff --git a/backend/migrations/20261023T090000Z_download_policy.sql b/backend/migrations/20261023T090000Z_download_policy.sql new file mode 100644 index 0000000..1353da5 --- /dev/null +++ b/backend/migrations/20261023T090000Z_download_policy.sql @@ -0,0 +1,11 @@ +-- Herunterladen des Originals: je Rolle steuerbar. Voreinstellung am Konto des Hauptnutzers, +-- Übernahme beim Anlegen eines Raums, danach je Raum änderbar. "direct" gilt für Personen, +-- die einen Eintrag direkt erhalten haben (ohne Raum). Bestehende Daten bleiben erlaubt. + +ALTER TABLE auth_accounts + ADD COLUMN download_defaults jsonb NOT NULL + DEFAULT '{"manager": true, "member": true, "reader": true, "direct": true}'::jsonb; + +ALTER TABLE data_rooms + ADD COLUMN download_roles jsonb NOT NULL + DEFAULT '{"manager": true, "member": true, "reader": true}'::jsonb; diff --git a/backend/tests/test_library.py b/backend/tests/test_library.py index 70a5aac..7e16bad 100644 --- a/backend/tests/test_library.py +++ b/backend/tests/test_library.py @@ -223,3 +223,51 @@ def test_unlinking_keeps_the_matter_and_its_other_cases(world): assert opened["title"] == "Nebenkosten" assert matter in {item["id"] for item in ada.request("GET", "/api/v1/matters")["items"]} ada.request("DELETE", f"/api/v1/matter-case-links/{link['id']}", status=404) + + +def test_download_policy_follows_the_room_role(world): + ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"] + matter = matter_of(ada, "Nebenkosten")["id"] + file = ada.request( + "POST", + "/api/v1/files", + data={"title": "Vertrag", "context_kind": "matter", "context_id": matter}, + files={"upload": ("vertrag.pdf", b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n", "application/pdf")}, + status=201, + )["id"] + _share(ada, "matters", matter, room) + path = f"/api/v1/files/{file}/content" + query = {"context_kind": "matter", "context_id": matter} + + def fetch(person, **extra): + from tests.support import ORIGIN + + headers = {"Origin": ORIGIN, "X-CSRF-Token": person.csrf} + if person.scope is not None: + headers["X-Scope-Kind"], headers["X-Scope-Id"] = person.scope["kind"], person.scope["id"] + return person.client.get(path, params={**query, **extra}, headers=headers) + + # By default every role may save the original. + for person in (ben, cem): + assert fetch(person, save="true").status_code == 200 + seen = ben.request("GET", f"/api/v1/matters/{matter}") + assert seen["rights"]["download"] is True + + # The owner turns it off for readers. Reading stays possible, saving does not. + assert cem.request("GET", f"/api/v1/rooms/{room}/download-policy")["can_change"] is False + cem.request("PUT", f"/api/v1/rooms/{room}/download-policy", json={"manager": True, "member": True, "reader": False}, status=403) + ada.request("PUT", f"/api/v1/rooms/{room}/download-policy", json={"manager": True, "member": True, "reader": False}) + assert fetch(cem).status_code == 200 + refused = fetch(cem, save="true") + assert refused.status_code == 403 + assert "freigegeben" in refused.json()["detail"] + assert cem.request("GET", f"/api/v1/matters/{matter}")["rights"]["download"] is False + assert fetch(ben, save="true").status_code == 200 + # A stranger learns nothing about the policy of the room. + dan.request("GET", f"/api/v1/rooms/{room}/download-policy", status=404) + + # The owner's default is copied into a new room. + ada.request("PUT", "/api/v1/auth/download-defaults", json={"manager": True, "member": False, "reader": False, "direct": True}) + fresh = ada.request("POST", "/api/v1/rooms", json={"name": "Neu", "default_visibility": "private"}, status=201)["id"] + assert ada.request("GET", f"/api/v1/rooms/{fresh}/download-policy")["roles"] == {"manager": True, "member": False, "reader": False} + assert ada.request("GET", f"/api/v1/rooms/{room}/download-policy")["roles"]["member"] is True diff --git a/backend/tests/test_mail_html.py b/backend/tests/test_mail_html.py new file mode 100644 index 0000000..be1c00c --- /dev/null +++ b/backend/tests/test_mail_html.py @@ -0,0 +1,38 @@ +"""HTML mail: formatting stays, everything active or loading from outside is removed.""" + +from __future__ import annotations + +from app.mailpack import sanitize_html + + +def test_formatting_stays_and_active_content_goes(): + cleaned = sanitize_html( + '
Hallo' + '
x

' + '
' + ) + assert 'style="color: #333; font-size: 14px"' in cleaned + assert '' in cleaned + assert 'bgcolor="#eee"' in cleaned and "
" in cleaned + for forbidden in ("onclick", "script", "iframe", "Text

' + ) + assert "url" not in cleaned and "position" not in cleaned and "expression" not in cleaned and "behavior" not in cleaned + assert "color: red" in cleaned and "margin: 4px" in cleaned + + +def test_links_and_images_are_limited(): + cleaned = sanitize_html( + 'abc' + 'logo' + ) + assert "javascript" not in cleaned and "data:text" not in cleaned and "track" not in cleaned and "svg" not in cleaned + assert 'href="https://ok.example/x"' in cleaned + assert 'rel="noreferrer noopener"' in cleaned and 'target="_blank"' in cleaned + assert 'src="data:image/png;base64,AAAA"' in cleaned diff --git a/backend/tests/test_room_access.py b/backend/tests/test_room_access.py index 9e5b8b7..9b3934d 100644 --- a/backend/tests/test_room_access.py +++ b/backend/tests/test_room_access.py @@ -68,10 +68,10 @@ def test_a_new_entry_follows_the_room_preset_and_rights_follow_the_role(world, d assert [(s["room_name"], s["access"]) for s in view["shares"]] == [("Werkstatt", "edit")] assert ben.request("GET", f"/api/v1/cases/{shared['id']}")["rights"] == { - "read": True, "edit": True, "share": False, "delete": False, + "read": True, "edit": True, "share": False, "delete": False, "download": True, } assert cem.request("GET", f"/api/v1/cases/{shared['id']}")["rights"] == { - "read": True, "edit": False, "share": False, "delete": False, + "read": True, "edit": False, "share": False, "delete": False, "download": True, } dan.request("GET", f"/api/v1/cases/{shared['id']}", status=404) assert "Gemeinsame Akte" in {item["title"] for item in ben.request("GET", "/api/v1/cases")["items"]} @@ -180,7 +180,7 @@ def test_a_standalone_matter_is_shared_like_a_case(world, db): matter = matter_of(ada, "Eigener Vorgang") assert ben.request("GET", f"/api/v1/matters/{matter['id']}")["rights"]["edit"] is True assert cem.request("GET", f"/api/v1/matters/{matter['id']}")["rights"] == { - "read": True, "edit": False, "share": False, "delete": False, + "read": True, "edit": False, "share": False, "delete": False, "download": True, } ben.request("POST", f"/api/v1/matters/{matter['id']}/delete", json={"expected_version": matter["version"]}, status=403) _unshare(ada, "matters", matter["id"], room) diff --git a/docs/architecture/BENUTZERVERWALTUNG.md b/docs/architecture/BENUTZERVERWALTUNG.md index f792e58..e4aa7cd 100644 --- a/docs/architecture/BENUTZERVERWALTUNG.md +++ b/docs/architecture/BENUTZERVERWALTUNG.md @@ -96,3 +96,15 @@ Der Baum „Meine Ablage“ steht links auf den Listenseiten und auf den Seiten - **Nachladen:** Die Wurzeln kommen aus `/cases` und `/matters`, die Struktur eines Knotens aus `GET /cases/{id}/outline` und `GET /matters/{id}/outline`, einmal beim Aufklappen. Die Antworten enthalten nur Lesbares (keine Inhalte). Ändert sich der offene Eintrag (Kapitel, Unterakte, Vorgang), lädt der Baum seine Struktur neu. - **Breite und Dichte:** Der Baum lässt sich an seiner rechten Kante mit der Maus ziehen (200 bis 560 Pixel, Pfeiltasten auf dem Griff, Doppelklick setzt zurück). Die Breite wird im Browser gemerkt (`localStorage`, Schlüssel `tsumugu-tree-width`); ohne Speicher gilt die Standardbreite. Zeilen und Einrückung sind kompakt, damit tiefe Strukturen hineinpassen. - **Vorgang aus einer Akte lösen:** Im Menü des Vorgangs steht „Aus Akte lösen“, wenn er in Akten liegt. Gelöst wird nur die Zuordnung zur gewählten Akte (`DELETE /matter-case-links/{id}`); der Vorgang, seine Inhalte und seine anderen Akten bleiben. Erlaubt ist es mit Bearbeitungsrecht in der Akte oder mit Teilen-Recht am Vorgang. + +### Herunterladen von Originalen (seit 23.10.2026) + +- **Regel je Rolle:** Das Recht „Herunterladen“ ist neben Lesen, Bearbeiten, Teilen und Löschen ein eigenes Recht. Der Eigentümer hat es immer. Über einen Raum folgt es der Rolle (Verwalter, Mitglied, Leser) laut Regel des Raums; direkt freigegebene Personen folgen dem Wert „direkt“ des Eigentümers. Ohne Leserecht gibt es kein Herunterladen. +- **Wo einstellen:** Voreinstellung am Konto des Hauptnutzers („Mein Konto“, wird beim Anlegen eines Raums übernommen), danach je Raum in der Raumverwaltung (nur Eigentümer). Bestehende Daten bleiben erlaubt (Migration `20261023T090000Z_download_policy.sql`). +- **Was geprüft wird (serverseitig):** Speichern oder Öffnen des Originals (`?save=true` bei Dateien, Paperless-Dokumenten und Mail-Anlagen), die vollständige E-Mail (`.eml`) und das Übergabepaket. Lesen in Tsumugu bleibt möglich; die Regel ist ein Nutzungsrecht, kein Kopierschutz (Abfotografieren oder Entwicklerwerkzeuge verhindert sie nicht). +- **Dateiname:** Gespeichert wird unter dem echten Namen (UTF-8, `filename*`), die E-Mail unter ihrem Betreff. +- **Endpunkte:** `GET/PUT /rooms/{id}/download-policy`, `GET/PUT /auth/download-defaults`. + +### E-Mails als HTML + +Die Mail wird formatiert (Standard) oder als Text gezeigt. Der Server bereinigt das HTML mit einer Positivliste (keine Skripte, Formulare, Rahmen, `" + + `${html}`; +} + export function MailBody({ html, text, truncated, notices = [] }) { + const [view, setView] = useState(html ? "html" : "text"); + const mode = html ? view : "text"; return (
- {html ?
: null} -

Vereinfachte Textfassung. Sie ist nicht die formatierte Ansicht.

- {text ?
{text}
:

Diese Nachricht hat keinen lesbaren Text.

} + {html ? ( +
+ + +
+ ) : null} + {mode === "html" ? ( + <> +