Explorar el Código

Merge pull request #97 from kaelthasmanu/some_minor_fix's

Some minor fix's
Manuel Gorrin hace 4 meses
padre
commit
3aa9c019fe

+ 2 - 3
routes/admin/blacklist.py

@@ -248,7 +248,7 @@ def register_routes(bp):
             session.rollback()
             logger.exception("Error eliminando usuario bloqueado")
             if data:
-                return json_error(_("Error al eliminar usuario bloqueado"), 500, str(e))
+                return json_error(_("Error al eliminar usuario bloqueado"), 500)
             flash_error_with_details(_("Error al eliminar usuario bloqueado"), e)
         finally:
             session.close()
@@ -280,10 +280,9 @@ def register_routes(bp):
             if ok:
                 return json_success(msg)
             return json_error(msg)
-        except Exception as e:
+        except Exception:
             logger.exception("Error en toggle de blocklist")
             return json_error(
                 "Error interno al cambiar estado de blocklist",
                 500,
-                details=str(e),
             )

+ 1 - 4
routes/admin/helpers.py

@@ -92,10 +92,7 @@ def _contains_stack_trace_error_hint(text: str) -> bool:
 
 
 def _sanitize_error_details(details: str) -> str:
-    """Sanitize textual error details by redacting stack trace / exception artifacts."""
-    if _contains_stack_trace_error_hint(details):
-        return "[REDACTED; check logs]"
-    return details
+    return "[REDACTED; check logs]"
 
 
 def sanitize_error_page_message(message: str) -> str:

+ 5 - 7
routes/admin/squid_config.py

@@ -114,14 +114,13 @@ def register_routes(bp):
 
         try:
             save_squid_env_vars_to_db(squid_env_vars)
-        except Exception as e:
+        except Exception:
             logger.exception("Error saving Squid env vars to DB")
             flash(
                 _(
-                    "Las variables de Squid se guardaron en .env, pero no se pudieron guardar en la base de datos: %(error)s"
-                )
-                % {"error": str(e)},
-                "error",
+                    "Las variables de Squid se guardaron en .env, pero no se pudieron guardar en la base de datos."
+                ),
+                "warning",
             )
             return redirect(url_for("admin.view_config"))
 
@@ -180,12 +179,11 @@ def register_routes(bp):
         except RuntimeError as e:
             logger.error(f"Error de validación: {e}")
             return json_error("Error de validación de la configuración", 400)
-        except Exception as e:
+        except Exception:
             logger.exception("Error al dividir el archivo de configuración")
             return json_error(
                 "Error interno al dividir la configuración",
                 500,
-                details=str(e),
             )
 
     @bp.route("/api/get-split-files", methods=["GET"])

+ 2 - 2
routes/admin/system_api.py

@@ -92,6 +92,6 @@ def register_routes(bp):
             resp, code = service_delete_table_data(table_name)
             return jsonify(resp), code
 
-        except Exception as e:
+        except Exception:
             logger.exception("Error deleting data from table")
-            return json_error("Error interno del servidor", 500, details=str(e))
+            return json_error("Error interno del servidor", 500)

+ 22 - 48
routes/admin_routes.py

@@ -617,26 +617,24 @@ def delete_user(user_id):
 @admin_bp.route("/api/restart-squid", methods=["POST"])
 @api_auth_required
 def restart_squid():
-    success, message, details = service_restart_squid()
+    success, message, _details = service_restart_squid()
     if success:
         return json_success(message)
     return json_error(
         message or "Could not restart squid",
         500,
-        details=str(details) if details else None,
     )
 
 
 @admin_bp.route("/api/reload-squid", methods=["POST"])
 @api_auth_required
 def reload_squid():
-    success, message, details = service_reload_squid()
+    success, message, _details = service_reload_squid()
     if success:
         return json_success(message)
     return json_error(
         message or "Could not reload squid",
         500,
-        details=str(details) if details else None,
     )
 
 
