Gib verknüpfte Originale im Datenraum je Person über die eigenen Zugänge frei, damit Raummitglieder Paperless-Dokumente und E-Mails geteilter Akten lesen können.
Deploy Development / deploy (push) Successful in 46s
Test Suite / pytest-backend (push) Successful in 6m39s
Test Suite / frontend-build (push) Successful in 24s
Test Suite / smoke-dev (push) Successful in 0s

Die Raumfreigabe allein gab die Zugänge des Owners nicht weiter. Ein Leser im Raum sah die Akte,
aber kein Original. Neu ist room_source_access: Wer im Raum teilen darf, schaltet für ein Mitglied
„Originale über meine Zugänge“ ein. Das gilt für alle eigenen, mit dem Raum geteilten Einträge.
Ausnahmen, Ende der Raumfreigabe und Verlassen des Raums schließen den Abruf. Beschluss R-01 ist
entsprechend ergänzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-04 15:19:15 +01:00
1 parent 363ecdfd0a
commit 15e0dc7e52
15 files changed
+362 -13

No files matched your search

+36 -7
View File
@@ -458,8 +458,35 @@ def _source_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> dict | Non
).fetchone()
def room_source_access(conn, actor: UUID, kind: str, resource_id: UUID, owner_id: UUID) -> bool:
"""Whether a room the entry is shared with lets this member read the owner's linked originals.
The owner has switched it on for this person in that room. Only an active room, an active
membership with a reading role and an active account count.
"""
readers = [role for role, rights in ROOM_RIGHTS.items() if rights.read]
row = conn.execute(
"""
SELECT 1
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'
JOIN auth_accounts a ON a.id = m.subject_id AND a.status = 'active'
JOIN room_source_access x ON x.room_id = s.room_id AND x.subject_id = m.subject_id AND x.owner_id = %s
WHERE s.resource_kind = %s AND s.resource_id = %s AND m.role = ANY(%s)
LIMIT 1
""",
(actor, owner_id, kind, resource_id, readers),
).fetchone()
return row is not None
def mediated_source_owner(conn, actor: UUID, element: dict, context: Ctx | None) -> UUID | None:
"""Owner whose stored connector may serve this reader. None unless the grant allows it."""
"""Owner whose stored connector may serve this reader.
None unless the owner allowed it, either on the personal grant or for this person in a room
the entry is shared with. Read rights and exceptions are checked first.
"""
if context is None or not element_rights(conn, actor, element, context).read:
return None
if context.kind == "case":
@@ -467,19 +494,21 @@ def mediated_source_owner(conn, actor: UUID, element: dict, context: Ctx | None)
if resource is None:
return None
resource = _rights_bearing_case(conn, resource)
grant = _source_grant(conn, actor, "case", resource["id"])
elif context.kind == "matter":
resource = get_matter(conn, context.id)
if resource is None:
return None
grant = _source_grant(conn, actor, "matter", resource["id"])
else:
return None
if resource["owner_subject_id"] == actor:
owner = resource["owner_subject_id"]
if owner == actor:
return None
if grant is None or not grant["can_read"] or not grant["use_owner_sources"]:
return None
return resource["owner_subject_id"]
grant = _source_grant(conn, actor, context.kind, resource["id"])
if grant is not None and grant["can_read"] and grant["use_owner_sources"]:
return owner
if room_source_access(conn, actor, context.kind, resource["id"], owner):
return owner
return None
def element_rights_via_case_or_direct(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
+86
View File
@@ -30,6 +30,7 @@ from app.api.schemas import (
OwnerIn,
RoomIn,
RoomPatchIn,
SourceAccessIn,
VisibilityIn,
)
from app.auth.accounts import normalize_email
@@ -114,6 +115,27 @@ def _drop_shares_of(conn, room_id: UUID, subject_id: UUID) -> None:
""",
(room_id, subject_id, subject_id),
)
# Without own shares in the room there is nothing left to lend.
conn.execute(
"DELETE FROM room_source_access WHERE room_id = %s AND owner_id = %s",
(room_id, subject_id),
)
def _drop_source_access_to(conn, room_id: UUID, subject_id: UUID) -> None:
"""A person who leaves the team loses every source access lent to them there. A return starts without it."""
conn.execute(
"DELETE FROM room_source_access WHERE room_id = %s AND subject_id = %s",
(room_id, subject_id),
)
def _lent_to(conn, room_id: UUID, owner_id: UUID) -> set[UUID]:
rows = conn.execute(
"SELECT subject_id FROM room_source_access WHERE room_id = %s AND owner_id = %s",
(room_id, owner_id),
).fetchall()
return {row["subject_id"] for row in rows}
def _set_role(conn, actor: UUID, room_id: UUID, subject_id: UUID, role: str, *, added: bool) -> None:
@@ -391,6 +413,7 @@ def members(room_id: UUID, principal: Principal = Depends(get_principal), conn:
""",
(room_id,),
).fetchall()
lent = _lent_to(conn, room_id, principal.account_id)
return {
"items": [
{
@@ -400,6 +423,8 @@ def members(room_id: UUID, principal: Principal = Depends(get_principal), conn:
"role": row["role"],
"account_status": row["status"],
"is_owner": row["subject_id"] == owner_id,
"is_self": row["subject_id"] == principal.account_id,
"my_sources": row["subject_id"] in lent,
}
for row in rows
]
@@ -472,6 +497,7 @@ def remove_member(
(room_id, subject_id),
)
_drop_shares_of(conn, room_id, subject_id)
_drop_source_access_to(conn, room_id, subject_id)
# The removed person works in the personal room again; own entries stay visible there.
conn.execute(
"""
@@ -485,6 +511,66 @@ def remove_member(
return Response(status_code=204)
@router.put("/api/v1/rooms/{room_id}/source-access/{subject_id}")
def put_source_access(
room_id: UUID,
subject_id: UUID,
body: SourceAccessIn,
principal: Principal = Depends(get_principal),
conn: Connection = Depends(get_conn),
):
"""Lend the own connectors to one member for the own entries shared with this room.
Only the person whose connectors are used decides. That is anyone who may share into the room.
"""
actor = principal.account_id
room = conn.execute(
"SELECT id, status FROM data_rooms WHERE id = %s AND kind = 'organization'", (room_id,)
).fetchone()
if room is None or room_role(conn, actor, room_id) is None:
raise not_found()
if room["status"] != "active":
raise unprocessable("Der Datenraum ist archiviert.")
if room_role(conn, actor, room_id) not in {"member", "manager"}:
raise forbidden("Quellen gibt frei, wer in diesem Datenraum teilen darf.")
if subject_id == actor:
raise unprocessable("Die eigenen Zugänge brauchen keine Freigabe.")
if room_role(conn, subject_id, room_id) is None:
raise not_found()
if body.enabled:
created = conn.execute(
"""
INSERT INTO room_source_access (room_id, owner_id, subject_id)
VALUES (%s, %s, %s)
ON CONFLICT DO NOTHING
RETURNING subject_id
""",
(room_id, actor, subject_id),
).fetchone()
changed = created is not None
else:
removed = conn.execute(
"""
DELETE FROM room_source_access
WHERE room_id = %s AND owner_id = %s AND subject_id = %s
RETURNING subject_id
""",
(room_id, actor, subject_id),
).fetchone()
changed = removed is not None
if changed:
audit(
conn,
actor,
room_id,
"room_source_access_granted" if body.enabled else "room_source_access_revoked",
"membership",
subject_id,
detail={"room_id": str(room_id)},
)
return {"subject_id": str(subject_id), "enabled": body.enabled}
@router.post("/api/v1/invitations")
def invite(
body: InvitationIn,
+6
View File
@@ -37,6 +37,11 @@ def _view(conn, actor: UUID, kind: str, resource_id: UUID) -> dict:
(kind, resource_id),
).fetchall()
result = []
lent = conn.execute(
"SELECT room_id, subject_id FROM room_source_access WHERE owner_id = %s",
(actor,),
).fetchall()
lent_pairs = {(row["room_id"], row["subject_id"]) for row in lent}
for share in shares:
members = conn.execute(
"""
@@ -65,6 +70,7 @@ def _view(conn, actor: UUID, kind: str, resource_id: UUID) -> dict:
"display_name": row["display_name"],
"role": row["role"],
"excluded": row["excluded"],
"sources": (share["room_id"], row["subject_id"]) in lent_pairs,
"rights": {
"read": _capped(row["role"], share["access"]).read,
"edit": _capped(row["role"], share["access"]).edit,
+4
View File
@@ -95,6 +95,10 @@ class ExclusionIn(APIModel):
excluded: bool
class SourceAccessIn(APIModel):
enabled: bool
class OwnerIn(APIModel):
subject_id: UUID
+2
View File
@@ -1078,6 +1078,8 @@ LABELS = {
"room_unshared": "Freigabe an Datenraum beendet",
"person_excluded": "Person von der Raumfreigabe ausgenommen",
"person_included": "Person wieder in die Raumfreigabe aufgenommen",
"room_source_access_granted": "Originale über eigene Zugänge im Datenraum freigegeben",
"room_source_access_revoked": "Originale über eigene Zugänge im Datenraum entzogen",
"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",
@@ -0,0 +1,14 @@
-- Quellenfreigabe im Raum: Eine Person erlaubt einem Mitglied, die verknüpften Originale
-- ihrer mit diesem Raum geteilten Akten und Vorgänge über ihre eigenen Zugänge zu lesen.
-- Die Freigabe gilt je Raum, je verleihender Person und je Mitglied. Sie entsteht nur ausdrücklich.
CREATE TABLE room_source_access (
room_id uuid NOT NULL REFERENCES data_rooms (id),
owner_id uuid NOT NULL REFERENCES auth_accounts (id),
subject_id uuid NOT NULL REFERENCES auth_accounts (id),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (room_id, owner_id, subject_id),
CONSTRAINT room_source_access_other CHECK (owner_id <> subject_id)
);
CREATE INDEX room_source_access_subject ON room_source_access (subject_id, room_id);
+178
View File
@@ -0,0 +1,178 @@
"""Room members read linked originals through the owner's connector only when the owner lends it to them."""
from __future__ import annotations
import json
import pytest
from fastapi.testclient import TestClient
import app.sources as sources
from app.auth.accounts import create_account
from tests.support import ORIGIN, PASSWORD, Actor
OWNER_TOKEN = "raum-owner-paperless-token"
UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar."
def _second_client():
from app.main import app
return TestClient(app)
def _actor(client, db, key: str, email: str, *, main: bool = False) -> Actor:
actor = Actor(client if main else _second_client(), email, key.title())
create_account(db, actor.email, actor.name, PASSWORD)
db.commit()
actor.login()
return actor
def _id(db, email: str) -> str:
row = db.execute("SELECT id FROM auth_accounts WHERE email = %s", (email,)).fetchone()
db.rollback()
return str(row["id"])
def _raw(actor: Actor, path: str):
headers = {"Origin": ORIGIN, "X-CSRF-Token": actor.csrf}
if actor.scope is not None:
headers["X-Scope-Kind"] = actor.scope["kind"]
headers["X-Scope-Id"] = actor.scope["id"]
return actor.client.get(path, headers=headers)
def _lend(actor: Actor, room: str, subject: str, enabled: bool, status: int = 200):
return actor.request(
"PUT",
f"/api/v1/rooms/{room}/source-access/{subject}",
json={"enabled": enabled},
status=status,
)
@pytest.fixture
def world(client, db, monkeypatch):
"""Ada owns the room and a case with a Paperless document. Ben is a member, Cem a reader, Dan outside."""
calls = []
def fake_file(base, token, path, max_bytes=40 * 1024 * 1024):
calls.append({"token": token, "path": path})
if path.endswith("/preview/"):
return (b"%PDF-1.4\nraum\n", "application/pdf", "vertrag.pdf")
return None
monkeypatch.setattr(sources, "_paperless_file", fake_file)
monkeypatch.setattr(sources, "_paperless_metadata", lambda *args, **kwargs: None)
actors = {
"ada": _actor(client, db, "ada", "ada-rq@example.test", main=True),
"ben": _actor(client, db, "ben", "ben-rq@example.test"),
"cem": _actor(client, db, "cem", "cem-rq@example.test"),
"dan": _actor(client, db, "dan", "dan-rq@example.test"),
}
ada = actors["ada"]
room = ada.request("POST", "/api/v1/rooms", json={"name": "Mandat"}, status=201)["id"]
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": actors["ben"].email, "role": "member"})
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": actors["cem"].email, "role": "reader"})
ada.use_room(room)
actors["cem"].use_room(room)
actors["ben"].use_room(room)
paper = ada.request(
"POST",
"/api/v1/connectors",
json={"kind": "paperless", "name": "Ada Archiv", "base_url": "https://paper.example.test", "token": OWNER_TOKEN},
status=201,
)["id"]
case = ada.request("POST", "/api/v1/cases", json={"title": "Mandatsakte"}, status=201)
document = ada.request(
"POST",
"/api/v1/external-refs",
json={
"title": "Vertrag",
"source": "paperless",
"external_id": "15",
"context": {"kind": "case", "id": case["id"]},
"detail": {"connector_id": paper},
},
status=201,
)
actors.update(
room=room,
case=case["id"],
path=f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}",
calls=calls,
ids={key: _id(db, actors[key].email) for key in ("ada", "ben", "cem", "dan")},
)
return actors
def test_a_room_reader_reads_originals_only_after_the_owner_lends_them(world, db):
ada, cem, room, ids, calls = world["ada"], world["cem"], world["room"], world["ids"], world["calls"]
assert cem.request("GET", f"/api/v1/cases/{world['case']}")["rights"]["read"] is True
refused = _raw(cem, world["path"])
assert refused.status_code == 422
assert refused.json()["detail"] == UNAVAILABLE
assert calls == []
_lend(ada, room, ids["cem"], True)
members = ada.request("GET", f"/api/v1/rooms/{room}/members")["items"]
flags = {item["subject_id"]: item["my_sources"] for item in members}
assert flags[ids["cem"]] is True
assert flags[ids["ben"]] is False
share = ada.request("GET", f"/api/v1/cases/{world['case']}/room-share")
shown = {item["subject_id"]: item["sources"] for item in share["shares"][0]["members"]}
assert shown[ids["cem"]] is True
opened = _raw(cem, world["path"])
assert opened.status_code == 200, opened.text
assert opened.content.startswith(b"%PDF")
assert calls == [{"token": OWNER_TOKEN, "path": "/api/documents/15/preview/"}]
assert OWNER_TOKEN not in json.dumps(cem.request("GET", f"/api/v1/cases/{world['case']}"))
events = db.execute(
"SELECT result FROM domain_events WHERE action = 'source_read_mediated' AND actor_subject_id = %s",
(ids["cem"],),
).fetchall()
db.rollback()
assert [row["result"] for row in events] == ["ok"]
_lend(ada, room, ids["cem"], False)
assert _raw(cem, world["path"]).status_code == 422
def test_only_the_lending_person_decides_and_only_for_members(world):
ada, ben, cem, dan, room, ids = world["ada"], world["ben"], world["cem"], world["dan"], world["room"], world["ids"]
# Ben lends his own connectors to Cem. That does not open Ada's originals.
_lend(ben, room, ids["cem"], True)
assert _raw(cem, world["path"]).status_code == 422
# A reader cannot share into the room and so cannot lend.
_lend(cem, room, ids["ben"], True, status=403)
# Outsiders and non-members are not addressable.
_lend(dan, room, ids["cem"], True, status=404)
_lend(ada, room, ids["dan"], True, status=404)
_lend(ada, room, ids["ada"], True, status=422)
def test_exclusion_leaving_the_room_and_ending_the_share_close_the_access(world):
ada, cem, room, ids = world["ada"], world["cem"], world["room"], world["ids"]
_lend(ada, room, ids["cem"], True)
assert _raw(cem, world["path"]).status_code == 200
ada.request("PUT", f"/api/v1/cases/{world['case']}/room-share/people/{ids['cem']}", json={"excluded": True})
assert _raw(cem, world["path"]).status_code == 404
ada.request("PUT", f"/api/v1/cases/{world['case']}/room-share/people/{ids['cem']}", json={"excluded": False})
assert _raw(cem, world["path"]).status_code == 200
ada.request("DELETE", f"/api/v1/cases/{world['case']}/room-share/rooms/{room}", status=204)
assert _raw(cem, world["path"]).status_code == 404
ada.request("PUT", f"/api/v1/cases/{world['case']}/room-share/rooms/{room}", json={"access": "read"})
assert _raw(cem, world["path"]).status_code == 200
ada.request("DELETE", f"/api/v1/rooms/{room}/members/{ids['cem']}", status=204)
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": cem.email, "role": "reader"})
cem.use_room(room)
assert _raw(cem, world["path"]).status_code == 422
flags = {item["subject_id"]: item["my_sources"] for item in ada.request("GET", f"/api/v1/rooms/{room}/members")["items"]}
assert flags[ids["cem"]] is False