Sfoglia il codice sorgente

Anmeldung ohne LDAP im Debug-Modus

gc-server3 1 mese fa
parent
commit
e46d02a259

+ 2 - 0
.env.example

@@ -1,4 +1,6 @@
 ENVIRONMENT=production
+# Development only: ENVIRONMENT=development and DEBUG_AUTH=true enable username=password login.
+DEBUG_AUTH=false
 DATABASE_URL=mssql+pyodbc://server/database?driver=ODBC+Driver+18+for+SQL+Server&trusted_connection=yes&TrustServerCertificate=no
 
 AUTH_PROXY_HEADER=X-Remote-User

+ 25 - 0
README.md

@@ -85,3 +85,28 @@ Tests werden ohne zusätzliche Testabhängigkeiten ausgeführt:
 ```cmd
 .venv\Scripts\python.exe -m unittest discover -v
 ```
+
+## Debug-Anmeldung ohne LDAP
+
+Für Entwicklung und manuelle Tests diese Werte in `.env` setzen und die Anwendung neu starten:
+
+```dotenv
+ENVIRONMENT=development
+DEBUG_AUTH=true
+COOKIE_SECURE=false
+```
+
+Unter `/login` dieselbe Benutzerkennung in beide Felder eingeben, z. B.
+Benutzername `winter` und Passwort `winter`. Beide Eingaben müssen exakt übereinstimmen.
+Die Kennung wird anschließend wie beim AD-Login normalisiert. Eine gültige Zuordnung in
+`dbo.Benutzer_Rechte` zu einer aktiven Rolle in `dbo.Rollen` ist weiterhin erforderlich;
+mehrere Berechtigungszeilen werden wie bisher vereinigt. Ein LDAP-Server ist dafür nicht nötig,
+die konfigurierte SQL-Datenbank und die Authentifizierungsmigration hingegen schon.
+
+Im Debugmodus werden IIS-Identitätsheader ignoriert, damit verschiedene Benutzer über
+das Formular getestet werden können. JWT, CSRF, Logout und die Rechteprüfung pro Request
+bleiben aktiv; der Token enthält `auth_source=debug`. Benutzername wird als Anzeigename
+verwendet, E-Mail bleibt leer. Nach dem Deaktivieren von `DEBUG_AUTH` werden diese Tokens
+nicht mehr akzeptiert. Standardmäßig ist `DEBUG_AUTH=false`; außerhalb der Umgebungen
+`development`, `debug` und `test` verweigert die Anwendung den Start mit aktivem Debug-Login.
+`COOKIE_SECURE=false` ist nur für lokale HTTP-Tests gedacht; bei HTTPS auf `true` setzen.

+ 4 - 2
app/auth.py

@@ -90,8 +90,10 @@ class AuthenticationMiddleware(BaseHTTPMiddleware):
 
         proxy_user = request.headers.get(settings.AUTH_PROXY_HEADER)
         proxy_host = request.client.host if request.client else None
-        trusted_proxy_identity = proxy_user if settings.is_trusted_proxy(proxy_host) else None
-        if proxy_user and not trusted_proxy_identity:
+        trusted_proxy_identity = (
+            proxy_user if not settings.debug_auth_enabled and settings.is_trusted_proxy(proxy_host) else None
+        )
+        if proxy_user and not trusted_proxy_identity and not settings.debug_auth_enabled:
             logger.warning("Nicht vertrauenswürdiger Proxy-Identitätsheader von %s ignoriert", proxy_host)
 
         try:

+ 7 - 0
app/config.py

@@ -20,6 +20,7 @@ class Settings(BaseSettings):
     model_config = SettingsConfigDict(env_file=".env", extra="ignore", case_sensitive=False)
 
     ENVIRONMENT: str = "development"
+    DEBUG_AUTH: bool = False
     DATABASE_URL: str = "sqlite:///./dev.db"
 
     AUTH_PROXY_HEADER: str = "X-Remote-User"
@@ -48,6 +49,8 @@ class Settings(BaseSettings):
 
     @model_validator(mode="after")
     def validate_security_settings(self) -> "Settings":