@@ -687,17 +685,11 @@ def delete_table_data():
         resp, code = service_delete_table_data(table_name)
         return jsonify(resp), code
 
-    except Exception as e:
+    except Exception:
         logger.exception("Error deleting data from table")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-
-        resp = {"status": "error", "message": _("Error interno del servidor")}
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+        return jsonify(
+            {"status": "error", "message": _("Error interno del servidor")}
+        ), 500
 
 
 @admin_bp.route("/config/split")
@@ -714,16 +706,9 @@ def split_config_view():
             output_exists=data["output_exists"],
             files_count=data["files_count"],
         )
-    except Exception as e:
+    except Exception:
         logger.exception("Error al cargar la vista de división de configuración")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-        if show_details:
-            flash(_("Error al cargar la vista: %(error)s") % {"error": str(e)}, "error")
-        else:
-            flash(_("Error al cargar la vista"), "error")
+        flash(_("Error al cargar la vista"), "error")
         return redirect(url_for("admin.admin_dashboard"))
 
 
@@ -776,20 +761,14 @@ def split_config():
             }
         ), 400
 
-    except Exception as e:
+    except Exception:
         logger.exception("Error al dividir el archivo de configuración")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-
-        resp = {
-            "status": "error",
-            "message": _("Error interno al dividir la configuración"),
-        }
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+        return jsonify(
+            {
+                "status": "error",
+                "message": _("Error interno al dividir la configuración"),
+            }
+        ), 500
 
 
 @admin_bp.route("/api/get-split-files", methods=["GET"])
@@ -1255,16 +1234,11 @@ def blocklist_toggle():
         if ok:
             return jsonify({"status": "success", "message": msg})
         return jsonify({"status": "error", "message": msg}), 400
-    except Exception as e:
+    except Exception:
         logger.exception("Error en toggle de blocklist")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-        resp = {
-            "status": "error",
-            "message": _("Error interno al cambiar estado de blocklist"),
-        }
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+        return jsonify(
+            {
+                "status": "error",
+                "message": _("Error interno al cambiar estado de blocklist"),
+            }
+        ), 500

+ 11 - 28
routes/api_routes.py

@@ -1,4 +1,4 @@
-from flask import Blueprint, current_app, jsonify, request
+from flask import Blueprint, jsonify, request
 from flask_babel import gettext as _
 from loguru import logger
 from werkzeug.exceptions import BadRequest
@@ -76,17 +76,9 @@ def api_get_all_users():
     try:
         users = get_all_usernames(db)
         return jsonify(users)
-    except Exception as e:
+    except Exception:
         logger.exception("Error retrieving all users")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-
-        resp = {"error": _("Internal server error")}
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+        return jsonify({"error": _("Internal server error")}), 500
     finally:
         db.close()
 
@@ -143,16 +135,9 @@ def api_mark_notifications_read():
         return jsonify(
             {"success": True, "unread_count": get_all_notifications()["unread_count"]}
         )
-    except Exception as e:
+    except Exception:
         logger.exception("Error marking notifications as read")
-        try:
-            show_details = bool(current_app.debug)
-        except RuntimeError:
-            show_details = False
-        resp = {"success": False, "error": _("Internal server error")}
-        if show_details:
-            resp["details"] = str(e)
-        return jsonify(resp), 500
+        return jsonify({"success": False, "error": _("Internal server error")}), 500
 
 
 @api_bp.route("/notifications/<int:notification_id>", methods=["DELETE"])
@@ -163,9 +148,9 @@ def api_delete_notification(notification_id):
             "Notification deleted",
             extra={"unread_count": get_all_notifications()["unread_count"]},
         )
-    except Exception as e:
+    except Exception:
         logger.exception("Error deleting notification")
-        return json_error("Internal server error", 500, details=str(e))
+        return json_error("Internal server error", 500)
 
 
 @api_bp.route("/notifications/delete-all", methods=["DELETE"])
