From 22b89265d62a229b04a5ff4103530ac15e527260 Mon Sep 17 00:00:00 2001 From: Yogesh Mahajan Date: Thu, 5 Dec 2024 16:54:35 +0530 Subject: [PATCH] Ensure CSRF errors handled to return unauthorized response. #8065 --- web/pgadmin/__init__.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/web/pgadmin/__init__.py b/web/pgadmin/__init__.py index 80ed5c44b..0b8790cc5 100644 --- a/web/pgadmin/__init__.py +++ b/web/pgadmin/__init__.py @@ -36,6 +36,7 @@ from werkzeug.datastructures import ImmutableDict from werkzeug.local import LocalProxy from werkzeug.utils import find_modules from jinja2 import select_autoescape +from flask_wtf.csrf import CSRFError from pgadmin.model import db, Role, Server, SharedServer, ServerGroup, \ User, Keys, Version, SCHEMA_VERSION as CURRENT_SCHEMA_VERSION @@ -45,7 +46,8 @@ from pgadmin.utils.session import create_session_interface, pga_unauthorised from pgadmin.utils.versioned_template_loader import VersionedTemplateLoader from datetime import timedelta, datetime from pgadmin.setup import get_version, set_version, check_db_tables -from pgadmin.utils.ajax import internal_server_error, make_json_response +from pgadmin.utils.ajax import internal_server_error, make_json_response, \ + unauthorized from pgadmin.utils.csrf import pgCSRFProtect from pgadmin import authenticate from pgadmin.utils.security_headers import SecurityHeaders @@ -915,13 +917,16 @@ def create_app(app_name=None): @app.errorhandler(HTTPException) def http_exception_handler(e): current_app.logger.error(e, exc_info=True) - if e.code == 400 and\ - e.description == 'The CSRF session token is missing.': - error = str(e.description) + 'Please refresh the page.' - return internal_server_error(errormsg=gettext(error)) return e - # Intialize the key manager + # Send unauthorized response if CSRF errors occurs. + @app.errorhandler(CSRFError) + def handle_csrf_error(error): + err_msg = str(error.description) + \ + gettext(' You need to refresh the page.') + return unauthorized(errormsg=err_msg) + + # Initialize the key manager app.keyManager = KeyManager() ##########################################################################