Przeglądaj źródła

feat: add error sanitization helper and corresponding tests

Manuel 8 miesięcy temu
rodzic
commit
9f4ae1d71e
2 zmienionych plików z 42 dodań i 5 usunięć
  1. 10 5
      routes/admin/helpers.py
  2. 32 0
      tests/test_admin_helpers.py

+ 10 - 5
routes/admin/helpers.py

@@ -84,6 +84,15 @@ def get_int_form_field(name: str) -> int | None:
 # ---------------------------------------------------------------------------
 
 
+def _sanitize_error_details(details: str) -> str:
+    """Sanitize textual error details by redacting stack trace / exception artifacts."""
+    normalized = details.lower()
+    suspects = ("traceback", "exception", "stack", "stacktrace", "error")
+    if any(token in normalized for token in suspects):
+        return "[REDACTED; check logs]"
+    return details
+
+
 def json_error(message: str, status_code: int = 400, *, details: str | None = None):
     """Build a standard JSON error response.
 
@@ -92,11 +101,7 @@ def json_error(message: str, status_code: int = 400, *, details: str | None = No
     """
     resp = {"status": "error", "message": message}
     if is_debug() and details:
-        # Avoid leaking raw stack traces in debug output too.
-        if "Traceback" in details or "Exception" in details:
-            resp["details"] = "[REDACTED; check logs]"
-        else:
-            resp["details"] = details
+        resp["details"] = _sanitize_error_details(details)
     return jsonify(resp), status_code
 
 

+ 32 - 0
tests/test_admin_helpers.py

@@ -0,0 +1,32 @@
+from unittest.mock import patch
+
+from routes.admin.helpers import _sanitize_error_details, _sanitize_response_payload, json_error
+
+
+def test_sanitize_response_payload_strips_sensitive_keys():
+    payload = {
+        "stack": "some stack text",
+        "stack_trace": "frag",
+        "normal": "ok",
+    }
+
+    sanitized = _sanitize_response_payload(payload)
+
+    assert sanitized["stack"] == "[REDACTED]"
+    assert sanitized["stack_trace"] == "[REDACTED]"
+    assert sanitized["normal"] == "ok"
+
+
+def test_sanitize_error_details_redacts_traceback_line():
+    details = "Traceback (most recent call last): ..."
+    assert _sanitize_error_details(details) == "[REDACTED; check logs]"
+
+
+def test_json_error_debug_redacts_exception_details(flask_app):
+    with flask_app.test_request_context():
+        with patch("routes.admin.helpers.is_debug", return_value=True):
+            resp, code = json_error("fail", status_code=500, details="Exception: boom")
+            assert code == 500
+            data = resp.get_json()
+            assert data["status"] == "error"
+            assert data["details"] == "[REDACTED; check logs]"