@@ -173,34 +158,32 @@ def api_delete_all_notifications():
     try:
         delete_all_notifications()
         return json_success("All notifications deleted", extra={"unread_count": 0})
-    except Exception as e:
+    except Exception:
         logger.exception("Error deleting all notifications")
-        return json_error("Internal server error", 500, details=str(e))
+        return json_error("Internal server error", 500)
 
 
 @api_bp.route("/restart-squid", methods=["POST"])
 @api_admin_required
 def api_restart_squid():
-    success, message, details = restart_squid()
+    success, message, _details = restart_squid()
     if success:
         return json_success(message)
     return json_error(
         message or "Could not restart squid",
         500,
-        details=str(details) if details else None,
     )
 
 
 @api_bp.route("/reload-squid", methods=["POST"])
 @api_admin_required
 def api_reload_squid():
-    success, message, details = reload_squid()
+    success, message, _details = reload_squid()
     if success:
         return json_success(message)
     return json_error(
         message or "Could not reload squid",
         500,
-        details=str(details) if details else None,
     )
 
 

+ 2 - 2
services/analytics/auditoria_service.py

@@ -1162,8 +1162,8 @@ def run_audit_operation(db, audit_type, data):
         if isinstance(result, dict) and result.get("error"):
             return result
         return result
-    except ValueError as e:
-        return {"error": str(e)}
+    except ValueError:
+        return {"error": _("Valor inválido")}
     except Exception:
         import traceback
 

+ 21 - 13
services/database/backup_service.py

@@ -161,13 +161,12 @@ def _get_safe_backup_path(backup_dir: Path, filename: str) -> Path | None:
     if normalized is None:
         return None
 
-    target = (backup_dir / normalized).resolve()
-    try:
-        target.relative_to(backup_dir.resolve())
-    except ValueError:
+    safe_root = os.path.realpath(backup_dir)
+    fullpath = os.path.realpath(os.path.join(backup_dir, str(normalized)))
+    if not fullpath.startswith(safe_root + os.sep) and fullpath != safe_root:
         return None
 
-    return target
+    return Path(fullpath)
 
 
 def _human_size(size_bytes: int) -> str:
@@ -413,8 +412,11 @@ def run_backup(is_auto: bool = False) -> dict:
     frequency = cfg.get("frequency", "daily_weekly")
     try:
         bdir = _backup_dir(cfg)
-    except OSError as e:
-        return {"status": "error", "message": str(e)}
+    except OSError:
+        return {
+            "status": "error",
+            "message": _("Error al acceder al directorio de salvas"),
+        }
     tag = "auto" if is_auto else "manual"
 
     if is_auto:
@@ -436,11 +438,14 @@ def run_backup(is_auto: bool = False) -> dict:
             dest = _postgresql_backup(bdir, tag)
         else:
             return {"status": "error", "message": f"Motor de BD desconocido: {db_type}"}
-    except NotImplementedError as e:
-        return {"status": "error", "message": str(e)}
-    except Exception as e:
+    except NotImplementedError:
+        return {
+            "status": "error",
+            "message": _("Funcionalidad de salva no implementada"),
+        }
+    except Exception:
         logger.exception("Backup failed")
-        return {"status": "error", "message": f"Error al crear salva: {e}"}
+        return {"status": "error", "message": _("Error al crear la salva")}
 
     _enforce_retention(bdir)
 
@@ -456,8 +461,11 @@ def delete_backup(filename: str) -> dict:
     cfg = load_config()
     try:
         bdir = _backup_dir(cfg)
-    except OSError as e:
-        return {"status": "error", "message": str(e)}
+    except OSError:
+        return {
+            "status": "error",
+            "message": _("Error al acceder al directorio de salvas"),
+        }
 
     target = _get_safe_backup_path(bdir, filename)
     if target is None:

+ 4 - 2
services/database/db_info_service.py

@@ -87,9 +87,11 @@ def get_db_health():
                     corruption_detail = (
                         qc_rows[0][0] if qc_rows else "Sin respuesta del PRAGMA"
                     )