+        if self.DEBUG_AUTH and self.ENVIRONMENT.lower() not in {"development", "debug", "test"}:
+            raise ValueError("DEBUG_AUTH is only allowed in development, debug or test")
         if self.ENVIRONMENT.lower() == "production":
             if len(self.JWT_SECRET.encode("utf-8")) < 32 or self.JWT_SECRET == DEVELOPMENT_JWT_SECRET:
                 raise ValueError("A unique JWT_SECRET with at least 32 bytes is required in production")
@@ -57,6 +60,10 @@ class Settings(BaseSettings):
             raise ValueError("JWT session lifetimes must be positive")
         return self
 
+    @property
+    def debug_auth_enabled(self) -> bool:
+        return self.DEBUG_AUTH and self.ENVIRONMENT.lower() in {"development", "debug", "test"}
+
     def is_trusted_proxy(self, host: str | None) -> bool:
         if not host:
             return False

+ 3 - 1
app/oauth_token.py

@@ -63,8 +63,10 @@ def decode_access_token(token: str) -> dict:
     required = {"sub", "name", "email", "role", "auth_source", "exp", "session_exp", "csrf"}
     if not required.issubset(payload):
         raise InvalidSessionToken("Session token is missing required claims")
-    if payload["auth_source"] not in {"iis", "ldap"}:
+    if payload["auth_source"] not in {"iis", "ldap", "debug"}:
         raise InvalidSessionToken("Unknown authentication source")
+    if payload["auth_source"] == "debug" and not settings.debug_auth_enabled:
+        raise InvalidSessionToken("Debug authentication is disabled")
     if int(payload["session_exp"]) <= int(utcnow().timestamp()):
         raise InvalidSessionToken("Absolute session lifetime exceeded")
     return payload

+ 12 - 20
app/permissions.py

@@ -25,20 +25,16 @@ class Principal:
     entitlements: tuple[Entitlement, ...]
 
 
-RIGHTS_SQL = text(
-    """
+RIGHTS_SQL = text("""
     SELECT BR.Hauptbetrieb_ID,
            BR.Standort_ID,
            BR.Abteilung,
-           BR.Rolle,
-           R.Prioritaet
+           BR.Rolle_Name,
+           BR.Rolle_Prio
     FROM dbo.Benutzer_Rechte AS BR
-    INNER JOIN dbo.Rollen AS R ON R.Rolle = BR.Rolle AND R.Aktiv = 1
-    WHERE LOWER(LTRIM(RTRIM(BR.Benutzer_ID))) = :username
-      AND NULLIF(LTRIM(RTRIM(BR.Benutzer_ID)), '') IS NOT NULL
-    ORDER BY R.Prioritaet DESC, BR.Rolle ASC
-    """
-)
+    WHERE BR.Benutzer_ID = :username
+    ORDER BY BR.Rolle_Prio DESC, BR.Rolle_Name ASC
+    """)
 
 
 def load_entitlements(db: Session, username: str) -> tuple[Entitlement, ...]:
@@ -48,8 +44,8 @@ def load_entitlements(db: Session, username: str) -> tuple[Entitlement, ...]:
             hauptbetrieb_id=str(row["Hauptbetrieb_ID"]),
             standort_id=str(row["Standort_ID"]),
             abteilung=row["Abteilung"],
-            role=row["Rolle"],
-            priority=int(row["Prioritaet"]),
+            role=row["Rolle_Name"],
+            priority=int(row["Rolle_Prio"]),
         )
         for row in rows
     )
@@ -61,8 +57,7 @@ def highest_role(entitlements: tuple[Entitlement, ...]) -> str:
     return sorted(entitlements, key=lambda item: (-item.priority, item.role))[0].role
 
 
