Compare commits
134
Commits
353001d819
..
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 | ||
|
|
2558239bfd | ||
|
|
cfe17ff909 | ||
|
|
e9ed29fedf | ||
|
|
94390797c1 | ||
|
|
2afdb50ee9 | ||
|
|
c6ed2f86f5 | ||
|
|
431007953f | ||
|
|
bb1c777558 | ||
|
|
337fcfb544 | ||
|
|
20b431399c | ||
|
|
4698718e5d | ||
|
|
7e6371a2f3 | ||
|
|
78bf29ae12 | ||
|
|
f0ffac579a | ||
|
|
b44faf7f50 | ||
|
|
802eb1bc65 | ||
|
|
c6f6ec3d0a | ||
|
|
8ae5bd9189 | ||
|
|
54581d9624 | ||
|
|
f06b74f4c3 | ||
|
|
75cdbeaa9a | ||
|
|
0e55e9e65d | ||
|
|
c88b93080d | ||
|
|
92e2b5c5fc | ||
|
|
997da92c9b | ||
|
|
c9031ed572 |
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/
|
||||
@@ -0,0 +1,7 @@
|
||||
# Tsumugu
|
||||
|
||||
Fachlich führend ist `docs/product/TSUMUGU_PRODUCT_SPEC.md`. Der technische Entwurf ist `docs/architecture/TSUMUGU_TECHNICAL_SPEC.md`. Vorläufige Rechte- und Löschregeln der ersten Lieferung stehen in `docs/MVP_ANNAHMEN.md` und sind keine endgültigen Produktentscheidungen.
|
||||
|
||||
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 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,7 +6,9 @@ Remote: `http://192.168.2.144:3000/Lars/tsumugu.git`
|
||||
|
||||
## Stand
|
||||
|
||||
Das Repository enthält das Deploy-Gerüst. 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.
|
||||
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 und entfernt Konten mit Herkunft `fixture`. Synthetische Beispieldaten entstehen in keiner Umgebung automatisch, nur in der Test-Suite auf einer Datenbank `*_test`.
|
||||
|
||||
| | Development | Production |
|
||||
|---|---|---|
|
||||
@@ -17,4 +19,12 @@ Das Repository enthält das Deploy-Gerüst. Ein Push auf `develop` baut und star
|
||||
|
||||
Details, Ports und der Synology-Reverse-Proxy: `docs/DEPLOYMENT.md`.
|
||||
|
||||
Backend und Frontend sind bewusst schmal: `/api/health` prüft Postgres, das Frontend reicht `/api/` an das Backend durch. Die Anwendung selbst ist noch nicht begonnen.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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,5 @@
|
||||
__pycache__
|
||||
.pytest_cache
|
||||
.venv
|
||||
data
|
||||
*.pyc
|
||||
+5
-1
@@ -2,11 +2,15 @@ FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY main.py .
|
||||
COPY app ./app
|
||||
COPY migrations ./migrations
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
CMD ["python", "-m", "app.entrypoint"]
|
||||
@@ -0,0 +1 @@
|
||||
"""Tsumugu application package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""Data rooms and the case-based access policy."""
|
||||
@@ -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
|
||||
@@ -0,0 +1,922 @@
|
||||
"""Context rights for the first delivery.
|
||||
|
||||
Provisional MVP assumptions, not final product decisions, live in docs/MVP_ANNAHMEN.md.
|
||||
The action context is the only rights path used here. A case link inherits that case's
|
||||
rights. Cross-links do not. Exceptions apply only in the context they name.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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."
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rights:
|
||||
read: bool = False
|
||||
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, True)
|
||||
|
||||
@classmethod
|
||||
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"]), 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, "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)
|
||||
class Ctx:
|
||||
kind: str
|
||||
id: UUID
|
||||
|
||||
def as_dict(self) -> dict[str, str]:
|
||||
return {"kind": self.kind, "id": str(self.id)}
|
||||
|
||||
|
||||
def parse_context(payload: dict | None, *, required: bool = False) -> Ctx | None:
|
||||
if not payload:
|
||||
if required:
|
||||
raise unprocessable("Der Handlungskontext fehlt.")
|
||||
return None
|
||||
kind = payload.get("kind")
|
||||
raw = payload.get("id")
|
||||
if kind not in ("case", "matter") or not raw:
|
||||
raise unprocessable("Der Handlungskontext ist ungültig.")
|
||||
try:
|
||||
return Ctx(kind, UUID(str(raw)))
|
||||
except ValueError as exc:
|
||||
raise unprocessable("Der Handlungskontext ist ungültig.") from exc
|
||||
|
||||
|
||||
def parse_query_context(kind: str | None, raw: str | None) -> Ctx | None:
|
||||
if kind is None and raw is None:
|
||||
return None
|
||||
return parse_context({"kind": kind, "id": raw}, required=True)
|
||||
|
||||
|
||||
def audit(
|
||||
conn,
|
||||
actor_id: UUID | None,
|
||||
scope_id: UUID | None,
|
||||
action: str,
|
||||
resource_kind: str,
|
||||
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, result, detail
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
actor_id,
|
||||
scope_id,
|
||||
action,
|
||||
resource_kind,
|
||||
resource_id,
|
||||
context.kind if context else None,
|
||||
context.id if context else None,
|
||||
occurred_on,
|
||||
result,
|
||||
Json(detail) if detail is not None else None,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def bump_version(conn, table: str, row_id: UUID, expected: int) -> int:
|
||||
if table not in {"cases", "matters", "elements", "tasks", "deadlines"}:
|
||||
raise RuntimeError("unsupported version table")
|
||||
row = conn.execute(
|
||||
f"UPDATE {table} SET version = version + 1, updated_at = now() "
|
||||
f"WHERE id = %s AND version = %s AND deleted_at IS NULL RETURNING version",
|
||||
(row_id, expected),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
current = conn.execute(
|
||||
f"SELECT version, deleted_at FROM {table} WHERE id = %s",
|
||||
(row_id,),
|
||||
).fetchone()
|
||||
if current is None or current["deleted_at"] is not None:
|
||||
raise not_found()
|
||||
raise conflict()
|
||||
return int(row["version"])
|
||||
|
||||
|
||||
def _get(conn, table: str, row_id: UUID) -> dict | None:
|
||||
if table not in {"cases", "matters", "elements", "tasks", "deadlines", "data_rooms"}:
|
||||
raise RuntimeError("unsupported lookup")
|
||||
return conn.execute(f"SELECT * FROM {table} WHERE id = %s", (row_id,)).fetchone()
|
||||
|
||||
|
||||
def get_case(conn, case_id: UUID) -> dict | None:
|
||||
row = _get(conn, "cases", case_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_matter(conn, matter_id: UUID) -> dict | None:
|
||||
row = _get(conn, "matters", matter_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_element(conn, element_id: UUID) -> dict | None:
|
||||
row = _get(conn, "elements", element_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_task(conn, task_id: UUID) -> dict | None:
|
||||
row = _get(conn, "tasks", task_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def get_deadline(conn, deadline_id: UUID) -> dict | None:
|
||||
row = _get(conn, "deadlines", deadline_id)
|
||||
if row is None or row["deleted_at"] is not None:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
def _direct_grant(conn, actor: UUID, kind: str, resource_id: UUID) -> Rights:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT can_read, can_edit, can_share, can_delete
|
||||
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()
|
||||
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:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT can_read, can_edit, can_share, can_delete
|
||||
FROM access_grants
|
||||
WHERE is_exception
|
||||
AND resource_kind = %s
|
||||
AND resource_id = %s
|
||||
AND context_kind IS NOT DISTINCT FROM %s
|
||||
AND context_id IS NOT DISTINCT FROM %s
|
||||
AND (grantee_subject_id IS NULL OR grantee_subject_id = %s)
|
||||
""",
|
||||
(
|
||||
kind,
|
||||
resource_id,
|
||||
context.kind if context else None,
|
||||
context.id if context else None,
|
||||
actor,
|
||||
),
|
||||
).fetchall()
|
||||
blocked = Rights()
|
||||
for row in rows:
|
||||
blocked = Rights(
|
||||
blocked.read or row["can_read"],
|
||||
blocked.edit or row["can_edit"],
|
||||
blocked.share or row["can_share"],
|
||||
blocked.delete or row["can_delete"],
|
||||
)
|
||||
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"])
|
||||
base = case_rights(conn, actor, parent) if parent else Rights()
|
||||
elif case["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
else:
|
||||
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))
|
||||
|
||||
|
||||
def _linked(conn, matter_id: UUID, case_id: UUID) -> bool:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM matter_case_links WHERE matter_id = %s AND case_id = %s",
|
||||
(matter_id, case_id),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def matter_rights(conn, actor: UUID, matter: dict, context: Ctx | None) -> Rights:
|
||||
if context is None:
|
||||
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":
|
||||
anchor_id = matter["id"]
|
||||
if not _linked(conn, matter["id"], context.id) and matter["parent_matter_id"] is not None:
|
||||
if _linked(conn, matter["parent_matter_id"], context.id):
|
||||
anchor_id = matter["parent_matter_id"]
|
||||
else:
|
||||
return Rights()
|
||||
elif not _linked(conn, matter["id"], context.id):
|
||||
return Rights()
|
||||
case = get_case(conn, context.id)
|
||||
if case is None:
|
||||
return Rights()
|
||||
base = case_rights(conn, actor, case)
|
||||
if anchor_id != matter["id"]:
|
||||
parent = get_matter(conn, anchor_id)
|
||||
if parent is None:
|
||||
return Rights()
|
||||
base = matter_rights(conn, actor, parent, context)
|
||||
return base.without(_exceptions(conn, actor, "matter", matter["id"], context))
|
||||
|
||||
if context.kind == "matter":
|
||||
if matter["parent_matter_id"] != context.id:
|
||||
return Rights()
|
||||
parent = get_matter(conn, context.id)
|
||||
if parent is None:
|
||||
return Rights()
|
||||
base = matter_rights(conn, actor, parent, None)
|
||||
return base.without(_exceptions(conn, actor, "matter", matter["id"], context))
|
||||
return Rights()
|
||||
|
||||
|
||||
def _bindings(conn, element_id: UUID) -> list[dict]:
|
||||
return conn.execute(
|
||||
"SELECT * FROM bindings WHERE element_id = %s ORDER BY position, created_at",
|
||||
(element_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
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 _matter_reaches_case(conn, matter_id: UUID, case_id: UUID) -> bool:
|
||||
matter = get_matter(conn, matter_id)
|
||||
if matter is None:
|
||||
return False
|
||||
if _linked(conn, matter_id, case_id):
|
||||
return True
|
||||
return bool(matter["parent_matter_id"] and _linked(conn, matter["parent_matter_id"], case_id))
|
||||
|
||||
|
||||
def element_rights(conn, actor: UUID, element: dict, context: Ctx | None) -> Rights:
|
||||
if context is None:
|
||||
base = (
|
||||
Rights.full()
|
||||
if element["owner_subject_id"] == actor
|
||||
else _direct_grant(conn, actor, "element", element["id"])
|
||||
)
|
||||
return base.without(_exceptions(conn, actor, "element", element["id"], None))
|
||||
|
||||
bindings = _bindings(conn, element["id"])
|
||||
if context.kind == "case":
|
||||
on_case = any(item["context_kind"] == "case" and item["context_id"] == context.id for item in bindings)
|
||||
via_matter = [
|
||||
item
|
||||
for item in bindings
|
||||
if item["context_kind"] == "matter" and _matter_reaches_case(conn, item["context_id"], context.id)
|
||||
]
|
||||
if not on_case and not via_matter:
|
||||
return Rights()
|
||||
if not on_case and _blocked(conn, context.id, element["id"]):
|
||||
return Rights()
|
||||
case = get_case(conn, context.id)
|
||||
if case is None:
|
||||
return Rights()
|
||||
base = case_rights(conn, actor, case)
|
||||
return base.without(_exceptions(conn, actor, "element", element["id"], context))
|
||||
|
||||
if context.kind == "matter":
|
||||
matter = get_matter(conn, context.id)
|
||||
if matter is None:
|
||||
return Rights()
|
||||
hosted = any(
|
||||
item["context_kind"] == "matter"
|
||||
and (item["context_id"] == context.id or _child_of(conn, item["context_id"], context.id))
|
||||
for item in bindings
|
||||
)
|
||||
if not hosted:
|
||||
return Rights()
|
||||
base = matter_rights(conn, actor, matter, None)
|
||||
return base.without(_exceptions(conn, actor, "element", element["id"], context))
|
||||
return Rights()
|
||||
|
||||
|
||||
def _child_of(conn, matter_id: UUID, parent_id: UUID) -> bool:
|
||||
matter = get_matter(conn, matter_id)
|
||||
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.
|
||||
|
||||
A matter context uses direct matter rights. A case context uses that case only.
|
||||
"""
|
||||
if context is None:
|
||||
return element_rights(conn, actor, element, None)
|
||||
if context.kind == "matter":
|
||||
return element_rights(conn, actor, element, context)
|
||||
return element_rights(conn, actor, element, context)
|
||||
|
||||
|
||||
def task_rights(conn, actor: UUID, task: dict, context: Ctx | None) -> Rights:
|
||||
if task["assignee_subject_id"] == actor and context is None:
|
||||
granted = _direct_grant(conn, actor, "task", task["id"])
|
||||
base = Rights(read=True, edit=granted.edit, share=False, delete=False)
|
||||
if task["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
return base.without(_exceptions(conn, actor, "task", task["id"], None))
|
||||
if context is None:
|
||||
base = Rights.full() if task["owner_subject_id"] == actor else _direct_grant(conn, actor, "task", task["id"])
|
||||
return base.without(_exceptions(conn, actor, "task", task["id"], None))
|
||||
if task["matter_id"] is None:
|
||||
return Rights()
|
||||
matter = get_matter(conn, task["matter_id"])
|
||||
if matter is None:
|
||||
return Rights()
|
||||
if context.kind == "matter" and context.id == task["matter_id"]:
|
||||
base = matter_rights(conn, actor, matter, None)
|
||||
elif context.kind == "case":
|
||||
base = matter_rights(conn, actor, matter, context)
|
||||
elif context.kind == "matter" and matter["parent_matter_id"] == context.id:
|
||||
base = matter_rights(conn, actor, matter, context)
|
||||
else:
|
||||
return Rights()
|
||||
return base.without(_exceptions(conn, actor, "task", task["id"], context))
|
||||
|
||||
|
||||
def deadline_rights(conn, actor: UUID, deadline: dict, context: Ctx | None) -> Rights:
|
||||
if deadline["assignee_subject_id"] == actor and context is None:
|
||||
base = Rights(read=True, edit=False, share=False, delete=False)
|
||||
if deadline["owner_subject_id"] == actor:
|
||||
base = Rights.full()
|
||||
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None))
|
||||
if context is None:
|
||||
base = (
|
||||
Rights.full()
|
||||
if deadline["owner_subject_id"] == actor
|
||||
else _direct_grant(conn, actor, "deadline", deadline["id"])
|
||||
)
|
||||
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], None))
|
||||
if deadline["matter_id"] is None:
|
||||
return Rights()
|
||||
matter = get_matter(conn, deadline["matter_id"])
|
||||
if matter is None:
|
||||
return Rights()
|
||||
if context.kind == "matter" and context.id == deadline["matter_id"]:
|
||||
base = matter_rights(conn, actor, matter, None)
|
||||
elif context.kind == "case":
|
||||
base = matter_rights(conn, actor, matter, context)
|
||||
else:
|
||||
return Rights()
|
||||
return base.without(_exceptions(conn, actor, "deadline", deadline["id"], context))
|
||||
|
||||
|
||||
def require_case(conn, actor: UUID, case_id: UUID, need: str) -> tuple[dict, Rights]:
|
||||
case = get_case(conn, case_id)
|
||||
if case is None:
|
||||
raise not_found()
|
||||
rights = case_rights(conn, actor, case)
|
||||
_require(rights, need)
|
||||
return case, rights
|
||||
|
||||
|
||||
def require_matter(conn, actor: UUID, matter_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]:
|
||||
matter = get_matter(conn, matter_id)
|
||||
if matter is None:
|
||||
raise not_found()
|
||||
rights = matter_rights(conn, actor, matter, context)
|
||||
_require(rights, need)
|
||||
return matter, rights
|
||||
|
||||
|
||||
def require_element(conn, actor: UUID, element_id: UUID, context: Ctx | None, need: str) -> tuple[dict, Rights]:
|
||||
element = get_element(conn, element_id)
|
||||
if element is None:
|
||||
raise not_found()
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
_require(rights, need)
|
||||
return element, rights
|
||||
|
||||
|
||||
def _require(rights: Rights, need: str) -> None:
|
||||
if not rights.read:
|
||||
raise not_found()
|
||||
if need != "read" and not rights.allows(need):
|
||||
raise forbidden()
|
||||
|
||||
|
||||
def can_change_status(actor: UUID, row: dict, rights: Rights, assignee_key: str = "assignee_subject_id") -> bool:
|
||||
if rights.edit or row["owner_subject_id"] == actor:
|
||||
return True
|
||||
return row[assignee_key] == actor and rights.read
|
||||
|
||||
|
||||
def readable_matter_contexts(conn, actor: UUID, matter: dict) -> list[dict]:
|
||||
found: list[dict] = []
|
||||
direct = matter_rights(conn, actor, matter, None)
|
||||
if direct.read:
|
||||
found.append({"kind": "matter", "id": str(matter["id"]), "title": matter["title"], "rights": direct.as_dict()})
|
||||
links = conn.execute(
|
||||
"""
|
||||
SELECT l.case_id, c.title
|
||||
FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id
|
||||
WHERE l.matter_id = %s AND c.deleted_at IS NULL
|
||||
""",
|
||||
(matter["id"],),
|
||||
).fetchall()
|
||||
if matter["parent_matter_id"] is not None:
|
||||
links = list(links) + list(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT l.case_id, c.title
|
||||
FROM matter_case_links l
|
||||
JOIN cases c ON c.id = l.case_id
|
||||
WHERE l.matter_id = %s AND c.deleted_at IS NULL
|
||||
""",
|
||||
(matter["parent_matter_id"],),
|
||||
).fetchall()
|
||||
)
|
||||
seen: set[UUID] = set()
|
||||
for link in links:
|
||||
if link["case_id"] in seen:
|
||||
continue
|
||||
seen.add(link["case_id"])
|
||||
rights = matter_rights(conn, actor, matter, Ctx("case", link["case_id"]))
|
||||
if rights.read:
|
||||
found.append(
|
||||
{
|
||||
"kind": "case",
|
||||
"id": str(link["case_id"]),
|
||||
"title": link["title"],
|
||||
"rights": rights.as_dict(),
|
||||
}
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def list_cases(conn, actor: UUID) -> list[dict]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT c.*
|
||||
FROM cases c
|
||||
WHERE c.deleted_at IS NULL
|
||||
AND (
|
||||
c.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'case' AND g.resource_id = c.id
|
||||
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
|
||||
WHERE p.id = c.parent_case_id AND p.deleted_at IS NULL
|
||||
AND (
|
||||
p.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'case' AND g.resource_id = p.id
|
||||
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
|
||||
))
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY c.updated_at DESC, c.id DESC
|
||||
""",
|
||||
{"actor": actor},
|
||||
).fetchall()
|
||||
visible = []
|
||||
for row in rows:
|
||||
rights = case_rights(conn, actor, row)
|
||||
if rights.read:
|
||||
visible.append((row, rights))
|
||||
return visible
|
||||
|
||||
|
||||
def list_matters(conn, actor: UUID) -> list[tuple[dict, list[dict]]]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT m.*
|
||||
FROM matters m
|
||||
WHERE m.deleted_at IS NULL
|
||||
AND (
|
||||
m.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'matter' AND g.resource_id = m.id
|
||||
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
|
||||
WHERE l.matter_id = m.id
|
||||
AND (
|
||||
c.owner_subject_id = %(actor)s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM access_grants g
|
||||
WHERE g.resource_kind = 'case' AND g.resource_id = c.id
|
||||
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
|
||||
))
|
||||
)
|
||||
)
|
||||
)
|
||||
ORDER BY m.updated_at DESC, m.id DESC
|
||||
""",
|
||||
{"actor": actor},
|
||||
).fetchall()
|
||||
visible = []
|
||||
for row in rows:
|
||||
contexts = readable_matter_contexts(conn, actor, row)
|
||||
if contexts:
|
||||
visible.append((row, contexts))
|
||||
return visible
|
||||
|
||||
|
||||
def assert_scope_can_host(conn, scope_id: UUID) -> dict:
|
||||
room = _get(conn, "data_rooms", scope_id)
|
||||
if room is None or room["status"] != "active":
|
||||
raise forbidden("Der gewählte Datenraum ist nicht verfügbar.")
|
||||
return room
|
||||
|
||||
|
||||
def same_home(row: dict, scope_id: UUID) -> None:
|
||||
if row["home_scope_id"] != scope_id:
|
||||
raise unprocessable(
|
||||
"Unterakten, Teilvorgänge und Kapitel bleiben im Datenraum ihres Behälters. "
|
||||
"Wähle diesen Datenraum, wenn du dort Mitglied bist, oder lege einen Querverweis an."
|
||||
)
|
||||
|
||||
|
||||
def account_by_email(conn, email: str) -> dict | None:
|
||||
return conn.execute(
|
||||
"SELECT id, email, display_name, status FROM auth_accounts WHERE email = %s",
|
||||
(email.strip().lower(),),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def display_name(conn, account_id: UUID | None) -> str | None:
|
||||
if account_id is None:
|
||||
return None
|
||||
row = conn.execute("SELECT display_name FROM auth_accounts WHERE id = %s", (account_id,)).fetchone()
|
||||
return row["display_name"] if row else None
|
||||
|
||||
|
||||
def room_name(conn, room_id: UUID) -> str | None:
|
||||
row = conn.execute("SELECT name FROM data_rooms WHERE id = %s", (room_id,)).fetchone()
|
||||
return row["name"] if row else None
|
||||
|
||||
|
||||
def visible_bindings_for_element(conn, actor: UUID, element: dict) -> list[dict]:
|
||||
"""Names and counts only bindings the actor can actually read."""
|
||||
result = []
|
||||
for binding in _bindings(conn, element["id"]):
|
||||
if binding["context_kind"] == "case":
|
||||
context = Ctx("case", binding["context_id"])
|
||||
rights = element_rights(conn, actor, element, context)
|
||||
if not rights.read:
|
||||
continue
|
||||
case = get_case(conn, binding["context_id"])
|
||||
if case is None:
|
||||
continue
|
||||
title = case["title"]
|
||||
else:
|
||||
matter = get_matter(conn, binding["context_id"])
|
||||
if matter is None:
|
||||
continue
|
||||
contexts = readable_matter_contexts(conn, actor, matter)
|
||||
if not contexts:
|
||||
continue
|
||||
direct = element_rights(conn, actor, element, Ctx("matter", matter["id"]))
|
||||
via_cases = []
|
||||
for item in contexts:
|
||||
if item["kind"] != "case":
|
||||
continue
|
||||
case_rights_now = element_rights(conn, actor, element, Ctx("case", UUID(item["id"])))
|
||||
if case_rights_now.read:
|
||||
via_cases.append(item)
|
||||
if not direct.read and not via_cases:
|
||||
continue
|
||||
title = matter["title"]
|
||||
context = Ctx("matter", matter["id"])
|
||||
result.append(
|
||||
{
|
||||
"id": str(binding["id"]),
|
||||
"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
|
||||
|
||||
|
||||
def chapter_for(conn, chapter_id: UUID | None, kind: str, container_id: UUID) -> None:
|
||||
if chapter_id is None:
|
||||
return
|
||||
column = "case_id" if kind == "case" else "matter_id"
|
||||
row = conn.execute(
|
||||
f"SELECT id FROM chapters WHERE id = %s AND {column} = %s",
|
||||
(chapter_id, container_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise unprocessable("Das Kapitel gehört nicht zu diesem Kontext.")
|
||||
|
||||
|
||||
def next_position(conn, kind: str, container_id: UUID) -> int:
|
||||
row = conn.execute(
|
||||
"SELECT COALESCE(MAX(position), 0) + 1 AS pos FROM bindings WHERE context_kind = %s AND context_id = %s",
|
||||
(kind, container_id),
|
||||
).fetchone()
|
||||
return int(row["pos"])
|
||||
|
||||
|
||||
def insert_binding(conn, element_id: UUID, kind: str, container_id: UUID, chapter_id: UUID | None, actor: UUID) -> dict:
|
||||
existing = conn.execute(
|
||||
"""
|
||||
SELECT id FROM bindings
|
||||
WHERE element_id = %s AND context_kind = %s AND context_id = %s
|
||||
""",
|
||||
(element_id, kind, container_id),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
raise unprocessable("Die Notiz ist in diesem Kontext bereits eingebunden.")
|
||||
chapter_for(conn, chapter_id, kind, container_id)
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO bindings (element_id, context_kind, context_id, chapter_id, position, created_by)
|
||||
VALUES (%s, %s, %s, %s, %s, %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(element_id, kind, container_id, chapter_id, next_position(conn, kind, container_id), actor),
|
||||
).fetchone()
|
||||
return row
|
||||
|
||||
|
||||
def block_unsharable_matter_elements(conn, actor: UUID, link_id: UUID, matter: dict) -> None:
|
||||
"""Contents the linking actor cannot share stay invisible in that case. No titles are stored."""
|
||||
matter_ids = [matter["id"]]
|
||||
children = conn.execute(
|
||||
"SELECT id FROM matters WHERE parent_matter_id = %s AND deleted_at IS NULL",
|
||||
(matter["id"],),
|
||||
).fetchall()
|
||||
matter_ids.extend(item["id"] for item in children)
|
||||
for matter_id in matter_ids:
|
||||
bindings = conn.execute(
|
||||
"SELECT element_id FROM bindings WHERE context_kind = 'matter' AND context_id = %s",
|
||||
(matter_id,),
|
||||
).fetchall()
|
||||
container = get_matter(conn, matter_id)
|
||||
if container is None:
|
||||
continue
|
||||
for binding in bindings:
|
||||
element = get_element(conn, binding["element_id"])
|
||||
if element is None:
|
||||
continue
|
||||
rights = element_rights(conn, actor, element, Ctx("matter", matter_id))
|
||||
if matter_id != matter["id"]:
|
||||
parent_rights = element_rights(conn, actor, element, Ctx("matter", matter["id"]))
|
||||
if parent_rights.share:
|
||||
rights = parent_rights
|
||||
if rights.share:
|
||||
continue
|
||||
conn.execute(
|
||||
"INSERT INTO case_link_blocks (link_id, element_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
||||
(link_id, element["id"]),
|
||||
)
|
||||
|
||||
|
||||
def matter_title_if_readable(conn, actor: UUID, matter_id: UUID | None) -> str | None:
|
||||
if matter_id is None:
|
||||
return None
|
||||
matter = get_matter(conn, matter_id)
|
||||
if matter is None:
|
||||
return None
|
||||
if readable_matter_contexts(conn, actor, matter):
|
||||
return matter["title"]
|
||||
return None
|
||||
|
||||
|
||||
def ensure_member_or_personal(conn, account_id: UUID, kind: str, scope_id: UUID) -> dict:
|
||||
room = assert_scope_can_host(conn, scope_id)
|
||||
if kind == "personal":
|
||||
if room["kind"] != "personal" or room["id"] != account_id:
|
||||
raise forbidden("Der persönliche Datenraum gehört zu einem anderen Konto.")
|
||||
return room
|
||||
if kind != "organization" or room["kind"] != "organization":
|
||||
raise forbidden("Dieser Datenraum kann nicht gewählt werden.")
|
||||
membership = conn.execute(
|
||||
"""
|
||||
SELECT role FROM room_memberships
|
||||
WHERE room_id = %s AND subject_id = %s AND status = 'active'
|
||||
""",
|
||||
(scope_id, account_id),
|
||||
).fetchone()
|
||||
if membership is None:
|
||||
raise forbidden("Du bist in diesem Datenraum nicht Mitglied.")
|
||||
return room
|
||||
@@ -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 @@
|
||||
"""HTTP adapters. Authorization stays in the domain services."""
|
||||
@@ -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",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Request scope: one transaction, a session principal, and no client-supplied identity."""
|
||||
|
||||
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
|
||||
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, 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
|
||||
email: str
|
||||
display_name: str
|
||||
session_id: UUID
|
||||
scope_kind: str
|
||||
scope_id: UUID
|
||||
scope_name: str
|
||||
epoch: int
|
||||
|
||||
|
||||
def get_conn(request: Request):
|
||||
pool = request.app.state.pool
|
||||
with pool.connection() as conn:
|
||||
try:
|
||||
conn.execute("SET TIME ZONE 'UTC'")
|
||||
yield conn
|
||||
conn.commit()
|
||||
for path in getattr(request.state, "delete_after_commit", []):
|
||||
discard_stored(path)
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
for path in getattr(request.state, "cleanup_files", []):
|
||||
discard_stored(path)
|
||||
raise
|
||||
|
||||
|
||||
def _session_row(conn: Connection, request: Request) -> dict:
|
||||
token = read_session_token(request)
|
||||
if not token:
|
||||
raise unauthorized()
|
||||
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, 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
|
||||
""",
|
||||
(hash_secret(token),),
|
||||
).fetchone()
|
||||
if row is None or row["revoked_at"] is not None or row["expires_at"] <= utcnow():
|
||||
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 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
|
||||
|
||||
|
||||
def get_session(request: Request, conn: Connection = Depends(get_conn)) -> dict:
|
||||
return _session_row(conn, request)
|
||||
|
||||
|
||||
def get_principal(request: Request, conn: Connection = Depends(get_conn)) -> Principal:
|
||||
row = _session_row(conn, request)
|
||||
kind = request.headers.get("x-scope-kind")
|
||||
raw_scope = request.headers.get("x-scope-id")
|
||||
if not kind or not raw_scope:
|
||||
raise forbidden("Der Datenraum ist nicht gewählt.")
|
||||
try:
|
||||
scope_id = UUID(raw_scope)
|
||||
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 scope_changed()
|
||||
room = ensure_member_or_personal(conn, row["account_id"], kind, scope_id)
|
||||
return Principal(
|
||||
account_id=row["account_id"],
|
||||
email=row["email"],
|
||||
display_name=row["display_name"],
|
||||
session_id=row["id"],
|
||||
scope_kind=kind,
|
||||
scope_id=scope_id,
|
||||
scope_name=room["name"],
|
||||
epoch=row["epoch"],
|
||||
)
|
||||
@@ -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")
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,553 @@
|
||||
"""Request bodies. Unknown fields are rejected."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
Email = Annotated[str, Field(min_length=3, max_length=320, pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")]
|
||||
|
||||
|
||||
class APIModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class LoginIn(APIModel):
|
||||
email: Email
|
||||
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
|
||||
|
||||
|
||||
class AcceptInviteIn(APIModel):
|
||||
token: str = Field(min_length=20, max_length=200)
|
||||
display_name: str = Field(min_length=1, max_length=120)
|
||||
password: str = Field(min_length=10, max_length=200)
|
||||
|
||||
|
||||
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", "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):
|
||||
kind: Literal["case", "matter"]
|
||||
id: UUID
|
||||
|
||||
|
||||
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):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
status: Literal["open", "closed"] | None = None
|
||||
|
||||
|
||||
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):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
status: Literal["open", "closed"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class CaseLinkIn(APIModel):
|
||||
case_id: UUID
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class CrossLinkIn(APIModel):
|
||||
target_matter_id: UUID
|
||||
target_context: ContextIn
|
||||
source_context: ContextIn | None = None
|
||||
|
||||
|
||||
class GrantIn(APIModel):
|
||||
email: Email
|
||||
can_read: bool = True
|
||||
can_edit: bool = False
|
||||
can_share: bool = False
|
||||
use_owner_sources: bool = False
|
||||
|
||||
|
||||
class ExceptionIn(APIModel):
|
||||
resource_kind: Literal["element", "matter", "task", "deadline"]
|
||||
resource_id: UUID
|
||||
context: ContextIn
|
||||
remove_read: bool = False
|
||||
remove_edit: bool = False
|
||||
remove_share: bool = False
|
||||
|
||||
|
||||
class DocumentIn(APIModel):
|
||||
version: Literal[1] = 1
|
||||
blocks: list[dict]
|
||||
|
||||
|
||||
class NoteIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
document: DocumentIn
|
||||
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):
|
||||
expected_version: int = Field(ge=1)
|
||||
document: DocumentIn
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class BindingIn(APIModel):
|
||||
element_id: UUID
|
||||
source_context: ContextIn
|
||||
target: ContextIn
|
||||
target_context: ContextIn | None = None
|
||||
chapter_id: UUID | None = None
|
||||
|
||||
|
||||
class AnnotationIn(APIModel):
|
||||
body: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
|
||||
class DatesIn(APIModel):
|
||||
document_on: date | None = None
|
||||
sent_on: date | None = None
|
||||
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: 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):
|
||||
expected_version: int = Field(ge=1)
|
||||
|
||||
|
||||
class TaskIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
due_on: date | None = None
|
||||
matter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class TaskPatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
due_on: date | None = None
|
||||
clear_due_on: bool = False
|
||||
status: Literal["open", "done"] | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class AssigneeIn(APIModel):
|
||||
email: str | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class DeadlineIn(APIModel):
|
||||
title: str = Field(min_length=1, max_length=200)
|
||||
due_on: date
|
||||
matter_id: UUID | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class DeadlinePatch(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
due_on: date | None = None
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
class FulfillIn(APIModel):
|
||||
expected_version: int = Field(ge=1)
|
||||
context: ContextIn | None = None
|
||||
|
||||
|
||||
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)
|
||||
@@ -0,0 +1 @@
|
||||
"""Accounts, sessions and cookies."""
|
||||
@@ -0,0 +1,328 @@
|
||||
"""Accounts, personal rooms, sessions and the administrative account actions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
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 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, 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, is_superadmin, origin,
|
||||
must_change_password, account_kind, sponsor_id,
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
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),
|
||||
)
|
||||
return conn.execute(
|
||||
"""
|
||||
SELECT id, email, display_name, is_superadmin, status, must_change_password, account_kind
|
||||
FROM auth_accounts WHERE id = %s
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
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()
|
||||
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, label, last_seen_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, now())
|
||||
RETURNING id
|
||||
""",
|
||||
(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'",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
rooms = []
|
||||
if personal is not None:
|
||||
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, 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'
|
||||
ORDER BY r.name, r.id
|
||||
""",
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
for room in shared:
|
||||
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
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Password hashing, session cookies and CSRF."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from functools import lru_cache
|
||||
|
||||
import bcrypt
|
||||
from fastapi import Request, Response
|
||||
|
||||
from app.core.settings import Settings
|
||||
from app.core.timeutil import utcnow
|
||||
|
||||
HOST_COOKIE = "__Host-jinkendo-session"
|
||||
PLAIN_COOKIE = "jinkendo-session"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
|
||||
except ValueError:
|
||||
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)
|
||||
|
||||
|
||||
def hash_secret(secret: str) -> str:
|
||||
return hashlib.sha256(secret.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def cookie_name_and_secure(request: Request, settings: Settings) -> tuple[str, bool]:
|
||||
# __Host- cookies require Secure. Production is only published behind HTTPS.
|
||||
# Development also serves the documented plain HTTP LAN addresses, which cannot store them.
|
||||
if settings.tsumugu_env == "production":
|
||||
return HOST_COOKIE, True
|
||||
forwarded = request.headers.get("x-forwarded-proto", request.url.scheme)
|
||||
if forwarded == "https":
|
||||
return HOST_COOKIE, True
|
||||
return PLAIN_COOKIE, False
|
||||
|
||||
|
||||
def read_session_token(request: Request) -> str | None:
|
||||
return request.cookies.get(HOST_COOKIE) or request.cookies.get(PLAIN_COOKIE)
|
||||
|
||||
|
||||
def set_session_cookie(response: Response, request: Request, settings: Settings, token: str) -> None:
|
||||
name, secure = cookie_name_and_secure(request, settings)
|
||||
response.set_cookie(
|
||||
key=name,
|
||||
value=token,
|
||||
httponly=True,
|
||||
secure=secure,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
max_age=settings.session_ttl_hours * 3600,
|
||||
)
|
||||
|
||||
|
||||
def clear_session_cookie(response: Response, request: Request, settings: Settings) -> None:
|
||||
name, secure = cookie_name_and_secure(request, settings)
|
||||
response.delete_cookie(key=name, path="/", secure=secure, httponly=True, samesite="lax")
|
||||
if name != PLAIN_COOKIE:
|
||||
response.delete_cookie(key=PLAIN_COOKIE, path="/", httponly=True, samesite="lax")
|
||||
|
||||
|
||||
def session_expiry(settings: Settings):
|
||||
return utcnow() + timedelta(hours=settings.session_ttl_hours)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Operator commands: migrate and create an account. Demo seed stays in the test suite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.settings import get_settings
|
||||
from app.db.migrate import migrate
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(prog="tsumugu")
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
sub.add_parser("migrate")
|
||||
sub.add_parser("seed-demo")
|
||||
create = sub.add_parser("create-account")
|
||||
create.add_argument("--email", required=True)
|
||||
create.add_argument("--name", required=True)
|
||||
create.add_argument("--password", required=True)
|
||||
args = parser.parse_args()
|
||||
settings = get_settings()
|
||||
if args.command == "migrate":
|
||||
applied = migrate(settings)
|
||||
print("applied" if applied else "up to date")
|
||||
return
|
||||
if args.command == "seed-demo":
|
||||
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:
|
||||
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"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
"""Notes, bindings, files and external references."""
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Bounded note documents. Paragraphs or one Markdown block are stored."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import unprocessable
|
||||
|
||||
|
||||
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"}:
|
||||
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
|
||||
if block.get("type") != "paragraph" or not isinstance(block.get("text"), str):
|
||||
raise unprocessable("Die Notiz enthält einen nicht unterstützten Block.")
|
||||
if len(block["text"]) > 20000:
|
||||
raise unprocessable("Ein Absatz ist zu lang.")
|
||||
clean.append({"type": "paragraph", "text": block["text"]})
|
||||
return {"version": 1, "blocks": clean}
|
||||
|
||||
|
||||
def document_text(document: dict) -> str:
|
||||
return "\n".join(block["text"] for block in document.get("blocks", []))
|
||||
@@ -0,0 +1 @@
|
||||
"""Core settings, errors and request helpers."""
|
||||
@@ -0,0 +1,96 @@
|
||||
"""RFC 9457 problem responses. Hidden objects use the same 404 as missing ones."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class Problem(Exception):
|
||||
def __init__(self, status: int, title: str, detail: str, code: str) -> None:
|
||||
super().__init__(detail)
|
||||
self.status = status
|
||||
self.title = title
|
||||
self.detail = detail
|
||||
self.code = code
|
||||
|
||||
def body(self, instance: str) -> dict:
|
||||
return {
|
||||
"type": "about:blank",
|
||||
"title": self.title,
|
||||
"status": self.status,
|
||||
"detail": self.detail,
|
||||
"instance": instance,
|
||||
"code": self.code,
|
||||
}
|
||||
|
||||
|
||||
def unauthorized() -> Problem:
|
||||
return Problem(401, "Anmeldung erforderlich", "Die Sitzung fehlt oder ist abgelaufen.", "unauthorized")
|
||||
|
||||
|
||||
def forbidden(detail: str = "Diese Aktion ist im gewählten Kontext nicht erlaubt.") -> Problem:
|
||||
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")
|
||||
|
||||
|
||||
def conflict() -> Problem:
|
||||
return Problem(
|
||||
409,
|
||||
"Versionskonflikt",
|
||||
"Der Stand hat sich geändert. Bitte neu laden.",
|
||||
"conflict",
|
||||
)
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
def storage_unavailable() -> Problem:
|
||||
return Problem(
|
||||
503,
|
||||
"Speicher nicht verfügbar",
|
||||
"Die Datei kann gerade nicht gelesen oder geschrieben werden.",
|
||||
"storage_unavailable",
|
||||
)
|
||||
|
||||
|
||||
def problem_response(problem: Problem, request: Request) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=problem.status,
|
||||
content=problem.body(request.url.path),
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Process settings. Unknown environments refuse to start."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(extra="ignore")
|
||||
|
||||
tsumugu_env: Literal["development", "production"]
|
||||
db_host: str = "localhost"
|
||||
db_port: int = 5432
|
||||
db_name: str
|
||||
db_user: str
|
||||
db_password: str
|
||||
db_runtime_user: str = "tsumugu_runtime"
|
||||
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
|
||||
|
||||
@field_validator("allowed_origins")
|
||||
@classmethod
|
||||
def strip_origins(cls, value: str) -> str:
|
||||
return value.strip()
|
||||
|
||||
@property
|
||||
def origin_set(self) -> set[str]:
|
||||
return {item.strip() for item in self.allowed_origins.split(",") if item.strip()}
|
||||
|
||||
def dsn(self, user: str | None = None) -> str:
|
||||
return (
|
||||
f"host={self.db_host} port={self.db_port} dbname={self.db_name} "
|
||||
f"user={user or self.db_user} password={self.db_password} connect_timeout=5"
|
||||
)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""UTC formatting for API values."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def dump_dt(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def dump_date(value: date | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
"""Database pool and migrations."""
|
||||
@@ -0,0 +1,107 @@
|
||||
"""SQL migrations with a checksum ledger, then a runtime role without DDL."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg import ClientCursor, sql
|
||||
|
||||
from app.core.settings import Settings, get_settings
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parent.parent.parent / "migrations"
|
||||
|
||||
|
||||
def _checksum(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def migrate(settings: Settings | None = None) -> list[str]:
|
||||
settings = settings or get_settings()
|
||||
applied: list[str] = []
|
||||
with psycopg.connect(settings.dsn(), autocommit=True, cursor_factory=ClientCursor) as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
checksum text NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
for path in sorted(MIGRATIONS.glob("*.sql")):
|
||||
version = path.name
|
||||
checksum = _checksum(path)
|
||||
row = conn.execute(
|
||||
"SELECT checksum FROM schema_migrations WHERE version = %s",
|
||||
(version,),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
if row[0] != checksum:
|
||||
raise RuntimeError(f"checksum mismatch for migration {version}")
|
||||
continue
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)",
|
||||
(version, checksum),
|
||||
)
|
||||
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)
|
||||
owner = sql.Identifier(settings.db_user)
|
||||
password = sql.Literal(settings.db_password)
|
||||
exists = conn.execute(
|
||||
"SELECT 1 FROM pg_roles WHERE rolname = %s",
|
||||
(settings.db_runtime_user,),
|
||||
).fetchone()
|
||||
if exists is None:
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}"
|
||||
).format(role, password)
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"ALTER ROLE {} WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT PASSWORD {}"
|
||||
).format(role, password)
|
||||
)
|
||||
conn.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(database, role))
|
||||
conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(role))
|
||||
conn.execute(sql.SQL("REVOKE CREATE ON SCHEMA public FROM {}").format(role))
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {}"
|
||||
).format(role)
|
||||
)
|
||||
conn.execute(sql.SQL("REVOKE ALL ON TABLE schema_migrations FROM {}").format(role))
|
||||
conn.execute(
|
||||
sql.SQL(
|
||||
"ALTER DEFAULT PRIVILEGES FOR ROLE {} IN SCHEMA public "
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO {}"
|
||||
).format(owner, role)
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Runtime connection pool. Importing the app does not open it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from app.core.settings import Settings
|
||||
|
||||
|
||||
def open_pool(settings: Settings) -> ConnectionPool:
|
||||
return ConnectionPool(
|
||||
conninfo=settings.dsn(settings.db_runtime_user),
|
||||
kwargs={"row_factory": dict_row},
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
open=True,
|
||||
timeout=10,
|
||||
)
|
||||
@@ -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",
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""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.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:
|
||||
prepare()
|
||||
os.execvp("uvicorn", ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
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
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Application factory. Importing this module does not open a database connection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
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
|
||||
|
||||
logger = logging.getLogger("tsumugu")
|
||||
|
||||
|
||||
def _database_ok(app: FastAPI) -> bool:
|
||||
pool = getattr(app.state, "pool", None)
|
||||
if pool is None:
|
||||
return False
|
||||
try:
|
||||
with pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
conn.rollback()
|
||||
return True
|
||||
except Exception:
|
||||
logger.warning("database check failed")
|
||||
return False
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
settings = get_settings()
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
app.state.pool = open_pool(settings)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
app.state.pool.close()
|
||||
|
||||
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
app.state.settings = settings
|
||||
|
||||
@app.middleware("http")
|
||||
async def origin_guard(request: Request, call_next):
|
||||
if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path.startswith("/api/"):
|
||||
origin = request.headers.get("origin")
|
||||
if origin not in settings.origin_set:
|
||||
problem = Problem(403, "Keine Berechtigung", "Der Ursprung der Anfrage ist nicht erlaubt.", "forbidden")
|
||||
return problem_response(problem, request)
|
||||
response = await call_next(request)
|
||||
logger.info("%s %s -> %s", request.method, request.url.path, response.status_code)
|
||||
return response
|
||||
|
||||
@app.exception_handler(Problem)
|
||||
async def handle_problem(request: Request, exc: Problem):
|
||||
return problem_response(exc, request)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation(request: Request, exc: RequestValidationError):
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content={
|
||||
"type": "about:blank",
|
||||
"title": "Eingabe ungültig",
|
||||
"status": 422,
|
||||
"detail": "Die Eingabe ist unvollständig oder ungültig.",
|
||||
"instance": request.url.path,
|
||||
"code": "unprocessable",
|
||||
},
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected(request: Request, exc: Exception):
|
||||
logger.exception("unhandled error")
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={
|
||||
"type": "about:blank",
|
||||
"title": "Unerwarteter Fehler",
|
||||
"status": 500,
|
||||
"detail": "Die Aktion konnte nicht abgeschlossen werden.",
|
||||
"instance": request.url.path,
|
||||
"code": "internal",
|
||||
},
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
|
||||
@app.get("/api/health")
|
||||
def api_health():
|
||||
ok = _database_ok(app)
|
||||
return JSONResponse(
|
||||
status_code=200 if ok else 503,
|
||||
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
|
||||
)
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok", "app": "tsumugu"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready():
|
||||
ok = _database_ok(app)
|
||||
return JSONResponse(
|
||||
status_code=200 if ok else 503,
|
||||
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
|
||||
app = create_app()
|
||||
@@ -0,0 +1 @@
|
||||
"""Private file storage. Paths are server-generated."""
|
||||
@@ -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
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Sniff uploads and keep client names out of the storage path."""
|
||||
|
||||
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
|
||||
|
||||
ALLOWED = {
|
||||
"application/pdf": "pdf",
|
||||
"image/png": "png",
|
||||
"image/jpeg": "jpg",
|
||||
"image/webp": "webp",
|
||||
}
|
||||
|
||||
|
||||
def sniff(data: bytes) -> str:
|
||||
if data.startswith(b"%PDF"):
|
||||
return "application/pdf"
|
||||
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "image/png"
|
||||
if data.startswith(b"\xff\xd8\xff"):
|
||||
return "image/jpeg"
|
||||
if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
|
||||
return "image/webp"
|
||||
raise unprocessable("Erlaubt sind PDF, PNG, JPEG und WebP.")
|
||||
|
||||
|
||||
def asset_path(media_root: str, asset_id: UUID) -> Path:
|
||||
root = Path(media_root).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
target = (root / str(asset_id)).resolve()
|
||||
if target.parent != root:
|
||||
raise unprocessable("Ungültiger Speicherpfad.")
|
||||
return target
|
||||
|
||||
|
||||
def write_bytes(path: Path, data: bytes) -> None:
|
||||
try:
|
||||
path.write_bytes(data)
|
||||
except OSError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
|
||||
def read_bytes(path: Path) -> bytes:
|
||||
try:
|
||||
if not path.is_file():
|
||||
raise storage_unavailable()
|
||||
return path.read_bytes()
|
||||
except OSError as exc:
|
||||
raise storage_unavailable() from exc
|
||||
|
||||
|
||||
def sha256(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def display_filename(name: str) -> str:
|
||||
cleaned = []
|
||||
for char in name.replace("\\", "/").split("/")[-1]:
|
||||
if char.isprintable() and char not in {'"', "\r", "\n", ":"}:
|
||||
cleaned.append(char)
|
||||
text = "".join(cleaned).strip() or "datei"
|
||||
return text[:240]
|
||||
|
||||
|
||||
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='')}"
|
||||
+1796
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)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Synthetic rental case for the ephemeral test database. Never persists on dev or prod."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from app.access.policy import Ctx
|
||||
from app.auth.accounts import create_account
|
||||
from app.core.errors import not_found
|
||||
from app.core.settings import Settings, get_settings
|
||||
from app.ops import (
|
||||
add_annotation,
|
||||
assign_task,
|
||||
bind_element,
|
||||
create_case,
|
||||
create_chapter,
|
||||
create_deadline,
|
||||
create_external,
|
||||
create_file,
|
||||
create_matter,
|
||||
create_note,
|
||||
create_task,
|
||||
grant_access,
|
||||
link_matter_to_case,
|
||||
link_task_deadline,
|
||||
)
|
||||
|
||||
ADA_EMAIL = "ada@example.test"
|
||||
BEN_EMAIL = "ben@example.test"
|
||||
ADA_PASSWORD = "Beispiel-Ada-2026"
|
||||
BEN_PASSWORD = "Beispiel-Ben-2026"
|
||||
|
||||
SAMPLE_PDF = b"""%PDF-1.1
|
||||
1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj
|
||||
2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj
|
||||
3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 320 160]/Contents 4 0 R>>endobj
|
||||
4 0 obj<</Length 55>>stream
|
||||
BT /F1 12 Tf 40 90 Td (Mietschreiben Beispiel) Tj ET
|
||||
endstream
|
||||
endobj
|
||||
trailer<</Root 1 0 R>>
|
||||
%%EOF
|
||||
"""
|
||||
|
||||
|
||||
_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 not demo_allowed(settings):
|
||||
raise not_found()
|
||||
return {
|
||||
"accounts": [
|
||||
{"email": ADA_EMAIL, "password": ADA_PASSWORD, "display_name": "Ada Beispiel"},
|
||||
{"email": BEN_EMAIL, "password": BEN_PASSWORD, "display_name": "Ben Beispiel"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def seed_demo(settings: Settings | None = None) -> bool:
|
||||
settings = settings or get_settings()
|
||||
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, 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, owner_id)
|
||||
VALUES (gen_random_uuid(), 'organization', 'Haushalt Musterstraße', %s, %s)
|
||||
RETURNING id
|
||||
""",
|
||||
(ada["id"], ada["id"]),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"INSERT INTO room_memberships (room_id, subject_id, role) VALUES (%s, %s, 'manager'), (%s, %s, 'member')",
|
||||
(room["id"], ada["id"], room["id"], ben["id"]),
|
||||
)
|
||||
private_case = create_case(conn, ada["id"], ada["id"], "Persönliche Verhandlungsstrategie", None, "explicit")
|
||||
shared_case = create_case(conn, ada["id"], ada["id"], "Mietstreit Musterstraße 12", None, "explicit")
|
||||
grant_access(conn, ada["id"], "case", shared_case["id"], ben["id"], True, True, False, None)
|
||||
strategy = create_matter(conn, ada["id"], ada["id"], "Interne Verhandlungsstrategie", None, None)
|
||||
moisture = create_matter(conn, ada["id"], ada["id"], "Mängelanzeige Feuchtigkeit", None, None)
|
||||
link_matter_to_case(conn, ada["id"], moisture["id"], shared_case["id"], None)
|
||||
link_matter_to_case(conn, ada["id"], strategy["id"], private_case["id"], None)
|
||||
note = create_note(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Gespräch mit der Hausverwaltung",
|
||||
{
|
||||
"version": 1,
|
||||
"blocks": [
|
||||
{
|
||||
"type": "paragraph",
|
||||
"text": (
|
||||
"Am 1. Oktober die Feuchtigkeit im Schlafzimmer angezeigt. "
|
||||
"Die Verwaltung will bis Ende November antworten."
|
||||
),
|
||||
}
|
||||
],
|
||||
},
|
||||
Ctx("case", shared_case["id"]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
matter_binding = bind_element(
|
||||
conn,
|
||||
ada["id"],
|
||||
note["element"]["id"],
|
||||
Ctx("case", shared_case["id"]),
|
||||
Ctx("matter", moisture["id"]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
add_annotation(
|
||||
conn,
|
||||
ada["id"],
|
||||
note["binding"]["id"],
|
||||
"Nur in der Akte: Original im blauen Ordner.",
|
||||
Ctx("case", shared_case["id"]),
|
||||
)
|
||||
add_annotation(
|
||||
conn,
|
||||
ada["id"],
|
||||
matter_binding["id"],
|
||||
"Nur in diesem Vorgang: Zeugin Frau Keller erinnern.",
|
||||
Ctx("matter", moisture["id"]),
|
||||
)
|
||||
create_note(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Nicht weitergeben",
|
||||
{
|
||||
"version": 1,
|
||||
"blocks": [
|
||||
{
|
||||
"type": "paragraph",
|
||||
"text": "Vergleich nur anbieten, wenn die Gegenseite zuerst einen Betrag nennt.",
|
||||
}
|
||||
],
|
||||
},
|
||||
Ctx("case", private_case["id"]),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
chapter = create_chapter(conn, ada["id"], "matter", moisture["id"], "Schriftwechsel", 0, None)
|
||||
create_file(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Schreiben an die Hausverwaltung",
|
||||
"Schreiben-Hausverwaltung.pdf",
|
||||
SAMPLE_PDF,
|
||||
Ctx("matter", moisture["id"]),
|
||||
None,
|
||||
chapter["id"],
|
||||
date(2026, 10, 1),
|
||||
date(2026, 10, 2),
|
||||
None,
|
||||
settings.media_root,
|
||||
settings.upload_max_bytes,
|
||||
cleanup,
|
||||
)
|
||||
create_external(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Antwort der Hausverwaltung",
|
||||
"paperless",
|
||||
"4821",
|
||||
Ctx("matter", moisture["id"]),
|
||||
None,
|
||||
chapter["id"],
|
||||
date(2026, 10, 8),
|
||||
None,
|
||||
date(2026, 10, 10),
|
||||
)
|
||||
task = create_task(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Unterlagen für die Antwort zusammenstellen",
|
||||
date(2026, 11, 25),
|
||||
moisture["id"],
|
||||
None,
|
||||
)
|
||||
assign_task(conn, ada["id"], task["id"], ben["id"], None)
|
||||
deadline = create_deadline(
|
||||
conn,
|
||||
ada["id"],
|
||||
ada["id"],
|
||||
"Antwort an die Gegenseite",
|
||||
date(2026, 11, 30),
|
||||
moisture["id"],
|
||||
None,
|
||||
)
|
||||
link_task_deadline(conn, ada["id"], task["id"], deadline["id"], None)
|
||||
conn.commit()
|
||||
return True
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
for path in cleanup:
|
||||
path.unlink(missing_ok=True)
|
||||
raise
|
||||
@@ -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
+3
-40
@@ -1,42 +1,5 @@
|
||||
"""Tsumugu — schmales Startgerüst, damit der Pi-Deploy einen Health-Check hat."""
|
||||
"""Uvicorn entry: `uvicorn main:app`."""
|
||||
|
||||
from __future__ import annotations
|
||||
from app.main import app
|
||||
|
||||
import os
|
||||
|
||||
import psycopg2
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None)
|
||||
|
||||
|
||||
def _database_status() -> str:
|
||||
try:
|
||||
connection = psycopg2.connect(
|
||||
host=os.environ.get("DB_HOST", "postgres"),
|
||||
port=os.environ.get("DB_PORT", "5432"),
|
||||
dbname=os.environ.get("DB_NAME", "tsumugu"),
|
||||
user=os.environ.get("DB_USER", "tsumugu"),
|
||||
password=os.environ.get("DB_PASSWORD", ""),
|
||||
connect_timeout=3,
|
||||
)
|
||||
connection.close()
|
||||
except Exception:
|
||||
return "error"
|
||||
return "ok"
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def api_health():
|
||||
database = _database_status()
|
||||
status = "ok" if database == "ok" else "degraded"
|
||||
return JSONResponse(
|
||||
status_code=200 if database == "ok" else 503,
|
||||
content={
|
||||
"status": status,
|
||||
"app": "tsumugu",
|
||||
"env": os.environ.get("TSUMUGU_ENV", "development"),
|
||||
"db": database,
|
||||
},
|
||||
)
|
||||
__all__ = ["app"]
|
||||
@@ -0,0 +1,356 @@
|
||||
-- Erster Fachschnitt: Identität, Struktur, Inhalte, Nachverfolgung, eigene Dateien.
|
||||
-- Finanz-, Zusammenstellungs- und Paperless-Abgleichstabellen gehören nicht in diese Lieferung.
|
||||
|
||||
CREATE TABLE auth_accounts (
|
||||
id uuid PRIMARY KEY,
|
||||
email text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT auth_accounts_status CHECK (status IN ('active', 'disabled')),
|
||||
CONSTRAINT auth_accounts_email_len CHECK (char_length(email) <= 320),
|
||||
CONSTRAINT auth_accounts_name_len CHECK (char_length(display_name) BETWEEN 1 AND 120)
|
||||
);
|
||||
|
||||
CREATE TABLE data_rooms (
|
||||
id uuid PRIMARY KEY,
|
||||
kind text NOT NULL,
|
||||
name text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT data_rooms_kind CHECK (kind IN ('personal', 'organization')),
|
||||
CONSTRAINT data_rooms_status CHECK (status IN ('active', 'archived')),
|
||||
CONSTRAINT data_rooms_name_len CHECK (char_length(name) BETWEEN 1 AND 160)
|
||||
);
|
||||
|
||||
CREATE TABLE auth_sessions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
account_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
secret_hash text NOT NULL UNIQUE,
|
||||
csrf_token text NOT NULL,
|
||||
scope_kind text NOT NULL,
|
||||
scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
epoch integer NOT NULL DEFAULT 1,
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT auth_sessions_scope_kind CHECK (scope_kind IN ('personal', 'organization'))
|
||||
);
|
||||
|
||||
CREATE INDEX auth_sessions_account ON auth_sessions (account_id);
|
||||
|
||||
CREATE TABLE auth_invitations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
email text NOT NULL,
|
||||
room_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
token_hash text NOT NULL UNIQUE,
|
||||
invited_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
expires_at timestamptz NOT NULL,
|
||||
accepted_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE room_memberships (
|
||||
room_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
role text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (room_id, subject_id),
|
||||
CONSTRAINT room_memberships_role CHECK (role IN ('member', 'manager')),
|
||||
CONSTRAINT room_memberships_status CHECK (status IN ('active', 'removed'))
|
||||
);
|
||||
|
||||
CREATE TABLE cases (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
parent_case_id uuid,
|
||||
rights_mode text NOT NULL DEFAULT 'explicit',
|
||||
record_status text NOT NULL DEFAULT 'open',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT cases_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT cases_rights_mode CHECK (rights_mode IN ('inherit_parent', 'explicit')),
|
||||
CONSTRAINT cases_status CHECK (record_status IN ('open', 'closed')),
|
||||
CONSTRAINT cases_root_explicit CHECK (
|
||||
(parent_case_id IS NULL AND rights_mode = 'explicit')
|
||||
OR parent_case_id IS NOT NULL
|
||||
),
|
||||
UNIQUE (id, home_scope_id)
|
||||
);
|
||||
|
||||
ALTER TABLE cases
|
||||
ADD CONSTRAINT cases_parent_same_scope
|
||||
FOREIGN KEY (parent_case_id, home_scope_id) REFERENCES cases (id, home_scope_id);
|
||||
|
||||
CREATE INDEX cases_owner ON cases (owner_subject_id) WHERE deleted_at IS NULL;
|
||||
CREATE INDEX cases_home ON cases (home_scope_id) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE matters (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
parent_matter_id uuid,
|
||||
record_status text NOT NULL DEFAULT 'open',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT matters_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT matters_status CHECK (record_status IN ('open', 'closed')),
|
||||
UNIQUE (id, home_scope_id)
|
||||
);
|
||||
|
||||
ALTER TABLE matters
|
||||
ADD CONSTRAINT matters_parent_same_scope
|
||||
FOREIGN KEY (parent_matter_id, home_scope_id) REFERENCES matters (id, home_scope_id);
|
||||
|
||||
CREATE INDEX matters_owner ON matters (owner_subject_id) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE chapters (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
case_id uuid,
|
||||
matter_id uuid,
|
||||
title text NOT NULL,
|
||||
position integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chapters_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT chapters_one_container CHECK ((case_id IS NULL) <> (matter_id IS NULL))
|
||||
);
|
||||
|
||||
ALTER TABLE chapters
|
||||
ADD CONSTRAINT chapters_case_same_scope
|
||||
FOREIGN KEY (case_id, home_scope_id) REFERENCES cases (id, home_scope_id);
|
||||
|
||||
ALTER TABLE chapters
|
||||
ADD CONSTRAINT chapters_matter_same_scope
|
||||
FOREIGN KEY (matter_id, home_scope_id) REFERENCES matters (id, home_scope_id);
|
||||
|
||||
CREATE TABLE matter_case_links (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
matter_id uuid NOT NULL REFERENCES matters (id),
|
||||
case_id uuid NOT NULL REFERENCES cases (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (matter_id, case_id)
|
||||
);
|
||||
|
||||
CREATE INDEX matter_case_links_case ON matter_case_links (case_id);
|
||||
|
||||
CREATE TABLE case_link_blocks (
|
||||
link_id uuid NOT NULL REFERENCES matter_case_links (id) ON DELETE CASCADE,
|
||||
element_id uuid NOT NULL,
|
||||
PRIMARY KEY (link_id, element_id)
|
||||
);
|
||||
|
||||
CREATE TABLE matter_cross_links (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
from_matter_id uuid NOT NULL REFERENCES matters (id),
|
||||
to_matter_id uuid NOT NULL REFERENCES matters (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (from_matter_id, to_matter_id),
|
||||
CONSTRAINT matter_cross_links_distinct CHECK (from_matter_id <> to_matter_id)
|
||||
);
|
||||
|
||||
CREATE TABLE elements (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
kind text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT elements_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT elements_kind CHECK (kind IN ('note', 'file', 'external_ref')),
|
||||
UNIQUE (id, home_scope_id)
|
||||
);
|
||||
|
||||
CREATE INDEX elements_owner ON elements (owner_subject_id) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE note_bodies (
|
||||
element_id uuid PRIMARY KEY REFERENCES elements (id),
|
||||
document_json jsonb NOT NULL,
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE correspondence_dates (
|
||||
element_id uuid PRIMARY KEY REFERENCES elements (id),
|
||||
document_on date,
|
||||
sent_on date,
|
||||
received_on date
|
||||
);
|
||||
|
||||
CREATE TABLE external_references (
|
||||
element_id uuid PRIMARY KEY REFERENCES elements (id),
|
||||
source text NOT NULL,
|
||||
external_id text NOT NULL,
|
||||
CONSTRAINT external_references_source CHECK (source IN ('paperless', 'url')),
|
||||
CONSTRAINT external_references_id_len CHECK (char_length(external_id) BETWEEN 1 AND 200)
|
||||
);
|
||||
|
||||
CREATE TABLE bindings (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
element_id uuid NOT NULL REFERENCES elements (id),
|
||||
context_kind text NOT NULL,
|
||||
context_id uuid NOT NULL,
|
||||
chapter_id uuid REFERENCES chapters (id),
|
||||
position integer NOT NULL DEFAULT 0,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (element_id, context_kind, context_id),
|
||||
CONSTRAINT bindings_context_kind CHECK (context_kind IN ('case', 'matter'))
|
||||
);
|
||||
|
||||
CREATE INDEX bindings_context ON bindings (context_kind, context_id);
|
||||
|
||||
CREATE TABLE context_annotations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
binding_id uuid NOT NULL REFERENCES bindings (id) ON DELETE CASCADE,
|
||||
body text NOT NULL,
|
||||
author_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT context_annotations_body CHECK (char_length(body) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
CREATE TABLE access_grants (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
grantee_subject_id uuid REFERENCES auth_accounts (id),
|
||||
resource_kind text NOT NULL,
|
||||
resource_id uuid NOT NULL,
|
||||
context_kind text,
|
||||
context_id uuid,
|
||||
can_read boolean NOT NULL DEFAULT false,
|
||||
can_edit boolean NOT NULL DEFAULT false,
|
||||
can_share boolean NOT NULL DEFAULT false,
|
||||
can_delete boolean NOT NULL DEFAULT false,
|
||||
is_exception boolean NOT NULL DEFAULT false,
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT access_grants_kind CHECK (resource_kind IN ('case', 'matter', 'element', 'task', 'deadline')),
|
||||
CONSTRAINT access_grants_context_pair CHECK ((context_kind IS NULL) = (context_id IS NULL)),
|
||||
CONSTRAINT access_grants_context_kind CHECK (context_kind IS NULL OR context_kind IN ('case', 'matter')),
|
||||
CONSTRAINT access_grants_grantee CHECK (is_exception OR grantee_subject_id IS NOT NULL),
|
||||
CONSTRAINT access_grants_exception_flag CHECK (
|
||||
NOT is_exception OR can_read OR can_edit OR can_share OR can_delete
|
||||
)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX access_grants_identity ON access_grants (
|
||||
resource_kind,
|
||||
resource_id,
|
||||
COALESCE(grantee_subject_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
COALESCE(context_kind, ''),
|
||||
COALESCE(context_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
is_exception
|
||||
);
|
||||
|
||||
CREATE INDEX access_grants_grantee ON access_grants (grantee_subject_id);
|
||||
CREATE INDEX access_grants_resource ON access_grants (resource_kind, resource_id);
|
||||
|
||||
CREATE TABLE tasks (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
matter_id uuid REFERENCES matters (id),
|
||||
assignee_subject_id uuid REFERENCES auth_accounts (id),
|
||||
due_on date,
|
||||
task_status text NOT NULL DEFAULT 'open',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT tasks_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT tasks_status CHECK (task_status IN ('open', 'done'))
|
||||
);
|
||||
|
||||
CREATE INDEX tasks_open ON tasks (task_status) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE deadlines (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
title text NOT NULL,
|
||||
matter_id uuid REFERENCES matters (id),
|
||||
element_id uuid REFERENCES elements (id),
|
||||
assignee_subject_id uuid REFERENCES auth_accounts (id),
|
||||
due_on date NOT NULL,
|
||||
deadline_status text NOT NULL DEFAULT 'open',
|
||||
fulfilled_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
deleted_at timestamptz,
|
||||
CONSTRAINT deadlines_title_len CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
CONSTRAINT deadlines_status CHECK (deadline_status IN ('open', 'fulfilled'))
|
||||
);
|
||||
|
||||
CREATE INDEX deadlines_open ON deadlines (deadline_status) WHERE deleted_at IS NULL;
|
||||
|
||||
CREATE TABLE task_deadline_links (
|
||||
task_id uuid NOT NULL REFERENCES tasks (id),
|
||||
deadline_id uuid NOT NULL REFERENCES deadlines (id),
|
||||
created_by uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (task_id, deadline_id)
|
||||
);
|
||||
|
||||
CREATE TABLE media_assets (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
element_id uuid NOT NULL UNIQUE REFERENCES elements (id),
|
||||
owner_subject_id uuid NOT NULL REFERENCES auth_accounts (id),
|
||||
home_scope_id uuid NOT NULL REFERENCES data_rooms (id),
|
||||
original_filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
byte_size bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
revision integer NOT NULL DEFAULT 1,
|
||||
status text NOT NULL DEFAULT 'active',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT media_assets_status CHECK (status IN ('active', 'purging', 'purged')),
|
||||
CONSTRAINT media_assets_filename CHECK (char_length(original_filename) BETWEEN 1 AND 240)
|
||||
);
|
||||
|
||||
CREATE TABLE media_operations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
element_id uuid,
|
||||
asset_id uuid,
|
||||
phase text NOT NULL,
|
||||
status text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE domain_events (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
actor_subject_id uuid REFERENCES auth_accounts (id),
|
||||
scope_id uuid,
|
||||
action text NOT NULL,
|
||||
resource_kind text NOT NULL,
|
||||
resource_id uuid NOT NULL,
|
||||
context_kind text,
|
||||
context_id uuid,
|
||||
occurred_on date,
|
||||
occurred_at timestamptz NOT NULL DEFAULT now(),
|
||||
result text NOT NULL DEFAULT 'ok'
|
||||
);
|
||||
|
||||
CREATE INDEX domain_events_resource ON domain_events (resource_kind, resource_id);
|
||||
CREATE INDEX domain_events_context ON domain_events (context_kind, context_id);
|
||||
@@ -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,3 @@
|
||||
-r requirements.txt
|
||||
pytest==8.3.4
|
||||
httpx==0.28.1
|
||||
@@ -1,3 +1,7 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.34.0
|
||||
psycopg2-binary==2.9.10
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg-pool==3.2.4
|
||||
bcrypt==4.2.1
|
||||
pydantic-settings==2.6.1
|
||||
python-multipart==0.0.18
|
||||
@@ -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"])
|
||||
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user