Просмотр исходного кода

feat: implement encryption for bind_password in LDAP config and update HTML template for secure input

Manuel 7 месяцев назад
Родитель
Сommit
2c7b5e1084
2 измененных файлов с 58 добавлено и 11 удалено
  1. 45 3
      services/ldap/ldap_config_service.py
  2. 13 8
      templates/admin/ldap_config.html

+ 45 - 3
services/ldap/ldap_config_service.py

@@ -6,8 +6,12 @@ table (single-row pattern, same as backup_config).
 
 from __future__ import annotations
 
+import base64
+import hashlib
+import os
 from datetime import datetime
 
+from cryptography.fernet import Fernet, InvalidToken
 from loguru import logger
 
 from database.database import get_session
@@ -26,6 +30,29 @@ def _default_config() -> dict:
     }
 
 
+def _get_fernet(raw_key: str | None) -> Fernet:
+    if not raw_key:
+        raise RuntimeError("No encryption key available")
+    key_bytes = raw_key.encode() if isinstance(raw_key, str) else raw_key
+    if len(key_bytes) != 44:
+        key_bytes = base64.urlsafe_b64encode(hashlib.sha256(key_bytes).digest())
+    return Fernet(key_bytes)
+
+
+def _generate_encryption_key() -> str:
+    return base64.urlsafe_b64encode(os.urandom(32)).decode()
+
+
+def _encrypt_password(password: str, encryption_key: str) -> str:
+    cipher = _get_fernet(encryption_key)
+    return cipher.encrypt(password.encode()).decode()
+
+
+def _decrypt_password(encrypted: str, encryption_key: str) -> str:
+    cipher = _get_fernet(encryption_key)
+    return cipher.decrypt(encrypted.encode()).decode()
+
+
 def load_config() -> dict:
     """Return LDAP config from the DB. Returns defaults if no row exists."""
     session = get_session()
@@ -38,13 +65,23 @@ def load_config() -> dict:
             )
             return cfg
 
+        bind_password = row.bind_password or ""
+        if bind_password and row.encryption_key:
+            try:
+                bind_password = _decrypt_password(bind_password, row.encryption_key)
+            except InvalidToken:
+                print("[LDAP DEBUG] load_config: stored bind_password could not be decrypted with row encryption key, hiding password")
+                bind_password = ""
+        elif bind_password and not row.encryption_key:
+            print("[LDAP DEBUG] load_config: bind_password present without encryption key, keeping raw value")
+
         cfg = {
             "host": row.host or "",
             "port": row.port or 389,
             "use_ssl": bool(row.use_ssl),
             "auth_type": row.auth_type or "SIMPLE",
             "bind_dn": row.bind_dn or "",
-            "bind_password": row.bind_password or "",
+            "bind_password": bind_password,
             "base_dn": row.base_dn or "",
         }
         print(f"[LDAP DEBUG] load_config: loaded row id={row.id} config={cfg}")
@@ -75,10 +112,15 @@ def save_config(cfg: dict) -> None:
         row.base_dn = cfg.get("base_dn", "")
         row.updated_at = datetime.now()
 
-        # Only overwrite the password if a non-empty value is supplied
         new_password = cfg.get("bind_password", "")
         if new_password:
-            row.bind_password = new_password
+            if not row.encryption_key:
+                row.encryption_key = _generate_encryption_key()
+            try:
+                row.bind_password = _encrypt_password(new_password, row.encryption_key)
+            except Exception as exc:
+                print(f"[LDAP DEBUG] save_config: encryption failed -> {exc}")
+                row.bind_password = new_password
 
         session.commit()
         print(

+ 13 - 8
templates/admin/ldap_config.html

@@ -97,7 +97,7 @@
 
             <div>
                 <label class="block text-xs font-medium text-gray-600 mb-1">Contraseña Bind</label>
-                <input x-model="cfg.bind_password" type="password" placeholder="••••••••"
+                <input x-model="cfg.bind_password" type="password" autocomplete="current-password" placeholder="••••••••"
                     class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
             </div>
 
@@ -282,18 +282,23 @@
     </div>
 </div>
 
+<script type="application/json" id="ldap-config-data">
+{{ cfg | tojson | safe }}
+</script>
+
 <script>
 function ldapApp() {
+    const initialCfg = JSON.parse(document.getElementById('ldap-config-data').textContent || '{}');
     return {
         // Config form
         cfg: {
-            host:          "{{ cfg.host }}",
-            port:          {{ cfg.port }},
-            use_ssl:       {{ 'true' if cfg.use_ssl else 'false' }},
-            auth_type:     "{{ cfg.auth_type }}",
-            bind_dn:       "{{ cfg.bind_dn }}",
-            bind_password: "",
-            base_dn:       "{{ cfg.base_dn }}",
+            host:          initialCfg.host || "",
+            port:          initialCfg.port || 389,
+            use_ssl:       initialCfg.use_ssl || false,
+            auth_type:     initialCfg.auth_type || "SIMPLE",
+            bind_dn:       initialCfg.bind_dn || "",
+            bind_password: initialCfg.bind_password || "",
+            base_dn:       initialCfg.base_dn || "",
         },
         savingCfg:    false,
         testingConn:  false,