-FORDERUNG_ACCESS_SQL = text(
-    """
+FORDERUNG_ACCESS_SQL = text("""
     SELECT TOP 1 1
     FROM dbo.Forderungen_Kopf AS F
     WHERE F.Client_DB = :client_db
@@ -70,15 +65,12 @@ FORDERUNG_ACCESS_SQL = text(
       AND EXISTS (
           SELECT 1
           FROM dbo.Benutzer_Rechte AS BR
-          INNER JOIN dbo.Rollen AS R ON R.Rolle = BR.Rolle AND R.Aktiv = 1
-          WHERE LOWER(LTRIM(RTRIM(BR.Benutzer_ID))) = :auth_username
-            AND NULLIF(LTRIM(RTRIM(BR.Benutzer_ID)), '') IS NOT NULL
+          WHERE BR.Benutzer_ID = :auth_username
             AND BR.Hauptbetrieb_ID = F.Hauptbetrieb_ID
             AND BR.Standort_ID = F.Standort_ID
-            AND (BR.Abteilung IS NULL OR BR.Abteilung = F.Abteilung)
+            AND BR.Abteilung = F.Abteilung
       )
-    """
-)
+    """)
 
 
 def ensure_forderung_access(db: Session, principal: Principal, client_db: str, beleg_nr: str) -> None:

+ 14 - 3
app/routes.py

@@ -26,7 +26,7 @@ from .config import settings
 from .db import get_session
 from .docuware_search import get_invoice_pdf_by_document_no
 from .jinja_templates import templates
-from .ldap import DirectoryUnavailable, ldap_authenticate
+from .ldap import DirectoryUnavailable, DirectoryUser, ldap_authenticate, normalize_username
 from .oauth_token import create_access_token
 from .permissions import (
     current_principal,
@@ -86,7 +86,18 @@ def login_post(
         raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Ungültiger CSRF-Token")
 
     try:
-        user = ldap_authenticate(username, password)
+        if settings.debug_auth_enabled:
+            user = None
+            if username and secrets.compare_digest(username.encode("utf-8"), password.encode("utf-8")):
+                normalized = normalize_username(username)
+                user = DirectoryUser(
+                    username=normalized,
+                    distinguished_name="",
+                    name=normalized,
+                    email="",
+                )
+        else:
+            user = ldap_authenticate(username, password)
     except DirectoryUnavailable:
         logger.exception("LDAP-Anmeldedienst nicht verfügbar")
         return templates.TemplateResponse(
@@ -123,7 +134,7 @@ def login_post(
         name=user.name,
         email=user.email,
         role=role,
-        auth_source="ldap",
+        auth_source="debug" if settings.debug_auth_enabled else "ldap",
     )
     response = RedirectResponse(url=safe_next_url(next), status_code=303)
     set_session_cookie(response, token)

+ 2 - 4
templates/forderungen/liste/queries/forderungen_liste.sql

@@ -62,12 +62,10 @@ FROM [dbo].[Forderungen_Kopf] [F]
 WHERE EXISTS (
     SELECT 1
     FROM [dbo].[Benutzer_Rechte] AS [BR]
-    INNER JOIN [dbo].[Rollen] AS [R] ON [R].[Rolle] = [BR].[Rolle] AND [R].[Aktiv] = 1
-    WHERE LOWER(LTRIM(RTRIM([BR].[Benutzer_ID]))) = :auth_username
-      AND NULLIF(LTRIM(RTRIM([BR].[Benutzer_ID])), '') IS NOT NULL
+    WHERE [BR].[Benutzer_ID] = :auth_username
       AND [F].[Hauptbetrieb_ID] = [BR].[Hauptbetrieb_ID]
       AND [F].[Standort_ID] = [BR].[Standort_ID]
-      AND ([BR].[Abteilung] IS NULL OR [F].[Abteilung] = [BR].[Abteilung])
+      AND [F].[Abteilung] = [BR].[Abteilung]
 )
 AND 1 = 1
 ORDER BY F.[Wiedervorlage] ASC, F.[Beleg_Tage_offen] DESC

+ 97 - 0
tests/test_debug_auth.py

@@ -0,0 +1,97 @@
+import unittest
+from unittest.mock import patch
+
+from fastapi.testclient import TestClient
+
+from app.config import Settings, settings
+from app.main import app
+from app.oauth_token import InvalidSessionToken, create_access_token, decode_access_token
+from app.permissions import Entitlement
+
+
+class DebugLoginTests(unittest.TestCase):
+    def setUp(self):
+        self.config = patch.multiple(settings, ENVIRONMENT="development", DEBUG_AUTH=True, COOKIE_SECURE=False)
+        self.config.start()
+        self.addCleanup(self.config.stop)
+        self.ldap = patch("app.routes.ldap_authenticate")
+        self.ldap_mock = self.ldap.start()
+        self.addCleanup(self.ldap.stop)
+        self.client = TestClient(app, base_url="http://testserver")
+        self.addCleanup(self.client.close)
+        self.entitlements = (
+            Entitlement("1", "10", None, "Buchhaltung", 400),
+            Entitlement("1", "20", "Service", "Mitarbeiter", 100),
+        )
+
+    def login(self, username="winter", password="winter", csrf=True):
+        self.client.get("/login")
+        return self.client.post(
+            "/login",
+            data={
+                "username": username,
+                "password": password,
+                "_csrf": self.client.cookies[settings.LOGIN_CSRF_COOKIE_NAME] if csrf else "incorrect",
+            },
+            follow_redirects=False,
+        )
+
+    @patch("app.routes.load_entitlements")
+    @patch("app.auth.load_entitlements")
+    def test_existing_user_gets_jwt_and_can_access_protected_page(self, request_rights, login_rights):
+        login_rights.return_value = request_rights.return_value = self.entitlements
+        response = self.login("Winter", "Winter")
+        self.assertEqual(response.status_code, 303)
+        payload = decode_access_token(response.cookies[settings.SESSION_COOKIE_NAME])
+        self.assertEqual(payload["sub"], "winter")
+        self.assertEqual(payload["role"], "Buchhaltung")
+        self.assertEqual(payload["auth_source"], "debug")
+        login_rights.assert_called_once()
+        self.assertEqual(login_rights.call_args.args[1], "winter")
+        self.assertEqual(self.client.get("/select").status_code, 200)
+        request_rights.assert_called_once()
+        self.ldap_mock.assert_not_called()
+
+    @patch("app.routes.load_entitlements")
+    def test_different_password_is_rejected_without_ldap_or_rights_lookup(self, login_rights):
+        response = self.login("winter", "Winter")
+        self.assertEqual(response.status_code, 401)
+        self.assertNotIn(settings.SESSION_COOKIE_NAME, response.cookies)
+        login_rights.assert_not_called()
+        self.ldap_mock.assert_not_called()
+
+    @patch("app.routes.load_entitlements", return_value=())
+    def test_user_without_rights_is_rejected(self, login_rights):
+        response = self.login("unknown", "unknown")
+        self.assertEqual(response.status_code, 403)
+        self.assertNotIn(settings.SESSION_COOKIE_NAME, response.cookies)
+        self.ldap_mock.assert_not_called()
+
+    def test_csrf_remains_required(self):
+        self.assertEqual(self.login(csrf=False).status_code, 403)
+
+    @patch("app.auth.lookup_directory_user")
+    def test_proxy_header_does_not_bypass_debug_form(self, lookup):
+        with patch.object(settings, "TRUSTED_PROXY_IPS", ["testclient"]):
+            response = self.client.get("/login", headers={"X-Remote-User": r"DOMAIN\winter"})
+        self.assertEqual(response.status_code, 200)
+        lookup.assert_not_called()
+
+    def test_debug_token_is_rejected_after_disabling_debug_mode(self):
+        token = create_access_token(
+            username="winter", name="winter", email="", role="Mitarbeiter", auth_source="debug"
+        )
+        with patch.object(settings, "DEBUG_AUTH", False):
+            with self.assertRaises(InvalidSessionToken):
+                decode_access_token(token)
+
+    def test_production_configuration_rejects_debug_auth(self):
+        with self.assertRaises(ValueError):
+            Settings(_env_file=None, ENVIRONMENT="production", DEBUG_AUTH=True)
+
+    def test_debug_auth_is_disabled_by_default(self):
+        self.assertFalse(Settings(_env_file=None, DEBUG_AUTH=False).debug_auth_enabled)
+
+
+if __name__ == "__main__":
+    unittest.main()