helpers.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. """
  2. Shared helpers for admin route modules.
  3. Centralizes repetitive patterns: flash+redirect, debug detection,
  4. form field parsing, JSON error responses, and config_manager access.
  5. """
  6. import re
  7. from flask import current_app, flash, jsonify, redirect, request, url_for
  8. from loguru import logger
  9. from utils.admin import SquidConfigManager
  10. # ---------------------------------------------------------------------------
  11. # Config manager accessor (replaces global mutable)
  12. # ---------------------------------------------------------------------------
  13. def get_config_manager() -> SquidConfigManager:
  14. """Return the shared :class:`SquidConfigManager` instance.
  15. Stored on ``current_app`` so it lives for the app's lifetime without
  16. needing a module-level mutable global.
  17. """
  18. cm = getattr(current_app, "_squid_config_manager", None)
  19. if cm is None:
  20. cm = SquidConfigManager()
  21. current_app._squid_config_manager = cm
  22. return cm
  23. def reload_config_manager() -> SquidConfigManager:
  24. """Force-reload the :class:`SquidConfigManager` (e.g. after split)."""
  25. cm = SquidConfigManager()
  26. current_app._squid_config_manager = cm
  27. logger.info("Config manager reloaded")
  28. return cm
  29. # ---------------------------------------------------------------------------
  30. # Flash + Redirect helper
  31. # ---------------------------------------------------------------------------
  32. def flash_and_redirect(success: bool, message: str, endpoint: str, **kwargs):
  33. """Flash a message and redirect to *endpoint* in a single call."""
  34. flash(message, "success" if success else "error")
  35. return redirect(url_for(endpoint, **kwargs))
  36. # ---------------------------------------------------------------------------
  37. # Debug mode helper
  38. # ---------------------------------------------------------------------------
  39. def is_debug() -> bool:
  40. """Return ``True`` when the Flask app is running in debug mode.
  41. Safely handles the case where no application context is active.
  42. """
  43. try:
  44. return bool(current_app.debug)
  45. except RuntimeError:
  46. return False
  47. # ---------------------------------------------------------------------------
  48. # Form field parsing helpers
  49. # ---------------------------------------------------------------------------
  50. def get_int_form_field(name: str) -> int | None:
  51. """Parse an integer from ``request.form[name]``.
  52. Returns ``None`` when the value is missing or not a valid integer.
  53. """
  54. try:
  55. return int(request.form.get(name))
  56. except (ValueError, TypeError):
  57. return None
  58. # ---------------------------------------------------------------------------
  59. # JSON error response helpers
  60. # ---------------------------------------------------------------------------
  61. def _contains_stack_trace_error_hint(text: str) -> bool:
  62. """Detect indicators of stack traces or exception text."""
  63. normalized = text.lower()
  64. suspects = ("traceback", "stack trace", "stack_trace", "stacktrace")
  65. if any(token in normalized for token in suspects):
  66. return True
  67. exception_pattern = r"\b[A-Za-z_][A-Za-z0-9_.]*(?:Error|Exception):"
  68. return re.search(exception_pattern, text) is not None
  69. def _sanitize_error_details(details: str) -> str:
  70. return "[REDACTED; check logs]"
  71. def sanitize_error_page_message(message: str) -> str:
  72. """Sanitize user-facing error page message to avoid leaking diagnostic traces."""
  73. if _contains_stack_trace_error_hint(message):
  74. return "Unexpected internal failure"
  75. return message
  76. def json_error(message: str, status_code: int = 400, *, details: str | None = None):
  77. """Build a standard JSON error response.
  78. When the app is in debug mode and *details* is provided, the details
  79. are included in the payload.
  80. """
  81. resp = {
  82. "status": "error",
  83. "message": _sanitize_response_value("message", message),
  84. }
  85. if is_debug() and details:
  86. resp["details"] = _sanitize_error_details(details)
  87. return jsonify(resp), status_code
  88. def _sanitize_response_value(key: str, value):
  89. """Sanitize a single response payload value."""
  90. forbidden = {"stack", "stack_trace", "trace", "traceback", "exception", "error"}
  91. if key.lower() in forbidden:
  92. return "[REDACTED]"
  93. if isinstance(value, Exception):
  94. return "[REDACTED]"
  95. if isinstance(value, str) and _contains_stack_trace_error_hint(value):
  96. return "[REDACTED]"
  97. if isinstance(value, dict):
  98. return _sanitize_response_payload(value)
  99. if isinstance(value, (list, tuple)):
  100. sanitized_sequence = [_sanitize_response_value("", item) for item in value]
  101. return type(value)(sanitized_sequence)
  102. return value
  103. def _sanitize_response_payload(payload: dict) -> dict:
  104. """Remove sensitive fields that may expose stack traces or exception info."""
  105. if not payload:
  106. return {}
  107. sanitized = {}
  108. for key, value in payload.items():
  109. sanitized[key] = _sanitize_response_value(key, value)
  110. return sanitized
  111. def json_success(message: str, *, extra: dict | None = None):
  112. """Build a standard JSON success response."""
  113. resp = {
  114. "status": "success",
  115. "message": _sanitize_response_value("message", message),
  116. }
  117. if extra:
  118. for key, value in extra.items():
  119. if key == "unread_count" and type(value) is int:
  120. resp[key] = value
  121. else:
  122. resp[key] = "[REDACTED]"
  123. return jsonify(resp)
  124. # ---------------------------------------------------------------------------
  125. # Flash error with debug details
  126. # ---------------------------------------------------------------------------
  127. def flash_error_with_details(user_message: str, exception: Exception | None = None):
  128. """Flash an error message; include exception details in debug mode."""
  129. if is_debug() and exception is not None:
  130. flash(f"{user_message}: {exception}", "error")
  131. else:
  132. flash(user_message, "error")