Meilenstein 2: Verbindungs-API und Dashboard
- CRUD-API /api/connections mit Filter nach Sichtbarkeit und Typ - Sichtbarkeit: privat nur für Besitzer (sonst 404), team für alle bearbeitbar; nur der Besitzer darf team auf privat setzen - Strenge serverseitige Prüfung von Ziel, Port, Benutzer und URL - Dashboard mit Kacheln nach Typ, Filter Alle/Privat/Team, Suche, Dialog zum Anlegen/Bearbeiten, Links itrdp:// und itssh:// - Tests für Validierung und Sichtbarkeitslogik, SETUP.md ergänzt Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
293367f33e
commit
2e89c4ad59
10 files changed
+816
-30
No files matched your search
+2
-1
@@ -7,7 +7,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .config import PROJEKT_ROOT
|
||||
from .db import init_db
|
||||
from .routes import auth_routes
|
||||
from .routes import auth_routes, connections
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
@@ -33,6 +33,7 @@ async def sicherheits_header(request, call_next):
|
||||
|
||||
|
||||
app.include_router(auth_routes.router)
|
||||
app.include_router(connections.router)
|
||||
|
||||
# Frontend zuletzt einhängen, damit /api/* Vorrang hat
|
||||
app.mount("/", StaticFiles(directory=PROJEKT_ROOT / "frontend", html=True), name="frontend")
|
||||
+76
-1
@@ -1,6 +1,16 @@
|
||||
"""Pydantic-Modelle für Requests und Responses."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator, model_validator
|
||||
|
||||
from .validierung import (
|
||||
STANDARD_PORTS,
|
||||
benutzer_pruefen,
|
||||
host_pruefen,
|
||||
text_pruefen,
|
||||
url_pruefen,
|
||||
)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
@@ -12,3 +22,68 @@ class AdminInfo(BaseModel):
|
||||
id: int
|
||||
benutzername: str
|
||||
csrf_token: str
|
||||
|
||||
|
||||
Typ = Literal["rdp", "ssh", "web"]
|
||||
Sichtbarkeit = Literal["privat", "team"]
|
||||
|
||||
|
||||
class ConnectionIn(BaseModel):
|
||||
typ: Typ
|
||||
anzeigename: str = Field(min_length=1, max_length=100)
|
||||
ziel: str = Field(min_length=1, max_length=2048)
|
||||
port: int | None = Field(default=None, ge=1, le=65535)
|
||||
benutzer: str | None = Field(default=None, max_length=64)
|
||||
notiz: str | None = Field(default=None, max_length=2000)
|
||||
sichtbarkeit: Sichtbarkeit = "privat"
|
||||
|
||||
@field_validator("anzeigename")
|
||||
@classmethod
|
||||
def _anzeigename(cls, v: str) -> str:
|
||||
v = text_pruefen(v, "Anzeigename")
|
||||
if not v:
|
||||
raise ValueError("Anzeigename darf nicht leer sein.")
|
||||
return v
|
||||
|
||||
@field_validator("notiz")
|
||||
@classmethod
|
||||
def _notiz(cls, v: str | None) -> str | None:
|
||||
if v is None:
|
||||
return None
|
||||
v = text_pruefen(v, "Notiz", mehrzeilig=True)
|
||||
return v or None
|
||||
|
||||
@field_validator("benutzer")
|
||||
@classmethod
|
||||
def _benutzer(cls, v: str | None) -> str | None:
|
||||
if v is None or not v.strip():
|
||||
return None
|
||||
return benutzer_pruefen(v)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _ziel_und_port(self):
|
||||
if self.typ == "web":
|
||||
self.ziel = url_pruefen(self.ziel)
|
||||
# Bei Web steckt der Port in der URL, Benutzer ist nicht sinnvoll
|
||||
self.port = None
|
||||
self.benutzer = None
|
||||
else:
|
||||
self.ziel = host_pruefen(self.ziel)
|
||||
if self.port is None:
|
||||
self.port = STANDARD_PORTS[self.typ]
|
||||
return self
|
||||
|
||||
|
||||
class ConnectionOut(BaseModel):
|
||||
id: int
|
||||
typ: Typ
|
||||
anzeigename: str
|
||||
ziel: str
|
||||
port: int | None
|
||||
benutzer: str | None
|
||||
notiz: str | None
|
||||
sichtbarkeit: Sichtbarkeit
|
||||
besitzer_id: int
|
||||
besitzer_name: str
|
||||
erstellt_am: str
|
||||
geaendert_am: str
|
||||
@@ -0,0 +1,115 @@
|
||||
"""CRUD-API für Verbindungen mit Sichtbarkeitslogik.
|
||||
|
||||
- privat: nur der Besitzer sieht und bearbeitet den Eintrag
|
||||
- team: alle Admins sehen und bearbeiten den Eintrag
|
||||
"""
|
||||
|
||||
import sqlite3
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
|
||||
from ..auth import aktueller_admin
|
||||
from ..db import get_db, jetzt
|
||||
from ..models import ConnectionIn, ConnectionOut, Sichtbarkeit, Typ
|
||||
|
||||
router = APIRouter(prefix="/api/connections", tags=["connections"])
|
||||
|
||||
_SELECT = (
|
||||
"SELECT c.*, a.benutzername AS besitzer_name "
|
||||
"FROM connections c JOIN admins a ON a.id = c.besitzer_id "
|
||||
)
|
||||
# Sichtbar ist alles, was team ist oder dem aktuellen Admin gehört
|
||||
_SICHTBAR = "(c.sichtbarkeit = 'team' OR c.besitzer_id = ?)"
|
||||
|
||||
|
||||
def _laden(db: sqlite3.Connection, conn_id: int, admin_id: int) -> sqlite3.Row:
|
||||
row = db.execute(
|
||||
_SELECT + f"WHERE c.id = ? AND {_SICHTBAR}", (conn_id, admin_id)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
# Fremde private Einträge sind nicht von nicht vorhandenen zu unterscheiden
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Eintrag nicht gefunden.")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("", response_model=list[ConnectionOut])
|
||||
def liste(
|
||||
sichtbarkeit: Sichtbarkeit | None = Query(default=None),
|
||||
typ: Typ | None = Query(default=None),
|
||||
session=Depends(aktueller_admin),
|
||||
db: sqlite3.Connection = Depends(get_db),
|
||||
):
|
||||
sql = _SELECT + f"WHERE {_SICHTBAR}"
|
||||
params: list = [session["admin_id"]]
|
||||
if sichtbarkeit:
|
||||
sql += " AND c.sichtbarkeit = ?"
|
||||
params.append(sichtbarkeit)
|
||||
if typ:
|
||||
sql += " AND c.typ = ?"
|
||||
params.append(typ)
|
||||
sql += " ORDER BY c.typ, c.anzeigename COLLATE NOCASE"
|
||||
return [dict(r) for r in db.execute(sql, params).fetchall()]
|
||||
|
||||
|
||||
@router.post("", response_model=ConnectionOut, status_code=status.HTTP_201_CREATED)
|
||||
def anlegen(
|
||||
daten: ConnectionIn,
|
||||
session=Depends(aktueller_admin),
|
||||
db: sqlite3.Connection = Depends(get_db),
|
||||
):
|
||||
zeit = jetzt()
|
||||
cur = db.execute(
|
||||
"INSERT INTO connections (typ, anzeigename, ziel, port, benutzer, notiz, "
|
||||
"besitzer_id, sichtbarkeit, erstellt_am, geaendert_am) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
daten.typ, daten.anzeigename, daten.ziel, daten.port, daten.benutzer,
|
||||
daten.notiz, session["admin_id"], daten.sichtbarkeit, zeit, zeit,
|
||||
),
|
||||
)
|
||||
return dict(_laden(db, cur.lastrowid, session["admin_id"]))
|
||||
|
||||
|
||||
@router.get("/{conn_id}", response_model=ConnectionOut)
|
||||
def einzeln(
|
||||
conn_id: int,
|
||||
session=Depends(aktueller_admin),
|
||||
db: sqlite3.Connection = Depends(get_db),
|
||||
):
|
||||
return dict(_laden(db, conn_id, session["admin_id"]))
|
||||
|
||||
|
||||
@router.put("/{conn_id}", response_model=ConnectionOut)
|
||||
def aendern(
|
||||
conn_id: int,
|
||||
daten: ConnectionIn,
|
||||
session=Depends(aktueller_admin),
|
||||
db: sqlite3.Connection = Depends(get_db),
|
||||
):
|
||||
alt = _laden(db, conn_id, session["admin_id"])
|
||||
ist_besitzer = alt["besitzer_id"] == session["admin_id"]
|
||||
if daten.sichtbarkeit == "privat" and alt["sichtbarkeit"] == "team" and not ist_besitzer:
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
"Nur der Besitzer kann einen Team-Eintrag auf privat setzen.",
|
||||
)
|
||||
db.execute(
|
||||
"UPDATE connections SET typ = ?, anzeigename = ?, ziel = ?, port = ?, benutzer = ?, "
|
||||
"notiz = ?, sichtbarkeit = ?, geaendert_am = ? WHERE id = ?",
|
||||
(
|
||||
daten.typ, daten.anzeigename, daten.ziel, daten.port, daten.benutzer,
|
||||
daten.notiz, daten.sichtbarkeit, jetzt(), conn_id,
|
||||
),
|
||||
)
|
||||
return dict(_laden(db, conn_id, session["admin_id"]))
|
||||
|
||||
|
||||
@router.delete("/{conn_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def loeschen(
|
||||
conn_id: int,
|
||||
session=Depends(aktueller_admin),
|
||||
db: sqlite3.Connection = Depends(get_db),
|
||||
):
|
||||
_laden(db, conn_id, session["admin_id"])
|
||||
db.execute("DELETE FROM connections WHERE id = ?", (conn_id,))
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Strenge Prüfung von Zielen, Ports und Benutzernamen (Sicherheitsregel 3).
|
||||
|
||||
Erlaubt sind nur Buchstaben, Ziffern, Punkte, Bindestriche, Doppelpunkte bei IPv6
|
||||
und Unterstriche bei Benutzernamen. Keine Shell-Metazeichen.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
# Ein Label eines Hostnamens: 1–63 Zeichen, Buchstaben/Ziffern/Bindestrich, nicht mit '-' am Rand
|
||||
_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$")
|
||||
BENUTZER_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
|
||||
_STEUERZEICHEN_RE = re.compile(r"[\x00-\x1f\x7f]")
|
||||
|
||||
STANDARD_PORTS = {"rdp": 3389, "ssh": 22}
|
||||
|
||||
|
||||
def ist_hostname(wert: str) -> bool:
|
||||
if not wert or len(wert) > 253:
|
||||
return False
|
||||
labels = wert.rstrip(".").split(".") if wert != "." else []
|
||||
return bool(labels) and all(_LABEL_RE.fullmatch(label) for label in labels)
|
||||
|
||||
|
||||
def ist_ip(wert: str) -> bool:
|
||||
# Nur reine Adressen, keine Zonen-IDs (%eth0) und keine Klammern
|
||||
if not re.fullmatch(r"[0-9A-Fa-f.:]+", wert):
|
||||
return False
|
||||
try:
|
||||
ipaddress.ip_address(wert)
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def host_pruefen(wert: str) -> str:
|
||||
wert = wert.strip()
|
||||
if ist_ip(wert) or ist_hostname(wert):
|
||||
return wert
|
||||
raise ValueError("Ungültiges Ziel. Erlaubt sind IP-Adressen und Hostnamen (Buchstaben, Ziffern, Punkte, Bindestriche).")
|
||||
|
||||
|
||||
def url_pruefen(wert: str) -> str:
|
||||
wert = wert.strip()
|
||||
if len(wert) > 2048 or _STEUERZEICHEN_RE.search(wert) or " " in wert:
|
||||
raise ValueError("Ungültige URL.")
|
||||
teile = urlsplit(wert)
|
||||
if teile.scheme.lower() not in ("http", "https"):
|
||||
raise ValueError("Die URL muss mit http:// oder https:// beginnen.")
|
||||
host = teile.hostname or ""
|
||||
if not (ist_hostname(host) or ist_ip(host)):
|
||||
raise ValueError("Die URL enthält keinen gültigen Hostnamen.")
|
||||
try:
|
||||
teile.port # löst bei ungültigem Port ValueError aus
|
||||
except ValueError:
|
||||
raise ValueError("Die URL enthält einen ungültigen Port.") from None
|
||||
return wert
|
||||
|
||||
|
||||
def benutzer_pruefen(wert: str) -> str:
|
||||
wert = wert.strip()
|
||||
if not BENUTZER_RE.fullmatch(wert):
|
||||
raise ValueError("Ungültiger Benutzername. Erlaubt sind Buchstaben, Ziffern, Punkte, Bindestriche und Unterstriche.")
|
||||
return wert
|
||||
|
||||
|
||||
def text_pruefen(wert: str, feld: str, *, mehrzeilig: bool = False) -> str:
|
||||
wert = wert.strip()
|
||||
erlaubt = wert.replace("\n", "").replace("\r", "").replace("\t", "") if mehrzeilig else wert
|
||||
if _STEUERZEICHEN_RE.search(erlaubt):
|
||||
raise ValueError(f"{feld} enthält unzulässige Steuerzeichen.")
|
||||
return wert
|
||||
@@ -21,16 +21,43 @@ def client(tmp_path, monkeypatch):
|
||||
yield c
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin(client):
|
||||
"""Legt den Test-Admin 'testadmin' an."""
|
||||
def admin_anlegen(benutzername: str, passwort: str) -> dict:
|
||||
from app.auth import passwort_hashen
|
||||
from app.db import jetzt, verbinden
|
||||
|
||||
conn = verbinden()
|
||||
conn.execute(
|
||||
"INSERT INTO admins (benutzername, passwort_hash, erstellt_am) VALUES (?, ?, ?)",
|
||||
("testadmin", passwort_hashen("geheimes-test-passwort"), jetzt()),
|
||||
(benutzername, passwort_hashen(passwort), jetzt()),
|
||||
)
|
||||
conn.close()
|
||||
return {"benutzername": "testadmin", "passwort": "geheimes-test-passwort"}
|
||||
return {"benutzername": benutzername, "passwort": passwort}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin(client):
|
||||
"""Legt den Test-Admin 'testadmin' an."""
|
||||
return admin_anlegen("testadmin", "geheimes-test-passwort")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def als(client):
|
||||
"""Liefert eine Funktion, die einen Admin anlegt, einloggt und einen eigenen Client zurückgibt."""
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
clients = []
|
||||
|
||||
def _als(benutzername: str) -> TestClient:
|
||||
daten = admin_anlegen(benutzername, "passwort-fuer-" + benutzername)
|
||||
c = TestClient(app)
|
||||
r = c.post("/api/auth/login", json=daten)
|
||||
assert r.status_code == 200, r.text
|
||||
c.headers["X-CSRF-Token"] = r.json()["csrf_token"]
|
||||
clients.append(c)
|
||||
return c
|
||||
|
||||
yield _als
|
||||
for c in clients:
|
||||
c.close()
|
||||
@@ -0,0 +1,130 @@
|
||||
import pytest
|
||||
|
||||
RDP = {
|
||||
"typ": "rdp",
|
||||
"anzeigename": "Fileserver Test",
|
||||
"ziel": "test-server-01.example.local",
|
||||
"benutzer": "test_admin",
|
||||
"sichtbarkeit": "privat",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def alice(client, als):
|
||||
return als("alice")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bob(client, als):
|
||||
return als("bob")
|
||||
|
||||
|
||||
def anlegen(c, **aenderungen):
|
||||
r = c.post("/api/connections", json={**RDP, **aenderungen})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def test_ohne_login_kein_zugriff(client):
|
||||
assert client.get("/api/connections").status_code == 401
|
||||
|
||||
|
||||
def test_anlegen_ohne_csrf_abgelehnt(alice):
|
||||
del alice.headers["X-CSRF-Token"]
|
||||
assert alice.post("/api/connections", json=RDP).status_code == 403
|
||||
|
||||
|
||||
def test_anlegen_setzt_standardport_und_besitzer(alice):
|
||||
c = anlegen(alice)
|
||||
assert c["port"] == 3389
|
||||
assert c["besitzer_name"] == "alice"
|
||||
assert anlegen(alice, typ="ssh")["port"] == 22
|
||||
|
||||
|
||||
def test_web_eintrag(alice):
|
||||
c = anlegen(alice, typ="web", ziel="https://intranet.example.local/wiki", port=8443, benutzer="x")
|
||||
assert c["ziel"] == "https://intranet.example.local/wiki"
|
||||
assert c["port"] is None and c["benutzer"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ziel", [
|
||||
"test-server-01.example.local", "192.0.2.10", "2001:db8::1", "fe80::1", "srv01",
|
||||
])
|
||||
def test_gueltige_ziele(alice, ziel):
|
||||
anlegen(alice, ziel=ziel)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ziel", [
|
||||
"server; calc.exe", "server&whoami", "server|x", "$(id)", "`id`", "a b",
|
||||
"-server", "server-.example.local", "[2001:db8::1]", "fe80::1%eth0",
|
||||
"host/path", "host\\x", "'host'", "\"host\"", "ho\nst", "",
|
||||
])
|
||||
def test_ungueltige_ziele(alice, ziel):
|
||||
r = alice.post("/api/connections", json={**RDP, "ziel": ziel})
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.parametrize("benutzer", ["admin;x", "DOMAIN\\user", "a b", "user@domain", "$x", "a" * 65])
|
||||
def test_ungueltige_benutzer(alice, benutzer):
|
||||
assert alice.post("/api/connections", json={**RDP, "benutzer": benutzer}).status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.parametrize("port", [0, 65536, -1])
|
||||
def test_ungueltige_ports(alice, port):
|
||||
assert alice.post("/api/connections", json={**RDP, "port": port}).status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [
|
||||
"javascript:alert(1)", "ftp://x.example.local", "intranet.example.local",
|
||||
"https://", "https://a b.example.local", "https://x.example.local:99999/",
|
||||
])
|
||||
def test_ungueltige_urls(alice, url):
|
||||
assert alice.post("/api/connections", json={**RDP, "typ": "web", "ziel": url}).status_code == 422
|
||||
|
||||
|
||||
def test_privat_nur_fuer_besitzer(alice, bob):
|
||||
c = anlegen(alice)
|
||||
assert [x["id"] for x in alice.get("/api/connections").json()] == [c["id"]]
|
||||
assert bob.get("/api/connections").json() == []
|
||||
assert bob.get(f"/api/connections/{c['id']}").status_code == 404
|
||||
assert bob.put(f"/api/connections/{c['id']}", json=RDP).status_code == 404
|
||||
assert bob.delete(f"/api/connections/{c['id']}").status_code == 404
|
||||
assert alice.get(f"/api/connections/{c['id']}").status_code == 200
|
||||
|
||||
|
||||
def test_team_fuer_alle_sicht_und_bearbeitbar(alice, bob):
|
||||
c = anlegen(alice, sichtbarkeit="team")
|
||||
assert [x["id"] for x in bob.get("/api/connections").json()] == [c["id"]]
|
||||
r = bob.put(f"/api/connections/{c['id']}", json={**RDP, "sichtbarkeit": "team", "anzeigename": "Neu"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["anzeigename"] == "Neu"
|
||||
assert r.json()["besitzer_name"] == "alice"
|
||||
assert bob.delete(f"/api/connections/{c['id']}").status_code == 204
|
||||
assert alice.get(f"/api/connections/{c['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_nur_besitzer_darf_team_auf_privat_setzen(alice, bob):
|
||||
c = anlegen(alice, sichtbarkeit="team")
|
||||
r = bob.put(f"/api/connections/{c['id']}", json={**RDP, "sichtbarkeit": "privat"})
|
||||
assert r.status_code == 403
|
||||
r = alice.put(f"/api/connections/{c['id']}", json={**RDP, "sichtbarkeit": "privat"})
|
||||
assert r.status_code == 200
|
||||
assert bob.get("/api/connections").json() == []
|
||||
|
||||
|
||||
def test_filter(alice, bob):
|
||||
p = anlegen(alice)
|
||||
t = anlegen(alice, typ="ssh", sichtbarkeit="team")
|
||||
anlegen(bob) # fremder privater Eintrag, darf nie auftauchen
|
||||
ids = lambda q: [x["id"] for x in alice.get("/api/connections" + q).json()] # noqa: E731
|
||||
assert sorted(ids("")) == sorted([p["id"], t["id"]])
|
||||
assert ids("?sichtbarkeit=privat") == [p["id"]]
|
||||
assert ids("?sichtbarkeit=team") == [t["id"]]
|
||||
assert ids("?typ=ssh") == [t["id"]]
|
||||
assert alice.get("/api/connections?sichtbarkeit=alle").status_code == 422
|
||||
|
||||
|
||||
def test_anzeigename_wird_nicht_als_html_interpretiert(alice):
|
||||
# Server speichert unverändert; das Frontend setzt Texte nur per textContent
|
||||
c = anlegen(alice, anzeigename="<script>alert(1)</script>")
|
||||
assert c["anzeigename"] == "<script>alert(1)</script>"
|
||||
Reference in new issue
Block a user