Compare commits
108
Commits
2558239bfd
..
V1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
363ecdfd0a | ||
|
|
4bd2d047f5 | ||
|
|
f925661937 | ||
|
|
a6dc24d8fe | ||
|
|
bee48bf4a5 | ||
|
|
6e1b0916a6 | ||
|
|
ffdaf1c721 | ||
|
|
0f2b7a8fab | ||
|
|
38406d3293 | ||
|
|
2f7de33049 | ||
|
|
5e32ba547d | ||
|
|
f580fb282d | ||
|
|
9089d830b3 | ||
|
|
4327f5a434 | ||
|
|
e2475555c0 | ||
|
|
7a1206b18c | ||
|
|
cd239a3ab8 | ||
|
|
d0f09830bb | ||
|
|
a3f328832e | ||
|
|
075525ee17 | ||
|
|
0a5daf6713 | ||
|
|
1d3c938def | ||
|
|
07e46c77f1 | ||
|
|
7b2d0c298e | ||
|
|
5f60e1fe40 | ||
|
|
322ad491c1 | ||
|
|
64dce6c20c | ||
|
|
d39c7d7999 | ||
|
|
30b6544514 | ||
|
|
1765714ccd | ||
|
|
1a2c959309 | ||
|
|
6d7b7c5f85 | ||
|
|
e47f50d513 | ||
|
|
ac3c3d81fe | ||
|
|
21c2d05fb8 | ||
|
|
1c2f045e7d | ||
|
|
037c0724a8 | ||
|
|
eb58dce4cd | ||
|
|
c29bd29f34 | ||
|
|
34c4084a7c | ||
|
|
7e39fbb2bd | ||
|
|
c3a07cee64 | ||
|
|
d6b70d8f92 | ||
|
|
75a3949f7c | ||
|
|
562c0848b1 | ||
|
|
79241831fd | ||
|
|
2b100eb934 | ||
|
|
3bfd641b9b | ||
|
|
5905df6c17 | ||
|
|
60a76803e1 | ||
|
|
59434a4045 | ||
|
|
97401a6d84 | ||
|
|
ea28c4f246 | ||
|
|
8b74e63417 | ||
|
|
2b23992a1a | ||
|
|
5b23e4aab0 | ||
|
|
a5350bc76e | ||
|
|
e3274bce21 | ||
|
|
0c611763c3 | ||
|
|
430108823c | ||
|
|
3f60901b71 | ||
|
|
9b9a09b97c | ||
|
|
f8cb9f8d4b | ||
|
|
20fa183c1c | ||
|
|
7e8a3e865e | ||
|
|
7846830765 | ||
|
|
9f5327f3be | ||
|
|
be027a1025 | ||
|
|
c774fb7206 | ||
|
|
c138df5e68 | ||
|
|
3c190c87b4 | ||
|
|
f21c64a944 | ||
|
|
deb5d662fe | ||
|
|
cbd45a8997 | ||
|
|
db4063296b | ||
|
|
339238ce21 | ||
|
|
e4380261fc | ||
|
|
eeeb81148a | ||
|
|
060d99bda0 | ||
|
|
95381030bc | ||
|
|
2664021e7f | ||
|
|
f0c8981e22 | ||
|
|
f6f8d5980c | ||
|
|
27cde035e8 | ||
|
|
7626c56f3d | ||
|
|
17a3b3a736 | ||
|
|
ad6240a5da | ||
|
|
20625b4596 | ||
|
|
f27df3ff35 | ||
|
|
97bffc6175 | ||
|
|
dc8a9c2db6 | ||
|
|
448e9a06ff | ||
|
|
94ef46d8eb | ||
|
|
1621a7eb2f | ||
|
|
7ef73ad500 | ||
|
|
cafa4e8b92 | ||
|
|
67d48378c9 | ||
|
|
3465ed57f6 | ||
|
|
52bda91aad | ||
|
|
27925093e2 | ||
|
|
0924e28fce | ||
|
|
b328385561 | ||
|
|
4420790707 | ||
|
|
528fc191e8 | ||
|
|
871c7d3ad5 | ||
|
|
0108a296bc | ||
|
|
b03f571cd8 | ||
|
|
332be8376e |
No files matched your search
@@ -0,0 +1,113 @@
|
||||
name: Test Suite
|
||||
|
||||
# One run per push. The deploy starts at the same time and updates the checkout this suite tests,
|
||||
# so the jobs wait until that checkout contains the pushed commit. A workflow_run trigger
|
||||
# (after the deploy) did not start reliably on this Gitea, see git log of this file.
|
||||
on:
|
||||
push:
|
||||
branches: [develop]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
pytest-backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: pytest against Dev Postgres (tsumugu_test)
|
||||
run: |
|
||||
set -e
|
||||
APP_DIR="/home/lars/docker/tsumugu-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
echo "pytest uses Dev Postgres (${APP_DIR}); event=${{ github.event_name }}"
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
for i in $(seq 1 180); do
|
||||
if git -c safe.directory='*' -C "$APP_DIR" merge-base --is-ancestor "${{ github.sha }}" HEAD 2>/dev/null; then
|
||||
echo "Dev checkout contains ${{ github.sha }} (attempt $i)"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq 180 ]; then
|
||||
echo "the deploy did not reach ${{ github.sha }} within 15 minutes"
|
||||
exit 1
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
fi
|
||||
cd "$APP_DIR"
|
||||
for i in $(seq 1 60); do
|
||||
if [ -f "$APP_DIR/backend/pytest.ini" ] && docker compose -f "$COMPOSE_FILE" exec -T backend true 2>/dev/null; then
|
||||
echo "backend and pytest.ini ready (attempt $i)"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq 60 ]; then
|
||||
echo "timeout waiting for Dev checkout/backend"
|
||||
docker compose -f "$COMPOSE_FILE" ps || true
|
||||
ls -la "$APP_DIR/backend" || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
PGUSER="$(docker compose -f "$COMPOSE_FILE" exec -T postgres printenv POSTGRES_USER | tr -d '\r')"
|
||||
echo "test database tsumugu_test on the existing Dev Postgres (owner ${PGUSER})"
|
||||
docker compose -f "$COMPOSE_FILE" exec -T postgres \
|
||||
psql -U "$PGUSER" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'tsumugu_test' AND pid <> pg_backend_pid();"
|
||||
docker compose -f "$COMPOSE_FILE" exec -T postgres \
|
||||
psql -U "$PGUSER" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "DROP DATABASE IF EXISTS tsumugu_test;"
|
||||
docker compose -f "$COMPOSE_FILE" exec -T postgres \
|
||||
psql -U "$PGUSER" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "CREATE DATABASE tsumugu_test OWNER ${PGUSER};"
|
||||
docker compose -f "$COMPOSE_FILE" run --rm --no-deps \
|
||||
-v "${APP_DIR}:/src:ro" \
|
||||
-w /src/backend \
|
||||
-e DB_NAME=tsumugu_test \
|
||||
-e SEED_DEMO=false \
|
||||
-e PYTHONUTF8=1 \
|
||||
backend sh -lc '
|
||||
set -e
|
||||
export DB_NAME=tsumugu_test
|
||||
export SEED_DEMO=false
|
||||
pip install -q -r requirements-dev.txt
|
||||
python -m pytest tests -ra --tb=short
|
||||
'
|
||||
|
||||
smoke-dev:
|
||||
# After pytest, so the deploy that started with the push has normally finished. The health check retries.
|
||||
needs: pytest-backend
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Non-destructive smoke against the running Dev app
|
||||
run: |
|
||||
set -e
|
||||
echo "live Dev API (tsumugu_dev), read-only health"
|
||||
for url in http://localhost:8094/api/health http://localhost:3094/api/health; do
|
||||
for i in $(seq 1 30); do
|
||||
if curl -sf "$url"; then echo; break; fi
|
||||
if [ "$i" -eq 30 ]; then echo "no health answer from $url"; exit 1; fi
|
||||
sleep 10
|
||||
done
|
||||
done
|
||||
echo "LAN smoke OK. Public URL after TLS: https://dev.tsumugu.jinkendo.de"
|
||||
|
||||
frontend-build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Frontend production build on Dev checkout
|
||||
run: |
|
||||
set -e
|
||||
APP_DIR="/home/lars/docker/tsumugu-dev"
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
for i in $(seq 1 180); do
|
||||
if git -c safe.directory='*' -C "$APP_DIR" merge-base --is-ancestor "${{ github.sha }}" HEAD 2>/dev/null; then
|
||||
echo "Dev checkout contains ${{ github.sha }} (attempt $i)"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq 180 ]; then
|
||||
echo "the deploy did not reach ${{ github.sha }} within 15 minutes"
|
||||
exit 1
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
fi
|
||||
cd "$APP_DIR/frontend"
|
||||
npm ci
|
||||
npm run build
|
||||
@@ -43,3 +43,6 @@ tmp/
|
||||
temp/
|
||||
data/local/
|
||||
*.db
|
||||
backend/data/
|
||||
backend/.pytest-tmp/
|
||||
backend/.pytest-export-tmp/
|
||||
@@ -4,4 +4,4 @@ Fachlich führend ist `docs/product/TSUMUGU_PRODUCT_SPEC.md`. Der technische Ent
|
||||
|
||||
Deployment und Ports: `docs/DEPLOYMENT.md`. Gearbeitet wird auf `develop`. Ein Push dorthin startet das Development-Deploy auf dem Raspberry Pi. Production entsteht nur durch einen Merge nach `main`.
|
||||
|
||||
Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und externer Anwaltszugang gehören nicht in diese Lieferung.
|
||||
Die Anwendung bleibt produktlokal: FastAPI, PostgreSQL, React. Keine gemeinsame Fachdatenbank mit anderen Jinkendo-Anwendungen. Finanzfunktionen, Paperless-Abgleich, KI und ein Anwaltszugang ohne eigenes Konto gehören nicht in diese Lieferung. Eine berechtigte Person mit Konto kann freigegebene verknüpfte Dokumente und E-Mails über die Zugänge des Owners lesen, ohne eigene Paperless- oder IMAP-Verbindungen.
|
||||
@@ -6,9 +6,9 @@ Remote: `http://192.168.2.144:3000/Lars/tsumugu.git`
|
||||
|
||||
## Stand
|
||||
|
||||
Die erste benutzbare Lieferung organisiert und verfolgt: Anmeldung, Datenräume, Akten und Vorgänge, Notizen, Dateien, manuelle Paperless-Referenzen, Chronologie, Aufgaben und unabhängige Fristen. Finanzfunktionen, automatische Paperless-Synchronisation, KI und externer Anwaltszugang folgen später.
|
||||
Die erste benutzbare Lieferung organisiert und verfolgt: Anmeldung, Datenräume, Akten und Vorgänge, Notizen, Dateien, manuelle Paperless-Referenzen, Chronologie, Aufgaben und unabhängige Fristen. Seitdem hinzugekommen: Paperless- und IMAP-Zugänge mit Auswahl und Vorschau, Antwortbezüge zwischen Unterlagen, Kommunikationsrichtung je Einbindung, Unterkapitel und das Übergabepaket als ZIP. Finanzfunktionen, automatische Paperless-Synchronisation, virtuelle Zusammenstellungen, KI und laufender Anwaltszugang folgen später.
|
||||
|
||||
Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nach `main` die Produktion. Der Gitea-Runner auf dem Raspberry Pi (`192.168.2.49`) übernimmt Build und Deploy. Beim Start führt das Backend die Migrationen aus. In Development legt es synthetische Beispieldaten an, in Production nicht.
|
||||
Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nach `main` die Produktion. Der Gitea-Runner auf dem Raspberry Pi (`192.168.2.49`) übernimmt Build und Deploy. Beim Start führt das Backend die Migrationen aus und entfernt Konten mit Herkunft `fixture`. Synthetische Beispieldaten entstehen in keiner Umgebung automatisch, nur in der Test-Suite auf einer Datenbank `*_test`.
|
||||
|
||||
| | Development | Production |
|
||||
|---|---|---|
|
||||
@@ -19,11 +19,12 @@ Ein Push auf `develop` baut und startet Development, ein Merge von `develop` nac
|
||||
|
||||
Details, Ports und der Synology-Reverse-Proxy: `docs/DEPLOYMENT.md`.
|
||||
|
||||
Development ist nach dem Deploy unter https://dev.tsumugu.jinkendo.de oder http://192.168.2.49:3094 erreichbar. Die Beispielkonten stehen auf der Anmeldeseite:
|
||||
Development ist nach dem Deploy unter https://dev.tsumugu.jinkendo.de oder http://192.168.2.49:3094 erreichbar. Auf einer leeren Datenbank bietet die Anmeldeseite einmalig das Anlegen des Betreiberkontos an; der Betreiber legt danach weitere Konten unter „Verwaltung → Nutzer“ an.
|
||||
|
||||
| | E-Mail | Passwort |
|
||||
|---|---|---|
|
||||
| Ada Beispiel | ada@example.test | Beispiel-Ada-2026 |
|
||||
| Ben Beispiel | ben@example.test | Beispiel-Ben-2026 |
|
||||
Die synthetischen Beispielkonten „Ada Beispiel“ (`ada@example.test`) und „Ben Beispiel“ (`ben@example.test`) mit dem Mietstreit Musterstraße legt nur die Test-Suite an (`backend/app/seed.py`). Die Anmeldeseite zeigt sie ausschließlich in Development mit einer Datenbank `*_test` und `SEED_DEMO=true`. Auf `tsumugu_dev` und `tsumugu` gibt es sie nicht; der Start entfernt sie dort.
|
||||
|
||||
Ada führt den Mietstreit Musterstraße. Ben darf diesen Kontext bearbeiten und sieht die private Verhandlungsstrategie nicht. Vorläufige Rechte- und Löschannahmen: `docs/MVP_ANNAHMEN.md`. `/api/health` prüft weiterhin nur, ob die Anwendung und die Datenbank antworten.
|
||||
Vorläufige Rechte- und Löschannahmen: `docs/MVP_ANNAHMEN.md`. `/api/health` prüft weiterhin nur, ob die Anwendung und die Datenbank antworten.
|
||||
|
||||
## Dokumentation
|
||||
|
||||
Übersicht aller Dokumente: [docs/README.md](docs/README.md). Lokaler Start und Tests: [docs/ENTWICKLUNG_UND_TESTS.md](docs/ENTWICKLUNG_UND_TESTS.md). Letztes Code-Review: [docs/review/](docs/review/README.md).
|
||||
@@ -0,0 +1,26 @@
|
||||
"""The one place where subscription limits will be checked.
|
||||
|
||||
Today there are no limits. The checks are called where a limit will matter, so that a plan
|
||||
can be added without touching the callers.
|
||||
|
||||
Target model (see the entitlements blueprint): the quota subject is the owner of a room, a main
|
||||
user, like the club at Shinkan. A plan, set by the operator, may later cap the number of active
|
||||
employees per main user and per room. The count comes from the database, never from the client.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
def ensure_can_create_room(conn, owner_id: UUID) -> None:
|
||||
"""Called before a main user creates a room."""
|
||||
del conn, owner_id
|
||||
|
||||
|
||||
def ensure_can_add_member(conn, owner_id: UUID, room_id: UUID) -> None:
|
||||
"""Called before a person becomes an active member of a room or is invited to it.
|
||||
|
||||
``owner_id`` is the owner of the room, the future quota subject.
|
||||
"""
|
||||
del conn, owner_id, room_id
|
||||
@@ -11,6 +11,8 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.core.errors import conflict, forbidden, not_found, unprocessable
|
||||
|
||||
SHARED_NOTICE = "Diese Änderung betrifft den gemeinsamen Inhalt der Notiz."
|
||||
@@ -22,30 +24,52 @@ 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(
|
||||
self.read or other.read,
|
||||
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.
|
||||
# Sharing, deleting and ownership never come from a room role. An unknown role gets nothing.
|
||||
ROOM_RIGHTS = {
|
||||
"reader": Rights(read=True),
|
||||
"member": Rights(read=True, edit=True),
|
||||
"manager": Rights(read=True, edit=True),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -87,14 +111,17 @@ def audit(
|
||||
resource_id: UUID,
|
||||
context: Ctx | None = None,
|
||||
occurred_on=None,
|
||||
*,
|
||||
result: str = "ok",
|
||||
detail: dict | None = None,
|
||||
) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO domain_events (
|
||||
actor_subject_id, scope_id, action, resource_kind, resource_id,
|
||||
context_kind, context_id, occurred_on
|
||||
context_kind, context_id, occurred_on, result, detail
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
actor_id,
|
||||
@@ -105,6 +132,8 @@ def audit(
|
||||
context.kind if context else None,
|
||||
context.id if context else None,
|
||||
occurred_on,
|
||||
result,
|
||||
Json(detail) if detail is not None else None,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -182,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:
|
||||
@@ -216,6 +263,37 @@ def _exceptions(conn, actor: UUID, kind: str, resource_id: UUID, context: Ctx |
|
||||
return blocked
|
||||
|
||||
|
||||
def room_default(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights:
|
||||
"""Rights of the current members of the rooms a case or matter is shared with.
|
||||
|
||||
A room is a team. The rights of one share are the role of the person in that room,
|
||||
capped by the share (`read` or `edit`). Several shares add up. Only an active room,
|
||||
an active membership and an active account count. Anything unclear gives no rights.
|
||||
"""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
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'
|
||||
JOIN auth_accounts a ON a.id = m.subject_id AND a.status = 'active'
|
||||
WHERE s.resource_kind = %s AND s.resource_id = %s
|
||||
""",
|
||||
(actor, kind, resource_id),
|
||||
).fetchall()
|
||||
result = Rights()
|
||||
for row in rows:
|
||||
rights = ROOM_RIGHTS.get(row["role"], Rights())
|
||||
if row["access"] == "read":
|
||||
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
|
||||
|
||||
|
||||
def case_rights(conn, actor: UUID, case: dict) -> Rights:
|
||||
if case["parent_case_id"] is not None and case["rights_mode"] == "inherit_parent":
|
||||
parent = get_case(conn, case["parent_case_id"])
|
||||
@@ -223,7 +301,7 @@ def case_rights(conn, actor: UUID, case: dict) -> Rights:
|
||||
elif case["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
else:
|
||||
base = _direct_grant(conn, actor, "case", case["id"])
|
||||
base = _direct_grant(conn, actor, "case", case["id"]).union(room_default(conn, actor, "case", case["id"]))
|
||||
return base.without(_exceptions(conn, actor, "case", case["id"], None))
|
||||
|
||||
|
||||
@@ -237,7 +315,10 @@ def _linked(conn, matter_id: UUID, case_id: UUID) -> bool:
|
||||
|
||||
def matter_rights(conn, actor: UUID, matter: dict, context: Ctx | None) -> Rights:
|
||||
if context is None:
|
||||
base = Rights.full() if matter["owner_subject_id"] == actor else _direct_grant(conn, actor, "matter", matter["id"])
|
||||
if matter["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
else:
|
||||
base = _direct_grant(conn, actor, "matter", matter["id"]).union(room_default(conn, actor, "matter", matter["id"]))
|
||||
return base.without(_exceptions(conn, actor, "matter", matter["id"], None))
|
||||
|
||||
if context.kind == "case":
|
||||
@@ -348,6 +429,59 @@ def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool:
|
||||
return bool(matter and matter["parent_matter_id"] == parent_id)
|
||||
|
||||
|
||||
def _rights_bearing_case(conn, case: dict) -> dict:
|
||||
seen: set[UUID] = set()
|
||||
current = case
|
||||
while current["parent_case_id"] is not None and current["rights_mode"] == "inherit_parent":
|
||||
if current["id"] in seen:
|
||||
break
|
||||
seen.add(current["id"])
|
||||
parent = get_case(conn, current["parent_case_id"])
|
||||
if parent is None:
|
||||
break
|
||||
current = parent
|
||||
return current
|
||||
|
||||
|
||||
def _source_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> dict | None:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT can_read, use_owner_sources
|
||||
FROM access_grants
|
||||
WHERE NOT is_exception
|
||||
AND grantee_subject_id = %s
|
||||
AND resource_kind = %s
|
||||
AND resource_id = %s
|
||||
AND context_kind IS NULL
|
||||
""",
|
||||
(actor, kind, resource_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def mediated_source_owner(conn, actor: UUID, element: dict, context: Ctx | None) -> UUID | None:
|
||||
"""Owner whose stored connector may serve this reader. None unless the grant allows it."""
|
||||
if context is None or not element_rights(conn, actor, element, context).read:
|
||||
return None
|
||||
if context.kind == "case":
|
||||
resource = get_case(conn, context.id)
|
||||
if resource is None:
|
||||
return None
|
||||
resource = _rights_bearing_case(conn, resource)
|
||||
grant = _source_grant(conn, actor, "case", resource["id"])
|
||||
elif context.kind == "matter":
|
||||
resource = get_matter(conn, context.id)
|
||||
if resource is None:
|
||||
return None
|
||||
grant = _source_grant(conn, actor, "matter", resource["id"])
|
||||
else:
|
||||
return None
|
||||
if resource["owner_subject_id"] == actor:
|
||||
return None
|
||||
if grant is None or not grant["can_read"] or not grant["use_owner_sources"]:
|
||||
return None
|
||||
return resource["owner_subject_id"]
|
||||
|
||||
|
||||
def element_rights_via_case_or_direct(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
|
||||
"""Rights for an element bound to a matter when the caller names a case path.
|
||||
|
||||
@@ -511,6 +645,12 @@ def list_cases(conn, actor: UUID) -> list[dict]:
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read
|
||||
AND g.context_id IS NULL
|
||||
)
|
||||
OR (EXISTS (
|
||||
SELECT 1 FROM room_shares sh
|
||||
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
|
||||
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
|
||||
WHERE sh.resource_kind = 'case' AND sh.resource_id = c.id
|
||||
))
|
||||
OR (
|
||||
c.rights_mode = 'inherit_parent' AND c.parent_case_id IS NOT NULL AND EXISTS (
|
||||
SELECT 1 FROM cases p
|
||||
@@ -523,6 +663,12 @@ def list_cases(conn, actor: UUID) -> list[dict]:
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception
|
||||
AND g.can_read AND g.context_id IS NULL
|
||||
)
|
||||
OR (EXISTS (
|
||||
SELECT 1 FROM room_shares sh
|
||||
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
|
||||
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
|
||||
WHERE sh.resource_kind = 'case' AND sh.resource_id = p.id
|
||||
))
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -553,6 +699,12 @@ def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]:
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception AND g.can_read
|
||||
AND g.context_id IS NULL
|
||||
)
|
||||
OR (EXISTS (
|
||||
SELECT 1 FROM room_shares sh
|
||||
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
|
||||
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
|
||||
WHERE sh.resource_kind = 'matter' AND sh.resource_id = m.id
|
||||
))
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
|
||||
@@ -565,6 +717,12 @@ def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]:
|
||||
AND g.grantee_subject_id = %(actor)s AND NOT g.is_exception
|
||||
AND g.can_read AND g.context_id IS NULL
|
||||
)
|
||||
OR (EXISTS (
|
||||
SELECT 1 FROM room_shares sh
|
||||
JOIN room_memberships sm ON sm.room_id = sh.room_id AND sm.subject_id = %(actor)s AND sm.status = 'active'
|
||||
JOIN data_rooms sr ON sr.id = sh.room_id AND sr.kind = 'organization' AND sr.status = 'active'
|
||||
WHERE sh.resource_kind = 'case' AND sh.resource_id = c.id
|
||||
))
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -652,6 +810,7 @@ def visible_bindings_for_element(conn, actor: UUID, element: dict) -> list[dict]
|
||||
"context_kind": binding["context_kind"],
|
||||
"context_id": str(binding["context_id"]),
|
||||
"context_title": title,
|
||||
"chapter_id": str(binding["chapter_id"]) if binding.get("chapter_id") else None,
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Fixed role bundles. Rights are read from the current database state, never from the session.
|
||||
|
||||
Platform: operator or user. Data room: member, manager or reader. There is no role editor.
|
||||
An operator has no read right on content. Unknown role or status is refused.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import forbidden
|
||||
|
||||
ROOM_ROLES = ("member", "manager", "reader")
|
||||
|
||||
ROOM_ROLE_LABELS = {
|
||||
"member": "Mitglied",
|
||||
"manager": "Verwalter",
|
||||
"reader": "Leser",
|
||||
}
|
||||
|
||||
|
||||
def account_kind(conn, account_id: UUID) -> str | None:
|
||||
row = conn.execute("SELECT account_kind FROM auth_accounts WHERE id = %s AND status = 'active'", (account_id,)).fetchone()
|
||||
return row["account_kind"] if row else None
|
||||
|
||||
|
||||
def require_main_user(conn, account_id: UUID) -> None:
|
||||
"""Employees work in the rooms they were invited to. They create no rooms of their own."""
|
||||
if account_kind(conn, account_id) != "main":
|
||||
raise forbidden("Als Mitarbeiter arbeitest du in den Räumen, in die du eingeladen wurdest.")
|
||||
|
||||
|
||||
def is_operator(conn, account_id: UUID) -> bool:
|
||||
row = conn.execute(
|
||||
"SELECT is_superadmin FROM auth_accounts WHERE id = %s AND status = 'active'",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
return bool(row and row["is_superadmin"])
|
||||
|
||||
|
||||
def require_operator(conn, account_id: UUID) -> None:
|
||||
if not is_operator(conn, account_id):
|
||||
raise forbidden("Das darf nur der Betreiber.")
|
||||
|
||||
|
||||
def room_role(conn, account_id: UUID, room_id: UUID) -> str | None:
|
||||
"""The active role of an account in an organization room, or None."""
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT m.role
|
||||
FROM room_memberships m
|
||||
JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.room_id = %s AND m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization'
|
||||
""",
|
||||
(room_id, account_id),
|
||||
).fetchone()
|
||||
if row is None or row["role"] not in ROOM_ROLES:
|
||||
return None
|
||||
return row["role"]
|
||||
|
||||
|
||||
def require_room_manager(conn, account_id: UUID, room_id: UUID) -> None:
|
||||
if room_role(conn, account_id, room_id) != "manager":
|
||||
raise forbidden("Das darf nur ein Verwalter dieses Datenraums.")
|
||||
|
||||
|
||||
def require_room_write(conn, account_id: UUID, room: dict) -> None:
|
||||
"""Creating content needs the own personal room or a member or manager role."""
|
||||
if room["kind"] == "personal":
|
||||
if room["id"] != account_id:
|
||||
raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.")
|
||||
require_main_user(conn, account_id)
|
||||
return
|
||||
role = room_role(conn, account_id, room["id"])
|
||||
if role in {"member", "manager"}:
|
||||
return
|
||||
if role == "reader":
|
||||
raise forbidden("Als Leser kannst du in diesem Datenraum nichts anlegen.")
|
||||
raise forbidden("Du bist in diesem Datenraum nicht Mitglied.")
|
||||
|
||||
|
||||
def count_active_operators(conn, *, lock: bool = False) -> int:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
rows = conn.execute(f"SELECT id FROM auth_accounts WHERE is_superadmin AND status = 'active'{suffix}").fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def count_active_managers(conn, room_id: UUID, *, lock: bool = False) -> int:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
SELECT m.subject_id FROM room_memberships m
|
||||
JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = %s AND m.role = 'manager' AND m.status = 'active' AND a.status = 'active'{suffix}
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ensure_can_create(conn, account_id: UUID, scope_id: UUID) -> None:
|
||||
"""Gate for every operation that creates content with this home room."""
|
||||
room = conn.execute("SELECT id, kind FROM data_rooms WHERE id = %s", (scope_id,)).fetchone()
|
||||
if room is None:
|
||||
raise forbidden("Der gewählte Datenraum ist nicht verfügbar.")
|
||||
require_room_write(conn, account_id, room)
|
||||
@@ -0,0 +1,273 @@
|
||||
"""Account administration for the operator and the own account (password, sessions)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import audit
|
||||
from app.access.roles import require_operator
|
||||
from app.api.deps import Principal, get_conn, get_principal, get_session
|
||||
from app.api.schemas import AccountIn, AccountPatchIn, PasswordChangeIn
|
||||
from app.auth.accounts import (
|
||||
promote_to_main,
|
||||
change_own_password,
|
||||
create_account,
|
||||
generate_password,
|
||||
reset_password,
|
||||
revoke_sessions,
|
||||
set_display_name,
|
||||
set_operator,
|
||||
set_status,
|
||||
)
|
||||
from app.core.errors import not_found, unprocessable
|
||||
from app.core.timeutil import dump_dt
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
def _account_item(row) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"is_superadmin": row["is_superadmin"],
|
||||
"status": row["status"],
|
||||
"must_change_password": row["must_change_password"],
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
"last_login_at": dump_dt(row["last_login_at"]),
|
||||
"account_kind": row["account_kind"],
|
||||
"sponsor_id": str(row["sponsor_id"]) if row["sponsor_id"] else None,
|
||||
"sponsor_name": row.get("sponsor_name"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts")
|
||||
def accounts(
|
||||
status: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
if status not in {None, "active", "disabled"}:
|
||||
raise unprocessable("Der Statusfilter ist ungültig.")
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at,
|
||||
account_kind, sponsor_id,
|
||||
(SELECT s.display_name FROM auth_accounts s WHERE s.id = auth_accounts.sponsor_id) AS sponsor_name
|
||||
FROM auth_accounts
|
||||
WHERE origin = 'operator' AND (%s::text IS NULL OR status = %s::text)
|
||||
ORDER BY status, display_name, email
|
||||
""",
|
||||
(status, status),
|
||||
).fetchall()
|
||||
return {"items": [_account_item(row) for row in rows], "next_cursor": None}
|
||||
|
||||
|
||||
@router.get("/api/v1/accounts/{account_id}")
|
||||
def account_detail(account_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_operator(conn, principal.account_id)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at,
|
||||
account_kind, sponsor_id,
|
||||
(SELECT s.display_name FROM auth_accounts s WHERE s.id = auth_accounts.sponsor_id) AS sponsor_name
|
||||
FROM auth_accounts WHERE id = %s AND origin = 'operator'
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
rooms = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, r.status, m.role
|
||||
FROM room_memberships m
|
||||
JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
sessions = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM auth_sessions
|
||||
WHERE account_id = %s AND revoked_at IS NULL AND expires_at > now()
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
body = _account_item(row)
|
||||
body["rooms"] = [
|
||||
{"id": str(room["id"]), "name": room["name"], "status": room["status"], "role": room["role"]} for room in rooms
|
||||
]
|
||||
body["active_sessions"] = sessions["n"]
|
||||
employees = conn.execute(
|
||||
"""
|
||||
SELECT id, display_name, email, status FROM auth_accounts
|
||||
WHERE sponsor_id = %s ORDER BY display_name, id
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
body["employees"] = [
|
||||
{"id": str(e["id"]), "display_name": e["display_name"], "email": e["email"], "status": e["status"]} for e in employees
|
||||
]
|
||||
return JSONResponse(body, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts")
|
||||
def post_account(body: AccountIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_operator(conn, principal.account_id)
|
||||
password = body.password or generate_password()
|
||||
account = create_account(
|
||||
conn,
|
||||
body.email,
|
||||
body.display_name,
|
||||
password,
|
||||
is_superadmin=body.is_operator,
|
||||
must_change_password=True,
|
||||
)
|
||||
audit(conn, principal.account_id, None, "account_created", "account", account["id"])
|
||||
if body.is_operator:
|
||||
audit(conn, principal.account_id, None, "operator_granted", "account", account["id"])
|
||||
payload = {
|
||||
"id": str(account["id"]),
|
||||
"email": account["email"],
|
||||
"display_name": account["display_name"],
|
||||
"is_superadmin": account["is_superadmin"],
|
||||
"status": account["status"],
|
||||
"must_change_password": True,
|
||||
"account_kind": account["account_kind"],
|
||||
}
|
||||
if not body.password:
|
||||
payload["temporary_password"] = password
|
||||
return JSONResponse(
|
||||
status_code=201,
|
||||
content=payload,
|
||||
headers={"Location": f"/api/v1/accounts/{account['id']}", **_NO_STORE},
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/api/v1/accounts/{account_id}")
|
||||
def patch_account(
|
||||
account_id: UUID,
|
||||
body: AccountPatchIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
exists = conn.execute("SELECT 1 FROM auth_accounts WHERE id = %s AND origin = 'operator'", (account_id,)).fetchone()
|
||||
if exists is None:
|
||||
raise not_found()
|
||||
if body.display_name is not None:
|
||||
set_display_name(conn, principal.account_id, account_id, body.display_name)
|
||||
if body.account_kind == "main":
|
||||
promote_to_main(conn, principal.account_id, account_id)
|
||||
if body.is_operator is not None:
|
||||
set_operator(conn, principal.account_id, account_id, body.is_operator)
|
||||
if body.status is not None:
|
||||
set_status(conn, principal.account_id, account_id, body.status)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, created_at, last_login_at,
|
||||
account_kind, sponsor_id,
|
||||
(SELECT s.display_name FROM auth_accounts s WHERE s.id = auth_accounts.sponsor_id) AS sponsor_name
|
||||
FROM auth_accounts WHERE id = %s
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
return _account_item(row)
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts/{account_id}/password-reset")
|
||||
def post_password_reset(
|
||||
account_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
password = reset_password(conn, principal.account_id, account_id)
|
||||
return JSONResponse({"temporary_password": password}, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.post("/api/v1/accounts/{account_id}/sessions/revoke")
|
||||
def post_revoke_sessions(
|
||||
account_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE id = %s", (account_id,)).fetchone() is None:
|
||||
raise not_found()
|
||||
count = revoke_sessions(conn, account_id)
|
||||
audit(conn, principal.account_id, None, "sessions_revoked", "account", account_id, detail={"count": count})
|
||||
return {"revoked": count}
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/password", status_code=204)
|
||||
def post_own_password(
|
||||
body: PasswordChangeIn,
|
||||
session: dict = Depends(get_session),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
change_own_password(conn, session["account_id"], session["id"], body.current_password, body.new_password)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/sessions")
|
||||
def own_sessions(session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, label, created_at, last_seen_at, expires_at
|
||||
FROM auth_sessions
|
||||
WHERE account_id = %s AND revoked_at IS NULL AND expires_at > now()
|
||||
ORDER BY created_at DESC, id
|
||||
""",
|
||||
(session["account_id"],),
|
||||
).fetchall()
|
||||
return JSONResponse(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"label": row["label"] or "Browser",
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
"last_seen_at": dump_dt(row["last_seen_at"]),
|
||||
"expires_at": dump_dt(row["expires_at"]),
|
||||
"current": row["id"] == session["id"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/{session_id}", status_code=204)
|
||||
def end_own_session(session_id: UUID, session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
if session_id == session["id"]:
|
||||
raise unprocessable("Diese Sitzung beendest du mit Abmelden.")
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions SET revoked_at = now()
|
||||
WHERE id = %s AND account_id = %s AND revoked_at IS NULL
|
||||
RETURNING id
|
||||
""",
|
||||
(session_id, session["account_id"]),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
audit(conn, session["account_id"], None, "session_ended", "session", session_id)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions/revoke-others")
|
||||
def end_other_sessions(session: dict = Depends(get_session), conn: Connection = Depends(get_conn)):
|
||||
count = revoke_sessions(conn, session["account_id"], keep=session["id"])
|
||||
audit(conn, session["account_id"], None, "sessions_revoked", "account", session["account_id"], detail={"count": count})
|
||||
return {"revoked": count}
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""HTTP for attachment roles, documented dispatches and secured editions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import Ctx
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import (
|
||||
AttachmentAssignIn,
|
||||
AttachmentDetachIn,
|
||||
AttachmentOrderIn,
|
||||
DispatchCorrectIn,
|
||||
DispatchEvidenceDetachIn,
|
||||
DispatchEvidenceIn,
|
||||
DispatchIn,
|
||||
FoldIn,
|
||||
)
|
||||
from app.correspondence import (
|
||||
GapNote,
|
||||
add_dispatch_evidence,
|
||||
assign_attachments,
|
||||
detach_dispatch_evidence,
|
||||
correct_dispatch,
|
||||
detach_attachment,
|
||||
dispatch_view,
|
||||
open_container,
|
||||
order_attachments,
|
||||
read_snapshot,
|
||||
record_dispatch,
|
||||
set_fold,
|
||||
)
|
||||
from app.core.errors import not_found
|
||||
from app.media.storage import content_disposition
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _ctx(value) -> Ctx:
|
||||
return Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
def _placement(value) -> Ctx | None:
|
||||
if value is None:
|
||||
return None
|
||||
return Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/attachments", status_code=201)
|
||||
def post_attachments(
|
||||
element_id: UUID,
|
||||
body: AttachmentAssignIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return assign_attachments(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.attachment_element_ids,
|
||||
body.fold,
|
||||
[],
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/attachments/order")
|
||||
def post_attachment_order(
|
||||
element_id: UUID,
|
||||
body: AttachmentOrderIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return order_attachments(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.attachment_element_ids,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/attachments/{attachment_id}/detach", status_code=204)
|
||||
def post_detach(
|
||||
element_id: UUID,
|
||||
attachment_id: UUID,
|
||||
body: AttachmentDetachIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
detach_attachment(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
attachment_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/api/v1/bindings/{binding_id}/fold")
|
||||
def patch_fold(
|
||||
binding_id: UUID,
|
||||
body: FoldIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return set_fold(
|
||||
conn,
|
||||
principal.account_id,
|
||||
binding_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.fold,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/elements/{element_id}/dispatches", status_code=201)
|
||||
def post_dispatch(
|
||||
element_id: UUID,
|
||||
body: DispatchIn,
|
||||
request: Request,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
request.state.cleanup_files = []
|
||||
return record_dispatch(
|
||||
conn,
|
||||
principal.account_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.channel,
|
||||
body.sent_on,
|
||||
body.counterpart,
|
||||
body.attachment_element_ids,
|
||||
[item.model_dump() for item in body.evidence],
|
||||
body.historical_gap,
|
||||
body.capture_editions,
|
||||
request.app.state.settings.media_root,
|
||||
request.state.cleanup_files,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/dispatches/{dispatch_id}/evidence", status_code=201)
|
||||
def post_evidence(
|
||||
dispatch_id: UUID,
|
||||
body: DispatchEvidenceIn,
|
||||
request: Request,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
request.state.cleanup_files = []
|
||||
return add_dispatch_evidence(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.element_id,
|
||||
body.role,
|
||||
body.fold,
|
||||
request.app.state.settings.media_root,
|
||||
request.state.cleanup_files,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/dispatches/{dispatch_id}/evidence/{element_id}/detach", status_code=204)
|
||||
def post_detach_evidence(
|
||||
dispatch_id: UUID,
|
||||
element_id: UUID,
|
||||
body: DispatchEvidenceDetachIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
detach_dispatch_evidence(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
element_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/dispatches/{dispatch_id}/correct")
|
||||
def post_correct(
|
||||
dispatch_id: UUID,
|
||||
body: DispatchCorrectIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return correct_dispatch(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
body.expected_version,
|
||||
_ctx(body.context),
|
||||
_placement(body.placement),
|
||||
body.channel,
|
||||
body.sent_on,
|
||||
body.clear_sent_on,
|
||||
body.counterpart,
|
||||
body.clear_counterpart,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/dispatches/{dispatch_id}")
|
||||
def get_dispatch(
|
||||
dispatch_id: UUID,
|
||||
context_kind: str,
|
||||
context_id: UUID,
|
||||
placement_kind: str | None = None,
|
||||
placement_id: UUID | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
context = Ctx(context_kind, context_id)
|
||||
placement = Ctx(placement_kind, placement_id) if placement_kind and placement_id else None
|
||||
_row, page, scope = open_container(conn, principal.account_id, context, placement, "read")
|
||||
return dispatch_view(conn, principal.account_id, dispatch_id, page, scope)
|
||||
|
||||
|
||||
@router.get("/api/v1/dispatches/{dispatch_id}/items/{item_id}/content")
|
||||
def get_dispatch_item(
|
||||
dispatch_id: UUID,
|
||||
item_id: UUID,
|
||||
context_kind: str,
|
||||
context_id: UUID,
|
||||
request: Request,
|
||||
placement_kind: str | None = None,
|
||||
placement_id: UUID | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
context = Ctx(context_kind, context_id)
|
||||
placement = Ctx(placement_kind, placement_id) if placement_kind and placement_id else None
|
||||
result = read_snapshot(
|
||||
conn,
|
||||
principal.account_id,
|
||||
dispatch_id,
|
||||
item_id,
|
||||
context,
|
||||
placement,
|
||||
request.app.state.settings.media_root,
|
||||
)
|
||||
if isinstance(result, GapNote):
|
||||
raise not_found()
|
||||
return Response(
|
||||
content=result.data,
|
||||
media_type=result.media_type or "application/octet-stream",
|
||||
headers={
|
||||
"Content-Disposition": content_disposition(result.filename),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
)
|
||||
+31
-6
@@ -2,8 +2,18 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def discard_stored(item) -> None:
|
||||
discard = getattr(item, "discard", None)
|
||||
if callable(discard):
|
||||
discard()
|
||||
return
|
||||
Path(item).unlink(missing_ok=True)
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, Request
|
||||
@@ -11,10 +21,19 @@ from psycopg import Connection
|
||||
|
||||
from app.access.policy import ensure_member_or_personal
|
||||
from app.auth.security import hash_secret, read_session_token
|
||||
from app.core.errors import forbidden, unauthorized
|
||||
from app.core.errors import forbidden, password_change_required, scope_changed, unauthorized
|
||||
from app.core.timeutil import utcnow
|
||||
|
||||
|
||||
# While a one-time password is set, only these routes answer.
|
||||
PASSWORD_CHANGE_PATHS = frozenset({
|
||||
"/api/v1/auth/session",
|
||||
"/api/v1/auth/password",
|
||||
"/api/v1/auth/logout",
|
||||
})
|
||||
SEEN_INTERVAL = timedelta(minutes=5)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Principal:
|
||||
account_id: UUID
|
||||
@@ -35,11 +54,11 @@ def get_conn(request: Request):
|
||||
yield conn
|
||||
conn.commit()
|
||||
for path in getattr(request.state, "delete_after_commit", []):
|
||||
Path(path).unlink(missing_ok=True)
|
||||
discard_stored(path)
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
for path in getattr(request.state, "cleanup_files", []):
|
||||
Path(path).unlink(missing_ok=True)
|
||||
discard_stored(path)
|
||||
raise
|
||||
|
||||
|
||||
@@ -50,7 +69,8 @@ def _session_row(conn: Connection, request: Request) -> dict:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT s.id, s.account_id, s.csrf_token, s.scope_kind, s.scope_id, s.epoch,
|
||||
s.expires_at, s.revoked_at, a.email, a.display_name, a.status AS account_status
|
||||
s.expires_at, s.revoked_at, s.last_seen_at, a.email, a.display_name,
|
||||
a.status AS account_status, a.must_change_password
|
||||
FROM auth_sessions s
|
||||
JOIN auth_accounts a ON a.id = s.account_id
|
||||
WHERE s.secret_hash = %s
|
||||
@@ -61,10 +81,15 @@ def _session_row(conn: Connection, request: Request) -> dict:
|
||||
raise unauthorized()
|
||||
if row["account_status"] != "active":
|
||||
raise unauthorized()
|
||||
if row["must_change_password"] and request.url.path not in PASSWORD_CHANGE_PATHS:
|
||||
raise password_change_required()
|
||||
if request.method not in {"GET", "HEAD", "OPTIONS"}:
|
||||
sent = request.headers.get("x-csrf-token") or ""
|
||||
if not sent or sent != row["csrf_token"]:
|
||||
if not sent or not secrets.compare_digest(sent, row["csrf_token"]):
|
||||
raise forbidden("Die Anfrage konnte der Sitzung nicht zugeordnet werden.")
|
||||
seen = row["last_seen_at"]
|
||||
if seen is None or utcnow() - seen > SEEN_INTERVAL:
|
||||
conn.execute("UPDATE auth_sessions SET last_seen_at = now() WHERE id = %s", (row["id"],))
|
||||
return row
|
||||
|
||||
|
||||
@@ -83,7 +108,7 @@ def get_principal(request: Request, conn: Connection = Depends(get_conn)) -> Pri
|
||||
except ValueError as exc:
|
||||
raise forbidden("Der Datenraum ist nicht gewählt.") from exc
|
||||
if kind != row["scope_kind"] or scope_id != row["scope_id"]:
|
||||
raise forbidden("Der gewählte Datenraum entspricht nicht mehr der Sitzung.")
|
||||
raise scope_changed()
|
||||
room = ensure_member_or_personal(conn, row["account_id"], kind, scope_id)
|
||||
return Principal(
|
||||
account_id=row["account_id"],
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Handover package: selection tree, completeness review, ZIP download."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, Response
|
||||
from psycopg import Connection
|
||||
|
||||
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 DOWNLOAD_REFUSED, forbidden, unprocessable
|
||||
from app.exporting import build_export, export_tree, review_export
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _disposition(filename: str) -> str:
|
||||
# Header values stay ASCII. The readable name travels in filename*.
|
||||
encoded = quote(filename)
|
||||
return f"attachment; filename=\"uebergabe.zip\"; filename*=UTF-8''{encoded}"
|
||||
|
||||
|
||||
def _context(value) -> Ctx | None:
|
||||
return None if value is None else Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
def _selection(body: ExportIn) -> tuple[list[str], dict[str, UUID]]:
|
||||
if len(body.assignments) > 200:
|
||||
raise unprocessable("Die Zuordnung der Zugänge ist zu umfangreich.")
|
||||
return list(body.selected), dict(body.assignments)
|
||||
|
||||
|
||||
@router.get("/api/v1/matters/{matter_id}/export-tree")
|
||||
def get_export_tree(
|
||||
matter_id: UUID,
|
||||
context_kind: str | None = None,
|
||||
context_id: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return export_tree(
|
||||
conn,
|
||||
principal.account_id,
|
||||
matter_id,
|
||||
parse_query_context(context_kind, context_id),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/matters/{matter_id}/export/review")
|
||||
def post_export_review(
|
||||
matter_id: UUID,
|
||||
body: ExportIn,
|
||||
request: Request,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
selected, assignments = _selection(body)
|
||||
plan = review_export(
|
||||
conn,
|
||||
principal.account_id,
|
||||
matter_id,
|
||||
_context(body.context),
|
||||
selected,
|
||||
assignments,
|
||||
request.app.state.settings.media_root,
|
||||
)
|
||||
return plan.review()
|
||||
|
||||
|
||||
@router.post("/api/v1/matters/{matter_id}/export")
|
||||
def post_export(
|
||||
matter_id: UUID,
|
||||
body: ExportIn,
|
||||
request: Request,
|
||||
principal: Principal = Depends(get_principal),
|
||||
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,
|
||||
matter_id,
|
||||
_context(body.context),
|
||||
selected,
|
||||
assignments,
|
||||
request.app.state.settings.media_root,
|
||||
)
|
||||
return Response(
|
||||
content=payload,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"Content-Disposition": _disposition(filename),
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Placing a source document into a container: a new reference, or one more binding of an existing element."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import Ctx
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import ExistingIn, ExternalIn
|
||||
from app.ops import bind_existing_external, create_external, existing_externals
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _ctx_model(value) -> Ctx | None:
|
||||
return None if value is None else Ctx(value.kind, value.id)
|
||||
|
||||
|
||||
def place_external(conn, principal: Principal, body: ExternalIn) -> dict:
|
||||
context = Ctx(body.context.kind, body.context.id)
|
||||
placement = _ctx_model(body.placement)
|
||||
if body.bind_element_id is not None:
|
||||
return bind_existing_external(conn, principal.account_id, principal.scope_id, body.bind_element_id, context, placement, body.chapter_id)
|
||||
return create_external(
|
||||
conn,
|
||||
principal.account_id,
|
||||
principal.scope_id,
|
||||
body.title,
|
||||
body.source,
|
||||
body.external_id,
|
||||
context,
|
||||
placement,
|
||||
body.chapter_id,
|
||||
body.dates.document_on,
|
||||
body.dates.sent_on,
|
||||
body.dates.received_on,
|
||||
body.detail.model_dump(mode="json", exclude_none=True) if body.detail else None,
|
||||
duplicate=body.duplicate,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/external-refs/existing")
|
||||
def existing(body: ExistingIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
"""Read only: which of these documents are already present around the target. Nothing is written."""
|
||||
items = [
|
||||
{"source": item.source, "external_id": item.external_id, "connector_id": str(item.connector_id) if item.connector_id else None}
|
||||
for item in body.items
|
||||
]
|
||||
result = existing_externals(conn, principal.account_id, Ctx(body.context.kind, body.context.id), _ctx_model(body.placement), items)
|
||||
return JSONResponse(result, headers={"Cache-Control": "no-store"})
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Library endpoints: rooms as tiles, what lies in a room, and sharing several entries at once."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import parse_query_context, require_case, require_matter
|
||||
from app.access.roles import room_role
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import BatchShareIn
|
||||
from app.core.errors import forbidden
|
||||
from app.library import case_items, case_outline, matter_items, matter_outline, room_contents, room_effect
|
||||
from app.ops import share_with_room
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/overview")
|
||||
def rooms_overview(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
"""The team rooms of the person as tiles. Names of members are only shown to managers."""
|
||||
actor = principal.account_id
|
||||
rooms = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, r.owner_id, r.default_visibility, m.role,
|
||||
(SELECT count(*) FROM room_memberships x WHERE x.room_id = r.id AND x.status = 'active') AS members
|
||||
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization' AND r.status = 'active'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(actor,),
|
||||
).fetchall()
|
||||
items = []
|
||||
for room in rooms:
|
||||
cases, matters = room_contents(conn, actor, room["id"])
|
||||
people = []
|
||||
if room["role"] == "manager":
|
||||
people = [
|
||||
row["display_name"]
|
||||
for row in conn.execute(
|
||||
"""
|
||||
SELECT a.display_name FROM room_memberships x JOIN auth_accounts a ON a.id = x.subject_id
|
||||
WHERE x.room_id = %s AND x.status = 'active'
|
||||
ORDER BY a.display_name, a.id LIMIT 6
|
||||
""",
|
||||
(room["id"],),
|
||||
).fetchall()
|
||||
]
|
||||
items.append(
|
||||
{
|
||||
"id": str(room["id"]),
|
||||
"name": room["name"],
|
||||
"role": room["role"],
|
||||
"is_owner": room["owner_id"] == actor,
|
||||
"private": room["members"] <= 1,
|
||||
"default_visibility": room["default_visibility"],
|
||||
"member_count": room["members"],
|
||||
"members": people,
|
||||
"case_count": sum(1 for case, _ in cases if not case["parent_case_id"]),
|
||||
"matter_count": sum(1 for matter, _ in matters if not matter["parent_matter_id"]),
|
||||
}
|
||||
)
|
||||
return JSONResponse({"items": items}, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/{room_id}/contents")
|
||||
def contents(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
"""Cases and matters shared with the room that the person may read."""
|
||||
if room_role(conn, principal.account_id, room_id) is None:
|
||||
raise forbidden()
|
||||
cases, matters = room_contents(conn, principal.account_id, room_id)
|
||||
return JSONResponse(
|
||||
{
|
||||
"cases": case_items(conn, principal.account_id, cases),
|
||||
"matters": matter_items(conn, principal.account_id, matters),
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms/{room_id}/shares")
|
||||
def share_many(
|
||||
room_id: UUID,
|
||||
body: BatchShareIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""Share several own entries with the room. All or none: one failure rolls the request back."""
|
||||
for item in body.items:
|
||||
share_with_room(conn, principal.account_id, item.kind, item.id, room_id, body.access)
|
||||
return {
|
||||
"shared": len(body.items),
|
||||
"access": body.access,
|
||||
"effect": room_effect(conn, room_id, principal.account_id, body.access),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/api/v1/cases/{case_id}/outline")
|
||||
def case_outline_view(case_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
case, _rights = require_case(conn, principal.account_id, case_id, "read")
|
||||
return JSONResponse(case_outline(conn, principal.account_id, case), headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.get("/api/v1/matters/{matter_id}/outline")
|
||||
def matter_outline_view(
|
||||
matter_id: UUID,
|
||||
context_kind: str | None = None,
|
||||
context_id: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
context = parse_query_context(context_kind, context_id)
|
||||
matter, _rights = require_matter(conn, principal.account_id, matter_id, context, "read")
|
||||
return JSONResponse(matter_outline(conn, principal.account_id, matter, context), headers=_NO_STORE)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Account preferences: read the effective value, change the own value, bind the team."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import audit
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import PreferenceIn
|
||||
from app.preferences import preference_state, store_preference
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
@router.get("/api/v1/auth/preferences/{key}")
|
||||
def get_preference(key: str, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return JSONResponse(preference_state(conn, principal.account_id, key), headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.put("/api/v1/auth/preferences/{key}")
|
||||
def put_preference(
|
||||
key: str,
|
||||
body: PreferenceIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
state = store_preference(conn, principal.account_id, key, body.value, body.team_mode)
|
||||
audit(
|
||||
conn,
|
||||
principal.account_id,
|
||||
None,
|
||||
"preference_changed",
|
||||
"account",
|
||||
principal.account_id,
|
||||
detail={"key": key, "value": body.value, "team_mode": body.team_mode},
|
||||
)
|
||||
return JSONResponse(state, headers=_NO_STORE)
|
||||
@@ -0,0 +1,711 @@
|
||||
"""Data rooms: members, roles, invitations, and the operator's room overview and audit."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import account_by_email, audit
|
||||
from app.access.limits import ensure_can_add_member, ensure_can_create_room
|
||||
from app.access.roles import (
|
||||
ROOM_ROLES,
|
||||
account_kind,
|
||||
count_active_managers,
|
||||
require_main_user,
|
||||
require_operator,
|
||||
require_room_manager,
|
||||
room_role,
|
||||
)
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import (
|
||||
InvitationIn,
|
||||
MemberIn,
|
||||
MemberRoleIn,
|
||||
OperatorManagerIn,
|
||||
OperatorOwnerIn,
|
||||
OwnerIn,
|
||||
RoomIn,
|
||||
RoomPatchIn,
|
||||
VisibilityIn,
|
||||
)
|
||||
from app.auth.accounts import normalize_email
|
||||
from app.auth.security import hash_secret, new_secret
|
||||
from app.core.errors import forbidden, not_found, unprocessable
|
||||
from app.core.timeutil import dump_dt, utcnow
|
||||
from app.present import LABELS
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
INVITATION_DAYS = 7
|
||||
|
||||
|
||||
def _created(path: str, payload: dict) -> JSONResponse:
|
||||
return JSONResponse(status_code=201, content=payload, headers={"Location": path, **_NO_STORE})
|
||||
|
||||
|
||||
def _require_owner(conn, account_id: UUID, room_id: UUID) -> dict:
|
||||
# An unknown room and a room owned by someone else answer alike: no way to probe ids.
|
||||
room = conn.execute(
|
||||
"SELECT * FROM data_rooms WHERE id = %s AND kind = 'organization'", (room_id,)
|
||||
).fetchone()
|
||||
if room is None or room["owner_id"] != account_id:
|
||||
raise forbidden("Das darf nur der Eigentümer des Datenraums.")
|
||||
return room
|
||||
|
||||
|
||||
def _protect_owner(room: dict, subject_id: UUID) -> None:
|
||||
if room["owner_id"] == subject_id:
|
||||
raise unprocessable("Der Eigentümer bleibt Verwalter. Übertrage den Datenraum zuerst.")
|
||||
|
||||
|
||||
def _room(conn, room_id: UUID) -> dict:
|
||||
row = conn.execute("SELECT * FROM data_rooms WHERE id = %s AND kind = 'organization'", (room_id,)).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return row
|
||||
|
||||
|
||||
def _audit_membership(conn, actor: UUID, room_id: UUID, subject_id: UUID, action: str, role: str | None = None) -> None:
|
||||
audit(
|
||||
conn,
|
||||
actor,
|
||||
room_id,
|
||||
action,
|
||||
"membership",
|
||||
subject_id,
|
||||
detail={"room_id": str(room_id), **({"role": role} if role else {})},
|
||||
)
|
||||
|
||||
|
||||
def _drop_edit_rights_in_room(conn, subject_id: UUID, room_id: UUID) -> None:
|
||||
"""A reader neither edits nor shares objects of this room. Read grants stay."""
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE access_grants g
|
||||
SET can_edit = false, can_share = false
|
||||
WHERE g.grantee_subject_id = %s AND NOT g.is_exception AND (g.can_edit OR g.can_share)
|
||||
AND (
|
||||
(g.resource_kind = 'case' AND g.resource_id IN (SELECT id FROM cases WHERE home_scope_id = %s))
|
||||
OR (g.resource_kind = 'matter' AND g.resource_id IN (SELECT id FROM matters WHERE home_scope_id = %s))
|
||||
OR (g.resource_kind = 'element' AND g.resource_id IN (SELECT id FROM elements WHERE home_scope_id = %s))
|
||||
OR (g.resource_kind = 'task' AND g.resource_id IN (SELECT id FROM tasks WHERE home_scope_id = %s))
|
||||
OR (g.resource_kind = 'deadline' AND g.resource_id IN (SELECT id FROM deadlines WHERE home_scope_id = %s))
|
||||
)
|
||||
""",
|
||||
(subject_id, room_id, room_id, room_id, room_id, room_id),
|
||||
)
|
||||
|
||||
|
||||
def _drop_shares_of(conn, room_id: UUID, subject_id: UUID) -> None:
|
||||
"""Whoever leaves a team, or may no longer write in it, takes the shares of their own entries with them."""
|
||||
conn.execute(
|
||||
"""
|
||||
DELETE FROM room_shares s
|
||||
WHERE s.room_id = %s
|
||||
AND (
|
||||
(s.resource_kind = 'case' AND s.resource_id IN (SELECT id FROM cases WHERE owner_subject_id = %s))
|
||||
OR (s.resource_kind = 'matter' AND s.resource_id IN (SELECT id FROM matters WHERE owner_subject_id = %s))
|
||||
)
|
||||
""",
|
||||
(room_id, subject_id, subject_id),
|
||||
)
|
||||
|
||||
|
||||
def _set_role(conn, actor: UUID, room_id: UUID, subject_id: UUID, role: str, *, added: bool) -> None:
|
||||
if role not in ROOM_ROLES:
|
||||
raise unprocessable("Diese Raumrolle gibt es nicht.")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role, status)
|
||||
VALUES (%s, %s, %s, 'active')
|
||||
ON CONFLICT (room_id, subject_id) DO UPDATE SET role = EXCLUDED.role, status = 'active'
|
||||
""",
|
||||
(room_id, subject_id, role),
|
||||
)
|
||||
if role == "reader":
|
||||
_drop_edit_rights_in_room(conn, subject_id, room_id)
|
||||
_drop_shares_of(conn, room_id, subject_id)
|
||||
_audit_membership(conn, actor, room_id, subject_id, "membership_added" if added else "membership_role_changed", role)
|
||||
|
||||
|
||||
def _membership(conn, room_id: UUID, subject_id: UUID, *, lock: bool = False) -> dict | None:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
return conn.execute(
|
||||
f"SELECT role, status FROM room_memberships WHERE room_id = %s AND subject_id = %s{suffix}",
|
||||
(room_id, subject_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms")
|
||||
def rooms(
|
||||
include_archived: bool = False,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
from app.auth.accounts import list_rooms
|
||||
|
||||
items = list_rooms(conn, principal.account_id)
|
||||
if include_archived:
|
||||
archived = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, m.role, r.owner_id
|
||||
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization' AND r.status = 'archived'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(principal.account_id,),
|
||||
).fetchall()
|
||||
items += [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"kind": "organization",
|
||||
"name": row["name"],
|
||||
"role": row["role"],
|
||||
"status": "archived",
|
||||
"is_owner": row["owner_id"] == principal.account_id,
|
||||
}
|
||||
for row in archived
|
||||
]
|
||||
return {"items": items, "next_cursor": None}
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms")
|
||||
def create_room(body: RoomIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_main_user(conn, principal.account_id)
|
||||
ensure_can_create_room(conn, principal.account_id)
|
||||
room_id = uuid4()
|
||||
name = body.name.strip()
|
||||
conn.execute(
|
||||
"""
|
||||
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, principal.account_id),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager')",
|
||||
(room_id, principal.account_id),
|
||||
)
|
||||
audit(conn, principal.account_id, room_id, "room_created", "room", room_id)
|
||||
return _created(
|
||||
f"/api/v1/rooms/{room_id}",
|
||||
{"id": str(room_id), "kind": "organization", "name": name, "default_visibility": body.default_visibility},
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/api/v1/rooms/{room_id}")
|
||||
def patch_room(
|
||||
room_id: UUID,
|
||||
body: RoomPatchIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
room = _room(conn, room_id)
|
||||
if body.name is not None and body.name.strip() != room["name"]:
|
||||
conn.execute("UPDATE data_rooms SET name = %s WHERE id = %s", (body.name.strip(), room_id))
|
||||
audit(conn, principal.account_id, room_id, "room_renamed", "room", room_id)
|
||||
if body.default_visibility is not None and body.default_visibility != room["default_visibility"]:
|
||||
_require_owner(conn, principal.account_id, room_id)
|
||||
conn.execute("UPDATE data_rooms SET default_visibility = %s WHERE id = %s", (body.default_visibility, room_id))
|
||||
audit(
|
||||
conn,
|
||||
principal.account_id,
|
||||
room_id,
|
||||
"room_default_changed",
|
||||
"room",
|
||||
room_id,
|
||||
detail={"visibility": body.default_visibility},
|
||||
)
|
||||
if body.status is not None and body.status != room["status"]:
|
||||
_require_owner(conn, principal.account_id, room_id)
|
||||
conn.execute("UPDATE data_rooms SET status = %s WHERE id = %s", (body.status, room_id))
|
||||
if body.status == "archived":
|
||||
# Sessions working in the room return to their personal room.
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions
|
||||
SET scope_kind = 'personal', scope_id = account_id, epoch = epoch + 1
|
||||
WHERE scope_id = %s AND revoked_at IS NULL
|
||||
""",
|
||||
(room_id,),
|
||||
)
|
||||
audit(
|
||||
conn,
|
||||
principal.account_id,
|
||||
room_id,
|
||||
"room_archived" if body.status == "archived" else "room_restored",
|
||||
"room",
|
||||
room_id,
|
||||
)
|
||||
row = _room(conn, room_id)
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"name": row["name"],
|
||||
"status": row["status"],
|
||||
"default_visibility": row["default_visibility"],
|
||||
}
|
||||
|
||||
|
||||
def _set_owner(conn, actor: UUID, room_id: UUID, new_owner: UUID, previous: UUID | None) -> None:
|
||||
conn.execute("UPDATE data_rooms SET owner_id = %s WHERE id = %s", (new_owner, room_id))
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO room_memberships (room_id, subject_id, role, status)
|
||||
VALUES (%s, %s, 'manager', 'active')
|
||||
ON CONFLICT (room_id, subject_id) DO UPDATE SET role = 'manager', status = 'active'
|
||||
""",
|
||||
(room_id, new_owner),
|
||||
)
|
||||
audit(
|
||||
conn,
|
||||
actor,
|
||||
room_id,
|
||||
"room_owner_changed",
|
||||
"room",
|
||||
room_id,
|
||||
detail={"from": str(previous) if previous else None, "to": str(new_owner)},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms/{room_id}/owner")
|
||||
def transfer_owner(
|
||||
room_id: UUID,
|
||||
body: OwnerIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""The owner hands the room to an active member. The new owner becomes manager."""
|
||||
room = _require_owner(conn, principal.account_id, room_id)
|
||||
target = _membership(conn, room_id, body.subject_id, lock=True)
|
||||
account = conn.execute("SELECT status FROM auth_accounts WHERE id = %s", (body.subject_id,)).fetchone()
|
||||
if target is None or target["status"] != "active" or account is None or account["status"] != "active":
|
||||
raise unprocessable("Der Datenraum geht nur an ein aktives Mitglied.")
|
||||
if account_kind(conn, body.subject_id) != "main":
|
||||
raise unprocessable("Ein Mitarbeiter-Konto kann keinen Datenraum besitzen.")
|
||||
if body.subject_id == room["owner_id"]:
|
||||
raise unprocessable("Diese Person ist bereits Eigentümer.")
|
||||
_set_owner(conn, principal.account_id, room_id, body.subject_id, room["owner_id"])
|
||||
return {"owner_id": str(body.subject_id)}
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/{room_id}/exposure")
|
||||
def exposure(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
"""Own cases and matters: shared with this room (`room`) or filed here but not shared (`private`)."""
|
||||
if room_role(conn, principal.account_id, room_id) is None:
|
||||
raise forbidden()
|
||||
result: dict = {}
|
||||
for table, kind in (("cases", "case"), ("matters", "matter")):
|
||||
row = conn.execute(
|
||||
f"""
|
||||
SELECT
|
||||
count(*) FILTER (WHERE EXISTS (
|
||||
SELECT 1 FROM room_shares s
|
||||
WHERE s.resource_kind = %s AND s.resource_id = t.id AND s.room_id = %s)) AS shared,
|
||||
count(*) FILTER (WHERE t.home_scope_id = %s AND NOT EXISTS (
|
||||
SELECT 1 FROM room_shares s
|
||||
WHERE s.resource_kind = %s AND s.resource_id = t.id AND s.room_id = %s)) AS filed
|
||||
FROM {table} t
|
||||
WHERE t.owner_subject_id = %s AND t.deleted_at IS NULL
|
||||
""",
|
||||
(kind, room_id, room_id, kind, room_id, principal.account_id),
|
||||
).fetchone()
|
||||
result[table] = {"room": row["shared"], "private": row["filed"]}
|
||||
return JSONResponse(result, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms/{room_id}/my-content/visibility")
|
||||
def set_my_content(
|
||||
room_id: UUID,
|
||||
body: VisibilityIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""`room`: share every own entry filed in this room with it. `private`: end all own shares to it."""
|
||||
role = room_role(conn, principal.account_id, room_id)
|
||||
if role is None:
|
||||
raise forbidden()
|
||||
changed = 0
|
||||
if body.visibility == "room":
|
||||
if role not in {"member", "manager"}:
|
||||
raise forbidden("Als Leser kannst du nichts mit dem Datenraum teilen.")
|
||||
for table, kind in (("cases", "case"), ("matters", "matter")):
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
INSERT INTO room_shares (resource_kind, resource_id, room_id, access, created_by)
|
||||
SELECT %s, t.id, %s, 'edit', %s FROM {table} t
|
||||
WHERE t.home_scope_id = %s AND t.owner_subject_id = %s AND t.deleted_at IS NULL
|
||||
ON CONFLICT DO NOTHING
|
||||
RETURNING id
|
||||
""",
|
||||
(kind, room_id, principal.account_id, room_id, principal.account_id),
|
||||
).fetchall()
|
||||
changed += len(rows)
|
||||
else:
|
||||
for table, kind in (("cases", "case"), ("matters", "matter")):
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
DELETE FROM room_shares s
|
||||
WHERE s.room_id = %s AND s.resource_kind = %s
|
||||
AND s.resource_id IN (SELECT id FROM {table} WHERE owner_subject_id = %s)
|
||||
RETURNING s.id
|
||||
""",
|
||||
(room_id, kind, principal.account_id),
|
||||
).fetchall()
|
||||
changed += len(rows)
|
||||
if changed:
|
||||
audit(
|
||||
conn,
|
||||
principal.account_id,
|
||||
room_id,
|
||||
"visibility_changed",
|
||||
"room",
|
||||
room_id,
|
||||
detail={"visibility": body.visibility, "count": changed},
|
||||
)
|
||||
return {"changed": changed}
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/{room_id}/members")
|
||||
def members(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
owner_id = _room(conn, room_id)["owner_id"]
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, m.role, a.email, a.display_name, a.status
|
||||
FROM room_memberships m
|
||||
JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = %s AND m.status = 'active'
|
||||
ORDER BY a.display_name, a.id
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"subject_id": str(row["subject_id"]),
|
||||
"email": row["email"],
|
||||
"display_name": row["display_name"],
|
||||
"role": row["role"],
|
||||
"account_status": row["status"],
|
||||
"is_owner": row["subject_id"] == owner_id,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/v1/rooms/{room_id}/members")
|
||||
def add_member(
|
||||
room_id: UUID,
|
||||
body: MemberIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
account = account_by_email(conn, body.email)
|
||||
if account is None or account["status"] != "active":
|
||||
raise not_found()
|
||||
existing = _membership(conn, room_id, account["id"], lock=True)
|
||||
if body.role != "manager":
|
||||
_protect_owner(_room(conn, room_id), account["id"])
|
||||
if existing and existing["status"] == "active" and existing["role"] == "manager" and body.role != "manager":
|
||||
if count_active_managers(conn, room_id, lock=True) <= 1:
|
||||
raise unprocessable("Der letzte Verwalter bleibt Verwalter.")
|
||||
was_active = bool(existing and existing["status"] == "active")
|
||||
if not was_active:
|
||||
ensure_can_add_member(conn, _room(conn, room_id)["owner_id"], room_id)
|
||||
_set_role(conn, principal.account_id, room_id, account["id"], body.role, added=not was_active)
|
||||
return {"subject_id": str(account["id"]), "role": body.role}
|
||||
|
||||
|
||||
@router.patch("/api/v1/rooms/{room_id}/members/{subject_id}")
|
||||
def change_member_role(
|
||||
room_id: UUID,
|
||||
subject_id: UUID,
|
||||
body: MemberRoleIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
count_active_managers(conn, room_id, lock=True)
|
||||
current = _membership(conn, room_id, subject_id, lock=True)
|
||||
if current is None or current["status"] != "active":
|
||||
raise not_found()
|
||||
if current["role"] == body.role:
|
||||
return {"subject_id": str(subject_id), "role": body.role}
|
||||
_protect_owner(_room(conn, room_id), subject_id)
|
||||
if current["role"] == "manager" and count_active_managers(conn, room_id) <= 1:
|
||||
raise unprocessable("Der letzte Verwalter bleibt Verwalter.")
|
||||
_set_role(conn, principal.account_id, room_id, subject_id, body.role, added=False)
|
||||
return {"subject_id": str(subject_id), "role": body.role}
|
||||
|
||||
|
||||
@router.delete("/api/v1/rooms/{room_id}/members/{subject_id}", status_code=204)
|
||||
def remove_member(
|
||||
room_id: UUID,
|
||||
subject_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
count_active_managers(conn, room_id, lock=True)
|
||||
current = _membership(conn, room_id, subject_id, lock=True)
|
||||
if current is None or current["status"] != "active":
|
||||
raise not_found()
|
||||
_protect_owner(_room(conn, room_id), subject_id)
|
||||
if current["role"] == "manager" and count_active_managers(conn, room_id) <= 1:
|
||||
raise unprocessable("Der letzte Verwalter kann den Datenraum nicht verlassen.")
|
||||
conn.execute(
|
||||
"UPDATE room_memberships SET status = 'removed' WHERE room_id = %s AND subject_id = %s",
|
||||
(room_id, subject_id),
|
||||
)
|
||||
_drop_shares_of(conn, room_id, subject_id)
|
||||
# The removed person works in the personal room again; own entries stay visible there.
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions
|
||||
SET scope_kind = 'personal', scope_id = account_id, epoch = epoch + 1
|
||||
WHERE account_id = %s AND scope_id = %s AND revoked_at IS NULL
|
||||
""",
|
||||
(subject_id, room_id),
|
||||
)
|
||||
_audit_membership(conn, principal.account_id, room_id, subject_id, "membership_removed")
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.post("/api/v1/invitations")
|
||||
def invite(
|
||||
body: InvitationIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
# Only the owner, a main user, brings new people in; they become employee accounts.
|
||||
room = _require_owner(conn, principal.account_id, body.room_id)
|
||||
require_main_user(conn, principal.account_id)
|
||||
ensure_can_add_member(conn, room["owner_id"], room["id"])
|
||||
email = normalize_email(body.email)
|
||||
if account_by_email(conn, email):
|
||||
raise unprocessable("Es gibt bereits ein Konto. Füge die Person als Mitglied hinzu.")
|
||||
token = new_secret()
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_invitations (email, room_id, token_hash, invited_by, expires_at, role)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, expires_at
|
||||
""",
|
||||
(email, room["id"], hash_secret(token), principal.account_id, utcnow() + timedelta(days=INVITATION_DAYS), body.role),
|
||||
).fetchone()
|
||||
audit(conn, principal.account_id, room["id"], "invitation_created", "invitation", row["id"], detail={"role": body.role})
|
||||
return _created(
|
||||
f"/api/v1/invitations/{row['id']}",
|
||||
{"id": str(row["id"]), "email": email, "role": body.role, "expires_at": dump_dt(row["expires_at"]), "token": token},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/rooms/{room_id}/invitations")
|
||||
def invitations(room_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, email, role, expires_at, created_at
|
||||
FROM auth_invitations
|
||||
WHERE room_id = %s AND accepted_at IS NULL AND revoked_at IS NULL AND expires_at > now()
|
||||
ORDER BY created_at DESC, id
|
||||
""",
|
||||
(room_id,),
|
||||
).fetchall()
|
||||
return JSONResponse(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"email": row["email"],
|
||||
"role": row["role"],
|
||||
"expires_at": dump_dt(row["expires_at"]),
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/api/v1/rooms/{room_id}/invitations/{invitation_id}", status_code=204)
|
||||
def revoke_invitation(
|
||||
room_id: UUID,
|
||||
invitation_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_room_manager(conn, principal.account_id, room_id)
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE auth_invitations SET revoked_at = now()
|
||||
WHERE id = %s AND room_id = %s AND accepted_at IS NULL AND revoked_at IS NULL
|
||||
RETURNING id
|
||||
""",
|
||||
(invitation_id, room_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
audit(conn, principal.account_id, room_id, "invitation_revoked", "invitation", invitation_id)
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@router.get("/api/v1/admin/rooms")
|
||||
def admin_rooms(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
"""Metadata only: names, state and who manages. No content."""
|
||||
require_operator(conn, principal.account_id)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, r.status, r.created_at,
|
||||
(SELECT o.display_name FROM auth_accounts o WHERE o.id = r.owner_id) AS owner_name,
|
||||
EXISTS (
|
||||
SELECT 1 FROM auth_accounts o
|
||||
JOIN room_memberships om ON om.subject_id = o.id AND om.room_id = r.id AND om.status = 'active'
|
||||
WHERE o.id = r.owner_id AND o.status = 'active'
|
||||
) AS owner_active,
|
||||
(SELECT count(*) FROM room_memberships m WHERE m.room_id = r.id AND m.status = 'active') AS members,
|
||||
COALESCE((
|
||||
SELECT json_agg(a.display_name ORDER BY a.display_name)
|
||||
FROM room_memberships m JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = r.id AND m.status = 'active' AND m.role = 'manager' AND a.status = 'active'
|
||||
), '[]'::json) AS managers
|
||||
FROM data_rooms r
|
||||
WHERE r.kind = 'organization'
|
||||
ORDER BY r.name, r.id
|
||||
"""
|
||||
).fetchall()
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"name": row["name"],
|
||||
"status": row["status"],
|
||||
"members": row["members"],
|
||||
"owner": row["owner_name"],
|
||||
"owner_active": row["owner_active"],
|
||||
"managers": row["managers"],
|
||||
"has_manager": bool(row["managers"]),
|
||||
"created_at": dump_dt(row["created_at"]),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
"next_cursor": None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/v1/admin/rooms/{room_id}/managers")
|
||||
def admin_assign_manager(
|
||||
room_id: UUID,
|
||||
body: OperatorManagerIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""Only for a room without an active manager, so it does not stay orphaned."""
|
||||
require_operator(conn, principal.account_id)
|
||||
_room(conn, room_id)
|
||||
if count_active_managers(conn, room_id, lock=True) > 0:
|
||||
raise forbidden("Dieser Datenraum hat bereits einen Verwalter.")
|
||||
account = account_by_email(conn, body.email)
|
||||
if account is None or account["status"] != "active":
|
||||
raise not_found()
|
||||
existing = _membership(conn, room_id, account["id"], lock=True)
|
||||
_set_role(
|
||||
conn,
|
||||
principal.account_id,
|
||||
room_id,
|
||||
account["id"],
|
||||
"manager",
|
||||
added=not (existing and existing["status"] == "active"),
|
||||
)
|
||||
return {"subject_id": str(account["id"]), "role": "manager"}
|
||||
|
||||
|
||||
@router.post("/api/v1/admin/rooms/{room_id}/owner")
|
||||
def admin_set_owner(
|
||||
room_id: UUID,
|
||||
body: OperatorOwnerIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""The operator steps in only when the owner can no longer act: disabled or not a member any more."""
|
||||
require_operator(conn, principal.account_id)
|
||||
room = _room(conn, room_id)
|
||||
owner = conn.execute("SELECT status FROM auth_accounts WHERE id = %s", (room["owner_id"],)).fetchone()
|
||||
active_owner = bool(owner and owner["status"] == "active" and room_role(conn, room["owner_id"], room_id))
|
||||
if active_owner:
|
||||
raise forbidden("Der Eigentümer ist aktiv. Er überträgt den Datenraum selbst.")
|
||||
account = account_by_email(conn, body.email)
|
||||
if account is None or account["status"] != "active":
|
||||
raise not_found()
|
||||
if account_kind(conn, account["id"]) != "main":
|
||||
raise unprocessable("Ein Mitarbeiter-Konto kann keinen Datenraum besitzen.")
|
||||
_set_owner(conn, principal.account_id, room_id, account["id"], room["owner_id"])
|
||||
return {"owner_id": str(account["id"])}
|
||||
|
||||
|
||||
_ADMIN_KINDS = ("account", "session", "room", "membership", "invitation")
|
||||
|
||||
|
||||
@router.get("/api/v1/admin/events")
|
||||
def admin_events(
|
||||
cursor: int = 0,
|
||||
limit: int = 50,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_operator(conn, principal.account_id)
|
||||
limit = max(1, min(limit, 100))
|
||||
cursor = max(0, cursor)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT e.id, e.action, e.resource_kind, e.resource_id, e.occurred_at, e.result, e.scope_id,
|
||||
actor.display_name AS actor_name,
|
||||
subject.display_name AS subject_name,
|
||||
room.name AS room_name
|
||||
FROM domain_events e
|
||||
LEFT JOIN auth_accounts actor ON actor.id = e.actor_subject_id
|
||||
LEFT JOIN auth_accounts subject ON subject.id = e.resource_id AND e.resource_kind IN ('account', 'membership')
|
||||
LEFT JOIN data_rooms room ON room.id = COALESCE(e.scope_id, CASE WHEN e.resource_kind = 'room' THEN e.resource_id END)
|
||||
AND room.kind = 'organization'
|
||||
WHERE e.resource_kind = ANY(%s)
|
||||
ORDER BY e.occurred_at DESC, e.id DESC
|
||||
OFFSET %s LIMIT %s
|
||||
""",
|
||||
(list(_ADMIN_KINDS), cursor, limit + 1),
|
||||
).fetchall()
|
||||
page = rows[:limit]
|
||||
return JSONResponse(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"action": row["action"],
|
||||
"label": LABELS.get(row["action"], "Ereignis"),
|
||||
"resource_kind": row["resource_kind"],
|
||||
"actor": row["actor_name"],
|
||||
"subject": row["subject_name"],
|
||||
"room": row["room_name"],
|
||||
"occurred_at": dump_dt(row["occurred_at"]),
|
||||
"result": row["result"],
|
||||
}
|
||||
for row in page
|
||||
],
|
||||
"next_cursor": cursor + limit if len(rows) > limit else None,
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Room shares of a case or matter. A room is a team: the owner shares an entry with any of the
|
||||
rooms he is a member of, independent of where the entry is filed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import ROOM_RIGHTS, Rights
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.schemas import ExclusionIn, RoomShareIn
|
||||
from app.library import room_effect
|
||||
from app.ops import _shareable, set_person_exclusion, share_with_room, unshare_from_room
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
def _capped(role: str, access: str) -> Rights:
|
||||
rights = ROOM_RIGHTS.get(role, Rights())
|
||||
return Rights(read=rights.read) if access == "read" else rights
|
||||
|
||||
|
||||
def _view(conn, actor: UUID, kind: str, resource_id: UUID) -> dict:
|
||||
_shareable(conn, actor, kind, resource_id)
|
||||
shares = conn.execute(
|
||||
"""
|
||||
SELECT s.room_id, s.access, r.name, r.status
|
||||
FROM room_shares s JOIN data_rooms r ON r.id = s.room_id
|
||||
WHERE s.resource_kind = %s AND s.resource_id = %s
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(kind, resource_id),
|
||||
).fetchall()
|
||||
result = []
|
||||
for share in shares:
|
||||
members = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, m.role, a.display_name,
|
||||
EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.is_exception AND g.grantee_subject_id = m.subject_id
|
||||
AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL
|
||||
) AS excluded
|
||||
FROM room_memberships m
|
||||
JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = %s AND m.status = 'active' AND m.subject_id <> %s
|
||||
ORDER BY a.display_name, a.id
|
||||
""",
|
||||
(kind, resource_id, share["room_id"], actor),
|
||||
).fetchall()
|
||||
result.append(
|
||||
{
|
||||
"room_id": str(share["room_id"]),
|
||||
"room_name": share["name"],
|
||||
"archived": share["status"] != "active",
|
||||
"access": share["access"],
|
||||
"members": [
|
||||
{
|
||||
"subject_id": str(row["subject_id"]),
|
||||
"display_name": row["display_name"],
|
||||
"role": row["role"],
|
||||
"excluded": row["excluded"],
|
||||
"rights": {
|
||||
"read": _capped(row["role"], share["access"]).read,
|
||||
"edit": _capped(row["role"], share["access"]).edit,
|
||||
},
|
||||
}
|
||||
for row in members
|
||||
],
|
||||
}
|
||||
)
|
||||
shared_ids = {item["room_id"] for item in result}
|
||||
candidates = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, m.role
|
||||
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND m.role IN ('member', 'manager')
|
||||
AND r.kind = 'organization' AND r.status = 'active'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(actor,),
|
||||
).fetchall()
|
||||
return {
|
||||
"id": str(resource_id),
|
||||
"shares": result,
|
||||
"available": [
|
||||
{"id": str(row["id"]), "name": row["name"]} for row in candidates if str(row["id"]) not in shared_ids
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _register(kind: str, plural: str) -> None:
|
||||
base = f"/api/v1/{plural}/{{resource_id}}/room-share"
|
||||
|
||||
@router.get(base, name=f"get_{kind}_room_share")
|
||||
def get_share(resource_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return JSONResponse(_view(conn, principal.account_id, kind, resource_id), headers=_NO_STORE)
|
||||
|
||||
@router.put(base + "/rooms/{room_id}", name=f"put_{kind}_room_share")
|
||||
def put_share(
|
||||
resource_id: UUID,
|
||||
room_id: UUID,
|
||||
body: RoomShareIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
shared = share_with_room(conn, principal.account_id, kind, resource_id, room_id, body.access)
|
||||
shared["effect"] = room_effect(conn, room_id, principal.account_id, body.access)
|
||||
return shared
|
||||
|
||||
@router.delete(base + "/rooms/{room_id}", status_code=204, name=f"delete_{kind}_room_share")
|
||||
def delete_share(
|
||||
resource_id: UUID,
|
||||
room_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
unshare_from_room(conn, principal.account_id, kind, resource_id, room_id)
|
||||
return Response(status_code=204)
|
||||
|
||||
@router.put(base + "/people/{subject_id}", name=f"put_{kind}_room_share_person")
|
||||
def put_person(
|
||||
resource_id: UUID,
|
||||
subject_id: UUID,
|
||||
body: ExclusionIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
set_person_exclusion(conn, principal.account_id, kind, resource_id, subject_id, body.excluded)
|
||||
return {"subject_id": str(subject_id), "excluded": body.excluded}
|
||||
|
||||
|
||||
_register("case", "cases")
|
||||
_register("matter", "matters")
|
||||
+761
-229
File diff suppressed because it is too large.
Load diff
+352
-2
@@ -20,6 +20,37 @@ class LoginIn(APIModel):
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
class BootstrapIn(APIModel):
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class AccountIn(APIModel):
|
||||
"""Without a password the server generates a one-time password."""
|
||||
|
||||
email: Email
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str | None = Field(default=None, min_length=10, max_length=200)
|
||||
is_operator: bool = False
|
||||
|
||||
|
||||
class AccountPatchIn(APIModel):
|
||||
display_name: str | None = Field(default=None, min_length=1, max_length=120)
|
||||
is_operator: bool | None = None
|
||||
status: Literal["active", "disabled"] | None = None
|
||||
account_kind: Literal["main"] | None = None
|
||||
|
||||
|
||||
class TeamPatchIn(APIModel):
|
||||
status: Literal["active", "disabled"]
|
||||
|
||||
|
||||
class PasswordChangeIn(APIModel):
|
||||
current_password: str = Field(min_length=1, max_length=200)
|
||||
new_password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
class ScopeIn(APIModel):
|
||||
kind: Literal["personal", "organization"]
|
||||
id: UUID
|
||||
@@ -34,15 +65,61 @@ class AcceptInviteIn(APIModel):
|
||||
class InvitationIn(APIModel):
|
||||
email: Email
|
||||
room_id: UUID
|
||||
role: Literal["member", "manager", "reader"] = "member"
|
||||
|
||||
|
||||
class RoomIn(APIModel):
|
||||
name: str = Field(min_length=1, max_length=160)
|
||||
default_visibility: Literal["private", "room"] = "room"
|
||||
|
||||
|
||||
class VisibilityIn(APIModel):
|
||||
visibility: Literal["private", "room"]
|
||||
|
||||
|
||||
class ShareItemIn(APIModel):
|
||||
kind: Literal["case", "matter"]
|
||||
id: UUID
|
||||
|
||||
|
||||
class BatchShareIn(APIModel):
|
||||
items: list[ShareItemIn] = Field(min_length=1, max_length=200)
|
||||
access: Literal["read", "edit"] = "edit"
|
||||
|
||||
|
||||
class RoomShareIn(APIModel):
|
||||
access: Literal["read", "edit"] = "edit"
|
||||
|
||||
|
||||
class ExclusionIn(APIModel):
|
||||
excluded: bool
|
||||
|
||||
|
||||
class OwnerIn(APIModel):
|
||||
subject_id: UUID
|
||||
|
||||
|
||||
class OperatorOwnerIn(APIModel):
|
||||
email: Email
|
||||
|
||||
|
||||
class MemberIn(APIModel):
|
||||
email: Email
|
||||
role: Literal["member", "manager"]
|
||||
role: Literal["member", "manager", "reader"]
|
||||
|
||||
|
||||
class MemberRoleIn(APIModel):
|
||||
role: Literal["member", "manager", "reader"]
|
||||
|
||||
|
||||
class RoomPatchIn(APIModel):
|
||||
name: str | None = Field(default=None, min_length=1, max_length=160)
|
||||
status: Literal["active", "archived"] | None = None
|
||||
default_visibility: Literal["private", "room"] | None = None
|
||||
|
||||
|
||||
class OperatorManagerIn(APIModel):
|
||||
email: Email
|
||||
|
||||
|
||||
class ContextIn(APIModel):
|
||||
@@ -54,6 +131,8 @@ class CaseIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
parent_case_id: UUID | None = None
|
||||
rights_mode: Literal["inherit_parent", "explicit"] = "inherit_parent"
|
||||
home_scope_id: UUID | None = None
|
||||
share_with_room_id: UUID | None = None
|
||||
|
||||
|
||||
class CasePatch(APIModel):
|
||||
@@ -65,12 +144,71 @@ class CasePatch(APIModel):
|
||||
class ChapterIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
position: int | None = Field(default=None, ge=0, le=10000)
|
||||
document_on: date | None = None
|
||||
parent_chapter_id: UUID | None = None
|
||||
|
||||
|
||||
class ChapterOrderIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
chapter_ids: list[UUID] = Field(min_length=0, max_length=200)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ChapterDateIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
document_on: date | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ChapterTitleIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ChapterDeleteIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ChapterParentIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
parent_chapter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class BindingChaptersIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
binding_ids: list[UUID] = Field(min_length=1, max_length=500)
|
||||
chapter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class RecordDeleteIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class MatterMoveIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn | None = None
|
||||
case_id: UUID | None = None
|
||||
parent_matter_id: UUID | None = None
|
||||
clear_parent: bool = False
|
||||
|
||||
|
||||
class CommunicationIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
direction: Literal["in", "out", "local"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class MatterIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
parent_matter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
home_scope_id: UUID | None = None
|
||||
share_with_room_id: UUID | None = None
|
||||
|
||||
|
||||
class MatterPatch(APIModel):
|
||||
@@ -96,6 +234,7 @@ class GrantIn(APIModel):
|
||||
can_read: bool = True
|
||||
can_edit: bool = False
|
||||
can_share: bool = False
|
||||
use_owner_sources: bool = False
|
||||
|
||||
|
||||
class ExceptionIn(APIModel):
|
||||
@@ -118,6 +257,48 @@ class NoteIn(APIModel):
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
chapter_id: UUID | None = None
|
||||
dates: DatesIn | None = None
|
||||
communication_direction: Literal["in", "out", "local"] | None = None
|
||||
|
||||
|
||||
class ContentOrderIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
mode: Literal["date", "position"]
|
||||
direction: Literal["asc", "desc"] = "asc"
|
||||
view: Literal["structure", "chronology"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class BindingOrderIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
binding_ids: list[UUID] = Field(min_length=0, max_length=500)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class DatesPatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
document_on: date | None = None
|
||||
sent_on: date | None = None
|
||||
received_on: date | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class SummaryPatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
summary: str | None = Field(default=None, max_length=400)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TitlePatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ChapterMoveIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
chapter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class NotePatch(APIModel):
|
||||
@@ -144,14 +325,73 @@ class DatesIn(APIModel):
|
||||
received_on: date | None = None
|
||||
|
||||
|
||||
class MailAttachment(APIModel):
|
||||
filename: str = Field(min_length=1, max_length=200)
|
||||
content_type: str | None = Field(default=None, max_length=120)
|
||||
|
||||
|
||||
class ExternalDetail(APIModel):
|
||||
correspondent: str | None = Field(default=None, max_length=200)
|
||||
message_from: str | None = Field(default=None, max_length=200)
|
||||
message_to: str | None = Field(default=None, max_length=500)
|
||||
message_cc: str | None = Field(default=None, max_length=500)
|
||||
direction: Literal["in", "out"] | None = None
|
||||
mailbox: str | None = Field(default=None, max_length=200)
|
||||
connector_id: UUID | None = None
|
||||
uid: int | None = Field(default=None, ge=1)
|
||||
attachments: list[MailAttachment] = Field(default_factory=list, max_length=40)
|
||||
open_url: str | None = Field(default=None, max_length=500, pattern=r"^https?://")
|
||||
|
||||
|
||||
class ExternalIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
source: Literal["paperless", "url"]
|
||||
source: str = Field(min_length=1, max_length=40)
|
||||
external_id: str = Field(min_length=1, max_length=200)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
chapter_id: UUID | None = None
|
||||
dates: DatesIn = DatesIn()
|
||||
detail: ExternalDetail | None = None
|
||||
# "ask": a document that is already present at the account's check level answers 409.
|
||||
# "insert": the user chose to insert it again. `bind_element_id` binds that element instead of creating one.
|
||||
duplicate: Literal["ask", "insert"] = "ask"
|
||||
bind_element_id: UUID | None = None
|
||||
|
||||
|
||||
class ExistingItemIn(APIModel):
|
||||
source: str = Field(min_length=1, max_length=40)
|
||||
external_id: str = Field(min_length=1, max_length=200)
|
||||
connector_id: UUID | None = None
|
||||
|
||||
|
||||
class ExistingIn(APIModel):
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
items: list[ExistingItemIn] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class ConnectorIn(APIModel):
|
||||
"""Kind is checked against the source registry. Source fields stay optional.
|
||||
|
||||
Paperless and IMAP still send their existing fields. A further module
|
||||
uses ``config`` and validates that bag itself.
|
||||
"""
|
||||
|
||||
kind: str = Field(min_length=1, max_length=40)
|
||||
name: str = Field(min_length=1, max_length=120)
|
||||
base_url: str | None = None
|
||||
token: str | None = None
|
||||
host: str | None = None
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
username: str | None = None
|
||||
password: str | None = None
|
||||
mailbox: str | None = Field(default=None, max_length=200)
|
||||
security: Literal["ssl", "starttls"] | None = None
|
||||
config: dict[str, str | int | None] | None = None
|
||||
|
||||
|
||||
class SourceAssignmentIn(APIModel):
|
||||
connector_id: UUID
|
||||
|
||||
|
||||
class DeleteElementIn(APIModel):
|
||||
@@ -201,3 +441,113 @@ class FulfillIn(APIModel):
|
||||
class TaskDeadlineIn(APIModel):
|
||||
deadline_id: UUID
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TaskElementsIn(APIModel):
|
||||
element_ids: list[UUID] = Field(default_factory=list, max_length=40)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TaskDependencyIn(APIModel):
|
||||
depends_on_task_id: UUID
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ElementReferenceIn(APIModel):
|
||||
refers_to_element_id: UUID
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class ExportIn(APIModel):
|
||||
context: ContextIn | None = None
|
||||
selected: list[str] = Field(default_factory=list, max_length=2000)
|
||||
assignments: dict[str, UUID] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class EvidenceIn(APIModel):
|
||||
element_id: UUID
|
||||
role: Literal["email", "submission", "delivery", "other"]
|
||||
fold: Literal["keep", "evidence"] = "keep"
|
||||
|
||||
|
||||
class AttachmentAssignIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
attachment_element_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
fold: Literal["keep", "attachment"] = "keep"
|
||||
|
||||
|
||||
class AttachmentOrderIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
attachment_element_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class AttachmentDetachIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
|
||||
|
||||
class FoldIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
fold: Literal["attachment", "evidence"] | None = None
|
||||
|
||||
|
||||
class DispatchIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
channel: Literal["email", "post", "other"]
|
||||
sent_on: date | None = None
|
||||
counterpart: str | None = Field(default=None, max_length=200)
|
||||
attachment_element_ids: list[UUID] = Field(default_factory=list, max_length=100)
|
||||
evidence: list[EvidenceIn] = Field(default_factory=list, max_length=20)
|
||||
historical_gap: bool = False
|
||||
capture_editions: bool = True
|
||||
|
||||
|
||||
class DispatchEvidenceIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
element_id: UUID
|
||||
role: Literal["email", "submission", "delivery", "other"]
|
||||
fold: Literal["keep", "evidence"] = "keep"
|
||||
|
||||
|
||||
class DispatchEvidenceDetachIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
|
||||
|
||||
class DispatchCorrectIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn
|
||||
placement: ContextIn | None = None
|
||||
channel: Literal["email", "post", "other"] | None = None
|
||||
sent_on: date | None = None
|
||||
clear_sent_on: bool = False
|
||||
counterpart: str | None = Field(default=None, max_length=200)
|
||||
clear_counterpart: bool = False
|
||||
|
||||
|
||||
class PreferenceIn(APIModel):
|
||||
"""`value` replaces the own value; null means: inherit. `team_mode` is for main users and stays as it is when absent."""
|
||||
|
||||
value: str | None = Field(default=None, max_length=40)
|
||||
team_mode: Literal["free", "locked"] | None = None
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,461 @@
|
||||
"""Connector administration and live Paperless / IMAP lookup."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import element_rights, get_element, parse_query_context
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.routes import _created
|
||||
from app.api.schemas import ConnectorIn, ExternalIn, SourceAssignmentIn
|
||||
from app.core.errors import DOWNLOAD_REFUSED, forbidden, not_found, unprocessable, unsupported
|
||||
from app.mailpack import _inline_images, parse_mail, sanitize_html
|
||||
from app.remoteimages import RemoteImages
|
||||
from app.media.storage import content_disposition
|
||||
from app.api.externals import place_external
|
||||
from app.retrieval import RetrievalFailure
|
||||
from app.sourcebind import assign_reference
|
||||
from app.sourceport import capability_payload, with_capabilities
|
||||
from app.sourceregistry import get_source, require_source
|
||||
from app.sources import (
|
||||
connector_detail,
|
||||
delete_connector,
|
||||
imap_preview,
|
||||
list_connectors,
|
||||
owned_connector,
|
||||
paperless_content,
|
||||
parse_connector,
|
||||
probe,
|
||||
save_connector,
|
||||
update_connector,
|
||||
)
|
||||
|
||||
_PRIVATE = {
|
||||
"Cache-Control": "private, no-store",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
}
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/v1/connectors")
|
||||
def get_connectors(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return {"items": list_connectors(conn, principal.account_id)}
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/capabilities")
|
||||
def source_capabilities(principal: Principal = Depends(get_principal)):
|
||||
del principal
|
||||
return capability_payload()
|
||||
|
||||
|
||||
@router.post("/api/v1/connectors", status_code=201)
|
||||
def post_connector(body: ConnectorIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
name, settings, secret = _connector_parts(body, None)
|
||||
row = save_connector(conn, principal.account_id, body.kind, name, settings, secret)
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/api/v1/connectors/{connector_id}")
|
||||
def get_connector(connector_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return connector_detail(conn, principal.account_id, connector_id)
|
||||
|
||||
|
||||
@router.patch("/api/v1/connectors/{connector_id}")
|
||||
def patch_connector(
|
||||
connector_id: UUID,
|
||||
body: ConnectorIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
current = owned_connector(conn, principal.account_id, connector_id)
|
||||
if current["kind"] != body.kind:
|
||||
raise unprocessable("Der Zugang bleibt bei seiner Quellenart.")
|
||||
name, settings, secret = _connector_parts(body, current)
|
||||
return update_connector(conn, principal.account_id, connector_id, name, settings, secret)
|
||||
|
||||
|
||||
@router.delete("/api/v1/connectors/{connector_id}", status_code=204)
|
||||
def remove_connector(connector_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
delete_connector(conn, principal.account_id, connector_id)
|
||||
|
||||
|
||||
@router.post("/api/v1/connectors/{connector_id}/probe")
|
||||
def probe_connector(connector_id: UUID, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
return probe(conn, principal.account_id, connector_id)
|
||||
|
||||
|
||||
@router.get("/api/v1/external-refs/{element_id}/content")
|
||||
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)
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
**_PRIVATE,
|
||||
"Content-Disposition": content_disposition(filename or "dokument.pdf").replace("attachment;", "inline;", 1),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/external-refs/{element_id}/mail")
|
||||
def view_mail(
|
||||
element_id: UUID,
|
||||
context_kind: str | None = None,
|
||||
context_id: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
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 JSONResponse(
|
||||
content={
|
||||
"title": parsed.subject,
|
||||
"message_from": parsed.sender,
|
||||
"message_to": parsed.recipient,
|
||||
"message_cc": parsed.copy,
|
||||
"text": parsed.text,
|
||||
"html": parsed.html,
|
||||
"remote_images": len(parsed.remote_images),
|
||||
"text_truncated": parsed.text_truncated,
|
||||
"complete": not parsed.missing,
|
||||
"notices": parsed.notices,
|
||||
"attachments": [
|
||||
{
|
||||
"index": index,
|
||||
"filename": item.display_name or item.filename,
|
||||
"archive_name": item.filename,
|
||||
"content_type": item.media_type,
|
||||
"byte_size": len(item.data),
|
||||
"inline": item.inline,
|
||||
}
|
||||
for index, item in enumerate(parsed.attachments)
|
||||
],
|
||||
},
|
||||
headers={"Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer"},
|
||||
)
|
||||
|
||||
|
||||
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":
|
||||
raise not_found()
|
||||
context = parse_query_context(context_kind, context_id)
|
||||
rights = element_rights(conn, principal.account_id, element, context)
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
ref = conn.execute(
|
||||
"""
|
||||
SELECT source, external_id, detail, connector_id, resolution
|
||||
FROM external_references WHERE element_id = %s
|
||||
""",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
return element, context, ref
|
||||
|
||||
|
||||
def _complete_mail(conn, principal: Principal, element, context, ref):
|
||||
module = get_source(ref["source"]) if ref is not None else None
|
||||
if module is None or module.representation != "email":
|
||||
raise unprocessable("Das ist keine E-Mail.")
|
||||
opened = module.open_original(conn, principal.account_id, element, context, ref)
|
||||
if isinstance(opened, RetrievalFailure):
|
||||
raise unprocessable(opened.message)
|
||||
raw = opened[0] if isinstance(opened, tuple) else opened
|
||||
parsed = parse_mail(raw)
|
||||
if parsed.missing:
|
||||
names = ", ".join(parsed.missing[:5])
|
||||
raise unprocessable(f"Eine Anlage der E-Mail ließ sich nicht vollständig lesen: {names}.")
|
||||
return parsed, raw
|
||||
|
||||
|
||||
@router.get("/api/v1/external-refs/{element_id}/mail/html-with-images")
|
||||
def view_mail_with_images(
|
||||
element_id: UUID,
|
||||
context_kind: str | None = None,
|
||||
context_id: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""The formatted mail with its pictures from other servers, loaded by the server on request."""
|
||||
element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id)
|
||||
parsed, _raw = _complete_mail(conn, principal, element, context, ref)
|
||||
loader = RemoteImages()
|
||||
rendered = sanitize_html(parsed.html_source, _inline_images(parsed.attachments), remote=loader) if parsed.html_source else ""
|
||||
return JSONResponse(
|
||||
content={"html": rendered, "loaded": loader.loaded, "failed": loader.failed},
|
||||
headers={"Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer"},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/external-refs/{element_id}/mail/original")
|
||||
def download_mail(
|
||||
element_id: UUID,
|
||||
context_kind: str | None = None,
|
||||
context_id: str | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
element, context, ref = _opened_ref(conn, principal, element_id, context_kind, context_id)
|
||||
_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}")
|
||||
def download_mail_attachment(
|
||||
element_id: UUID,
|
||||
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()
|
||||
item = parsed.attachments[index]
|
||||
name = item.display_name or item.filename or "anlage"
|
||||
media = (item.media_type or "application/octet-stream").split(";", 1)[0].strip()
|
||||
if item.data[:1024].lstrip(b"\xef\xbb\xbf\r\n\t ").startswith(b"%PDF"):
|
||||
media = "application/pdf"
|
||||
if not name.lower().endswith(".pdf"):
|
||||
leaf = name.replace("\\", "/").split("/")[-1]
|
||||
name = name if "." in leaf else f"{name}.pdf"
|
||||
return _mail_bytes(item.data, media or "application/octet-stream", name, inline=True)
|
||||
|
||||
|
||||
def _mail_bytes(data: bytes, media_type: str, filename: str, inline: bool = False) -> Response:
|
||||
disposition = content_disposition(filename, inline=inline)
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
**_PRIVATE,
|
||||
"Content-Disposition": disposition,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# These belong to the route. Every other query parameter is a filter the registered module must declare.
|
||||
_ROUTE_PARAMS = frozenset({"q", "connector_id", "mailbox", "before", "uidvalidity"})
|
||||
|
||||
|
||||
def _filters(request: Request) -> dict:
|
||||
return {name: value for name, value in request.query_params.items() if name not in _ROUTE_PARAMS}
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/paperless/documents")
|
||||
def search_paperless(
|
||||
request: Request,
|
||||
q: str = "",
|
||||
connector_id: UUID | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return _run_search("paperless", conn, principal.account_id, q.strip(), connector_id, "", None, _filters(request))
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/{kind}/facets")
|
||||
def source_facets(
|
||||
kind: str,
|
||||
connector_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
module = require_source(kind)
|
||||
if module.facets is None:
|
||||
raise unsupported("Diese Quelle hat keine Auswahllisten.")
|
||||
return module.facets(conn, principal.account_id, connector_id)
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/paperless/documents/{document_id}/preview")
|
||||
def preview_paperless_document(
|
||||
document_id: str,
|
||||
connector_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
data, media, name = paperless_content(conn, principal.account_id, document_id, connector_id)
|
||||
return Response(
|
||||
content=data,
|
||||
media_type=media,
|
||||
headers={**_PRIVATE, "Content-Disposition": content_disposition(name).replace("attachment;", "inline;", 1)},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/{kind}/thumbnail")
|
||||
def thumbnail_source(
|
||||
kind: str,
|
||||
connector_id: UUID,
|
||||
item: str,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
module = require_source(kind)
|
||||
if not module.capabilities["search"].get("result_preview") or module.thumbnail is None:
|
||||
raise unsupported("Diese Quelle hat keine Vorschaubilder.")
|
||||
data, media = module.thumbnail(conn, principal.account_id, connector_id, item)
|
||||
return Response(content=data, media_type=media, headers=_PRIVATE)
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/imap/mailboxes")
|
||||
def list_mailboxes(
|
||||
connector_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return _run_navigate("imap", conn, principal.account_id, connector_id)
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/imap/messages")
|
||||
def search_mail(
|
||||
request: Request,
|
||||
connector_id: UUID,
|
||||
q: str = "",
|
||||
mailbox: str = "",
|
||||
before: int | None = None,
|
||||
uidvalidity: int | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
if before is not None and before < 1:
|
||||
raise unprocessable("Die Seitenangabe ist ungültig.")
|
||||
return _run_search(
|
||||
"imap", conn, principal.account_id, q.strip(), connector_id, mailbox.strip(), before, _filters(request), uidvalidity
|
||||
)
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/imap/message")
|
||||
def read_mail(
|
||||
connector_id: UUID,
|
||||
mailbox: str,
|
||||
uid: int,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
if uid < 1:
|
||||
raise unprocessable("Die Nachricht ist ungültig.")
|
||||
return imap_preview(conn, principal.account_id, connector_id, mailbox.strip(), uid)
|
||||
|
||||
|
||||
@router.post("/api/v1/sources/link", status_code=201)
|
||||
def link_source(body: ExternalIn, principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
if get_source(body.source) is None:
|
||||
raise unprocessable("Verknüpft werden registrierte Quellen.")
|
||||
element = place_external(conn, principal, body)
|
||||
return _created(f"/api/v1/elements/{element['id']}", {"id": str(element["id"]), "title": element["title"]})
|
||||
|
||||
|
||||
@router.post("/api/v1/external-refs/{element_id}/assignment")
|
||||
def assign_source(
|
||||
element_id: UUID,
|
||||
body: SourceAssignmentIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
assign_reference(conn, principal.account_id, element_id, body.connector_id)
|
||||
return {"id": str(element_id), "connector_id": str(body.connector_id), "resolution": "bound"}
|
||||
|
||||
|
||||
def _connector_parts(body: ConnectorIn, current: dict | None) -> tuple[str, dict, str]:
|
||||
"""The registered module validates. Flat fields of the first release are folded into ``config``."""
|
||||
flat = body.model_dump(exclude={"kind", "name", "config"})
|
||||
return parse_connector(body.kind, body.name, flat, body.config, current)
|
||||
|
||||
|
||||
def _run_search(kind: str, conn, owner, query: str, connector_id: UUID | None, mailbox: str, before: int | None, filters: dict, uidvalidity: int | None = None) -> dict:
|
||||
module = require_source(kind)
|
||||
search = module.capabilities["search"]
|
||||
refused = [
|
||||
name
|
||||
for name, value in filters.items()
|
||||
if str(value or "").strip() and not search.get(module.search_params.get(name, ""))
|
||||
]
|
||||
if before is not None and not search.get("continuation"):
|
||||
refused.append("before")
|
||||
if refused:
|
||||
raise unsupported("Diese Suche unterstützt den Filter nicht: " + ", ".join(refused) + ".")
|
||||
options = {"mailbox": mailbox, "before": before}
|
||||
if uidvalidity is not None:
|
||||
options["uidvalidity"] = uidvalidity
|
||||
options.update({key: value for key, value in filters.items() if str(value or "").strip()})
|
||||
found = module.find(conn, owner, connector_id, query, options)
|
||||
bound = str(found.get("connector_id") or connector_id or "")
|
||||
return with_capabilities(kind, bound, found)
|
||||
|
||||
|
||||
def _run_navigate(kind: str, conn, owner, connector_id: UUID) -> dict:
|
||||
module = require_source(kind)
|
||||
if not module.capabilities.get("navigate") or module.navigate is None:
|
||||
raise unsupported("Diese Quelle hat keine Fachnavigation.")
|
||||
return {"items": module.navigate(conn, owner, connector_id)}
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/{kind}/search")
|
||||
def search_source(
|
||||
request: Request,
|
||||
kind: str,
|
||||
q: str = "",
|
||||
connector_id: UUID | None = None,
|
||||
mailbox: str = "",
|
||||
before: int | None = None,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
if before is not None and before < 1:
|
||||
raise unprocessable("Die Seitenangabe ist ungültig.")
|
||||
return _run_search(kind, conn, principal.account_id, q.strip(), connector_id, mailbox.strip(), before, _filters(request))
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/{kind}/navigate")
|
||||
def navigate_source(
|
||||
kind: str,
|
||||
connector_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
return _run_navigate(kind, conn, principal.account_id, connector_id)
|
||||
|
||||
|
||||
@router.get("/api/v1/sources/{kind}/preview")
|
||||
def preview_source(
|
||||
kind: str,
|
||||
connector_id: UUID,
|
||||
mailbox: str = "",
|
||||
uid: int = 0,
|
||||
item: str = "",
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
module = require_source(kind)
|
||||
if not module.capabilities.get("read_preview") or module.preview is None:
|
||||
raise unsupported("Diese Quelle hat keine Vorschau vor dem Übernehmen.")
|
||||
return module.preview(conn, principal.account_id, connector_id, {"mailbox": mailbox, "uid": uid, "item": item})
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Team of a main user and the operator's overview of all teams.
|
||||
|
||||
A main user sees the people in the rooms he owns and manages the employees he invited.
|
||||
The operator sees main users with their employees, rooms and roles: accounts and roles, never content.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import Connection
|
||||
|
||||
from app.access.policy import audit
|
||||
from app.access.roles import require_main_user, require_operator
|
||||
from app.api.deps import Principal, get_conn, get_principal
|
||||
from app.api.rooms import _audit_membership, _drop_shares_of
|
||||
from app.api.schemas import TeamPatchIn
|
||||
from app.auth.accounts import reset_password, set_status
|
||||
from app.core.errors import forbidden
|
||||
from app.core.timeutil import dump_dt
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
_NO_STORE = {"Cache-Control": "no-store"}
|
||||
|
||||
|
||||
def _own_employee(conn, owner_id: UUID, account_id: UUID) -> dict:
|
||||
"""An employee this main user invited. Unknown and foreign accounts answer alike."""
|
||||
row = conn.execute(
|
||||
"SELECT id, status FROM auth_accounts WHERE id = %s AND account_kind = 'employee' AND sponsor_id = %s",
|
||||
(account_id, owner_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise forbidden("Das ist keiner deiner Mitarbeiter.")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/api/v1/team")
|
||||
def team(principal: Principal = Depends(get_principal), conn: Connection = Depends(get_conn)):
|
||||
require_main_user(conn, principal.account_id)
|
||||
me = principal.account_id
|
||||
people = conn.execute(
|
||||
"""
|
||||
SELECT DISTINCT a.id, a.display_name, a.email, a.status, a.account_kind, a.last_login_at,
|
||||
(a.sponsor_id = %s) AS mine
|
||||
FROM auth_accounts a
|
||||
WHERE a.id <> %s AND (
|
||||
a.sponsor_id = %s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = a.id AND m.status = 'active'
|
||||
AND r.kind = 'organization' AND r.owner_id = %s
|
||||
)
|
||||
)
|
||||
ORDER BY a.display_name, a.id
|
||||
""",
|
||||
(me, me, me, me),
|
||||
).fetchall()
|
||||
rooms = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, r.id AS room_id, r.name, r.status, m.role
|
||||
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.status = 'active' AND r.kind = 'organization' AND r.owner_id = %s AND m.subject_id <> %s
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(me, me),
|
||||
).fetchall()
|
||||
by_person: dict = {}
|
||||
for row in rooms:
|
||||
by_person.setdefault(row["subject_id"], []).append(
|
||||
{"room_id": str(row["room_id"]), "name": row["name"], "archived": row["status"] != "active", "role": row["role"]}
|
||||
)
|
||||
return JSONResponse(
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": str(person["id"]),
|
||||
"display_name": person["display_name"],
|
||||
"email": person["email"],
|
||||
"status": person["status"],
|
||||
"account_kind": person["account_kind"],
|
||||
"last_login_at": dump_dt(person["last_login_at"]),
|
||||
"mine": person["mine"],
|
||||
"rooms": by_person.get(person["id"], []),
|
||||
}
|
||||
for person in people
|
||||
]
|
||||
},
|
||||
headers=_NO_STORE,
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/api/v1/team/{account_id}")
|
||||
def patch_team_member(
|
||||
account_id: UUID,
|
||||
body: TeamPatchIn,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_main_user(conn, principal.account_id)
|
||||
_own_employee(conn, principal.account_id, account_id)
|
||||
set_status(conn, principal.account_id, account_id, body.status)
|
||||
return {"id": str(account_id), "status": body.status}
|
||||
|
||||
|
||||
@router.post("/api/v1/team/{account_id}/password-reset")
|
||||
def reset_team_password(
|
||||
account_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
require_main_user(conn, principal.account_id)
|
||||
_own_employee(conn, principal.account_id, account_id)
|
||||
password = reset_password(conn, principal.account_id, account_id)
|
||||
audit(conn, principal.account_id, None, "employee_password_reset", "account", account_id)
|
||||
return JSONResponse({"temporary_password": password}, headers=_NO_STORE)
|
||||
|
||||
|
||||
@router.delete("/api/v1/team/{account_id}/memberships", status_code=204)
|
||||
def remove_from_my_rooms(
|
||||
account_id: UUID,
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""End the memberships of one person in all rooms this main user owns."""
|
||||
require_main_user(conn, principal.account_id)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.room_id FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization' AND r.owner_id = %s
|
||||
FOR UPDATE OF m
|
||||
""",
|
||||
(account_id, principal.account_id),
|
||||
).fetchall()
|
||||
if account_id == principal.account_id or not rows:
|
||||
raise forbidden("Diese Person ist in keinem deiner Räume Mitglied.")
|
||||
for row in rows:
|
||||
room_id = row["room_id"]
|
||||
conn.execute(
|
||||
"UPDATE room_memberships SET status = 'removed' WHERE room_id = %s AND subject_id = %s",
|
||||
(room_id, account_id),
|
||||
)
|
||||
_drop_shares_of(conn, room_id, account_id)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions
|
||||
SET scope_kind = 'personal', scope_id = account_id, epoch = epoch + 1
|
||||
WHERE account_id = %s AND scope_id = %s AND revoked_at IS NULL
|
||||
""",
|
||||
(account_id, room_id),
|
||||
)
|
||||
_audit_membership(conn, principal.account_id, room_id, account_id, "membership_removed")
|
||||
audit(conn, principal.account_id, None, "employee_removed", "account", account_id, detail={"rooms": len(rows)})
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
def _csv_cell(value) -> str:
|
||||
text = "" if value is None else str(value)
|
||||
# A cell that starts like a formula would run in a spreadsheet.
|
||||
return "'" + text if text[:1] in {"=", "+", "-", "@", "\t", "\r"} else text
|
||||
|
||||
|
||||
@router.get("/api/v1/admin/team")
|
||||
def admin_team(
|
||||
format: str = "json",
|
||||
principal: Principal = Depends(get_principal),
|
||||
conn: Connection = Depends(get_conn),
|
||||
):
|
||||
"""Main users with their employees, rooms and roles. Metadata only."""
|
||||
require_operator(conn, principal.account_id)
|
||||
owners = conn.execute(
|
||||
"""
|
||||
SELECT a.id, a.display_name, a.email, a.status
|
||||
FROM auth_accounts a
|
||||
WHERE a.account_kind = 'main'
|
||||
AND (EXISTS (SELECT 1 FROM auth_accounts e WHERE e.sponsor_id = a.id)
|
||||
OR EXISTS (SELECT 1 FROM data_rooms r WHERE r.owner_id = a.id AND r.kind = 'organization'))
|
||||
ORDER BY a.display_name, a.id
|
||||
"""
|
||||
).fetchall()
|
||||
employees = conn.execute(
|
||||
"""
|
||||
SELECT e.id, e.sponsor_id, e.display_name, e.email, e.status, e.last_login_at
|
||||
FROM auth_accounts e WHERE e.account_kind = 'employee'
|
||||
ORDER BY e.display_name, e.id
|
||||
"""
|
||||
).fetchall()
|
||||
memberships = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, r.id AS room_id, r.name, r.status, r.owner_id, m.role
|
||||
FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.status = 'active' AND r.kind = 'organization'
|
||||
ORDER BY r.name, r.id
|
||||
"""
|
||||
).fetchall()
|
||||
rooms_of: dict = {}
|
||||
for row in memberships:
|
||||
rooms_of.setdefault(row["subject_id"], []).append(row)
|
||||
result = []
|
||||
for owner in owners:
|
||||
mine = [e for e in employees if e["sponsor_id"] == owner["id"]]
|
||||
result.append(
|
||||
{
|
||||
"id": str(owner["id"]),
|
||||
"display_name": owner["display_name"],
|
||||
"email": owner["email"],
|
||||
"status": owner["status"],
|
||||
"employees": [
|
||||
{
|
||||
"id": str(e["id"]),
|
||||
"display_name": e["display_name"],
|
||||
"email": e["email"],
|
||||
"status": e["status"],
|
||||
"last_login_at": dump_dt(e["last_login_at"]),
|
||||
"rooms": [
|
||||
{"room_id": str(r["room_id"]), "name": r["name"], "archived": r["status"] != "active", "role": r["role"]}
|
||||
for r in rooms_of.get(e["id"], [])
|
||||
],
|
||||
}
|
||||
for e in mine
|
||||
],
|
||||
}
|
||||
)
|
||||
if format == "csv":
|
||||
out = io.StringIO()
|
||||
writer = csv.writer(out)
|
||||
writer.writerow(["Hauptnutzer", "Mitarbeiter", "E-Mail", "Status", "Datenraum", "Rolle"])
|
||||
for owner in result:
|
||||
for e in owner["employees"]:
|
||||
if not e["rooms"]:
|
||||
writer.writerow([_csv_cell(v) for v in (owner["display_name"], e["display_name"], e["email"], e["status"], "", "")])
|
||||
for room in e["rooms"]:
|
||||
writer.writerow(
|
||||
[_csv_cell(v) for v in (owner["display_name"], e["display_name"], e["email"], e["status"], room["name"], room["role"])]
|
||||
)
|
||||
return Response(
|
||||
content=out.getvalue(),
|
||||
media_type="text/csv; charset=utf-8",
|
||||
headers={"Content-Disposition": 'attachment; filename="team-uebersicht.csv"', **_NO_STORE},
|
||||
)
|
||||
return JSONResponse({"items": result}, headers=_NO_STORE)
|
||||
+269
-19
@@ -1,60 +1,299 @@
|
||||
"""Accounts, personal rooms and sessions."""
|
||||
"""Accounts, personal rooms, sessions and the administrative account actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app.auth.security import hash_password, hash_secret, new_secret, session_expiry
|
||||
from app.core.errors import unprocessable
|
||||
from app.access.policy import audit
|
||||
from app.access.roles import count_active_operators
|
||||
from app.auth.security import (
|
||||
hash_password,
|
||||
hash_secret,
|
||||
new_secret,
|
||||
session_expiry,
|
||||
verify_password,
|
||||
)
|
||||
from app.core.errors import not_found, unprocessable
|
||||
from app.core.settings import Settings
|
||||
|
||||
MIN_PASSWORD = 10
|
||||
MAX_PASSWORD_BYTES = 72
|
||||
|
||||
|
||||
def normalize_email(email: str) -> str:
|
||||
return email.strip().lower()
|
||||
|
||||
|
||||
def create_account(conn, email: str, display_name: str, password: str) -> dict:
|
||||
def check_password_policy(password: str) -> None:
|
||||
if len(password) < MIN_PASSWORD:
|
||||
raise unprocessable(f"Das Passwort braucht mindestens {MIN_PASSWORD} Zeichen.")
|
||||
if len(password.encode("utf-8")) > MAX_PASSWORD_BYTES:
|
||||
raise unprocessable("Das Passwort ist zu lang. Erlaubt sind höchstens 72 Byte.")
|
||||
|
||||
|
||||
def generate_password() -> str:
|
||||
"""A one-time password for hand-over. It is shown once and must be changed at the first login."""
|
||||
return secrets.token_urlsafe(12)
|
||||
|
||||
|
||||
def create_account(
|
||||
conn,
|
||||
email: str,
|
||||
display_name: str,
|
||||
password: str,
|
||||
*,
|
||||
is_superadmin: bool = False,
|
||||
origin: str = "operator",
|
||||
must_change_password: bool = False,
|
||||
account_kind: str = "main",
|
||||
sponsor_id: UUID | None = None,
|
||||
) -> dict:
|
||||
email = normalize_email(email)
|
||||
display_name = display_name.strip()
|
||||
if origin not in {"operator", "fixture"}:
|
||||
raise unprocessable("Die Kontenherkunft ist ungültig.")
|
||||
if account_kind not in {"main", "employee"} or (account_kind == "employee") != (sponsor_id is not None):
|
||||
raise unprocessable("Die Kontoart ist ungültig.")
|
||||
check_password_policy(password)
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (email,)).fetchone():
|
||||
raise unprocessable("Für diese E-Mail gibt es bereits ein Konto.")
|
||||
account_id = uuid4()
|
||||
password_hash = hash_password(password)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_accounts (id, email, display_name, password_hash)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
INSERT INTO auth_accounts (
|
||||
id, email, display_name, password_hash, is_superadmin, origin,
|
||||
must_change_password, password_changed_at, account_kind, sponsor_id
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, now(), %s, %s)
|
||||
""",
|
||||
(account_id, email, display_name, password_hash),
|
||||
(
|
||||
account_id, email, display_name, password_hash, is_superadmin, origin,
|
||||
must_change_password, account_kind, sponsor_id,
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
VALUES (%s, 'personal', 'Persönlicher Raum', %s)
|
||||
INSERT INTO data_rooms (id, kind, name, created_by, owner_id)
|
||||
VALUES (%s, 'personal', 'Persönlicher Raum', %s, %s)
|
||||
""",
|
||||
(account_id, account_id),
|
||||
(account_id, account_id, account_id),
|
||||
)
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name FROM auth_accounts WHERE id = %s",
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, account_kind
|
||||
FROM auth_accounts WHERE id = %s
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def start_session(conn, settings: Settings, account_id: UUID) -> tuple[str, str]:
|
||||
def promote_to_main(conn, actor: UUID, account_id: UUID) -> None:
|
||||
"""Only the operator turns an employee into a main user."""
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if account["account_kind"] == "main":
|
||||
return
|
||||
conn.execute("UPDATE auth_accounts SET account_kind = 'main', sponsor_id = NULL WHERE id = %s", (account_id,))
|
||||
# A raised kind starts from a fresh login.
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "employee_promoted", "account", account_id)
|
||||
|
||||
|
||||
def initial_scope(conn, account_id: UUID) -> tuple[str, UUID]:
|
||||
"""Where a new session starts: the personal room, or for an employee the first team room."""
|
||||
account = conn.execute("SELECT account_kind FROM auth_accounts WHERE id = %s", (account_id,)).fetchone()
|
||||
if account is not None and account["account_kind"] == "employee":
|
||||
room = conn.execute(
|
||||
"""
|
||||
SELECT r.id FROM room_memberships m JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.kind = 'organization' AND r.status = 'active'
|
||||
ORDER BY r.name, r.id LIMIT 1
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
if room is not None:
|
||||
return "organization", room["id"]
|
||||
return "personal", account_id
|
||||
|
||||
|
||||
def start_session(conn, settings: Settings, account_id: UUID, label: str | None = None) -> tuple[str, str]:
|
||||
token = new_secret()
|
||||
csrf = new_secret()
|
||||
conn.execute(
|
||||
scope_kind, scope_id = initial_scope(conn, account_id)
|
||||
session = conn.execute(
|
||||
"""
|
||||
INSERT INTO auth_sessions (
|
||||
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at
|
||||
account_id, secret_hash, csrf_token, scope_kind, scope_id, expires_at, label, last_seen_at
|
||||
)
|
||||
VALUES (%s, %s, %s, 'personal', %s, %s)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, now())
|
||||
RETURNING id
|
||||
""",
|
||||
(account_id, hash_secret(token), csrf, account_id, session_expiry(settings)),
|
||||
)
|
||||
(account_id, hash_secret(token), csrf, scope_kind, scope_id, session_expiry(settings), (label or None) and label[:80]),
|
||||
).fetchone()
|
||||
conn.execute("UPDATE auth_accounts SET last_login_at = now() WHERE id = %s", (account_id,))
|
||||
audit(conn, account_id, None, "session_started", "session", session["id"])
|
||||
return token, csrf
|
||||
|
||||
|
||||
def _account(conn, account_id: UUID, *, lock: bool = False) -> dict:
|
||||
suffix = " FOR UPDATE" if lock else ""
|
||||
row = conn.execute(f"SELECT * FROM auth_accounts WHERE id = %s{suffix}", (account_id,)).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return row
|
||||
|
||||
|
||||
def revoke_sessions(conn, account_id: UUID, *, keep: UUID | None = None) -> int:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
UPDATE auth_sessions SET revoked_at = now()
|
||||
WHERE account_id = %s AND revoked_at IS NULL AND (%s::uuid IS NULL OR id <> %s::uuid)
|
||||
RETURNING id
|
||||
""",
|
||||
(account_id, keep, keep),
|
||||
).fetchall()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def set_display_name(conn, actor: UUID, account_id: UUID, display_name: str) -> None:
|
||||
name = " ".join(display_name.split())
|
||||
if not name or len(name) > 120:
|
||||
raise unprocessable("Der Name ist ungültig.")
|
||||
_account(conn, account_id)
|
||||
conn.execute("UPDATE auth_accounts SET display_name = %s WHERE id = %s", (name, account_id))
|
||||
audit(conn, actor, None, "account_renamed", "account", account_id)
|
||||
|
||||
|
||||
def set_status(conn, actor: UUID, account_id: UUID, status: str) -> None:
|
||||
"""Disable or enable. A disabled account keeps its content, owner links and audit trail."""
|
||||
if status not in {"active", "disabled"}:
|
||||
raise unprocessable("Der Kontostatus ist ungültig.")
|
||||
# Lock the operators first so two parallel changes cannot remove the last one.
|
||||
operators = count_active_operators(conn, lock=True)
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if account["status"] == status:
|
||||
return
|
||||
if status == "disabled":
|
||||
if account_id == actor:
|
||||
raise unprocessable("Du kannst dein eigenes Konto nicht deaktivieren.")
|
||||
owned = _owned_shared_rooms(conn, account_id)
|
||||
if owned:
|
||||
raise unprocessable(
|
||||
f"Das Konto ist Eigentümer von {owned} Datenraum(en) mit weiteren Mitgliedern. "
|
||||
"Der Eigentümer überträgt sie zuerst, oder der Betreiber setzt einen neuen Eigentümer ein."
|
||||
)
|
||||
if account["is_superadmin"] and operators <= 1:
|
||||
raise unprocessable("Der letzte Betreiber lässt sich nicht deaktivieren.")
|
||||
conn.execute(
|
||||
"UPDATE auth_accounts SET status = 'disabled', disabled_at = now(), disabled_by = %s WHERE id = %s",
|
||||
(actor, account_id),
|
||||
)
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "account_disabled", "account", account_id)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE auth_accounts SET status = 'active', disabled_at = NULL, disabled_by = NULL WHERE id = %s",
|
||||
(account_id,),
|
||||
)
|
||||
audit(conn, actor, None, "account_enabled", "account", account_id)
|
||||
|
||||
|
||||
def set_operator(conn, actor: UUID, account_id: UUID, value: bool) -> None:
|
||||
operators = count_active_operators(conn, lock=True)
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if bool(account["is_superadmin"]) == value:
|
||||
return
|
||||
if value:
|
||||
if account["status"] != "active":
|
||||
raise unprocessable("Ein deaktiviertes Konto kann nicht Betreiber werden.")
|
||||
conn.execute("UPDATE auth_accounts SET is_superadmin = true WHERE id = %s", (account_id,))
|
||||
# A raised role starts from a fresh login (Auth blueprint).
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "operator_granted", "account", account_id)
|
||||
return
|
||||
if account["status"] == "active" and operators <= 1:
|
||||
raise unprocessable("Der letzte Betreiber lässt sich nicht zurückstufen.")
|
||||
conn.execute("UPDATE auth_accounts SET is_superadmin = false WHERE id = %s", (account_id,))
|
||||
audit(conn, actor, None, "operator_revoked", "account", account_id)
|
||||
|
||||
|
||||
def reset_password(conn, actor: UUID, account_id: UUID) -> str:
|
||||
if account_id == actor:
|
||||
raise unprocessable("Dein eigenes Passwort änderst du unter Mein Konto.")
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if account["status"] != "active":
|
||||
raise unprocessable("Für ein deaktiviertes Konto lässt sich kein Passwort setzen.")
|
||||
password = generate_password()
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_accounts
|
||||
SET password_hash = %s, must_change_password = true, password_changed_at = now()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(hash_password(password), account_id),
|
||||
)
|
||||
revoke_sessions(conn, account_id)
|
||||
audit(conn, actor, None, "password_reset", "account", account_id)
|
||||
return password
|
||||
|
||||
|
||||
def change_own_password(conn, account_id: UUID, session_id: UUID, current: str, new: str) -> None:
|
||||
account = _account(conn, account_id, lock=True)
|
||||
if not verify_password(current, account["password_hash"]):
|
||||
raise unprocessable("Das aktuelle Passwort ist nicht richtig.")
|
||||
check_password_policy(new)
|
||||
if verify_password(new, account["password_hash"]):
|
||||
raise unprocessable("Das neue Passwort muss sich vom bisherigen unterscheiden.")
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE auth_accounts
|
||||
SET password_hash = %s, must_change_password = false, password_changed_at = now()
|
||||
WHERE id = %s
|
||||
""",
|
||||
(hash_password(new), account_id),
|
||||
)
|
||||
revoke_sessions(conn, account_id, keep=session_id)
|
||||
audit(conn, account_id, None, "password_changed", "account", account_id)
|
||||
|
||||
|
||||
def login_blocked(conn, bucket: str, *, limit: int = 8, minutes: int = 10) -> bool:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM auth_login_attempts
|
||||
WHERE bucket = %s AND attempted_at > now() - make_interval(mins => %s)
|
||||
""",
|
||||
(bucket, minutes),
|
||||
).fetchone()
|
||||
return row["n"] >= limit
|
||||
|
||||
|
||||
def record_failed_login(conn, bucket: str) -> None:
|
||||
"""Committed at once: the failed request rolls back, the count must survive."""
|
||||
conn.execute("DELETE FROM auth_login_attempts WHERE attempted_at < now() - interval '1 day'")
|
||||
conn.execute("INSERT INTO auth_login_attempts (bucket) VALUES (%s)", (bucket,))
|
||||
conn.commit()
|
||||
|
||||
|
||||
def clear_login_attempts(conn, bucket: str) -> None:
|
||||
conn.execute("DELETE FROM auth_login_attempts WHERE bucket = %s", (bucket,))
|
||||
|
||||
|
||||
def _owned_shared_rooms(conn, account_id: UUID) -> int:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT count(*) AS n FROM data_rooms r
|
||||
WHERE r.kind = 'organization' AND r.status = 'active' AND r.owner_id = %s
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = r.id AND m.status = 'active' AND m.subject_id <> %s
|
||||
)
|
||||
""",
|
||||
(account_id, account_id),
|
||||
).fetchone()
|
||||
return int(row["n"])
|
||||
|
||||
|
||||
def list_rooms(conn, account_id: UUID) -> list[dict]:
|
||||
personal = conn.execute(
|
||||
"SELECT id, kind, name FROM data_rooms WHERE id = %s AND kind = 'personal'",
|
||||
@@ -65,7 +304,8 @@ def list_rooms(conn, account_id: UUID) -> list[dict]:
|
||||
rooms.append({"id": str(personal["id"]), "kind": personal["kind"], "name": personal["name"], "role": "owner"})
|
||||
shared = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.kind, r.name, m.role
|
||||
SELECT r.id, r.kind, r.name, m.role, r.owner_id, r.default_visibility,
|
||||
(SELECT count(*) FROM room_memberships x WHERE x.room_id = r.id AND x.status = 'active') AS members
|
||||
FROM room_memberships m
|
||||
JOIN data_rooms r ON r.id = m.room_id
|
||||
WHERE m.subject_id = %s AND m.status = 'active' AND r.status = 'active' AND r.kind = 'organization'
|
||||
@@ -74,5 +314,15 @@ def list_rooms(conn, account_id: UUID) -> list[dict]:
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
for room in shared:
|
||||
rooms.append({"id": str(room["id"]), "kind": room["kind"], "name": room["name"], "role": room["role"]})
|
||||
rooms.append(
|
||||
{
|
||||
"id": str(room["id"]),
|
||||
"kind": room["kind"],
|
||||
"name": room["name"],
|
||||
"role": room["role"],
|
||||
"is_owner": room["owner_id"] == account_id,
|
||||
"private": room["members"] <= 1,
|
||||
"default_visibility": room["default_visibility"],
|
||||
}
|
||||
)
|
||||
return rooms
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from functools import lru_cache
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Request, Response
|
||||
@@ -27,6 +28,33 @@ def verify_password(password: str, password_hash: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _dummy_hash() -> str:
|
||||
return hash_password("kein-konto-nur-zeitausgleich")
|
||||
|
||||
|
||||
def verify_unknown_account(password: str) -> None:
|
||||
"""Spend the same time as a real check so the answer time does not reveal an account."""
|
||||
verify_password(password, _dummy_hash())
|
||||
|
||||
|
||||
def login_bucket(host: str, email: str) -> str:
|
||||
"""Rate-limit key. The address is never stored in the clear."""
|
||||
return hashlib.sha256(f"{host}|{email}".encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
_BROWSERS = (("Edg/", "Edge"), ("OPR/", "Opera"), ("Firefox/", "Firefox"), ("Chrome/", "Chrome"), ("Safari/", "Safari"))
|
||||
_SYSTEMS = (("Windows", "Windows"), ("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"), ("Mac OS", "macOS"), ("Linux", "Linux"))
|
||||
|
||||
|
||||
def device_label(user_agent: str | None) -> str:
|
||||
"""A short, readable hint for the session list. The full user agent is not kept."""
|
||||
agent = user_agent or ""
|
||||
browser = next((name for marker, name in _BROWSERS if marker in agent), "Browser")
|
||||
system = next((name for marker, name in _SYSTEMS if marker in agent), "")
|
||||
return f"{browser} auf {system}" if system else browser
|
||||
|
||||
|
||||
def new_secret() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
+4
-6
@@ -1,4 +1,4 @@
|
||||
"""Operator commands: migrate, seed demo data, create the first account."""
|
||||
"""Operator commands: migrate and create an account. Demo seed stays in the test suite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,6 @@ import argparse
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
@@ -29,13 +28,12 @@ def main() -> None:
|
||||
print("applied" if applied else "up to date")
|
||||
return
|
||||
if args.command == "seed-demo":
|
||||
created = seed_demo(settings)
|
||||
print("seeded" if created else "unchanged")
|
||||
return
|
||||
raise SystemExit("Testdaten legt nur die Test-Suite an und entfernt sie wieder.")
|
||||
if len(args.password) < 10:
|
||||
raise SystemExit("password must be at least 10 characters")
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
account = create_account(conn, args.email, args.name, args.password)
|
||||
has_admin = conn.execute("SELECT 1 FROM auth_accounts WHERE is_superadmin LIMIT 1").fetchone()
|
||||
account = create_account(conn, args.email, args.name, args.password, is_superadmin=has_admin is None)
|
||||
conn.commit()
|
||||
print(account["id"])
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Bounded note documents. Only paragraph text is stored."""
|
||||
"""Bounded note documents. Paragraphs or one Markdown block are stored."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -9,6 +9,11 @@ def clean_document(document: dict) -> dict:
|
||||
blocks = document.get("blocks")
|
||||
if not isinstance(blocks, list) or len(blocks) > 400:
|
||||
raise unprocessable("Die Notiz hat kein gültiges Dokument.")
|
||||
if len(blocks) == 1 and isinstance(blocks[0], dict) and blocks[0].get("type") == "markdown":
|
||||
text = blocks[0].get("text")
|
||||
if not isinstance(text, str) or len(text) > 100_000:
|
||||
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
|
||||
return {"version": 1, "blocks": [{"type": "markdown", "text": text}]}
|
||||
clean = []
|
||||
for block in blocks:
|
||||
if not isinstance(block, dict) or set(block) - {"type", "text"}:
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -50,6 +53,28 @@ def unprocessable(detail: str) -> Problem:
|
||||
return Problem(422, "Eingabe ungültig", detail, "unprocessable")
|
||||
|
||||
|
||||
def unsupported(detail: str) -> Problem:
|
||||
return Problem(422, "Nicht unterstützt", detail, "unsupported")
|
||||
|
||||
|
||||
def scope_changed() -> Problem:
|
||||
return Problem(
|
||||
403,
|
||||
"Datenraum gewechselt",
|
||||
"Der gewählte Datenraum entspricht nicht mehr der Sitzung. Die Ansicht wird neu geladen.",
|
||||
"scope_changed",
|
||||
)
|
||||
|
||||
|
||||
def password_change_required() -> Problem:
|
||||
return Problem(
|
||||
403,
|
||||
"Passwortwechsel erforderlich",
|
||||
"Bitte lege zuerst ein eigenes Passwort fest.",
|
||||
"password_change_required",
|
||||
)
|
||||
|
||||
|
||||
def too_many() -> Problem:
|
||||
return Problem(429, "Zu viele Versuche", "Bitte kurz warten und es erneut versuchen.", "too_many_requests")
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ class Settings(BaseSettings):
|
||||
app_url: str = "http://localhost:5173"
|
||||
allowed_origins: str = "http://localhost:5173,http://localhost:3094"
|
||||
media_root: str = "data/media"
|
||||
paperless_media_root: str = ""
|
||||
seed_demo: bool = False
|
||||
session_ttl_hours: int = 336
|
||||
upload_max_bytes: int = 20 * 1024 * 1024
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -49,9 +49,26 @@ def migrate(settings: Settings | None = None) -> list[str]:
|
||||
)
|
||||
applied.append(version)
|
||||
_ensure_runtime_role(conn, settings)
|
||||
_prepare_source_storage(settings)
|
||||
return applied
|
||||
|
||||
|
||||
def _prepare_source_storage(settings: Settings) -> None:
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from app.media.port import ensure_legacy_instance
|
||||
from app.sourcebind import backfill_source_bindings
|
||||
from app.sources import _install_sources
|
||||
|
||||
# The process that migrates has not imported the application yet.
|
||||
# Without the modules, a legacy reference would stay unresolved.
|
||||
_install_sources()
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
backfill_source_bindings(conn)
|
||||
ensure_legacy_instance(conn, settings.media_root)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _ensure_runtime_role(conn: psycopg.Connection, settings: Settings) -> None:
|
||||
role = sql.Identifier(settings.db_runtime_user)
|
||||
database = sql.Identifier(settings.db_name)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Documents of a source that are inserted into a container again.
|
||||
|
||||
The same document in different Vorgänge stays allowed. This module only finds where a document is
|
||||
already present around the target, so the dialog can warn and the user can decide. Levels (account
|
||||
preference `duplicate_check`):
|
||||
|
||||
- here: bound directly to the target.
|
||||
- inside: also what the target shows: Teilvorgänge of a Vorgang, the linked Vorgänge of an Akte.
|
||||
- around: also where the target lies: its Vorgang, the Akten it is linked to, the parent Akte.
|
||||
|
||||
Only elements the actor may read are reported. A hit outside the actor's rights does not exist here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from app.access.policy import (
|
||||
Ctx,
|
||||
case_rights,
|
||||
element_rights,
|
||||
get_case,
|
||||
get_matter,
|
||||
matter_rights,
|
||||
)
|
||||
from app.core.errors import Problem
|
||||
|
||||
LEVELS = {"off": (), "here": ("here",), "inside": ("here", "inside"), "around": ("here", "inside", "around")}
|
||||
_ORDER = {"here": 0, "inside": 1, "around": 2}
|
||||
|
||||
|
||||
def _stored_connector(row: dict) -> str | None:
|
||||
if row["connector_id"] is not None:
|
||||
return str(row["connector_id"])
|
||||
stored = (row["detail"] or {}).get("connector_id")
|
||||
return str(stored) if stored else None
|
||||
|
||||
|
||||
def _candidates(conn, source: str, external_id: str, connector_id: str | None) -> list[dict]:
|
||||
"""Elements for the same document. `certain` is False when only one side knows the connection."""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT e.id, e.title, e.owner_subject_id, er.connector_id, er.detail
|
||||
FROM external_references er
|
||||
JOIN elements e ON e.id = er.element_id
|
||||
WHERE er.source = %s AND er.external_id = %s AND e.deleted_at IS NULL
|
||||
""",
|
||||
(source, external_id.strip()[:200]),
|
||||
).fetchall()
|
||||
found = []
|
||||
for row in rows:
|
||||
stored = _stored_connector(row)
|
||||
if stored is not None and connector_id is not None and stored != connector_id:
|
||||
continue
|
||||
found.append(row | {"certain": stored == connector_id})
|
||||
return found
|
||||
|
||||
|
||||
def _children(conn, matter_id: UUID) -> list[UUID]:
|
||||
rows = conn.execute("SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL", (matter_id,)).fetchall()
|
||||
return [row["id"] for row in rows]
|
||||
|
||||
|
||||
def _zones(conn, target: Ctx) -> dict[str, list[Ctx]]:
|
||||
inside: list[Ctx] = []
|
||||
around: list[Ctx] = []
|
||||
if target.kind == "matter":
|
||||
inside = [Ctx("matter", child) for child in _children(conn, target.id)]
|
||||
matter = get_matter(conn, target.id)
|
||||
anchors = [target.id]
|
||||
if matter is not None and matter["parent_matter_id"] is not None:
|
||||
around.append(Ctx("matter", matter["parent_matter_id"]))
|
||||
anchors.append(matter["parent_matter_id"])
|
||||
links = conn.execute("SELECT DISTINCT case_id FROM matter_case_links WHERE matter_id = ANY(%s)", (anchors,)).fetchall()
|
||||
around += [Ctx("case", row["case_id"]) for row in links]
|
||||
else:
|
||||
links = conn.execute("SELECT matter_id FROM matter_case_links WHERE case_id = %s", (target.id,)).fetchall()
|
||||
for row in links:
|
||||
inside.append(Ctx("matter", row["matter_id"]))
|
||||
inside += [Ctx("matter", child) for child in _children(conn, row["matter_id"])]
|
||||
case = get_case(conn, target.id)
|
||||
if case is not None and case["parent_case_id"] is not None:
|
||||
around.append(Ctx("case", case["parent_case_id"]))
|
||||
return {"here": [target], "inside": inside, "around": around}
|
||||
|
||||
|
||||
def _blocked(conn, case_id: UUID, element_id: UUID) -> bool:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 FROM case_link_blocks b JOIN matter_case_links l ON l.id = b.link_id
|
||||
WHERE l.case_id = %s AND b.element_id = %s
|
||||
""",
|
||||
(case_id, element_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def _title_if_readable(conn, actor: UUID, container: Ctx) -> str | None:
|
||||
if container.kind == "case":
|
||||
case = get_case(conn, container.id)
|
||||
return case["title"] if case is not None and case_rights(conn, actor, case).read else None
|
||||
matter = get_matter(conn, container.id)
|
||||
return matter["title"] if matter is not None and matter_rights(conn, actor, matter, None).read else None
|
||||
|
||||
|
||||
def find_existing(
|
||||
conn,
|
||||
actor: UUID,
|
||||
source: str,
|
||||
external_id: str,
|
||||
connector_id: str | None,
|
||||
target: Ctx,
|
||||
rights_context: Ctx | None,
|
||||
level: str,
|
||||
) -> list[dict]:
|
||||
"""Matches of one document at the chosen level, readable by the actor, nearest zone first."""
|
||||
zones = LEVELS.get(level, ())
|
||||
if not zones:
|
||||
return []
|
||||
candidates = _candidates(conn, source, external_id, connector_id)
|
||||
if not candidates:
|
||||
return []
|
||||
layout = _zones(conn, target)
|
||||
by_element: dict[UUID, dict] = {}
|
||||
for candidate in candidates:
|
||||
bindings = conn.execute(
|
||||
"SELECT b.context_kind, b.context_id, c.title AS chapter FROM bindings b LEFT JOIN chapters c ON c.id = b.chapter_id WHERE b.element_id = %s",
|
||||
(candidate["id"],),
|
||||
).fetchall()
|
||||
for zone in zones:
|
||||
for container in layout[zone]:
|
||||
hit = next((b for b in bindings if b["context_kind"] == container.kind and b["context_id"] == container.id), None)
|
||||
if hit is None:
|
||||
continue
|
||||
if target.kind == "case" and zone == "inside" and _blocked(conn, target.id, candidate["id"]):
|
||||
continue
|
||||
seen_in = [container] if zone == "around" else [c for c in (target, rights_context) if c is not None]
|
||||
rights = [element_rights(conn, actor, candidate, ctx) for ctx in seen_in]
|
||||
if not any(r.read for r in rights):
|
||||
continue
|
||||
match = {
|
||||
"element_id": str(candidate["id"]),
|
||||
"title": candidate["title"],
|
||||
"where": zone,
|
||||
"certain": candidate["certain"],
|
||||
"chapter": hit["chapter"] if zone == "here" else None,
|
||||
"container": {
|
||||
"kind": container.kind,
|
||||
"title": _title_if_readable(conn, actor, container) if zone != "here" else None,
|
||||
},
|
||||
"can_bind": any(r.share for r in rights),
|
||||
}
|
||||
known = by_element.get(candidate["id"])
|
||||
if known is None or _ORDER[zone] < _ORDER[known["where"]]:
|
||||
by_element[candidate["id"]] = match
|
||||
return sorted(by_element.values(), key=lambda item: (_ORDER[item["where"]], item["title"]))
|
||||
|
||||
|
||||
def already_present(matches: list[dict]) -> Problem:
|
||||
where = {"here": "hier", "inside": "in diesem Bestand", "around": "im Umfeld"}[matches[0]["where"]]
|
||||
return Problem(
|
||||
409,
|
||||
"Bereits vorhanden",
|
||||
f"Dieses Dokument ist {where} schon vorhanden. Füge es nur dann erneut ein, wenn das gewollt ist.",
|
||||
"already_present",
|
||||
)
|
||||
@@ -1,16 +1,24 @@
|
||||
"""Migrate, optionally seed development data, then serve."""
|
||||
"""Migrate, drop leftover fixtures, then serve. Demo seed never runs here."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
from app.db.migrate import migrate
|
||||
from app.seed import seed_demo
|
||||
from app.fixtures import purge_fixture_data
|
||||
|
||||
|
||||
def prepare(settings: Settings | None = None) -> None:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env == "production" and settings.seed_demo:
|
||||
raise SystemExit("SEED_DEMO darf in der Produktion nicht aktiv sein.")
|
||||
migrate(settings)
|
||||
purge_fixture_data(settings)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
migrate()
|
||||
seed_demo()
|
||||
prepare()
|
||||
os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"])
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,203 @@
|
||||
"""Remove fixture accounts and everything that belongs only to them.
|
||||
|
||||
Operator accounts and their cases stay. The test suite calls this after seeding
|
||||
the ephemeral database. Every environment also calls it at startup, so a copied
|
||||
development database cannot carry Ada and Ben into production.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
|
||||
_PURGE = (
|
||||
"""
|
||||
DELETE FROM context_annotations
|
||||
WHERE author_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR binding_id IN (
|
||||
SELECT b.id FROM bindings b
|
||||
JOIN elements e ON e.id = b.element_id
|
||||
WHERE e.owner_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR b.created_by IN (SELECT id FROM fixture_accounts)
|
||||
)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM bindings
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM correspondence_dates
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM note_bodies
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM external_references
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM media_operations
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR asset_id IN (SELECT id FROM media_assets WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM media_assets
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM task_element_links
|
||||
WHERE task_id IN (SELECT id FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM element_references
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR refers_to_element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM task_dependencies
|
||||
WHERE task_id IN (SELECT id FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR depends_on_task_id IN (SELECT id FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM task_deadline_links
|
||||
WHERE task_id IN (SELECT id FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR deadline_id IN (SELECT id FROM deadlines WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE tasks SET assignee_subject_id = NULL
|
||||
WHERE assignee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET assignee_subject_id = NULL
|
||||
WHERE assignee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE tasks SET matter_id = NULL
|
||||
WHERE matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET matter_id = NULL
|
||||
WHERE matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
UPDATE deadlines SET element_id = NULL
|
||||
WHERE element_id IN (SELECT id FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"DELETE FROM tasks WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM deadlines WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
DELETE FROM matter_case_links
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM matter_cross_links
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
OR from_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR to_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
DELETE FROM chapters
|
||||
WHERE case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
OR matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
""",
|
||||
"""
|
||||
UPDATE matters SET parent_matter_id = NULL
|
||||
WHERE parent_matter_id IN (SELECT id FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM matters
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts) AND parent_matter_id IS NOT NULL
|
||||
""",
|
||||
"DELETE FROM matters WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
UPDATE cases SET parent_case_id = NULL
|
||||
WHERE parent_case_id IN (SELECT id FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts))
|
||||
AND owner_subject_id NOT IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM cases
|
||||
WHERE owner_subject_id IN (SELECT id FROM fixture_accounts) AND parent_case_id IS NOT NULL
|
||||
""",
|
||||
"DELETE FROM cases WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM elements WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
DELETE FROM access_grants
|
||||
WHERE grantee_subject_id IN (SELECT id FROM fixture_accounts)
|
||||
OR created_by IN (SELECT id FROM fixture_accounts)
|
||||
""",
|
||||
"DELETE FROM auth_invitations WHERE invited_by IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM auth_sessions WHERE account_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM room_memberships WHERE subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM connectors WHERE owner_id IN (SELECT id FROM fixture_accounts)",
|
||||
"DELETE FROM domain_events WHERE actor_subject_id IN (SELECT id FROM fixture_accounts)",
|
||||
"""
|
||||
UPDATE data_rooms
|
||||
SET created_by = (
|
||||
SELECT m.subject_id FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
ORDER BY m.created_at
|
||||
LIMIT 1
|
||||
)
|
||||
WHERE created_by IN (SELECT id FROM fixture_accounts)
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
)
|
||||
""",
|
||||
"""
|
||||
DELETE FROM data_rooms
|
||||
WHERE id IN (SELECT id FROM fixture_accounts)
|
||||
OR (
|
||||
created_by IN (SELECT id FROM fixture_accounts)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM room_memberships m
|
||||
WHERE m.room_id = data_rooms.id AND m.status = 'active'
|
||||
)
|
||||
)
|
||||
""",
|
||||
"DELETE FROM auth_accounts WHERE id IN (SELECT id FROM fixture_accounts)",
|
||||
)
|
||||
|
||||
|
||||
def purge_fixture_data(settings: Settings | None = None) -> int:
|
||||
settings = settings or get_settings()
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
fixtures = conn.execute("SELECT id FROM auth_accounts WHERE origin = 'fixture'").fetchall()
|
||||
if not fixtures:
|
||||
conn.rollback()
|
||||
return 0
|
||||
conn.execute("CREATE TEMP TABLE fixture_accounts (id uuid PRIMARY KEY) ON COMMIT DROP")
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO fixture_accounts (id) VALUES (%s)",
|
||||
[(row["id"],) for row in fixtures],
|
||||
)
|
||||
assets = conn.execute(
|
||||
"SELECT id FROM media_assets WHERE owner_subject_id IN (SELECT id FROM fixture_accounts)"
|
||||
).fetchall()
|
||||
for statement in _PURGE:
|
||||
conn.execute(statement)
|
||||
conn.commit()
|
||||
root = Path(settings.media_root)
|
||||
for asset in assets:
|
||||
(root / str(asset["id"])).unlink(missing_ok=True)
|
||||
return len(fixtures)
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Overviews for the library: cases and matters as tiles, and what lies in a room.
|
||||
|
||||
A room is a virtual folder. Cases and matters stay where they are; a share puts them into a room.
|
||||
Counts only include what the person may read. Hidden entries are neither named nor counted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from uuid import UUID
|
||||
|
||||
from app.access.policy import (
|
||||
ROOM_RIGHTS,
|
||||
Ctx,
|
||||
Rights,
|
||||
case_rights,
|
||||
get_case,
|
||||
list_cases,
|
||||
list_matters,
|
||||
matter_rights,
|
||||
room_name,
|
||||
)
|
||||
from app.present import _chapters, _matter_tree, case_summary, matter_summary
|
||||
|
||||
|
||||
def shared_rooms(conn, kind: str, resource_id: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, s.access FROM room_shares s JOIN data_rooms r ON r.id = s.room_id
|
||||
WHERE s.resource_kind = %s AND s.resource_id = %s
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(kind, resource_id),
|
||||
).fetchall()
|
||||
return [{"id": str(row["id"]), "name": row["name"], "access": row["access"]} for row in rows]
|
||||
|
||||
|
||||
def readable_matter_count(conn, actor: UUID, case: dict) -> int:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.* FROM matter_case_links l JOIN matters m ON m.id = l.matter_id
|
||||
WHERE l.case_id = %s AND m.deleted_at IS NULL AND m.parent_matter_id IS NULL
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall()
|
||||
context = Ctx("case", case["id"])
|
||||
return sum(1 for matter in rows if matter_rights(conn, actor, matter, context).read)
|
||||
|
||||
|
||||
def case_items(conn, actor: UUID, visible: list[tuple[dict, Rights]]) -> list[dict]:
|
||||
children = Counter(case["parent_case_id"] for case, _ in visible if case["parent_case_id"])
|
||||
items = []
|
||||
for case, rights in visible:
|
||||
summary = case_summary(case, rights)
|
||||
owner = case["owner_subject_id"] == actor
|
||||
summary["home_scope_name"] = room_name(conn, case["home_scope_id"])
|
||||
summary["kind_label"] = "Unterakte" if case["parent_case_id"] else "Akte"
|
||||
summary["parent_title"] = None
|
||||
summary["is_owner"] = owner
|
||||
summary["shared_with"] = shared_rooms(conn, "case", case["id"]) if owner else []
|
||||
summary["child_cases"] = children.get(case["id"], 0)
|
||||
summary["matter_count"] = readable_matter_count(conn, actor, case)
|
||||
if case["parent_case_id"]:
|
||||
parent = get_case(conn, case["parent_case_id"])
|
||||
if parent is not None and case_rights(conn, actor, parent).read:
|
||||
summary["parent_title"] = parent["title"]
|
||||
items.append(summary)
|
||||
return items
|
||||
|
||||
|
||||
def matter_items(conn, actor: UUID, visible: list[tuple[dict, list[dict]]]) -> list[dict]:
|
||||
children = Counter(matter["parent_matter_id"] for matter, _ in visible if matter["parent_matter_id"])
|
||||
items = []
|
||||
for matter, _contexts in visible:
|
||||
summary = matter_summary(conn, actor, matter)
|
||||
summary["child_matters"] = children.get(matter["id"], 0)
|
||||
items.append(summary)
|
||||
return items
|
||||
|
||||
|
||||
def room_contents(conn, actor: UUID, room_id: UUID) -> tuple[list[tuple[dict, Rights]], list[tuple[dict, list[dict]]]]:
|
||||
"""Cases and matters shared with the room that the person may read, with their readable sub-entries."""
|
||||
rows = conn.execute(
|
||||
"SELECT resource_kind, resource_id FROM room_shares WHERE room_id = %s",
|
||||
(room_id,),
|
||||
).fetchall()
|
||||
case_ids = {row["resource_id"] for row in rows if row["resource_kind"] == "case"}
|
||||
matter_ids = {row["resource_id"] for row in rows if row["resource_kind"] == "matter"}
|
||||
cases = [
|
||||
(case, rights)
|
||||
for case, rights in list_cases(conn, actor)
|
||||
if case["id"] in case_ids
|
||||
or (case["rights_mode"] == "inherit_parent" and case["parent_case_id"] in case_ids)
|
||||
]
|
||||
matters = [
|
||||
(matter, contexts)
|
||||
for matter, contexts in list_matters(conn, actor)
|
||||
if matter["id"] in matter_ids or matter["parent_matter_id"] in matter_ids
|
||||
]
|
||||
return cases, matters
|
||||
|
||||
|
||||
def room_effect(conn, room_id: UUID, actor: UUID, access: str) -> list[dict]:
|
||||
"""Who gets which rights through a share with this room."""
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.subject_id, m.role, a.display_name
|
||||
FROM room_memberships m JOIN auth_accounts a ON a.id = m.subject_id
|
||||
WHERE m.room_id = %s AND m.status = 'active' AND a.status = 'active' AND m.subject_id <> %s
|
||||
ORDER BY a.display_name, a.id
|
||||
""",
|
||||
(room_id, actor),
|
||||
).fetchall()
|
||||
effect = []
|
||||
for row in rows:
|
||||
rights = ROOM_RIGHTS.get(row["role"], Rights())
|
||||
if access == "read":
|
||||
rights = Rights(read=rights.read)
|
||||
effect.append(
|
||||
{
|
||||
"display_name": row["display_name"],
|
||||
"role": row["role"],
|
||||
"rights": {"read": rights.read, "edit": rights.edit},
|
||||
}
|
||||
)
|
||||
return effect
|
||||
|
||||
|
||||
def case_outline(conn, actor: UUID, case: dict) -> dict:
|
||||
"""What the navigation tree shows below a case. Only readable entries; no bindings or texts."""
|
||||
chapters = _chapters(conn, "case", case["id"], case.get("content_order") or "position", case.get("content_order_dir") or "asc")
|
||||
subcases = []
|
||||
for row in conn.execute(
|
||||
"SELECT * FROM cases WHERE parent_case_id = %s AND deleted_at IS NULL ORDER BY title, id",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
if case_rights(conn, actor, row).read:
|
||||
subcases.append({"id": str(row["id"]), "title": row["title"], "status": row["record_status"]})
|
||||
linked = []
|
||||
for link in conn.execute(
|
||||
"""
|
||||
SELECT m.* FROM matter_case_links l JOIN matters m ON m.id = l.matter_id
|
||||
WHERE l.case_id = %s AND m.deleted_at IS NULL ORDER BY m.title, m.id
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
if matter_rights(conn, actor, link, Ctx("case", case["id"])).read:
|
||||
linked.append(link)
|
||||
return {
|
||||
"kind": "case",
|
||||
"id": str(case["id"]),
|
||||
"chapters": chapters,
|
||||
"subcases": subcases,
|
||||
"matters": _matter_tree(conn, actor, case["id"], linked),
|
||||
}
|
||||
|
||||
|
||||
def matter_outline(conn, actor: UUID, matter: dict, context: Ctx | None) -> dict:
|
||||
"""What the navigation tree shows below a matter: its chapters and its readable Teilvorgänge."""
|
||||
chapters = _chapters(
|
||||
conn, "matter", matter["id"], matter.get("content_order") or "position", matter.get("content_order_dir") or "asc"
|
||||
)
|
||||
children = []
|
||||
for row in conn.execute(
|
||||
"SELECT * FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL ORDER BY title, id",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
if matter_rights(conn, actor, row, context).read:
|
||||
children.append({"id": str(row["id"]), "title": row["title"], "status": row["record_status"]})
|
||||
return {"kind": "matter", "id": str(matter["id"]), "chapters": chapters, "submatters": children}
|
||||
@@ -0,0 +1,518 @@
|
||||
"""Pure mail identity and attachment extraction for a complete export.
|
||||
|
||||
A preview cutoff does not belong here. Duplicate attachment names stay distinct.
|
||||
The same tree feeds preview, reading, attachment download and export.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import html
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from email import policy
|
||||
from email.header import decode_header, make_header
|
||||
from email.message import EmailMessage
|
||||
from email.parser import BytesParser
|
||||
from email.utils import parsedate_to_datetime
|
||||
from html.parser import HTMLParser
|
||||
|
||||
_UID_PREFIX = "uid:"
|
||||
_POLICY = policy.default
|
||||
_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", "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)
|
||||
|
||||
|
||||
class MailIdentityError(Exception):
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AttachmentBytes:
|
||||
filename: str
|
||||
media_type: str
|
||||
data: bytes
|
||||
sha256: str
|
||||
display_name: str = ""
|
||||
content_id: str = ""
|
||||
inline: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParsedMail:
|
||||
message_id: str
|
||||
subject: str
|
||||
sender: str
|
||||
recipient: str
|
||||
copy: str
|
||||
text: str
|
||||
attachments: list[AttachmentBytes] = field(default_factory=list)
|
||||
missing: list[str] = field(default_factory=list)
|
||||
html: str = ""
|
||||
html_source: str = ""
|
||||
remote_images: list[str] = field(default_factory=list)
|
||||
notices: list[str] = field(default_factory=list)
|
||||
text_truncated: bool = False
|
||||
document_on: str | None = None
|
||||
|
||||
|
||||
def header_message_id(raw: bytes) -> str:
|
||||
message = BytesParser(policy=_POLICY).parsebytes(raw)
|
||||
return str(message.get("Message-ID") or "").strip()
|
||||
|
||||
|
||||
def identities_match(found: str | None, expected: str | None) -> bool:
|
||||
"""A stored uid fallback matches only a message that still has no Message-ID."""
|
||||
expected_text = (expected or "").strip()
|
||||
found_text = (found or "").strip()
|
||||
if expected_text.casefold().startswith(_UID_PREFIX):
|
||||
return found_text == ""
|
||||
if not expected_text or not found_text:
|
||||
return False
|
||||
return _bare(expected_text) == _bare(found_text)
|
||||
|
||||
|
||||
def choose_message(candidate: bytes | None, alternates: list[bytes], expected: str) -> bytes:
|
||||
"""Keep the stored message when it still matches. Otherwise accept one unambiguous hit."""
|
||||
if candidate is not None and identities_match(header_message_id(candidate), expected):
|
||||
return candidate
|
||||
if (expected or "").strip().casefold().startswith(_UID_PREFIX):
|
||||
raise MailIdentityError("Die gespeicherte Nachricht lässt sich nicht eindeutig wiederfinden.")
|
||||
matches = [raw for raw in alternates if identities_match(header_message_id(raw), expected)]
|
||||
if len(matches) == 1:
|
||||
return matches[0]
|
||||
if len(matches) > 1:
|
||||
raise MailIdentityError("Die Nachrichtenidentität ist mehrdeutig. Es wurde keine E-Mail übernommen.")
|
||||
raise MailIdentityError("Die gespeicherte Nachricht lässt sich nicht eindeutig wiederfinden.")
|
||||
|
||||
|
||||
def header_text(value) -> str:
|
||||
"""Decode encoded-words. A raw MIME header is not a display name."""
|
||||
if value is None:
|
||||
return ""
|
||||
raw = str(value).replace("\r", " ").replace("\n", " ")
|
||||
try:
|
||||
text = str(make_header(decode_header(raw)))
|
||||
except (UnicodeError, LookupError, ValueError):
|
||||
text = raw
|
||||
return re.sub(r"\s+", " ", text).strip()
|
||||
|
||||
|
||||
def parse_mail(raw: bytes) -> ParsedMail:
|
||||
message = BytesParser(policy=_POLICY).parsebytes(raw)
|
||||
attachments: list[AttachmentBytes] = []
|
||||
missing: list[str] = []
|
||||
notices: list[str] = []
|
||||
used: set[str] = set()
|
||||
plain: list[str] = []
|
||||
html_parts: list[str] = []
|
||||
index = 0
|
||||
for kind, part in _walk(message):
|
||||
if kind == "message":
|
||||
index += 1
|
||||
label = header_text(part.get_filename()) or f"nachricht-{index}.eml"
|
||||
data = _message_bytes(part)
|
||||
if data is None:
|
||||
missing.append(label)
|
||||
notices.append(f"Die angehängte Nachricht {label} ließ sich nicht vollständig lesen.")
|
||||
continue
|
||||
name = _unique_filename(label, used)
|
||||
attachments.append(_attachment(part, name, label, data, inline=False))
|
||||
continue
|
||||
disposition = (part.get_content_disposition() or "").lower()
|
||||
media = part.get_content_type()
|
||||
filename = part.get_filename()
|
||||
content_id = _content_id(part)
|
||||
body = media in {"text/plain", "text/html"} and disposition != "attachment" and not filename
|
||||
if body:
|
||||
text = _decoded_text(part)
|
||||
if text is None:
|
||||
notices.append("Ein Textteil ließ sich nicht sicher dekodieren.")
|
||||
continue
|
||||
if media == "text/plain":
|
||||
plain.append(text)
|
||||
else:
|
||||
html_parts.append(text)
|
||||
continue
|
||||
if not filename and disposition != "attachment" and not content_id:
|
||||
continue
|
||||
index += 1
|
||||
label = header_text(filename) if filename else f"anlage-{index}.bin"
|
||||
data = _leaf_bytes(part)
|
||||
if data is None:
|
||||
missing.append(label or f"Anlage {index}")
|
||||
notices.append(f"Die Anlage {label or index} ließ sich nicht vollständig lesen.")
|
||||
continue
|
||||
data = _unwrap_pdf_payload(data, media, label)
|
||||
if _is_pdf(data):
|
||||
media = "application/pdf"
|
||||
label = _pdf_filename(label)
|
||||
name = _unique_filename(label or f"anlage-{index}.bin", used)
|
||||
inline = disposition == "inline" or bool(content_id)
|
||||
attachments.append(_attachment(part, name, label or name, data, inline=inline, media=media))
|
||||
simplified = "\n".join(chunk for chunk in plain if chunk).strip()
|
||||
rendered = ""
|
||||
if html_parts:
|
||||
source = "\n".join(html_parts)
|
||||
remote_found: list[str] = []
|
||||
rendered = sanitize_html(source, _inline_images(attachments), found=remote_found)
|
||||
if not simplified:
|
||||
simplified = simplified_text("\n".join(html_parts))
|
||||
if missing:
|
||||
notices.append("Mindestens eine Anlage fehlt in der Aufbereitung.")
|
||||
return ParsedMail(
|
||||
message_id=str(message.get("Message-ID") or "").strip(),
|
||||
subject=header_text(message.get("Subject")) or "(ohne Betreff)",
|
||||
sender=header_text(message.get("From")),
|
||||
recipient=header_text(message.get("To")),
|
||||
copy=header_text(message.get("Cc")),
|
||||
text=simplified,
|
||||
attachments=attachments,
|
||||
missing=missing,
|
||||
html=rendered,
|
||||
html_source=source if html_parts else "",
|
||||
remote_images=remote_found if html_parts else [],
|
||||
notices=notices,
|
||||
document_on=_message_date(message.get("Date")),
|
||||
)
|
||||
|
||||
|
||||
def decode_transfer(payload: bytes, charset: str | None) -> str:
|
||||
return bytes(payload).decode(charset or "utf-8", errors="replace")
|
||||
|
||||
|
||||
def simplified_text(value: str) -> str:
|
||||
"""A recognizable plain reading. It is not the formatted view."""
|
||||
class Collector(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.parts: list[str] = []
|
||||
self.skip = 0
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
name = tag.lower()
|
||||
if name in {"script", "style"}:
|
||||
self.skip += 1
|
||||
return
|
||||
if name in {"br", "p", "div", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote"}:
|
||||
self.parts.append("\n")
|
||||
elif name in {"td", "th"}:
|
||||
self.parts.append("\t")
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
name = tag.lower()
|
||||
if name in {"script", "style"} and self.skip:
|
||||
self.skip -= 1
|
||||
return
|
||||
if name in {"p", "div", "tr", "li", "table", "h1", "h2", "h3", "h4", "h5", "h6"}:
|
||||
self.parts.append("\n")
|
||||
|
||||
def handle_data(self, data):
|
||||
if not self.skip:
|
||||
self.parts.append(data)
|
||||
|
||||
collector = Collector()
|
||||
try:
|
||||
collector.feed(value)
|
||||
collector.close()
|
||||
except Exception:
|
||||
return ""
|
||||
text = "".join(collector.parts)
|
||||
text = text.replace("\r", "")
|
||||
text = re.sub(r"[ \t]+\n", "\n", text)
|
||||
text = re.sub(r"\n{3,}", "\n\n", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def sanitize_html(value: str, images: dict[str, str] | None = None, *, remote=None, found: list[str] | None = None) -> str:
|
||||
"""Keep a formatted reading. Scripts and active content stay out.
|
||||
|
||||
Pictures from other servers stay out too, unless `remote` turns an address into an inline picture.
|
||||
`found` collects the addresses that were met."""
|
||||
images = images or {}
|
||||
|
||||
class Cleaner(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.parts: list[str] = []
|
||||
self.skip = 0
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
name = tag.lower()
|
||||
if name in {"script", "style", "iframe", "object", "embed", "form", "link", "meta"}:
|
||||
self.skip += 1
|
||||
return
|
||||
if self.skip or name not in _ALLOWED_TAGS:
|
||||
return
|
||||
rendered = _clean_attrs(name, attrs, images, remote, found)
|
||||
if rendered is None:
|
||||
return
|
||||
self.parts.append(f"<{name}{rendered}>")
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
name = tag.lower()
|
||||
if name in {"script", "style", "iframe", "object", "embed", "form", "link", "meta"}:
|
||||
if self.skip:
|
||||
self.skip -= 1
|
||||
return
|
||||
if self.skip or name not in _ALLOWED_TAGS or name in _VOID_TAGS:
|
||||
return
|
||||
self.parts.append(f"</{name}>")
|
||||
|
||||
def handle_data(self, data):
|
||||
if not self.skip:
|
||||
self.parts.append(html.escape(data))
|
||||
|
||||
def handle_entityref(self, name):
|
||||
if not self.skip:
|
||||
self.parts.append(f"&{name};")
|
||||
|
||||
def handle_charref(self, name):
|
||||
if not self.skip:
|
||||
self.parts.append(f"&#{name};")
|
||||
|
||||
cleaner = Cleaner()
|
||||
try:
|
||||
cleaner.feed(value)
|
||||
cleaner.close()
|
||||
except Exception:
|
||||
return ""
|
||||
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], remote=None, found: list[str] | None = None) -> str | None:
|
||||
kept: list[str] = []
|
||||
for key, value in attrs:
|
||||
name = (key or "").lower()
|
||||
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)}" title="{html.escape(target, quote=True)}"')
|
||||
elif tag == "img" and name == "src":
|
||||
source = (value or "").strip()
|
||||
if source.lower().startswith("cid:"):
|
||||
token = source[4:].strip().strip("<>")
|
||||
source = images.get(token.casefold(), "")
|
||||
elif re.match(r"https://", source, re.IGNORECASE):
|
||||
if found is not None and source not in found:
|
||||
found.append(source)
|
||||
source = remote(source) if remote is not None else ""
|
||||
if not _DATA_IMAGE.match(source):
|
||||
continue
|
||||
kept.append(f' src="{source}"')
|
||||
elif tag == "img" and name == "alt":
|
||||
kept.append(f' alt="{html.escape(value or "", quote=True)}"')
|
||||
elif name in {"colspan", "rowspan"} and str(value or "").isdigit():
|
||||
kept.append(f" {name}=\"{int(value)}\"")
|
||||
if tag == "img" and not any(item.startswith(" src=") for item in kept):
|
||||
return None
|
||||
if tag == "a":
|
||||
kept.append(' rel="noreferrer noopener" target="_blank"')
|
||||
return "".join(kept)
|
||||
|
||||
|
||||
def _walk(message: EmailMessage):
|
||||
if message.get_content_maintype() == "message" and message.get_content_subtype() == "rfc822":
|
||||
yield "message", message
|
||||
return
|
||||
if message.is_multipart():
|
||||
for child in message.iter_parts():
|
||||
yield from _walk(child)
|
||||
return
|
||||
yield "leaf", message
|
||||
|
||||
|
||||
def _decoded_text(part: EmailMessage) -> str | None:
|
||||
try:
|
||||
payload = part.get_payload(decode=True)
|
||||
except Exception:
|
||||
return None
|
||||
if not isinstance(payload, (bytes, bytearray)):
|
||||
raw = part.get_payload()
|
||||
return raw.strip() if isinstance(raw, str) else None
|
||||
charset = part.get_content_charset() or "utf-8"
|
||||
try:
|
||||
return decode_transfer(bytes(payload), charset).strip()
|
||||
except LookupError:
|
||||
return decode_transfer(bytes(payload), "utf-8").strip()
|
||||
|
||||
|
||||
def _leaf_bytes(part: EmailMessage) -> bytes | None:
|
||||
try:
|
||||
payload = part.get_payload(decode=True)
|
||||
except Exception:
|
||||
return None
|
||||
if isinstance(payload, (bytes, bytearray)):
|
||||
return bytes(payload)
|
||||
return None
|
||||
|
||||
|
||||
def _message_bytes(part: EmailMessage) -> bytes | None:
|
||||
payload = part.get_payload()
|
||||
if isinstance(payload, list) and payload:
|
||||
inner = payload[0]
|
||||
if isinstance(inner, EmailMessage):
|
||||
return inner.as_bytes()
|
||||
data = _leaf_bytes(part)
|
||||
return data or None
|
||||
|
||||
|
||||
def _content_id(part: EmailMessage) -> str:
|
||||
token = str(part.get("Content-ID") or "").strip().strip("<>").strip()
|
||||
return token
|
||||
|
||||
|
||||
def _is_pdf(data: bytes) -> bool:
|
||||
return data[:1024].lstrip(b"\xef\xbb\xbf\r\n\t ").startswith(b"%PDF")
|
||||
|
||||
|
||||
def _unwrap_pdf_payload(data: bytes, media: str, name: str) -> bytes:
|
||||
"""A PDF that arrived as undecoded Base64 is still the PDF, not the transfer text."""
|
||||
if _is_pdf(data):
|
||||
return data
|
||||
declared = (media or "").split(";", 1)[0].strip().lower()
|
||||
hinted = "pdf" in declared or (name or "").lower().endswith(".pdf") or declared in {
|
||||
"application/octet-stream",
|
||||
"application/x-octet-stream",
|
||||
"binary/octet-stream",
|
||||
}
|
||||
if not hinted:
|
||||
return data
|
||||
stripped = b"".join(data.split())
|
||||
if len(stripped) < 16 or re.fullmatch(rb"[A-Za-z0-9+/=]+", stripped) is None:
|
||||
return data
|
||||
try:
|
||||
decoded = base64.b64decode(stripped, validate=True)
|
||||
except Exception:
|
||||
return data
|
||||
return decoded if _is_pdf(decoded) else data
|
||||
|
||||
|
||||
def _pdf_filename(name: str) -> str:
|
||||
text = (name or "").strip() or "anlage"
|
||||
if text.lower().endswith(".pdf"):
|
||||
return text
|
||||
if text.lower().endswith(".bin"):
|
||||
text = text[:-4].rstrip(" .") or "anlage"
|
||||
leaf = text.replace("\\", "/").split("/")[-1]
|
||||
if "." in leaf:
|
||||
return text
|
||||
return f"{text}.pdf"
|
||||
|
||||
|
||||
def _attachment(part: EmailMessage, filename: str, label: str, data: bytes, inline: bool, media: str | None = None) -> AttachmentBytes:
|
||||
resolved = (media or part.get_content_type() or "application/octet-stream").split(";", 1)[0].strip()
|
||||
return AttachmentBytes(
|
||||
filename=filename,
|
||||
media_type=(resolved or "application/octet-stream")[:120],
|
||||
data=data,
|
||||
sha256=hashlib.sha256(data).hexdigest(),
|
||||
display_name=label or filename,
|
||||
content_id=_content_id(part),
|
||||
inline=inline,
|
||||
)
|
||||
|
||||
|
||||
def _inline_images(attachments: list[AttachmentBytes]) -> dict[str, str]:
|
||||
import base64
|
||||
|
||||
images: dict[str, str] = {}
|
||||
for item in attachments:
|
||||
if not item.content_id or not item.media_type.startswith("image/"):
|
||||
continue
|
||||
if len(item.data) > 1_500_000:
|
||||
continue
|
||||
subtype = item.media_type.split("/", 1)[1].split(";", 1)[0].lower()
|
||||
if subtype == "jpg":
|
||||
subtype = "jpeg"
|
||||
if subtype not in {"png", "jpeg", "gif", "webp"}:
|
||||
continue
|
||||
encoded = base64.b64encode(item.data).decode("ascii")
|
||||
images[item.content_id.casefold()] = f"data:image/{subtype};base64,{encoded}"
|
||||
return images
|
||||
|
||||
|
||||
def _message_date(value) -> str | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return parsedate_to_datetime(str(value)).date().isoformat()
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
|
||||
|
||||
def _bare(value: str) -> str:
|
||||
return value.strip().strip("<>").strip().casefold()
|
||||
|
||||
|
||||
def _unique_filename(name: str, used: set[str]) -> str:
|
||||
cleaned = name.replace("\\", "/").split("/")[-1].strip() or "anlage.bin"
|
||||
cleaned = re.sub(r"[\r\n\x00]", "", cleaned)[:180] or "anlage.bin"
|
||||
if cleaned not in used:
|
||||
used.add(cleaned)
|
||||
return cleaned
|
||||
stem, dot, ext = cleaned.rpartition(".")
|
||||
if not dot or not stem:
|
||||
stem, ext = cleaned, ""
|
||||
else:
|
||||
ext = f".{ext}"
|
||||
number = 2
|
||||
while True:
|
||||
candidate = f"{stem} ({number}){ext}"
|
||||
if candidate not in used:
|
||||
used.add(candidate)
|
||||
return candidate
|
||||
number += 1
|
||||
@@ -9,7 +9,18 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
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.externals import router as externals_router
|
||||
from app.api.library import router as library_router
|
||||
from app.api.preferences import router as preferences_router
|
||||
from app.api.rooms import router as rooms_router
|
||||
from app.api.roomshare import router as roomshare_router
|
||||
from app.api.team import router as team_router
|
||||
from app.api.routes import router
|
||||
from app.api.sources import router as sources_router
|
||||
from app.core.errors import Problem, problem_response
|
||||
from app.core.settings import get_settings
|
||||
from app.db.pool import open_pool
|
||||
@@ -113,6 +124,17 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
|
||||
app.include_router(router)
|
||||
app.include_router(accounts_router)
|
||||
app.include_router(library_router)
|
||||
app.include_router(rooms_router)
|
||||
app.include_router(roomshare_router)
|
||||
app.include_router(team_router)
|
||||
app.include_router(sources_router)
|
||||
app.include_router(export_router)
|
||||
app.include_router(downloads_router)
|
||||
app.include_router(preferences_router)
|
||||
app.include_router(externals_router)
|
||||
app.include_router(correspondence_router)
|
||||
return app
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
"""Opaque storage port. The adapter stores bytes and does not decide who may read them.
|
||||
|
||||
Cleartext for a reader goes through require_cleartext. Locked profiles stay
|
||||
bytes on disk and are not decrypted here. No new cryptography is implemented.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import Problem, storage_unavailable, unprocessable
|
||||
from app.media.storage import read_bytes, sha256, write_bytes
|
||||
|
||||
LEGACY_GENERATION = "legacy-local-1"
|
||||
LEGACY_PROFILE = "legacy-plaintext"
|
||||
LOCKED_PROFILES = frozenset({"managed-encrypted", "client-encrypted"})
|
||||
PROFILES = frozenset({LEGACY_PROFILE, *LOCKED_PROFILES})
|
||||
|
||||
|
||||
def require_cleartext(profile: str | None) -> None:
|
||||
name = profile or LEGACY_PROFILE
|
||||
if name == LEGACY_PROFILE:
|
||||
return
|
||||
if name in LOCKED_PROFILES:
|
||||
raise Problem(
|
||||
422,
|
||||
"Geschützter Inhalt",
|
||||
"Dieser Inhalt ist geschützt. Ein Klartextabruf ist in dieser Lieferung nicht möglich.",
|
||||
"unsupported",
|
||||
)
|
||||
raise Problem(
|
||||
422,
|
||||
"Nicht unterstützt",
|
||||
"Dieses Schutzprofil wird nicht unterstützt.",
|
||||
"unsupported",
|
||||
)
|
||||
|
||||
|
||||
def check_object_key(object_key: str) -> str:
|
||||
key = (object_key or "").replace("\\", "/").strip()
|
||||
parts = key.split("/")
|
||||
if not key or key.startswith("/") or any(part in {"", ".", ".."} for part in parts):
|
||||
raise unprocessable("Ungültiger Speicherpfad.")
|
||||
try:
|
||||
if len(parts) == 1:
|
||||
UUID(parts[0])
|
||||
elif len(parts) == 2 and parts[0] == "dispatch":
|
||||
UUID(parts[1])
|
||||
else:
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
raise unprocessable("Ungültiger Speicherpfad.") from None
|
||||
return key
|
||||
|
||||
|
||||
def object_path(root: Path, object_key: str) -> Path:
|
||||
key = check_object_key(object_key)
|
||||
base = Path(root).resolve()
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
target = (base / key).resolve()
|
||||
if base != target and base not in target.parents:
|
||||
raise unprocessable("Ungültiger Speicherpfad.")
|
||||
return target
|
||||
|
||||
|
||||
class LocalAdapter:
|
||||
"""Files stay under one recorded root. A client path is not an address."""
|
||||
|
||||
def __init__(self, root: str | Path) -> None:
|
||||
self.root = Path(root)
|
||||
|
||||
def put(self, object_key: str, data: bytes) -> None:
|
||||
path = object_path(self.root, object_key)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
write_bytes(path, data)
|
||||
|
||||
def open(self, object_key: str) -> bytes:
|
||||
return read_bytes(object_path(self.root, object_key))
|
||||
|
||||
def delete(self, object_key: str) -> None:
|
||||
path = object_path(self.root, object_key)
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
def describe(self, object_key: str) -> dict:
|
||||
path = object_path(self.root, object_key)
|
||||
try:
|
||||
if not path.is_file():
|
||||
raise storage_unavailable()
|
||||
return {"byte_size": path.stat().st_size, "object_key": object_key}
|
||||
except OSError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
|
||||
class MemoryAdapter:
|
||||
"""In-memory stand-in for the same port. It is not a second product store."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._items: dict[str, bytes] = {}
|
||||
self.fail_put = False
|
||||
|
||||
def put(self, object_key: str, data: bytes) -> None:
|
||||
if self.fail_put:
|
||||
raise storage_unavailable()
|
||||
key = check_object_key(object_key)
|
||||
self._items[key] = bytes(data)
|
||||
|
||||
def open(self, object_key: str) -> bytes:
|
||||
key = check_object_key(object_key)
|
||||
try:
|
||||
return self._items[key]
|
||||
except KeyError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
def delete(self, object_key: str) -> None:
|
||||
key = check_object_key(object_key)
|
||||
self._items.pop(key, None)
|
||||
|
||||
def describe(self, object_key: str) -> dict:
|
||||
data = self.open(object_key)
|
||||
return {"byte_size": len(data), "object_key": object_key}
|
||||
|
||||
|
||||
def publish(adapter, object_key: str, data: bytes) -> None:
|
||||
"""Make bytes readable only after a checked roundtrip. A failed put leaves nothing published."""
|
||||
adapter.put(object_key, data)
|
||||
try:
|
||||
opened = adapter.open(object_key)
|
||||
except Problem:
|
||||
adapter.delete(object_key)
|
||||
raise
|
||||
if opened != data:
|
||||
adapter.delete(object_key)
|
||||
raise storage_unavailable()
|
||||
|
||||
|
||||
def ensure_legacy_instance(conn, media_root: str) -> dict:
|
||||
"""Bind the legacy generation to the current root once. Later roots do not retarget it."""
|
||||
root = str(Path(media_root).resolve())
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO storage_instances (kind, generation, root_path)
|
||||
VALUES ('local', %s, %s)
|
||||
ON CONFLICT (generation) DO NOTHING
|
||||
""",
|
||||
(LEGACY_GENERATION, root),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE storage_instances
|
||||
SET root_path = %s
|
||||
WHERE generation = %s AND root_path IS NULL
|
||||
""",
|
||||
(root, LEGACY_GENERATION),
|
||||
)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, kind, generation, root_path
|
||||
FROM storage_instances
|
||||
WHERE generation = %s
|
||||
""",
|
||||
(LEGACY_GENERATION,),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE media_assets
|
||||
SET storage_instance_id = %s
|
||||
WHERE storage_generation = %s AND storage_instance_id IS NULL
|
||||
""",
|
||||
(row["id"], LEGACY_GENERATION),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE dispatch_snapshots
|
||||
SET storage_instance_id = %s
|
||||
WHERE storage_generation = %s AND storage_instance_id IS NULL
|
||||
""",
|
||||
(row["id"], LEGACY_GENERATION),
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def instance_for_write(conn, media_root: str) -> dict:
|
||||
legacy = ensure_legacy_instance(conn, media_root)
|
||||
root = str(Path(media_root).resolve())
|
||||
if legacy["root_path"] == root:
|
||||
return legacy
|
||||
generation = "local-" + hashlib.sha256(root.encode("utf-8")).hexdigest()[:16]
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO storage_instances (kind, generation, root_path)
|
||||
VALUES ('local', %s, %s)
|
||||
ON CONFLICT (generation) DO NOTHING
|
||||
""",
|
||||
(generation, root),
|
||||
)
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT id, kind, generation, root_path
|
||||
FROM storage_instances
|
||||
WHERE generation = %s
|
||||
""",
|
||||
(generation,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
class StoredHandle:
|
||||
"""Rollback and delete go through the adapter that owns the bytes."""
|
||||
|
||||
def __init__(self, adapter: StoragePort, object_key: str):
|
||||
self._adapter = adapter
|
||||
self._key = object_key
|
||||
|
||||
def discard(self) -> None:
|
||||
self._adapter.delete(self._key)
|
||||
|
||||
|
||||
_FACTORIES: dict[str, callable] = {}
|
||||
|
||||
|
||||
def _local_factory(row: dict) -> StoragePort:
|
||||
return LocalAdapter(row["root_path"])
|
||||
|
||||
|
||||
_FACTORIES["local"] = _local_factory
|
||||
|
||||
|
||||
def adapter_for(row: dict) -> StoragePort:
|
||||
factory = _FACTORIES.get(row["kind"])
|
||||
if factory is None or not row.get("root_path") and row["kind"] == "local":
|
||||
raise storage_unavailable()
|
||||
return factory(row)
|
||||
|
||||
|
||||
def removal_for(conn, instance_id, generation: str | None, object_key: str, media_root: str) -> StoredHandle:
|
||||
row = None
|
||||
if instance_id is not None:
|
||||
row = conn.execute(
|
||||
"SELECT id, kind, generation, root_path FROM storage_instances WHERE id = %s",
|
||||
(instance_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
root = resolve_root(conn, instance_id, generation, media_root)
|
||||
return StoredHandle(LocalAdapter(root), object_key)
|
||||
return StoredHandle(adapter_for(row), object_key)
|
||||
|
||||
|
||||
def resolve_root(conn, instance_id, generation: str | None, media_root: str) -> str:
|
||||
if instance_id is not None:
|
||||
row = conn.execute(
|
||||
"SELECT root_path FROM storage_instances WHERE id = %s",
|
||||
(instance_id,),
|
||||
).fetchone()
|
||||
if row is not None and row["root_path"]:
|
||||
return row["root_path"]
|
||||
if generation in {None, LEGACY_GENERATION}:
|
||||
return ensure_legacy_instance(conn, media_root)["root_path"]
|
||||
return str(Path(media_root).resolve())
|
||||
|
||||
|
||||
def stored_path(conn, instance_id, generation: str | None, object_key: str, media_root: str) -> Path:
|
||||
return object_path(Path(resolve_root(conn, instance_id, generation, media_root)), object_key)
|
||||
|
||||
|
||||
def read_clear_bytes(
|
||||
conn,
|
||||
*,
|
||||
instance_id,
|
||||
generation: str | None,
|
||||
object_key: str,
|
||||
media_root: str,
|
||||
protection_profile: str | None,
|
||||
expected_sha256: str | None,
|
||||
) -> bytes:
|
||||
require_cleartext(protection_profile)
|
||||
row = None
|
||||
if instance_id is not None:
|
||||
row = conn.execute(
|
||||
"SELECT id, kind, generation, root_path FROM storage_instances WHERE id = %s",
|
||||
(instance_id,),
|
||||
).fetchone()
|
||||
adapter = adapter_for(row) if row is not None else LocalAdapter(resolve_root(conn, instance_id, generation, media_root))
|
||||
data = adapter.open(object_key)
|
||||
if expected_sha256 and sha256(data) != expected_sha256:
|
||||
raise Problem(
|
||||
422,
|
||||
"Inhalt nicht geprüft",
|
||||
"Die gespeicherte Datei stimmt nicht mit dem erfassten Stand überein.",
|
||||
"processing",
|
||||
)
|
||||
return data
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import storage_unavailable, unprocessable
|
||||
@@ -66,6 +67,17 @@ def display_filename(name: str) -> str:
|
||||
return text[:240]
|
||||
|
||||
|
||||
def content_disposition(filename: str) -> str:
|
||||
safe = display_filename(filename).replace('"', "")
|
||||
return f'attachment; filename="{safe}"'
|
||||
def content_disposition(filename: str, *, inline: bool = False) -> str:
|
||||
"""The real name goes along in UTF-8 (RFC 5987), with a plain ASCII fallback for old clients."""
|
||||
name = display_filename(filename)
|
||||
kind = "inline" if inline else "attachment"
|
||||
suffix = ""
|
||||
leaf = name.rsplit(".", 1)
|
||||
if len(leaf) == 2 and leaf[1].isascii() and leaf[1].isalnum():
|
||||
suffix = f".{leaf[1]}"
|
||||
fallback = name.encode("ascii", "replace").decode("ascii").replace("?", "_").replace('"', "").replace("\\", "_").replace(";", "_")
|
||||
fallback = " ".join(fallback.split())
|
||||
if suffix and not fallback.lower().endswith(suffix.lower()):
|
||||
fallback = f"{fallback}{suffix}".strip()
|
||||
fallback = fallback or f"datei{suffix}"
|
||||
return f"{kind}; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}"
|
||||
+1056
-44
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
"""Display order for bindings. Stored positions stay intact when sorting by date."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def arrange(items: list[dict], mode: str, direction: str) -> list[dict]:
|
||||
"""Return a new list. Undated entries stay last in both date directions."""
|
||||
if mode == "position":
|
||||
ordered = sorted(items, key=lambda item: (item["_raw_position"], item["id"]))
|
||||
else:
|
||||
dated = [item for item in items if item.get("_document_on")]
|
||||
undated = [item for item in items if not item.get("_document_on")]
|
||||
if direction == "desc":
|
||||
dated.sort(key=lambda item: (item["_raw_position"], item["id"]))
|
||||
dated.sort(key=lambda item: item["_document_on"], reverse=True)
|
||||
else:
|
||||
dated.sort(key=lambda item: (item["_document_on"], item["_raw_position"], item["id"]))
|
||||
undated.sort(key=lambda item: (item["_raw_position"], item["id"]))
|
||||
ordered = dated + undated
|
||||
result = []
|
||||
for index, item in enumerate(ordered):
|
||||
visible = {key: value for key, value in item.items() if not key.startswith("_")}
|
||||
visible["position"] = index
|
||||
result.append(visible)
|
||||
return result
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Account preferences with inheritance.
|
||||
|
||||
An employee inherits the value of the main user who sponsors the account and may change it,
|
||||
unless the main user made the preference binding for the team. A binding value overrides an own
|
||||
value without deleting it: it applies again once the binding is lifted.
|
||||
Allowed values, default and lockability of each key are fixed here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.core.errors import forbidden, not_found, unprocessable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Preference:
|
||||
default: str
|
||||
allowed: tuple[str, ...]
|
||||
team_lockable: bool = True
|
||||
|
||||
|
||||
PREFERENCES: dict[str, Preference] = {
|
||||
# Where an element that is inserted again counts as already present.
|
||||
"duplicate_check": Preference("here", ("off", "here", "inside", "around")),
|
||||
}
|
||||
|
||||
|
||||
def spec(key: str) -> Preference:
|
||||
found = PREFERENCES.get(key)
|
||||
if found is None:
|
||||
raise not_found()
|
||||
return found
|
||||
|
||||
|
||||
def _valid(wanted: Preference, value) -> str | None:
|
||||
return value if isinstance(value, str) and value in wanted.allowed else None
|
||||
|
||||
|
||||
def preference_state(conn, account_id: UUID, key: str) -> dict:
|
||||
"""The effective value and where it comes from: locked, own, team or default."""
|
||||
wanted = spec(key)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT a.account_kind,
|
||||
own.value AS own_value, own.team_mode AS own_mode,
|
||||
sp.value AS team_value, sp.team_mode AS team_mode
|
||||
FROM auth_accounts a
|
||||
LEFT JOIN account_preferences own ON own.account_id = a.id AND own.key = %s
|
||||
LEFT JOIN account_preferences sp ON sp.account_id = a.sponsor_id AND sp.key = %s
|
||||
WHERE a.id = %s
|
||||
""",
|
||||
(key, key, account_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
employee = row["account_kind"] == "employee"
|
||||
own = _valid(wanted, row["own_value"])
|
||||
team = _valid(wanted, row["team_value"]) if employee else None
|
||||
locked = employee and wanted.team_lockable and row["team_mode"] == "locked"
|
||||
inherited = team or wanted.default
|
||||
if locked:
|
||||
value, source = inherited, "locked"
|
||||
elif own is not None:
|
||||
value, source = own, "own"
|
||||
elif team is not None:
|
||||
value, source = team, "team"
|
||||
else:
|
||||
value, source = wanted.default, "default"
|
||||
return {
|
||||
"key": key,
|
||||
"value": value,
|
||||
"source": source,
|
||||
"own": own,
|
||||
"inherited": inherited,
|
||||
"locked": locked,
|
||||
"allowed": list(wanted.allowed),
|
||||
"default": wanted.default,
|
||||
"can_lock": row["account_kind"] == "main" and wanted.team_lockable,
|
||||
"team_mode": row["own_mode"] if row["own_mode"] and not employee else "free",
|
||||
}
|
||||
|
||||
|
||||
def effective_preference(conn, account_id: UUID, key: str) -> str:
|
||||
return preference_state(conn, account_id, key)["value"]
|
||||
|
||||
|
||||
def store_preference(conn, account_id: UUID, key: str, value: str | None, team_mode: str | None) -> dict:
|
||||
"""Own value (None: inherit) and, for a main user, the binding for the team."""
|
||||
wanted = spec(key)
|
||||
state = preference_state(conn, account_id, key)
|
||||
if value is not None and value not in wanted.allowed:
|
||||
raise unprocessable("Dieser Wert ist für die Einstellung nicht vorgesehen.")
|
||||
if team_mode is not None and not state["can_lock"]:
|
||||
raise forbidden("Nur der Hauptnutzer kann eine Einstellung für das Team verbindlich setzen.")
|
||||
if state["locked"]:
|
||||
raise forbidden("Der Hauptnutzer hat diese Einstellung für das Team vorgegeben.")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO account_preferences (account_id, key, value, team_mode)
|
||||
VALUES (%s, %s, %s, COALESCE(%s, 'free'))
|
||||
ON CONFLICT (account_id, key) DO UPDATE
|
||||
SET value = EXCLUDED.value,
|
||||
team_mode = COALESCE(%s, account_preferences.team_mode),
|
||||
updated_at = now()
|
||||
""",
|
||||
(account_id, key, Json(value) if value is not None else None, team_mode, team_mode),
|
||||
)
|
||||
return preference_state(conn, account_id, key)
|
||||
+654
-57
@@ -13,6 +13,7 @@ from app.access.policy import (
|
||||
get_case,
|
||||
get_element,
|
||||
get_matter,
|
||||
get_task,
|
||||
matter_rights,
|
||||
matter_title_if_readable,
|
||||
readable_matter_contexts,
|
||||
@@ -22,19 +23,39 @@ from app.access.policy import (
|
||||
)
|
||||
from app.access.policy import SHARED_NOTICE
|
||||
from app.core.timeutil import dump_date, dump_dt
|
||||
from app.order import arrange
|
||||
|
||||
|
||||
def rights_dict(rights) -> dict:
|
||||
return rights.as_dict()
|
||||
|
||||
|
||||
def _chapters(conn, kind: str, container_id: UUID) -> list[dict]:
|
||||
def _chapters(conn, kind: str, container_id: UUID, mode: str = "position", direction: str = "asc") -> list[dict]:
|
||||
column = "case_id" if kind == "case" else "matter_id"
|
||||
rows = conn.execute(
|
||||
f"SELECT id, title, position FROM chapters WHERE {column} = %s ORDER BY position, created_at",
|
||||
f"SELECT id, title, position, document_on, parent_chapter_id FROM chapters WHERE {column} = %s",
|
||||
(container_id,),
|
||||
).fetchall()
|
||||
return [{"id": str(row["id"]), "title": row["title"], "position": row["position"]} for row in rows]
|
||||
items = [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"position": row["position"],
|
||||
"document_on": dump_date(row["document_on"]),
|
||||
"parent_chapter_id": str(row["parent_chapter_id"]) if row["parent_chapter_id"] else None,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
if mode == "date":
|
||||
dated = [item for item in items if item["document_on"]]
|
||||
undated = [item for item in items if not item["document_on"]]
|
||||
dated.sort(key=lambda item: (item["document_on"], item["position"], item["id"]))
|
||||
undated.sort(key=lambda item: (item["position"], item["id"]))
|
||||
if direction == "desc":
|
||||
dated.reverse()
|
||||
return dated + undated
|
||||
items.sort(key=lambda item: (item["position"], item["id"]))
|
||||
return items
|
||||
|
||||
|
||||
def _annotations(conn, binding_id: UUID) -> list[dict]:
|
||||
@@ -72,43 +93,145 @@ def _dates(conn, element: dict) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _element_body(conn, element: dict) -> dict:
|
||||
def _plain_excerpt(document: dict | None) -> str | None:
|
||||
if not isinstance(document, dict):
|
||||
return None
|
||||
parts = []
|
||||
for block in document.get("blocks") or []:
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
text = str(block.get("text") or "").strip()
|
||||
if text:
|
||||
parts.append(text)
|
||||
raw = " ".join(parts).strip()
|
||||
if not raw:
|
||||
return None
|
||||
return raw[:180]
|
||||
|
||||
|
||||
def _preview_meta(kind: str, content_type: str | None, source: str | None) -> dict:
|
||||
if kind == "note":
|
||||
return {"available": False, "media": "note", "source": "note"}
|
||||
media = (content_type or "").split(";")[0].strip().lower()
|
||||
if kind == "file" and media.startswith("image/"):
|
||||
return {"available": True, "media": "image", "source": "file"}
|
||||
if kind == "file" and media == "application/pdf":
|
||||
return {"available": True, "media": "pdf", "source": "file"}
|
||||
if kind == "external_ref" and source:
|
||||
from app.sourceregistry import get_source
|
||||
|
||||
module = get_source(source)
|
||||
if module is not None:
|
||||
return {
|
||||
"available": bool(module.capabilities.get("read_preview")),
|
||||
"media": module.representation,
|
||||
"source": source,
|
||||
}
|
||||
if kind == "file":
|
||||
return {"available": False, "media": "file", "source": "file"}
|
||||
return {"available": False, "media": "none", "source": source}
|
||||
|
||||
|
||||
_HIDDEN_SOURCE_FIELDS = frozenset({
|
||||
"connector_id",
|
||||
"mailbox",
|
||||
"uid",
|
||||
"host",
|
||||
"username",
|
||||
"port",
|
||||
"password",
|
||||
"secret",
|
||||
"base_url",
|
||||
"server",
|
||||
"security",
|
||||
"open_url",
|
||||
})
|
||||
|
||||
|
||||
def _connector_owner(conn, raw) -> UUID | None:
|
||||
try:
|
||||
connector_id = UUID(str(raw))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone()
|
||||
return row["owner_id"] if row else None
|
||||
|
||||
|
||||
def _element_body(conn, actor: UUID, element: dict) -> dict:
|
||||
payload = {
|
||||
"id": str(element["id"]),
|
||||
"kind": element["kind"],
|
||||
"title": element["title"],
|
||||
"summary": element.get("summary") or None,
|
||||
"excerpt": None,
|
||||
"version": element["version"],
|
||||
"owner_subject_id": str(element["owner_subject_id"]),
|
||||
"dates": _dates(conn, element),
|
||||
"preview": _preview_meta(element["kind"], None, None),
|
||||
}
|
||||
if element["kind"] == "note":
|
||||
body = conn.execute(
|
||||
"SELECT document_json FROM note_bodies WHERE element_id = %s",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
payload["document"] = body["document_json"] if body else {"version": 1, "blocks": []}
|
||||
document = body["document_json"] if body else {"version": 1, "blocks": []}
|
||||
payload["document"] = document
|
||||
payload["excerpt"] = _plain_excerpt(document)
|
||||
payload["preview"] = _preview_meta("note", None, "note")
|
||||
elif element["kind"] == "file":
|
||||
asset = conn.execute(
|
||||
"""
|
||||
SELECT original_filename, content_type, byte_size, status
|
||||
SELECT original_filename, content_type, byte_size, status, protection_profile
|
||||
FROM media_assets WHERE element_id = %s
|
||||
""",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
if asset is not None:
|
||||
profile = asset["protection_profile"] or "legacy-plaintext"
|
||||
payload["file"] = {
|
||||
"filename": asset["original_filename"],
|
||||
"content_type": asset["content_type"],
|
||||
"byte_size": asset["byte_size"],
|
||||
"status": asset["status"],
|
||||
"protection_profile": profile,
|
||||
}
|
||||
if profile != "legacy-plaintext":
|
||||
payload["preview"] = {"available": False, "media": "locked", "source": "file"}
|
||||
else:
|
||||
payload["preview"] = _preview_meta("file", asset["content_type"], "file")
|
||||
elif element["kind"] == "external_ref":
|
||||
ref = conn.execute(
|
||||
"SELECT source, external_id FROM external_references WHERE element_id = %s",
|
||||
"""
|
||||
SELECT source, external_id, detail, connector_id, resolution
|
||||
FROM external_references WHERE element_id = %s
|
||||
""",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
if ref is not None:
|
||||
payload["external"] = {"source": ref["source"], "external_id": ref["external_id"]}
|
||||
detail = dict(ref["detail"] or {})
|
||||
connector_owner = _connector_owner(conn, ref["connector_id"] or detail.get("connector_id"))
|
||||
revealed = actor == element["owner_subject_id"] or (connector_owner is not None and actor == connector_owner)
|
||||
if not revealed:
|
||||
detail = {key: value for key, value in detail.items() if key not in _HIDDEN_SOURCE_FIELDS}
|
||||
resolution = ref["resolution"] or "unresolved"
|
||||
external = {"source": ref["source"], "detail": detail, "resolution": resolution}
|
||||
if revealed:
|
||||
external["external_id"] = ref["external_id"]
|
||||
payload["external"] = external
|
||||
from app.sourcebind import resolve_for_read
|
||||
from app.sourceregistry import get_source
|
||||
|
||||
module = get_source(ref["source"])
|
||||
if module is None:
|
||||
payload["preview"] = _preview_meta("external_ref", None, ref["source"])
|
||||
else:
|
||||
resolved = resolve_for_read(conn, element["owner_subject_id"], ref["source"], ref, None)
|
||||
if resolved.code == "ok":
|
||||
payload["preview"] = _preview_meta("external_ref", None, ref["source"])
|
||||
elif actor == element["owner_subject_id"]:
|
||||
payload["preview"] = {"available": False, "media": "unassigned", "source": ref["source"]}
|
||||
else:
|
||||
payload["preview"] = {"available": False, "media": "none", "source": ref["source"]}
|
||||
return payload
|
||||
|
||||
|
||||
@@ -130,6 +253,83 @@ def _exception(conn, kind: str, resource_id: UUID, context: Ctx | None) -> dict
|
||||
return {"remove_read": row["can_read"], "remove_edit": row["can_edit"], "remove_share": row["can_share"]}
|
||||
|
||||
|
||||
def communication_from_row(conn, binding: dict, element: dict) -> dict:
|
||||
"""Explicit binding direction wins. An adopted mailbox direction may prefill. Dates never do."""
|
||||
stored = binding.get("communication_direction")
|
||||
stored = stored if stored in ("in", "out", "local") else None
|
||||
if binding.get("direction_explicit"):
|
||||
return {"direction": stored, "explicit": True}
|
||||
source = None
|
||||
if element["kind"] == "external_ref":
|
||||
ref = conn.execute(
|
||||
"SELECT source, detail FROM external_references WHERE element_id = %s",
|
||||
(element["id"],),
|
||||
).fetchone()
|
||||
detail = (ref["detail"] or {}) if ref is not None else {}
|
||||
if detail.get("direction") in ("in", "out"):
|
||||
source = detail["direction"]
|
||||
return {"direction": source, "explicit": False}
|
||||
|
||||
|
||||
def _reference_view(conn, actor: UUID, element_id: UUID, context: Ctx, container: Ctx) -> dict | None:
|
||||
element = get_element(conn, element_id)
|
||||
if element is None or not element_rights(conn, actor, element, context).read:
|
||||
return None
|
||||
dates = _dates(conn, element)
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT communication_direction, direction_explicit
|
||||
FROM bindings
|
||||
WHERE element_id = %s AND context_kind = %s AND context_id = %s
|
||||
""",
|
||||
(element["id"], container.kind, container.id),
|
||||
).fetchone()
|
||||
direction = communication_from_row(
|
||||
conn,
|
||||
row or {"communication_direction": None, "direction_explicit": False},
|
||||
element,
|
||||
)["direction"]
|
||||
return {
|
||||
"id": str(element["id"]),
|
||||
"title": element["title"],
|
||||
"document_on": dates["document_on"],
|
||||
"direction": direction,
|
||||
}
|
||||
|
||||
|
||||
def _attach_references(conn, actor: UUID, element: dict, context: Ctx, container: Ctx, body: dict) -> None:
|
||||
refers = []
|
||||
for row in conn.execute(
|
||||
"""
|
||||
SELECT refers_to_element_id
|
||||
FROM element_references
|
||||
WHERE element_id = %s
|
||||
ORDER BY created_at, refers_to_element_id
|
||||
""",
|
||||
(element["id"],),
|
||||
).fetchall():
|
||||
view = _reference_view(conn, actor, row["refers_to_element_id"], context, container)
|
||||
if view is not None:
|
||||
refers.append(view)
|
||||
replies = []
|
||||
for row in conn.execute(
|
||||
"""
|
||||
SELECT element_id
|
||||
FROM element_references
|
||||
WHERE refers_to_element_id = %s
|
||||
ORDER BY created_at, element_id
|
||||
""",
|
||||
(element["id"],),
|
||||
).fetchall():
|
||||
view = _reference_view(conn, actor, row["element_id"], context, container)
|
||||
if view is not None:
|
||||
replies.append(view)
|
||||
if refers:
|
||||
body["refers_to"] = refers
|
||||
if replies:
|
||||
body["referred_by"] = replies
|
||||
|
||||
|
||||
def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | None:
|
||||
element = get_element(conn, binding["element_id"])
|
||||
if element is None:
|
||||
@@ -137,13 +337,17 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
if not rights.read:
|
||||
return None
|
||||
body = _element_body(conn, actor, element)
|
||||
container = Ctx(binding["context_kind"], binding["context_id"])
|
||||
_attach_references(conn, actor, element, context, container, body)
|
||||
payload = {
|
||||
"id": str(binding["id"]),
|
||||
"position": binding["position"],
|
||||
"chapter_id": str(binding["chapter_id"]) if binding["chapter_id"] else None,
|
||||
"rights": rights.as_dict(),
|
||||
"annotations": _annotations(conn, binding["id"]),
|
||||
"element": _element_body(conn, element),
|
||||
"communication": communication_from_row(conn, binding, element),
|
||||
"element": body,
|
||||
}
|
||||
if element["owner_subject_id"] == actor:
|
||||
payload["exception"] = _exception(conn, "element", element["id"], context)
|
||||
@@ -153,7 +357,8 @@ def binding_payload(conn, actor: UUID, binding: dict, context: Ctx) -> dict | No
|
||||
def _grants(conn, kind: str, resource_id: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, a.email, a.display_name
|
||||
SELECT g.id, g.grantee_subject_id, g.can_read, g.can_edit, g.can_share, g.use_owner_sources,
|
||||
a.email, a.display_name
|
||||
FROM access_grants g
|
||||
JOIN auth_accounts a ON a.id = g.grantee_subject_id
|
||||
WHERE NOT g.is_exception AND g.resource_kind = %s AND g.resource_id = %s AND g.context_kind IS NULL
|
||||
@@ -170,11 +375,256 @@ def _grants(conn, kind: str, resource_id: UUID) -> list[dict]:
|
||||
"can_read": row["can_read"],
|
||||
"can_edit": row["can_edit"],
|
||||
"can_share": row["can_share"],
|
||||
"use_owner_sources": row["use_owner_sources"],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def _ordered_bindings(conn, actor: UUID, kind: str, container_id: UUID, context: Ctx, mode: str, direction: str) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT * FROM bindings
|
||||
WHERE context_kind = %s AND context_id = %s
|
||||
ORDER BY position, id
|
||||
""",
|
||||
(kind, container_id),
|
||||
).fetchall()
|
||||
visible = []
|
||||
for binding in rows:
|
||||
item = binding_payload(conn, actor, binding, context)
|
||||
if item is None:
|
||||
continue
|
||||
item["_raw_position"] = binding["position"]
|
||||
item["_document_on"] = item["element"]["dates"]["document_on"]
|
||||
item["container"] = {"kind": kind, "id": str(container_id)}
|
||||
item["_fold"] = binding.get("list_fold")
|
||||
visible.append(item)
|
||||
arranged = arrange(visible, mode or "position", direction or "asc")
|
||||
from app.correspondence import attach_correspondence
|
||||
|
||||
attach_correspondence(conn, actor, arranged, context)
|
||||
for item in arranged:
|
||||
item.pop("_fold", None)
|
||||
return arranged
|
||||
|
||||
|
||||
def course_items(bindings: list[dict]) -> list[dict]:
|
||||
"""One fachlicher Eintrag je Unterlage. Das Erfassungsdatum ist kein Belegdatum."""
|
||||
items = []
|
||||
for binding in bindings:
|
||||
dates = binding["element"]["dates"]
|
||||
items.append(
|
||||
{
|
||||
"id": binding["element"]["id"],
|
||||
"binding_id": binding["id"],
|
||||
"title": binding["element"]["title"],
|
||||
"kind": binding["element"]["kind"],
|
||||
"document_on": dates["document_on"],
|
||||
"sent_on": dates["sent_on"],
|
||||
"received_on": dates["received_on"],
|
||||
"dated": dates["document_on"] is not None,
|
||||
}
|
||||
)
|
||||
dated = [item for item in items if item["dated"]]
|
||||
undated = [item for item in items if not item["dated"]]
|
||||
dated.sort(key=lambda item: (item["document_on"], item["id"]))
|
||||
undated.sort(key=lambda item: item["id"])
|
||||
return dated + undated
|
||||
|
||||
|
||||
def _matter_href(matter_id: UUID, context: Ctx | None) -> str:
|
||||
href = f"/matters/{matter_id}"
|
||||
if context is not None and context.kind == "case":
|
||||
href += f"?context_kind=case&context_id={context.id}"
|
||||
return href
|
||||
|
||||
|
||||
def _append_matter_steps(conn, actor: UUID, trail: list[dict], matter: dict, context: Ctx | None) -> None:
|
||||
"""Object path only. The same labels apply from a case, a list or a direct link."""
|
||||
page = context if context is not None and context.kind == "case" else None
|
||||
if matter["parent_matter_id"]:
|
||||
parent = get_matter(conn, matter["parent_matter_id"])
|
||||
if parent is not None and matter_title_if_readable(conn, actor, parent["id"]):
|
||||
trail.append({"label": f"Vorgang {parent['title']}", "href": _matter_href(parent["id"], page if _parent_keeps_context(conn, actor, parent, page) else None)})
|
||||
kind = "Teilvorgang" if matter["parent_matter_id"] else "Vorgang"
|
||||
trail.append({"label": f"{kind} {matter['title']}", "href": None})
|
||||
|
||||
|
||||
def _parent_keeps_context(conn, actor: UUID, parent: dict, page: Ctx | None) -> bool:
|
||||
return page is not None and matter_rights(conn, actor, parent, page).read
|
||||
|
||||
|
||||
def case_trail(conn, actor: UUID, case: dict) -> list[dict]:
|
||||
trail = [{"label": "Akten", "href": "/cases"}]
|
||||
if case["parent_case_id"]:
|
||||
parent = get_case(conn, case["parent_case_id"])
|
||||
if parent is not None and case_rights(conn, actor, parent).read:
|
||||
trail.append({"label": f"Akte {parent['title']}", "href": f"/cases/{parent['id']}"})
|
||||
kind = "Unterakte" if case["parent_case_id"] else "Akte"
|
||||
trail.append({"label": f"{kind} {case['title']}", "href": None})
|
||||
return trail
|
||||
|
||||
|
||||
def _structural_case(conn, actor: UUID, matter: dict, context: Ctx | None) -> dict | None:
|
||||
"""The case that places this matter in the structure. Several placements do not invent a main case."""
|
||||
if context is not None and context.kind == "case":
|
||||
case = get_case(conn, context.id)
|
||||
if case is not None and case_rights(conn, actor, case).read:
|
||||
return case
|
||||
return None
|
||||
placements = matter_placements(conn, actor, matter["id"], None)
|
||||
if len(placements) != 1:
|
||||
return None
|
||||
case = get_case(conn, UUID(placements[0]["case_id"]))
|
||||
if case is None or not case_rights(conn, actor, case).read:
|
||||
return None
|
||||
return case
|
||||
|
||||
|
||||
def matter_trail(conn, actor: UUID, matter: dict, context: Ctx | None) -> list[dict]:
|
||||
case = _structural_case(conn, actor, matter, context)
|
||||
if case is None:
|
||||
trail = [{"label": "Vorgänge", "href": "/matters"}]
|
||||
_append_matter_steps(conn, actor, trail, matter, None)
|
||||
return trail
|
||||
trail = case_trail(conn, actor, case)
|
||||
trail[-1]["href"] = f"/cases/{case['id']}"
|
||||
_append_matter_steps(conn, actor, trail, matter, Ctx("case", case["id"]))
|
||||
return trail
|
||||
|
||||
|
||||
def _case_chain_label(conn, actor: UUID, case: dict) -> str:
|
||||
parts = []
|
||||
current = case
|
||||
guard = 0
|
||||
while current is not None and guard < 4:
|
||||
if not case_rights(conn, actor, current).read:
|
||||
break
|
||||
kind = "Unterakte" if current["parent_case_id"] else "Akte"
|
||||
parts.append(f"{kind} {current['title']}")
|
||||
parent_id = current["parent_case_id"]
|
||||
current = get_case(conn, parent_id) if parent_id else None
|
||||
guard += 1
|
||||
parts.reverse()
|
||||
return " → ".join(parts)
|
||||
|
||||
|
||||
def _placement_rows(conn, matter_id: UUID) -> list[dict]:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT c.*
|
||||
FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id AND c.deleted_at IS NULL
|
||||
WHERE l.matter_id = %s
|
||||
ORDER BY c.title, c.id
|
||||
""",
|
||||
(matter_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def matter_placements(conn, actor: UUID, matter_id: UUID, context: Ctx | None) -> list[dict]:
|
||||
"""Readable case assignments of this matter and its readable parent chain."""
|
||||
items = []
|
||||
seen: set[UUID] = set()
|
||||
matter = get_matter(conn, matter_id)
|
||||
guard = 0
|
||||
while matter is not None and guard < 4:
|
||||
for link in _placement_rows(conn, matter["id"]):
|
||||
if link["id"] in seen or not case_rights(conn, actor, link).read:
|
||||
continue
|
||||
seen.add(link["id"])
|
||||
items.append(
|
||||
{
|
||||
"case_id": str(link["id"]),
|
||||
"label": _case_chain_label(conn, actor, link),
|
||||
"href": f"/cases/{link['id']}",
|
||||
"current": context is not None and context.kind == "case" and context.id == link["id"],
|
||||
}
|
||||
)
|
||||
parent_id = matter["parent_matter_id"]
|
||||
if parent_id is None or matter_title_if_readable(conn, actor, parent_id) is None:
|
||||
break
|
||||
matter = get_matter(conn, parent_id)
|
||||
guard += 1
|
||||
return items
|
||||
|
||||
|
||||
def _contained_group(conn, actor: UUID, matter: dict, context: Ctx) -> dict | None:
|
||||
matter_right = matter_rights(conn, actor, matter, context)
|
||||
if not matter_right.read:
|
||||
return None
|
||||
return {
|
||||
"matter_id": str(matter["id"]),
|
||||
"title": matter["title"],
|
||||
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
||||
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
||||
"version": matter["version"],
|
||||
"rights": matter_right.as_dict(),
|
||||
"chapters": _chapters(
|
||||
conn,
|
||||
"matter",
|
||||
matter["id"],
|
||||
matter.get("content_order") or "position",
|
||||
matter.get("content_order_dir") or "asc",
|
||||
),
|
||||
"content_order": matter.get("content_order") or "position",
|
||||
"content_order_dir": matter.get("content_order_dir") or "asc",
|
||||
"bindings": _ordered_bindings(
|
||||
conn,
|
||||
actor,
|
||||
"matter",
|
||||
matter["id"],
|
||||
context,
|
||||
matter.get("content_order") or "position",
|
||||
matter.get("content_order_dir") or "asc",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _matter_node(row: dict) -> dict:
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"status": row["record_status"],
|
||||
"kind_label": "Teilvorgang" if row["parent_matter_id"] else "Vorgang",
|
||||
"parent_matter_id": str(row["parent_matter_id"]) if row["parent_matter_id"] else None,
|
||||
"children": [],
|
||||
}
|
||||
|
||||
|
||||
def _matter_tree(conn, actor: UUID, case_id: UUID, linked: list[dict]) -> list[dict]:
|
||||
"""One level: a Teilvorgang sits under its Vorgang, not beside it."""
|
||||
context = Ctx("case", case_id)
|
||||
rows = list(linked)
|
||||
seen = {row["id"] for row in rows}
|
||||
for row in list(rows):
|
||||
children = conn.execute(
|
||||
"""
|
||||
SELECT * FROM matters
|
||||
WHERE parent_matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY title, id
|
||||
""",
|
||||
(row["id"],),
|
||||
).fetchall()
|
||||
for child in children:
|
||||
if child["id"] in seen:
|
||||
continue
|
||||
if matter_rights(conn, actor, child, context).read:
|
||||
rows.append(child)
|
||||
seen.add(child["id"])
|
||||
nodes = {row["id"]: _matter_node(row) for row in rows}
|
||||
roots = []
|
||||
for row in rows:
|
||||
parent_id = row["parent_matter_id"]
|
||||
node = nodes[row["id"]]
|
||||
if parent_id and parent_id in nodes:
|
||||
nodes[parent_id]["children"].append(node)
|
||||
else:
|
||||
roots.append(node)
|
||||
return roots
|
||||
|
||||
|
||||
def case_summary(case: dict, rights) -> dict:
|
||||
return {
|
||||
"id": str(case["id"]),
|
||||
@@ -190,9 +640,20 @@ def case_summary(case: dict, rights) -> dict:
|
||||
|
||||
def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
||||
payload = case_summary(case, rights)
|
||||
payload["content_order"] = case.get("content_order") or "position"
|
||||
payload["content_order_dir"] = case.get("content_order_dir") or "asc"
|
||||
payload["content_view"] = case.get("content_view") or "structure"
|
||||
payload["trail"] = case_trail(conn, actor, case)
|
||||
payload["kind_label"] = "Unterakte" if case["parent_case_id"] else "Akte"
|
||||
payload["home_scope_name"] = room_name(conn, case["home_scope_id"])
|
||||
payload["is_owner"] = case["owner_subject_id"] == actor
|
||||
payload["chapters"] = _chapters(conn, "case", case["id"])
|
||||
if case["parent_case_id"]:
|
||||
parent = get_case(conn, case["parent_case_id"])
|
||||
if parent is not None and case_rights(conn, actor, parent).read:
|
||||
payload["parent_title"] = parent["title"]
|
||||
payload["chapters"] = _chapters(
|
||||
conn, "case", case["id"], case.get("content_order") or "position", case.get("content_order_dir") or "asc"
|
||||
)
|
||||
subcases = []
|
||||
for row in conn.execute(
|
||||
"""
|
||||
@@ -220,29 +681,59 @@ def case_detail(conn, actor: UUID, case: dict, rights) -> dict:
|
||||
matter_right = matter_rights(conn, actor, link, Ctx("case", case["id"]))
|
||||
if not matter_right.read:
|
||||
continue
|
||||
matters.append(
|
||||
{
|
||||
"id": str(link["id"]),
|
||||
"link_id": str(link["link_id"]),
|
||||
"title": link["title"],
|
||||
"status": link["record_status"],
|
||||
}
|
||||
)
|
||||
payload["matters"] = matters
|
||||
matters.append(link)
|
||||
payload["matters"] = _matter_tree(conn, actor, case["id"], matters)
|
||||
context = Ctx("case", case["id"])
|
||||
bindings = []
|
||||
for binding in conn.execute(
|
||||
payload["bindings"] = _ordered_bindings(
|
||||
conn, actor, "case", case["id"], context, payload["content_order"], payload["content_order_dir"]
|
||||
)
|
||||
contained = []
|
||||
seen_matters: set[UUID] = set()
|
||||
linked_matters = conn.execute(
|
||||
"""
|
||||
SELECT * FROM bindings
|
||||
WHERE context_kind = 'case' AND context_id = %s
|
||||
ORDER BY position, created_at
|
||||
SELECT m.*
|
||||
FROM matter_case_links l
|
||||
JOIN matters m ON m.id = l.matter_id
|
||||
WHERE l.case_id = %s AND m.deleted_at IS NULL
|
||||
ORDER BY m.title, m.id
|
||||
""",
|
||||
(case["id"],),
|
||||
).fetchall():
|
||||
item = binding_payload(conn, actor, binding, context)
|
||||
if item is not None:
|
||||
bindings.append(item)
|
||||
payload["bindings"] = bindings
|
||||
).fetchall()
|
||||
for link in linked_matters:
|
||||
block = [link]
|
||||
if not link["parent_matter_id"]:
|
||||
block.extend(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM matters
|
||||
WHERE parent_matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY title, id
|
||||
""",
|
||||
(link["id"],),
|
||||
).fetchall()
|
||||
)
|
||||
for matter in block:
|
||||
if matter["id"] in seen_matters:
|
||||
continue
|
||||
seen_matters.add(matter["id"])
|
||||
group = _contained_group(conn, actor, matter, context)
|
||||
if group is not None:
|
||||
contained.append(group)
|
||||
payload["contained"] = contained
|
||||
payload["tasks"] = []
|
||||
payload["deadlines"] = []
|
||||
payload["task_deadline_links"] = []
|
||||
|
||||
def _walk(nodes):
|
||||
for node in nodes:
|
||||
yield node
|
||||
yield from _walk(node["children"])
|
||||
|
||||
for node in _walk(payload["matters"]):
|
||||
tracked = _tracking(conn, actor, UUID(node["id"]), context)
|
||||
payload["tasks"].extend(tracked["tasks"])
|
||||
payload["deadlines"].extend(tracked["deadlines"])
|
||||
payload["task_deadline_links"].extend(tracked["links"])
|
||||
if rights.share or case["owner_subject_id"] == actor:
|
||||
payload["grants"] = _grants(conn, "case", case["id"])
|
||||
return payload
|
||||
@@ -256,14 +747,32 @@ def matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]:
|
||||
return contexts
|
||||
|
||||
|
||||
def _shared_rooms(conn, kind: str, resource_id: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT r.id, r.name, s.access FROM room_shares s JOIN data_rooms r ON r.id = s.room_id
|
||||
WHERE s.resource_kind = %s AND s.resource_id = %s
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(kind, resource_id),
|
||||
).fetchall()
|
||||
return [{"id": str(row["id"]), "name": row["name"], "access": row["access"]} for row in rows]
|
||||
|
||||
|
||||
def matter_summary(conn, actor: UUID, matter: dict) -> dict:
|
||||
owner = matter["owner_subject_id"] == actor
|
||||
return {
|
||||
"is_owner": owner,
|
||||
"shared_with": _shared_rooms(conn, "matter", matter["id"]) if owner else [],
|
||||
"id": str(matter["id"]),
|
||||
"title": matter["title"],
|
||||
"status": matter["record_status"],
|
||||
"version": matter["version"],
|
||||
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
||||
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
|
||||
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
||||
"home_scope_id": str(matter["home_scope_id"]),
|
||||
"home_scope_name": room_name(conn, matter["home_scope_id"]),
|
||||
"contexts": matter_contexts(conn, actor, matter),
|
||||
}
|
||||
|
||||
@@ -282,12 +791,25 @@ def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None)
|
||||
"status": matter["record_status"],
|
||||
"version": matter["version"],
|
||||
"parent_matter_id": str(matter["parent_matter_id"]) if matter["parent_matter_id"] else None,
|
||||
"parent_title": matter_title_if_readable(conn, actor, matter["parent_matter_id"]),
|
||||
"home_scope_id": str(matter["home_scope_id"]),
|
||||
"home_scope_name": room_name(conn, matter["home_scope_id"]),
|
||||
"is_owner": matter["owner_subject_id"] == actor,
|
||||
"content_order": matter.get("content_order") or "position",
|
||||
"content_order_dir": matter.get("content_order_dir") or "asc",
|
||||
"content_view": matter.get("content_view") or "structure",
|
||||
"trail": matter_trail(conn, actor, matter, context),
|
||||
"placements": matter_placements(conn, actor, matter["id"], context),
|
||||
"kind_label": "Teilvorgang" if matter["parent_matter_id"] else "Vorgang",
|
||||
"rights": rights.as_dict(),
|
||||
"context": None if context is None else context.as_dict(),
|
||||
"chapters": _chapters(conn, "matter", matter["id"]),
|
||||
"chapters": _chapters(
|
||||
conn,
|
||||
"matter",
|
||||
matter["id"],
|
||||
matter.get("content_order") or "position",
|
||||
matter.get("content_order_dir") or "asc",
|
||||
),
|
||||
}
|
||||
submatters = []
|
||||
for child in conn.execute(
|
||||
@@ -326,32 +848,40 @@ def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None)
|
||||
if title is not None:
|
||||
crosses.append({"id": str(link["id"]), "matter_id": str(link["to_matter_id"]), "title": title})
|
||||
payload["cross_links"] = crosses
|
||||
bindings = []
|
||||
for binding in conn.execute(
|
||||
"""
|
||||
SELECT * FROM bindings
|
||||
WHERE context_kind = 'matter' AND context_id = %s
|
||||
ORDER BY position, created_at
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall():
|
||||
item = binding_payload(conn, actor, binding, page)
|
||||
if item is not None:
|
||||
bindings.append(item)
|
||||
payload["bindings"] = bindings
|
||||
payload["tasks"] = []
|
||||
payload["bindings"] = _ordered_bindings(
|
||||
conn,
|
||||
actor,
|
||||
"matter",
|
||||
matter["id"],
|
||||
page,
|
||||
payload["content_order"],
|
||||
payload["content_order_dir"],
|
||||
)
|
||||
tracked = _tracking(conn, actor, matter["id"], context)
|
||||
payload["tasks"] = tracked["tasks"]
|
||||
payload["deadlines"] = tracked["deadlines"]
|
||||
payload["task_deadline_links"] = tracked["links"]
|
||||
if rights.share or matter["owner_subject_id"] == actor:
|
||||
payload["grants"] = _grants(conn, "matter", matter["id"])
|
||||
if matter["owner_subject_id"] == actor:
|
||||
payload["exception"] = _exception(conn, "matter", matter["id"], context)
|
||||
return payload
|
||||
|
||||
|
||||
def _tracking(conn, actor: UUID, matter_id: UUID, context: Ctx | None) -> dict:
|
||||
tasks = []
|
||||
for task in conn.execute(
|
||||
"""
|
||||
SELECT * FROM tasks
|
||||
WHERE matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY due_on NULLS LAST, created_at
|
||||
""",
|
||||
(matter["id"],),
|
||||
(matter_id,),
|
||||
).fetchall():
|
||||
task_right = task_rights(conn, actor, task, context)
|
||||
if task_right.read:
|
||||
payload["tasks"].append(task_payload(conn, actor, task, task_right))
|
||||
payload["deadlines"] = []
|
||||
tasks.append(task_payload(conn, actor, task, task_right))
|
||||
deadlines = []
|
||||
visible_deadlines = set()
|
||||
for deadline in conn.execute(
|
||||
"""
|
||||
@@ -359,14 +889,14 @@ def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None)
|
||||
WHERE matter_id = %s AND deleted_at IS NULL
|
||||
ORDER BY due_on, created_at
|
||||
""",
|
||||
(matter["id"],),
|
||||
(matter_id,),
|
||||
).fetchall():
|
||||
deadline_right = deadline_rights(conn, actor, deadline, context)
|
||||
if deadline_right.read:
|
||||
payload["deadlines"].append(deadline_payload(conn, actor, deadline))
|
||||
deadlines.append(deadline_payload(conn, actor, deadline))
|
||||
visible_deadlines.add(deadline["id"])
|
||||
visible_tasks = {UUID(item["id"]) for item in payload["tasks"]}
|
||||
links = []
|
||||
visible_tasks = {UUID(item["id"]) for item in tasks}
|
||||
if visible_tasks and visible_deadlines:
|
||||
for link in conn.execute(
|
||||
"SELECT task_id, deadline_id FROM task_deadline_links WHERE task_id = ANY(%s::uuid[])",
|
||||
@@ -374,12 +904,7 @@ def matter_detail(conn, actor: UUID, matter: dict, rights, context: Ctx | None)
|
||||
).fetchall():
|
||||
if link["deadline_id"] in visible_deadlines:
|
||||
links.append({"task_id": str(link["task_id"]), "deadline_id": str(link["deadline_id"])})
|
||||
payload["task_deadline_links"] = links
|
||||
if rights.share or matter["owner_subject_id"] == actor:
|
||||
payload["grants"] = _grants(conn, "matter", matter["id"])
|
||||
if matter["owner_subject_id"] == actor:
|
||||
payload["exception"] = _exception(conn, "matter", matter["id"], context)
|
||||
return payload
|
||||
return {"tasks": tasks, "deadlines": deadlines, "links": links}
|
||||
|
||||
|
||||
def task_payload(conn, actor: UUID, task: dict, rights=None) -> dict:
|
||||
@@ -400,6 +925,30 @@ def task_payload(conn, actor: UUID, task: dict, rights=None) -> dict:
|
||||
action = _task_action_context(conn, actor, task)
|
||||
if action is not None:
|
||||
payload["action_context"] = action
|
||||
elements = []
|
||||
for link in conn.execute(
|
||||
"SELECT element_id FROM task_element_links WHERE task_id = %s ORDER BY created_at, element_id",
|
||||
(task["id"],),
|
||||
).fetchall():
|
||||
element = get_element(conn, link["element_id"])
|
||||
if element is None or element["deleted_at"] is not None:
|
||||
continue
|
||||
if not element_rights(conn, actor, element, None).read:
|
||||
continue
|
||||
elements.append({"id": str(element["id"]), "title": element["title"]})
|
||||
if elements:
|
||||
payload["elements"] = elements
|
||||
depends_on = []
|
||||
for link in conn.execute(
|
||||
"SELECT depends_on_task_id FROM task_dependencies WHERE task_id = %s ORDER BY created_at, depends_on_task_id",
|
||||
(task["id"],),
|
||||
).fetchall():
|
||||
earlier = get_task(conn, link["depends_on_task_id"])
|
||||
if earlier is None or not task_rights(conn, actor, earlier, None).read:
|
||||
continue
|
||||
depends_on.append({"id": str(earlier["id"]), "title": earlier["title"], "status": earlier["task_status"]})
|
||||
if depends_on:
|
||||
payload["depends_on"] = depends_on
|
||||
return payload
|
||||
|
||||
|
||||
@@ -472,6 +1021,7 @@ LABELS = {
|
||||
"annotation_created": "Kontextbezogene Anmerkung erfasst",
|
||||
"file_added": "Datei hinzugefügt",
|
||||
"external_ref_added": "Externe Referenz erfasst",
|
||||
"export_created": "Übergabepaket erzeugt",
|
||||
"binding_created": "Einbindung ergänzt",
|
||||
"binding_removed": "Einbindung entfernt",
|
||||
"element_deleted": "Element gelöscht",
|
||||
@@ -482,9 +1032,56 @@ LABELS = {
|
||||
"deadline_fulfilled": "Frist erfüllt",
|
||||
"grant_created": "Freigabe erteilt",
|
||||
"grant_revoked": "Freigabe entzogen",
|
||||
"source_read_mediated": "Verknüpftes Original gelesen",
|
||||
"correspondence_document": "Dokumentdatum",
|
||||
"correspondence_sent": "Versand",
|
||||
"correspondence_received": "Zugang",
|
||||
"correspondence_recorded": "Erfassung",
|
||||
"chapter_created": "Kapitel angelegt",
|
||||
"summary_changed": "Kurzbeschreibung geändert",
|
||||
"title_changed": "Titel geändert",
|
||||
"binding_chapter": "In ein Kapitel eingeordnet",
|
||||
"chapters_reordered": "Kapitelreihenfolge geändert",
|
||||
"chapter_dated": "Kapiteldatum geändert",
|
||||
"chapter_moved": "Kapitel umgehängt",
|
||||
"content_order": "Ordnungsart geändert",
|
||||
"content_reordered": "Eigene Reihenfolge geändert",
|
||||
"account_created": "Konto angelegt",
|
||||
"account_renamed": "Kontoname geändert",
|
||||
"account_disabled": "Konto deaktiviert",
|
||||
"account_enabled": "Konto aktiviert",
|
||||
"operator_granted": "Betreiberrolle vergeben",
|
||||
"operator_revoked": "Betreiberrolle entzogen",
|
||||
"password_reset": "Passwort zurückgesetzt",
|
||||
"password_changed": "Passwort geändert",
|
||||
"sessions_revoked": "Sitzungen beendet",
|
||||
"session_started": "Angemeldet",
|
||||
"session_ended": "Abgemeldet",
|
||||
"room_created": "Datenraum angelegt",
|
||||
"room_renamed": "Datenraum umbenannt",
|
||||
"room_archived": "Datenraum archiviert",
|
||||
"room_restored": "Datenraum wieder aktiviert",
|
||||
"membership_added": "Mitglied hinzugefügt",
|
||||
"membership_role_changed": "Raumrolle geändert",
|
||||
"membership_removed": "Mitglied entfernt",
|
||||
"invitation_created": "Einladung erstellt",
|
||||
"invitation_revoked": "Einladung widerrufen",
|
||||
"invitation_accepted": "Einladung angenommen",
|
||||
"visibility_changed": "Raumfreigabe geändert",
|
||||
"employee_promoted": "Mitarbeiter zum Hauptnutzer gemacht",
|
||||
"employee_disabled": "Mitarbeiter-Konto deaktiviert",
|
||||
"employee_enabled": "Mitarbeiter-Konto aktiviert",
|
||||
"employee_password_reset": "Passwort eines Mitarbeiters zurückgesetzt",
|
||||
"employee_removed": "Mitarbeiter aus allen Räumen entfernt",
|
||||
"room_shared": "Mit Datenraum geteilt",
|
||||
"room_share_changed": "Freigabe an Datenraum geändert",
|
||||
"room_unshared": "Freigabe an Datenraum beendet",
|
||||
"person_excluded": "Person von der Raumfreigabe ausgenommen",
|
||||
"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",
|
||||
"preference_changed": "Einstellung des Kontos geändert",
|
||||
"external_ref_bound": "Vorhandene Referenz zusätzlich eingebunden",
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Fetching the pictures a mail refers to, on the server and only on request.
|
||||
|
||||
The browser never contacts the sender: the server loads each picture, checks that it really is
|
||||
a PNG, JPEG, GIF or WebP, and hands it over inline. This hides the reader's address and device.
|
||||
It cannot hide that the mail was opened, because the sender sees the request.
|
||||
|
||||
Only public https addresses are fetched. The address is resolved once, every result must be a
|
||||
public one, and the connection goes to exactly that address, so a changing DNS answer cannot
|
||||
lead to an internal host. Redirects are followed a few times with the same checks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.client
|
||||
import ipaddress
|
||||
import socket
|
||||
import ssl
|
||||
from urllib.parse import urljoin, urlsplit
|
||||
|
||||
MAX_IMAGE_BYTES = 1_500_000
|
||||
MAX_REDIRECTS = 3
|
||||
TIMEOUT_SECONDS = 5
|
||||
MAX_IMAGES = 12
|
||||
MAX_TOTAL_BYTES = 6_000_000
|
||||
|
||||
_SIGNATURES = (
|
||||
(b"\x89PNG\r\n\x1a\n", "png"),
|
||||
(b"\xff\xd8\xff", "jpeg"),
|
||||
(b"GIF87a", "gif"),
|
||||
(b"GIF89a", "gif"),
|
||||
)
|
||||
|
||||
|
||||
class _Pinned(http.client.HTTPSConnection):
|
||||
"""An https connection that goes to a fixed, already checked address."""
|
||||
|
||||
def __init__(self, host: str, address: str, port: int) -> None:
|
||||
super().__init__(host, port, timeout=TIMEOUT_SECONDS, context=ssl.create_default_context())
|
||||
self._address = address
|
||||
|
||||
def connect(self) -> None:
|
||||
sock = socket.create_connection((self._address, self.port), self.timeout)
|
||||
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
|
||||
|
||||
|
||||
def is_public(address: str) -> bool:
|
||||
try:
|
||||
ip = ipaddress.ip_address(address)
|
||||
except ValueError:
|
||||
return False
|
||||
return ip.is_global and not ip.is_multicast
|
||||
|
||||
|
||||
def _public_address(host: str, port: int) -> str | None:
|
||||
try:
|
||||
found = {item[4][0] for item in socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)}
|
||||
except OSError:
|
||||
return None
|
||||
if not found or not all(is_public(address) for address in found):
|
||||
return None
|
||||
return sorted(found)[0]
|
||||
|
||||
|
||||
def _kind(data: bytes) -> str | None:
|
||||
for signature, kind in _SIGNATURES:
|
||||
if data.startswith(signature):
|
||||
return kind
|
||||
if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return "webp"
|
||||
return None
|
||||
|
||||
|
||||
def fetch_image(url: str) -> bytes | None:
|
||||
"""The bytes of a picture, or None when anything about it is not safe."""
|
||||
for _ in range(MAX_REDIRECTS + 1):
|
||||
parts = urlsplit(url)
|
||||
if parts.scheme != "https" or not parts.hostname or parts.username or parts.password:
|
||||
return None
|
||||
port = parts.port or 443
|
||||
if port != 443:
|
||||
return None
|
||||
address = _public_address(parts.hostname, port)
|
||||
if address is None:
|
||||
return None
|
||||
target = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
|
||||
connection = _Pinned(parts.hostname, address, port)
|
||||
try:
|
||||
connection.request("GET", target, headers={"User-Agent": "Mozilla/5.0", "Accept": "image/png,image/jpeg,image/gif,image/webp", "Connection": "close"})
|
||||
response = connection.getresponse()
|
||||
if response.status in {301, 302, 303, 307, 308}:
|
||||
location = response.getheader("Location")
|
||||
if not location:
|
||||
return None
|
||||
url = urljoin(url, location)
|
||||
continue
|
||||
if response.status != 200:
|
||||
return None
|
||||
data = response.read(MAX_IMAGE_BYTES + 1)
|
||||
except (OSError, http.client.HTTPException, ssl.SSLError):
|
||||
return None
|
||||
finally:
|
||||
connection.close()
|
||||
if len(data) > MAX_IMAGE_BYTES or _kind(data) is None:
|
||||
return None
|
||||
return data
|
||||
return None
|
||||
|
||||
|
||||
class RemoteImages:
|
||||
"""Loads the pictures of one mail within a budget and remembers each address once."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.cache: dict[str, str] = {}
|
||||
self.total = 0
|
||||
self.loaded = 0
|
||||
self.failed = 0
|
||||
|
||||
def __call__(self, url: str) -> str:
|
||||
if url in self.cache:
|
||||
return self.cache[url]
|
||||
result = ""
|
||||
if len(self.cache) < MAX_IMAGES and self.total < MAX_TOTAL_BYTES:
|
||||
data = fetch_image(url)
|
||||
if data is not None:
|
||||
self.total += len(data)
|
||||
result = f"data:image/{_kind(data)};base64,{base64.b64encode(data).decode('ascii')}"
|
||||
self.cache[url] = result
|
||||
if result:
|
||||
self.loaded += 1
|
||||
else:
|
||||
self.failed += 1
|
||||
return result
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Complete content retrieval for export.
|
||||
|
||||
Preview and original stay apart. A reference uses its own access, never an
|
||||
arbitrary latest connector. Missing capability is reported, not replaced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import Problem
|
||||
from app.mailpack import ParsedMail
|
||||
from app.media.port import read_clear_bytes
|
||||
from app.sources import COMPLETE_MAIL_LIMIT
|
||||
|
||||
EXPORT_BYTE_LIMIT = COMPLETE_MAIL_LIMIT
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RetrievalFailure:
|
||||
code: str
|
||||
message: str
|
||||
choices: tuple[dict, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FilePayload:
|
||||
filename: str
|
||||
media_type: str
|
||||
data: bytes
|
||||
sha256: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class MailPayload:
|
||||
raw: bytes
|
||||
parsed: ParsedMail
|
||||
notices: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def load_external(conn, actor_id: UUID, element_id: UUID, assigned: UUID | None) -> FilePayload | MailPayload | RetrievalFailure:
|
||||
from app.sourceregistry import get_source
|
||||
|
||||
ref = conn.execute(
|
||||
"""
|
||||
SELECT element_id, source, external_id, detail, connector_id, resolution
|
||||
FROM external_references WHERE element_id = %s
|
||||
""",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
if ref is None:
|
||||
return RetrievalFailure("missing", "Die Quellenreferenz fehlt.")
|
||||
module = get_source(ref["source"])
|
||||
if module is None or module.export_original is None:
|
||||
return RetrievalFailure("capability", "Für diese Quelle ist kein Originalabruf vorgesehen.")
|
||||
return module.export_original(conn, actor_id, ref["external_id"], ref["detail"] or {}, assigned, ref)
|
||||
|
||||
|
||||
def load_file(conn, element_id: UUID, media_root: str) -> FilePayload | RetrievalFailure:
|
||||
asset = conn.execute(
|
||||
"""
|
||||
SELECT id, original_filename, content_type, sha256, status,
|
||||
storage_instance_id, storage_generation, object_key, protection_profile
|
||||
FROM media_assets WHERE element_id = %s
|
||||
""",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
if asset is None or asset["status"] != "active":
|
||||
return RetrievalFailure("missing", "Die Originaldatei ist nicht mehr vorhanden.")
|
||||
if (asset["protection_profile"] or "legacy-plaintext") != "legacy-plaintext":
|
||||
return RetrievalFailure(
|
||||
"unsupported",
|
||||
"Dieser Inhalt ist geschützt und kann hier nicht im Klartext gelesen werden.",
|
||||
)
|
||||
try:
|
||||
data = read_clear_bytes(
|
||||
conn,
|
||||
instance_id=asset["storage_instance_id"],
|
||||
generation=asset["storage_generation"],
|
||||
object_key=asset["object_key"] or str(asset["id"]),
|
||||
media_root=media_root,
|
||||
protection_profile=asset["protection_profile"],
|
||||
expected_sha256=asset["sha256"],
|
||||
)
|
||||
except Problem as exc:
|
||||
if exc.code == "unsupported":
|
||||
return RetrievalFailure("unsupported", exc.detail)
|
||||
return RetrievalFailure("missing", "Die Originaldatei ist nicht mehr vorhanden.")
|
||||
if len(data) > EXPORT_BYTE_LIMIT:
|
||||
return RetrievalFailure("too_large", "Die Originaldatei ist für den Export zu groß.")
|
||||
return FilePayload(asset["original_filename"], asset["content_type"], data, asset["sha256"])
|
||||
|
||||
|
||||
def failure_from_problem(exc: Problem) -> RetrievalFailure:
|
||||
text = exc.detail
|
||||
lowered = text.casefold()
|
||||
if "exportgrenze" in lowered or "zu groß" in lowered:
|
||||
code = "too_large"
|
||||
elif "mehrdeutig" in lowered or "nicht eindeutig" in lowered or "nicht die referenzierte" in lowered:
|
||||
code = "identity"
|
||||
elif "nicht erreichbar" in lowered or "abgelehnt" in lowered:
|
||||
code = "unreachable"
|
||||
elif "vorschau wird nicht" in lowered or "nicht verfügbar" in lowered or "gibt es" in lowered:
|
||||
code = "missing"
|
||||
else:
|
||||
code = "missing"
|
||||
return RetrievalFailure(code, text)
|
||||
+24
-8
@@ -1,4 +1,4 @@
|
||||
"""Synthetic development accounts and a rental matter. Never runs in production."""
|
||||
"""Synthetic rental case for the ephemeral test database. Never persists on dev or prod."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -47,8 +47,24 @@ trailer<</Root 1 0 R>>
|
||||
"""
|
||||
|
||||
|
||||
_LIVE_DATABASES = frozenset({"tsumugu", "tsumugu_dev", "postgres", "template0", "template1"})
|
||||
|
||||
|
||||
def is_test_database(name: str) -> bool:
|
||||
lowered = name.strip().lower()
|
||||
return bool(lowered) and lowered.endswith("_test") and lowered not in _LIVE_DATABASES
|
||||
|
||||
|
||||
def demo_allowed(settings: Settings) -> bool:
|
||||
return (
|
||||
settings.tsumugu_env == "development"
|
||||
and is_test_database(settings.db_name)
|
||||
and settings.seed_demo
|
||||
)
|
||||
|
||||
|
||||
def demo_public(settings: Settings) -> dict:
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
if not demo_allowed(settings):
|
||||
raise not_found()
|
||||
return {
|
||||
"accounts": [
|
||||
@@ -60,22 +76,22 @@ def demo_public(settings: Settings) -> dict:
|
||||
|
||||
def seed_demo(settings: Settings | None = None) -> bool:
|
||||
settings = settings or get_settings()
|
||||
if settings.tsumugu_env != "development" or not settings.seed_demo:
|
||||
if not demo_allowed(settings):
|
||||
return False
|
||||
cleanup: list[Path] = []
|
||||
with psycopg.connect(settings.dsn(), row_factory=dict_row) as conn:
|
||||
try:
|
||||
if conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone():
|
||||
return False
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD)
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD)
|
||||
ada = create_account(conn, ADA_EMAIL, "Ada Beispiel", ADA_PASSWORD, origin="fixture")
|
||||
ben = create_account(conn, BEN_EMAIL, "Ben Beispiel", BEN_PASSWORD, origin="fixture")
|
||||
room = conn.execute(
|
||||
"""
|
||||
INSERT INTO data_rooms (id, kind, name, created_by)
|
||||
VALUES (gen_random_uuid(), 'organization', 'Haushalt Musterstraße', %s)
|
||||
INSERT INTO data_rooms (id, kind, name, created_by, owner_id)
|
||||
VALUES (gen_random_uuid(), 'organization', 'Haushalt Musterstraße', %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(ada["id"],),
|
||||
(ada["id"], ada["id"]),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager'), (%s, %s, 'member')",
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Rights stay in one place. A source module only fetches its own bytes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
import psycopg
|
||||
|
||||
from app.access.policy import Ctx, audit, mediated_source_owner
|
||||
from app.core.errors import Problem, not_found, unprocessable
|
||||
from app.sourcebind import resolve_for_read
|
||||
|
||||
ORIGINAL_UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar."
|
||||
|
||||
|
||||
@dataclass
|
||||
class BorrowedOriginal:
|
||||
row: dict
|
||||
external_id: str
|
||||
mediated: bool
|
||||
actor_id: UUID
|
||||
owner_id: UUID
|
||||
element: dict
|
||||
context: Ctx | None
|
||||
kind: str
|
||||
|
||||
|
||||
def release_for_external(conn) -> None:
|
||||
"""External calls must not sit inside an open domain transaction."""
|
||||
if conn.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
|
||||
conn.commit()
|
||||
|
||||
|
||||
def connector_owner(conn, connector_id: UUID | None) -> UUID | None:
|
||||
if connector_id is None:
|
||||
return None
|
||||
row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (connector_id,)).fetchone()
|
||||
return row["owner_id"] if row else None
|
||||
|
||||
|
||||
def assert_still_owned(conn, connector_id, owner_id: UUID) -> None:
|
||||
row = conn.execute(
|
||||
"SELECT id FROM connectors WHERE id = %s AND owner_id = %s",
|
||||
(connector_id, owner_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
|
||||
|
||||
def audit_mediated(conn, actor_id: UUID, element: dict, context: Ctx | None, source: str, connector_id, outcome: str) -> None:
|
||||
audit(
|
||||
conn,
|
||||
actor_id,
|
||||
element["home_scope_id"],
|
||||
"source_read_mediated",
|
||||
"element",
|
||||
element["id"],
|
||||
context,
|
||||
result="ok" if outcome == "ok" else "unavailable",
|
||||
detail={
|
||||
"source": source,
|
||||
"connector_id": str(connector_id) if connector_id else None,
|
||||
"outcome": outcome,
|
||||
},
|
||||
)
|
||||
if outcome != "ok":
|
||||
conn.commit()
|
||||
|
||||
|
||||
def _uuid(value) -> UUID | None:
|
||||
if isinstance(value, UUID):
|
||||
return value
|
||||
try:
|
||||
return UUID(str(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def borrow_original(conn, actor_id: UUID, element: dict, context: Ctx | None, ref, kind: str) -> BorrowedOriginal:
|
||||
"""Resolve the owner's connector. A grantee never supplies another account's connector."""
|
||||
detail = (ref or {}).get("detail") or {}
|
||||
external_id = str((ref or {}).get("external_id") or "")
|
||||
stored = _uuid(detail.get("connector_id")) or _uuid((ref or {}).get("connector_id"))
|
||||
stored_owner = connector_owner(conn, stored)
|
||||
mediated = not (element["owner_subject_id"] == actor_id or stored_owner == actor_id)
|
||||
if mediated:
|
||||
owner_id = mediated_source_owner(conn, actor_id, element, context)
|
||||
if owner_id is None:
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
else:
|
||||
owner_id = actor_id
|
||||
result = resolve_for_read(conn, owner_id, kind, ref, None)
|
||||
if result.row is None:
|
||||
if mediated:
|
||||
audit_mediated(conn, actor_id, element, context, kind, stored, "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
raise unprocessable(result.message)
|
||||
return BorrowedOriginal(
|
||||
row=result.row,
|
||||
external_id=external_id,
|
||||
mediated=mediated,
|
||||
actor_id=actor_id,
|
||||
owner_id=owner_id,
|
||||
element=element,
|
||||
context=context,
|
||||
kind=kind,
|
||||
)
|
||||
|
||||
|
||||
def _recheck(conn, borrowed: BorrowedOriginal) -> None:
|
||||
if borrowed.mediated:
|
||||
owner_id = mediated_source_owner(conn, borrowed.actor_id, borrowed.element, borrowed.context)
|
||||
if owner_id != borrowed.owner_id:
|
||||
audit_mediated(conn, borrowed.actor_id, borrowed.element, borrowed.context, borrowed.kind, borrowed.row["id"], "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
row = conn.execute("SELECT owner_id FROM connectors WHERE id = %s", (borrowed.row["id"],)).fetchone()
|
||||
if row is None or row["owner_id"] != borrowed.owner_id:
|
||||
if borrowed.mediated:
|
||||
audit_mediated(conn, borrowed.actor_id, borrowed.element, borrowed.context, borrowed.kind, borrowed.row["id"], "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE)
|
||||
raise not_found()
|
||||
|
||||
|
||||
def complete_borrow(conn, borrowed: BorrowedOriginal, fetch):
|
||||
"""Run the adapter fetch outside the open transaction, then check the grant again."""
|
||||
release_for_external(conn)
|
||||
try:
|
||||
value = fetch(borrowed.row)
|
||||
except Problem:
|
||||
if borrowed.mediated:
|
||||
audit_mediated(conn, borrowed.actor_id, borrowed.element, borrowed.context, borrowed.kind, borrowed.row["id"], "unavailable")
|
||||
raise unprocessable(ORIGINAL_UNAVAILABLE) from None
|
||||
raise
|
||||
_recheck(conn, borrowed)
|
||||
if borrowed.mediated:
|
||||
audit_mediated(conn, borrowed.actor_id, borrowed.element, borrowed.context, borrowed.kind, borrowed.row["id"], "ok")
|
||||
return value
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Bind a reference to one connector instance.
|
||||
|
||||
The newest connection is never a fallback. A stored id that no longer
|
||||
exists stays missing. Ambiguous stock waits for an explicit assignment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
from psycopg.types.json import Json
|
||||
|
||||
from app.access.policy import get_element
|
||||
from app.core.errors import not_found, unprocessable
|
||||
from app.sourceregistry import get_source
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolveResult:
|
||||
row: dict | None
|
||||
code: str
|
||||
message: str
|
||||
choices: tuple[dict, ...] = ()
|
||||
|
||||
|
||||
def _uuid(value) -> UUID | None:
|
||||
if isinstance(value, UUID):
|
||||
return value
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return UUID(str(value))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def stored_id(ref) -> UUID | None:
|
||||
if not ref:
|
||||
return None
|
||||
detail = ref["detail"] if "detail" in ref.keys() else None
|
||||
detail = detail or {}
|
||||
return _uuid(detail.get("connector_id")) or _uuid(ref["connector_id"] if "connector_id" in ref.keys() else None)
|
||||
|
||||
|
||||
def _connectors(conn, owner_id: UUID, kind: str) -> list[dict]:
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT id, owner_id, kind, name, settings, secret
|
||||
FROM connectors
|
||||
WHERE owner_id = %s AND kind = %s
|
||||
ORDER BY name, id
|
||||
""",
|
||||
(owner_id, kind),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def resolve_for_read(conn, owner_id: UUID, kind: str, ref, assigned: UUID | None) -> ResolveResult:
|
||||
"""Resolve one access. Assignment applies only when the reference has no stored id."""
|
||||
stored = stored_id(ref)
|
||||
resolution = (ref["resolution"] if ref and "resolution" in ref.keys() and ref["resolution"] else None) or "unresolved"
|
||||
rows = _connectors(conn, owner_id, kind)
|
||||
if stored is not None:
|
||||
match = next((row for row in rows if row["id"] == stored), None)
|
||||
if match is None:
|
||||
return ResolveResult(None, "missing", "Der gespeicherte Zugang für diese Quelle ist nicht mehr vorhanden.")
|
||||
return ResolveResult(match, "ok", "")
|
||||
if assigned is not None:
|
||||
match = next((row for row in rows if row["id"] == assigned), None)
|
||||
if match is None:
|
||||
return ResolveResult(
|
||||
None,
|
||||
"assignment",
|
||||
"Der gewählte Zugang gehört nicht zu diesem Konto oder passt nicht zur Quelle.",
|
||||
)
|
||||
return ResolveResult(match, "ok", "")
|
||||
if resolution == "ambiguous" or len(rows) != 1:
|
||||
if not rows:
|
||||
return ResolveResult(None, "missing", "Für diese Quelle ist kein Zugang vorhanden.")
|
||||
return ResolveResult(
|
||||
None,
|
||||
"ambiguous",
|
||||
"Für diese Quelle ist kein eindeutiger Zugang zugeordnet. Die Zuordnung muss bewusst gewählt werden.",
|
||||
tuple({"id": str(row["id"]), "name": row["name"]} for row in rows),
|
||||
)
|
||||
return ResolveResult(rows[0], "ok", "")
|
||||
|
||||
|
||||
def _set_binding(conn, element_id: UUID, connector_id: UUID | None, resolution: str, detail: dict | None = None) -> None:
|
||||
if detail is None:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET connector_id = %s, resolution = %s
|
||||
WHERE element_id = %s
|
||||
""",
|
||||
(connector_id, resolution, element_id),
|
||||
)
|
||||
return
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET connector_id = %s, resolution = %s, detail = %s
|
||||
WHERE element_id = %s
|
||||
""",
|
||||
(connector_id, resolution, Json(detail), element_id),
|
||||
)
|
||||
|
||||
|
||||
def attach_new_reference(conn, element_id: UUID) -> None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT er.source, er.detail, e.owner_subject_id
|
||||
FROM external_references er
|
||||
JOIN elements e ON e.id = er.element_id
|
||||
WHERE er.element_id = %s
|
||||
""",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return
|
||||
if get_source(row["source"]) is None:
|
||||
_set_binding(conn, element_id, None, "none")
|
||||
return
|
||||
detail = dict(row["detail"] or {})
|
||||
stored = _uuid(detail.get("connector_id"))
|
||||
if stored is not None:
|
||||
match = conn.execute(
|
||||
"""
|
||||
SELECT id FROM connectors
|
||||
WHERE id = %s AND owner_id = %s AND kind = %s
|
||||
""",
|
||||
(stored, row["owner_subject_id"], row["source"]),
|
||||
).fetchone()
|
||||
_set_binding(conn, element_id, stored, "bound" if match else "unresolved")
|
||||
return
|
||||
rows = _connectors(conn, row["owner_subject_id"], row["source"])
|
||||
if len(rows) == 1:
|
||||
detail["connector_id"] = str(rows[0]["id"])
|
||||
_set_binding(conn, element_id, rows[0]["id"], "bound", detail)
|
||||
return
|
||||
if len(rows) > 1:
|
||||
_set_binding(conn, element_id, None, "ambiguous")
|
||||
return
|
||||
_set_binding(conn, element_id, None, "unresolved")
|
||||
|
||||
|
||||
def backfill_source_bindings(conn) -> None:
|
||||
"""Idempotent. Unique stock is bound once. A stored id is never retargeted.
|
||||
|
||||
Startup calls this before the application has imported the connector
|
||||
modules. Register them first, otherwise every existing reference stays
|
||||
unresolved and the case or matter can no longer open its originals.
|
||||
"""
|
||||
from app.sources import _install_sources
|
||||
|
||||
_install_sources()
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET resolution = 'none'
|
||||
WHERE source = 'url' AND resolution = 'unresolved'
|
||||
"""
|
||||
)
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT er.element_id, er.source, er.detail, e.owner_subject_id
|
||||
FROM external_references er
|
||||
JOIN elements e ON e.id = er.element_id
|
||||
WHERE er.source <> 'url'
|
||||
AND er.resolution IN ('unresolved', 'ambiguous')
|
||||
AND er.connector_id IS NULL
|
||||
"""
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
if get_source(row["source"]) is None:
|
||||
continue
|
||||
detail = dict(row["detail"] or {})
|
||||
stored = _uuid(detail.get("connector_id"))
|
||||
if stored is not None:
|
||||
match = conn.execute(
|
||||
"""
|
||||
SELECT id FROM connectors
|
||||
WHERE id = %s AND owner_id = %s AND kind = %s
|
||||
""",
|
||||
(stored, row["owner_subject_id"], row["source"]),
|
||||
).fetchone()
|
||||
_set_binding(conn, row["element_id"], stored, "bound" if match else "unresolved")
|
||||
continue
|
||||
found = _connectors(conn, row["owner_subject_id"], row["source"])
|
||||
if len(found) == 1:
|
||||
detail["connector_id"] = str(found[0]["id"])
|
||||
_set_binding(conn, row["element_id"], found[0]["id"], "bound", detail)
|
||||
elif len(found) > 1:
|
||||
_set_binding(conn, row["element_id"], None, "ambiguous")
|
||||
|
||||
|
||||
def assign_reference(conn, actor_id: UUID, element_id: UUID, connector_id: UUID) -> None:
|
||||
element = get_element(conn, element_id)
|
||||
if element is None or element["kind"] != "external_ref" or element["owner_subject_id"] != actor_id:
|
||||
raise not_found()
|
||||
ref = conn.execute(
|
||||
"SELECT source, detail FROM external_references WHERE element_id = %s",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
if ref is None or get_source(ref["source"]) is None:
|
||||
raise unprocessable("Diese Referenz hat keinen Quellzugang.")
|
||||
connector = conn.execute(
|
||||
"""
|
||||
SELECT id, kind FROM connectors
|
||||
WHERE id = %s AND owner_id = %s
|
||||
""",
|
||||
(connector_id, actor_id),
|
||||
).fetchone()
|
||||
if connector is None or connector["kind"] != ref["source"]:
|
||||
raise unprocessable("Der Zugang gehört nicht zu diesem Konto oder passt nicht zur Quelle.")
|
||||
detail = dict(ref["detail"] or {})
|
||||
detail["connector_id"] = str(connector_id)
|
||||
_set_binding(conn, element_id, connector_id, "bound", detail)
|
||||
|
||||
|
||||
def remember_imap_location(
|
||||
conn,
|
||||
element_id: UUID,
|
||||
external_id: str,
|
||||
previous_mailbox: str,
|
||||
previous_uid: int,
|
||||
mailbox: str,
|
||||
uid: int,
|
||||
) -> None:
|
||||
"""Store the folder and UID of a message found at a new place.
|
||||
|
||||
Only the previous place is replaced. The message identity, the connector
|
||||
and an adopted direction stay as they were.
|
||||
"""
|
||||
if (
|
||||
not mailbox
|
||||
or any(char in mailbox for char in "\r\n\x00")
|
||||
or uid < 1
|
||||
or (mailbox == previous_mailbox and uid == previous_uid)
|
||||
):
|
||||
return
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET detail = jsonb_set(
|
||||
jsonb_set(detail, '{mailbox}', to_jsonb(%s::text)),
|
||||
'{uid}',
|
||||
to_jsonb(%s::bigint)
|
||||
)
|
||||
WHERE element_id = %s
|
||||
AND source = 'imap'
|
||||
AND external_id = %s
|
||||
AND detail->>'mailbox' = %s
|
||||
AND detail->>'uid' = %s
|
||||
""",
|
||||
(mailbox, uid, element_id, external_id, previous_mailbox, str(previous_uid)),
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Declared editor capabilities and the payloads that carry them.
|
||||
|
||||
The capabilities of a source belong to its module. A filter is offered only when that module implements it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
EDITORS = {
|
||||
"note": True,
|
||||
"markdown_file": False,
|
||||
}
|
||||
|
||||
|
||||
def capability_payload() -> dict:
|
||||
from app.sourceregistry import registered_sources
|
||||
|
||||
return {
|
||||
"sources": [module.capabilities for module in registered_sources()],
|
||||
"modules": [
|
||||
{
|
||||
"kind": module.kind,
|
||||
"label": module.label,
|
||||
"representation": module.representation,
|
||||
"config_fields": [item.public() for item in module.config_fields],
|
||||
}
|
||||
for module in registered_sources()
|
||||
],
|
||||
"editors": EDITORS,
|
||||
"protection_profiles": {
|
||||
"legacy-plaintext": "cleartext",
|
||||
"managed-encrypted": "locked",
|
||||
"client-encrypted": "locked",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def with_capabilities(kind: str, connector_id: str, payload: dict) -> dict:
|
||||
from app.sourceregistry import require_source
|
||||
|
||||
body = dict(payload)
|
||||
spec = require_source(kind).capabilities
|
||||
body["connector_id"] = connector_id
|
||||
body["capabilities"] = spec
|
||||
body["unsupported"] = [name for name, enabled in spec["search"].items() if not enabled]
|
||||
if spec["search"].get("continuation"):
|
||||
body["continuation"] = body.get("next_before") if body.get("next_before") is not None else body.get("next_page")
|
||||
else:
|
||||
body["continuation"] = None
|
||||
body["incomplete"] = bool(body.get("incomplete"))
|
||||
return body
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Registered source modules. Unknown kinds are rejected, not guessed."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
from app.core.errors import unprocessable
|
||||
|
||||
FIELD_TYPES = ("text", "url", "number", "password", "select")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConfigField:
|
||||
"""One configuration field a module declares for its connector instances.
|
||||
|
||||
At most one field per module is a secret. Its value is stored apart from
|
||||
the settings and is never handed out again.
|
||||
"""
|
||||
|
||||
key: str
|
||||
label: str
|
||||
type: str = "text"
|
||||
required: bool = False
|
||||
secret: bool = False
|
||||
default: str | int | None = None
|
||||
options: tuple[tuple[str, str], ...] = ()
|
||||
help: str = ""
|
||||
placeholder: str = ""
|
||||
minimum: int | None = None
|
||||
maximum: int | None = None
|
||||
max_length: int = 200
|
||||
|
||||
def public(self) -> dict:
|
||||
return {
|
||||
"key": self.key,
|
||||
"label": self.label,
|
||||
"type": self.type,
|
||||
"required": self.required,
|
||||
"secret": self.secret,
|
||||
"default": self.default,
|
||||
"options": [{"value": value, "label": label} for value, label in self.options],
|
||||
"help": self.help,
|
||||
"placeholder": self.placeholder,
|
||||
"minimum": self.minimum,
|
||||
"maximum": self.maximum,
|
||||
"max_length": self.max_length,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class SourceModule:
|
||||
kind: str
|
||||
label: str
|
||||
representation: str
|
||||
capabilities: dict
|
||||
probe: Callable
|
||||
find: Callable
|
||||
open_original: Callable
|
||||
export_original: Callable
|
||||
# A module either declares fields (generic validation) or parses the payload itself.
|
||||
parse_config: Callable[[dict], tuple[str, dict, str]] | None = None
|
||||
config_fields: tuple[ConfigField, ...] = ()
|
||||
normalize_config: Callable[[dict, str], dict] | None = None
|
||||
navigate: Callable | None = None
|
||||
preview: Callable | None = None
|
||||
facets: Callable | None = None
|
||||
# Query parameter of a search, mapped to the capability flag that must be true for it.
|
||||
# The module owns its filter names. Anything not declared here is refused.
|
||||
search_params: dict[str, str] = field(default_factory=dict)
|
||||
# thumbnail(conn, owner_id, connector_id, item) -> (bytes, media type), when the module declares it.
|
||||
thumbnail: Callable | None = None
|
||||
|
||||
|
||||
_MODULES: dict[str, SourceModule] = {}
|
||||
|
||||
|
||||
def register_source(module: SourceModule) -> None:
|
||||
if module.parse_config is None and not module.config_fields:
|
||||
raise ValueError(f"Quelle {module.kind} braucht Konfigurationsfelder oder parse_config.")
|
||||
if sum(1 for item in module.config_fields if item.secret) > 1:
|
||||
raise ValueError(f"Quelle {module.kind} darf höchstens ein Geheimnisfeld haben.")
|
||||
for item in module.config_fields:
|
||||
if item.type not in FIELD_TYPES:
|
||||
raise ValueError(f"Feldtyp {item.type} ist unbekannt.")
|
||||
_MODULES[module.kind] = module
|
||||
|
||||
|
||||
def unregister_source(kind: str) -> None:
|
||||
_MODULES.pop(kind, None)
|
||||
|
||||
|
||||
def registered_sources() -> list[SourceModule]:
|
||||
return list(_MODULES.values())
|
||||
|
||||
|
||||
def get_source(kind: str) -> SourceModule | None:
|
||||
return _MODULES.get(kind)
|
||||
|
||||
|
||||
def require_source(kind: str) -> SourceModule:
|
||||
module = _MODULES.get(kind)
|
||||
if module is None:
|
||||
raise unprocessable("Diese Quelle ist nicht registriert.")
|
||||
return module
|
||||
|
||||
|
||||
def accepts_reference(source: str) -> bool:
|
||||
return source == "url" or source in _MODULES
|
||||
|
||||
|
||||
def _blank(value) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
|
||||
def _coerce(field: ConfigField, value):
|
||||
if field.type == "number":
|
||||
try:
|
||||
number = int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
raise unprocessable(f"{field.label} muss eine ganze Zahl sein.") from None
|
||||
if field.minimum is not None and number < field.minimum:
|
||||
raise unprocessable(f"{field.label} ist zu klein.")
|
||||
if field.maximum is not None and number > field.maximum:
|
||||
raise unprocessable(f"{field.label} ist zu groß.")
|
||||
return number
|
||||
text = str(value) if field.secret else str(value).strip()
|
||||
if len(text) > field.max_length:
|
||||
raise unprocessable(f"{field.label} ist zu lang.")
|
||||
if field.type == "select" and text not in {option for option, _label in field.options}:
|
||||
raise unprocessable(f"{field.label} ist keine zulässige Auswahl.")
|
||||
return text
|
||||
|
||||
|
||||
def parse_fields(
|
||||
fields: tuple[ConfigField, ...],
|
||||
values: dict,
|
||||
current_settings: dict | None = None,
|
||||
current_secret: str = "",
|
||||
) -> tuple[dict, str]:
|
||||
"""Validate declared fields. Unknown keys are refused, a blank secret keeps the stored one."""
|
||||
known = {item.key for item in fields}
|
||||
extra = sorted(key for key, value in values.items() if key not in known and not _blank(value))
|
||||
if extra:
|
||||
raise unprocessable("Unbekanntes Konfigurationsfeld: " + ", ".join(extra[:3]) + ".")
|
||||
current_settings = current_settings or {}
|
||||
settings: dict = {}
|
||||
secret = current_secret
|
||||
for item in fields:
|
||||
raw = values.get(item.key)
|
||||
if item.secret:
|
||||
if _blank(raw):
|
||||
if not current_secret and item.required:
|
||||
raise unprocessable(f"{item.label} fehlt.")
|
||||
continue
|
||||
secret = _coerce(item, raw)
|
||||
continue
|
||||
if _blank(raw):
|
||||
raw = current_settings.get(item.key)
|
||||
if _blank(raw):
|
||||
raw = item.default
|
||||
if _blank(raw):
|
||||
if item.required:
|
||||
raise unprocessable(f"{item.label} fehlt.")
|
||||
continue
|
||||
settings[item.key] = _coerce(item, raw)
|
||||
return settings, secret
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,19 @@
|
||||
ALTER TABLE external_references DROP CONSTRAINT external_references_source;
|
||||
ALTER TABLE external_references
|
||||
ADD CONSTRAINT external_references_source CHECK (source IN ('paperless', 'url', 'imap'));
|
||||
ALTER TABLE external_references
|
||||
ADD COLUMN detail jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||
|
||||
CREATE TABLE connectors (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
owner_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
kind text NOT NULL,
|
||||
name text NOT NULL,
|
||||
settings jsonb NOT NULL,
|
||||
secret text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT connectors_kind CHECK (kind IN ('paperless', 'imap')),
|
||||
CONSTRAINT connectors_name_len CHECK (char_length(name) BETWEEN 1 AND 120)
|
||||
);
|
||||
|
||||
CREATE INDEX connectors_owner ON connectors (owner_id, kind);
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Betreiberkonten und Testdaten bleiben unterscheidbar.
|
||||
-- Bestehende Beispielkonten sind Fixtures und werden beim Start entfernt.
|
||||
|
||||
ALTER TABLE auth_accounts
|
||||
ADD COLUMN is_superadmin boolean NOT NULL DEFAULT false,
|
||||
ADD COLUMN origin text NOT NULL DEFAULT 'operator';
|
||||
|
||||
ALTER TABLE auth_accounts
|
||||
ADD CONSTRAINT auth_accounts_origin CHECK (origin IN ('operator', 'fixture'));
|
||||
|
||||
UPDATE auth_accounts
|
||||
SET origin = 'fixture'
|
||||
WHERE email IN ('ada@example.test', 'ben@example.test');
|
||||
@@ -0,0 +1,15 @@
|
||||
ALTER TABLE cases
|
||||
ADD COLUMN content_order text NOT NULL DEFAULT 'position',
|
||||
ADD COLUMN content_order_dir text NOT NULL DEFAULT 'asc';
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD CONSTRAINT cases_content_order CHECK (content_order IN ('date', 'position')),
|
||||
ADD CONSTRAINT cases_content_order_dir CHECK (content_order_dir IN ('asc', 'desc'));
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD COLUMN content_order text NOT NULL DEFAULT 'position',
|
||||
ADD COLUMN content_order_dir text NOT NULL DEFAULT 'asc';
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD CONSTRAINT matters_content_order CHECK (content_order IN ('date', 'position')),
|
||||
ADD CONSTRAINT matters_content_order_dir CHECK (content_order_dir IN ('asc', 'desc'));
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE elements
|
||||
ADD COLUMN summary text;
|
||||
|
||||
ALTER TABLE elements
|
||||
ADD CONSTRAINT elements_summary_len CHECK (summary IS NULL OR char_length(summary) BETWEEN 1 AND 400);
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE chapters
|
||||
ADD COLUMN document_on date;
|
||||
@@ -0,0 +1,16 @@
|
||||
CREATE TABLE task_element_links (
|
||||
task_id uuid NOT NULL REFERENCES tasks (id),
|
||||
element_id uuid NOT NULL REFERENCES elements (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, element_id)
|
||||
);
|
||||
|
||||
CREATE TABLE task_dependencies (
|
||||
task_id uuid NOT NULL REFERENCES tasks (id),
|
||||
depends_on_task_id uuid NOT NULL REFERENCES tasks (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, depends_on_task_id),
|
||||
CONSTRAINT task_dependencies_not_self CHECK (task_id <> depends_on_task_id)
|
||||
);
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE element_references (
|
||||
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
refers_to_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (element_id, refers_to_element_id),
|
||||
CHECK (element_id <> refers_to_element_id)
|
||||
);
|
||||
|
||||
CREATE INDEX element_references_target_idx ON element_references (refers_to_element_id);
|
||||
@@ -0,0 +1,7 @@
|
||||
ALTER TABLE bindings
|
||||
ADD COLUMN communication_direction text,
|
||||
ADD COLUMN direction_explicit boolean NOT NULL DEFAULT false;
|
||||
|
||||
ALTER TABLE bindings
|
||||
ADD CONSTRAINT bindings_communication_direction
|
||||
CHECK (communication_direction IS NULL OR communication_direction IN ('in', 'out'));
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE bindings DROP CONSTRAINT bindings_communication_direction;
|
||||
|
||||
ALTER TABLE bindings
|
||||
ADD CONSTRAINT bindings_communication_direction
|
||||
CHECK (communication_direction IS NULL OR communication_direction IN ('in', 'out', 'local'));
|
||||
@@ -0,0 +1,54 @@
|
||||
ALTER TABLE chapters
|
||||
ADD COLUMN parent_chapter_id uuid;
|
||||
|
||||
ALTER TABLE chapters
|
||||
ADD CONSTRAINT chapters_not_self
|
||||
CHECK (parent_chapter_id IS NULL OR parent_chapter_id <> id);
|
||||
|
||||
ALTER TABLE chapters
|
||||
ADD CONSTRAINT chapters_parent_fk
|
||||
FOREIGN KEY (parent_chapter_id) REFERENCES chapters (id);
|
||||
|
||||
CREATE INDEX chapters_parent ON chapters (parent_chapter_id);
|
||||
|
||||
CREATE FUNCTION chapters_parent_guard() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
parent chapters%ROWTYPE;
|
||||
current_id uuid;
|
||||
seen uuid[] := ARRAY[]::uuid[];
|
||||
depth integer := 1;
|
||||
BEGIN
|
||||
IF NEW.parent_chapter_id IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
SELECT * INTO parent FROM chapters WHERE id = NEW.parent_chapter_id;
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION 'Kapiteleltern ungültig';
|
||||
END IF;
|
||||
IF NEW.case_id IS DISTINCT FROM parent.case_id
|
||||
OR NEW.matter_id IS DISTINCT FROM parent.matter_id
|
||||
OR NEW.home_scope_id IS DISTINCT FROM parent.home_scope_id THEN
|
||||
RAISE EXCEPTION 'Kapiteleltern ungültig';
|
||||
END IF;
|
||||
current_id := NEW.parent_chapter_id;
|
||||
WHILE current_id IS NOT NULL LOOP
|
||||
IF current_id = NEW.id OR current_id = ANY (seen) THEN
|
||||
RAISE EXCEPTION 'Kapiteleltern ungültig';
|
||||
END IF;
|
||||
seen := array_append(seen, current_id);
|
||||
depth := depth + 1;
|
||||
IF depth > 32 THEN
|
||||
RAISE EXCEPTION 'Kapiteleltern ungültig';
|
||||
END IF;
|
||||
SELECT parent_chapter_id INTO current_id FROM chapters WHERE id = current_id;
|
||||
END LOOP;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TRIGGER chapters_parent_guard
|
||||
BEFORE INSERT OR UPDATE OF parent_chapter_id, case_id, matter_id, home_scope_id
|
||||
ON chapters
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION chapters_parent_guard();
|
||||
@@ -0,0 +1,147 @@
|
||||
-- Anlagenverwendung, dokumentierter Versand und Arbeitsansicht.
|
||||
-- Bestehende Kapitel, Einbindungen und Dateien bleiben unverändert.
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD COLUMN content_view text NOT NULL DEFAULT 'structure';
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD CONSTRAINT cases_content_view
|
||||
CHECK (content_view IN ('structure', 'chronology'));
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD COLUMN content_view text NOT NULL DEFAULT 'structure';
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD CONSTRAINT matters_content_view
|
||||
CHECK (content_view IN ('structure', 'chronology'));
|
||||
|
||||
ALTER TABLE bindings
|
||||
ADD COLUMN list_fold text;
|
||||
|
||||
ALTER TABLE bindings
|
||||
ADD CONSTRAINT bindings_list_fold
|
||||
CHECK (list_fold IS NULL OR list_fold IN ('attachment', 'evidence'));
|
||||
|
||||
CREATE TABLE attachment_uses (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
context_kind text NOT NULL,
|
||||
context_id uuid NOT NULL,
|
||||
host_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
attachment_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
position integer NOT NULL,
|
||||
label text,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT attachment_uses_kind CHECK (context_kind IN ('case', 'matter')),
|
||||
CONSTRAINT attachment_uses_not_self CHECK (host_element_id <> attachment_element_id),
|
||||
CONSTRAINT attachment_uses_position CHECK (position >= 0),
|
||||
CONSTRAINT attachment_uses_label CHECK (label IS NULL OR char_length(label) BETWEEN 1 AND 200),
|
||||
CONSTRAINT attachment_uses_once UNIQUE (context_kind, context_id, host_element_id, attachment_element_id)
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_uses_host
|
||||
ON attachment_uses (context_kind, context_id, host_element_id, position);
|
||||
|
||||
CREATE TABLE dispatches (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
context_kind text NOT NULL,
|
||||
context_id uuid NOT NULL,
|
||||
host_element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
channel text NOT NULL,
|
||||
sent_on date,
|
||||
counterpart text,
|
||||
completeness text NOT NULL,
|
||||
provenance text NOT NULL,
|
||||
recorded_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
recorded_at timestamptz NOT NULL DEFAULT now(),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT dispatches_kind CHECK (context_kind IN ('case', 'matter')),
|
||||
CONSTRAINT dispatches_channel CHECK (channel IN ('email', 'post', 'other')),
|
||||
CONSTRAINT dispatches_completeness CHECK (completeness IN ('secured', 'partial', 'gap')),
|
||||
CONSTRAINT dispatches_provenance CHECK (provenance IN ('captured', 'reconstructed')),
|
||||
CONSTRAINT dispatches_counterpart CHECK (counterpart IS NULL OR char_length(counterpart) BETWEEN 1 AND 200),
|
||||
CONSTRAINT dispatches_version CHECK (version >= 1)
|
||||
);
|
||||
|
||||
CREATE INDEX dispatches_host
|
||||
ON dispatches (context_kind, context_id, host_element_id, recorded_at);
|
||||
|
||||
CREATE TABLE dispatch_items (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
|
||||
role text NOT NULL,
|
||||
position integer NOT NULL,
|
||||
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
title text NOT NULL,
|
||||
document_on date,
|
||||
filename text,
|
||||
content_type text,
|
||||
byte_size bigint,
|
||||
content_sha256 text,
|
||||
source_state text NOT NULL,
|
||||
gap_reason text,
|
||||
note_document jsonb,
|
||||
external_source text,
|
||||
external_id text,
|
||||
CONSTRAINT dispatch_items_role CHECK (role IN ('host', 'attachment')),
|
||||
CONSTRAINT dispatch_items_position CHECK (position >= 0),
|
||||
CONSTRAINT dispatch_items_state CHECK (source_state IN ('snapshot', 'gap')),
|
||||
CONSTRAINT dispatch_items_once UNIQUE (dispatch_id, element_id)
|
||||
);
|
||||
|
||||
CREATE INDEX dispatch_items_dispatch ON dispatch_items (dispatch_id, position);
|
||||
|
||||
CREATE TABLE dispatch_snapshots (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_item_id uuid UNIQUE REFERENCES dispatch_items (id) ON DELETE CASCADE,
|
||||
evidence_id uuid,
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
original_filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
byte_size bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT dispatch_snapshots_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240),
|
||||
CONSTRAINT dispatch_snapshots_target CHECK (
|
||||
(dispatch_item_id IS NOT NULL AND evidence_id IS NULL)
|
||||
OR (dispatch_item_id IS NULL AND evidence_id IS NOT NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE TABLE dispatch_evidence (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
|
||||
element_id uuid NOT NULL REFERENCES elements (id) ON DELETE CASCADE,
|
||||
role text NOT NULL,
|
||||
source_state text NOT NULL,
|
||||
gap_reason text,
|
||||
message_id text,
|
||||
identity_sha256 text,
|
||||
comparisons jsonb NOT NULL DEFAULT '[]'::jsonb,
|
||||
manual boolean NOT NULL DEFAULT true,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT dispatch_evidence_role CHECK (role IN ('email', 'submission', 'delivery', 'other')),
|
||||
CONSTRAINT dispatch_evidence_state CHECK (source_state IN ('identified', 'gap')),
|
||||
CONSTRAINT dispatch_evidence_once UNIQUE (dispatch_id, element_id)
|
||||
);
|
||||
|
||||
ALTER TABLE dispatch_snapshots
|
||||
ADD CONSTRAINT dispatch_snapshots_evidence_fk
|
||||
FOREIGN KEY (evidence_id) REFERENCES dispatch_evidence (id) ON DELETE CASCADE;
|
||||
|
||||
CREATE TABLE dispatch_corrections (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
dispatch_id uuid NOT NULL REFERENCES dispatches (id) ON DELETE CASCADE,
|
||||
corrected_at timestamptz NOT NULL DEFAULT now(),
|
||||
corrected_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
summary text NOT NULL,
|
||||
CONSTRAINT dispatch_corrections_summary CHECK (char_length(summary) BETWEEN 1 AND 500)
|
||||
);
|
||||
|
||||
CREATE INDEX dispatch_corrections_dispatch ON dispatch_corrections (dispatch_id, corrected_at);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Owner kann an einer Freigabe erlauben, verknüpfte Originale über die eigenen Zugänge zu lesen.
|
||||
-- Bestehende Freigaben bleiben ohne diesen Abruf.
|
||||
|
||||
ALTER TABLE access_grants
|
||||
ADD COLUMN use_owner_sources boolean NOT NULL DEFAULT false;
|
||||
|
||||
ALTER TABLE domain_events
|
||||
ADD COLUMN detail jsonb;
|
||||
@@ -0,0 +1,66 @@
|
||||
-- Source instance binding and opaque storage generation.
|
||||
-- Connector ids are not a foreign key: deleting an access must not
|
||||
-- retarget or remove an existing reference.
|
||||
-- The legacy root path is bound in the migrator, not in this file.
|
||||
|
||||
CREATE TABLE storage_instances (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
kind text NOT NULL,
|
||||
generation text NOT NULL,
|
||||
root_path text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT storage_instances_kind CHECK (kind IN ('local')),
|
||||
CONSTRAINT storage_instances_generation UNIQUE (generation),
|
||||
CONSTRAINT storage_instances_generation_len CHECK (char_length(generation) BETWEEN 1 AND 80)
|
||||
);
|
||||
|
||||
ALTER TABLE media_assets
|
||||
ADD COLUMN storage_instance_id uuid REFERENCES storage_instances (id),
|
||||
ADD COLUMN storage_generation text,
|
||||
ADD COLUMN object_key text,
|
||||
ADD COLUMN content_revision text,
|
||||
ADD COLUMN protection_profile text NOT NULL DEFAULT 'legacy-plaintext',
|
||||
ADD COLUMN key_responsibility text NOT NULL DEFAULT 'none',
|
||||
ADD CONSTRAINT media_assets_protection CHECK (
|
||||
protection_profile IN ('legacy-plaintext', 'managed-encrypted', 'client-encrypted')
|
||||
),
|
||||
ADD CONSTRAINT media_assets_key_responsibility CHECK (
|
||||
key_responsibility IN ('none', 'operator', 'client')
|
||||
);
|
||||
|
||||
ALTER TABLE dispatch_snapshots
|
||||
ADD COLUMN storage_instance_id uuid REFERENCES storage_instances (id),
|
||||
ADD COLUMN storage_generation text,
|
||||
ADD COLUMN object_key text,
|
||||
ADD COLUMN content_revision text,
|
||||
ADD COLUMN protection_profile text NOT NULL DEFAULT 'legacy-plaintext',
|
||||
ADD COLUMN key_responsibility text NOT NULL DEFAULT 'none',
|
||||
ADD CONSTRAINT dispatch_snapshots_protection CHECK (
|
||||
protection_profile IN ('legacy-plaintext', 'managed-encrypted', 'client-encrypted')
|
||||
),
|
||||
ADD CONSTRAINT dispatch_snapshots_key_responsibility CHECK (
|
||||
key_responsibility IN ('none', 'operator', 'client')
|
||||
);
|
||||
|
||||
UPDATE media_assets
|
||||
SET storage_generation = 'legacy-local-1',
|
||||
object_key = id::text,
|
||||
content_revision = id::text,
|
||||
protection_profile = 'legacy-plaintext',
|
||||
key_responsibility = 'none'
|
||||
WHERE object_key IS NULL;
|
||||
|
||||
UPDATE dispatch_snapshots
|
||||
SET storage_generation = 'legacy-local-1',
|
||||
object_key = 'dispatch/' || id::text,
|
||||
content_revision = id::text,
|
||||
protection_profile = 'legacy-plaintext',
|
||||
key_responsibility = 'none'
|
||||
WHERE object_key IS NULL;
|
||||
|
||||
ALTER TABLE external_references
|
||||
ADD COLUMN connector_id uuid,
|
||||
ADD COLUMN resolution text NOT NULL DEFAULT 'unresolved',
|
||||
ADD CONSTRAINT external_references_resolution CHECK (
|
||||
resolution IN ('bound', 'ambiguous', 'unresolved', 'none')
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Connector kinds are validated by the registered source modules.
|
||||
-- A database checklist must not grow for every additional source.
|
||||
|
||||
ALTER TABLE connectors DROP CONSTRAINT IF EXISTS connectors_kind;
|
||||
ALTER TABLE external_references DROP CONSTRAINT IF EXISTS external_references_source;
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Last connection check per connector instance. Display only: it grants nothing
|
||||
-- and carries no secret.
|
||||
|
||||
ALTER TABLE connectors
|
||||
ADD COLUMN last_probe_at timestamptz,
|
||||
ADD COLUMN last_probe_ok boolean,
|
||||
ADD COLUMN last_probe_detail text,
|
||||
ADD CONSTRAINT connectors_probe_detail_len CHECK (last_probe_detail IS NULL OR char_length(last_probe_detail) <= 300);
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Benutzerverwaltung: Kontostatus, Sitzungsübersicht, persistente Login-Begrenzung,
|
||||
-- Raumrolle "Leser" und Rollen in Einladungen. Bestehende Zeilen bleiben gültig.
|
||||
|
||||
ALTER TABLE auth_accounts
|
||||
ADD COLUMN must_change_password boolean NOT NULL DEFAULT false,
|
||||
ADD COLUMN password_changed_at timestamptz,
|
||||
ADD COLUMN last_login_at timestamptz,
|
||||
ADD COLUMN disabled_at timestamptz,
|
||||
ADD COLUMN disabled_by uuid REFERENCES auth_accounts (id);
|
||||
|
||||
ALTER TABLE auth_sessions
|
||||
ADD COLUMN last_seen_at timestamptz,
|
||||
ADD COLUMN label text,
|
||||
ADD CONSTRAINT auth_sessions_label_len CHECK (label IS NULL OR char_length(label) <= 80);
|
||||
|
||||
-- Der Bucket ist ein Hash aus Adresse und E-Mail. Die Roh-E-Mail wird nie gespeichert.
|
||||
CREATE TABLE auth_login_attempts (
|
||||
bucket text NOT NULL,
|
||||
attempted_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX auth_login_attempts_bucket ON auth_login_attempts (bucket, attempted_at);
|
||||
|
||||
ALTER TABLE room_memberships DROP CONSTRAINT room_memberships_role;
|
||||
ALTER TABLE room_memberships
|
||||
ADD CONSTRAINT room_memberships_role CHECK (role IN ('member', 'manager', 'reader'));
|
||||
|
||||
ALTER TABLE auth_invitations
|
||||
ADD COLUMN role text NOT NULL DEFAULT 'member',
|
||||
ADD COLUMN revoked_at timestamptz,
|
||||
ADD CONSTRAINT auth_invitations_role CHECK (role IN ('member', 'manager', 'reader'));
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Raum-Eigentümer und Raumfreigabe. Bestehende Akten und Vorgänge bleiben privat.
|
||||
|
||||
ALTER TABLE data_rooms
|
||||
ADD COLUMN owner_id uuid REFERENCES auth_accounts (id),
|
||||
ADD COLUMN default_visibility text NOT NULL DEFAULT 'private',
|
||||
ADD CONSTRAINT data_rooms_default_visibility CHECK (default_visibility IN ('private', 'room'));
|
||||
|
||||
UPDATE data_rooms SET owner_id = created_by;
|
||||
|
||||
ALTER TABLE data_rooms
|
||||
ADD CONSTRAINT data_rooms_owner CHECK (kind = 'personal' OR owner_id IS NOT NULL);
|
||||
|
||||
CREATE INDEX data_rooms_owner ON data_rooms (owner_id) WHERE kind = 'organization';
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD COLUMN visibility text NOT NULL DEFAULT 'private',
|
||||
ADD CONSTRAINT cases_visibility CHECK (visibility IN ('private', 'room'));
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD COLUMN visibility text NOT NULL DEFAULT 'private',
|
||||
ADD CONSTRAINT matters_visibility CHECK (visibility IN ('private', 'room'));
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Raum als Team: Eine Akte oder ein Vorgang wird mit beliebigen Datenräumen geteilt,
|
||||
-- unabhängig vom Heimatraum. Der Heimatraum bleibt Ablage. Die Freigabe zum Heimatraum
|
||||
-- aus 20261021T090000Z_room_access.sql wird übernommen, danach entfallen die Spalten.
|
||||
|
||||
CREATE TABLE room_shares (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
resource_kind text NOT NULL,
|
||||
resource_id uuid NOT NULL,
|
||||
room_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
-- Obergrenze der Freigabe: 'edit' = Rechte nach Raumrolle, 'read' = höchstens Lesen.
|
||||
access text NOT NULL DEFAULT 'edit',
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT room_shares_kind CHECK (resource_kind IN ('case', 'matter')),
|
||||
CONSTRAINT room_shares_access CHECK (access IN ('read', 'edit')),
|
||||
UNIQUE (resource_kind, resource_id, room_id)
|
||||
);
|
||||
|
||||
CREATE INDEX room_shares_room ON room_shares (room_id);
|
||||
|
||||
INSERT INTO room_shares (resource_kind, resource_id, room_id, access, created_by)
|
||||
SELECT 'case', c.id, c.home_scope_id, 'edit', c.owner_subject_id
|
||||
FROM cases c
|
||||
WHERE c.visibility = 'room';
|
||||
|
||||
INSERT INTO room_shares (resource_kind, resource_id, room_id, access, created_by)
|
||||
SELECT 'matter', m.id, m.home_scope_id, 'edit', m.owner_subject_id
|
||||
FROM matters m
|
||||
WHERE m.visibility = 'room';
|
||||
|
||||
ALTER TABLE cases DROP CONSTRAINT cases_visibility, DROP COLUMN visibility;
|
||||
ALTER TABLE matters DROP CONSTRAINT matters_visibility, DROP COLUMN visibility;
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Hauptnutzer und Mitarbeiter. Alle bestehenden Konten sind Hauptnutzer.
|
||||
-- Ein Mitarbeiter-Konto entsteht durch eine Einladung und hat den einladenden Eigentümer als Förderer.
|
||||
|
||||
ALTER TABLE auth_accounts
|
||||
ADD COLUMN account_kind text NOT NULL DEFAULT 'main',
|
||||
ADD COLUMN sponsor_id uuid REFERENCES auth_accounts (id),
|
||||
ADD CONSTRAINT auth_accounts_kind CHECK (account_kind IN ('main', 'employee')),
|
||||
ADD CONSTRAINT auth_accounts_sponsor CHECK (
|
||||
(account_kind = 'employee' AND sponsor_id IS NOT NULL)
|
||||
OR (account_kind = 'main' AND sponsor_id IS NULL)
|
||||
);
|
||||
|
||||
CREATE INDEX auth_accounts_sponsor ON auth_accounts (sponsor_id) WHERE sponsor_id IS NOT NULL;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Einstellungen je Konto. Ein Mitarbeiter erbt den Wert seines Hauptnutzers und kann ihn ändern,
|
||||
-- solange der Hauptnutzer die Einstellung nicht für das Team verbindlich gesetzt hat (team_mode).
|
||||
-- Erlaubte Werte, Standard und Verbindlichkeit je Schlüssel stehen im Code (app/preferences.py).
|
||||
-- value NULL: kein eigener Wert, es gilt die Erbung bzw. der Standard.
|
||||
|
||||
CREATE TABLE account_preferences (
|
||||
account_id uuid NOT NULL REFERENCES auth_accounts (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
value jsonb,
|
||||
team_mode text NOT NULL DEFAULT 'free',
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (account_id, key),
|
||||
CONSTRAINT account_preferences_key_len CHECK (char_length(key) BETWEEN 1 AND 60),
|
||||
CONSTRAINT account_preferences_team_mode CHECK (team_mode IN ('free', 'locked'))
|
||||
);
|
||||
|
||||
-- Dieselbe Quelle und Kennung: Suche nach bereits eingefügten Dokumenten (app/duplicates.py).
|
||||
CREATE INDEX external_references_identity ON external_references (source, external_id);
|
||||
@@ -0,0 +1,3 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
addopts = -q --tb=short
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Suite on the existing Dev Postgres, database tsumugu_test.
|
||||
|
||||
Dev and prod databases are refused. The workflow drops and recreates
|
||||
tsumugu_test beside tsumugu_dev. This is not a third server.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
|
||||
FORBIDDEN = frozenset({"tsumugu", "tsumugu_dev", "postgres", "template0", "template1"})
|
||||
|
||||
_name = os.environ.get("DB_NAME", "").strip().lower()
|
||||
if not _name.endswith("_test") or _name in FORBIDDEN:
|
||||
raise RuntimeError(
|
||||
"DB_NAME fehlt oder ist gesperrt. Die Suite nutzt auf der Dev-Postgres "
|
||||
"die Datenbank tsumugu_test, nicht tsumugu oder tsumugu_dev."
|
||||
)
|
||||
|
||||
os.environ["TSUMUGU_ENV"] = "development"
|
||||
os.environ["ALLOWED_ORIGINS"] = "http://testserver"
|
||||
os.environ["SEED_DEMO"] = "false"
|
||||
os.environ["MEDIA_ROOT"] = tempfile.mkdtemp(prefix="tsumugu-pytest-")
|
||||
|
||||
|
||||
def _reset(settings) -> None:
|
||||
# The suite truncates between tests while the app pool may still release
|
||||
# the previous request's transaction. A deadlock abort would roll back that
|
||||
# transaction and the next login would fail. Waiting and retrying keeps the
|
||||
# reset outside the product path.
|
||||
last_error: Exception | None = None
|
||||
for attempt in range(8):
|
||||
try:
|
||||
with psycopg.connect(settings.dsn(), autocommit=True) as conn:
|
||||
conn.execute("SET lock_timeout = '1500ms'")
|
||||
conn.execute(
|
||||
"""
|
||||
TRUNCATE TABLE
|
||||
media_operations,
|
||||
domain_events,
|
||||
auth_login_attempts,
|
||||
auth_accounts,
|
||||
data_rooms
|
||||
RESTART IDENTITY CASCADE
|
||||
"""
|
||||
)
|
||||
return
|
||||
except (psycopg.errors.DeadlockDetected, psycopg.errors.LockNotAvailable) as exc:
|
||||
last_error = exc
|
||||
time.sleep(0.15 * (attempt + 1))
|
||||
if last_error is not None:
|
||||
raise last_error
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def database():
|
||||
name = os.environ.get("DB_NAME", "").strip().lower()
|
||||
if name in FORBIDDEN or not name.endswith("_test"):
|
||||
pytest.fail(
|
||||
"DB_NAME muss auf der Dev-Postgres eine Datenbank *_test sein, "
|
||||
"nicht tsumugu oder tsumugu_dev."
|
||||
)
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
|
||||
get_settings.cache_clear()
|
||||
settings = get_settings()
|
||||
if settings.db_name.lower() in FORBIDDEN or not settings.db_name.lower().endswith("_test"):
|
||||
pytest.fail("Die Test-Suite darf nicht gegen Dev- oder Prod-Datenbanken laufen.")
|
||||
migrate(settings)
|
||||
yield settings
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client(database):
|
||||
from fastapi.testclient import TestClient
|
||||
from app.main import app
|
||||
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean(database, client):
|
||||
client.cookies.clear()
|
||||
_reset(database)
|
||||
yield
|
||||
client.cookies.clear()
|
||||
_reset(database)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db(database, clean):
|
||||
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.rollback()
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Third source used only to prove that registration is enough.
|
||||
|
||||
This module is not a product connector and is not imported by the application.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import UUID
|
||||
|
||||
from app.core.errors import not_found, unprocessable
|
||||
from app.retrieval import FilePayload, RetrievalFailure
|
||||
from app.sourcebind import resolve_for_read
|
||||
from app.sourceregistry import ConfigField, SourceModule, register_source, unregister_source
|
||||
from app.sourceaccess import borrow_original, complete_borrow
|
||||
|
||||
KIND = "sample"
|
||||
|
||||
CATALOG = {
|
||||
"alpha": {
|
||||
"brief": {
|
||||
"id": "brief",
|
||||
"title": "Probenbrief",
|
||||
"text": "Der Probenbrief bleibt lesbar.",
|
||||
},
|
||||
"notiz": {
|
||||
"id": "notiz",
|
||||
"title": "Randnotiz",
|
||||
"text": "Die Randnotiz bleibt in der Quelle.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
CAPABILITIES = {
|
||||
"kind": KIND,
|
||||
"navigate": False,
|
||||
"read_original": True,
|
||||
"read_preview": True,
|
||||
"read_attachment": False,
|
||||
"edit_content": False,
|
||||
"edit_metadata": False,
|
||||
"search": {
|
||||
"query": True,
|
||||
"title": False,
|
||||
"correspondent": False,
|
||||
"document_type": False,
|
||||
"tags": False,
|
||||
"document_range": False,
|
||||
"sort": False,
|
||||
"continuation": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
CONFIG_FIELDS = (
|
||||
ConfigField("catalog", "Katalog", required=True, default="alpha", help="Name des Beispielkatalogs."),
|
||||
)
|
||||
|
||||
|
||||
def normalize_config(settings: dict, secret: str) -> dict:
|
||||
del secret
|
||||
if settings["catalog"] not in CATALOG:
|
||||
raise unprocessable("Der Katalog dieser Beispielquelle ist unbekannt.")
|
||||
return settings
|
||||
|
||||
|
||||
def probe(row) -> dict:
|
||||
items = _items(row)
|
||||
return {"ok": True, "detail": f"Beispielquelle antwortet. {len(items)} Einträge sichtbar."}
|
||||
|
||||
|
||||
def find(conn, owner_id: UUID, connector_id: UUID | None, query: str, options: dict) -> dict:
|
||||
del options
|
||||
row = _connector(conn, owner_id, connector_id)
|
||||
needle = query.casefold()
|
||||
items = list(_items(row).values())
|
||||
if needle:
|
||||
items = [
|
||||
item for item in items
|
||||
if needle in item["title"].casefold() or needle in item["text"].casefold()
|
||||
]
|
||||
return {"items": items, "connector_id": str(row["id"])}
|
||||
|
||||
|
||||
def preview(conn, owner_id: UUID, connector_id: UUID, options: dict) -> dict:
|
||||
row = _connector(conn, owner_id, connector_id)
|
||||
item = _items(row).get(str(options.get("item") or ""))
|
||||
if item is None:
|
||||
raise unprocessable("Dieser Eintrag ist in der Beispielquelle nicht vorhanden.")
|
||||
return {"id": item["id"], "title": item["title"], "text": item["text"], "media": "text"}
|
||||
|
||||
|
||||
def open_original(conn, actor_id: UUID, element: dict, context, ref) -> tuple[bytes, str, str]:
|
||||
borrowed = borrow_original(conn, actor_id, element, context, ref, KIND)
|
||||
return complete_borrow(conn, borrowed, lambda row: _bytes(row, borrowed.external_id))
|
||||
|
||||
|
||||
def export_original(conn, actor_id: UUID, external_id: str, detail: dict, assigned, ref):
|
||||
del detail
|
||||
result = resolve_for_read(conn, actor_id, KIND, ref, assigned)
|
||||
if result.row is None:
|
||||
return RetrievalFailure(result.code, result.message, result.choices)
|
||||
try:
|
||||
data, media, name = _bytes(result.row, str(external_id))
|
||||
except Exception as exc:
|
||||
return RetrievalFailure("missing", str(getattr(exc, "detail", exc)))
|
||||
return FilePayload(name, media, data, "")
|
||||
|
||||
|
||||
def install_sample_source() -> None:
|
||||
register_source(SourceModule(
|
||||
kind=KIND,
|
||||
label="Beispielquelle",
|
||||
representation="text",
|
||||
capabilities=CAPABILITIES,
|
||||
config_fields=CONFIG_FIELDS,
|
||||
normalize_config=normalize_config,
|
||||
probe=probe,
|
||||
find=find,
|
||||
open_original=open_original,
|
||||
export_original=export_original,
|
||||
navigate=None,
|
||||
preview=preview,
|
||||
))
|
||||
|
||||
|
||||
def remove_sample_source() -> None:
|
||||
unregister_source(KIND)
|
||||
|
||||
|
||||
def _connector(conn, owner_id: UUID, connector_id: UUID | None):
|
||||
if connector_id is not None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id, owner_id, kind, name, settings, secret
|
||||
FROM connectors WHERE id = %s AND owner_id = %s
|
||||
""",
|
||||
(connector_id, owner_id),
|
||||
).fetchone()
|
||||
if row is None or row["kind"] != KIND:
|
||||
raise not_found()
|
||||
return row
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id, owner_id, kind, name, settings, secret
|
||||
FROM connectors
|
||||
WHERE owner_id = %s AND kind = %s
|
||||
ORDER BY name, id
|
||||
""",
|
||||
(owner_id, KIND),
|
||||
).fetchall()
|
||||
if len(rows) != 1:
|
||||
raise unprocessable("Für diese Quelle ist kein eindeutiger Zugang zugeordnet.")
|
||||
return rows[0]
|
||||
|
||||
|
||||
def _items(row) -> dict:
|
||||
catalog = (row["settings"] or {}).get("catalog")
|
||||
return CATALOG.get(catalog) or {}
|
||||
|
||||
|
||||
def _bytes(row, external_id: str) -> tuple[bytes, str, str]:
|
||||
item = _items(row).get(external_id)
|
||||
if item is None:
|
||||
raise unprocessable("Dieser Eintrag ist in der Beispielquelle nicht vorhanden.")
|
||||
return item["text"].encode("utf-8"), "text/plain", f"{item['id']}.txt"
|
||||
@@ -0,0 +1,111 @@
|
||||
"""HTTP session helper for the mandatory suite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
ORIGIN = "http://testserver"
|
||||
PASSWORD = "Beispiel-Test-2026"
|
||||
|
||||
|
||||
def document(text: str) -> dict:
|
||||
return {"version": 1, "blocks": [{"type": "paragraph", "text": text}]}
|
||||
|
||||
|
||||
class Actor:
|
||||
def __init__(self, client, email: str, name: str):
|
||||
self.client = client
|
||||
self.email = email
|
||||
self.name = name
|
||||
self.password = PASSWORD
|
||||
self.csrf = ""
|
||||
self.scope = None
|
||||
|
||||
def login(self) -> dict:
|
||||
response = self.client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"email": self.email, "password": self.password},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
body = response.json()
|
||||
self.csrf = body["csrf_token"]
|
||||
self.scope = body["scope"]
|
||||
return body
|
||||
|
||||
def use_room(self, room_id: str) -> dict:
|
||||
body = self.request("POST", "/api/v1/auth/session/scope", json={"kind": "organization", "id": room_id})
|
||||
self.csrf = body["csrf_token"]
|
||||
self.scope = body["scope"]
|
||||
return body
|
||||
|
||||
def request(self, method: str, path: str, *, json=None, params=None, data=None, files=None, status: int = 200):
|
||||
headers = {"Origin": ORIGIN, "X-CSRF-Token": self.csrf}
|
||||
if self.scope is not None:
|
||||
headers["X-Scope-Kind"] = self.scope["kind"]
|
||||
headers["X-Scope-Id"] = self.scope["id"]
|
||||
response = self.client.request(method, path, json=json, params=params, data=data, files=files, headers=headers)
|
||||
assert response.status_code == status, response.text
|
||||
if status == 204 or not response.content:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
|
||||
def register(conn, email: str, name: str, *, superadmin: bool = False):
|
||||
from app.auth.accounts import create_account
|
||||
|
||||
account = create_account(conn, email, name, PASSWORD, is_superadmin=superadmin, origin="fixture")
|
||||
conn.commit()
|
||||
return account
|
||||
|
||||
|
||||
def case_of(actor: Actor, title: str) -> dict:
|
||||
return actor.request("POST", "/api/v1/cases", json={"title": title}, status=201)
|
||||
|
||||
|
||||
def matter_of(actor: Actor, title: str) -> dict:
|
||||
return actor.request("POST", "/api/v1/matters", json={"title": title}, status=201)
|
||||
|
||||
|
||||
def grant(actor: Actor, case_id: str, email: str, *, edit: bool = False, share: bool = False) -> None:
|
||||
actor.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case_id}/grants",
|
||||
json={"email": email, "can_read": True, "can_edit": edit, "can_share": share},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def note_on(actor: Actor, title: str, text: str, case_id: str) -> dict:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": title, "document": document(text), "context": {"kind": "case", "id": case_id}},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def bind_to(actor: Actor, element_id: str, source_id: str, target_id: str) -> dict:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={
|
||||
"element_id": element_id,
|
||||
"source_context": {"kind": "case", "id": source_id},
|
||||
"target": {"kind": "case", "id": target_id},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def binding_for(case: dict, title: str) -> dict:
|
||||
for binding in case["bindings"]:
|
||||
if binding["element"]["title"] == title:
|
||||
return binding
|
||||
raise AssertionError(title)
|
||||
|
||||
|
||||
def texts(case: dict) -> dict[str, str]:
|
||||
found = {}
|
||||
for binding in case["bindings"]:
|
||||
blocks = binding["element"].get("document", {}).get("blocks", [])
|
||||
found[binding["element"]["title"]] = blocks[0]["text"] if blocks else ""
|
||||
return found
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Betreiber legt Nutzer an. Andere Konten dürfen das nicht."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import ORIGIN, PASSWORD, Actor
|
||||
|
||||
|
||||
def test_session_missing_is_401(client):
|
||||
response = client.get("/api/v1/cases")
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_bootstrap_once_then_superadmin_creates_users(client):
|
||||
first = client.post(
|
||||
"/api/v1/auth/bootstrap",
|
||||
json={"email": "betreiber@example.test", "display_name": "Betreiber", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert first.status_code == 201, first.text
|
||||
body = first.json()
|
||||
assert body["account"]["is_superadmin"] is True
|
||||
second = client.post(
|
||||
"/api/v1/auth/bootstrap",
|
||||
json={"email": "andere@example.test", "display_name": "Andere", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert second.status_code == 404
|
||||
|
||||
owner = Actor(client, "betreiber@example.test", "Betreiber")
|
||||
owner.login()
|
||||
created = owner.request(
|
||||
"POST",
|
||||
"/api/v1/accounts",
|
||||
json={"email": "mitglied@example.test", "display_name": "Mitglied", "password": PASSWORD},
|
||||
status=201,
|
||||
)
|
||||
assert created["is_superadmin"] is False
|
||||
assert created["must_change_password"] is True
|
||||
assert "password" not in created and "temporary_password" not in created
|
||||
listed = owner.request("GET", "/api/v1/accounts")
|
||||
assert {item["email"] for item in listed["items"]} == {"betreiber@example.test", "mitglied@example.test"}
|
||||
assert all("password_hash" not in item and "password" not in item for item in listed["items"])
|
||||
|
||||
member = Actor(client, "mitglied@example.test", "Mitglied")
|
||||
member.login()
|
||||
member.request(
|
||||
"POST",
|
||||
"/api/v1/accounts",
|
||||
json={"email": "noch@example.test", "display_name": "Noch", "password": PASSWORD},
|
||||
status=403,
|
||||
)
|
||||
member.request("GET", "/api/v1/accounts", status=403)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Production boundary, fixture cleanup, health and the runtime role."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import Settings
|
||||
from app.entrypoint import prepare
|
||||
from app.fixtures import purge_fixture_data
|
||||
from app.ops import create_case
|
||||
from app.seed import ADA_EMAIL, BEN_EMAIL, is_test_database, seed_demo
|
||||
from tests.conftest import FORBIDDEN
|
||||
from tests.support import PASSWORD
|
||||
|
||||
|
||||
def test_database_is_ephemeral(database):
|
||||
assert is_test_database(database.db_name)
|
||||
assert database.db_name.lower() not in FORBIDDEN
|
||||
assert database.tsumugu_env == "development"
|
||||
|
||||
|
||||
def test_unknown_environment_refuses_to_start():
|
||||
with pytest.raises(ValidationError):
|
||||
Settings(tsumugu_env="staging", db_name="x", db_user="x", db_password="x")
|
||||
|
||||
|
||||
def test_seed_never_touches_dev_or_prod():
|
||||
for env, name in (("production", "tsumugu"), ("development", "tsumugu_dev"), ("development", "tsumugu")):
|
||||
settings = Settings(
|
||||
tsumugu_env=env,
|
||||
db_host="192.0.2.1",
|
||||
db_name=name,
|
||||
db_user="x",
|
||||
db_password="x",
|
||||
seed_demo=True,
|
||||
)
|
||||
assert seed_demo(settings) is False
|
||||
|
||||
|
||||
def test_production_refuses_seed_flag():
|
||||
settings = Settings(
|
||||
tsumugu_env="production",
|
||||
db_host="192.0.2.1",
|
||||
db_name="tsumugu",
|
||||
db_user="x",
|
||||
db_password="x",
|
||||
seed_demo=True,
|
||||
)
|
||||
with pytest.raises(SystemExit, match="SEED_DEMO"):
|
||||
prepare(settings)
|
||||
|
||||
|
||||
def test_import_does_not_open_the_database_by_itself():
|
||||
import app.main
|
||||
|
||||
assert app.main.app.title == "Tsumugu"
|
||||
|
||||
|
||||
def test_health_stays_small(client):
|
||||
response = client.get("/api/health")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok", "app": "tsumugu"}
|
||||
|
||||
|
||||
def test_runtime_role_cannot_create_tables(database):
|
||||
with psycopg.connect(database.dsn(user=database.db_runtime_user)) as conn:
|
||||
with pytest.raises(psycopg.errors.InsufficientPrivilege):
|
||||
conn.execute("CREATE TABLE pytest_forbidden (id integer)")
|
||||
|
||||
|
||||
def test_purge_removes_fixtures_and_keeps_operator_work(database):
|
||||
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
operator = create_account(conn, "betreiber-echt@example.test", "Betreiber Beispiel", PASSWORD)
|
||||
kept = create_case(conn, operator["id"], operator["id"], "Echte Akte", None, "explicit")
|
||||
conn.commit()
|
||||
kept_id = kept["id"]
|
||||
seeded = database.model_copy(update={"seed_demo": True})
|
||||
assert seed_demo(seeded) is True
|
||||
assert any(Path(database.media_root).iterdir())
|
||||
assert purge_fixture_data(database) == 2
|
||||
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
assert conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (ADA_EMAIL,)).fetchone() is None
|
||||
assert conn.execute("SELECT 1 FROM auth_accounts WHERE email = %s", (BEN_EMAIL,)).fetchone() is None
|
||||
assert conn.execute("SELECT 1 FROM data_rooms WHERE name = %s", ("Haushalt Musterstraße",)).fetchone() is None
|
||||
row = conn.execute("SELECT title FROM cases WHERE id = %s", (kept_id,)).fetchone()
|
||||
assert row["title"] == "Echte Akte"
|
||||
assert list(Path(database.media_root).iterdir()) == []
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Nested chapters stay outline only: same object, no rights, no partial moves."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
|
||||
from tests.support import Actor, binding_for, case_of, document, grant, matter_of, register
|
||||
|
||||
|
||||
def _note(actor: Actor, title: str, matter: dict, chapter_id: str | None = None) -> dict:
|
||||
body = {
|
||||
"title": title,
|
||||
"document": document(title),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
}
|
||||
if chapter_id:
|
||||
body["chapter_id"] = chapter_id
|
||||
return actor.request("POST", "/api/v1/notes", json=body, status=201)
|
||||
|
||||
|
||||
def _detail(actor: Actor, matter_id: str) -> dict:
|
||||
return actor.request("GET", f"/api/v1/matters/{matter_id}")
|
||||
|
||||
|
||||
def _by_title(detail: dict) -> dict[str, dict]:
|
||||
return {item["title"]: item for item in detail["chapters"]}
|
||||
|
||||
|
||||
def test_flat_chapters_keep_identity_order_and_bindings(client, db):
|
||||
ada = Actor(client, "ada-flach@example.test", "Ada Flach")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Bestehender Vorgang")
|
||||
first = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Schriftverkehr", "document_on": "2024-02-02"},
|
||||
status=201,
|
||||
)
|
||||
second = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Nachweise", "document_on": "2024-01-01"},
|
||||
status=201,
|
||||
)
|
||||
_note(ada, "Altes Schreiben", matter, first["id"])
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert [item["id"] for item in detail["chapters"]] == [second["id"], first["id"]]
|
||||
assert all(item["parent_chapter_id"] is None for item in detail["chapters"])
|
||||
assert binding_for(detail, "Altes Schreiben")["chapter_id"] == first["id"]
|
||||
ada.login()
|
||||
again = _detail(ada, matter["id"])
|
||||
assert [(item["id"], item["title"], item["parent_chapter_id"]) for item in again["chapters"]] == [
|
||||
(second["id"], "Nachweise", None),
|
||||
(first["id"], "Schriftverkehr", None),
|
||||
]
|
||||
assert binding_for(again, "Altes Schreiben")["chapter_id"] == first["id"]
|
||||
|
||||
|
||||
def test_three_levels_bulk_move_reorder_reparent_and_dissolve(client, db):
|
||||
ada = Actor(client, "ada-nest@example.test", "Ada Nest")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Nebenkostenabrechnung")
|
||||
root = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Nebenkostenabrechnung 2025"},
|
||||
status=201,
|
||||
)
|
||||
sent = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Übermittelte Abrechnungsunterlagen", "parent_chapter_id": root["id"]},
|
||||
status=201,
|
||||
)
|
||||
receipts = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Einzelbelege", "parent_chapter_id": sent["id"]},
|
||||
status=201,
|
||||
)
|
||||
sibling = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Weiterer Ordner", "parent_chapter_id": root["id"]},
|
||||
status=201,
|
||||
)
|
||||
_note(ada, "Anschreiben", matter, sent["id"])
|
||||
_note(ada, "Abrechnung", matter, sent["id"])
|
||||
_note(ada, "Rückfrage zur Abrechnung", matter, root["id"])
|
||||
_note(ada, "Antwort des Vermieters", matter, root["id"])
|
||||
for index in range(8):
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": f"Beleg {index + 1}",
|
||||
"source": "paperless",
|
||||
"external_id": str(700 + index),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": root["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
chapters = _by_title(detail)
|
||||
assert chapters["Übermittelte Abrechnungsunterlagen"]["parent_chapter_id"] == root["id"]
|
||||
assert chapters["Einzelbelege"]["parent_chapter_id"] == sent["id"]
|
||||
assert binding_for(detail, "Rückfrage zur Abrechnung")["chapter_id"] == root["id"]
|
||||
assert binding_for(detail, "Anschreiben")["chapter_id"] == sent["id"]
|
||||
receipt_ids = [binding_for(detail, f"Beleg {index + 1}")["id"] for index in range(8)]
|
||||
moved = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/chapters",
|
||||
json={"expected_version": detail["version"], "binding_ids": receipt_ids, "chapter_id": receipts["id"]},
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert detail["version"] == moved["version"]
|
||||
assert all(binding_for(detail, f"Beleg {index + 1}")["chapter_id"] == receipts["id"] for index in range(8))
|
||||
assert binding_for(detail, "Rückfrage zur Abrechnung")["chapter_id"] == root["id"]
|
||||
assert binding_for(detail, "Anschreiben")["chapter_id"] == sent["id"]
|
||||
stale = detail["version"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/chapters",
|
||||
json={
|
||||
"expected_version": stale,
|
||||
"binding_ids": [receipt_ids[0], "00000000-0000-4000-8000-000000000099"],
|
||||
"chapter_id": root["id"],
|
||||
},
|
||||
status=404,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert detail["version"] == stale
|
||||
assert binding_for(detail, "Beleg 1")["chapter_id"] == receipts["id"]
|
||||
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters/order",
|
||||
json={"expected_version": detail["version"], "chapter_ids": [sibling["id"], sent["id"]]},
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
ordered = [item["id"] for item in detail["chapters"] if item["parent_chapter_id"] == root["id"]]
|
||||
assert ordered == [sibling["id"], sent["id"]]
|
||||
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == sent["id"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters/order",
|
||||
json={"expected_version": detail["version"], "chapter_ids": [root["id"], sent["id"]]},
|
||||
status=422,
|
||||
)
|
||||
|
||||
stale_parent = detail["version"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/chapters/{receipts['id']}/parent",
|
||||
json={"expected_version": stale_parent, "parent_chapter_id": root["id"]},
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == root["id"]
|
||||
assert all(binding_for(detail, f"Beleg {index + 1}")["chapter_id"] == receipts["id"] for index in range(8))
|
||||
ada.login()
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == root["id"]
|
||||
assert [item["id"] for item in detail["chapters"] if item["parent_chapter_id"] == root["id"]][:2] == [
|
||||
sibling["id"],
|
||||
sent["id"],
|
||||
]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/chapters/{sent['id']}/parent",
|
||||
json={"expected_version": stale_parent, "parent_chapter_id": receipts["id"]},
|
||||
status=409,
|
||||
)
|
||||
other = matter_of(ada, "Fremder Vorgang")
|
||||
foreign = ada.request("POST", f"/api/v1/matters/{other['id']}/chapters", json={"title": "Fremd"}, status=201)
|
||||
detail = _detail(ada, matter["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/chapters/{sent['id']}/parent",
|
||||
json={"expected_version": detail["version"], "parent_chapter_id": foreign["id"]},
|
||||
status=422,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/chapters/{sent['id']}/parent",
|
||||
json={"expected_version": detail["version"], "parent_chapter_id": sent["id"]},
|
||||
status=422,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/chapters/{root['id']}/parent",
|
||||
json={"expected_version": detail["version"], "parent_chapter_id": sent["id"]},
|
||||
status=422,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert _by_title(detail)["Übermittelte Abrechnungsunterlagen"]["parent_chapter_id"] == root["id"]
|
||||
|
||||
dissolved = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/chapters/{sent['id']}/delete",
|
||||
json={"expected_version": detail["version"]},
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
assert detail["version"] == dissolved["version"]
|
||||
assert "Übermittelte Abrechnungsunterlagen" not in _by_title(detail)
|
||||
assert binding_for(detail, "Anschreiben")["chapter_id"] == root["id"]
|
||||
assert binding_for(detail, "Abrechnung")["chapter_id"] == root["id"]
|
||||
assert binding_for(detail, "Rückfrage zur Abrechnung")["chapter_id"] == root["id"]
|
||||
assert _by_title(detail)["Einzelbelege"]["parent_chapter_id"] == root["id"]
|
||||
assert binding_for(detail, "Beleg 8")["chapter_id"] == receipts["id"]
|
||||
|
||||
|
||||
def test_reclassifying_one_context_leaves_the_other_and_hidden_rows_alone(client, db):
|
||||
ada = Actor(client, "ada-zwei@example.test", "Ada Zwei")
|
||||
ben = Actor(client, "ben-zwei@example.test", "Ben Zwei")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
case = case_of(ada, "Wohnung")
|
||||
left = matter_of(ada, "Vorgang A")
|
||||
right = matter_of(ada, "Vorgang B")
|
||||
ada.request("POST", f"/api/v1/matters/{left['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
chapter_a = ada.request("POST", f"/api/v1/matters/{left['id']}/chapters", json={"title": "Lage A"}, status=201)
|
||||
other_a = ada.request("POST", f"/api/v1/matters/{left['id']}/chapters", json={"title": "Ziel A"}, status=201)
|
||||
chapter_b = ada.request("POST", f"/api/v1/matters/{right['id']}/chapters", json={"title": "Lage B"}, status=201)
|
||||
shared = _note(ada, "Gemeinsame Notiz", left, chapter_a["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={
|
||||
"element_id": shared["id"],
|
||||
"source_context": {"kind": "matter", "id": left["id"]},
|
||||
"target": {"kind": "matter", "id": right["id"]},
|
||||
"chapter_id": chapter_b["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
hidden = _note(ada, "Verborgene Strategie", left, chapter_a["id"])
|
||||
reply = _note(ada, "Antwort", left, chapter_a["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{reply['id']}/references",
|
||||
json={"refers_to_element_id": shared["id"], "context": {"kind": "matter", "id": left["id"]}},
|
||||
status=204,
|
||||
)
|
||||
detail = _detail(ada, left["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{left['id']}/bindings/chapters",
|
||||
json={
|
||||
"expected_version": detail["version"],
|
||||
"binding_ids": [binding_for(detail, "Gemeinsame Notiz")["id"], binding_for(detail, "Antwort")["id"]],
|
||||
"chapter_id": other_a["id"],
|
||||
},
|
||||
)
|
||||
left_view = _detail(ada, left["id"])
|
||||
right_view = _detail(ada, right["id"])
|
||||
assert binding_for(left_view, "Gemeinsame Notiz")["chapter_id"] == other_a["id"]
|
||||
assert binding_for(right_view, "Gemeinsame Notiz")["chapter_id"] == chapter_b["id"]
|
||||
assert binding_for(left_view, "Gemeinsame Notiz")["element"]["excerpt"] == "Gemeinsame Notiz"
|
||||
assert binding_for(right_view, "Gemeinsame Notiz")["element"]["excerpt"] == "Gemeinsame Notiz"
|
||||
assert binding_for(left_view, "Antwort")["element"]["refers_to"][0]["title"] == "Gemeinsame Notiz"
|
||||
grant(ada, case["id"], ben.email, edit=False, share=False)
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": hidden["id"],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
ben.login()
|
||||
visible = ben.request("GET", f"/api/v1/matters/{left['id']}?context_kind=case&context_id={case['id']}")
|
||||
titles = [item["element"]["title"] for item in visible["bindings"]]
|
||||
assert "Verborgene Strategie" not in titles
|
||||
assert "Gemeinsame Notiz" in titles
|
||||
assert "Lage B" not in str(visible)
|
||||
ben.request("GET", f"/api/v1/matters/{right['id']}", status=404)
|
||||
|
||||
|
||||
def test_child_matter_keeps_its_own_chapters_and_depth_is_guarded(client, db):
|
||||
ada = Actor(client, "ada-tiefe@example.test", "Ada Tiefe")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
parent = matter_of(ada, "Hauptvorgang")
|
||||
child = ada.request(
|
||||
"POST",
|
||||
"/api/v1/matters",
|
||||
json={"title": "Belegeinsicht", "parent_matter_id": parent["id"]},
|
||||
status=201,
|
||||
)
|
||||
own = ada.request("POST", f"/api/v1/matters/{child['id']}/chapters", json={"title": "Nur hier"}, status=201)
|
||||
parent_view = _detail(ada, parent["id"])
|
||||
child_view = _detail(ada, child["id"])
|
||||
assert parent_view["chapters"] == []
|
||||
assert child_view["chapters"][0]["id"] == own["id"]
|
||||
assert child_view["chapters"][0]["parent_chapter_id"] is None
|
||||
|
||||
case = case_of(ada, "Akte")
|
||||
outer = ada.request("POST", f"/api/v1/cases/{case['id']}/chapters", json={"title": "Aktenkapitel"}, status=201)
|
||||
inner = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case['id']}/chapters",
|
||||
json={"title": "Unterlagen", "parent_chapter_id": outer["id"]},
|
||||
status=201,
|
||||
)
|
||||
case_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
assert {item["title"]: item["parent_chapter_id"] for item in case_view["chapters"]} == {
|
||||
"Aktenkapitel": None,
|
||||
"Unterlagen": outer["id"],
|
||||
}
|
||||
|
||||
current = None
|
||||
for level in range(1, 33):
|
||||
body = {"title": f"Ebene {level}"}
|
||||
if current:
|
||||
body["parent_chapter_id"] = current
|
||||
created = ada.request("POST", f"/api/v1/matters/{parent['id']}/chapters", json=body, status=201)
|
||||
current = created["id"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{parent['id']}/chapters",
|
||||
json={"title": "Ebene 33", "parent_chapter_id": current},
|
||||
status=422,
|
||||
)
|
||||
stored = _detail(ada, parent["id"])
|
||||
assert len(stored["chapters"]) == 32
|
||||
root_id = next(item["id"] for item in stored["chapters"] if item["title"] == "Ebene 1")
|
||||
with pytest.raises(psycopg.Error):
|
||||
db.execute(
|
||||
"UPDATE chapters SET parent_chapter_id = %s WHERE id = %s",
|
||||
(current, root_id),
|
||||
)
|
||||
@@ -0,0 +1,539 @@
|
||||
"""Section A: source binding and the storage port, with today's behaviour kept."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import Problem
|
||||
from app.media.port import (
|
||||
LEGACY_GENERATION,
|
||||
LocalAdapter,
|
||||
MemoryAdapter,
|
||||
check_object_key,
|
||||
instance_for_write,
|
||||
publish,
|
||||
read_clear_bytes,
|
||||
)
|
||||
from app.sourcebind import backfill_source_bindings
|
||||
from tests.support import ORIGIN, Actor, register
|
||||
|
||||
PDF = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\n"
|
||||
|
||||
|
||||
def _raw(actor: Actor, path: str):
|
||||
return actor.client.get(
|
||||
path,
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _case(actor: Actor) -> dict:
|
||||
return actor.request("POST", "/api/v1/cases", json={"title": "Bestand"}, status=201)
|
||||
|
||||
|
||||
def _paperless(actor: Actor, name: str, token: str) -> str:
|
||||
row = actor.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "paperless", "name": name, "base_url": "https://paper.example.test", "token": token},
|
||||
status=201,
|
||||
)
|
||||
return row["id"]
|
||||
|
||||
|
||||
def _link(actor: Actor, case_id: str, connector_id: str | None, external_id: str, title: str) -> str:
|
||||
body = {
|
||||
"title": title,
|
||||
"source": "paperless",
|
||||
"external_id": external_id,
|
||||
"context": {"kind": "case", "id": case_id},
|
||||
}
|
||||
if connector_id:
|
||||
body["detail"] = {"connector_id": connector_id}
|
||||
created = actor.request("POST", "/api/v1/external-refs", json=body, status=201)
|
||||
return created["id"]
|
||||
|
||||
|
||||
def test_storage_adapters_roundtrip_and_reject_escape(tmp_path):
|
||||
payload = b"opaque-bytes"
|
||||
key = str(uuid4())
|
||||
revision = "rev-1"
|
||||
for adapter in (LocalAdapter(tmp_path), MemoryAdapter()):
|
||||
publish(adapter, key, payload)
|
||||
assert adapter.open(key) == payload
|
||||
assert adapter.describe(key)["byte_size"] == len(payload)
|
||||
assert adapter.open(key) == payload
|
||||
assert revision == "rev-1"
|
||||
memory = MemoryAdapter()
|
||||
memory.fail_put = True
|
||||
with pytest.raises(Problem) as failed:
|
||||
publish(memory, str(uuid4()), payload)
|
||||
assert failed.value.code == "storage_unavailable"
|
||||
assert memory._items == {}
|
||||
with pytest.raises(Problem):
|
||||
check_object_key("../secret")
|
||||
with pytest.raises(Problem):
|
||||
check_object_key("/etc/passwd")
|
||||
with pytest.raises(Problem):
|
||||
LocalAdapter(tmp_path).open("dispatch/../../" + str(uuid4()))
|
||||
|
||||
|
||||
def test_changed_root_does_not_retarget_legacy(db, database):
|
||||
legacy = db.execute(
|
||||
"SELECT id, root_path FROM storage_instances WHERE generation = %s",
|
||||
(LEGACY_GENERATION,),
|
||||
).fetchone()
|
||||
key = str(uuid4())
|
||||
original = b"%PDF-legacy-root"
|
||||
publish(LocalAdapter(legacy["root_path"]), key, original)
|
||||
other = Path(database.media_root).parent / f"other-root-{uuid4().hex}"
|
||||
other.mkdir()
|
||||
moved = instance_for_write(db, str(other))
|
||||
assert moved["id"] != legacy["id"]
|
||||
assert moved["generation"] != LEGACY_GENERATION
|
||||
publish(LocalAdapter(moved["root_path"]), key, b"%PDF-other-root")
|
||||
seen = read_clear_bytes(
|
||||
db,
|
||||
instance_id=legacy["id"],
|
||||
generation=LEGACY_GENERATION,
|
||||
object_key=key,
|
||||
media_root=str(other),
|
||||
protection_profile="legacy-plaintext",
|
||||
expected_sha256=None,
|
||||
)
|
||||
assert seen == original
|
||||
db.rollback()
|
||||
|
||||
|
||||
def test_existing_file_keeps_id_bytes_and_revision(client, db):
|
||||
register(db, "ada-file@example.test", "Ada File")
|
||||
ada = Actor(client, "ada-file@example.test", "Ada File")
|
||||
ada.login()
|
||||
case = _case(ada)
|
||||
upload = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Scan", "context_kind": "case", "context_id": case["id"]},
|
||||
files={"upload": ("scan.pdf", PDF, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
stored = db.execute(
|
||||
"""
|
||||
SELECT a.id, a.object_key, a.content_revision, a.storage_generation, a.protection_profile,
|
||||
s.root_path
|
||||
FROM media_assets a
|
||||
JOIN storage_instances s ON s.id = a.storage_instance_id
|
||||
WHERE a.element_id = %s
|
||||
""",
|
||||
(upload["id"],),
|
||||
).fetchone()
|
||||
assert stored["protection_profile"] == "legacy-plaintext"
|
||||
assert stored["object_key"] == str(stored["id"])
|
||||
assert Path(stored["root_path"]) == Path(client.app.state.settings.media_root).resolve()
|
||||
assert stored["storage_generation"]
|
||||
first = stored["content_revision"]
|
||||
opened = _raw(ada, f"/api/v1/files/{upload['id']}/content")
|
||||
assert opened.status_code == 200
|
||||
assert opened.content == PDF
|
||||
again = db.execute(
|
||||
"SELECT content_revision FROM media_assets WHERE element_id = %s",
|
||||
(upload["id"],),
|
||||
).fetchone()
|
||||
assert again["content_revision"] == first
|
||||
refused = ada.client.patch(
|
||||
f"/api/v1/notes/{upload['id']}",
|
||||
json={"expected_version": 1, "document": {"version": 1, "blocks": [{"type": "paragraph", "text": "nein"}]}},
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": ada.csrf,
|
||||
"X-Scope-Kind": ada.scope["kind"],
|
||||
"X-Scope-Id": ada.scope["id"],
|
||||
},
|
||||
)
|
||||
assert refused.status_code == 422
|
||||
assert refused.json()["code"] == "unsupported"
|
||||
|
||||
|
||||
def test_two_paperless_instances_stay_bound_when_order_changes(client, db, monkeypatch):
|
||||
register(db, "ada-two@example.test", "Ada Two")
|
||||
ada = Actor(client, "ada-two@example.test", "Ada Two")
|
||||
ada.login()
|
||||
case = _case(ada)
|
||||
older = _paperless(ada, "Zweitens", "token-older")
|
||||
newer = _paperless(ada, "Erstens", "token-newer")
|
||||
assert older != newer
|
||||
|
||||
def fake_bytes(row, document_id):
|
||||
return f"%PDF-{row['secret']}-{document_id}\n".encode(), "application/pdf", "dokument.pdf"
|
||||
|
||||
monkeypatch.setattr("app.sources._paperless_bytes", fake_bytes)
|
||||
left = _link(ada, case["id"], older, "15", "Altbestand")
|
||||
right = _link(ada, case["id"], newer, "15", "Zweiter Bestand")
|
||||
db.execute("UPDATE connectors SET created_at = now() - interval '2 days' WHERE id = %s", (newer,))
|
||||
db.execute("UPDATE connectors SET created_at = now() WHERE id = %s", (older,))
|
||||
db.commit()
|
||||
assert _raw(ada, f"/api/v1/external-refs/{left}/content").content.startswith(b"%PDF-token-older-15")
|
||||
assert _raw(ada, f"/api/v1/external-refs/{right}/content").content.startswith(b"%PDF-token-newer-15")
|
||||
calls = []
|
||||
|
||||
def fake_get(*args, **kwargs):
|
||||
calls.append(args)
|
||||
return {"results": [{"id": 15, "title": "Treffer", "created": "2024-01-02"}]}
|
||||
|
||||
monkeypatch.setattr("app.sources._paperless_get", fake_get)
|
||||
headers = {
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": ada.csrf,
|
||||
"X-Scope-Kind": ada.scope["kind"],
|
||||
"X-Scope-Id": ada.scope["id"],
|
||||
}
|
||||
refused = ada.client.get("/api/v1/sources/paperless/documents", params={"q": "Treffer"}, headers=headers)
|
||||
assert refused.status_code == 422
|
||||
assert calls == []
|
||||
found = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"q": "Treffer", "connector_id": older},
|
||||
)
|
||||
assert found["items"][0]["title"] == "Treffer"
|
||||
assert found["connector_id"] == older
|
||||
assert found["capabilities"]["search"]["correspondent"] is True
|
||||
assert "correspondent" not in found["unsupported"]
|
||||
filtered = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"q": "Treffer", "connector_id": older, "correspondent": "4"},
|
||||
)
|
||||
assert filtered["items"][0]["title"] == "Treffer"
|
||||
assert calls[-1][3]["correspondent__id"] == "4"
|
||||
assert calls[-1][3]["title_content"] == "Treffer"
|
||||
|
||||
|
||||
def test_ambiguous_legacy_stays_until_assignment(client, db, monkeypatch):
|
||||
register(db, "ada-old@example.test", "Ada Old")
|
||||
ada = Actor(client, "ada-old@example.test", "Ada Old")
|
||||
ada.login()
|
||||
case = _case(ada)
|
||||
loose = _link(ada, case["id"], None, "15", "Ohne Instanz")
|
||||
_paperless(ada, "Alpha", "token-alpha")
|
||||
second = _paperless(ada, "Beta", "token-beta")
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET connector_id = NULL, resolution = 'unresolved', detail = '{}'::jsonb
|
||||
WHERE element_id = %s
|
||||
""",
|
||||
(loose,),
|
||||
)
|
||||
backfill_source_bindings(db)
|
||||
state = db.execute(
|
||||
"SELECT connector_id, resolution FROM external_references WHERE element_id = %s",
|
||||
(loose,),
|
||||
).fetchone()
|
||||
db.commit()
|
||||
assert state["resolution"] == "ambiguous"
|
||||
assert state["connector_id"] is None
|
||||
opened = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
assert opened["bindings"][0]["element"]["id"] == loose
|
||||
assert opened["bindings"][0]["element"]["preview"]["media"] == "unassigned"
|
||||
blocked = _raw(ada, f"/api/v1/external-refs/{loose}/content")
|
||||
assert blocked.status_code == 422
|
||||
assert "eindeutiger Zugang" in blocked.json()["detail"]
|
||||
|
||||
def fake_bytes(row, document_id):
|
||||
del document_id
|
||||
return f"%PDF-{row['secret']}\n".encode(), "application/pdf", "dokument.pdf"
|
||||
|
||||
monkeypatch.setattr("app.sources._paperless_bytes", fake_bytes)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/external-refs/{loose}/assignment",
|
||||
json={"connector_id": second},
|
||||
)
|
||||
_paperless(ada, "Gamma", "token-gamma")
|
||||
assert _raw(ada, f"/api/v1/external-refs/{loose}/content").content.startswith(b"%PDF-token-beta")
|
||||
|
||||
|
||||
def test_legacy_stock_rebinds_and_case_and_matter_open(client, db, monkeypatch):
|
||||
from app.sourceregistry import get_source, unregister_source
|
||||
|
||||
register(db, "ada-keep@example.test", "Ada Keep")
|
||||
ada = Actor(client, "ada-keep@example.test", "Ada Keep")
|
||||
ada.login()
|
||||
case = _case(ada)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Bestand"}, status=201)
|
||||
kept = _paperless(ada, "Archiv", "token-kept")
|
||||
case_ref = _link(ada, case["id"], None, "15", "Vertragsakte")
|
||||
matter_ref = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Vertragsvorgang",
|
||||
"source": "paperless",
|
||||
"external_id": "16",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=201,
|
||||
)["id"]
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET connector_id = NULL, resolution = 'unresolved', detail = '{}'::jsonb
|
||||
WHERE element_id IN (%s, %s)
|
||||
""",
|
||||
(case_ref, matter_ref),
|
||||
)
|
||||
db.commit()
|
||||
unregister_source("paperless")
|
||||
unregister_source("imap")
|
||||
assert get_source("paperless") is None
|
||||
try:
|
||||
backfill_source_bindings(db)
|
||||
db.commit()
|
||||
for element_id in (case_ref, matter_ref):
|
||||
state = db.execute(
|
||||
"SELECT connector_id::text AS connector_id, resolution FROM external_references WHERE element_id = %s",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
assert state["resolution"] == "bound"
|
||||
assert state["connector_id"] == kept
|
||||
assert get_source("paperless") is not None
|
||||
case_page = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
matter_page = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
assert case_page["bindings"][0]["element"]["preview"]["available"] is True
|
||||
assert case_page["bindings"][0]["element"]["preview"]["media"] == "pdf"
|
||||
assert matter_page["bindings"][0]["element"]["preview"]["available"] is True
|
||||
monkeypatch.setattr(
|
||||
"app.sources._paperless_bytes",
|
||||
lambda row, document_id: (f"%PDF-{row['secret']}-{document_id}\n".encode(), "application/pdf", "dokument.pdf"),
|
||||
)
|
||||
assert _raw(ada, f"/api/v1/external-refs/{case_ref}/content").content.startswith(b"%PDF-token-kept-15")
|
||||
assert _raw(ada, f"/api/v1/external-refs/{matter_ref}/content").content.startswith(b"%PDF-token-kept-16")
|
||||
finally:
|
||||
from app.sources import _install_sources
|
||||
|
||||
_install_sources()
|
||||
|
||||
|
||||
def test_connectors_remain_with_their_account(client, db, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
"app.sources._paperless_get",
|
||||
lambda *args, **kwargs: calls.append(args) or {"results": []},
|
||||
)
|
||||
register(db, "ada-own@example.test", "Ada Own")
|
||||
register(db, "ben-own@example.test", "Ben Own")
|
||||
ada = Actor(client, "ada-own@example.test", "Ada Own")
|
||||
ben = Actor(client, "ben-own@example.test", "Ben Own")
|
||||
ada.login()
|
||||
ada_paper = _paperless(ada, "Ada Archiv", "token-ada")
|
||||
ben.login()
|
||||
ben_paper = _paperless(ben, "Ben Archiv", "token-ben")
|
||||
listed = ben.request("GET", "/api/v1/connectors")
|
||||
ids = {item["id"] for item in listed["items"]}
|
||||
assert ben_paper in ids
|
||||
assert ada_paper not in ids
|
||||
assert all(item["name"] != "Ada Archiv" for item in listed["items"])
|
||||
ben.request("POST", f"/api/v1/connectors/{ada_paper}/probe", status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"q": "fremd", "connector_id": ada_paper},
|
||||
status=404,
|
||||
)
|
||||
assert calls == []
|
||||
ada.login()
|
||||
own = {item["id"] for item in ada.request("GET", "/api/v1/connectors")["items"]}
|
||||
assert ada_paper in own
|
||||
assert ben_paper not in own
|
||||
|
||||
|
||||
def test_locked_profile_serves_metadata_not_cleartext(client, db):
|
||||
register(db, "ada-lock@example.test", "Ada Lock")
|
||||
ada = Actor(client, "ada-lock@example.test", "Ada Lock")
|
||||
ada.login()
|
||||
case = _case(ada)
|
||||
upload = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Geschuetzt", "context_kind": "case", "context_id": case["id"]},
|
||||
files={"upload": ("geheim.pdf", PDF, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
dummy = b"cipher-dummy-not-clear"
|
||||
asset = db.execute(
|
||||
"SELECT id, object_key, storage_instance_id FROM media_assets WHERE element_id = %s",
|
||||
(upload["id"],),
|
||||
).fetchone()
|
||||
root = db.execute(
|
||||
"SELECT root_path FROM storage_instances WHERE id = %s",
|
||||
(asset["storage_instance_id"],),
|
||||
).fetchone()["root_path"]
|
||||
path = Path(root) / asset["object_key"]
|
||||
path.write_bytes(dummy)
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE media_assets
|
||||
SET protection_profile = 'client-encrypted',
|
||||
key_responsibility = 'client',
|
||||
sha256 = %s
|
||||
WHERE element_id = %s
|
||||
""",
|
||||
(hashlib.sha256(dummy).hexdigest(), upload["id"]),
|
||||
)
|
||||
db.commit()
|
||||
detail = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
rendered = json.dumps(detail)
|
||||
assert "client-encrypted" in rendered
|
||||
assert "Geschuetzt" in rendered
|
||||
assert dummy.decode() not in rendered
|
||||
opened = _raw(ada, f"/api/v1/files/{upload['id']}/content")
|
||||
assert opened.status_code == 422
|
||||
assert opened.json()["code"] == "unsupported"
|
||||
assert path.read_bytes() == dummy
|
||||
|
||||
|
||||
def test_credential_update_keeps_the_instance(client, db):
|
||||
register(db, "ada-key@example.test", "Ada Key")
|
||||
ada = Actor(client, "ada-key@example.test", "Ada Key")
|
||||
ada.login()
|
||||
first = _paperless(ada, "Archiv", "token-first-1")
|
||||
second = _paperless(ada, "Anderes Archiv", "token-second-2")
|
||||
renewed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/connectors/{first}",
|
||||
json={"kind": "paperless", "name": "Archiv", "base_url": "https://paper.example.test", "token": "token-renewed"},
|
||||
)
|
||||
assert renewed["id"] == first
|
||||
secrets = {
|
||||
str(row["id"]): row["secret"]
|
||||
for row in db.execute("SELECT id, secret FROM connectors").fetchall()
|
||||
}
|
||||
assert secrets[first] == "token-renewed"
|
||||
assert secrets[second] == "token-second-2"
|
||||
caps = ada.request("GET", "/api/v1/sources/capabilities")
|
||||
assert caps["editors"]["note"] is True
|
||||
assert caps["editors"]["markdown_file"] is False
|
||||
assert caps["protection_profiles"]["client-encrypted"] == "locked"
|
||||
paperless = next(item for item in caps["sources"] if item["kind"] == "paperless")
|
||||
assert paperless["search"]["query"] is True
|
||||
assert paperless["edit_content"] is False
|
||||
|
||||
|
||||
def test_legacy_reference_stays_bound_and_foreign_connectors_stay_hidden(client, db, database, monkeypatch):
|
||||
"""A startup without loaded modules must still keep the one existing connection."""
|
||||
from app.db.migrate import _prepare_source_storage
|
||||
from app.sourceregistry import unregister_source
|
||||
from app.sources import _install_sources
|
||||
|
||||
def fake_bytes(row, document_id):
|
||||
del document_id
|
||||
return f"%PDF-{row['secret']}\n".encode(), "application/pdf", "dokument.pdf"
|
||||
|
||||
monkeypatch.setattr("app.sources._paperless_bytes", fake_bytes)
|
||||
register(db, "ada-legacy@example.test", "Ada Legacy")
|
||||
register(db, "ben-legacy@example.test", "Ben Legacy")
|
||||
ada = Actor(client, "ada-legacy@example.test", "Ada Legacy")
|
||||
ben = Actor(client, "ben-legacy@example.test", "Ben Legacy")
|
||||
ada.login()
|
||||
case = _case(ada)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Altbestand"}, status=201)
|
||||
connector = _paperless(ada, "Archiv", "token-legacy")
|
||||
case_ref = _link(ada, case["id"], None, "15", "Akte")
|
||||
matter_ref = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Vorgang",
|
||||
"source": "paperless",
|
||||
"external_id": "16",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=201,
|
||||
)["id"]
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET connector_id = NULL, resolution = 'unresolved', detail = '{}'::jsonb
|
||||
WHERE element_id IN (%s, %s)
|
||||
""",
|
||||
(case_ref, matter_ref),
|
||||
)
|
||||
db.commit()
|
||||
|
||||
opened = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
shown = next(item["element"] for item in opened["bindings"] if item["element"]["id"] == case_ref)
|
||||
assert shown["preview"]["media"] == "pdf"
|
||||
assert shown["preview"]["available"] is True
|
||||
assert _raw(ada, f"/api/v1/external-refs/{case_ref}/content?context_kind=case&context_id={case['id']}").content.startswith(
|
||||
b"%PDF-token-legacy"
|
||||
)
|
||||
matter_view = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
matter_element = next(item["element"] for item in matter_view["bindings"] if item["element"]["id"] == matter_ref)
|
||||
assert matter_element["preview"]["media"] == "pdf"
|
||||
|
||||
unregister_source("paperless")
|
||||
unregister_source("imap")
|
||||
try:
|
||||
_prepare_source_storage(database)
|
||||
finally:
|
||||
_install_sources()
|
||||
state = db.execute(
|
||||
"SELECT connector_id::text AS connector_id, resolution FROM external_references WHERE element_id = %s",
|
||||
(case_ref,),
|
||||
).fetchone()
|
||||
assert state["connector_id"] == connector
|
||||
assert state["resolution"] == "bound"
|
||||
|
||||
ben.login()
|
||||
own = _paperless(ben, "Bens Archiv", "token-ben")
|
||||
listed = {item["id"] for item in ben.request("GET", "/api/v1/connectors")["items"]}
|
||||
assert listed == {own}
|
||||
ben.request("POST", f"/api/v1/connectors/{connector}/probe", status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"q": "Alt", "connector_id": connector},
|
||||
status=404,
|
||||
)
|
||||
ada.login()
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": False},
|
||||
status=201,
|
||||
)
|
||||
ben.login()
|
||||
shared = ben.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
shared_element = next(item["element"] for item in shared["bindings"] if item["element"]["id"] == matter_ref)
|
||||
assert "connector_id" not in shared_element["external"]["detail"]
|
||||
assert "external_id" not in shared_element["external"]
|
||||
blocked = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{matter_ref}/content?context_kind=matter&context_id={matter['id']}",
|
||||
)
|
||||
assert blocked.status_code == 422
|
||||
ada.login()
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": True},
|
||||
status=201,
|
||||
)
|
||||
ben.login()
|
||||
allowed = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{matter_ref}/content?context_kind=matter&context_id={matter['id']}",
|
||||
)
|
||||
assert allowed.status_code == 200
|
||||
assert allowed.content.startswith(b"%PDF-token-legacy")
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Connector configuration: fields come from the module, secrets never leave the server."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import Problem
|
||||
from app.sourceregistry import ConfigField, parse_fields
|
||||
from tests.sample_source import install_sample_source, remove_sample_source
|
||||
from tests.support import Actor, register
|
||||
|
||||
SECRET_WORDS = ("secret", "token-geheim-1234", "passwort-geheim")
|
||||
|
||||
PAPERLESS = {"kind": "paperless", "name": "Archiv", "base_url": "https://paper.example.test", "token": "token-geheim-1234"}
|
||||
IMAP = {
|
||||
"kind": "imap",
|
||||
"name": "Postfach",
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": "ada",
|
||||
"password": "passwort-geheim",
|
||||
"security": "ssl",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_source():
|
||||
install_sample_source()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
remove_sample_source()
|
||||
|
||||
|
||||
def _ada(client, db) -> Actor:
|
||||
ada = Actor(client, "ada-config@example.test", "Ada Konfig")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
return ada
|
||||
|
||||
|
||||
def _stored(db, connector_id: str) -> dict:
|
||||
return db.execute("SELECT settings, secret FROM connectors WHERE id = %s", (connector_id,)).fetchone()
|
||||
|
||||
|
||||
def test_parse_fields_checks_types_and_refuses_unknown_keys():
|
||||
fields = (
|
||||
ConfigField("host", "Server", required=True),
|
||||
ConfigField("port", "Port", type="number", default=993, minimum=1, maximum=65535),
|
||||
ConfigField("mode", "Modus", type="select", default="a", options=(("a", "A"), ("b", "B"))),
|
||||
ConfigField("key", "Schlüssel", type="password", required=True, secret=True),
|
||||
)
|
||||
settings, secret = parse_fields(fields, {"host": " h ", "key": "k"})
|
||||
assert settings == {"host": "h", "port": 993, "mode": "a"}
|
||||
assert secret == "k"
|
||||
for bad in (
|
||||
{"host": "h", "key": "k", "port": "abc"},
|
||||
{"host": "h", "key": "k", "port": 0},
|
||||
{"host": "h", "key": "k", "mode": "c"},
|
||||
{"host": "h", "key": "k", "fremd": "x"},
|
||||
{"key": "k"},
|
||||
{"host": "h"},
|
||||
):
|
||||
with pytest.raises(Problem) as caught:
|
||||
parse_fields(fields, bad)
|
||||
assert caught.value.status == 422
|
||||
kept_settings, kept_secret = parse_fields(fields, {"host": "neu", "key": ""}, {"host": "alt", "port": 143}, "bleibt")
|
||||
assert kept_settings["host"] == "neu" and kept_settings["port"] == 143
|
||||
assert kept_secret == "bleibt"
|
||||
|
||||
|
||||
def test_capabilities_list_the_fields_of_each_module(client, db):
|
||||
ada = _ada(client, db)
|
||||
modules = {item["kind"]: item for item in ada.request("GET", "/api/v1/sources/capabilities")["modules"]}
|
||||
assert {"paperless", "imap"} <= set(modules)
|
||||
paperless = {item["key"]: item for item in modules["paperless"]["config_fields"]}
|
||||
assert paperless["token"]["secret"] is True and paperless["base_url"]["required"] is True
|
||||
imap = {item["key"]: item for item in modules["imap"]["config_fields"]}
|
||||
assert imap["password"]["secret"] is True
|
||||
assert imap["port"]["type"] == "number" and imap["port"]["default"] == 993
|
||||
assert [option["value"] for option in imap["security"]["options"]] == ["ssl", "starttls"]
|
||||
assert imap["mailbox"]["default"] == "INBOX"
|
||||
|
||||
|
||||
def test_create_with_config_and_flat_fields_gives_the_same_stored_result(client, db):
|
||||
ada = _ada(client, db)
|
||||
flat = ada.request("POST", "/api/v1/connectors", json=PAPERLESS, status=201)
|
||||
config = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "paperless",
|
||||
"name": "Zweites Archiv",
|
||||
"config": {"base_url": "https://paper.example.test/", "token": "token-geheim-1234"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert _stored(db, flat["id"]) == _stored(db, config["id"])
|
||||
assert _stored(db, flat["id"])["settings"] == {"base_url": "https://paper.example.test"}
|
||||
|
||||
|
||||
def test_secrets_never_leave_the_server(client, db):
|
||||
ada = _ada(client, db)
|
||||
created = ada.request("POST", "/api/v1/connectors", json=IMAP, status=201)
|
||||
detail = ada.request("GET", f"/api/v1/connectors/{created['id']}")
|
||||
listed = ada.request("GET", "/api/v1/connectors")
|
||||
for body in (created, detail, listed):
|
||||
text = str(body)
|
||||
assert not any(word in text for word in SECRET_WORDS if word != "secret"), text
|
||||
assert "'secret'" not in text and "'password'" not in text and "'token'" not in text
|
||||
assert detail["has_secret"] is True
|
||||
assert detail["settings"]["mailbox"] == "INBOX"
|
||||
assert detail["settings"]["port"] == 993
|
||||
assert detail["protection_profile"] == "legacy-plaintext"
|
||||
assert detail["references"] == 0
|
||||
assert detail["probe"] is None
|
||||
|
||||
|
||||
def test_change_without_secret_keeps_the_stored_one_and_the_instance(client, db):
|
||||
ada = _ada(client, db)
|
||||
created = ada.request("POST", "/api/v1/connectors", json=IMAP, status=201)
|
||||
changed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/connectors/{created['id']}",
|
||||
json={"kind": "imap", "name": "Umbenannt", "config": {"host": "mail.example.test", "port": "143", "security": "starttls"}},
|
||||
)
|
||||
assert changed["id"] == created["id"]
|
||||
assert changed["name"] == "Umbenannt"
|
||||
stored = _stored(db, created["id"])
|
||||
assert stored["secret"] == "passwort-geheim"
|
||||
assert stored["settings"]["host"] == "mail.example.test"
|
||||
assert stored["settings"]["port"] == 143
|
||||
assert stored["settings"]["security"] == "starttls"
|
||||
assert stored["settings"]["username"] == "ada"
|
||||
renewed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/connectors/{created['id']}",
|
||||
json={"kind": "imap", "name": "Umbenannt", "config": {"password": "neues-passwort"}},
|
||||
)
|
||||
assert renewed["id"] == created["id"]
|
||||
assert _stored(db, created["id"])["secret"] == "neues-passwort"
|
||||
|
||||
|
||||
def test_module_validation_refuses_bad_input(client, db):
|
||||
ada = _ada(client, db)
|
||||
ada.request("POST", "/api/v1/connectors", json={**PAPERLESS, "base_url": "ftp://paper.example.test"}, status=422)
|
||||
ada.request("POST", "/api/v1/connectors", json={**PAPERLESS, "token": "kurz"}, status=422)
|
||||
ada.request("POST", "/api/v1/connectors", json={**IMAP, "host": "mail server"}, status=422)
|
||||
ada.request("POST", "/api/v1/connectors", json={**IMAP, "port": 70000}, status=422)
|
||||
ada.request("POST", "/api/v1/connectors", json={**IMAP, "password": None}, status=422)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "paperless", "name": "Fremdfeld", "config": {"base_url": "https://paper.example.test", "token": "token-geheim-1234", "host": "x"}},
|
||||
status=422,
|
||||
)
|
||||
created = ada.request("POST", "/api/v1/connectors", json=PAPERLESS, status=201)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/connectors/{created['id']}",
|
||||
json={**PAPERLESS, "kind": "imap"},
|
||||
status=422,
|
||||
)
|
||||
assert _stored(db, created["id"])["settings"] == {"base_url": "https://paper.example.test"}
|
||||
|
||||
|
||||
def test_a_foreign_instance_is_not_found(client, db):
|
||||
ada = _ada(client, db)
|
||||
ben = Actor(client, "ben-config@example.test", "Ben Konfig")
|
||||
register(db, ben.email, ben.name)
|
||||
created = ada.request("POST", "/api/v1/connectors", json=PAPERLESS, status=201)
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/connectors/{created['id']}", status=404)
|
||||
ben.request("PATCH", f"/api/v1/connectors/{created['id']}", json=PAPERLESS, status=404)
|
||||
ben.request("DELETE", f"/api/v1/connectors/{created['id']}", status=404)
|
||||
|
||||
|
||||
def test_probe_result_is_kept_for_display(client, db, sample_source):
|
||||
del sample_source
|
||||
ada = _ada(client, db)
|
||||
created = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "sample", "name": "Katalog", "config": {"catalog": "alpha"}},
|
||||
status=201,
|
||||
)
|
||||
probed = ada.request("POST", f"/api/v1/connectors/{created['id']}/probe")
|
||||
detail = ada.request("GET", f"/api/v1/connectors/{created['id']}")
|
||||
assert detail["probe"]["ok"] is True
|
||||
assert detail["probe"]["detail"] == probed["detail"]
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/connectors/{created['id']}",
|
||||
json={"kind": "sample", "name": "Katalog", "config": {"catalog": "alpha"}},
|
||||
)
|
||||
assert ada.request("GET", f"/api/v1/connectors/{created['id']}")["probe"] is None
|
||||
|
||||
|
||||
def test_a_module_with_fields_needs_no_central_schema(client, db, sample_source):
|
||||
del sample_source
|
||||
ada = _ada(client, db)
|
||||
modules = {item["kind"]: item for item in ada.request("GET", "/api/v1/sources/capabilities")["modules"]}
|
||||
assert [item["key"] for item in modules["sample"]["config_fields"]] == ["catalog"]
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "sample", "name": "Ohne Wert", "config": {}},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "sample", "name": "Falsch", "config": {"catalog": "kein-katalog"}},
|
||||
status=422,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,503 @@
|
||||
"""Corrections K1–K3 and K7. Synthetic only; no live mailbox or Paperless."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import imaplib
|
||||
|
||||
import psycopg
|
||||
import pytest
|
||||
from email.message import EmailMessage
|
||||
|
||||
import app.sources as sources
|
||||
from app.core.errors import unprocessable
|
||||
from app.mailpack import parse_mail
|
||||
from tests.support import Actor, register
|
||||
|
||||
|
||||
def test_mailbox_names_are_quoted_protocol_strings():
|
||||
client = imaplib.IMAP4.__new__(imaplib.IMAP4)
|
||||
client.sent = []
|
||||
client.state = "AUTH"
|
||||
client._encoding = "ascii"
|
||||
client.tagpre = b"T"
|
||||
client.tagnum = 1
|
||||
client.tagged_commands = {}
|
||||
client.untagged_responses = {}
|
||||
client.is_readonly = True
|
||||
client.literal = None
|
||||
client.debug = 0
|
||||
client._mesg = lambda *args: None
|
||||
client._log = lambda *args: None
|
||||
client.send = lambda data: client.sent.append(data)
|
||||
|
||||
value = "Sent Items"
|
||||
client._command("EXAMINE", sources._mailbox_argument(value))
|
||||
assert client.sent[-1] == b'T1 EXAMINE "Sent Items"\r\n'
|
||||
value = 'Ordner "A"\\B'
|
||||
client._command("EXAMINE", sources._mailbox_argument(value))
|
||||
assert client.sent[-1] == b'T2 EXAMINE "Ordner \\"A\\"\\\\B"\r\n'
|
||||
assert sources._mailbox_argument("INBOX") == "INBOX"
|
||||
with pytest.raises(Exception):
|
||||
sources._mailbox_argument("Sent\nItems")
|
||||
|
||||
|
||||
def test_parse_mail_keeps_names_html_and_attached_messages():
|
||||
inner = EmailMessage()
|
||||
inner["Subject"] = "Innen"
|
||||
inner.set_content("innen bleibt drin")
|
||||
inner.add_attachment(b"innen-pdf", maintype="application", subtype="pdf", filename="innen.pdf")
|
||||
outer = EmailMessage()
|
||||
outer["From"] = "Ada <ada@example.test>"
|
||||
outer["To"] = "Ben <ben@example.test>"
|
||||
outer["Subject"] = "=?utf-8?q?Aussen?="
|
||||
outer.set_content("aussen bleibt aussen")
|
||||
outer.add_attachment(b"%PDF-same", maintype="application", subtype="pdf", filename="lage.pdf")
|
||||
outer.add_attachment(b"%PDF-other", maintype="application", subtype="pdf", filename="lage.pdf")
|
||||
outer.add_attachment(inner, subtype="rfc822", filename="weitergeleitet.eml")
|
||||
html = (
|
||||
"<p>A & B</p><table><tr><td>Zelle</td><td>Zwei</td></tr></table>"
|
||||
"<script>alert(1)</script><img src=\"https://evil.test/a.png\">"
|
||||
"<a href=\"javascript:alert(1)\">x</a><img src=\"cid:logo@x\">"
|
||||
)
|
||||
mixed = EmailMessage()
|
||||
mixed["Subject"] = "HTML"
|
||||
mixed.set_content("nur text")
|
||||
mixed.add_alternative(html, subtype="html")
|
||||
logo = b"\x89PNG\r\n"
|
||||
mixed.add_attachment(logo, maintype="image", subtype="png", filename="logo.png", cid="<logo@x>")
|
||||
encoded = EmailMessage()
|
||||
encoded["Subject"] = "Namen"
|
||||
encoded.set_content("datei")
|
||||
encoded.add_attachment(
|
||||
b"pdf",
|
||||
maintype="application",
|
||||
subtype="pdf",
|
||||
filename="=?utf-8?q?Buero_Uebergabe=2Epdf?=",
|
||||
)
|
||||
|
||||
parsed = parse_mail(outer.as_bytes())
|
||||
assert parsed.subject == "Aussen"
|
||||
assert parsed.text == "aussen bleibt aussen"
|
||||
assert "innen" not in parsed.text
|
||||
names = [item.display_name for item in parsed.attachments]
|
||||
assert "weitergeleitet.eml" in names
|
||||
assert names.count("lage.pdf") == 2
|
||||
archives = [item.filename for item in parsed.attachments]
|
||||
assert len(set(archives)) == len(archives)
|
||||
attached = next(item for item in parsed.attachments if item.display_name == "weitergeleitet.eml")
|
||||
assert b"innen bleibt drin" in attached.data or b"Innen" in attached.data
|
||||
assert attached.sha256 == hashlib.sha256(attached.data).hexdigest()
|
||||
|
||||
view = parse_mail(mixed.as_bytes())
|
||||
assert "<table>" in view.html
|
||||
assert "<script" not in view.html
|
||||
assert "https://evil.test" not in view.html
|
||||
assert "javascript:" not in view.html
|
||||
assert "data:image/png;base64," in view.html
|
||||
assert "A & B" in view.html or "A & B" in view.html
|
||||
assert "Zelle" in view.html
|
||||
|
||||
named = parse_mail(encoded.as_bytes())
|
||||
assert named.attachments[0].display_name == "Buero Uebergabe.pdf"
|
||||
assert "=?utf-8?" not in named.attachments[0].display_name
|
||||
assert named.attachments[0].data == b"pdf"
|
||||
|
||||
|
||||
def test_an_undecoded_pdf_stays_a_named_pdf():
|
||||
import base64
|
||||
from app.media.storage import content_disposition
|
||||
|
||||
pdf = b"%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n"
|
||||
raw = (
|
||||
b"Subject: Scan\r\n"
|
||||
b"MIME-Version: 1.0\r\n"
|
||||
b"Content-Type: multipart/mixed; boundary=bound\r\n"
|
||||
b"\r\n"
|
||||
b"--bound\r\n"
|
||||
b"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
b"\r\n"
|
||||
b"text\r\n"
|
||||
b"--bound\r\n"
|
||||
b"Content-Type: application/octet-stream\r\n"
|
||||
b"Content-Transfer-Encoding: 8bit\r\n"
|
||||
b"Content-Disposition: attachment; filename=\"scan-7f3a9c\"\r\n"
|
||||
b"\r\n"
|
||||
+ base64.b64encode(pdf) + b"\r\n"
|
||||
b"--bound--\r\n"
|
||||
)
|
||||
item = parse_mail(raw).attachments[0]
|
||||
assert item.data.startswith(b"%PDF")
|
||||
assert item.media_type == "application/pdf"
|
||||
assert item.display_name == "scan-7f3a9c.pdf"
|
||||
header = content_disposition("\u00dcbergabe.pdf", inline=True)
|
||||
assert header.startswith("inline;")
|
||||
header.encode("ascii")
|
||||
assert ".pdf" in header
|
||||
assert "filename*=UTF-8''" in header
|
||||
assert "%C3%9Cbergabe.pdf" in header
|
||||
|
||||
|
||||
class QuotedIMAP:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.untagged_responses = {}
|
||||
|
||||
def login(self, username, secret):
|
||||
return "OK", [b"logged"]
|
||||
|
||||
def list(self):
|
||||
return "OK", [b'(\\HasNoChildren) "/" "Sent Items"']
|
||||
|
||||
def select(self, mailbox, readonly=False):
|
||||
assert readonly is True
|
||||
assert mailbox == '"Sent Items"'
|
||||
self.untagged_responses = {
|
||||
"EXISTS": [b"4200"],
|
||||
"UIDVALIDITY": [b"8"],
|
||||
"UIDNEXT": [b"2"],
|
||||
}
|
||||
return "OK", [b"4200"]
|
||||
|
||||
def uid(self, command, *args):
|
||||
if command == "SEARCH":
|
||||
return "OK", [b""]
|
||||
header = b"From: Ada <ada@example.test>\r\nSubject: Leer\r\nDate: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
return "OK", [(b"body", header), b")"]
|
||||
|
||||
def logout(self):
|
||||
return "BYE", [b""]
|
||||
|
||||
|
||||
def test_a_filled_folder_with_spaces_is_not_reported_empty(client, db, monkeypatch):
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", QuotedIMAP)
|
||||
ada = Actor(client, "ada-sent@example.test", "Ada Gesendet")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
account = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": "Post",
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": "ada@example.test",
|
||||
"password": "Postfach-Geheim",
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
page = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/messages",
|
||||
params={"connector_id": account["id"], "mailbox": "Sent Items"},
|
||||
)
|
||||
assert page["items"] == []
|
||||
assert page["contradictory"] is True
|
||||
assert page["exists"] == 4200
|
||||
assert "leer" not in str(page).casefold()
|
||||
|
||||
|
||||
def _multipart(text: str, name: str, payload: bytes) -> bytes:
|
||||
message = EmailMessage()
|
||||
message["From"] = "Ada <ada@example.test>"
|
||||
message["To"] = "Ben <ben@example.test>"
|
||||
message["Subject"] = "Grenze"
|
||||
message["Message-ID"] = "<grenze@example.test>"
|
||||
message.set_content(text)
|
||||
message.add_attachment(payload, maintype="application", subtype="pdf", filename=name)
|
||||
return message.as_bytes()
|
||||
|
||||
|
||||
class LimitIMAP:
|
||||
raw = b""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.untagged_responses = {}
|
||||
|
||||
def login(self, username, secret):
|
||||
return "OK", [b"ok"]
|
||||
|
||||
def list(self):
|
||||
return "OK", [b'(\\HasNoChildren) "/" "INBOX"']
|
||||
|
||||
def select(self, mailbox, readonly=False):
|
||||
self.untagged_responses = {"UIDVALIDITY": [b"1"], "UIDNEXT": [b"3"], "EXISTS": [b"1"]}
|
||||
return "OK", [b"1"]
|
||||
|
||||
def uid(self, command, *args):
|
||||
spec = " ".join(str(part) for part in args[1:])
|
||||
if "BODY.PEEK[]" in spec and "<" not in spec:
|
||||
return "OK", [(b"rfc822", type(self).raw)]
|
||||
if "BODYSTRUCTURE" in spec:
|
||||
structure = (
|
||||
b'(("TEXT" "PLAIN" ("CHARSET" "utf-8") NIL NIL "7BIT" 12 1 NIL NIL NIL NIL)'
|
||||
b'("APPLICATION" "PDF" NIL NIL NIL "BASE64" 20 NIL '
|
||||
b'("ATTACHMENT" ("FILENAME" "=?utf-8?q?Buero_Uebergabe=2Epdf?=")) NIL NIL)'
|
||||
b' "MIXED" ("BOUNDARY" "b") NIL NIL NIL)'
|
||||
)
|
||||
return "OK", [(b"body", structure)]
|
||||
if "BODY.PEEK[1]" in spec:
|
||||
return "OK", [(b"part", b"gleicher text")]
|
||||
if "BODY.PEEK[2]" in spec:
|
||||
return "OK", [(b"part", b"nicht text")]
|
||||
header = (
|
||||
b"From: Ada <ada@example.test>\r\nTo: Ben <ben@example.test>\r\n"
|
||||
b"Subject: Grenze\r\nDate: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
)
|
||||
return "OK", [(b"body", header), b")"]
|
||||
|
||||
def logout(self):
|
||||
return "BYE", [b""]
|
||||
|
||||
|
||||
def test_preview_below_and_above_the_limit_uses_the_same_parts(client, db, monkeypatch):
|
||||
payload = b"%PDF-plan"
|
||||
small = _multipart("gleicher text", "Buero Uebergabe.pdf", payload)
|
||||
LimitIMAP.raw = small + b"X" * 50
|
||||
monkeypatch.setattr(sources, "PREVIEW_BYTE_LIMIT", len(small))
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", LimitIMAP)
|
||||
ada = Actor(client, "ada-limit@example.test", "Ada Grenze")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
account = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": "Post",
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": "ada@example.test",
|
||||
"password": "Postfach-Geheim",
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
under = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/message",
|
||||
params={"connector_id": account["id"], "mailbox": "INBOX", "uid": 1},
|
||||
)
|
||||
LimitIMAP.raw = small + b"Y"
|
||||
over = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/message",
|
||||
params={"connector_id": account["id"], "mailbox": "INBOX", "uid": 1},
|
||||
)
|
||||
assert "gleicher text" in under["text"]
|
||||
assert "gleicher text" in over["text"]
|
||||
assert under["attachments"][0]["filename"] == "Buero Uebergabe.pdf"
|
||||
assert over["attachments"][0]["filename"] == "Buero Uebergabe.pdf"
|
||||
assert "Content-Transfer-Encoding" not in over["text"]
|
||||
assert "BASE64" not in over["text"].upper()
|
||||
assert over["preview_limited"] is True
|
||||
|
||||
|
||||
def test_upload_and_mail_fetch_leave_the_domain_transaction(client, db, monkeypatch):
|
||||
seen = []
|
||||
|
||||
import app.api.routes as routes
|
||||
import app.ops as ops
|
||||
from app.media.port import publish as real_publish
|
||||
|
||||
def watching(adapter, key, data):
|
||||
seen.append(("publish", ops_conn[0].info.transaction_status))
|
||||
return real_publish(adapter, key, data)
|
||||
|
||||
ops_conn = [None]
|
||||
real_create = ops.create_file
|
||||
|
||||
def wrapped_create(conn, *args, **kwargs):
|
||||
ops_conn[0] = conn
|
||||
return real_create(conn, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(ops, "publish", watching)
|
||||
monkeypatch.setattr(routes, "create_file", wrapped_create)
|
||||
ada = Actor(client, "ada-idle@example.test", "Ada Leerlauf")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Ablage"}, status=201)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Scan", "context_kind": "case", "context_id": case["id"]},
|
||||
files={"upload": ("scan.pdf", b"%PDF-1.4\n", "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
assert seen[0][1] == psycopg.pq.TransactionStatus.IDLE
|
||||
|
||||
import app.sourceaccess as sourceaccess
|
||||
|
||||
phase = {"external": False, "status": None}
|
||||
real_release = sourceaccess.release_for_external
|
||||
|
||||
def spy_release(conn):
|
||||
real_release(conn)
|
||||
phase["external"] = True
|
||||
phase["status"] = conn.info.transaction_status
|
||||
|
||||
def spy_owned(*args, **kwargs):
|
||||
if phase["external"]:
|
||||
raise AssertionError("Datenbankzugriff im externen Abschnitt")
|
||||
return real_owned(*args, **kwargs)
|
||||
|
||||
def spy_pull(*args, **kwargs):
|
||||
assert phase["status"] == psycopg.pq.TransactionStatus.IDLE
|
||||
return _multipart("brief", "a.pdf", b"%PDF")
|
||||
|
||||
real_owned = sources._owned
|
||||
monkeypatch.setattr(sourceaccess, "release_for_external", spy_release)
|
||||
monkeypatch.setattr(sources, "_owned", spy_owned)
|
||||
monkeypatch.setattr(sources, "pull_rfc822", spy_pull)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", QuotedIMAP)
|
||||
account = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": "Post",
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": "ada@example.test",
|
||||
"password": "Postfach-Geheim",
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Post"}, status=201)
|
||||
linked = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Brief",
|
||||
"source": "imap",
|
||||
"external_id": "<grenze@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": account["id"], "mailbox": "Sent Items", "uid": 4},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
opened = ada.request("GET", f"/api/v1/external-refs/{linked['id']}/mail")
|
||||
assert opened["text"]
|
||||
assert phase["status"] == psycopg.pq.TransactionStatus.IDLE
|
||||
|
||||
|
||||
def test_failed_conclusion_keeps_no_partial_file(client, db, monkeypatch):
|
||||
import app.ops as ops
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise unprocessable("Abschluss fehlgeschlagen")
|
||||
|
||||
monkeypatch.setattr(ops, "_new_element", fail)
|
||||
ada = Actor(client, "ada-fail@example.test", "Ada Abschluss")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Ablage"}, status=201)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Scan", "context_kind": "case", "context_id": case["id"]},
|
||||
files={"upload": ("scan.pdf", b"%PDF-FAIL-CONCLUSION\n", "application/pdf")},
|
||||
status=422,
|
||||
)
|
||||
stored = db.execute("SELECT count(*) AS n FROM elements WHERE title = 'Scan'").fetchone()
|
||||
assert stored["n"] == 0
|
||||
from pathlib import Path
|
||||
from app.core.settings import get_settings
|
||||
|
||||
root = Path(get_settings().media_root)
|
||||
left = [path for path in root.rglob("*") if path.is_file() and b"PDF-FAIL-CONCLUSION" in path.read_bytes()]
|
||||
assert left == []
|
||||
|
||||
|
||||
def test_paperless_filters_change_the_hits(client, db, monkeypatch):
|
||||
catalog = []
|
||||
for number in range(1, 46):
|
||||
catalog.append({
|
||||
"id": number,
|
||||
"title": "Vertrag" if number % 5 == 0 else f"Schrift {number}",
|
||||
"content": "nurinhalt" if number == 41 else f"text {number}",
|
||||
"correspondent": 4 if number % 2 == 0 else 9,
|
||||
"document_type": 8 if number < 30 else 1,
|
||||
"tags": [2, 5] if number % 3 == 0 else [2],
|
||||
"created": "2024-06-01" if number > 20 else "2023-01-01",
|
||||
})
|
||||
|
||||
def fake_get(base, token, path, params):
|
||||
if path != "/api/documents/":
|
||||
return {"count": 1, "results": [{"id": 4, "name": "Haus"}]}
|
||||
matched = []
|
||||
for item in catalog:
|
||||
query = params.get("title_content") or params.get("query") or ""
|
||||
title = params.get("title__icontains") or ""
|
||||
if query and query.casefold() not in f"{item['title']} {item['content']}".casefold():
|
||||
continue
|
||||
if title and title.casefold() not in item["title"].casefold():
|
||||
continue
|
||||
if params.get("correspondent__id") and str(item["correspondent"]) != params["correspondent__id"]:
|
||||
continue
|
||||
if params.get("document_type__id") and str(item["document_type"]) != params["document_type__id"]:
|
||||
continue
|
||||
if params.get("tags__id__all"):
|
||||
needed = {int(part) for part in params["tags__id__all"].split(",") if part}
|
||||
if not needed.issubset(set(item["tags"])):
|
||||
continue
|
||||
start = params.get("created__date__gte")
|
||||
end = params.get("created__date__lte")
|
||||
if start and item["created"] < start:
|
||||
continue
|
||||
if end and item["created"] > end:
|
||||
continue
|
||||
matched.append(item)
|
||||
page = int(params.get("page") or 1)
|
||||
start_at = (page - 1) * 20
|
||||
rows = matched[start_at:start_at + 20]
|
||||
return {
|
||||
"count": len(matched),
|
||||
"results": [{"id": item["id"], "title": item["title"], "created": item["created"]} for item in rows],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(sources, "_paperless_get", fake_get)
|
||||
ada = Actor(client, "ada-sense@example.test", "Ada Sinn")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
account = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "paperless", "name": "Archiv", "base_url": "https://paper.example.test", "token": "token-alpha"},
|
||||
status=201,
|
||||
)
|
||||
content = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"connector_id": account["id"], "q": "nurinhalt"},
|
||||
)
|
||||
assert [item["id"] for item in content["items"]] == ["41"]
|
||||
title = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"connector_id": account["id"], "title": "Vertrag"},
|
||||
)
|
||||
assert title["items"]
|
||||
assert all("Vertrag" in item["title"] for item in title["items"])
|
||||
assert all(item["id"] != "41" for item in title["items"])
|
||||
combined = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={
|
||||
"connector_id": account["id"],
|
||||
"correspondent": "4",
|
||||
"document_type": "8",
|
||||
"tag": "2,5",
|
||||
"document_from": "2023-01-01",
|
||||
"document_to": "2024-12-31",
|
||||
},
|
||||
)
|
||||
plain = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"connector_id": account["id"], "cursor": "2"},
|
||||
)
|
||||
assert [item["id"] for item in combined["items"]] == ["6", "12", "18", "24"]
|
||||
assert [item["id"] for item in plain["items"]][0] == "21"
|
||||
@@ -0,0 +1,640 @@
|
||||
"""Schreiben, Anlagen, Versandfassungen, Nachweise, Rechte und Export."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import zipfile
|
||||
from email.message import EmailMessage
|
||||
from pathlib import Path
|
||||
|
||||
from tests.support import ORIGIN, Actor, document, grant, register
|
||||
|
||||
PDF_A = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nA\n"
|
||||
PDF_B = b"%PDF-1.4\n2 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nB\n"
|
||||
PDF_C = b"%PDF-1.4\n3 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nC\n"
|
||||
PDF_D = b"%PDF-1.4\n4 0 obj<<>>endobj\ntrailer<<>>\n%%EOF\nD\n"
|
||||
|
||||
|
||||
def _detail(actor: Actor, matter_id: str, context: dict | None = None) -> dict:
|
||||
params = None
|
||||
if context is not None:
|
||||
params = {"context_kind": context["kind"], "context_id": context["id"]}
|
||||
return actor.request("GET", f"/api/v1/matters/{matter_id}", params=params)
|
||||
|
||||
|
||||
def _binding(detail: dict, title: str) -> dict:
|
||||
for item in detail["bindings"]:
|
||||
if item["element"]["title"] == title:
|
||||
return item
|
||||
raise AssertionError(title)
|
||||
|
||||
|
||||
def _file(actor: Actor, matter_id: str, title: str, name: str, data: bytes, document_on: str, chapter_id: str | None = None) -> dict:
|
||||
form = {"title": title, "context_kind": "matter", "context_id": matter_id, "document_on": document_on}
|
||||
if chapter_id:
|
||||
form["chapter_id"] = chapter_id
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data=form,
|
||||
files={"upload": (name, data, "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def _ctx(matter_id: str) -> dict:
|
||||
return {"kind": "matter", "id": matter_id}
|
||||
|
||||
|
||||
def _eml(message_id: str, body: str, attachments: list[tuple[str, bytes]]) -> bytes:
|
||||
message = EmailMessage()
|
||||
message["Subject"] = "Versandnachweis"
|
||||
message["From"] = "kanzlei@example.test"
|
||||
message["To"] = "gegenueber@example.test"
|
||||
message["Message-ID"] = message_id
|
||||
message["Date"] = "Thu, 12 Mar 2026 10:00:00 +0100"
|
||||
message.set_content(body)
|
||||
for name, data in attachments:
|
||||
message.add_attachment(data, maintype="application", subtype="pdf", filename=name)
|
||||
return message.as_bytes()
|
||||
|
||||
|
||||
def _zip(actor: Actor, matter_id: str, selected: list[str]) -> zipfile.ZipFile:
|
||||
headers = {
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"Content-Type": "application/json",
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
}
|
||||
response = actor.client.post(
|
||||
f"/api/v1/matters/{matter_id}/export",
|
||||
json={"selected": selected},
|
||||
headers=headers,
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
return zipfile.ZipFile(io.BytesIO(response.content))
|
||||
|
||||
|
||||
def _walk(node):
|
||||
yield node
|
||||
for child in node.get("children") or []:
|
||||
yield from _walk(child)
|
||||
|
||||
|
||||
def test_attachments_keep_other_uses_and_do_not_copy_files(client, db):
|
||||
ada = Actor(client, "ada-anlage@example.test", "Ada Anlage")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Schreiben A"}, status=201)
|
||||
other = ada.request("POST", "/api/v1/matters", json={"title": "Schreiben B"}, status=201)
|
||||
chapter = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Korrespondenz"}, status=201)
|
||||
sub = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Einzelbelege", "parent_chapter_id": chapter["id"]},
|
||||
status=201,
|
||||
)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Anschreiben",
|
||||
"document": document("Bitte um Stellungnahme"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"chapter_id": chapter["id"],
|
||||
"dates": {"document_on": "2026-03-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
first = _file(ada, matter["id"], "Rechnung 2023", "rechnung.pdf", PDF_A, "2023-05-01", sub["id"])
|
||||
second = _file(ada, matter["id"], "Lageplan", "lage.pdf", PDF_B, "2024-01-15", sub["id"])
|
||||
third = _file(ada, matter["id"], "Kontoauszug", "konto.pdf", PDF_C, "2025-11-02", sub["id"])
|
||||
before = db.execute("SELECT count(*) AS n FROM media_assets").fetchone()["n"]
|
||||
detail = _detail(ada, matter["id"])
|
||||
host = _binding(detail, "Anschreiben")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [first["id"], second["id"], third["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ordered = _detail(ada, matter["id"])
|
||||
host = _binding(ordered, "Anschreiben")
|
||||
assert [item["title"] for item in host["correspondence"]["attachments"]] == [
|
||||
"Rechnung 2023",
|
||||
"Lageplan",
|
||||
"Kontoauszug",
|
||||
]
|
||||
assert [item["document_on"] for item in host["correspondence"]["attachments"]] == [
|
||||
"2023-05-01",
|
||||
"2024-01-15",
|
||||
"2025-11-02",
|
||||
]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments/order",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [third["id"], first["id"], second["id"]],
|
||||
},
|
||||
)
|
||||
moved = _detail(ada, matter["id"])
|
||||
host = _binding(moved, "Anschreiben")
|
||||
assert [item["element_id"] for item in host["correspondence"]["attachments"]] == [third["id"], first["id"], second["id"]]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments/{second['id']}/detach",
|
||||
json={"expected_version": host["element"]["version"], "context": _ctx(matter["id"])},
|
||||
status=204,
|
||||
)
|
||||
kept = _detail(ada, matter["id"])
|
||||
assert _binding(kept, "Lageplan")["chapter_id"] == sub["id"]
|
||||
assert [item["title"] for item in _binding(kept, "Anschreiben")["correspondence"]["attachments"]] == [
|
||||
"Kontoauszug",
|
||||
"Rechnung 2023",
|
||||
]
|
||||
assert any(item["title"] == "Einzelbelege" and item["parent_chapter_id"] == chapter["id"] for item in kept["chapters"])
|
||||
after = db.execute("SELECT count(*) AS n FROM media_assets").fetchone()["n"]
|
||||
assert after == before
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={"element_id": first["id"], "source_context": _ctx(matter["id"]), "target": _ctx(other["id"])},
|
||||
status=201,
|
||||
)
|
||||
other_letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Zweites Schreiben", "document": document("Andere Sache"), "context": _ctx(other["id"])},
|
||||
status=201,
|
||||
)
|
||||
other_detail = _detail(ada, other["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{other_letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(other_detail, "Zweites Schreiben")["element"]["version"],
|
||||
"context": _ctx(other["id"]),
|
||||
"attachment_element_ids": [first["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
again = _detail(ada, matter["id"])
|
||||
elsewhere = _detail(ada, other["id"])
|
||||
assert [item["element_id"] for item in _binding(again, "Anschreiben")["correspondence"]["attachments"]] == [
|
||||
third["id"],
|
||||
first["id"],
|
||||
]
|
||||
assert [item["element_id"] for item in _binding(elsewhere, "Zweites Schreiben")["correspondence"]["attachments"]] == [
|
||||
first["id"],
|
||||
]
|
||||
grants = db.execute("SELECT count(*) AS n FROM access_grants").fetchone()["n"]
|
||||
assert grants == 0
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(again, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [letter["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=422,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(again, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(other["id"]),
|
||||
"attachment_element_ids": [first["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=404,
|
||||
)
|
||||
|
||||
|
||||
def test_dispatch_keeps_the_secured_stand_and_distinct_mail_parts(client, db, monkeypatch):
|
||||
raw = _eml(
|
||||
"<versand@example.test>",
|
||||
"Fachlicher Zusatz: die Frist bleibt der 1. Juni.",
|
||||
[("rechnung.pdf", PDF_A), ("lage.pdf", PDF_B), ("konto.pdf", PDF_C), ("lage.pdf", PDF_D)],
|
||||
)
|
||||
monkeypatch.setattr("app.sources.pull_rfc822", lambda *args, **kwargs: raw)
|
||||
ada = Actor(client, "ada-versand@example.test", "Ada Versand")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Versandakte"}, status=201)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Anschreiben",
|
||||
"document": document("Ursprünglicher Text"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"dates": {"document_on": "2026-02-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
invoice = _file(ada, matter["id"], "Rechnung 2023", "rechnung.pdf", PDF_A, "2023-05-01")
|
||||
plan = _file(ada, matter["id"], "Lageplan", "lage.pdf", PDF_B, "2024-01-15")
|
||||
account = _file(ada, matter["id"], "Kontoauszug", "konto.pdf", PDF_C, "2025-11-02")
|
||||
mailbox = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "imap", "name": "Postfach", "host": "mail.example.test", "username": "ada", "password": "secret-pass"},
|
||||
status=201,
|
||||
)
|
||||
mail = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Gesendete Nachricht",
|
||||
"source": "imap",
|
||||
"external_id": "<versand@example.test>",
|
||||
"context": _ctx(matter["id"]),
|
||||
"detail": {"connector_id": mailbox["id"], "mailbox": "INBOX", "uid": 4},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(detail, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [invoice["id"], plan["id"], account["id"]],
|
||||
"fold": "attachment",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
folded = _detail(ada, matter["id"])
|
||||
assert _binding(folded, "Rechnung 2023")["correspondence"]["fold"] == "attachment"
|
||||
host = _binding(folded, "Anschreiben")
|
||||
dispatch = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "email",
|
||||
"sent_on": "2026-03-12",
|
||||
"counterpart": "Gegenüber Beispiel",
|
||||
"attachment_element_ids": [invoice["id"], plan["id"], account["id"]],
|
||||
"evidence": [{"element_id": mail["id"], "role": "email", "fold": "evidence"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert dispatch["completeness"] == "secured"
|
||||
assert dispatch["provenance"] == "captured"
|
||||
assert dispatch["sent_on"] == "2026-03-12"
|
||||
proof = dispatch["evidence"][0]
|
||||
assert proof["source_state"] == "identified"
|
||||
assert proof["manual"] is True
|
||||
by_name = {item["filename"]: item["disposition"] for item in proof["comparisons"]}
|
||||
assert by_name["rechnung.pdf"] == "same_bytes"
|
||||
assert by_name["lage.pdf"] == "same_bytes"
|
||||
assert by_name["konto.pdf"] == "same_bytes"
|
||||
assert by_name["lage (2).pdf"] == "same_name_different_bytes"
|
||||
uses = db.execute("SELECT count(*) AS n FROM attachment_uses").fetchone()["n"]
|
||||
assert uses == 3
|
||||
hidden = _detail(ada, matter["id"])
|
||||
assert _binding(hidden, "Gesendete Nachricht")["correspondence"]["fold"] == "evidence"
|
||||
placed = list(_walk(ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]))
|
||||
assert not any(node["kind"] == "binding" and node["title"] in {"Rechnung 2023", "Gesendete Nachricht"} for node in placed)
|
||||
assert sum(1 for node in placed if node["kind"] == "attachment" and node["title"] == "Rechnung 2023") == 1
|
||||
assert any(node["kind"] == "dispatch_item" and node["title"] == "Rechnung 2023" for node in placed)
|
||||
assert any(node["kind"] == "evidence" and node["title"] == "Gesendete Nachricht" for node in placed)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{_binding(hidden, 'Gesendete Nachricht')['id']}/fold",
|
||||
json={
|
||||
"expected_version": _binding(hidden, "Gesendete Nachricht")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"fold": None,
|
||||
},
|
||||
)
|
||||
restored = _detail(ada, matter["id"])
|
||||
assert _binding(restored, "Gesendete Nachricht")["correspondence"]["fold"] is None
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{_binding(restored, 'Gesendete Nachricht')['id']}/fold",
|
||||
json={
|
||||
"expected_version": _binding(restored, "Gesendete Nachricht")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"fold": "evidence",
|
||||
},
|
||||
)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{letter['id']}",
|
||||
json={
|
||||
"expected_version": _binding(restored, "Anschreiben")["element"]["version"],
|
||||
"document": document("Später geänderter Text"),
|
||||
"context": _ctx(matter["id"]),
|
||||
},
|
||||
)
|
||||
changed = _detail(ada, matter["id"])
|
||||
assert "Später geänderter Text" in _binding(changed, "Anschreiben")["element"]["excerpt"]
|
||||
asset = db.execute("SELECT id FROM media_assets WHERE element_id = %s", (plan["id"],)).fetchone()
|
||||
Path(os.environ["MEDIA_ROOT"], str(asset["id"])).write_bytes(PDF_D)
|
||||
fresh = _detail(ada, matter["id"])
|
||||
host = _binding(fresh, "Anschreiben")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments/{account['id']}/detach",
|
||||
json={"expected_version": host["element"]["version"], "context": _ctx(matter["id"])},
|
||||
status=204,
|
||||
)
|
||||
current = _detail(ada, matter["id"])
|
||||
recorded = _binding(current, "Anschreiben")["correspondence"]["dispatches"][0]
|
||||
assert [item["title"] for item in recorded["items"] if item["role"] == "attachment"] == [
|
||||
"Rechnung 2023",
|
||||
"Lageplan",
|
||||
"Kontoauszug",
|
||||
]
|
||||
assert recorded["sent_on"] == "2026-03-12"
|
||||
assert _binding(current, "Anschreiben")["element"]["dates"]["document_on"] == "2026-02-01"
|
||||
plan_item = next(item for item in recorded["items"] if item["title"] == "Lageplan")
|
||||
content = ada.client.get(
|
||||
f"/api/v1/dispatches/{recorded['id']}/items/{plan_item['id']}/content",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": ada.csrf,
|
||||
"X-Scope-Kind": ada.scope["kind"],
|
||||
"X-Scope-Id": ada.scope["id"],
|
||||
},
|
||||
)
|
||||
assert content.status_code == 200
|
||||
assert content.content == PDF_B
|
||||
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")
|
||||
nodes = list(_walk(tree["tree"]))
|
||||
selected = [node["id"] for node in nodes if node["kind"] in {"dispatch_item", "evidence"}]
|
||||
archive = _zip(ada, matter["id"], selected)
|
||||
names = archive.namelist()
|
||||
snapshot = next(
|
||||
name for name in names if "Anschreiben" in name and name.endswith("/Anlagen/Lageplan.pdf")
|
||||
)
|
||||
assert archive.read(snapshot) == PDF_B
|
||||
eml_name = next(name for name in names if name.endswith("nachricht.eml"))
|
||||
assert b"Fachlicher Zusatz" in archive.read(eml_name)
|
||||
assert archive.read(eml_name).count(b"lage.pdf") >= 2
|
||||
overview = archive.read("inhalt.md").decode("utf-8")
|
||||
assert "Gesicherte Versandfassung" in overview
|
||||
assert "Schreiben → Versand → Nachweis" in overview
|
||||
first_text = "\n".join(
|
||||
archive.read(name).decode("utf-8", errors="replace")
|
||||
for name in names
|
||||
if name.endswith((".md", ".txt", ".eml", ".json"))
|
||||
)
|
||||
assert "Ursprünglicher Text" in first_text
|
||||
assert "Später geänderter Text" not in first_text
|
||||
gap = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": _binding(current, "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "post",
|
||||
"sent_on": None,
|
||||
"counterpart": None,
|
||||
"attachment_element_ids": [invoice["id"]],
|
||||
"historical_gap": True,
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert gap["provenance"] == "reconstructed"
|
||||
assert gap["completeness"] == "gap"
|
||||
assert gap["undated"] is True
|
||||
assert gap["sent_on"] is None
|
||||
assert all(item["source_state"] == "gap" for item in gap["items"])
|
||||
receipt = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Einlieferungsbeleg",
|
||||
"document": document("Eingeliefert am Schalter"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"dates": {"document_on": "2026-03-20"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
delivery = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Zustellbestätigung",
|
||||
"document": document("Zugestellt"),
|
||||
"context": _ctx(matter["id"]),
|
||||
"dates": {"document_on": "2026-03-28"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
posted = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": _binding(_detail(ada, matter["id"]), "Anschreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "post",
|
||||
"sent_on": "2026-03-18",
|
||||
"counterpart": "Poststelle",
|
||||
"attachment_element_ids": [invoice["id"]],
|
||||
"evidence": [{"element_id": receipt["id"], "role": "submission", "fold": "keep"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert posted["evidence"][0]["role"] == "submission"
|
||||
assert "zugestellt" not in json.dumps(posted).lower()
|
||||
added = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/dispatches/{posted['id']}/evidence",
|
||||
json={
|
||||
"expected_version": posted["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"element_id": delivery["id"],
|
||||
"role": "delivery",
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
assert added["role"] == "delivery"
|
||||
final = _detail(ada, matter["id"])
|
||||
sends = _binding(final, "Anschreiben")["correspondence"]["dispatches"]
|
||||
assert len(sends) == 3
|
||||
assert {item["channel"] for item in sends} == {"email", "post"}
|
||||
post_send = next(item for item in sends if item["sent_on"] == "2026-03-18")
|
||||
assert {item["role"] for item in post_send["evidence"]} == {"submission", "delivery"}
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/dispatches/{post_send['id']}/evidence/{delivery['id']}/detach",
|
||||
json={"expected_version": post_send["version"], "context": _ctx(matter["id"])},
|
||||
status=204,
|
||||
)
|
||||
final = _detail(ada, matter["id"])
|
||||
sends = _binding(final, "Anschreiben")["correspondence"]["dispatches"]
|
||||
post_send = next(item for item in sends if item["sent_on"] == "2026-03-18")
|
||||
assert {item["role"] for item in post_send["evidence"]} == {"submission"}
|
||||
assert _binding(final, "Zustellbestätigung")["correspondence"]["fold"] is None
|
||||
assert _binding(final, "Zustellbestätigung")["element"]["dates"]["document_on"] == "2026-03-28"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": final["version"], "mode": "date", "direction": "asc", "view": "chronology"},
|
||||
)
|
||||
viewed = _detail(ada, matter["id"])
|
||||
assert viewed["content_view"] == "chronology"
|
||||
assert viewed["content_order"] == "date"
|
||||
assert _binding(viewed, "Anschreiben")["chapter_id"] is None
|
||||
excerpt_tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")
|
||||
host_item = next(
|
||||
node["id"]
|
||||
for node in _walk(excerpt_tree["tree"])
|
||||
if node["kind"] == "dispatch_item" and node["title"] == "Anschreiben"
|
||||
)
|
||||
review = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/export/review",
|
||||
json={"selected": [host_item]},
|
||||
)
|
||||
assert any("Auszug dieses Versands" in item["message"] for item in review["notices"])
|
||||
whole = [node["id"] for node in _walk(excerpt_tree["tree"]) if node["id"].startswith("dispatch-item:") or node["id"].startswith("evidence:")]
|
||||
full = _zip(ada, matter["id"], whole)
|
||||
joined = "\n".join(full.read(name).decode("utf-8", errors="replace") for name in full.namelist() if name.endswith((".md", ".txt", ".eml", ".json")))
|
||||
assert "Ursprünglicher Text" in joined
|
||||
assert "Historische Fassung liegt nicht vor" in joined
|
||||
gaps = [name for name in full.namelist() if name.endswith("-luecke.txt")]
|
||||
assert gaps
|
||||
assert all("Später geänderter Text" not in full.read(name).decode("utf-8") for name in gaps)
|
||||
assert all(b"%PDF" not in full.read(name) for name in gaps)
|
||||
secured = next(
|
||||
name for name in full.namelist() if "Anschreiben" in name and name.endswith("/Anlagen/Lageplan.pdf")
|
||||
)
|
||||
assert full.read(secured) == PDF_B
|
||||
|
||||
|
||||
def test_locked_parts_and_readers_stay_outside(client, db):
|
||||
ada = Actor(client, "ada-sperre@example.test", "Ada Sperre")
|
||||
ben = Actor(client, "ben-sperre@example.test", "Ben Sperre")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Geteilte Akte"}, status=201)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Geteilter Vorgang"}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Sichtbares Schreiben", "document": document("Sichtbar"), "context": _ctx(matter["id"])},
|
||||
status=201,
|
||||
)
|
||||
secret = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Geheime AnlageXQ", "document": document("Nicht zeigen"), "context": _ctx(matter["id"])},
|
||||
status=201,
|
||||
)
|
||||
proof = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Geheimer NachweisXQ", "document": document("Auch nicht"), "context": _ctx(matter["id"])},
|
||||
status=201,
|
||||
)
|
||||
detail = _detail(ada, matter["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(detail, "Sichtbares Schreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [secret["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
sent = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/dispatches",
|
||||
json={
|
||||
"expected_version": _binding(_detail(ada, matter["id"]), "Sichtbares Schreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"channel": "other",
|
||||
"sent_on": "2026-04-01",
|
||||
"attachment_element_ids": [secret["id"]],
|
||||
"evidence": [{"element_id": proof["id"], "role": "other", "fold": "keep"}],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
grant(ada, case["id"], ben.email, edit=False, share=False)
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": secret["id"],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": proof["id"],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
ben.login()
|
||||
page = {"kind": "case", "id": case["id"]}
|
||||
visible = _detail(ben, matter["id"], page)
|
||||
blob = json.dumps(visible)
|
||||
assert "Geheime AnlageXQ" not in blob
|
||||
assert "Geheimer NachweisXQ" not in blob
|
||||
assert "Nicht zeigen" not in blob
|
||||
host = _binding(visible, "Sichtbares Schreiben")
|
||||
assert host["correspondence"]["attachments"] == []
|
||||
assert host["correspondence"]["dispatches"][0]["evidence"] == []
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": host["element"]["version"],
|
||||
"context": page,
|
||||
"placement": _ctx(matter["id"]),
|
||||
"attachment_element_ids": [letter["id"]],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/dispatches/{sent['id']}/correct",
|
||||
json={"expected_version": sent["version"], "context": page, "placement": _ctx(matter["id"]), "counterpart": "Fremd"},
|
||||
status=403,
|
||||
)
|
||||
ada.login()
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{letter['id']}/attachments",
|
||||
json={
|
||||
"expected_version": _binding(_detail(ada, matter["id"]), "Sichtbares Schreiben")["element"]["version"],
|
||||
"context": _ctx(matter["id"]),
|
||||
"attachment_element_ids": ["00000000-0000-4000-8000-000000000099"],
|
||||
"fold": "keep",
|
||||
},
|
||||
status=404,
|
||||
)
|
||||
@@ -0,0 +1,258 @@
|
||||
"""Communication direction lives on the binding and is never inferred from dates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import Actor, bind_to, case_of, document, matter_of, register
|
||||
|
||||
|
||||
def _matter(actor: Actor, matter_id: str) -> dict:
|
||||
return actor.request("GET", f"/api/v1/matters/{matter_id}")
|
||||
|
||||
|
||||
def _binding(detail: dict, title: str) -> dict:
|
||||
return next(item for item in detail["bindings"] if item["element"]["title"] == title)
|
||||
|
||||
|
||||
def _note(actor: Actor, matter_id: str, title: str, direction: str | None = None, **dates) -> dict:
|
||||
body = {
|
||||
"title": title,
|
||||
"document": document(title),
|
||||
"context": {"kind": "matter", "id": matter_id},
|
||||
}
|
||||
if dates:
|
||||
body["dates"] = dates
|
||||
if direction in ("in", "out"):
|
||||
body["communication_direction"] = direction
|
||||
return actor.request("POST", "/api/v1/notes", json=body, status=201)
|
||||
|
||||
|
||||
def test_dates_do_not_invent_a_direction_and_explicit_choice_survives(client, db):
|
||||
ada = Actor(client, "ada-richtung@example.test", "Ada Richtung")
|
||||
ben = Actor(client, "ben-richtung@example.test", "Ben Richtung")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Kautionsabrechnung")
|
||||
_note(ada, matter["id"], "Beide Daten", document_on="2026-10-12", sent_on="2026-10-01", received_on="2026-10-12")
|
||||
_note(ada, matter["id"], "Telefon Eingang", "in")
|
||||
_note(ada, matter["id"], "Telefon Ausgang", "out")
|
||||
_note(ada, matter["id"], "Gedankenprotokoll")
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Scan ohne Richtung",
|
||||
"source": "paperless",
|
||||
"external_id": "scan-42",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"open_url": "https://example.test/scan-42"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Mail der Verwaltung",
|
||||
"source": "imap",
|
||||
"external_id": "<verwaltung@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {
|
||||
"direction": "in",
|
||||
"message_from": "Hausverwaltung Mueller",
|
||||
"mailbox": "INBOX",
|
||||
"connector_id": "6f0b6a2e-1c4d-4b8a-9e2f-0a1b2c3d4e5f",
|
||||
"uid": 17,
|
||||
},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
shown = _matter(ada, matter["id"])
|
||||
both = _binding(shown, "Beide Daten")
|
||||
assert both["communication"] == {"direction": None, "explicit": False}
|
||||
assert both["element"]["dates"]["sent_on"] == "2026-10-01"
|
||||
assert both["element"]["dates"]["received_on"] == "2026-10-12"
|
||||
assert _binding(shown, "Telefon Eingang")["communication"]["direction"] == "in"
|
||||
assert _binding(shown, "Telefon Ausgang")["communication"]["direction"] == "out"
|
||||
assert _binding(shown, "Gedankenprotokoll")["communication"]["direction"] is None
|
||||
assert _binding(shown, "Scan ohne Richtung")["communication"]["direction"] is None
|
||||
mail = _binding(shown, "Mail der Verwaltung")
|
||||
assert mail["communication"] == {"direction": "in", "explicit": True}
|
||||
assert mail["element"]["external"]["detail"]["connector_id"] == "6f0b6a2e-1c4d-4b8a-9e2f-0a1b2c3d4e5f"
|
||||
assert mail["element"]["external"]["detail"]["uid"] == 17
|
||||
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{mail['id']}/communication",
|
||||
json={"expected_version": mail["element"]["version"], "direction": None, "context": {"kind": "matter", "id": matter["id"]}},
|
||||
)
|
||||
cleared = _binding(_matter(ada, matter["id"]), "Mail der Verwaltung")
|
||||
assert cleared["communication"] == {"direction": None, "explicit": True}
|
||||
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{both['id']}/communication",
|
||||
json={"expected_version": both["element"]["version"], "direction": "out", "context": {"kind": "matter", "id": matter["id"]}},
|
||||
)
|
||||
chosen = _binding(_matter(ada, matter["id"]), "Beide Daten")
|
||||
assert chosen["communication"] == {"direction": "out", "explicit": True}
|
||||
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False},
|
||||
status=201,
|
||||
)
|
||||
ben.login()
|
||||
visible = _binding(_matter(ben, matter["id"]), "Beide Daten")
|
||||
assert visible["communication"]["direction"] == "out"
|
||||
ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{visible['id']}/communication",
|
||||
json={"expected_version": visible["element"]["version"], "direction": "in", "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=403,
|
||||
)
|
||||
|
||||
|
||||
def test_a_second_binding_keeps_its_own_direction(client, db):
|
||||
ada = Actor(client, "ada-bindung@example.test", "Ada Bindung")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
first = case_of(ada, "Erste Akte")
|
||||
second = case_of(ada, "Zweite Akte")
|
||||
created = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Gemeinsame Notiz",
|
||||
"document": {"version": 1, "blocks": [{"type": "markdown", "text": "# Anruf\n\n**Eingang**"}]},
|
||||
"context": {"kind": "case", "id": first["id"]},
|
||||
"communication_direction": "in",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
bind_to(ada, created["id"], first["id"], second["id"])
|
||||
left = ada.request("GET", f"/api/v1/cases/{first['id']}")
|
||||
right = ada.request("GET", f"/api/v1/cases/{second['id']}")
|
||||
left_binding = next(item for item in left["bindings"] if item["element"]["title"] == "Gemeinsame Notiz")
|
||||
right_binding = next(item for item in right["bindings"] if item["element"]["title"] == "Gemeinsame Notiz")
|
||||
assert left_binding["communication"]["direction"] == "in"
|
||||
assert right_binding["communication"]["direction"] is None
|
||||
assert left_binding["element"]["document"]["blocks"][0]["type"] == "markdown"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{right_binding['id']}/communication",
|
||||
json={"expected_version": right_binding["element"]["version"], "direction": "out", "context": {"kind": "case", "id": second["id"]}},
|
||||
)
|
||||
left_again = ada.request("GET", f"/api/v1/cases/{first['id']}")
|
||||
right_again = ada.request("GET", f"/api/v1/cases/{second['id']}")
|
||||
assert next(item for item in left_again["bindings"] if item["element"]["id"] == created["id"])["communication"]["direction"] == "in"
|
||||
assert next(item for item in right_again["bindings"] if item["element"]["id"] == created["id"])["communication"]["direction"] == "out"
|
||||
|
||||
|
||||
def test_chapter_and_matter_can_be_renamed_and_moved(client, db):
|
||||
ada = Actor(client, "ada-struktur@example.test", "Ada Struktur")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
case = case_of(ada, "Vermietung")
|
||||
other = case_of(ada, "Ferienhaus")
|
||||
matter = matter_of(ada, "Nebenkosten")
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
parent = matter_of(ada, "Wohnung")
|
||||
ada.request("POST", f"/api/v1/matters/{parent['id']}/case-links", json={"case_id": other["id"]}, status=201)
|
||||
chapter = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Schreiben"},
|
||||
status=201,
|
||||
)
|
||||
detail = _matter(ada, matter["id"])
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/chapters/{chapter['id']}/title",
|
||||
json={"expected_version": detail["version"], "title": "Korrespondenz", "context": {"kind": "case", "id": case["id"]}},
|
||||
)
|
||||
current = _matter(ada, matter["id"])
|
||||
assert current["chapters"][0]["title"] == "Korrespondenz"
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/move",
|
||||
json={
|
||||
"expected_version": current["version"],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"case_id": other["id"],
|
||||
"parent_matter_id": parent["id"],
|
||||
},
|
||||
)
|
||||
moved = _matter(ada, matter["id"])
|
||||
assert moved["parent_matter_id"] == parent["id"]
|
||||
assert any(item["case_id"] == other["id"] for item in moved["placements"])
|
||||
assert all(item["case_id"] != case["id"] for item in moved["placements"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case['id']}/delete",
|
||||
json={"expected_version": ada.request("GET", f"/api/v1/cases/{case['id']}")["version"]},
|
||||
)
|
||||
ada.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
|
||||
|
||||
def test_one_beleg_does_not_classify_the_chapter(client, db):
|
||||
ada = Actor(client, "ada-kapitel@example.test", "Ada Kapitel")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Schriftverkehr")
|
||||
chapter = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters",
|
||||
json={"title": "Belege"},
|
||||
status=201,
|
||||
)
|
||||
for title, external_id in (("Eingangsschreiben", "pl-1"), ("Antwortschreiben", "pl-2"), ("Rechnung", "pl-3")):
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": title,
|
||||
"source": "paperless",
|
||||
"external_id": external_id,
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": chapter["id"],
|
||||
"dates": {"document_on": "2026-10-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = _matter(ada, matter["id"])
|
||||
incoming = _binding(detail, "Eingangsschreiben")
|
||||
reply = _binding(detail, "Antwortschreiben")
|
||||
invoice = _binding(detail, "Rechnung")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{reply['element']['id']}/references",
|
||||
json={"refers_to_element_id": incoming["element"]["id"], "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=204,
|
||||
)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{incoming['id']}/communication",
|
||||
json={"expected_version": incoming["element"]["version"], "direction": "in", "context": {"kind": "matter", "id": matter["id"]}},
|
||||
)
|
||||
shown = _matter(ada, matter["id"])
|
||||
assert _binding(shown, "Eingangsschreiben")["communication"] == {"direction": "in", "explicit": True}
|
||||
assert _binding(shown, "Antwortschreiben")["communication"]["direction"] is None
|
||||
assert _binding(shown, "Rechnung")["communication"]["direction"] is None
|
||||
assert _binding(shown, "Antwortschreiben")["element"]["refers_to"][0]["direction"] == "in"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{reply['id']}/communication",
|
||||
json={"expected_version": reply["element"]["version"], "direction": "out", "context": {"kind": "matter", "id": matter["id"]}},
|
||||
)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{invoice['id']}/communication",
|
||||
json={"expected_version": invoice["element"]["version"], "direction": "local", "context": {"kind": "matter", "id": matter["id"]}},
|
||||
)
|
||||
final = _matter(ada, matter["id"])
|
||||
assert _binding(final, "Eingangsschreiben")["communication"]["direction"] == "in"
|
||||
assert _binding(final, "Antwortschreiben")["communication"]["direction"] == "out"
|
||||
assert _binding(final, "Rechnung")["communication"] == {"direction": "local", "explicit": True}
|
||||
assert all(item["chapter_id"] == chapter["id"] for item in final["bindings"])
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Bereits eingefügte Quelldokumente: Vorabfrage, Warnung (409), erneutes Einfügen und zusätzliches Einbinden."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.support import matter_of
|
||||
from tests.test_team import _main
|
||||
|
||||
PREF = "/api/v1/auth/preferences/duplicate_check"
|
||||
EXISTING = "/api/v1/external-refs/existing"
|
||||
CONNECTOR = str(uuid4())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ada(client, db):
|
||||
return _main(client, db, "ada", main=True)
|
||||
|
||||
|
||||
def _ref(actor, kind, container, external_id="41", connector=CONNECTOR, status=201, **extra):
|
||||
body = {
|
||||
"title": f"Dokument {external_id}",
|
||||
"source": "paperless",
|
||||
"external_id": external_id,
|
||||
"context": {"kind": kind, "id": container},
|
||||
"detail": {"connector_id": connector},
|
||||
**extra,
|
||||
}
|
||||
return actor.request("POST", "/api/v1/external-refs", json=body, status=status)
|
||||
|
||||
|
||||
def _ask(actor, kind, container, external_id="41", connector=CONNECTOR):
|
||||
body = {
|
||||
"context": {"kind": kind, "id": container},
|
||||
"items": [{"source": "paperless", "external_id": external_id, "connector_id": connector}],
|
||||
}
|
||||
return actor.request("POST", EXISTING, json=body)["items"][0]["matches"]
|
||||
|
||||
|
||||
def _level(actor, value):
|
||||
actor.request("PUT", PREF, json={"value": value})
|
||||
|
||||
|
||||
def test_a_document_in_the_same_container_warns_and_can_be_inserted_anyway(ada):
|
||||
matter = matter_of(ada, "Mietminderung")["id"]
|
||||
first = _ref(ada, "matter", matter)
|
||||
found = _ask(ada, "matter", matter)
|
||||
assert [(m["element_id"], m["where"], m["certain"]) for m in found] == [(first["id"], "here", True)]
|
||||
|
||||
refused = _ref(ada, "matter", matter, status=409)
|
||||
assert refused["code"] == "already_present"
|
||||
# A deliberate second insert goes through. Another document or another connection is no duplicate.
|
||||
_ref(ada, "matter", matter, duplicate="insert")
|
||||
_ref(ada, "matter", matter, external_id="42")
|
||||
_ref(ada, "matter", matter, connector=str(uuid4()))
|
||||
assert _ask(ada, "matter", matter, external_id="42")[0]["where"] == "here"
|
||||
|
||||
|
||||
def test_the_same_document_in_another_vorgang_is_no_duplicate(ada):
|
||||
one = matter_of(ada, "Eins")["id"]
|
||||
two = matter_of(ada, "Zwei")["id"]
|
||||
_ref(ada, "matter", one)
|
||||
assert _ask(ada, "matter", two) == []
|
||||
_ref(ada, "matter", two)
|
||||
|
||||
|
||||
def test_the_check_can_be_switched_off(ada):
|
||||
matter = matter_of(ada, "Mietminderung")["id"]
|
||||
_ref(ada, "matter", matter)
|
||||
_level(ada, "off")
|
||||
assert _ask(ada, "matter", matter) == []
|
||||
_ref(ada, "matter", matter)
|
||||
|
||||
|
||||
def test_levels_reach_into_teilvorgang_vorgang_and_akte(ada):
|
||||
parent = matter_of(ada, "Hauptvorgang")["id"]
|
||||
child = ada.request("POST", "/api/v1/matters", json={"title": "Teil", "parent_matter_id": parent}, status=201)["id"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Akte"}, status=201)["id"]
|
||||
ada.request("POST", f"/api/v1/matters/{parent}/case-links", json={"case_id": case}, status=201)
|
||||
_ref(ada, "matter", child, external_id="1")
|
||||
_ref(ada, "matter", parent, external_id="2")
|
||||
_ref(ada, "case", case, external_id="3")
|
||||
|
||||
def where(kind, container, external_id):
|
||||
return [m["where"] for m in _ask(ada, kind, container, external_id)]
|
||||
|
||||
# Standard: only what sits directly in the target.
|
||||
assert where("matter", parent, "1") == []
|
||||
_level(ada, "inside")
|
||||
assert where("matter", parent, "1") == ["inside"]
|
||||
assert where("matter", child, "2") == []
|
||||
assert where("case", case, "2") == ["inside"]
|
||||
assert where("case", case, "3") == ["here"]
|
||||
_level(ada, "around")
|
||||
assert where("matter", child, "2") == ["around"]
|
||||
assert where("matter", parent, "3") == ["around"]
|
||||
assert where("matter", child, "3") == ["around"]
|
||||
# The server warns at the same level.
|
||||
_ref(ada, "matter", child, external_id="3", status=409)
|
||||
|
||||
|
||||
def test_an_existing_element_can_be_bound_instead_of_a_new_one(ada):
|
||||
parent = matter_of(ada, "Hauptvorgang")["id"]
|
||||
child = ada.request("POST", "/api/v1/matters", json={"title": "Teil", "parent_matter_id": parent}, status=201)["id"]
|
||||
original = _ref(ada, "matter", child)
|
||||
_level(ada, "inside")
|
||||
assert _ask(ada, "matter", parent)[0]["can_bind"] is True
|
||||
|
||||
bound = _ref(ada, "matter", parent, bind_element_id=original["id"])
|
||||
assert bound["id"] == original["id"]
|
||||
assert [m["where"] for m in _ask(ada, "matter", parent)] == ["here"]
|
||||
refused = _ref(ada, "matter", parent, bind_element_id=original["id"], status=422)
|
||||
assert "bereits" in refused["detail"]
|
||||
|
||||
|
||||
def test_a_stranger_neither_sees_nor_binds_my_element(client, db, ada):
|
||||
mine = matter_of(ada, "Mein Vorgang")["id"]
|
||||
element = _ref(ada, "matter", mine)
|
||||
ben = _main(client, db, "ben")
|
||||
theirs = matter_of(ben, "Ihr Vorgang")["id"]
|
||||
_level(ben, "around")
|
||||
assert _ask(ben, "matter", theirs) == []
|
||||
_ref(ben, "matter", theirs)
|
||||
_ref(ben, "matter", theirs, bind_element_id=element["id"], status=404)
|
||||
@@ -0,0 +1,47 @@
|
||||
"""An entry title can be renamed without touching the document body."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import Actor, document, register
|
||||
|
||||
|
||||
def test_element_title_can_be_renamed(client, db):
|
||||
ada = Actor(client, "ada-titel@example.test", "Ada Titel")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Alter Titel",
|
||||
"document": document("Text"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
element = detail["bindings"][0]["element"]
|
||||
renamed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/elements/{element['id']}/title",
|
||||
json={
|
||||
"expected_version": element["version"],
|
||||
"title": "Neuer Titel",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
)
|
||||
assert renamed["title"] == "Neuer Titel"
|
||||
assert renamed["version"] == element["version"] + 1
|
||||
shown = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
assert shown["bindings"][0]["element"]["title"] == "Neuer Titel"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/elements/{element['id']}/title",
|
||||
json={
|
||||
"expected_version": renamed["version"],
|
||||
"title": " ",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=422,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,273 @@
|
||||
"""Bibliothek: Zähler nur aus Lesbarem, Rauminhalt, Raumübersicht und Teilen im Stapel."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from tests.support import PASSWORD, Actor, matter_of
|
||||
|
||||
|
||||
def _second_client():
|
||||
from app.main import app
|
||||
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _actor(client, db, key: str, *, main: bool = False) -> Actor:
|
||||
actor = Actor(client if main else _second_client(), f"{key}-bib@example.test", key.title())
|
||||
create_account(db, actor.email, actor.name, PASSWORD)
|
||||
db.commit()
|
||||
actor.login()
|
||||
return actor
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def world(client, db):
|
||||
ada = _actor(client, db, "ada", main=True)
|
||||
ben = _actor(client, db, "ben")
|
||||
cem = _actor(client, db, "cem")
|
||||
dan = _actor(client, db, "dan")
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Werkstatt", "default_visibility": "private"}, status=201)["id"]
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "member"})
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": cem.email, "role": "reader"})
|
||||
return {"ada": ada, "ben": ben, "cem": cem, "dan": dan, "room": room}
|
||||
|
||||
|
||||
def _share(actor, plural, resource_id, room, status=200):
|
||||
return actor.request("PUT", f"/api/v1/{plural}/{resource_id}/room-share/rooms/{room}", json={"access": "edit"}, status=status)
|
||||
|
||||
|
||||
def _link(actor, matter, case):
|
||||
actor.request("POST", f"/api/v1/matters/{matter}/case-links", json={"case_id": case}, status=201)
|
||||
|
||||
|
||||
def test_counts_include_only_what_the_person_may_read(world):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Vermietung"}, status=201)
|
||||
child = ada.request(
|
||||
"POST", "/api/v1/cases",
|
||||
json={"title": "Nebenkosten", "parent_case_id": case["id"], "rights_mode": "inherit_parent"}, status=201,
|
||||
)
|
||||
one = matter_of(ada, "Mietminderung")
|
||||
two = matter_of(ada, "Eigenbedarf intern")
|
||||
_link(ada, one["id"], case["id"])
|
||||
_link(ada, two["id"], case["id"])
|
||||
_share(ada, "cases", case["id"], room)
|
||||
|
||||
mine = next(i for i in ada.request("GET", "/api/v1/cases")["items"] if i["id"] == case["id"])
|
||||
assert (mine["child_cases"], mine["matter_count"]) == (1, 2)
|
||||
assert [s["name"] for s in mine["shared_with"]] == ["Werkstatt"]
|
||||
|
||||
# One matter is withheld from the room members in this case.
|
||||
ada.request(
|
||||
"PUT", "/api/v1/exceptions",
|
||||
json={"resource_kind": "matter", "resource_id": two["id"], "context": {"kind": "case", "id": case["id"]}, "remove_read": True},
|
||||
)
|
||||
seen = next(i for i in ben.request("GET", "/api/v1/cases")["items"] if i["id"] == case["id"])
|
||||
assert seen["matter_count"] == 1 and seen["shared_with"] == [] and seen["is_owner"] is False
|
||||
assert child["title"] == "Nebenkosten"
|
||||
|
||||
|
||||
def test_a_room_shows_its_contents_to_members_only(world):
|
||||
ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Im Raum"}, status=201)
|
||||
sub = ada.request(
|
||||
"POST", "/api/v1/cases",
|
||||
json={"title": "Unter der Akte", "parent_case_id": case["id"], "rights_mode": "inherit_parent"}, status=201,
|
||||
)
|
||||
ada.request("POST", "/api/v1/cases", json={"title": "Bleibt privat"}, status=201)
|
||||
matter = matter_of(ada, "Vorgang im Raum")
|
||||
_share(ada, "cases", case["id"], room)
|
||||
_share(ada, "matters", matter["id"], room)
|
||||
|
||||
for member in (ada, ben, cem):
|
||||
found = member.request("GET", f"/api/v1/rooms/{room}/contents")
|
||||
assert {c["title"] for c in found["cases"]} == {"Im Raum", "Unter der Akte"}
|
||||
assert [m["title"] for m in found["matters"]] == ["Vorgang im Raum"]
|
||||
dan.request("GET", f"/api/v1/rooms/{room}/contents", status=403)
|
||||
# A person who is excluded does not see the entry in the room either.
|
||||
ada.request("PUT", f"/api/v1/cases/{case['id']}/room-share/people/{_id(ada, ben)}", json={"excluded": True})
|
||||
titles = {c["title"] for c in ben.request("GET", f"/api/v1/rooms/{room}/contents")["cases"]}
|
||||
assert "Im Raum" not in titles
|
||||
assert sub["title"] == "Unter der Akte"
|
||||
|
||||
|
||||
def test_the_room_overview_names_members_only_to_managers(world):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Gezählt"}, status=201)
|
||||
_share(ada, "cases", case["id"], room)
|
||||
mine = next(r for r in ada.request("GET", "/api/v1/rooms/overview")["items"] if r["id"] == room)
|
||||
assert mine["is_owner"] is True and mine["role"] == "manager" and mine["member_count"] == 3
|
||||
assert mine["case_count"] == 1 and mine["matter_count"] == 0
|
||||
assert set(mine["members"]) == {"Ada", "Ben", "Cem"}
|
||||
theirs = next(r for r in ben.request("GET", "/api/v1/rooms/overview")["items"] if r["id"] == room)
|
||||
assert theirs["members"] == [] and theirs["member_count"] == 3 and theirs["is_owner"] is False
|
||||
assert world["dan"].request("GET", "/api/v1/rooms/overview")["items"] == []
|
||||
|
||||
|
||||
def test_several_entries_are_shared_at_once_or_not_at_all(world):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
a = ada.request("POST", "/api/v1/cases", json={"title": "Eins"}, status=201)
|
||||
b = ada.request("POST", "/api/v1/cases", json={"title": "Zwei"}, status=201)
|
||||
m = matter_of(ada, "Drei")
|
||||
done = ada.request(
|
||||
"POST", f"/api/v1/rooms/{room}/shares",
|
||||
json={"items": [{"kind": "case", "id": a["id"]}, {"kind": "case", "id": b["id"]}, {"kind": "matter", "id": m["id"]}], "access": "read"},
|
||||
)
|
||||
assert done["shared"] == 3
|
||||
assert {(e["display_name"], e["role"], e["rights"]["edit"]) for e in done["effect"]} == {("Ben", "member", False), ("Cem", "reader", False)}
|
||||
assert ben.request("GET", f"/api/v1/cases/{a['id']}")["rights"]["edit"] is False
|
||||
|
||||
foreign = ben.request("POST", "/api/v1/cases", json={"title": "Von Ben"}, status=201)
|
||||
c = ada.request("POST", "/api/v1/cases", json={"title": "Vier"}, status=201)
|
||||
ada.request(
|
||||
"POST", f"/api/v1/rooms/{room}/shares",
|
||||
json={"items": [{"kind": "case", "id": c["id"]}, {"kind": "case", "id": foreign["id"]}]}, status=404,
|
||||
)
|
||||
assert room not in [s["room_id"] for s in ada.request("GET", f"/api/v1/cases/{c['id']}/room-share")["shares"]]
|
||||
# An outsider cannot put his own entry into the room, and nobody shares an entry of someone else.
|
||||
own = world["dan"].request("POST", "/api/v1/cases", json={"title": "Von Dan"}, status=201)
|
||||
world["dan"].request("POST", f"/api/v1/rooms/{room}/shares", json={"items": [{"kind": "case", "id": own["id"]}]}, status=403)
|
||||
world["cem"].request("POST", f"/api/v1/rooms/{room}/shares", json={"items": [{"kind": "case", "id": c["id"]}]}, status=404)
|
||||
|
||||
|
||||
def test_creating_an_entry_can_put_it_into_a_room_and_reports_the_effect(world):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Gleich im Raum", "share_with_room_id": room}, status=201)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang im Raum", "share_with_room_id": room}, status=201)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
other = ada.request("POST", "/api/v1/cases", json={"title": "Ohne Raum"}, status=201)
|
||||
ben.request("GET", f"/api/v1/cases/{other['id']}", status=404)
|
||||
answer = _share(ada, "cases", other["id"], room)
|
||||
assert {e["display_name"] for e in answer["effect"]} == {"Ben", "Cem"}
|
||||
world["dan"].request("POST", "/api/v1/cases", json={"title": "Fremd", "share_with_room_id": room}, status=403)
|
||||
|
||||
|
||||
def _id(owner: Actor, person: Actor) -> str:
|
||||
from app.core.settings import get_settings
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(get_settings().dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
return str(conn.execute("SELECT id FROM auth_accounts WHERE email = %s", (person.email,)).fetchone()["id"])
|
||||
|
||||
|
||||
def test_the_outline_lists_only_what_the_person_may_read(world):
|
||||
ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Gliederung"}, status=201)
|
||||
ada.request("POST", f"/api/v1/cases/{case['id']}/chapters", json={"title": "Schriftverkehr"}, status=201)
|
||||
sub = ada.request(
|
||||
"POST", "/api/v1/cases",
|
||||
json={"title": "Unterakte", "parent_case_id": case["id"], "rights_mode": "inherit_parent"}, status=201,
|
||||
)
|
||||
open_matter = matter_of(ada, "Offener Vorgang")
|
||||
hidden_matter = matter_of(ada, "Verborgener Vorgang")
|
||||
child = ada.request("POST", "/api/v1/matters", json={"title": "Teilvorgang", "parent_matter_id": open_matter["id"]}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{open_matter['id']}/chapters", json={"title": "Belege"}, status=201)
|
||||
_link(ada, open_matter["id"], case["id"])
|
||||
_link(ada, hidden_matter["id"], case["id"])
|
||||
_share(ada, "cases", case["id"], room)
|
||||
ada.request(
|
||||
"PUT", "/api/v1/exceptions",
|
||||
json={"resource_kind": "matter", "resource_id": hidden_matter["id"], "context": {"kind": "case", "id": case["id"]}, "remove_read": True},
|
||||
)
|
||||
|
||||
mine = ada.request("GET", f"/api/v1/cases/{case['id']}/outline")
|
||||
assert [c["title"] for c in mine["chapters"]] == ["Schriftverkehr"]
|
||||
assert [c["title"] for c in mine["subcases"]] == ["Unterakte"]
|
||||
# An exception in the case context hides the matter there for everyone, the owner included.
|
||||
assert {m["title"] for m in mine["matters"]} == {"Offener Vorgang"}
|
||||
seen = ben.request("GET", f"/api/v1/cases/{case['id']}/outline")
|
||||
assert {m["title"] for m in seen["matters"]} == {"Offener Vorgang"}
|
||||
assert [c["title"] for c in seen["matters"][0]["children"]] == ["Teilvorgang"]
|
||||
assert sub["id"] in [c["id"] for c in seen["subcases"]]
|
||||
|
||||
matter = ada.request("GET", f"/api/v1/matters/{open_matter['id']}/outline")
|
||||
assert [c["title"] for c in matter["chapters"]] == ["Belege"]
|
||||
assert [c["title"] for c in matter["submatters"]] == ["Teilvorgang"]
|
||||
in_case = ben.request(
|
||||
"GET", f"/api/v1/matters/{open_matter['id']}/outline",
|
||||
params={"context_kind": "case", "context_id": case["id"]},
|
||||
)
|
||||
assert [c["title"] for c in in_case["submatters"]] == ["Teilvorgang"]
|
||||
ben.request("GET", f"/api/v1/matters/{open_matter['id']}/outline", status=404)
|
||||
assert child["title"] == "Teilvorgang"
|
||||
|
||||
unknown = "00000000-0000-4000-8000-000000000000"
|
||||
seen_status = dan.request("GET", f"/api/v1/cases/{case['id']}/outline", status=404)
|
||||
missing = dan.request("GET", f"/api/v1/cases/{unknown}/outline", status=404)
|
||||
assert seen_status["detail"] == missing["detail"]
|
||||
dan.request("GET", f"/api/v1/matters/{open_matter['id']}/outline", status=404)
|
||||
assert cem.request("GET", f"/api/v1/cases/{case['id']}/outline")["id"] == case["id"]
|
||||
|
||||
|
||||
def test_unlinking_keeps_the_matter_and_its_other_cases(world):
|
||||
ada, ben = world["ada"], world["ben"]
|
||||
first = ada.request("POST", "/api/v1/cases", json={"title": "Vermietung"}, status=201)["id"]
|
||||
second = ada.request("POST", "/api/v1/cases", json={"title": "Steuer"}, status=201)["id"]
|
||||
matter = matter_of(ada, "Nebenkosten")["id"]
|
||||
ada.request("POST", f"/api/v1/matters/{matter}/case-links", json={"case_id": first}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{matter}/case-links", json={"case_id": second}, status=201)
|
||||
links = ada.request("GET", f"/api/v1/matters/{matter}")["case_links"]
|
||||
assert {item["case_id"] for item in links} == {first, second}
|
||||
link = next(item for item in links if item["case_id"] == first)
|
||||
|
||||
# A stranger cannot detach it and learns nothing about it.
|
||||
ben.request("DELETE", f"/api/v1/matter-case-links/{link['id']}", status=404)
|
||||
|
||||
ada.request("DELETE", f"/api/v1/matter-case-links/{link['id']}", status=204)
|
||||
opened = ada.request("GET", f"/api/v1/matters/{matter}")
|
||||
assert [item["case_id"] for item in opened["case_links"]] == [second]
|
||||
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
|
||||
@@ -0,0 +1,81 @@
|
||||
"""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
|
||||
|
||||
|
||||
def test_remote_pictures_stay_out_unless_the_server_loads_them():
|
||||
source = '<img src="https://cdn.example/a.png" alt="a"><img src="http://plain.example/b.png"><p>Text</p>'
|
||||
found: list[str] = []
|
||||
assert "<img" not in sanitize_html(source, found=found)
|
||||
assert found == ["https://cdn.example/a.png"]
|
||||
loaded = sanitize_html(source, remote=lambda url: "data:image/png;base64,AAAA" if "cdn" in url else "")
|
||||
assert loaded.count("<img") == 1 and 'src="data:image/png;base64,AAAA"' in loaded
|
||||
|
||||
|
||||
def test_the_server_never_fetches_internal_or_odd_addresses():
|
||||
from app.remoteimages import RemoteImages, fetch_image, is_public
|
||||
|
||||
for address in ("127.0.0.1", "10.0.0.5", "192.168.1.1", "169.254.169.254", "::1", "fd00::1", "224.0.0.1", "not-an-ip"):
|
||||
assert is_public(address) is False
|
||||
assert is_public("93.184.216.34") is True
|
||||
for url in (
|
||||
"http://example.org/a.png",
|
||||
"https://127.0.0.1/a.png",
|
||||
"https://localhost/a.png",
|
||||
"https://[::1]/a.png",
|
||||
"https://example.org:8443/a.png",
|
||||
"https://user:pw@example.org/a.png",
|
||||
"file:///etc/passwd",
|
||||
"https:///a.png",
|
||||
):
|
||||
assert fetch_image(url) is None
|
||||
assert RemoteImages()("https://127.0.0.1/a.png") == ""
|
||||
|
||||
|
||||
def test_remote_pictures_are_checked_by_content_and_limited(monkeypatch):
|
||||
import app.remoteimages as module
|
||||
|
||||
png = b"\x89PNG\r\n\x1a\n" + b"0" * 20
|
||||
monkeypatch.setattr(module, "fetch_image", lambda url: png if url.endswith(".png") else None)
|
||||
loader = module.RemoteImages()
|
||||
assert loader("https://a.example/1.png").startswith("data:image/png;base64,")
|
||||
assert loader("https://a.example/1.png").startswith("data:image/png")
|
||||
assert loader("https://a.example/1.svg") == ""
|
||||
assert (loader.loaded, loader.failed) == (1, 1)
|
||||
assert module._kind(b"<svg xmlns='http://www.w3.org/2000/svg'></svg>") is None
|
||||
assert module._kind(b"RIFF\x00\x00\x00\x00WEBPVP8 ") == "webp"
|
||||
@@ -0,0 +1,479 @@
|
||||
"""IMAP folders are browsed; search stays inside the open folder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import app.sources as sources
|
||||
from tests.support import Actor, matter_of, register
|
||||
|
||||
|
||||
class FakeIMAP:
|
||||
selects: list[str] = []
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def login(self, username, secret):
|
||||
assert secret == "Postfach-Geheim"
|
||||
return "OK", [b"logged"]
|
||||
|
||||
def list(self):
|
||||
return "OK", [
|
||||
b'(\\HasNoChildren) "/" "INBOX"',
|
||||
b'(\\HasNoChildren) "/" "&AMQ-nderungen"',
|
||||
b'(\\Noselect \\HasChildren) "/" "[Gmail]"',
|
||||
b'(\\HasNoChildren) "/" "[Gmail]/Gesendet"',
|
||||
]
|
||||
|
||||
def select(self, mailbox, readonly=False):
|
||||
assert readonly is True
|
||||
FakeIMAP.selects.append(mailbox)
|
||||
return "OK", [b"5"]
|
||||
|
||||
def uid(self, command, *args):
|
||||
if command == "SEARCH":
|
||||
if any(isinstance(arg, str) and "Einwendung" in arg for arg in args):
|
||||
return "OK", [b"2"]
|
||||
return "OK", [b"1 2 3 4 5"]
|
||||
uid = int(args[0])
|
||||
spec = " ".join(str(part) for part in args[1:])
|
||||
if "BODY.PEEK[]" in spec:
|
||||
raw = (
|
||||
f"From: Ada Beispiel <ada@example.test>\r\n"
|
||||
f"To: Gegenseite <gegen@example.test>\r\n"
|
||||
f"Subject: Nachricht {uid}\r\n"
|
||||
f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
f"Message-ID: <{uid}@example.test>\r\n"
|
||||
f"MIME-Version: 1.0\r\n"
|
||||
f'Content-Type: multipart/mixed; boundary="grenze"\r\n'
|
||||
f"\r\n"
|
||||
f"--grenze\r\n"
|
||||
f"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
f"\r\n"
|
||||
f"Bitte die Einwendung pruefen.\r\n"
|
||||
f"--grenze\r\n"
|
||||
f"Content-Type: application/pdf\r\n"
|
||||
f"Content-Disposition: attachment; filename=\"einwendung.pdf\"\r\n"
|
||||
f"\r\n"
|
||||
f"%PDF\r\n"
|
||||
f"--grenze--\r\n"
|
||||
).encode()
|
||||
return "OK", [(b"rfc822", raw)]
|
||||
if "BODYSTRUCTURE" in spec:
|
||||
structure = b'("ATTACHMENT" ("FILENAME" "einwendung.pdf"))'
|
||||
return "OK", [structure]
|
||||
header = (
|
||||
f"From: Ada Beispiel <ada@example.test>\r\n"
|
||||
f"To: Gegenseite <gegen@example.test>\r\n"
|
||||
f"Subject: Nachricht {uid}\r\n"
|
||||
f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
f"Message-ID: <{uid}@example.test>\r\n"
|
||||
).encode()
|
||||
return "OK", [(b"body", header), b")"]
|
||||
|
||||
def logout(self):
|
||||
return "BYE", [b""]
|
||||
|
||||
|
||||
def _account(monkeypatch, actor: Actor) -> str:
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", FakeIMAP)
|
||||
created = actor.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": "Kanzlei",
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": "ada@example.test",
|
||||
"password": "Postfach-Geheim",
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
return created["id"]
|
||||
|
||||
|
||||
def test_mailboxes_are_named_and_inbox_comes_first(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-mail@example.test", "Ada Post")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
account = _account(monkeypatch, ada)
|
||||
listed = ada.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": account})
|
||||
assert [item["label"] for item in listed["items"]] == ["Posteingang", "[Gmail]", "[Gmail]/Gesendet", "Änderungen"]
|
||||
gmail = next(item for item in listed["items"] if item["name"] == "[Gmail]")
|
||||
sent = next(item for item in listed["items"] if item["name"] == "[Gmail]/Gesendet")
|
||||
assert gmail["selectable"] is False
|
||||
assert sent["selectable"] is True
|
||||
assert sent["depth"] == 1
|
||||
|
||||
|
||||
def test_folder_pages_newest_first_and_search_stays_inside(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-page@example.test", "Ada Seite")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
account = _account(monkeypatch, ada)
|
||||
monkeypatch.setattr(sources, "PAGE_SIZE", 2)
|
||||
FakeIMAP.selects = []
|
||||
first = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/messages",
|
||||
params={"connector_id": account, "mailbox": "[Gmail]/Gesendet"},
|
||||
)
|
||||
assert first["mailbox"] == "[Gmail]/Gesendet"
|
||||
assert [item["title"] for item in first["items"]] == ["Nachricht 5", "Nachricht 4"]
|
||||
assert first["items"][0]["document_on"] == "2024-05-02"
|
||||
assert first["items"][0]["message_from"] == "Ada Beispiel <ada@example.test>"
|
||||
assert first["items"][0]["message_to"] == "Gegenseite <gegen@example.test>"
|
||||
assert first["items"][0]["direction"] == "out"
|
||||
assert first["items"][0]["attachments"] == [{"filename": "einwendung.pdf"}]
|
||||
assert first["next_before"] == 4
|
||||
older = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/messages",
|
||||
params={"connector_id": account, "mailbox": "[Gmail]/Gesendet", "before": first["next_before"]},
|
||||
)
|
||||
assert [item["title"] for item in older["items"]] == ["Nachricht 3", "Nachricht 2"]
|
||||
found = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/messages",
|
||||
params={"connector_id": account, "mailbox": "INBOX", "q": "Einwendung"},
|
||||
)
|
||||
assert [item["title"] for item in found["items"]] == ["Nachricht 2"]
|
||||
assert found["items"][0]["direction"] == "in"
|
||||
assert found["next_before"] is None
|
||||
preview = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/message",
|
||||
params={"connector_id": account, "mailbox": "INBOX", "uid": 2},
|
||||
)
|
||||
assert preview["direction"] == "in"
|
||||
assert preview["message_to"] == "Gegenseite <gegen@example.test>"
|
||||
assert "Einwendung" in preview["text"]
|
||||
other = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/messages",
|
||||
params={"connector_id": account, "mailbox": "&AMQ-nderungen"},
|
||||
)
|
||||
assert other["items"][0]["direction"] is None
|
||||
assert preview["attachments"][0]["filename"] == "einwendung.pdf"
|
||||
ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/messages",
|
||||
params={"connector_id": account, "mailbox": "Geheim"},
|
||||
status=422,
|
||||
)
|
||||
assert "Geheim" not in FakeIMAP.selects
|
||||
|
||||
|
||||
def test_foreign_mailbox_stays_hidden(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-own@example.test", "Ada Eigen")
|
||||
ben = Actor(client, "ben-own@example.test", "Ben Fremd")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
account = _account(monkeypatch, ada)
|
||||
ben.login()
|
||||
ben.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": account}, status=404)
|
||||
ben.request("GET", "/api/v1/sources/imap/messages", params={"connector_id": account}, status=404)
|
||||
|
||||
|
||||
class HugeIMAP(FakeIMAP):
|
||||
def uid(self, command, *args):
|
||||
spec = " ".join(str(part) for part in args[1:]) if len(args) > 1 else ""
|
||||
if command == "FETCH" and "BODY.PEEK[]" in spec and "<" not in spec:
|
||||
return "OK", [(b"rfc822", b"x" * 8_000_001)]
|
||||
if "BODYSTRUCTURE" in spec:
|
||||
structure = b'("TEXT" "PLAIN" ("CHARSET" "utf-8") NIL NIL "7BIT" 40 1 NIL NIL NIL NIL)'
|
||||
return "OK", [(b"body", structure)]
|
||||
if "BODY.PEEK[1]" in spec:
|
||||
return "OK", [(b"text", "Kurzer Auszug der grossen Nachricht.".encode())]
|
||||
return super().uid(command, *args)
|
||||
|
||||
|
||||
def test_oversized_message_still_returns_text(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-huge@example.test", "Ada Gross")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", HugeIMAP)
|
||||
account = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": "Gross",
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": "ada@example.test",
|
||||
"password": "Postfach-Geheim",
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)["id"]
|
||||
preview = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/imap/message",
|
||||
params={"connector_id": account, "mailbox": "INBOX", "uid": 2},
|
||||
)
|
||||
assert "Kurzer Auszug" in preview["text"]
|
||||
assert preview["text_truncated"] is True
|
||||
assert preview["direction"] == "in"
|
||||
assert preview["message_from"]
|
||||
|
||||
|
||||
def _raw(actor: Actor, path: str):
|
||||
return actor.client.get(
|
||||
path,
|
||||
headers={
|
||||
"Origin": "http://testserver",
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_an_adopted_message_loads_in_full_with_its_attachment(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-voll@example.test", "Ada Voll")
|
||||
ben = Actor(client, "ben-voll@example.test", "Ben Voll")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
account = _account(monkeypatch, ada)
|
||||
matter = matter_of(ada, "Nebenkosten")
|
||||
created = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Nachricht 2",
|
||||
"source": "imap",
|
||||
"external_id": "<2@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": account, "mailbox": "INBOX", "uid": 2, "direction": "in"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
letter = ada.request("GET", f"/api/v1/external-refs/{created['id']}/mail")
|
||||
assert letter["complete"] is True
|
||||
assert letter["text_truncated"] is False
|
||||
assert "Einwendung" in letter["text"]
|
||||
assert letter["attachments"][0]["filename"] == "einwendung.pdf"
|
||||
assert letter["attachments"][0]["content_type"] == "application/pdf"
|
||||
assert letter["attachments"][0]["byte_size"] >= 4
|
||||
original = _raw(ada, f"/api/v1/external-refs/{created['id']}/mail/original")
|
||||
assert original.status_code == 200
|
||||
assert b"Message-ID: <2@example.test>" in original.content
|
||||
assert b"%PDF" in original.content
|
||||
attachment = _raw(ada, f"/api/v1/external-refs/{created['id']}/mail/attachments/0")
|
||||
assert attachment.status_code == 200
|
||||
assert attachment.content.startswith(b"%PDF")
|
||||
assert attachment.headers["content-type"].startswith("application/pdf")
|
||||
assert attachment.headers["content-disposition"].startswith("inline;")
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Fremde Nachricht",
|
||||
"source": "imap",
|
||||
"external_id": "<andere@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": account, "mailbox": "INBOX", "uid": 2},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
shown = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
wrong = next(item for item in shown["bindings"] if item["element"]["title"] == "Fremde Nachricht")
|
||||
ada.request("GET", f"/api/v1/external-refs/{wrong['element']['id']}/mail", status=422)
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/external-refs/{created['id']}/mail", status=404)
|
||||
|
||||
|
||||
def _letter(message_id: str, body: str) -> bytes:
|
||||
return (
|
||||
f"From: Ada Beispiel <ada@example.test>\r\n"
|
||||
f"To: Gegenseite <gegen@example.test>\r\n"
|
||||
f"Subject: Verschoben\r\n"
|
||||
f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
f"Message-ID: {message_id}\r\n"
|
||||
f"MIME-Version: 1.0\r\n"
|
||||
f"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
f"\r\n"
|
||||
f"{body}\r\n"
|
||||
).encode()
|
||||
|
||||
|
||||
class RelocatingIMAP:
|
||||
"""The saved UID holds another message. The Message-ID lives in Archiv."""
|
||||
|
||||
log: list[tuple] = []
|
||||
copies: dict[tuple[str, int], bytes] = {}
|
||||
header_uids: dict[str, bytes] | None = None
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.selected = ""
|
||||
|
||||
def login(self, username, secret):
|
||||
assert secret == "Postfach-Geheim"
|
||||
return "OK", [b"logged"]
|
||||
|
||||
def list(self):
|
||||
return "OK", [
|
||||
b'(\\HasNoChildren) "/" "INBOX"',
|
||||
b'(\\HasNoChildren) "/" "Archiv"',
|
||||
]
|
||||
|
||||
def select(self, mailbox, readonly=False):
|
||||
assert readonly is True
|
||||
self.selected = mailbox
|
||||
RelocatingIMAP.log.append(("select", mailbox))
|
||||
return "OK", [b"2"]
|
||||
|
||||
def uid(self, command, *args):
|
||||
if command == "SEARCH":
|
||||
if args and args[0] == "HEADER":
|
||||
RelocatingIMAP.log.append(("header", self.selected))
|
||||
override = (RelocatingIMAP.header_uids or {}).get(self.selected)
|
||||
if override is not None:
|
||||
return "OK", [override]
|
||||
found = [
|
||||
str(uid)
|
||||
for (folder, uid), raw in RelocatingIMAP.copies.items()
|
||||
if folder == self.selected and b"Message-ID: <moved@example.test>" in raw
|
||||
]
|
||||
return "OK", [" ".join(found).encode()]
|
||||
return "OK", [b""]
|
||||
uid = int(args[0])
|
||||
spec = " ".join(str(part) for part in args[1:])
|
||||
if "BODY.PEEK[]" in spec:
|
||||
RelocatingIMAP.log.append(("fetch", self.selected, uid))
|
||||
raw = RelocatingIMAP.copies.get((self.selected, uid))
|
||||
if raw is None:
|
||||
return "OK", [None]
|
||||
return "OK", [(b"rfc822", raw)]
|
||||
return "OK", [None]
|
||||
|
||||
def logout(self):
|
||||
return "BYE", [b""]
|
||||
|
||||
|
||||
def _stored_mail(db, element_id: str) -> dict:
|
||||
row = db.execute(
|
||||
"SELECT detail FROM external_references WHERE element_id = %s",
|
||||
(element_id,),
|
||||
).fetchone()
|
||||
return dict(row["detail"])
|
||||
|
||||
|
||||
def _linked_mail(actor: Actor, account: str, matter_id: str) -> dict:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Verschoben",
|
||||
"source": "imap",
|
||||
"external_id": "<moved@example.test>",
|
||||
"context": {"kind": "matter", "id": matter_id},
|
||||
"detail": {
|
||||
"connector_id": account,
|
||||
"mailbox": "INBOX",
|
||||
"uid": 2,
|
||||
"direction": "in",
|
||||
},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
|
||||
|
||||
def test_a_moved_message_remembers_its_new_folder(client, db, monkeypatch):
|
||||
from uuid import UUID
|
||||
|
||||
from app.retrieval import MailPayload, load_external
|
||||
|
||||
ada = Actor(client, "ada-move@example.test", "Ada Umzug")
|
||||
account_row = register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
RelocatingIMAP.log = []
|
||||
RelocatingIMAP.header_uids = None
|
||||
RelocatingIMAP.copies = {
|
||||
("INBOX", 2): _letter("<other@example.test>", "Eine andere Nachricht."),
|
||||
("Archiv", 9): _letter("<moved@example.test>", "Der Brief liegt jetzt im Archiv."),
|
||||
}
|
||||
account = _account(monkeypatch, ada)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RelocatingIMAP)
|
||||
matter = matter_of(ada, "Ablage")
|
||||
created = _linked_mail(ada, account, matter["id"])
|
||||
|
||||
opened = ada.request("GET", f"/api/v1/external-refs/{created['id']}/mail")
|
||||
assert "Archiv" in opened["text"]
|
||||
stored = _stored_mail(db, created["id"])
|
||||
assert stored["mailbox"] == "Archiv"
|
||||
assert stored["uid"] == 9
|
||||
assert stored["direction"] == "in"
|
||||
assert stored["connector_id"] == account
|
||||
assert any(item[0] == "header" for item in RelocatingIMAP.log)
|
||||
|
||||
RelocatingIMAP.log = []
|
||||
again = ada.request("GET", f"/api/v1/external-refs/{created['id']}/mail")
|
||||
assert again["text"] == opened["text"]
|
||||
assert ("fetch", "Archiv", 9) in RelocatingIMAP.log
|
||||
assert not any(item[0] == "header" for item in RelocatingIMAP.log)
|
||||
assert _stored_mail(db, created["id"])["uid"] == 9
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE external_references
|
||||
SET detail = jsonb_set(
|
||||
jsonb_set(detail, '{mailbox}', to_jsonb('INBOX'::text)),
|
||||
'{uid}',
|
||||
to_jsonb(2)
|
||||
)
|
||||
WHERE element_id = %s
|
||||
""",
|
||||
(created["id"],),
|
||||
)
|
||||
db.commit()
|
||||
RelocatingIMAP.log = []
|
||||
loaded = load_external(db, account_row["id"], UUID(created["id"]), None)
|
||||
assert isinstance(loaded, MailPayload)
|
||||
assert "Archiv" in loaded.parsed.text
|
||||
exported = _stored_mail(db, created["id"])
|
||||
assert exported["mailbox"] == "Archiv"
|
||||
assert exported["uid"] == 9
|
||||
assert exported["direction"] == "in"
|
||||
assert any(item[0] == "header" for item in RelocatingIMAP.log)
|
||||
|
||||
|
||||
def test_an_ambiguous_or_truncated_move_does_not_replace_the_stored_place(client, db, monkeypatch):
|
||||
ada = Actor(client, "ada-ambiguous@example.test", "Ada Zweifach")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
RelocatingIMAP.header_uids = None
|
||||
RelocatingIMAP.copies = {
|
||||
("INBOX", 2): _letter("<other@example.test>", "Altbestand."),
|
||||
("INBOX", 4): _letter("<moved@example.test>", "Erste Kopie."),
|
||||
("Archiv", 9): _letter("<moved@example.test>", "Zweite Kopie."),
|
||||
}
|
||||
account = _account(monkeypatch, ada)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RelocatingIMAP)
|
||||
matter = matter_of(ada, "Zweifach")
|
||||
created = _linked_mail(ada, account, matter["id"])
|
||||
ada.request("GET", f"/api/v1/external-refs/{created['id']}/mail", status=422)
|
||||
assert _stored_mail(db, created["id"])["mailbox"] == "INBOX"
|
||||
assert _stored_mail(db, created["id"])["uid"] == 2
|
||||
|
||||
RelocatingIMAP.copies = {
|
||||
("INBOX", 2): _letter("<other@example.test>", "Altbestand."),
|
||||
("INBOX", 11): _letter("<moved@example.test>", "Treffer in der abgebrochenen Suche."),
|
||||
("INBOX", 12): _letter("<a@example.test>", "a"),
|
||||
("INBOX", 13): _letter("<b@example.test>", "b"),
|
||||
("INBOX", 14): _letter("<c@example.test>", "c"),
|
||||
("INBOX", 15): _letter("<d@example.test>", "d"),
|
||||
("INBOX", 16): _letter("<e@example.test>", "e"),
|
||||
("Archiv", 9): _letter("<moved@example.test>", "Eigentlich auch hier."),
|
||||
}
|
||||
RelocatingIMAP.header_uids = {"INBOX": b"11 12 13 14 15 16"}
|
||||
RelocatingIMAP.log = []
|
||||
opened = ada.request("GET", f"/api/v1/external-refs/{created['id']}/mail")
|
||||
assert "abgebrochenen Suche" in opened["text"]
|
||||
assert not any(item == ("header", "Archiv") for item in RelocatingIMAP.log)
|
||||
assert _stored_mail(db, created["id"])["mailbox"] == "INBOX"
|
||||
assert _stored_mail(db, created["id"])["uid"] == 2
|
||||
@@ -0,0 +1,615 @@
|
||||
"""Persistent content order, fachliche dates and context limits."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import Actor, binding_for, case_of, document, grant, matter_of, register
|
||||
|
||||
|
||||
def _note(actor: Actor, title: str, container: dict, *, kind: str = "matter", document_on: str | None = None) -> None:
|
||||
body = {
|
||||
"title": title,
|
||||
"document": document(title),
|
||||
"context": {"kind": kind, "id": container["id"]},
|
||||
}
|
||||
if document_on:
|
||||
body["dates"] = {"document_on": document_on}
|
||||
actor.request("POST", "/api/v1/notes", json=body, status=201)
|
||||
|
||||
|
||||
def _matter(actor: Actor, matter_id: str) -> dict:
|
||||
return actor.request("GET", f"/api/v1/matters/{matter_id}")
|
||||
|
||||
|
||||
def _titles(detail: dict) -> list[str]:
|
||||
return [item["element"]["title"] for item in detail["bindings"]]
|
||||
|
||||
|
||||
def test_date_order_keeps_undated_last_and_ignores_recorded_time(client, db):
|
||||
ada = Actor(client, "ada-order@example.test", "Ada Ordnung")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Fristenmappe")
|
||||
dates = ["2024-05-02", "2020-01-01", "2024-05-02", "2022-07-07", "2023-03-03", "2021-02-02"]
|
||||
for index, day in enumerate(dates):
|
||||
_note(ada, f"D{index}-{day}", matter, document_on=day)
|
||||
_note(ada, "Ohne-A", matter)
|
||||
_note(ada, "Ohne-B", matter)
|
||||
detail = _matter(ada, matter["id"])
|
||||
titles = _titles(detail)
|
||||
assert titles[:6] == ["D1-2020-01-01", "D5-2021-02-02", "D3-2022-07-07", "D4-2023-03-03", "D0-2024-05-02", "D2-2024-05-02"]
|
||||
assert titles[6:] == ["Ohne-A", "Ohne-B"]
|
||||
assert all(item["element"]["dates"]["document_on"] is None for item in detail["bindings"] if item["element"]["title"].startswith("Ohne"))
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": detail["version"], "mode": "date", "direction": "desc"},
|
||||
)
|
||||
descending = _titles(_matter(ada, matter["id"]))
|
||||
assert descending[:6] == ["D0-2024-05-02", "D2-2024-05-02", "D4-2023-03-03", "D3-2022-07-07", "D5-2021-02-02", "D1-2020-01-01"]
|
||||
assert descending[6:] == ["Ohne-A", "Ohne-B"]
|
||||
|
||||
|
||||
def test_custom_order_survives_reload_login_and_date_mode(client, db):
|
||||
ada = Actor(client, "ada-seq@example.test", "Ada Folge")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Reihenfolge")
|
||||
for title, day in (("Alpha", "2020-01-01"), ("Beta", "2021-01-01"), ("Gamma", "2022-01-01")):
|
||||
_note(ada, title, matter, document_on=day)
|
||||
detail = _matter(ada, matter["id"])
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": detail["version"], "mode": "position", "direction": "asc"},
|
||||
)
|
||||
detail = _matter(ada, matter["id"])
|
||||
ids = [binding_for(detail, name)["id"] for name in ("Gamma", "Alpha", "Beta")]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/order",
|
||||
json={"expected_version": detail["version"], "binding_ids": ids},
|
||||
)
|
||||
ada.login()
|
||||
restored = _matter(ada, matter["id"])
|
||||
assert _titles(restored) == ["Gamma", "Alpha", "Beta"]
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": restored["version"], "mode": "date", "direction": "asc"},
|
||||
)
|
||||
dated = _matter(ada, matter["id"])
|
||||
assert _titles(dated) == ["Alpha", "Beta", "Gamma"]
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": dated["version"], "mode": "position", "direction": "asc"},
|
||||
)
|
||||
assert _titles(_matter(ada, matter["id"])) == ["Gamma", "Alpha", "Beta"]
|
||||
_note(ada, "Delta", matter)
|
||||
assert _titles(_matter(ada, matter["id"]))[-1] == "Delta"
|
||||
|
||||
|
||||
def test_same_element_has_independent_positions(client, db):
|
||||
ada = Actor(client, "ada-two@example.test", "Ada Zwei")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
left = case_of(ada, "Akte A")
|
||||
right = case_of(ada, "Akte B")
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Gemeinsam", "document": document("Wort"), "context": {"kind": "case", "id": left["id"]}},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Nur A", "document": document("A"), "context": {"kind": "case", "id": left["id"]}},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Nur B", "document": document("B"), "context": {"kind": "case", "id": right["id"]}},
|
||||
status=201,
|
||||
)
|
||||
shared = binding_for(ada.request("GET", f"/api/v1/cases/{left['id']}"), "Gemeinsam")
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={
|
||||
"element_id": shared["element"]["id"],
|
||||
"source_context": {"kind": "case", "id": left["id"]},
|
||||
"target": {"kind": "case", "id": right["id"]},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
for case in (left, right):
|
||||
detail = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/cases/{case['id']}/content-order",
|
||||
json={"expected_version": detail["version"], "mode": "position", "direction": "asc"},
|
||||
)
|
||||
left_detail = ada.request("GET", f"/api/v1/cases/{left['id']}")
|
||||
right_detail = ada.request("GET", f"/api/v1/cases/{right['id']}")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{left['id']}/bindings/order",
|
||||
json={
|
||||
"expected_version": left_detail["version"],
|
||||
"binding_ids": [binding_for(left_detail, "Gemeinsam")["id"], binding_for(left_detail, "Nur A")["id"]],
|
||||
},
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{right['id']}/bindings/order",
|
||||
json={
|
||||
"expected_version": right_detail["version"],
|
||||
"binding_ids": [binding_for(right_detail, "Nur B")["id"], binding_for(right_detail, "Gemeinsam")["id"]],
|
||||
},
|
||||
)
|
||||
assert _titles(ada.request("GET", f"/api/v1/cases/{left['id']}")) == ["Gemeinsam", "Nur A"]
|
||||
assert _titles(ada.request("GET", f"/api/v1/cases/{right['id']}")) == ["Nur B", "Gemeinsam"]
|
||||
left_note = binding_for(ada.request("GET", f"/api/v1/cases/{left['id']}"), "Gemeinsam")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/bindings/{left_note['id']}/annotations",
|
||||
json={"body": "Nur in A"},
|
||||
status=201,
|
||||
)
|
||||
right_note = binding_for(ada.request("GET", f"/api/v1/cases/{right['id']}"), "Gemeinsam")
|
||||
assert right_note["annotations"] == []
|
||||
assert left_note["element"]["id"] == right_note["element"]["id"]
|
||||
|
||||
|
||||
def test_chapters_and_contained_matters_stay_distinct(client, db):
|
||||
ada = Actor(client, "ada-chap@example.test", "Ada Kapitel")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
case = case_of(ada, "Sammelakte")
|
||||
matter = matter_of(ada, "Enthaltener Vorgang")
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
chapter = ada.request("POST", f"/api/v1/cases/{case['id']}/chapters", json={"title": "Belege"}, status=201)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Im Kapitel",
|
||||
"document": document("kapitel"),
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
"chapter_id": chapter["id"],
|
||||
"dates": {"document_on": "2021-01-01"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Ohne Kapitel", "document": document("lose"), "context": {"kind": "case", "id": case["id"]}},
|
||||
status=201,
|
||||
)
|
||||
_note(ada, "Im Vorgang", matter, document_on="2019-01-01")
|
||||
detail = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/cases/{case['id']}/content-order",
|
||||
json={"expected_version": detail["version"], "mode": "date", "direction": "desc"},
|
||||
)
|
||||
detail = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
direct = {item["element"]["title"]: item["chapter_id"] for item in detail["bindings"]}
|
||||
assert direct["Im Kapitel"] == chapter["id"]
|
||||
assert direct["Ohne Kapitel"] is None
|
||||
assert [item["element"]["title"] for item in detail["bindings"]] == ["Im Kapitel", "Ohne Kapitel"]
|
||||
assert detail["contained"][0]["title"] == "Enthaltener Vorgang"
|
||||
assert detail["contained"][0]["bindings"][0]["element"]["title"] == "Im Vorgang"
|
||||
assert "Im Vorgang" not in direct
|
||||
|
||||
|
||||
def test_course_is_not_a_copy_of_the_audit_log(client, db):
|
||||
ada = Actor(client, "ada-course@example.test", "Ada Verlauf")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Verlauf")
|
||||
created = ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Schreiben",
|
||||
"document": document("Text"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"dates": {"document_on": "2024-04-04"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/elements/{created['id']}/dates",
|
||||
json={"expected_version": created["version"], "document_on": "2024-04-05", "context": {"kind": "matter", "id": matter["id"]}},
|
||||
)
|
||||
course = ada.request("GET", f"/api/v1/matters/{matter['id']}/course")
|
||||
audit = ada.request("GET", f"/api/v1/matters/{matter['id']}/chronology")
|
||||
assert [item["title"] for item in course["items"]] == ["Schreiben"]
|
||||
assert course["items"][0]["document_on"] == "2024-04-05"
|
||||
assert "recorded_at" not in course["items"][0]
|
||||
assert len(audit["items"]) > len(course["items"])
|
||||
|
||||
|
||||
def test_reorder_rejects_readers_foreign_ids_and_conflicts(client, db):
|
||||
ada = Actor(client, "ada-guard@example.test", "Ada Schutz")
|
||||
ben = Actor(client, "ben-guard@example.test", "Ben Schutz")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Geschützt")
|
||||
hidden_case = case_of(ada, "Verborgene Akte")
|
||||
for title in ("Sichtbar", "Verborgen"):
|
||||
_note(ada, title, matter)
|
||||
detail = _matter(ada, matter["id"])
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": detail["version"], "mode": "position", "direction": "asc"},
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False},
|
||||
status=201,
|
||||
)
|
||||
ben.login()
|
||||
ben_view = _matter(ben, matter["id"])
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/order",
|
||||
json={"expected_version": ben_view["version"], "binding_ids": [item["id"] for item in ben_view["bindings"]]},
|
||||
status=403,
|
||||
)
|
||||
ben.request("GET", f"/api/v1/cases/{hidden_case['id']}", status=404)
|
||||
ada.login()
|
||||
ada_view = _matter(ada, matter["id"])
|
||||
visible_id = binding_for(ada_view, "Sichtbar")["id"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/order",
|
||||
json={"expected_version": ada_view["version"], "binding_ids": [visible_id]},
|
||||
status=422,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={"title": "Fremd", "document": document("x"), "context": {"kind": "case", "id": hidden_case["id"]}},
|
||||
status=201,
|
||||
)
|
||||
foreign = binding_for(ada.request("GET", f"/api/v1/cases/{hidden_case['id']}"), "Fremd")
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/order",
|
||||
json={"expected_version": ada_view["version"], "binding_ids": [foreign["id"], visible_id]},
|
||||
status=404,
|
||||
)
|
||||
hidden = binding_for(ada_view, "Verborgen")
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": hidden["element"]["id"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
masked = _matter(ada, matter["id"])
|
||||
assert _titles(masked) == ["Sichtbar"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/order",
|
||||
json={"expected_version": masked["version"], "binding_ids": [binding_for(masked, "Sichtbar")["id"]]},
|
||||
)
|
||||
conflict = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/bindings/order",
|
||||
json={"expected_version": masked["version"], "binding_ids": [binding_for(masked, "Sichtbar")["id"]]},
|
||||
status=409,
|
||||
)
|
||||
assert conflict["detail"] == "Der Stand hat sich geändert. Bitte neu laden."
|
||||
kept = db.execute("SELECT id FROM bindings WHERE id = %s", (hidden["id"],)).fetchone()
|
||||
assert kept is not None
|
||||
ben.login()
|
||||
assert "Verborgen" not in str(_matter(ben, matter["id"]))
|
||||
|
||||
|
||||
def test_existing_position_mode_is_not_rewritten(client, db):
|
||||
ada = Actor(client, "ada-keep@example.test", "Ada Bestand")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
room = ada.scope["id"]
|
||||
row = db.execute(
|
||||
"""
|
||||
INSERT INTO cases (home_scope_id, owner_subject_id, created_by, title, rights_mode)
|
||||
VALUES (%s, (SELECT id FROM auth_accounts WHERE email = %s), (SELECT id FROM auth_accounts WHERE email = %s), 'Altakte', 'explicit')
|
||||
RETURNING id
|
||||
""",
|
||||
(room, ada.email, ada.email),
|
||||
).fetchone()
|
||||
db.commit()
|
||||
detail = ada.request("GET", f"/api/v1/cases/{row['id']}")
|
||||
assert detail["content_order"] == "position"
|
||||
assert detail["content_order_dir"] == "asc"
|
||||
|
||||
|
||||
def test_direct_matter_trail_invents_no_case(client, db):
|
||||
ada = Actor(client, "ada-trail@example.test", "Ada Pfad")
|
||||
ben = Actor(client, "ben-trail@example.test", "Ben Pfad")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
parent = case_of(ada, "Vermietung")
|
||||
child = ada.request(
|
||||
"POST",
|
||||
"/api/v1/cases",
|
||||
json={"title": "Wohnung", "parent_case_id": parent["id"], "rights_mode": "explicit"},
|
||||
status=201,
|
||||
)
|
||||
matter = matter_of(ada, "Nebenkosten")
|
||||
other = case_of(ada, "Geheim")
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": child["id"]}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": other["id"]}, status=201)
|
||||
grant(ada, child["id"], ben.email)
|
||||
ben.login()
|
||||
opened = ben.request("GET", f"/api/v1/matters/{matter['id']}?context_kind=case&context_id={child['id']}")
|
||||
labels = [item["label"] for item in opened["trail"]]
|
||||
assert labels == ["Akten", "Unterakte Wohnung", "Vorgang Nebenkosten"]
|
||||
assert opened["trail"][-1]["href"] is None
|
||||
assert opened["context"]["id"] == child["id"]
|
||||
assert [item["label"] for item in opened["placements"]] == ["Unterakte Wohnung"]
|
||||
assert opened["placements"][0]["current"] is True
|
||||
assert all(item["title"] != "Geheim" for item in opened["case_links"])
|
||||
ada.login()
|
||||
direct = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
assert [item["label"] for item in direct["trail"]] == ["Vorgänge", "Vorgang Nebenkosten"]
|
||||
assert "Geheim" not in " ".join(item["label"] for item in opened["placements"])
|
||||
assert any(item["label"] == "Akte Geheim" for item in direct["placements"])
|
||||
|
||||
|
||||
def test_teilvorgang_keeps_its_parent_in_the_trail(client, db):
|
||||
ada = Actor(client, "ada-child@example.test", "Ada Kind")
|
||||
register(db, ada.email, ada.name)
|
||||
ada.login()
|
||||
parent = matter_of(ada, "Hauptvorgang")
|
||||
child = ada.request(
|
||||
"POST",
|
||||
"/api/v1/matters",
|
||||
json={"title": "Prüfung", "parent_matter_id": parent["id"]},
|
||||
status=201,
|
||||
)
|
||||
direct = ada.request("GET", f"/api/v1/matters/{child['id']}")
|
||||
assert [item["label"] for item in direct["trail"]] == ["Vorgänge", "Vorgang Hauptvorgang", "Teilvorgang Prüfung"]
|
||||
case = case_of(ada, "Sammelakte")
|
||||
ada.request("POST", f"/api/v1/matters/{parent['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
opened = ada.request("GET", f"/api/v1/matters/{child['id']}?context_kind=case&context_id={case['id']}")
|
||||
assert [item["label"] for item in opened["trail"]] == [
|
||||
"Akten",
|
||||
"Akte Sammelakte",
|
||||
"Vorgang Hauptvorgang",
|
||||
"Teilvorgang Prüfung",
|
||||
]
|
||||
assert opened["trail"][2]["href"].endswith(f"context_id={case['id']}")
|
||||
placed = ada.request("GET", f"/api/v1/matters/{child['id']}")
|
||||
assert [item["label"] for item in placed["trail"]] == [item["label"] for item in opened["trail"]]
|
||||
assert opened["placements"][0]["label"] == "Akte Sammelakte"
|
||||
assert opened["placements"][0]["current"] is True
|
||||
listed = ada.request("GET", "/api/v1/matters")
|
||||
rows = {item["title"]: item for item in listed["items"]}
|
||||
assert rows["Prüfung"]["kind_label"] == "Teilvorgang"
|
||||
assert rows["Prüfung"]["parent_title"] == "Hauptvorgang"
|
||||
assert rows["Hauptvorgang"]["kind_label"] == "Vorgang"
|
||||
chapter = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{child['id']}/chapters?context_kind=case&context_id={case['id']}",
|
||||
json={"title": "Schriftverkehr"},
|
||||
status=201,
|
||||
)
|
||||
_note(ada, "Einwendung", child, document_on="2024-05-02")
|
||||
case_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
assert [item["title"] for item in case_view["matters"]] == ["Hauptvorgang"]
|
||||
assert case_view["matters"][0]["children"][0]["title"] == "Prüfung"
|
||||
contained = {item["title"]: item for item in case_view["contained"]}
|
||||
assert contained["Prüfung"]["kind_label"] == "Teilvorgang"
|
||||
assert contained["Prüfung"]["parent_title"] == "Hauptvorgang"
|
||||
assert contained["Prüfung"]["chapters"][0]["id"] == chapter["id"]
|
||||
assert contained["Prüfung"]["bindings"][0]["element"]["title"] == "Einwendung"
|
||||
|
||||
|
||||
def test_chapters_follow_the_container_not_the_entry(client, db):
|
||||
ada = Actor(client, "ada-ziel@example.test", "Ada Ziel")
|
||||
ben = Actor(client, "ben-ziel@example.test", "Ben Ziel")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
case = case_of(ada, "Wohnung")
|
||||
matter = matter_of(ada, "Nebenkosten 2025")
|
||||
child = ada.request(
|
||||
"POST",
|
||||
"/api/v1/matters",
|
||||
json={"title": "Belegeinsicht", "parent_matter_id": matter["id"]},
|
||||
status=201,
|
||||
)
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
case_chapter = ada.request("POST", f"/api/v1/cases/{case['id']}/chapters", json={"title": "Aktenkapitel"}, status=201)
|
||||
abrechnung = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Abrechnung"}, status=201)
|
||||
schrift = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Schriftverkehr"}, status=201)
|
||||
belege = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{child['id']}/chapters?context_kind=case&context_id={case['id']}",
|
||||
json={"title": "Belege"},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Abrechnungsschreiben",
|
||||
"document": document("Abrechnungstext"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": abrechnung["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Einwendung",
|
||||
"document": document("Einwendungstext"),
|
||||
"context": {"kind": "matter", "id": child["id"]},
|
||||
"chapter_id": belege["id"],
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/notes",
|
||||
json={
|
||||
"title": "Fremdes Kapitel",
|
||||
"document": document("nein"),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"chapter_id": case_chapter["id"],
|
||||
},
|
||||
status=422,
|
||||
)
|
||||
direct = _matter(ada, matter["id"])
|
||||
via_case = ada.request("GET", f"/api/v1/matters/{matter['id']}?context_kind=case&context_id={case['id']}")
|
||||
assert [item["title"] for item in direct["chapters"]] == ["Abrechnung", "Schriftverkehr"]
|
||||
assert [item["id"] for item in via_case["chapters"]] == [item["id"] for item in direct["chapters"]]
|
||||
assert via_case["context"]["kind"] == "case"
|
||||
child_view = ada.request("GET", f"/api/v1/matters/{child['id']}?context_kind=case&context_id={case['id']}")
|
||||
assert [item["title"] for item in child_view["chapters"]] == ["Belege"]
|
||||
case_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
assert [item["title"] for item in case_view["chapters"]] == ["Aktenkapitel"]
|
||||
contained = {item["title"]: item for item in case_view["contained"]}
|
||||
assert [item["title"] for item in contained["Nebenkosten 2025"]["chapters"]] == ["Abrechnung", "Schriftverkehr"]
|
||||
assert [item["title"] for item in contained["Belegeinsicht"]["chapters"]] == ["Belege"]
|
||||
binding = binding_for(direct, "Abrechnungsschreiben")
|
||||
before = len(direct["bindings"])
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{binding['id']}/chapter",
|
||||
json={"expected_version": direct["version"], "chapter_id": schrift["id"]},
|
||||
)
|
||||
moved = _matter(ada, matter["id"])
|
||||
assert binding_for(moved, "Abrechnungsschreiben")["chapter_id"] == schrift["id"]
|
||||
assert binding_for(moved, "Abrechnungsschreiben")["element"]["excerpt"] == "Abrechnungstext"
|
||||
assert len(moved["bindings"]) == before
|
||||
grant(ada, case["id"], ben.email)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters?context_kind=case&context_id={case['id']}",
|
||||
json={"title": "Unerlaubt"},
|
||||
status=403,
|
||||
)
|
||||
ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{binding['id']}/chapter",
|
||||
json={"expected_version": moved["version"], "chapter_id": abrechnung["id"], "context": {"kind": "case", "id": case["id"]}},
|
||||
status=403,
|
||||
)
|
||||
|
||||
|
||||
_PNG = bytes.fromhex(
|
||||
"89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c489"
|
||||
"0000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082"
|
||||
)
|
||||
|
||||
|
||||
def test_summary_and_preview_follow_the_read_right(client, db):
|
||||
ada = Actor(client, "ada-preview@example.test", "Ada Vorschau")
|
||||
ben = Actor(client, "ben-preview@example.test", "Ben Vorschau")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Mappe")
|
||||
_note(ada, "Einwendungstext", matter)
|
||||
detail = _matter(ada, matter["id"])
|
||||
note = detail["bindings"][0]["element"]
|
||||
assert note["excerpt"] == "Einwendungstext"
|
||||
assert note["summary"] is None
|
||||
assert note["preview"]["available"] is False
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/elements/{note['id']}/summary",
|
||||
json={
|
||||
"expected_version": note["version"],
|
||||
"summary": "Kurze Einwendung",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Scan", "context_kind": "matter", "context_id": matter["id"]},
|
||||
files={"upload": ("punkt.png", _PNG, "image/png")},
|
||||
status=201,
|
||||
)
|
||||
detail = _matter(ada, matter["id"])
|
||||
by_title = {item["element"]["title"]: item["element"] for item in detail["bindings"]}
|
||||
assert by_title["Einwendungstext"]["summary"] == "Kurze Einwendung"
|
||||
assert by_title["Scan"]["preview"] == {"available": True, "media": "image", "source": "file"}
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}", status=404)
|
||||
ben.request("GET", f"/api/v1/files/{by_title['Scan']['id']}/content", status=404)
|
||||
|
||||
|
||||
def test_chapters_move_with_their_entries_and_follow_their_date(client, db):
|
||||
ada = Actor(client, "ada-kapitel-ordnung@example.test", "Ada Kapitel")
|
||||
ben = Actor(client, "ben-kapitel-ordnung@example.test", "Ben Kapitel")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
matter = matter_of(ada, "Nebenkosten")
|
||||
first = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Abrechnung", "document_on": "2025-03-01"}, status=201)
|
||||
second = ada.request("POST", f"/api/v1/matters/{matter['id']}/chapters", json={"title": "Schriftverkehr", "document_on": "2025-01-15"}, status=201)
|
||||
_note(ada, "Schreiben", matter, document_on="2025-06-02")
|
||||
detail = _matter(ada, matter["id"])
|
||||
binding = binding_for(detail, "Schreiben")
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/bindings/{binding['id']}/chapter",
|
||||
json={"expected_version": detail["version"], "chapter_id": first["id"]},
|
||||
)
|
||||
detail = _matter(ada, matter["id"])
|
||||
assert detail["content_order"] == "date"
|
||||
assert [item["title"] for item in detail["chapters"]] == ["Schriftverkehr", "Abrechnung"]
|
||||
dated = detail
|
||||
assert binding_for(dated, "Schreiben")["chapter_id"] == first["id"]
|
||||
assert binding_for(dated, "Schreiben")["element"]["excerpt"] == "Schreiben"
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": dated["version"], "mode": "position", "direction": "asc"},
|
||||
)
|
||||
positioned = _matter(ada, matter["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters/order",
|
||||
json={"expected_version": positioned["version"], "chapter_ids": [first["id"], second["id"]]},
|
||||
)
|
||||
ordered = _matter(ada, matter["id"])
|
||||
assert [item["title"] for item in ordered["chapters"]] == ["Abrechnung", "Schriftverkehr"]
|
||||
assert binding_for(ordered, "Schreiben")["chapter_id"] == first["id"]
|
||||
assert len(ordered["bindings"]) == 1
|
||||
case = case_of(ada, "Wohnung")
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
grant(ada, case["id"], ben.email)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/chapters/order",
|
||||
json={
|
||||
"expected_version": ordered["version"],
|
||||
"chapter_ids": [second["id"], first["id"]],
|
||||
"context": {"kind": "case", "id": case["id"]},
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
@@ -0,0 +1,461 @@
|
||||
"""Granted readers see linked originals only through the owner's stored connector."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import app.sources as sources
|
||||
from tests.support import ORIGIN, Actor, register
|
||||
|
||||
OWNER_TOKEN = "owner-paperless-token"
|
||||
GRANTEE_TOKEN = "grantee-paperless-token"
|
||||
OWNER_MAIL = "owner-postfach-geheim"
|
||||
GRANTEE_MAIL = "grantee-postfach-geheim"
|
||||
UNAVAILABLE = "Das Original ist über die Freigabe nicht abrufbar."
|
||||
|
||||
|
||||
class RecordingIMAP:
|
||||
logins: list[str] = []
|
||||
fetches: list[int] = []
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def login(self, username, secret):
|
||||
RecordingIMAP.logins.append(secret)
|
||||
return "OK", [b"logged"]
|
||||
|
||||
def list(self):
|
||||
return "OK", [b'(\\HasNoChildren) "/" "INBOX"']
|
||||
|
||||
def select(self, mailbox, readonly=False):
|
||||
return "OK", [b"5"]
|
||||
|
||||
def uid(self, command, *args):
|
||||
if command == "SEARCH":
|
||||
return "OK", [b""]
|
||||
uid = int(args[0])
|
||||
spec = " ".join(str(part) for part in args[1:])
|
||||
if "BODY.PEEK[]" in spec:
|
||||
RecordingIMAP.fetches.append(uid)
|
||||
raw = (
|
||||
f"From: Ada Beispiel <ada@example.test>\r\n"
|
||||
f"To: Kanzlei <kanzlei@example.test>\r\n"
|
||||
f"Subject: Nachricht {uid}\r\n"
|
||||
f"Date: Thu, 02 May 2024 08:00:00 +0000\r\n"
|
||||
f"Message-ID: <{uid}@example.test>\r\n"
|
||||
f"MIME-Version: 1.0\r\n"
|
||||
f'Content-Type: multipart/mixed; boundary="grenze"\r\n'
|
||||
f"\r\n"
|
||||
f"--grenze\r\n"
|
||||
f"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
f"\r\n"
|
||||
f"Bitte die Einwendung pruefen.\r\n"
|
||||
f"--grenze\r\n"
|
||||
f"Content-Type: application/pdf\r\n"
|
||||
f'Content-Disposition: attachment; filename="einwendung.pdf"\r\n'
|
||||
f"\r\n"
|
||||
f"%PDF\r\n"
|
||||
f"--grenze--\r\n"
|
||||
).encode()
|
||||
return "OK", [(b"rfc822", raw)]
|
||||
return "OK", [(b"body", b"From: Ada\r\n"), b")"]
|
||||
|
||||
def logout(self):
|
||||
return "BYE", [b""]
|
||||
|
||||
|
||||
def _reset_imap():
|
||||
RecordingIMAP.logins = []
|
||||
RecordingIMAP.fetches = []
|
||||
|
||||
|
||||
def _paperless(actor: Actor, token: str, name: str) -> str:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "paperless", "name": name, "base_url": "https://paper.example.test", "token": token},
|
||||
status=201,
|
||||
)["id"]
|
||||
|
||||
|
||||
def _mailbox(actor: Actor, password: str, name: str) -> str:
|
||||
return actor.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={
|
||||
"kind": "imap",
|
||||
"name": name,
|
||||
"host": "imap.example.test",
|
||||
"port": 993,
|
||||
"username": f"{name}@example.test",
|
||||
"password": password,
|
||||
"security": "ssl",
|
||||
},
|
||||
status=201,
|
||||
)["id"]
|
||||
|
||||
|
||||
def _raw(actor: Actor, path: str):
|
||||
return actor.client.get(
|
||||
path,
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _grant(actor: Actor, kind: str, resource_id: str, email: str, **flags):
|
||||
body = {"email": email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": False}
|
||||
body.update(flags)
|
||||
return actor.request("POST", f"/api/v1/{kind}/{resource_id}/grants", json=body, status=201)
|
||||
|
||||
|
||||
def _events(db):
|
||||
return db.execute(
|
||||
"""
|
||||
SELECT action, result, detail
|
||||
FROM domain_events
|
||||
WHERE action = 'source_read_mediated'
|
||||
ORDER BY occurred_at, id
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
|
||||
def test_owner_alone_sets_source_access_and_a_delegate_cannot_change_it(client, db):
|
||||
ada = Actor(client, "ada-flag@example.test", "Ada Flag")
|
||||
ben = Actor(client, "ben-flag@example.test", "Ben Flag")
|
||||
cleo = Actor(client, "cleo-flag@example.test", "Cleo Flag")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
register(db, cleo.email, cleo.name)
|
||||
ada.login()
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Streit"}, status=201)
|
||||
_grant(ada, "cases", case["id"], ben.email, can_share=True, use_owner_sources=True)
|
||||
ada_view = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ben_grant = next(item for item in ada_view["grants"] if item["email"] == ben.email)
|
||||
assert ben_grant["use_owner_sources"] is True
|
||||
|
||||
ben.login()
|
||||
_grant(ben, "cases", case["id"], cleo.email, use_owner_sources=True)
|
||||
ada.login()
|
||||
after_delegate = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
cleo_grant = next(item for item in after_delegate["grants"] if item["email"] == cleo.email)
|
||||
assert cleo_grant["use_owner_sources"] is False
|
||||
|
||||
_grant(ada, "cases", case["id"], cleo.email, use_owner_sources=True)
|
||||
ben.login()
|
||||
_grant(ben, "cases", case["id"], cleo.email, can_share=True, use_owner_sources=False)
|
||||
ada.login()
|
||||
kept = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
cleo_grant = next(item for item in kept["grants"] if item["email"] == cleo.email)
|
||||
assert cleo_grant["can_share"] is True
|
||||
assert cleo_grant["use_owner_sources"] is True
|
||||
|
||||
_grant(ada, "cases", case["id"], cleo.email, use_owner_sources=False)
|
||||
cleared = ada.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
cleo_grant = next(item for item in cleared["grants"] if item["email"] == cleo.email)
|
||||
assert cleo_grant["use_owner_sources"] is False
|
||||
|
||||
|
||||
def test_grantee_reads_linked_originals_only_through_the_owner(client, db, monkeypatch):
|
||||
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\nverknuepft\n", "application/pdf", "vertrag.pdf")
|
||||
return None
|
||||
|
||||
def fake_get(base, token, path, params):
|
||||
calls.append({"token": token, "path": path, "query": params.get("query")})
|
||||
if token == OWNER_TOKEN:
|
||||
return {"count": 1, "results": [{"id": 15, "title": "Geheimes Archivdokument", "created": "2026-01-01"}]}
|
||||
return {"count": 0, "results": []}
|
||||
|
||||
monkeypatch.setattr(sources, "_paperless_file", fake_file)
|
||||
monkeypatch.setattr(sources, "_paperless_get", fake_get)
|
||||
monkeypatch.setattr(sources, "_paperless_metadata", lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RecordingIMAP)
|
||||
_reset_imap()
|
||||
|
||||
ada = Actor(client, "ada-quelle@example.test", "Ada Quelle")
|
||||
ben = Actor(client, "ben-quelle@example.test", "Ben Quelle")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
paper = _paperless(ada, OWNER_TOKEN, "Ada Archiv")
|
||||
mailbox = _mailbox(ada, OWNER_MAIL, "Ada Post")
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Akte"}, status=201)
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201)
|
||||
other = ada.request("POST", "/api/v1/matters", json={"title": "Fremder Vorgang"}, 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, "correspondent": "Hausverwaltung"},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
letter = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Einwendung",
|
||||
"source": "imap",
|
||||
"external_id": "<2@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {
|
||||
"connector_id": mailbox,
|
||||
"mailbox": "INBOX",
|
||||
"uid": 2,
|
||||
"direction": "in",
|
||||
"message_from": "Hausverwaltung",
|
||||
},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
owner_file = _raw(ada, f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}")
|
||||
assert owner_file.status_code == 200
|
||||
assert owner_file.content.startswith(b"%PDF")
|
||||
assert calls[-1]["token"] == OWNER_TOKEN
|
||||
assert "/api/documents/15/" in calls[-1]["path"]
|
||||
owner_mail = ada.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
)
|
||||
assert "Einwendung" in owner_mail["text"]
|
||||
assert OWNER_MAIL in RecordingIMAP.logins
|
||||
calls.clear()
|
||||
_reset_imap()
|
||||
|
||||
ben.login()
|
||||
_paperless(ben, GRANTEE_TOKEN, "Ben Archiv")
|
||||
_mailbox(ben, GRANTEE_MAIL, "Ben Post")
|
||||
ada.login()
|
||||
_grant(ada, "cases", case["id"], ben.email)
|
||||
_grant(ada, "matters", matter["id"], ben.email)
|
||||
_grant(ada, "matters", other["id"], ben.email, use_owner_sources=True)
|
||||
|
||||
ben.login()
|
||||
shown = ben.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
visible = next(item for item in shown["bindings"] if item["element"]["title"] == "Einwendung")
|
||||
detail = visible["element"]["external"]["detail"]
|
||||
assert detail["direction"] == "in"
|
||||
assert detail["message_from"] == "Hausverwaltung"
|
||||
assert "connector_id" not in detail
|
||||
assert "mailbox" not in detail
|
||||
assert "uid" not in detail
|
||||
assert "external_id" not in visible["element"]["external"]
|
||||
dumped = json.dumps(shown)
|
||||
assert OWNER_MAIL not in dumped
|
||||
assert OWNER_TOKEN not in dumped
|
||||
assert "imap.example.test" not in dumped
|
||||
assert mailbox not in dumped
|
||||
|
||||
hidden = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{document['id']}/content",
|
||||
params={"context_kind": "case", "context_id": case["id"], "document": "999"},
|
||||
status=422,
|
||||
)
|
||||
assert hidden["detail"] == UNAVAILABLE
|
||||
assert calls == []
|
||||
missed = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"], "uid": "9", "mailbox": "Geheim"},
|
||||
status=422,
|
||||
)
|
||||
assert missed["detail"] == UNAVAILABLE
|
||||
assert RecordingIMAP.logins == []
|
||||
assert RecordingIMAP.fetches == []
|
||||
|
||||
ada.login()
|
||||
_grant(ada, "cases", case["id"], ben.email, use_owner_sources=True)
|
||||
_grant(ada, "matters", matter["id"], ben.email, use_owner_sources=True)
|
||||
ben.login()
|
||||
opened = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{document['id']}/content?context_kind=case&context_id={case['id']}&document=999",
|
||||
)
|
||||
assert opened.status_code == 200
|
||||
assert opened.content.startswith(b"%PDF")
|
||||
assert opened.headers["x-content-type-options"] == "nosniff"
|
||||
assert opened.headers["cache-control"] == "private, no-store"
|
||||
assert opened.headers["referrer-policy"] == "no-referrer"
|
||||
assert calls == [{"token": OWNER_TOKEN, "path": "/api/documents/15/preview/"}]
|
||||
assert GRANTEE_TOKEN not in json.dumps(calls)
|
||||
own_connectors = {item["id"] for item in ben.request("GET", "/api/v1/connectors")["items"]}
|
||||
assert paper not in own_connectors
|
||||
assert mailbox not in own_connectors
|
||||
ben.request("POST", f"/api/v1/connectors/{paper}/probe", status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
"/api/v1/sources/paperless/documents",
|
||||
params={"q": "Geheim", "connector_id": paper},
|
||||
status=404,
|
||||
)
|
||||
search = ben.request("GET", "/api/v1/sources/paperless/documents", params={"q": "Geheim"})
|
||||
assert "Geheimes Archivdokument" not in json.dumps(search)
|
||||
assert all(item["token"] != OWNER_TOKEN for item in calls if "query" in item)
|
||||
|
||||
mail = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"], "uid": "9", "connector_id": paper},
|
||||
)
|
||||
assert mail["text"] == "Bitte die Einwendung pruefen."
|
||||
assert mail["attachments"][0]["filename"] == "einwendung.pdf"
|
||||
assert RecordingIMAP.logins == [OWNER_MAIL]
|
||||
assert RecordingIMAP.fetches == [2]
|
||||
original = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{letter['id']}/mail/original?context_kind=matter&context_id={matter['id']}",
|
||||
)
|
||||
assert original.status_code == 200
|
||||
assert b"Message-ID: <2@example.test>" in original.content
|
||||
attachment = _raw(
|
||||
ben,
|
||||
f"/api/v1/external-refs/{letter['id']}/mail/attachments/0?context_kind=matter&context_id={matter['id']}",
|
||||
)
|
||||
assert attachment.status_code == 200
|
||||
assert attachment.content.startswith(b"%PDF")
|
||||
assert attachment.headers["content-disposition"].startswith("inline;")
|
||||
assert GRANTEE_MAIL not in RecordingIMAP.logins
|
||||
page = ben.request("GET", f"/api/v1/matters/{matter['id']}/chronology")
|
||||
chronology = json.dumps(page)
|
||||
assert "source_read_mediated" in [item["action"] for item in page["items"]]
|
||||
assert "Verknüpftes Original gelesen" in [item["label"] for item in page["items"]]
|
||||
assert mailbox not in chronology
|
||||
assert OWNER_MAIL not in chronology
|
||||
|
||||
quiet = len(RecordingIMAP.logins)
|
||||
ben.request("GET", "/api/v1/sources/imap/mailboxes", params={"connector_id": mailbox}, status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": other["id"]},
|
||||
status=404,
|
||||
)
|
||||
ada.login()
|
||||
ada.request(
|
||||
"PUT",
|
||||
"/api/v1/exceptions",
|
||||
json={
|
||||
"resource_kind": "element",
|
||||
"resource_id": letter["id"],
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"remove_read": True,
|
||||
},
|
||||
)
|
||||
grant_id = next(item["id"] for item in ada.request("GET", f"/api/v1/cases/{case['id']}")["grants"])
|
||||
ben.login()
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{letter['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=404,
|
||||
)
|
||||
assert len(RecordingIMAP.logins) == quiet
|
||||
ada.login()
|
||||
ada.request("DELETE", f"/api/v1/grants/{grant_id}", status=204)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{document['id']}/content",
|
||||
params={"context_kind": "case", "context_id": case["id"]},
|
||||
status=404,
|
||||
)
|
||||
assert len(RecordingIMAP.logins) == quiet
|
||||
assert [item["token"] for item in calls if "query" not in item] == [OWNER_TOKEN]
|
||||
|
||||
rows = _events(db)
|
||||
blob = json.dumps(rows, default=str)
|
||||
assert OWNER_TOKEN not in blob
|
||||
assert OWNER_MAIL not in blob
|
||||
assert "Bitte die Einwendung" not in blob
|
||||
assert "imap.example.test" not in blob
|
||||
assert any(row["result"] == "ok" and row["detail"]["source"] == "paperless" for row in rows)
|
||||
assert any(row["result"] == "ok" and row["detail"]["connector_id"] == mailbox for row in rows)
|
||||
|
||||
|
||||
def test_deleted_or_foreign_connector_is_not_used(client, db, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
sources,
|
||||
"_paperless_file",
|
||||
lambda *args, **kwargs: calls.append("paperless") or (b"%PDF-1.4\n", "application/pdf", "x.pdf"),
|
||||
)
|
||||
monkeypatch.setattr(sources.imaplib, "IMAP4_SSL", RecordingIMAP)
|
||||
_reset_imap()
|
||||
|
||||
ada = Actor(client, "ada-weg@example.test", "Ada Weg")
|
||||
ben = Actor(client, "ben-weg@example.test", "Ben Weg")
|
||||
cleo = Actor(client, "cleo-weg@example.test", "Cleo Weg")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
register(db, cleo.email, cleo.name)
|
||||
ada.login()
|
||||
paper = _paperless(ada, OWNER_TOKEN, "Ada Archiv")
|
||||
ben.login()
|
||||
foreign = _mailbox(ben, GRANTEE_MAIL, "Ben Post")
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Vorgang"}, status=201)
|
||||
document = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Scan",
|
||||
"source": "paperless",
|
||||
"external_id": "15",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": paper},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
foreign_mail = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Fremde Quelle",
|
||||
"source": "imap",
|
||||
"external_id": "<2@example.test>",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": foreign, "mailbox": "INBOX", "uid": 2},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
_grant(ada, "matters", matter["id"], cleo.email, use_owner_sources=True)
|
||||
ada.request("DELETE", f"/api/v1/connectors/{paper}", status=204)
|
||||
cleo.login()
|
||||
blocked = cleo.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{document['id']}/content",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=422,
|
||||
)
|
||||
assert blocked["detail"] == UNAVAILABLE
|
||||
assert "paper.example.test" not in blocked["detail"]
|
||||
assert calls == []
|
||||
refused = cleo.request(
|
||||
"GET",
|
||||
f"/api/v1/external-refs/{foreign_mail['id']}/mail",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=422,
|
||||
)
|
||||
assert refused["detail"] == UNAVAILABLE
|
||||
assert RecordingIMAP.logins == []
|
||||
rows = _events(db)
|
||||
assert rows
|
||||
assert all(row["result"] == "unavailable" for row in rows)
|
||||
assert OWNER_TOKEN not in json.dumps(rows, default=str)
|
||||
assert GRANTEE_MAIL not in json.dumps(rows, default=str)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""The Paperless disk fallback stays inside the archive directory."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.sources import read_paperless_file
|
||||
|
||||
|
||||
def test_reads_the_archive_pdf(tmp_path):
|
||||
target = tmp_path / "documents" / "archive" / "2026" / "brief.pdf"
|
||||
target.parent.mkdir(parents=True)
|
||||
target.write_bytes(b"%PDF-1.1 sample")
|
||||
assert read_paperless_file(str(tmp_path), "archive", "2026/brief.pdf") == b"%PDF-1.1 sample"
|
||||
|
||||
|
||||
def test_rejects_paths_outside_the_archive(tmp_path):
|
||||
secret = tmp_path / "documents" / "secret.pdf"
|
||||
secret.parent.mkdir(parents=True)
|
||||
secret.write_bytes(b"%PDF-1.1 secret")
|
||||
(tmp_path / "documents" / "archive").mkdir()
|
||||
assert read_paperless_file(str(tmp_path), "archive", "../secret.pdf") is None
|
||||
assert read_paperless_file(str(tmp_path), "archive", "/etc/passwd") is None
|
||||
assert read_paperless_file(str(tmp_path), "other", "2026/brief.pdf") is None
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Einstellungen je Konto: Erbung vom Hauptnutzer, eigener Wert, Verbindlichkeit für das Team."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_team import _invite, _main
|
||||
|
||||
PATH = "/api/v1/auth/preferences/duplicate_check"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def world(client, db):
|
||||
ada = _main(client, db, "ada", main=True)
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Kanzlei"}, status=201)["id"]
|
||||
ada.use_room(room)
|
||||
emp = _invite(ada, room, "emp-pref@example.test", name="Eva")
|
||||
return {"ada": ada, "emp": emp}
|
||||
|
||||
|
||||
def test_the_default_applies_without_any_choice(world):
|
||||
for person in (world["ada"], world["emp"]):
|
||||
state = person.request("GET", PATH)
|
||||
assert (state["value"], state["source"]) == ("here", "default")
|
||||
assert world["ada"].request("GET", PATH)["can_lock"] is True
|
||||
assert world["emp"].request("GET", PATH)["can_lock"] is False
|
||||
|
||||
|
||||
def test_an_employee_inherits_the_main_user_and_may_override(world):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
ada.request("PUT", PATH, json={"value": "inside"})
|
||||
inherited = emp.request("GET", PATH)
|
||||
assert (inherited["value"], inherited["source"]) == ("inside", "team")
|
||||
|
||||
own = emp.request("PUT", PATH, json={"value": "off"})
|
||||
assert (own["value"], own["source"]) == ("off", "own")
|
||||
# The main user's change does not touch an own choice.
|
||||
ada.request("PUT", PATH, json={"value": "around"})
|
||||
assert emp.request("GET", PATH)["value"] == "off"
|
||||
assert ada.request("GET", PATH)["value"] == "around"
|
||||
|
||||
# Inheriting again.
|
||||
back = emp.request("PUT", PATH, json={"value": None})
|
||||
assert (back["value"], back["source"]) == ("around", "team")
|
||||
|
||||
|
||||
def test_a_binding_overrides_an_own_value_without_deleting_it(world):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
emp.request("PUT", PATH, json={"value": "off"})
|
||||
ada.request("PUT", PATH, json={"value": "inside", "team_mode": "locked"})
|
||||
|
||||
locked = emp.request("GET", PATH)
|
||||
assert (locked["value"], locked["source"], locked["locked"]) == ("inside", "locked", True)
|
||||
refused = emp.request("PUT", PATH, json={"value": "here"}, status=403)
|
||||
assert "vorgegeben" in refused["detail"]
|
||||
|
||||
# The main user is not bound by the own binding.
|
||||
assert ada.request("PUT", PATH, json={"value": "here"})["value"] == "here"
|
||||
assert ada.request("GET", PATH)["team_mode"] == "locked"
|
||||
assert emp.request("GET", PATH)["value"] == "here"
|
||||
|
||||
ada.request("PUT", PATH, json={"value": "here", "team_mode": "free"})
|
||||
again = emp.request("GET", PATH)
|
||||
assert (again["value"], again["source"]) == ("off", "own")
|
||||
|
||||
|
||||
def test_only_the_main_user_binds_and_values_are_checked(world):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
emp.request("PUT", PATH, json={"value": "off", "team_mode": "locked"}, status=403)
|
||||
assert emp.request("GET", PATH)["source"] == "default"
|
||||
ada.request("PUT", PATH, json={"value": "everywhere"}, status=422)
|
||||
ada.request("GET", "/api/v1/auth/preferences/unknown", status=404)
|
||||
ada.request("PUT", "/api/v1/auth/preferences/unknown", json={"value": "off"}, status=404)
|
||||
|
||||
|
||||
def test_a_binding_of_a_stranger_does_not_reach_my_employee(client, db, world):
|
||||
ben = _main(client, db, "ben")
|
||||
ben.request("PUT", PATH, json={"value": "off", "team_mode": "locked"})
|
||||
assert world["emp"].request("GET", PATH)["value"] == "here"
|
||||
@@ -0,0 +1,93 @@
|
||||
"""A reply refers to one earlier element; letters in between stay in the list."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.support import Actor, document, register
|
||||
|
||||
|
||||
def _note(actor: Actor, title: str, matter_id: str, direction: str | None = None, **dates) -> None:
|
||||
body = {
|
||||
"title": title,
|
||||
"document": document(title),
|
||||
"context": {"kind": "matter", "id": matter_id},
|
||||
"dates": dates,
|
||||
}
|
||||
if direction in ("in", "out"):
|
||||
body["communication_direction"] = direction
|
||||
actor.request("POST", "/api/v1/notes", json=body, status=201)
|
||||
|
||||
|
||||
def _by_title(detail: dict) -> dict:
|
||||
return {item["element"]["title"]: item["element"] for item in detail["bindings"]}
|
||||
|
||||
|
||||
def test_reply_names_its_letter_and_leaves_the_gap(client, db):
|
||||
ada = Actor(client, "ada-bezug@example.test", "Ada Bezug")
|
||||
ben = Actor(client, "ben-bezug@example.test", "Ben Bezug")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Schriftwechsel"}, status=201)
|
||||
_note(ada, "Anschreiben", matter["id"], "in", document_on="2026-03-12", received_on="2026-03-12")
|
||||
_note(ada, "Zwischennachricht", matter["id"], document_on="2026-04-02", received_on="2026-04-02", sent_on="2026-04-02")
|
||||
_note(ada, "Antwort", matter["id"], "out", document_on="2026-05-18", sent_on="2026-05-18")
|
||||
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}/content-order",
|
||||
json={"expected_version": detail["version"], "mode": "date", "direction": "asc"},
|
||||
)
|
||||
elements = _by_title(ada.request("GET", f"/api/v1/matters/{matter['id']}"))
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{elements['Antwort']['id']}/references",
|
||||
json={"refers_to_element_id": elements["Antwort"]["id"], "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=422,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{elements['Antwort']['id']}/references",
|
||||
json={"refers_to_element_id": elements["Anschreiben"]["id"], "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=204,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{elements['Anschreiben']['id']}/references",
|
||||
json={"refers_to_element_id": elements["Antwort"]["id"], "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=422,
|
||||
)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"POST",
|
||||
f"/api/v1/elements/{elements['Antwort']['id']}/references",
|
||||
json={"refers_to_element_id": elements["Zwischennachricht"]["id"], "context": {"kind": "matter", "id": matter["id"]}},
|
||||
status=404,
|
||||
)
|
||||
ada.login()
|
||||
shown = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
titles = [item["element"]["title"] for item in shown["bindings"]]
|
||||
assert titles == ["Anschreiben", "Zwischennachricht", "Antwort"]
|
||||
linked = _by_title(shown)
|
||||
assert linked["Antwort"]["refers_to"] == [
|
||||
{
|
||||
"id": elements["Anschreiben"]["id"],
|
||||
"title": "Anschreiben",
|
||||
"document_on": "2026-03-12",
|
||||
"direction": "in",
|
||||
}
|
||||
]
|
||||
assert linked["Anschreiben"]["referred_by"][0]["title"] == "Antwort"
|
||||
assert linked["Anschreiben"]["referred_by"][0]["direction"] == "out"
|
||||
gap = next(item for item in shown["bindings"] if item["element"]["title"] == "Zwischennachricht")
|
||||
assert gap["communication"]["direction"] is None
|
||||
assert "refers_to" not in linked["Zwischennachricht"]
|
||||
assert "referred_by" not in linked["Zwischennachricht"]
|
||||
ada.request(
|
||||
"DELETE",
|
||||
f"/api/v1/elements/{elements['Antwort']['id']}/references/{elements['Anschreiben']['id']}",
|
||||
params={"context_kind": "matter", "context_id": matter["id"]},
|
||||
status=204,
|
||||
)
|
||||
cleared = _by_title(ada.request("GET", f"/api/v1/matters/{matter['id']}"))
|
||||
assert "refers_to" not in cleared["Antwort"]
|
||||
assert "referred_by" not in cleared["Anschreiben"]
|
||||
@@ -0,0 +1,297 @@
|
||||
"""T-ISO, T-SHARE, T-CONTEXT, T-DETACH, T-GRANT and the personal-room boundary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from app.access.policy import SHARED_NOTICE
|
||||
from tests.support import Actor, bind_to, case_of, document, grant, note_on, register, texts
|
||||
|
||||
|
||||
def test_manager_does_not_read_a_personal_case(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
private = case_of(ada, "Persoenliche Akte")
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Haushalt", "default_visibility": "private"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": "ben@example.test", "role": "manager"})
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.use_room(room["id"])
|
||||
ben.request("GET", f"/api/v1/cases/{private['id']}", status=404)
|
||||
|
||||
|
||||
def test_t_iso_hides_unshared_case_note_file_search_and_chronology(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Akte A Isoliert")
|
||||
case_b = case_of(ada, "Akte B Isoliert")
|
||||
shared = note_on(ada, "Gemeinsame Notiz", "Sichtbar in B", case_a["id"])
|
||||
bind_to(ada, shared["id"], case_a["id"], case_b["id"])
|
||||
note_on(ada, "Private Notiz", "Isolierwort bleibt in A", case_a["id"])
|
||||
upload = ada.request(
|
||||
"POST",
|
||||
"/api/v1/files",
|
||||
data={"title": "Geheimes Schreiben", "context_kind": "case", "context_id": case_a["id"]},
|
||||
files={"upload": ("schreiben.pdf", b"%PDF-1.1\ntrailer<</Root 1 0 R>>\n%%EOF\n", "application/pdf")},
|
||||
status=201,
|
||||
)
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=False)
|
||||
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/cases/{case_a['id']}", status=404)
|
||||
visible = ben.request("GET", f"/api/v1/cases/{case_b['id']}")
|
||||
assert "Gemeinsame Notiz" in texts(visible)
|
||||
assert "Private Notiz" not in texts(visible)
|
||||
assert "Isolierwort" not in json.dumps(visible)
|
||||
|
||||
hidden = ben.request("GET", "/api/v1/search", params={"q": "Isolierwort"})
|
||||
assert hidden["items"] == []
|
||||
ada.login()
|
||||
found = ada.request("GET", "/api/v1/search", params={"q": "Isolierwort"})
|
||||
assert any(item["title"] == "Private Notiz" for item in found["items"])
|
||||
|
||||
ben.login()
|
||||
download = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/files/{upload['id']}/content",
|
||||
params={"context_kind": "case", "context_id": case_a["id"]},
|
||||
status=404,
|
||||
)
|
||||
assert download["detail"] == "Der Eintrag ist nicht vorhanden."
|
||||
assert "schreiben" not in json.dumps(download).casefold()
|
||||
chronology = ben.request("GET", f"/api/v1/cases/{case_b['id']}/chronology")
|
||||
blob = json.dumps(chronology)
|
||||
assert "Private Notiz" not in blob
|
||||
assert "Isolierwort" not in blob
|
||||
assert "Geheimes Schreiben" not in blob
|
||||
|
||||
|
||||
def test_t_share_text_annotation_and_hidden_binding_count(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Akte Anteil A")
|
||||
case_b = case_of(ada, "Akte Anteil B")
|
||||
case_c = case_of(ada, "Akte Verborgen")
|
||||
created = note_on(ada, "Geteilte Notiz", "Erster Text", case_a["id"])
|
||||
bound = bind_to(ada, created["id"], case_a["id"], case_b["id"])
|
||||
bind_to(ada, created["id"], case_a["id"], case_c["id"])
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/bindings/{bound['id']}/annotations",
|
||||
params={"context_kind": "case", "context_id": case_b["id"]},
|
||||
json={"body": "Nur in B vermerkt"},
|
||||
status=201,
|
||||
)
|
||||
changed = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{created['id']}",
|
||||
json={
|
||||
"expected_version": created["version"],
|
||||
"document": document("Gleicher Text"),
|
||||
"context": {"kind": "case", "id": case_a["id"]},
|
||||
},
|
||||
)
|
||||
from_b = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{created['id']}",
|
||||
json={
|
||||
"expected_version": changed["version"],
|
||||
"document": document("Von beiden Seiten"),
|
||||
"context": {"kind": "case", "id": case_b["id"]},
|
||||
},
|
||||
)
|
||||
seen_a = texts(ada.request("GET", f"/api/v1/cases/{case_a['id']}"))
|
||||
seen_b = ada.request("GET", f"/api/v1/cases/{case_b['id']}")
|
||||
assert seen_a["Geteilte Notiz"] == "Von beiden Seiten"
|
||||
assert texts(seen_b)["Geteilte Notiz"] == "Von beiden Seiten"
|
||||
assert "Nur in B vermerkt" not in json.dumps(ada.request("GET", f"/api/v1/cases/{case_a['id']}"))
|
||||
assert "Nur in B vermerkt" in json.dumps(seen_b)
|
||||
assert from_b["notice"] == SHARED_NOTICE
|
||||
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=True)
|
||||
plain = note_on(ada, "Nur B", "Kontrolltext", case_b["id"])
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
hidden = ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{created['id']}",
|
||||
json={
|
||||
"expected_version": from_b["version"],
|
||||
"document": document("Ben aendert"),
|
||||
"context": {"kind": "case", "id": case_b["id"]},
|
||||
},
|
||||
)
|
||||
only_b = ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{plain['id']}",
|
||||
json={
|
||||
"expected_version": plain["version"],
|
||||
"document": document("Kontrolltext neu"),
|
||||
"context": {"kind": "case", "id": case_b["id"]},
|
||||
},
|
||||
)
|
||||
|
||||
def shape(payload: dict) -> dict:
|
||||
return {
|
||||
"notice": payload["notice"],
|
||||
"count": len(payload["visible_bindings"]),
|
||||
"names": sorted(item["context_title"] for item in payload["visible_bindings"]),
|
||||
}
|
||||
|
||||
assert shape(hidden) == shape(only_b)
|
||||
assert shape(hidden)["names"] == ["Akte Anteil B"]
|
||||
assert "Akte Verborgen" not in json.dumps(hidden)
|
||||
assert hidden["notice"] == SHARED_NOTICE
|
||||
|
||||
ada.login()
|
||||
readonly = case_of(ada, "Akte Nur Lesen")
|
||||
locked = note_on(ada, "Geschuetzte Notiz", "Unveraendert", readonly["id"])
|
||||
grant(ada, readonly["id"], "ben@example.test", edit=False)
|
||||
ben.login()
|
||||
ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{locked['id']}",
|
||||
json={
|
||||
"expected_version": locked["version"],
|
||||
"document": document("Darf nicht"),
|
||||
"context": {"kind": "case", "id": readonly["id"]},
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
ada.login()
|
||||
assert texts(ada.request("GET", f"/api/v1/cases/{readonly['id']}"))["Geschuetzte Notiz"] == "Unveraendert"
|
||||
|
||||
|
||||
def test_t_context_uses_only_the_requested_case(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Kontext A")
|
||||
case_b = case_of(ada, "Kontext B")
|
||||
case_c = case_of(ada, "Kontext Fremd")
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Gleicher Vorgang"}, status=201)
|
||||
version = matter["version"]
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case_a["id"]}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case_b["id"]}, status=201)
|
||||
again = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
assert again["version"] == version
|
||||
grant(ada, case_a["id"], "ben@example.test", edit=True)
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=False)
|
||||
grant(ada, case_c["id"], "ben@example.test", edit=True)
|
||||
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}", status=404)
|
||||
ben.request("PATCH", f"/api/v1/matters/{matter['id']}", json={"expected_version": version, "title": "Ohne Kontext"}, status=404)
|
||||
ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
params={"context_kind": "case", "context_id": case_c["id"]},
|
||||
status=404,
|
||||
)
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}/chronology", status=404)
|
||||
opened = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
params={"context_kind": "case", "context_id": case_a["id"]},
|
||||
)
|
||||
assert opened["rights"]["edit"] is True
|
||||
read_only = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
params={"context_kind": "case", "context_id": case_b["id"]},
|
||||
)
|
||||
assert read_only["rights"]["read"] is True
|
||||
assert read_only["rights"]["edit"] is False
|
||||
ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
json={"expected_version": version, "title": "Aus B", "context": {"kind": "case", "id": case_b["id"]}},
|
||||
status=403,
|
||||
)
|
||||
renamed = ben.request(
|
||||
"PATCH",
|
||||
f"/api/v1/matters/{matter['id']}",
|
||||
json={"expected_version": version, "title": "Aus A", "context": {"kind": "case", "id": case_a["id"]}},
|
||||
)
|
||||
assert renamed["title"] == "Aus A"
|
||||
chronology = ben.request(
|
||||
"GET",
|
||||
f"/api/v1/matters/{matter['id']}/chronology",
|
||||
params={"context_kind": "case", "context_id": case_a["id"]},
|
||||
)
|
||||
assert chronology["items"]
|
||||
|
||||
|
||||
def test_t_detach_keeps_the_other_binding(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
case_a = case_of(ada, "Akte Bleibt")
|
||||
case_b = case_of(ada, "Akte Loesen")
|
||||
created = note_on(ada, "Notiz Bleibt", "Inhalt bleibt", case_a["id"])
|
||||
bound = bind_to(ada, created["id"], case_a["id"], case_b["id"])
|
||||
grant(ada, case_b["id"], "ben@example.test", edit=True)
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
ben.request(
|
||||
"DELETE",
|
||||
f"/api/v1/bindings/{bound['id']}",
|
||||
params={"context_kind": "case", "context_id": case_b["id"]},
|
||||
status=204,
|
||||
)
|
||||
ben_view = ben.request("GET", f"/api/v1/cases/{case_b['id']}")
|
||||
assert "Notiz Bleibt" not in texts(ben_view)
|
||||
ada.login()
|
||||
kept = ada.request("GET", f"/api/v1/cases/{case_a['id']}")
|
||||
assert texts(kept)["Notiz Bleibt"] == "Inhalt bleibt"
|
||||
|
||||
|
||||
def test_t_grant_edit_does_not_create_a_new_binding(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
register(db, "ben@example.test", "Ben")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
source = case_of(ada, "Akte Quelle")
|
||||
created = note_on(ada, "Nicht weiterreichen", "Bleibt hier", source["id"])
|
||||
grant(ada, source["id"], "ben@example.test", edit=True, share=False)
|
||||
ben = Actor(client, "ben@example.test", "Ben")
|
||||
ben.login()
|
||||
target = case_of(ben, "Akte Ziel")
|
||||
ben.request(
|
||||
"POST",
|
||||
"/api/v1/bindings",
|
||||
json={
|
||||
"element_id": created["id"],
|
||||
"source_context": {"kind": "case", "id": source["id"]},
|
||||
"target": {"kind": "case", "id": target["id"]},
|
||||
},
|
||||
status=403,
|
||||
)
|
||||
assert "Nicht weiterreichen" not in texts(ben.request("GET", f"/api/v1/cases/{target['id']}"))
|
||||
|
||||
|
||||
def test_matter_without_a_case_and_same_version_in_two_cases(client, db):
|
||||
register(db, "ada@example.test", "Ada")
|
||||
ada = Actor(client, "ada@example.test", "Ada")
|
||||
ada.login()
|
||||
alone = ada.request("POST", "/api/v1/matters", json={"title": "Ohne Akte"}, status=201)
|
||||
detail = ada.request("GET", f"/api/v1/matters/{alone['id']}")
|
||||
assert detail["case_links"] == []
|
||||
first = case_of(ada, "Erste Akte")
|
||||
second = case_of(ada, "Zweite Akte")
|
||||
version = alone["version"]
|
||||
ada.request("POST", f"/api/v1/matters/{alone['id']}/case-links", json={"case_id": first["id"]}, status=201)
|
||||
ada.request("POST", f"/api/v1/matters/{alone['id']}/case-links", json={"case_id": second["id"]}, status=201)
|
||||
linked = ada.request("GET", f"/api/v1/matters/{alone['id']}")
|
||||
assert linked["version"] == version
|
||||
assert {item["title"] for item in linked["case_links"]} == {"Erste Akte", "Zweite Akte"}
|
||||
@@ -0,0 +1,377 @@
|
||||
"""Raum als Team: Akten und Vorgänge werden mit Datenräumen geteilt, unabhängig vom Heimatraum."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from tests.support import PASSWORD, Actor, document, matter_of, note_on
|
||||
|
||||
|
||||
def _second_client():
|
||||
from app.main import app
|
||||
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _make(db, email: str, name: str):
|
||||
account = create_account(db, email, name, PASSWORD)
|
||||
db.commit()
|
||||
return account
|
||||
|
||||
|
||||
def _actor(client, db, key: str, email: str, *, main: bool = False) -> Actor:
|
||||
actor = Actor(client if main else _second_client(), email, key.title())
|
||||
_make(db, actor.email, actor.name)
|
||||
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 _share(actor: Actor, plural: str, resource_id: str, room: str, access: str = "edit", status: int = 200):
|
||||
return actor.request("PUT", f"/api/v1/{plural}/{resource_id}/room-share/rooms/{room}", json={"access": access}, status=status)
|
||||
|
||||
|
||||
def _unshare(actor: Actor, plural: str, resource_id: str, room: str, status: int = 204):
|
||||
return actor.request("DELETE", f"/api/v1/{plural}/{resource_id}/room-share/rooms/{room}", status=status)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def world(client, db):
|
||||
"""Ada owns the room; Ben is a member, Cem a reader, Dan is outside."""
|
||||
actors = {
|
||||
"ada": _actor(client, db, "ada", "ada-raum@example.test", main=True),
|
||||
"ben": _actor(client, db, "ben", "ben-raum@example.test"),
|
||||
"cem": _actor(client, db, "cem", "cem-raum@example.test"),
|
||||
"dan": _actor(client, db, "dan", "dan-raum@example.test"),
|
||||
}
|
||||
ada = actors["ada"]
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Werkstatt"}, status=201)
|
||||
assert room["default_visibility"] == "room"
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": actors["ben"].email, "role": "member"})
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": actors["cem"].email, "role": "reader"})
|
||||
ada.use_room(room["id"])
|
||||
actors["room"] = room["id"]
|
||||
return actors
|
||||
|
||||
|
||||
def test_a_new_entry_follows_the_room_preset_and_rights_follow_the_role(world, db):
|
||||
ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"]
|
||||
shared = ada.request("POST", "/api/v1/cases", json={"title": "Gemeinsame Akte"}, status=201)
|
||||
view = ada.request("GET", f"/api/v1/cases/{shared['id']}/room-share")
|
||||
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, "download": True,
|
||||
}
|
||||
assert cem.request("GET", f"/api/v1/cases/{shared['id']}")["rights"] == {
|
||||
"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"]}
|
||||
assert dan.request("GET", "/api/v1/cases")["items"] == []
|
||||
|
||||
version = ben.request("GET", f"/api/v1/cases/{shared['id']}")["version"]
|
||||
ben.request("PATCH", f"/api/v1/cases/{shared['id']}", json={"expected_version": version, "title": "Von Ben geändert"})
|
||||
cem.request("PATCH", f"/api/v1/cases/{shared['id']}", json={"expected_version": version + 1, "title": "Nein"}, status=403)
|
||||
ben.request("POST", f"/api/v1/cases/{shared['id']}/delete", json={"expected_version": version + 1}, status=403)
|
||||
ben.request("POST", f"/api/v1/cases/{shared['id']}/grants", json={"email": dan.email, "can_read": True}, status=403)
|
||||
|
||||
|
||||
def test_unsharing_and_leaving_take_the_rights_back_at_once(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Zeitweise sichtbar"}, status=201)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
_unshare(ada, "cases", case["id"], room)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
_share(ada, "cases", case["id"], room)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ada.request("DELETE", f"/api/v1/rooms/{room}/members/{_id(db, ben.email)}", status=204)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
assert ben.request("GET", "/api/v1/cases")["items"] == []
|
||||
|
||||
|
||||
def test_an_archived_room_shares_nothing_until_it_is_restored(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Archivtest"}, status=201)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
db.execute("UPDATE data_rooms SET status = 'archived' WHERE id = %s", (room,))
|
||||
db.commit()
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
db.execute("UPDATE data_rooms SET status = 'active' WHERE id = %s", (room,))
|
||||
db.commit()
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
|
||||
|
||||
def test_the_owner_sees_all_own_entries_whatever_happens_to_the_room(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
mine = ada.request("POST", "/api/v1/cases", json={"title": "Meine Akte im Raum"}, status=201)
|
||||
personal = Actor(ada.client, ada.email, ada.name)
|
||||
personal_body = personal.login()
|
||||
personal.request("POST", "/api/v1/cases", json={"title": "Meine persönliche Akte"}, status=201)
|
||||
# Ben owns an entry filed in the room; Ada, the owner of the room, does not see it.
|
||||
ben.use_room(room)
|
||||
bens = ben.request("POST", "/api/v1/cases", json={"title": "Bens Akte"}, status=201)
|
||||
|
||||
def titles(actor):
|
||||
return {item["title"] for item in actor.request("GET", "/api/v1/cases")["items"]}
|
||||
|
||||
assert {"Meine Akte im Raum", "Meine persönliche Akte"} <= titles(personal)
|
||||
assert "Bens Akte" in titles(personal) # shared with the room by the preset
|
||||
_unshare(ben, "cases", bens["id"], room)
|
||||
assert "Bens Akte" not in titles(personal)
|
||||
assert "Bens Akte" in titles(ben)
|
||||
|
||||
# Ben leaves the room, the room is archived: he still sees and edits what he owns.
|
||||
personal.request("DELETE", f"/api/v1/rooms/{room}/members/{_id(db, ben.email)}", status=204)
|
||||
# Ben's old room headers no longer fit his session; he is told to reload, then lists everything he owns.
|
||||
assert ben.request("GET", "/api/v1/cases", status=403)["code"] == "scope_changed"
|
||||
body = ben.request("GET", "/api/v1/auth/session")
|
||||
assert body["scope"]["kind"] == "personal"
|
||||
ben.scope, ben.csrf = body["scope"], body["csrf_token"]
|
||||
assert "Bens Akte" in titles(ben)
|
||||
ben.request("GET", f"/api/v1/cases/{bens['id']}")
|
||||
db.execute("UPDATE data_rooms SET status = 'archived' WHERE id = %s", (room,))
|
||||
db.commit()
|
||||
assert {"Meine Akte im Raum", "Meine persönliche Akte"} <= titles(personal)
|
||||
personal.request("GET", f"/api/v1/cases/{mine['id']}")
|
||||
assert personal_body["account"]["email"] == ada.email
|
||||
|
||||
|
||||
def test_one_member_can_be_excluded(world, db):
|
||||
ada, ben, cem, dan = world["ada"], world["ben"], world["cem"], world["dan"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Ohne Ben"}, status=201)
|
||||
view = ada.request("GET", f"/api/v1/cases/{case['id']}/room-share")
|
||||
assert {(m["display_name"], m["role"]) for m in view["shares"][0]["members"]} == {("Ben", "member"), ("Cem", "reader")}
|
||||
base = f"/api/v1/cases/{case['id']}/room-share/people"
|
||||
ada.request("PUT", f"{base}/{_id(db, ben.email)}", json={"excluded": True})
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
cem.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
assert any(m["excluded"] for m in ada.request("GET", f"/api/v1/cases/{case['id']}/room-share")["shares"][0]["members"])
|
||||
ada.request("PUT", f"{base}/{_id(db, ben.email)}", json={"excluded": False})
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
ada.request("PUT", f"{base}/{_id(db, ada.email)}", json={"excluded": True}, status=422)
|
||||
ada.request("PUT", f"{base}/{_id(db, dan.email)}", json={"excluded": True}, status=404)
|
||||
ben.request("PUT", f"{base}/{_id(db, cem.email)}", json={"excluded": True}, status=404)
|
||||
|
||||
|
||||
def test_contents_follow_the_room_role(world, db):
|
||||
ada, ben, cem, dan = world["ada"], world["ben"], world["cem"], world["dan"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Akte mit Notiz"}, status=201)
|
||||
note = note_on(ada, "Notiz in der Akte", "Raumtext", case["id"])
|
||||
detail = ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
assert any(b["element"]["title"] == "Notiz in der Akte" for b in detail["bindings"])
|
||||
context = {"kind": "case", "id": case["id"]}
|
||||
ben.request("PATCH", f"/api/v1/notes/{note['id']}", json={"expected_version": note["version"], "document": document("Von Ben ergänzt"), "context": context})
|
||||
cem.request("PATCH", f"/api/v1/notes/{note['id']}", json={"expected_version": note["version"] + 1, "document": document("Nein"), "context": context}, status=403)
|
||||
dan.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
assert dan.request("GET", "/api/v1/search", params={"q": "Notiz in der Akte"})["items"] == []
|
||||
assert any(i["title"] == "Notiz in der Akte" for i in cem.request("GET", "/api/v1/search", params={"q": "Notiz in der Akte"})["items"])
|
||||
|
||||
|
||||
def test_a_standalone_matter_is_shared_like_a_case(world, db):
|
||||
ada, ben, cem, room = world["ada"], world["ben"], world["cem"], world["room"]
|
||||
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, "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)
|
||||
ben.request("GET", f"/api/v1/matters/{matter['id']}", status=404)
|
||||
assert "Eigener Vorgang" not in {item["title"] for item in ben.request("GET", "/api/v1/matters")["items"]}
|
||||
|
||||
|
||||
def test_subcases_follow_their_parent(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
parent = ada.request("POST", "/api/v1/cases", json={"title": "Eltern"}, status=201)
|
||||
child = ada.request(
|
||||
"POST", "/api/v1/cases",
|
||||
json={"title": "Kind", "parent_case_id": parent["id"], "rights_mode": "inherit_parent"}, status=201,
|
||||
)
|
||||
ben.request("GET", f"/api/v1/cases/{child['id']}")
|
||||
_unshare(ada, "cases", parent["id"], room)
|
||||
_unshare(ada, "cases", child["id"], room)
|
||||
ben.request("GET", f"/api/v1/cases/{child['id']}", status=404)
|
||||
|
||||
|
||||
def test_an_entry_in_the_personal_room_can_be_shared_with_a_team(world, db):
|
||||
ada, ben, dan, room = world["ada"], world["ben"], world["dan"], world["room"]
|
||||
personal = Actor(ada.client, ada.email, ada.name)
|
||||
personal.login()
|
||||
case = personal.request("POST", "/api/v1/cases", json={"title": "Aus dem persönlichen Raum"}, status=201)
|
||||
assert personal.request("GET", f"/api/v1/cases/{case['id']}/room-share")["shares"] == []
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
shared = personal.request("GET", f"/api/v1/cases/{case['id']}/room-share")
|
||||
assert [item["name"] for item in shared["available"]] == ["Werkstatt"]
|
||||
_share(personal, "cases", case["id"], room)
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
dan.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
|
||||
|
||||
def test_one_matter_goes_to_the_lawyer_and_the_rest_of_the_case_stays_hidden(client, db):
|
||||
ada = _actor(client, db, "ada", "ada-anwalt@example.test", main=True)
|
||||
lawyer = _actor(client, db, "anwalt", "anwalt@example.test")
|
||||
team = ada.request("POST", "/api/v1/rooms", json={"name": "Anwalt Müller", "default_visibility": "private"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{team['id']}/members", json={"email": lawyer.email, "role": "member"})
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Vermietung"}, status=201)
|
||||
shared = ada.request("POST", "/api/v1/matters", json={"title": "Mietminderung"}, status=201)
|
||||
hidden = ada.request("POST", "/api/v1/matters", json={"title": "Eigenbedarf intern"}, status=201)
|
||||
for matter in (shared, hidden):
|
||||
ada.request("POST", f"/api/v1/matters/{matter['id']}/case-links", json={"case_id": case["id"]}, status=201)
|
||||
note_on(ada, "Schreiben des Mieters", "Minderung", case["id"])
|
||||
_share(ada, "matters", shared["id"], team["id"], access="edit")
|
||||
|
||||
lawyer.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
assert lawyer.request("GET", "/api/v1/cases")["items"] == []
|
||||
listed = {item["title"] for item in lawyer.request("GET", "/api/v1/matters")["items"]}
|
||||
assert listed == {"Mietminderung"}
|
||||
lawyer.request("GET", f"/api/v1/matters/{hidden['id']}", status=404)
|
||||
assert lawyer.request("GET", f"/api/v1/matters/{shared['id']}")["rights"]["edit"] is True
|
||||
|
||||
|
||||
def test_the_share_caps_the_role_and_several_rooms_add_up(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
other = ada.request("POST", "/api/v1/rooms", json={"name": "Zweites Team", "default_visibility": "private"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{other['id']}/members", json={"email": ben.email, "role": "member"})
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Begrenzt"}, status=201)
|
||||
_share(ada, "cases", case["id"], room, access="read")
|
||||
assert ben.request("GET", f"/api/v1/cases/{case['id']}")["rights"]["edit"] is False
|
||||
_share(ada, "cases", case["id"], other["id"], access="edit")
|
||||
assert ben.request("GET", f"/api/v1/cases/{case['id']}")["rights"]["edit"] is True
|
||||
_unshare(ada, "cases", case["id"], other["id"])
|
||||
assert ben.request("GET", f"/api/v1/cases/{case['id']}")["rights"]["edit"] is False
|
||||
_unshare(ada, "cases", case["id"], other["id"], status=404)
|
||||
|
||||
|
||||
def test_only_the_owner_shares_and_only_into_rooms_where_he_writes(world, db):
|
||||
ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Nur Ada teilt"}, status=201)
|
||||
ben.request("PUT", f"/api/v1/cases/{case['id']}/room-share/rooms/{room}", json={"access": "edit"}, status=404)
|
||||
ben.request("DELETE", f"/api/v1/cases/{case['id']}/room-share/rooms/{room}", status=404)
|
||||
bens = ben.request("GET", "/api/v1/auth/session") # Ben may share his own entries into rooms he writes in
|
||||
assert any(r["id"] == room for r in bens["rooms"])
|
||||
ben.use_room(room)
|
||||
own = ben.request("POST", "/api/v1/cases", json={"title": "Bens"}, status=201)
|
||||
# A reader may not share into the room; an outsider cannot even see it.
|
||||
cem.use_room(room)
|
||||
cem_own = Actor(cem.client, cem.email, cem.name)
|
||||
cem_own.login()
|
||||
mine = cem_own.request("POST", "/api/v1/cases", json={"title": "Von Cem"}, status=201)
|
||||
cem_own.request("PUT", f"/api/v1/cases/{mine['id']}/room-share/rooms/{room}", json={"access": "edit"}, status=403)
|
||||
dan_own = Actor(dan.client, dan.email, dan.name)
|
||||
dan_own.login()
|
||||
theirs = dan_own.request("POST", "/api/v1/cases", json={"title": "Von Dan"}, status=201)
|
||||
dan_own.request("PUT", f"/api/v1/cases/{theirs['id']}/room-share/rooms/{room}", json={"access": "edit"}, status=403)
|
||||
assert own["title"] == "Bens"
|
||||
|
||||
|
||||
def test_leaving_the_team_takes_the_own_shares_along(world, db):
|
||||
ada, ben, cem, room = world["ada"], world["ben"], world["cem"], world["room"]
|
||||
ben.use_room(room)
|
||||
bens = ben.request("POST", "/api/v1/cases", json={"title": "Bens Freigabe"}, status=201)
|
||||
cem.request("GET", f"/api/v1/cases/{bens['id']}")
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{_id(db, ben.email)}", json={"role": "reader"})
|
||||
cem.request("GET", f"/api/v1/cases/{bens['id']}", status=404)
|
||||
ben.request("GET", f"/api/v1/cases/{bens['id']}")
|
||||
|
||||
|
||||
def test_the_bulk_action_and_the_exposure_count_own_entries(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
old = ada.request("POST", "/api/v1/cases", json={"title": "Bestand"}, status=201)
|
||||
db.execute("DELETE FROM room_shares WHERE resource_id = %s", (old["id"],))
|
||||
db.commit()
|
||||
ben.request("GET", f"/api/v1/cases/{old['id']}", status=404)
|
||||
assert ada.request("GET", f"/api/v1/rooms/{room}/exposure")["cases"] == {"room": 0, "private": 1}
|
||||
assert ada.request("POST", f"/api/v1/rooms/{room}/my-content/visibility", json={"visibility": "room"}) == {"changed": 1}
|
||||
ben.request("GET", f"/api/v1/cases/{old['id']}")
|
||||
assert ada.request("GET", f"/api/v1/rooms/{room}/exposure")["cases"] == {"room": 1, "private": 0}
|
||||
ben.use_room(room)
|
||||
theirs = ben.request("POST", "/api/v1/cases", json={"title": "Bens"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/my-content/visibility", json={"visibility": "private"})
|
||||
ben.request("GET", f"/api/v1/cases/{old['id']}", status=404)
|
||||
ben.request("GET", f"/api/v1/cases/{theirs['id']}")
|
||||
world["dan"].request("GET", f"/api/v1/rooms/{room}/exposure", status=403)
|
||||
|
||||
|
||||
def test_a_room_can_start_without_sharing(client, db):
|
||||
ada = _actor(client, db, "ada", "ada-start@example.test", main=True)
|
||||
ben = _actor(client, db, "ben", "ben-start@example.test")
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Privat", "default_visibility": "private"}, status=201)
|
||||
ada.use_room(room["id"])
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Nur ich"}, status=201)
|
||||
ada.request("POST", f"/api/v1/rooms/{room['id']}/members", json={"email": ben.email, "role": "member"})
|
||||
ben.request("GET", f"/api/v1/cases/{case['id']}", status=404)
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room['id']}", json={"default_visibility": "room"})
|
||||
other = ada.request("POST", "/api/v1/cases", json={"title": "Jetzt geteilt"}, status=201)
|
||||
ben.request("GET", f"/api/v1/cases/{other['id']}")
|
||||
ben.request("PATCH", f"/api/v1/rooms/{room['id']}", json={"default_visibility": "private"}, status=403)
|
||||
|
||||
|
||||
def test_lists_tell_the_owner_what_is_shared_and_rooms_are_managed_from_any_room(world, db):
|
||||
ada, ben, room = world["ada"], world["ben"], world["room"]
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Liste"}, status=201)
|
||||
item = next(i for i in ada.request("GET", "/api/v1/cases")["items"] if i["id"] == case["id"])
|
||||
assert item["is_owner"] is True and [s["name"] for s in item["shared_with"]] == ["Werkstatt"]
|
||||
seen = next(i for i in ben.request("GET", "/api/v1/cases")["items"] if i["id"] == case["id"])
|
||||
assert seen["is_owner"] is False and seen["shared_with"] == []
|
||||
matter = matter_of(ada, "Listenvorgang")
|
||||
row = next(i for i in ada.request("GET", "/api/v1/matters")["items"] if i["id"] == matter["id"])
|
||||
assert row["is_owner"] is True and [s["name"] for s in row["shared_with"]] == ["Werkstatt"]
|
||||
|
||||
# The owner manages the team while working in the personal room, without switching.
|
||||
personal = Actor(ada.client, ada.email, ada.name)
|
||||
body = personal.login()
|
||||
assert body["scope"]["kind"] == "personal"
|
||||
members = personal.request("GET", f"/api/v1/rooms/{room}/members")["items"]
|
||||
assert {m["role"] for m in members} == {"manager", "member", "reader"}
|
||||
personal.request("PATCH", f"/api/v1/rooms/{room}/members/{_id(db, ben.email)}", json={"role": "reader"})
|
||||
personal.request("PATCH", f"/api/v1/rooms/{room}", json={"name": "Werkstatt neu"})
|
||||
assert [r["name"] for r in personal.request("GET", "/api/v1/rooms")["items"] if r["id"] == room] == ["Werkstatt neu"]
|
||||
|
||||
|
||||
def test_room_endpoints_are_closed_to_outsiders_and_do_not_reveal_which_ids_exist(world, db):
|
||||
import uuid
|
||||
|
||||
ada, ben, cem, dan, room = world["ada"], world["ben"], world["cem"], world["dan"], world["room"]
|
||||
foreign = str(uuid.uuid4())
|
||||
dan_id = _id(db, dan.email)
|
||||
ben_id = _id(db, ben.email)
|
||||
attempts = [
|
||||
("GET", "/members", None),
|
||||
("POST", "/members", {"email": dan.email, "role": "manager"}),
|
||||
("PATCH", f"/members/{ben_id}", {"role": "manager"}),
|
||||
("DELETE", f"/members/{ben_id}", None),
|
||||
("GET", "/invitations", None),
|
||||
("PATCH", "", {"name": "Übernommen"}),
|
||||
("POST", "/owner", {"subject_id": dan_id}),
|
||||
("GET", "/exposure", None),
|
||||
("POST", "/my-content/visibility", {"visibility": "room"}),
|
||||
]
|
||||
for method, suffix, body in attempts:
|
||||
# Dan is no member, Cem is a reader, Ben a plain member: none of them administers the room.
|
||||
for actor in (dan, cem, ben):
|
||||
if method == "GET" and suffix == "/exposure" and actor in (cem, ben):
|
||||
continue # members may read their own exposure counts
|
||||
if method == "POST" and suffix == "/my-content/visibility" and actor is ben:
|
||||
continue # members may share their own entries
|
||||
actor.request(method, f"/api/v1/rooms/{room}{suffix}", json=body, status=403)
|
||||
# A room that does not exist answers like a room that is closed to the caller.
|
||||
dan.request(method, f"/api/v1/rooms/{foreign}{suffix.replace(ben_id, dan_id)}", json=body, status=403)
|
||||
dan.request("POST", "/api/v1/invitations", json={"email": "x@example.test", "room_id": room}, status=403)
|
||||
dan.request("POST", "/api/v1/invitations", json={"email": "x@example.test", "room_id": foreign}, status=403)
|
||||
dan.request("GET", "/api/v1/admin/rooms", status=403)
|
||||
dan.request("POST", f"/api/v1/admin/rooms/{room}/owner", json={"email": dan.email}, status=403)
|
||||
dan.request("GET", "/api/v1/admin/events", status=403)
|
||||
# Nothing changed.
|
||||
members = ada.request("GET", f"/api/v1/rooms/{room}/members")["items"]
|
||||
assert {m["email"]: m["role"] for m in members}[ben.email] == "member"
|
||||
assert dan.email not in {m["email"] for m in members}
|
||||
assert db.execute("SELECT name FROM data_rooms WHERE id = %s", (room,)).fetchone()["name"] == "Werkstatt"
|
||||
db.rollback()
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Datenraumrollen (Mitglied, Verwalter, Leser), Einladungen, Betreiberübersicht."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from tests.support import ORIGIN, PASSWORD, Actor, register
|
||||
|
||||
|
||||
def _second_client():
|
||||
from app.main import app
|
||||
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _setup(client, db):
|
||||
ada = Actor(client, "ada-rolle@example.test", "Ada Rolle")
|
||||
ben = Actor(_second_client(), "ben-rolle@example.test", "Ben Rolle")
|
||||
cem = Actor(_second_client(), "cem-rolle@example.test", "Cem Rolle")
|
||||
for actor in (ada, ben, cem):
|
||||
register(db, actor.email, actor.name)
|
||||
actor.login()
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Verein"}, status=201)
|
||||
ada.use_room(room["id"])
|
||||
return ada, ben, cem, room["id"]
|
||||
|
||||
|
||||
def test_manager_sets_roles_and_a_reader_creates_nothing(client, db):
|
||||
ada, ben, cem, room = _setup(client, db)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "reader"})
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": cem.email, "role": "member"})
|
||||
members = {item["email"]: item["role"] for item in ada.request("GET", f"/api/v1/rooms/{room}/members")["items"]}
|
||||
assert members == {ada.email: "manager", ben.email: "reader", cem.email: "member"}
|
||||
|
||||
ben.use_room(room)
|
||||
cem.use_room(room)
|
||||
refused = ben.request("POST", "/api/v1/cases", json={"title": "Nicht erlaubt"}, status=403)
|
||||
assert "Leser" in refused["detail"]
|
||||
ben.request("POST", "/api/v1/matters", json={"title": "Auch nicht"}, status=403)
|
||||
cem.request("POST", "/api/v1/cases", json={"title": "Erlaubt"}, status=201)
|
||||
|
||||
# The role is read from the database at every request.
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{_subject(ada, room, ben.email)}", json={"role": "member"})
|
||||
ben.request("POST", "/api/v1/cases", json={"title": "Jetzt erlaubt"}, status=201)
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{_subject(ada, room, ben.email)}", json={"role": "reader"})
|
||||
ben.request("POST", "/api/v1/cases", json={"title": "Wieder nicht"}, status=403)
|
||||
|
||||
|
||||
def test_a_reader_gets_no_edit_grant_and_loses_existing_ones(client, db):
|
||||
ada, ben, cem, room = _setup(client, db)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "member"})
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": cem.email, "role": "reader"})
|
||||
case = ada.request("POST", "/api/v1/cases", json={"title": "Gemeinsam"}, status=201)
|
||||
refused = ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case['id']}/grants",
|
||||
json={"email": cem.email, "can_read": True, "can_edit": True, "can_share": False},
|
||||
status=422,
|
||||
)
|
||||
assert "Leser" in refused["detail"]
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case['id']}/grants",
|
||||
json={"email": cem.email, "can_read": True, "can_edit": False, "can_share": False},
|
||||
status=201,
|
||||
)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/cases/{case['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": True, "can_share": True},
|
||||
status=201,
|
||||
)
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{_subject(ada, room, ben.email)}", json={"role": "reader"})
|
||||
grant = db.execute(
|
||||
"SELECT can_read, can_edit, can_share FROM access_grants WHERE grantee_subject_id = (SELECT id FROM auth_accounts WHERE email = %s)",
|
||||
(ben.email,),
|
||||
).fetchone()
|
||||
db.rollback()
|
||||
assert grant == {"can_read": True, "can_edit": False, "can_share": False}
|
||||
|
||||
|
||||
def test_the_last_manager_stays(client, db):
|
||||
ada, ben, _cem, room = _setup(client, db)
|
||||
me = _subject(ada, room, ada.email)
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{me}", json={"role": "member"}, status=422)
|
||||
ada.request("DELETE", f"/api/v1/rooms/{room}/members/{me}", status=422)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ada.email, "role": "reader"}, status=422)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "manager"})
|
||||
# Ada owns the room and stays manager until she hands it over.
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{me}", json={"role": "member"}, status=422)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": _subject(ada, room, ben.email)})
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}/members/{me}", json={"role": "member"})
|
||||
# Ben is owner and the only manager now.
|
||||
ben.use_room(room)
|
||||
ben.request("DELETE", f"/api/v1/rooms/{room}/members/{_subject(ben, room, ben.email)}", status=422)
|
||||
ada.request("GET", f"/api/v1/rooms/{room}/members", status=403)
|
||||
|
||||
|
||||
def test_owner_transfer_and_operator_step_in(client, db):
|
||||
ada, ben, cem, room = _setup(client, db)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "member"})
|
||||
ben.use_room(room)
|
||||
ben_id = _subject(ben, room, ben.email)
|
||||
ben.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": ben_id}, status=403)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": _subject(ada, room, cem.email)}, status=422)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": _subject(ada, room, ada.email)}, status=422)
|
||||
# Ada cannot leave or be demoted while she owns the room, and cannot be disabled while members depend on it.
|
||||
ada_id = _subject(ada, room, ada.email)
|
||||
db.execute("UPDATE auth_accounts SET origin = 'operator' WHERE id = %s", (ada_id,))
|
||||
db.commit()
|
||||
operator = Actor(_second_client(), "betreiber-eigner@example.test", "Betreiber Eigner")
|
||||
register(db, operator.email, operator.name, superadmin=True)
|
||||
operator.login()
|
||||
operator.request("PATCH", f"/api/v1/accounts/{ada_id}", json={"status": "disabled"}, status=422)
|
||||
operator.request("POST", f"/api/v1/admin/rooms/{room}/owner", json={"email": ben.email}, status=403)
|
||||
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": ben_id})
|
||||
ben.request("GET", f"/api/v1/rooms/{room}/members")
|
||||
owners = [r for r in ben.request("GET", "/api/v1/auth/session")["rooms"] if r["id"] == room]
|
||||
assert owners[0]["is_owner"] is True
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}", json={"status": "archived"}, status=403)
|
||||
ben.request("PATCH", f"/api/v1/rooms/{room}", json={"default_visibility": "private"})
|
||||
|
||||
# The old owner may be disabled now; the room keeps its owner. A disabled owner is replaced by the operator.
|
||||
operator.request("PATCH", f"/api/v1/accounts/{ada_id}", json={"status": "disabled"})
|
||||
db.execute("UPDATE data_rooms SET owner_id = %s WHERE id = %s", (ada_id, room))
|
||||
db.commit()
|
||||
stepped = operator.request("POST", f"/api/v1/admin/rooms/{room}/owner", json={"email": ben.email})
|
||||
assert stepped["owner_id"] == ben_id
|
||||
events = operator.request("GET", "/api/v1/admin/events", params={"limit": 100})["items"]
|
||||
assert "room_owner_changed" in [item["action"] for item in events]
|
||||
|
||||
|
||||
def test_a_removed_member_loses_the_room_at_once(client, db):
|
||||
ada, ben, _cem, room = _setup(client, db)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "member"})
|
||||
ben.use_room(room)
|
||||
ben.request("GET", "/api/v1/cases")
|
||||
ada.request("DELETE", f"/api/v1/rooms/{room}/members/{_subject(ada, room, ben.email)}", status=204)
|
||||
ben.request("GET", "/api/v1/cases", status=403)
|
||||
|
||||
|
||||
def test_invitations_carry_a_role_and_can_be_revoked(client, db):
|
||||
ada, ben, _cem, room = _setup(client, db)
|
||||
invited = ada.request(
|
||||
"POST",
|
||||
"/api/v1/invitations",
|
||||
json={"email": "neu-rolle@example.test", "room_id": room, "role": "reader"},
|
||||
status=201,
|
||||
)
|
||||
assert invited["role"] == "reader" and invited["token"]
|
||||
ada.request("POST", "/api/v1/invitations", json={"email": ben.email, "room_id": room}, status=422)
|
||||
open_items = ada.request("GET", f"/api/v1/rooms/{room}/invitations")["items"]
|
||||
assert [item["email"] for item in open_items] == ["neu-rolle@example.test"]
|
||||
assert "token" not in open_items[0]
|
||||
ben.request("GET", f"/api/v1/rooms/{room}/invitations", status=403)
|
||||
|
||||
guest = _second_client()
|
||||
accepted = guest.post(
|
||||
f"/api/v1/invitations/{invited['id']}/accept",
|
||||
json={"token": invited["token"], "display_name": "Neu Gast", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert accepted.status_code == 201, accepted.text
|
||||
assert [(r["name"], r["role"]) for r in accepted.json()["rooms"] if r["kind"] == "organization"] == [("Verein", "reader")]
|
||||
again = _second_client().post(
|
||||
f"/api/v1/invitations/{invited['id']}/accept",
|
||||
json={"token": invited["token"], "display_name": "Zweiter", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert again.status_code == 404
|
||||
|
||||
second = ada.request("POST", "/api/v1/invitations", json={"email": "widerruf@example.test", "room_id": room}, status=201)
|
||||
ada.request("DELETE", f"/api/v1/rooms/{room}/invitations/{second['id']}", status=204)
|
||||
refused = _second_client().post(
|
||||
f"/api/v1/invitations/{second['id']}/accept",
|
||||
json={"token": second["token"], "display_name": "Widerruf", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert refused.status_code == 404
|
||||
ada.request("DELETE", f"/api/v1/rooms/{room}/invitations/{second['id']}", status=404)
|
||||
|
||||
|
||||
def test_rooms_are_renamed_archived_and_restored_by_a_manager(client, db):
|
||||
ada, ben, _cem, room = _setup(client, db)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "member"})
|
||||
ben.request("PATCH", f"/api/v1/rooms/{room}", json={"name": "Fremd"}, status=403)
|
||||
renamed = ada.request("PATCH", f"/api/v1/rooms/{room}", json={"name": "Verein e.V."})
|
||||
assert renamed["name"] == "Verein e.V."
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}", json={"status": "archived"})
|
||||
# The session of the archiving manager moved back to the personal room.
|
||||
ada.request("GET", "/api/v1/rooms", status=403)
|
||||
body = ada.request("GET", "/api/v1/auth/session")
|
||||
assert body["scope"]["kind"] == "personal"
|
||||
ada.scope, ada.csrf = body["scope"], body["csrf_token"]
|
||||
listed = ada.request("GET", "/api/v1/rooms", params={"include_archived": "true"})["items"]
|
||||
assert any(item["id"] == room and item.get("status") == "archived" for item in listed)
|
||||
ada.request("POST", "/api/v1/auth/session/scope", json={"kind": "organization", "id": room}, status=403)
|
||||
ada.request("PATCH", f"/api/v1/rooms/{room}", json={"status": "active"})
|
||||
ada.use_room(room)
|
||||
|
||||
|
||||
def test_operator_sees_rooms_without_content_and_fills_an_orphaned_room(client, db):
|
||||
ada, ben, _cem, room = _setup(client, db)
|
||||
operator = Actor(_second_client(), "betreiber-rolle@example.test", "Betreiber Rolle")
|
||||
register(db, operator.email, operator.name, superadmin=True)
|
||||
operator.login()
|
||||
ada.request("POST", "/api/v1/cases", json={"title": "Nur für Ada"}, status=201)
|
||||
overview = operator.request("GET", "/api/v1/admin/rooms")["items"]
|
||||
row = next(item for item in overview if item["id"] == room)
|
||||
assert row["managers"] == ["Ada Rolle"] and row["members"] == 1 and row["has_manager"] is True
|
||||
assert row["owner"] == "Ada Rolle" and row["owner_active"] is True
|
||||
assert "Nur für Ada" not in str(overview)
|
||||
operator.request("GET", f"/api/v1/rooms/{room}/members", status=403)
|
||||
ben.request("GET", "/api/v1/admin/rooms", status=403)
|
||||
operator.request("POST", f"/api/v1/admin/rooms/{room}/managers", json={"email": ben.email}, status=403)
|
||||
|
||||
db.execute("UPDATE auth_accounts SET status = 'disabled' WHERE email = %s", (ada.email,))
|
||||
db.commit()
|
||||
assigned = operator.request("POST", f"/api/v1/admin/rooms/{room}/managers", json={"email": ben.email})
|
||||
assert assigned["role"] == "manager"
|
||||
ben.use_room(room)
|
||||
assert {item["email"] for item in ben.request("GET", f"/api/v1/rooms/{room}/members")["items"]} >= {ben.email}
|
||||
|
||||
|
||||
def test_room_events_reach_the_operator_audit_without_secrets(client, db):
|
||||
ada, ben, _cem, room = _setup(client, db)
|
||||
operator = Actor(_second_client(), "audit-rolle@example.test", "Audit Rolle")
|
||||
register(db, operator.email, operator.name, superadmin=True)
|
||||
operator.login()
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "reader"})
|
||||
invited = ada.request("POST", "/api/v1/invitations", json={"email": "audit-gast@example.test", "room_id": room}, status=201)
|
||||
events = operator.request("GET", "/api/v1/admin/events", params={"limit": 50})
|
||||
actions = [item["action"] for item in events["items"]]
|
||||
assert {"room_created", "membership_added", "invitation_created"} <= set(actions)
|
||||
text = str(events)
|
||||
assert "audit-gast@example.test" not in text and invited["token"] not in text
|
||||
ben.request("GET", "/api/v1/admin/events", status=403)
|
||||
page = operator.request("GET", "/api/v1/admin/events", params={"limit": 1})
|
||||
assert len(page["items"]) == 1 and page["next_cursor"] == 1
|
||||
|
||||
|
||||
def _subject(actor: Actor, room: str, email: str) -> str:
|
||||
# A manager lists the members; Ada manages in these tests. Fall back to the account table.
|
||||
from app.core.settings import get_settings
|
||||
import psycopg
|
||||
|
||||
with psycopg.connect(get_settings().dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
||||
return str(conn.execute("SELECT id FROM auth_accounts WHERE email = %s", (email,)).fetchone()["id"])
|
||||
@@ -0,0 +1,226 @@
|
||||
"""A third source appears only by registering its module."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.sample_source import install_sample_source, remove_sample_source
|
||||
from tests.support import ORIGIN, Actor, document, register
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TEXT = "Der Probenbrief bleibt lesbar."
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_source():
|
||||
install_sample_source()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
remove_sample_source()
|
||||
|
||||
|
||||
def test_registered_sample_source_links_reads_and_exports(client, db, sample_source):
|
||||
del sample_source
|
||||
ada = Actor(client, "ada-sample@example.test", "Ada Probe")
|
||||
ben = Actor(client, "ben-sample@example.test", "Ben Probe")
|
||||
register(db, ada.email, ada.name)
|
||||
register(db, ben.email, ben.name)
|
||||
ada.login()
|
||||
refused = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "missing", "name": "Unbekannt"},
|
||||
status=422,
|
||||
)
|
||||
assert refused["code"] == "unprocessable"
|
||||
ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "sample", "name": "Ohne Katalog", "config": {"catalog": "kein-katalog"}},
|
||||
status=422,
|
||||
)
|
||||
connector_id = ada.request(
|
||||
"POST",
|
||||
"/api/v1/connectors",
|
||||
json={"kind": "sample", "name": "Katalog Alpha", "config": {"catalog": "alpha"}},
|
||||
status=201,
|
||||
)["id"]
|
||||
probed = ada.request("POST", f"/api/v1/connectors/{connector_id}/probe")
|
||||
assert probed["ok"] is True
|
||||
assert "2 Einträge" in probed["detail"]
|
||||
blocked = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/sample/search",
|
||||
params={"q": "Probe", "correspondent": "geheim-wert"},
|
||||
status=422,
|
||||
)
|
||||
assert blocked["code"] == "unsupported"
|
||||
assert "geheim-wert" not in blocked["detail"]
|
||||
ada.request("GET", "/api/v1/sources/sample/navigate", params={"connector_id": connector_id}, status=422)
|
||||
found = ada.request("GET", "/api/v1/sources/sample/search", params={"q": "Proben", "connector_id": connector_id})
|
||||
assert [item["id"] for item in found["items"]] == ["brief"]
|
||||
preview = ada.request(
|
||||
"GET",
|
||||
"/api/v1/sources/sample/preview",
|
||||
params={"connector_id": connector_id, "item": "brief"},
|
||||
)
|
||||
assert preview["text"] == TEXT
|
||||
matter = ada.request("POST", "/api/v1/matters", json={"title": "Probenvorgang"}, status=201)
|
||||
linked = ada.request(
|
||||
"POST",
|
||||
"/api/v1/external-refs",
|
||||
json={
|
||||
"title": "Probenbrief",
|
||||
"source": "sample",
|
||||
"external_id": "brief",
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
"detail": {"connector_id": connector_id},
|
||||
},
|
||||
status=201,
|
||||
)
|
||||
opened = _raw(ada, f"/api/v1/external-refs/{linked['id']}/content?context_kind=matter&context_id={matter['id']}")
|
||||
assert opened.status_code == 200
|
||||
assert opened.content == TEXT.encode("utf-8")
|
||||
assert opened.headers["content-type"].startswith("text/plain")
|
||||
detail = ada.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
element = next(item["element"] for item in detail["bindings"] if item["element"]["id"] == linked["id"])
|
||||
assert element["preview"]["media"] == "text"
|
||||
written = ada.request(
|
||||
"PATCH",
|
||||
f"/api/v1/notes/{linked['id']}",
|
||||
json={
|
||||
"expected_version": element["version"],
|
||||
"document": document("Das darf nicht geschrieben werden."),
|
||||
"context": {"kind": "matter", "id": matter["id"]},
|
||||
},
|
||||
status=422,
|
||||
)
|
||||
assert written["code"] == "unsupported"
|
||||
tree = ada.request("GET", f"/api/v1/matters/{matter['id']}/export-tree")["tree"]
|
||||
selected = [node["id"] for node in _walk(tree) if node["kind"] == "binding" and node.get("exportable")]
|
||||
body = {"context": {"kind": "matter", "id": matter["id"]}, "selected": selected}
|
||||
review = ada.request("POST", f"/api/v1/matters/{matter['id']}/export/review", json=body)
|
||||
assert review["ready"] is True, review
|
||||
package = _post_zip(ada, matter["id"], body)
|
||||
assert package.status_code == 200, package.text
|
||||
archive = zipfile.ZipFile(io.BytesIO(package.content))
|
||||
assert any(archive.read(name) == TEXT.encode("utf-8") for name in archive.namelist())
|
||||
|
||||
ben.login()
|
||||
ben.request(
|
||||
"GET",
|
||||
"/api/v1/sources/sample/search",
|
||||
params={"connector_id": connector_id, "q": "Proben"},
|
||||
status=404,
|
||||
)
|
||||
hidden = _raw(ben, f"/api/v1/external-refs/{linked['id']}/content?context_kind=matter&context_id={matter['id']}")
|
||||
assert hidden.status_code == 404
|
||||
ada.login()
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": False},
|
||||
status=201,
|
||||
)
|
||||
ben.login()
|
||||
denied = _raw(ben, f"/api/v1/external-refs/{linked['id']}/content?context_kind=matter&context_id={matter['id']}")
|
||||
assert denied.status_code == 422
|
||||
assert denied.json()["detail"] == "Das Original ist über die Freigabe nicht abrufbar."
|
||||
ada.login()
|
||||
grant_id = next(item["id"] for item in ada.request("GET", f"/api/v1/matters/{matter['id']}")["grants"])
|
||||
ada.request("DELETE", f"/api/v1/grants/{grant_id}", status=204)
|
||||
ada.request(
|
||||
"POST",
|
||||
f"/api/v1/matters/{matter['id']}/grants",
|
||||
json={"email": ben.email, "can_read": True, "can_edit": False, "can_share": False, "use_owner_sources": True},
|
||||
status=201,
|
||||
)
|
||||
ben.login()
|
||||
shared = _raw(ben, f"/api/v1/external-refs/{linked['id']}/content?context_kind=matter&context_id={matter['id']}")
|
||||
assert shared.status_code == 200
|
||||
assert shared.content == TEXT.encode("utf-8")
|
||||
shown = ben.request("GET", f"/api/v1/matters/{matter['id']}")
|
||||
visible = next(item["element"] for item in shown["bindings"] if item["element"]["id"] == linked["id"])
|
||||
assert "connector_id" not in (visible["external"].get("detail") or {})
|
||||
ada.login()
|
||||
grant_id = next(item["id"] for item in ada.request("GET", f"/api/v1/matters/{matter['id']}")["grants"])
|
||||
ada.request("DELETE", f"/api/v1/grants/{grant_id}", status=204)
|
||||
ben.login()
|
||||
revoked = _raw(ben, f"/api/v1/external-refs/{linked['id']}/content?context_kind=matter&context_id={matter['id']}")
|
||||
assert revoked.status_code == 404
|
||||
|
||||
|
||||
def test_sample_registration_does_not_edit_generic_modules():
|
||||
forbidden = [
|
||||
"backend/app/api/schemas.py",
|
||||
"backend/app/exporting.py",
|
||||
"backend/app/present.py",
|
||||
"frontend/src/pages/Cases.jsx",
|
||||
"frontend/src/pages/Matters.jsx",
|
||||
"frontend/src/pages/ReadingPane.jsx",
|
||||
"frontend/src/pages/ExportPackage.jsx",
|
||||
"frontend/src/App.jsx",
|
||||
"frontend/src/pages/Sources.jsx",
|
||||
]
|
||||
for relative in forbidden:
|
||||
text = (ROOT / relative).read_text(encoding="utf-8")
|
||||
assert '"sample"' not in text and "'sample'" not in text, relative
|
||||
# The backend image that runs this suite has no Node. The sample module is
|
||||
# small enough to check against the registry operations it calls.
|
||||
sample = (ROOT / "frontend/src/sources/sample-source.js").read_text(encoding="utf-8")
|
||||
registry = (ROOT / "frontend/src/sources/registry-core.js").read_text(encoding="utf-8")
|
||||
assert "registerSourceModule" in sample and "unregisterSourceModule" in sample
|
||||
assert 'kind: "sample"' in sample and 'representation: "text"' in sample
|
||||
assert 'unregisterSourceModule("sample")' in sample
|
||||
assert "modules.set(module.kind, module)" in registry
|
||||
assert "modules.delete(kind)" in registry
|
||||
modules: dict[str, dict] = {}
|
||||
|
||||
def register(module: dict) -> dict:
|
||||
modules[module["kind"]] = module
|
||||
return module
|
||||
|
||||
def unregister(kind: str) -> None:
|
||||
modules.pop(kind, None)
|
||||
|
||||
register({"kind": "sample", "representation": "text"})
|
||||
assert any(item["kind"] == "sample" and item["representation"] == "text" for item in modules.values())
|
||||
unregister("sample")
|
||||
assert not any(item["kind"] == "sample" for item in modules.values())
|
||||
|
||||
|
||||
def _raw(actor: Actor, path: str):
|
||||
return actor.client.get(
|
||||
path,
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _post_zip(actor: Actor, matter_id: str, body: dict):
|
||||
return actor.client.post(
|
||||
f"/api/v1/matters/{matter_id}/export",
|
||||
json=body,
|
||||
headers={
|
||||
"Origin": ORIGIN,
|
||||
"X-CSRF-Token": actor.csrf,
|
||||
"Content-Type": "application/json",
|
||||
"X-Scope-Kind": actor.scope["kind"],
|
||||
"X-Scope-Id": actor.scope["id"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _walk(node):
|
||||
yield node
|
||||
for child in node.get("children") or []:
|
||||
yield from _walk(child)
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Hauptnutzer, Mitarbeiter und Teamverwaltung."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.errors import unprocessable
|
||||
from tests.support import ORIGIN, PASSWORD, Actor
|
||||
|
||||
|
||||
def _second_client():
|
||||
from app.main import app
|
||||
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def _main(client, db, key: str, *, main: bool = False, superadmin: bool = False) -> Actor:
|
||||
actor = Actor(client if main else _second_client(), f"{key}-team@example.test", key.title())
|
||||
create_account(db, actor.email, actor.name, PASSWORD, is_superadmin=superadmin)
|
||||
db.commit()
|
||||
actor.login()
|
||||
return actor
|
||||
|
||||
|
||||
def _invite(owner: Actor, room: str, email: str, role: str = "member", name: str = "Mitarbeiter") -> Actor:
|
||||
invited = owner.request("POST", "/api/v1/invitations", json={"email": email, "room_id": room, "role": role}, status=201)
|
||||
client = _second_client()
|
||||
response = client.post(
|
||||
f"/api/v1/invitations/{invited['id']}/accept",
|
||||
json={"token": invited["token"], "display_name": name, "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert response.status_code == 201, response.text
|
||||
employee = Actor(client, email, name)
|
||||
employee.login()
|
||||
return employee
|
||||
|
||||
|
||||
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"])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def world(client, db):
|
||||
ada = _main(client, db, "ada", main=True)
|
||||
room = ada.request("POST", "/api/v1/rooms", json={"name": "Kanzlei"}, status=201)["id"]
|
||||
ada.use_room(room)
|
||||
employee = _invite(ada, room, "emp-team@example.test", name="Eva Mitarbeiterin")
|
||||
return {"ada": ada, "room": room, "emp": employee}
|
||||
|
||||
|
||||
def test_an_invitation_creates_an_employee_account_sponsored_by_the_owner(world, db):
|
||||
row = db.execute("SELECT account_kind, sponsor_id FROM auth_accounts WHERE email = 'emp-team@example.test'").fetchone()
|
||||
db.rollback()
|
||||
assert row["account_kind"] == "employee"
|
||||
assert str(row["sponsor_id"]) == _id(db, world["ada"].email)
|
||||
assert world["emp"].request("GET", "/api/v1/auth/session")["account"]["account_kind"] == "employee"
|
||||
assert world["ada"].request("GET", "/api/v1/auth/session")["account"]["account_kind"] == "main"
|
||||
|
||||
|
||||
def test_an_employee_works_only_in_the_rooms_he_was_invited_to(world, db):
|
||||
emp, room = world["emp"], world["room"]
|
||||
emp.request("POST", "/api/v1/rooms", json={"name": "Eigener Raum"}, status=403)
|
||||
# The session starts in the team room, not in a personal room.
|
||||
assert emp.scope["kind"] == "organization" and emp.scope["id"] == room
|
||||
# In the personal room nothing is created.
|
||||
personal = emp.request("POST", "/api/v1/auth/session/scope", json={"kind": "personal", "id": _id(db, emp.email)})
|
||||
emp.scope, emp.csrf = personal["scope"], personal["csrf_token"]
|
||||
emp.request("POST", "/api/v1/cases", json={"title": "Privat"}, status=403)
|
||||
emp.request("POST", "/api/v1/matters", json={"title": "Privat"}, status=403)
|
||||
emp.use_room(room)
|
||||
case = emp.request("POST", "/api/v1/cases", json={"title": "Im Team"}, status=201)
|
||||
world["ada"].request("GET", f"/api/v1/cases/{case['id']}")
|
||||
# Rights follow the role: a reader only reads.
|
||||
world["ada"].request("PATCH", f"/api/v1/rooms/{room}/members/{_id(db, emp.email)}", json={"role": "reader"})
|
||||
emp.request("POST", "/api/v1/cases", json={"title": "Nicht mehr"}, status=403)
|
||||
emp.request("GET", f"/api/v1/cases/{case['id']}")
|
||||
|
||||
|
||||
def test_only_the_owner_invites_and_an_employee_never_does(world, client, db):
|
||||
ada, emp, room = world["ada"], world["emp"], world["room"]
|
||||
ben = _main(client, db, "ben")
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": ben.email, "role": "manager"})
|
||||
ben.use_room(room)
|
||||
# A manager who is not the owner adds existing accounts but creates no new ones.
|
||||
ben.request("POST", "/api/v1/invitations", json={"email": "neu-team@example.test", "room_id": room}, status=403)
|
||||
ben.request("POST", f"/api/v1/rooms/{room}/members", json={"email": emp.email, "role": "reader"})
|
||||
emp.request("POST", "/api/v1/invitations", json={"email": "neu-team@example.test", "room_id": room}, status=403)
|
||||
|
||||
|
||||
def test_an_employee_cannot_own_a_room(world, db):
|
||||
ada, emp, room = world["ada"], world["emp"], world["room"]
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/owner", json={"subject_id": _id(db, emp.email)}, status=422)
|
||||
operator = _main(world["ada"].client.__class__ and _second_client(), db, "betreiber", superadmin=True)
|
||||
db.execute("UPDATE auth_accounts SET status = 'disabled' WHERE id = %s", (_id(db, ada.email),))
|
||||
db.commit()
|
||||
operator.request("POST", f"/api/v1/admin/rooms/{room}/owner", json={"email": emp.email}, status=422)
|
||||
|
||||
|
||||
def test_my_team_lists_only_people_in_my_rooms_and_acts_only_on_my_employees(world, client, db):
|
||||
ada, emp = world["ada"], world["emp"]
|
||||
cara = _main(client, db, "cara")
|
||||
emp_id = _id(db, emp.email)
|
||||
listed = ada.request("GET", "/api/v1/team")["items"]
|
||||
assert [(p["email"], p["mine"], p["rooms"][0]["role"]) for p in listed] == [(emp.email, True, "member")]
|
||||
assert cara.request("GET", "/api/v1/team")["items"] == []
|
||||
emp.request("GET", "/api/v1/team", status=403)
|
||||
unknown = str(uuid.uuid4())
|
||||
for actor in (cara,):
|
||||
foreign = actor.request("PATCH", f"/api/v1/team/{emp_id}", json={"status": "disabled"}, status=403)
|
||||
missing = actor.request("PATCH", f"/api/v1/team/{unknown}", json={"status": "disabled"}, status=403)
|
||||
assert foreign["detail"] == missing["detail"]
|
||||
actor.request("POST", f"/api/v1/team/{emp_id}/password-reset", status=403)
|
||||
actor.request("DELETE", f"/api/v1/team/{emp_id}/memberships", status=403)
|
||||
# A main user is not a sponsored employee: no team action on him, not even by the owner.
|
||||
cara_id = _id(db, cara.email)
|
||||
ada.request("PATCH", f"/api/v1/team/{cara_id}", json={"status": "disabled"}, status=403)
|
||||
ada.request("POST", f"/api/v1/team/{cara_id}/password-reset", status=403)
|
||||
|
||||
|
||||
def test_the_owner_disables_resets_and_removes_an_employee(world, db):
|
||||
ada, emp, room = world["ada"], world["emp"], world["room"]
|
||||
emp_id = _id(db, emp.email)
|
||||
ada.request("PATCH", f"/api/v1/team/{emp_id}", json={"status": "disabled"})
|
||||
emp.request("GET", "/api/v1/auth/session", status=401)
|
||||
login = emp.client.post("/api/v1/auth/login", json={"email": emp.email, "password": PASSWORD}, headers={"Origin": ORIGIN})
|
||||
assert login.status_code == 401
|
||||
ada.request("PATCH", f"/api/v1/team/{emp_id}", json={"status": "active"})
|
||||
reset = ada.request("POST", f"/api/v1/team/{emp_id}/password-reset")
|
||||
emp.password = reset["temporary_password"]
|
||||
assert emp.login()["account"]["must_change_password"] is True
|
||||
emp.request("GET", "/api/v1/cases", status=403)
|
||||
|
||||
ada.request("DELETE", f"/api/v1/team/{emp_id}/memberships", status=204)
|
||||
assert ada.request("GET", "/api/v1/team")["items"][0]["rooms"] == []
|
||||
# Without a room the employee lands in the personal room, where he can do nothing but change his password.
|
||||
assert emp.login()["scope"]["kind"] == "personal"
|
||||
ada.request("DELETE", f"/api/v1/team/{emp_id}/memberships", status=403)
|
||||
ada.request("DELETE", f"/api/v1/team/{_id(db, ada.email)}/memberships", status=403)
|
||||
assert room
|
||||
|
||||
|
||||
def test_the_operator_sees_the_teams_as_metadata_and_exports_them_safely(world, client, db):
|
||||
ada, room = world["ada"], world["room"]
|
||||
_invite(ada, room, "formel-team@example.test", role="reader", name="=SUM(1+1)")
|
||||
operator = _main(_second_client(), db, "betreiber", superadmin=True)
|
||||
note = ada.request("POST", "/api/v1/cases", json={"title": "Geheimer Inhalt"}, status=201)
|
||||
overview = operator.request("GET", "/api/v1/admin/team")["items"]
|
||||
owner = next(item for item in overview if item["email"] == ada.email)
|
||||
assert {e["email"] for e in owner["employees"]} == {"emp-team@example.test", "formel-team@example.test"}
|
||||
assert all(r["name"] == "Kanzlei" for e in owner["employees"] for r in e["rooms"])
|
||||
assert "Geheimer Inhalt" not in str(overview) and note["title"] == "Geheimer Inhalt"
|
||||
response = operator.client.get(
|
||||
"/api/v1/admin/team",
|
||||
params={"format": "csv"},
|
||||
headers={"Origin": ORIGIN, "X-Scope-Kind": operator.scope["kind"], "X-Scope-Id": operator.scope["id"]},
|
||||
)
|
||||
assert response.status_code == 200 and response.headers["content-type"].startswith("text/csv")
|
||||
lines = response.text.splitlines()
|
||||
assert lines[0] == "Hauptnutzer,Mitarbeiter,E-Mail,Status,Datenraum,Rolle"
|
||||
assert any("'=SUM(1+1)" in line for line in lines)
|
||||
assert not any(line.split(",")[1].startswith("=") for line in lines[1:])
|
||||
world["emp"].request("GET", "/api/v1/admin/team", status=403)
|
||||
ada.request("GET", "/api/v1/admin/team", status=403)
|
||||
|
||||
|
||||
def test_only_the_operator_promotes_an_employee(world, client, db):
|
||||
ada, emp, room = world["ada"], world["emp"], world["room"]
|
||||
emp_id = _id(db, emp.email)
|
||||
ada.request("PATCH", f"/api/v1/accounts/{emp_id}", json={"account_kind": "main"}, status=403)
|
||||
operator = _main(_second_client(), db, "betreiber", superadmin=True)
|
||||
listed = {a["email"]: a for a in operator.request("GET", "/api/v1/accounts")["items"]}
|
||||
assert listed[emp.email]["account_kind"] == "employee" and listed[emp.email]["sponsor_name"] == "Ada"
|
||||
assert operator.request("GET", f"/api/v1/accounts/{_id(db, ada.email)}")["employees"][0]["email"] == emp.email
|
||||
operator.request("PATCH", f"/api/v1/accounts/{emp_id}", json={"account_kind": "main"})
|
||||
emp.request("GET", "/api/v1/cases", status=401)
|
||||
fresh = Actor(emp.client, emp.email, emp.name)
|
||||
assert fresh.login()["account"]["account_kind"] == "main"
|
||||
fresh.request("POST", "/api/v1/rooms", json={"name": "Eigener Raum"}, status=201)
|
||||
assert room
|
||||
|
||||
|
||||
def test_limits_have_one_place_and_are_checked_where_they_matter(world, client, db, monkeypatch):
|
||||
ada, room = world["ada"], world["room"]
|
||||
seen = []
|
||||
|
||||
def block_room(conn, owner_id):
|
||||
seen.append(("room", owner_id))
|
||||
raise unprocessable("Grenze erreicht.")
|
||||
|
||||
def block_member(conn, owner_id, room_id):
|
||||
seen.append(("member", owner_id, room_id))
|
||||
raise unprocessable("Grenze erreicht.")
|
||||
|
||||
cem = _main(client, db, "cem")
|
||||
monkeypatch.setattr("app.api.rooms.ensure_can_create_room", block_room)
|
||||
ada.request("POST", "/api/v1/rooms", json={"name": "Noch ein Raum"}, status=422)
|
||||
monkeypatch.setattr("app.api.rooms.ensure_can_add_member", block_member)
|
||||
ada.request("POST", f"/api/v1/rooms/{room}/members", json={"email": cem.email, "role": "member"}, status=422)
|
||||
ada.request("POST", "/api/v1/invitations", json={"email": "grenze-team@example.test", "room_id": room}, status=422)
|
||||
assert [entry[0] for entry in seen] == ["room", "member", "member"]
|
||||
assert all(entry[1] == uuid.UUID(_id(db, ada.email)) for entry in seen)
|
||||
# Changing the role of an existing member needs no check.
|
||||
monkeypatch.undo()
|
||||
invited = ada.request("POST", "/api/v1/invitations", json={"email": "spaet-team@example.test", "room_id": room}, status=201)
|
||||
monkeypatch.setattr("app.api.routes.ensure_can_add_member", block_member)
|
||||
refused = _second_client().post(
|
||||
f"/api/v1/invitations/{invited['id']}/accept",
|
||||
json={"token": invited["token"], "display_name": "Spät", "password": PASSWORD},
|
||||
headers={"Origin": ORIGIN},
|
||||
)
|
||||
assert refused.status_code == 422
|
||||
assert db.execute("SELECT 1 FROM auth_accounts WHERE email = 'spaet-team@example.test'").fetchone() is None
|
||||
db.rollback()
|
||||
Loaded 100 of 319 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user