test_safe_error_boundary.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from __future__ import annotations
  2. import logging
  3. def test_global_error_boundary_redacts_secrets_and_returns_correlation_id(
  4. caplog,
  5. monkeypatch,
  6. ):
  7. from flask import Blueprint
  8. from app import create_app
  9. monkeypatch.setattr(
  10. "app.core.system.permissions.authenticate_request",
  11. lambda: {
  12. "id": "00000000-0000-7000-8000-000000000111",
  13. "roles": ["admin"],
  14. },
  15. )
  16. app = create_app()
  17. app.config.update(TESTING=False, PROPAGATE_EXCEPTIONS=False)
  18. failure = Blueprint("wp12_failure", __name__)
  19. @failure.get("/api/wp12/failure")
  20. def unsafe_failure():
  21. raise RuntimeError(
  22. "password=database-secret "
  23. "postgresql://admin:url-secret@db/dataops "
  24. "Authorization: Bearer bearer-secret"
  25. )
  26. app.register_blueprint(failure)
  27. with caplog.at_level(logging.ERROR):
  28. response = app.test_client().get("/api/wp12/failure")
  29. assert response.status_code == 500
  30. payload = response.get_json()
  31. assert payload["message"] == "服务器内部错误"
  32. assert len(payload["correlation_id"]) == 36
  33. combined = caplog.text + repr(payload)
  34. for secret in ("database-secret", "url-secret", "bearer-secret"):
  35. assert secret not in combined
  36. def test_audit_and_auth_responses_disable_storage_and_add_security_headers(
  37. monkeypatch,
  38. ):
  39. from app import create_app
  40. monkeypatch.setattr(
  41. "app.core.system.permissions.authenticate_request",
  42. lambda: {
  43. "id": "00000000-0000-7000-8000-000000000111",
  44. "roles": ["admin"],
  45. },
  46. )
  47. app = create_app()
  48. app.config.update(TESTING=True)
  49. response = app.test_client().get("/api/system/auth/me")
  50. assert response.status_code == 200
  51. assert response.headers["Cache-Control"] == "no-store"
  52. assert response.headers["Referrer-Policy"] == "no-referrer"
  53. assert response.headers["Permissions-Policy"] == (
  54. "camera=(), microphone=(), geolocation=()"
  55. )