Steuere das Herunterladen von Originalen je Rolle, benenne Dateien richtig und zeige HTML-Mails gesichert im Sandbox-Rahmen.
Deploy Development / deploy (push) Successful in 40s
Test Suite / pytest-backend (push) Successful in 5m35s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 22s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
StommerandClaude Sonnet 5.5 committed 2026-10-22 14:22:35 +02:00
1 parent 0a5daf6713
commit 075525ee17
26 files changed
+494 -71

No files matched your search

+31 -6
View File
@@ -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
+82
View File
@@ -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)
+8 -2
View File
@@ -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,
+9 -3
View File
@@ -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')",
+4 -1
View File
@@ -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,
+9
View File
@@ -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
+16 -5
View File
@@ -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()
+3
View File
@@ -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")
+45 -4
View File
@@ -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)
+2
View File
@@ -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
+5 -1
View File
@@ -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='')}"
+2
View File
@@ -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",
}
@@ -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;
+48
View File
@@ -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
+38
View File
@@ -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(
'<div style="color:#333;font-size:14px" onclick="steal()"><font color="red" size="3">Hallo</font>'
'<table bgcolor="#eee" width="100%"><tr><td align="center">x</td></tr></table><hr>'
'<script>alert(1)</script><iframe src="http://x"></iframe><form action="http://x"><input></form></div>'
)
assert 'style="color: #333; font-size: 14px"' in cleaned
assert '<font color="red" size="3">' in cleaned
assert 'bgcolor="#eee"' in cleaned and "<hr>" in cleaned
for forbidden in ("onclick", "script", "iframe", "<form", "<input", "alert"):
assert forbidden not in cleaned
def test_styles_cannot_load_or_position():
cleaned = sanitize_html(
'<p style="background:url(http://track/p.png);position:fixed;width:expression(alert(1));'
'color:red;behavior:url(x.htc);margin:4px">Text</p>'
)
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(
'<a href="javascript:alert(1)">a</a><a href="https://ok.example/x">b</a><a href="data:text/html,x">c</a>'
'<img src="http://track/p.gif"><img src="data:image/png;base64,AAAA" alt="logo"><img src="data:image/svg+xml;base64,AAAA">'
)
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
+3 -3
View File
@@ -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)
+12
View File
@@ -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, `<style>`-Blöcke; Formatierung nur aus erlaubten Eigenschaften, ohne `url()`, Position oder Ausdrücke; Bilder nur eingebettet als PNG/JPEG/GIF/WebP; Links nur `http(s)` und `mailto`, mit `noopener`). Im Browser läuft die Ansicht in einem Rahmen mit leerem `sandbox` (eigene Herkunft, keine Skripte), Content-Security-Policy `default-src 'none'; img-src data:` und ohne Referrer. Fremde Bilder werden nicht geladen.
+13
View File
@@ -3,6 +3,8 @@ import { api } from "../api.js";
import { SessionContext } from "../session.js";
import { ErrorNote } from "../pages/widgets.jsx";
import { formatWhen } from "./admin-core.js";
import { DownloadPolicy } from "./DownloadPolicy.jsx";
import { isEmployee } from "./admin-core.js";
import { PasswordForm } from "./widgets.jsx";
export function Account() {
@@ -54,6 +56,17 @@ export function Account() {
</header>
<ErrorNote error={error} />
{notice ? <p className="notice" role="status">{notice}</p> : null}
{isEmployee(session) ? null : (
<section className="card stack" aria-label="Herunterladen">
<h2>Herunterladen von Originalen</h2>
<DownloadPolicy
path="/api/v1/auth/download-defaults"
editable
withDirect
intro="Diese Regel übernehmen neue Räume. Bestehende Räume ändert ihr Eigentümer in der Raumverwaltung. Die Regel für direkt freigegebene Personen gilt sofort für alle deine Einträge."
/>
</section>
)}
<section className="card stack" aria-label="Passwort">
<h2>Passwort ändern</h2>
<p className="muted">Beim Ändern werden deine anderen Sitzungen beendet.</p>
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useState } from "react";
import { api } from "../api.js";
import { ErrorNote } from "../pages/widgets.jsx";
const ROLES = [
["manager", "Verwalter"],
["member", "Mitglieder"],
["reader", "Leser"],
];
// Who may save a document or mail to their device. Reading in Tsumugu stays possible for everyone.
// The rule applies to saving and opening the original, not to what the screen shows.
export function DownloadPolicy({ path, editable, withDirect = false, intro }) {
const [roles, setRoles] = useState(null);
const [canChange, setCanChange] = useState(editable);
const [error, setError] = useState("");
const [notice, setNotice] = useState("");
useEffect(() => {
let alive = true;
api(path).then((data) => {
if (!alive) return;
setRoles(data.roles);
if (data.can_change !== undefined) setCanChange(data.can_change);
}).catch((err) => alive && setError(err.message));
return () => {
alive = false;
};
}, [path]);
async function change(key, value) {
setError("");
setNotice("");
const next = { ...roles, [key]: value };
try {
const saved = await api(path, { method: "PUT", body: next });
setRoles(saved.roles);
setNotice("Die Regel ist gespeichert.");
} catch (err) {
setError(err.message);
}
}
if (!roles) return error ? <ErrorNote error={error} /> : null;
const items = withDirect ? [...ROLES, ["direct", "Direkt freigegebene Personen"]] : ROLES;
return (
<fieldset className="pick-group">
<legend>Herunterladen erlaubt für</legend>
{intro ? <p className="muted">{intro}</p> : null}
{items.map(([key, label]) => (
<label key={key} className="check">
<input type="checkbox" checked={Boolean(roles[key])} disabled={!canChange} onChange={(event) => change(key, event.target.checked)} />
{label}
</label>
))}
<span className="muted">Lesen in Tsumugu bleibt für alle Rollen möglich. Die Regel betrifft das Speichern und Öffnen der Originale sowie das Übergabepaket. Was auf dem Bildschirm erscheint, lässt sich damit nicht gegen Abfotografieren schützen.</span>
{canChange ? null : <span className="muted">Nur der Eigentümer kann die Regel ändern.</span>}
<ErrorNote error={error} />
{notice ? <p className="notice" role="status">{notice}</p> : null}
</fieldset>
);
}
+34 -24
View File
@@ -92,18 +92,48 @@ export async function fetchMailPart(elementId, context, suffix) {
return response.blob();
}
export async function downloadMailPart(elementId, context, suffix, filename) {
const blob = await fetchMailPart(elementId, context, suffix);
// The name the server gave the file (RFC 5987 form first), so a saved file keeps its real name.
export function nameFromDisposition(header, fallback) {
const text = header || "";
const star = /filename\*\s*=\s*UTF-8''([^;]+)/i.exec(text);
if (star) {
try {
return decodeURIComponent(star[1].trim());
} catch {
/* fall through to the plain name */
}
}
const plain = /filename\s*=\s*"([^"]+)"/i.exec(text) || /filename\s*=\s*([^;]+)/i.exec(text);
return plain ? plain[1].trim() : fallback;
}
export function saveBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename || "nachricht.eml";
link.download = filename;
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 60000);
}
// Saves a document to the device. The server checks the download right of the role.
export async function saveDocument(path, context, fallbackName) {
const params = mailQuery(context);
params.set("save", "true");
const response = await fetch(`${path}?${params}`, { credentials: "include", headers: scopeHeaders() });
if (!response.ok) {
const data = await response.json().catch(() => null);
throw new Error(data?.detail || "Die Datei ist nicht verfügbar.");
}
saveBlob(await response.blob(), nameFromDisposition(response.headers.get("Content-Disposition"), fallbackName));
}
export async function downloadMailPart(elementId, context, suffix, filename) {
await saveDocument(`/api/v1/external-refs/${elementId}/mail/${suffix}`, context, filename || "nachricht.eml");
}
export async function fetchExternal(elementId, context) {
const params = new URLSearchParams();
if (context?.kind && context?.id) {
@@ -140,27 +170,7 @@ export async function fetchFile(elementId, context) {
}
export async function downloadFile(elementId, context, filename) {
const params = new URLSearchParams();
if (context?.kind && context?.id) {
params.set("context_kind", context.kind);
params.set("context_id", context.id);
}
const response = await fetch(`/api/v1/files/${elementId}/content?${params}`, {
credentials: "include",
headers: scopeHeaders(),
});
if (!response.ok) {
throw new Error("Die Datei ist nicht verfügbar.");
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename || "datei";
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
await saveDocument(`/api/v1/files/${elementId}/content`, context, filename || "datei");
}
export async function fetchBlob(path) {
+3
View File
@@ -150,3 +150,6 @@ body.is-resizing .library__resizer { background: color-mix(in srgb, var(--accent
.app-main:has(.workspace) .library__main { flex: 1; }
}
@media (max-width: 759px) { body.is-phone-reading .library__toggle { display: none; } }
.mail-frame { display: block; width: 100%; height: 60vh; min-height: 260px; border: 1px solid var(--border); border-radius: 8px; background: #fff; }
.mail-reading .segmented { display: inline-flex; gap: 6px; margin-bottom: 8px; }
+32 -3
View File
@@ -1,9 +1,38 @@
import { useState } from "react";
// The cleaned HTML of a mail is shown in a frame without scripts and without any reach into the app:
// an empty `sandbox` gives it its own origin, and the policy inside allows no loads except inline images.
const FRAME_POLICY = "default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
export function mailDocument(html) {
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${FRAME_POLICY}">`
+ '<meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width, initial-scale=1"><base target="_blank">'
+ "<style>body{margin:12px;font:15px/1.45 system-ui,sans-serif;color:#1c1b18;background:#fff;overflow-wrap:anywhere}"
+ "img,table{max-width:100%}table{border-collapse:collapse}a{color:#0b5d4b}blockquote{margin:8px 0 8px 4px;padding-left:10px;border-left:3px solid #ccc;color:#555}</style>"
+ `</head><body>${html}</body></html>`;
}
export function MailBody({ html, text, truncated, notices = [] }) {
const [view, setView] = useState(html ? "html" : "text");
const mode = html ? view : "text";
return (
<div className="mail-reading">
{html ? <div className="mail-letter__html" dangerouslySetInnerHTML={{ __html: html }} /> : null}
<p className="muted">Vereinfachte Textfassung. Sie ist nicht die formatierte Ansicht.</p>
{text ? <pre className="mail-letter__body">{text}</pre> : <p className="muted">Diese Nachricht hat keinen lesbaren Text.</p>}
{html ? (
<div className="segmented" role="group" aria-label="Darstellung der Nachricht">
<button type="button" className={mode === "html" ? "" : "quiet"} aria-pressed={mode === "html"} onClick={() => setView("html")}>Formatiert</button>
<button type="button" className={mode === "text" ? "" : "quiet"} aria-pressed={mode === "text"} onClick={() => setView("text")}>Nur Text</button>
</div>
) : null}
{mode === "html" ? (
<>
<iframe className="mail-frame" title="Nachricht" sandbox="allow-popups allow-popups-to-escape-sandbox" referrerPolicy="no-referrer" srcDoc={mailDocument(html)} />
<p className="muted">Aus Sicherheitsgründen sind Skripte, eingebettete Formulare und Bilder von fremden Servern entfernt. Links öffnen externe Seiten: nur bekannten Absendern vertrauen.</p>
</>
) : (
<>
{text ? <pre className="mail-letter__body">{text}</pre> : <p className="muted">Diese Nachricht hat keinen lesbaren Text.</p>}
</>
)}
{truncated ? <p className="muted">Der Text ist gekürzt, weil die Nachricht sehr groß ist. Das Original bleibt die vollständige E-Mail.</p> : null}
{notices.map((item) => <p key={item} className="notice">{item}</p>)}
</div>
+10 -12
View File
@@ -1,7 +1,7 @@
import { DocumentView } from "./DocumentView.jsx";
import { useContext, useEffect, useRef, useState } from "react";
import { SessionContext } from "../session.js";
import { documentToText, downloadMailPart, fetchExternal, fetchFile, fetchMailPart, isDirty, markDirty, textToDocument, api } from "../api.js";
import { documentToText, downloadMailPart, fetchExternal, fetchFile, fetchMailPart, isDirty, markDirty, saveDocument, textToDocument, api } from "../api.js";
import { SourceAssignment, representationOf, stageFor } from "../sources/registry.jsx";
import "../sources/builtin-views.jsx";
import { ErrorNote } from "./widgets.jsx";
@@ -356,12 +356,10 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
setError("");
try {
const view = representationOf(element);
const blob = view === "source-file" || view === "text"
? await fetchExternal(element.id, context)
: await fetchFile(element.id, context);
const url = URL.createObjectURL(blob);
window.open(url, "_blank", "noopener");
setTimeout(() => URL.revokeObjectURL(url), 60000);
const path = view === "source-file" || view === "text"
? `/api/v1/external-refs/${element.id}/content`
: `/api/v1/files/${element.id}/content`;
await saveDocument(path, context, element.file?.filename || element.title || "dokument");
} catch (err) {
setError(err.message);
}
@@ -526,8 +524,8 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
</p>
</div>
<div className="reader-pane__tools">
{element.kind !== "note" && !isMail ? (
<button type="button" className="icon-button" aria-label="Original öffnen" onClick={openOriginal}>
{element.kind !== "note" && !isMail && binding.rights.download ? (
<button type="button" className="icon-button" aria-label="Original herunterladen" title="Original herunterladen" onClick={openOriginal}>
<NavIcon name="link" />
</button>
) : null}
@@ -572,13 +570,13 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
{!isMail && !locked && !unassigned && phase === "missing" ? (
<div className="reader-pane__state">
<p>Für diesen Inhalt gibt es keine eingebaute Vorschau.</p>
<button type="button" onClick={openOriginal}>Original öffnen</button>
{binding.rights.download ? <button type="button" onClick={openOriginal}>Original herunterladen</button> : null}
</div>
) : null}
{!isMail && phase === "error" ? (
<div className="reader-pane__state">
<p>Die Vorschau ist nicht verfügbar.</p>
<button type="button" onClick={openOriginal}>Original öffnen</button>
{binding.rights.download ? <button type="button" onClick={openOriginal}>Original herunterladen</button> : null}
</div>
) : null}
{!isMail && media === "text" ? <pre className="mail-letter__body">{sourceText}</pre> : null}
@@ -590,7 +588,7 @@ export function ReadingPane({ binding, context, backLabel, onClose, onReload, ca
{!isMail && media === "other" && blobUrl ? (
<div className="reader-pane__state">
<p>Die Datei ist geladen, aber hier nicht als Seite darstellbar.</p>
<a href={blobUrl} target="_blank" rel="noreferrer">Original öffnen</a>
{binding.rights.download ? <a href={blobUrl} target="_blank" rel="noreferrer">Original öffnen</a> : null}
</div>
) : null}
</div>
+3
View File
@@ -10,6 +10,7 @@ import {
lastManagerIds,
roleLabel,
} from "../admin/admin-core.js";
import { DownloadPolicy } from "../admin/DownloadPolicy.jsx";
import { OneTimeSecret } from "../admin/widgets.jsx";
import { SessionContext } from "../session.js";
import { ErrorNote } from "./widgets.jsx";
@@ -176,6 +177,8 @@ export function RoomAdmin({ room, onRenamed, onArchived }) {
</label>
) : null}
<DownloadPolicy path={`/api/v1/rooms/${room.id}/download-policy`} editable={Boolean(room.is_owner)} />
<h3>Mitglieder</h3>
<ul className="index">
{members.map((member) => (
+5 -3
View File
@@ -200,9 +200,11 @@ function Binding({ binding, context, canEdit, isOwner, onChange }) {
{element.kind === "note" ? <RegisteredNote element={element} context={context} binding={binding} onReload={onChange} /> : null}
{element.kind === "file" && element.file ? (
element.file.status === "active" ? (
<button type="button" onClick={() => downloadFile(element.id, context, element.file.filename)}>
{element.file.filename} herunterladen
</button>
binding.rights.download ? (
<button type="button" onClick={() => downloadFile(element.id, context, element.file.filename).catch((err) => setError(err.message))}>
{element.file.filename} herunterladen
</button>
) : <p className="muted">{element.file.filename} · Das Herunterladen ist für dich nicht freigegeben.</p>
) : (
<p className="error">Die Datei ist gerade nicht verfügbar.</p>
)
+4 -4
View File
@@ -124,7 +124,7 @@ export function TextStage({ element, context }) {
);
}
export function MailStage({ element, context, shownDirection }) {
export function MailStage({ element, context, binding, shownDirection }) {
const [letter, setLetter] = useState(null);
const [error, setError] = useState("");
const [shownFor, setShownFor] = useState(null);
@@ -236,7 +236,7 @@ export function MailStage({ element, context, shownDirection }) {
async function openOriginal() {
setError("");
try {
await downloadMailPart(element.id, context, "original", "nachricht.eml");
await downloadMailPart(element.id, context, "original", `${letter?.title || "nachricht"}.eml`);
} catch (err) {
setError(err.message);
}
@@ -262,7 +262,7 @@ export function MailStage({ element, context, shownDirection }) {
{media === "image" && blobUrl ? <img className="reader-image" alt={shownFile?.filename || element.title} src={blobUrl} /> : null}
{media === "pdf" && pdf ? <canvas ref={canvasRef} className="reader-canvas" /> : null}
{media === "pdf-frame" && blobUrl ? <DocumentView title={shownFile?.filename || element.title} url={blobUrl} /> : null}
{media === "other" && blobUrl ? <a href={blobUrl} target="_blank" rel="noreferrer">Anlage öffnen</a> : null}
{media === "other" && blobUrl && binding?.rights?.download ? <a href={blobUrl} target="_blank" rel="noreferrer">Anlage öffnen</a> : null}
{pages > 1 ? (
<div className="reader-pages">
<button type="button" disabled={page <= 1} onClick={() => setPage((current) => Math.max(1, current - 1))}>Vorherige Seite</button>
@@ -271,7 +271,7 @@ export function MailStage({ element, context, shownDirection }) {
</div>
) : null}
<MailBody html={letter.html} text={letter.text} truncated={letter.text_truncated} notices={letter.notices} />
<button type="button" onClick={openOriginal}>Vollständige E-Mail</button>
{binding?.rights?.download ? <button type="button" onClick={openOriginal}>Vollständige E-Mail herunterladen</button> : null}
</>
) : (
<p className="muted">{error ? "Die vollständige Nachricht konnte nicht geladen werden." : "Die vollständige Nachricht wird geladen …"}</p>