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)