-            except Exception as qc_err:
+            except Exception:
                 corruption = True
-                corruption_detail = str(qc_err)
+                corruption_detail = _(
+                    "No se pudo completar la verificación de integridad"
+                )
 
             health["extra"] = {
                 "page_size": page_size,

+ 33 - 10
services/ldap/ldap_service.py

@@ -55,12 +55,15 @@ def test_connection(cfg: dict) -> dict:
             "status": "success",
             "message": _("Conexión exitosa al servidor LDAP/AD."),
         }
-    except core.exceptions.LDAPBindError as exc:
-        logger.warning(f"LDAP bind falló: {exc}")
-        return {"status": "error", "message": f"Error de autenticación: {exc}"}
-    except Exception as exc:
-        logger.error(f"Error de conexión LDAP: {exc}")
-        return {"status": "error", "message": str(exc)}
+    except core.exceptions.LDAPBindError:
+        logger.exception("LDAP bind falló")
+        return {"status": "error", "message": _("Error de autenticación LDAP")}
+    except Exception:
+        logger.exception("Error de conexión LDAP")
+        return {
+            "status": "error",
+            "message": _("Error al conectar con el servidor LDAP"),
+        }
 
 
 def _paged_count(cfg: dict, object_class: str) -> int:
@@ -91,7 +94,12 @@ def get_stats(cfg: dict) -> dict:
         return {"status": "success", "users": user_count, "groups": group_count}
     except Exception as exc:
         logger.error(f"Error al obtener estadísticas LDAP: {exc}")
-        return {"status": "error", "message": str(exc), "users": 0, "groups": 0}
+        return {
+            "status": "error",
+            "message": _("Error al obtener estadísticas LDAP"),
+            "users": 0,
+            "groups": 0,
+        }
 
 
 def _escape_ldap_filter_value(value: str) -> str:
@@ -139,7 +147,12 @@ def search_users(cfg: dict, query: str, limit: int = 50) -> dict:
         return {"status": "success", "results": users, "total": len(users)}
     except Exception as exc:
         logger.error(f"Error al buscar usuarios LDAP: {exc}")
-        return {"status": "error", "message": str(exc), "results": [], "total": 0}
+        return {
+            "status": "error",
+            "message": _("Error al buscar usuarios LDAP"),
+            "results": [],
+            "total": 0,
+        }
 
 
 def search_groups(cfg: dict, query: str, limit: int = 50) -> dict:
@@ -176,7 +189,12 @@ def search_groups(cfg: dict, query: str, limit: int = 50) -> dict:
         return {"status": "success", "results": groups, "total": len(groups)}
     except Exception as exc:
         logger.error(f"Error al buscar grupos LDAP: {exc}")
-        return {"status": "error", "message": str(exc), "results": [], "total": 0}
+        return {
+            "status": "error",
+            "message": _("Error al buscar grupos LDAP"),
+            "results": [],
+            "total": 0,
+        }
 
 
 def get_user_groups(cfg: dict, username: str) -> dict:
@@ -221,7 +239,12 @@ def get_user_groups(cfg: dict, username: str) -> dict:
         }
     except Exception as exc:
         logger.error(f"Error al obtener grupos del usuario LDAP: {exc}")
-        return {"status": "error", "message": str(exc), "groups": [], "user": None}
+        return {
+            "status": "error",
+            "message": _("Error al obtener grupos del usuario"),
+            "groups": [],
+            "user": None,
+        }
 
 
 # ---------------------------------------------------------------------------

+ 2 - 2
services/notifications/telegram_service.py

@@ -431,9 +431,9 @@ class TelegramService:
                 status["connected"] = True
                 status["user_id"] = me.id
                 status["username"] = getattr(me, "username", None)
-        except Exception as exc:
+        except Exception:
             logger.exception("Health check failed")
-            status["error"] = str(exc) or "Health check failed"
+            status["error"] = "Health check failed"
 
         return status