From 22c3232e071110bccaf8921b0c836e21e2ccafc5 Mon Sep 17 00:00:00 2001 From: Dave Page Date: Tue, 1 Dec 2026 11:37:44 +0000 Subject: [PATCH 1/2] Don't change the current session's saved connection state when releasing an idle session's connections. #10917 Driver.gc_timeout() releases the server managers of other, idle sessions during an unrelated request, and ServerManager.release() then called update_session(), which writes to the Flask session of that request. As a released manager has no state to save, this removed the current user's saved connection state for any server with the same id, such as a shared server. gc_timeout() now marks each manager whilst it releases it, and update_session() leaves the Flask session alone for a marked manager. Closes #10917 --- web/pgadmin/utils/driver/psycopg3/__init__.py | 9 ++- .../utils/driver/psycopg3/server_manager.py | 10 +++ .../tests/test_gc_timeout_session_state.py | 64 +++++++++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py diff --git a/web/pgadmin/utils/driver/psycopg3/__init__.py b/web/pgadmin/utils/driver/psycopg3/__init__.py index ee387a840fd..8282f0db7ae 100644 --- a/web/pgadmin/utils/driver/psycopg3/__init__.py +++ b/web/pgadmin/utils/driver/psycopg3/__init__.py @@ -516,7 +516,14 @@ def gc_timeout(self): m for m in sess_mgr.values() if isinstance(m, ServerManager) ]: - mgr.release() + # Releasing would otherwise record the manager's state + # in this request's Flask session rather than in the + # idle session that owns it. + mgr.releasing_for_other_session = True + try: + mgr.release() + finally: + mgr.releasing_for_other_session = False # Expired sessions stay in self.managers, so only run the # callbacks once per idle period rather than on every sweep. if not sess_mgr.get('gc_callbacks_run'): diff --git a/web/pgadmin/utils/driver/psycopg3/server_manager.py b/web/pgadmin/utils/driver/psycopg3/server_manager.py index 20bde533fbe..36dc51ff368 100644 --- a/web/pgadmin/utils/driver/psycopg3/server_manager.py +++ b/web/pgadmin/utils/driver/psycopg3/server_manager.py @@ -74,6 +74,9 @@ def __init__(self, server): # fs_uniquifier of the pgAdmin user this manager was built for; # set by the driver, see Driver._current_pga_user. self.pga_user = None + # Set whilst Driver.gc_timeout() releases this manager on behalf + # of another session; see update_session(). + self.releasing_for_other_session = False self.update(server) @@ -571,6 +574,13 @@ def _update_password(self, passwd): conn.password = passwd def update_session(self): + if getattr(self, 'releasing_for_other_session', False): + # The Flask session belongs to the request that is cleaning + # up idle sessions, not to the session that owns this + # manager, so writing to it would overwrite or drop that + # user's own saved state for a server with the same id. + return + managers = session['__pgsql_server_managers'] \ if '__pgsql_server_managers' in session else dict() updated_mgr = self.as_dict() diff --git a/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py b/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py new file mode 100644 index 00000000000..6b17c68176c --- /dev/null +++ b/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py @@ -0,0 +1,64 @@ +########################################################################## +# +# pgAdmin 4 - PostgreSQL Tools +# +# Copyright (C) 2013 - 2026, The pgAdmin Development Team +# This software is released under the PostgreSQL Licence +# +########################################################################## + +"""Regression test for #10917: releasing an idle session's connections in +gc_timeout() must not change the saved connection state in the Flask +session of the request that runs the sweep.""" + +import datetime +from unittest.mock import MagicMock, patch + +from flask import session + +from config import PG_DEFAULT_DRIVER +from pgadmin.utils.driver import get_driver +import pgadmin.utils.driver.psycopg3 as psycopg3_driver +from pgadmin.utils.driver.psycopg3.server_manager import ServerManager +from pgadmin.utils.route import BaseTestGenerator + + +class GcTimeoutKeepsCurrentSessionStateTest(BaseTestGenerator): + """gc_timeout() releases the idle session's manager without touching + the current session's saved state for the same server id.""" + + scenarios = [ + ('Current session has saved state for the same server', + dict(saved={1: {'sid': 1, 'ver': 'saved'}})), + ('Current session has no saved state', + dict(saved=None)), + ] + + def runTest(self): + idle_mgr = ServerManager.__new__(ServerManager) + idle_mgr.sid = 1 + idle_mgr.connections = {'CONN:1': MagicMock(conn_id='CONN:1')} + idle_mgr.connections['CONN:1'].connected.return_value = False + + managers = { + 'idle': {'pinged': datetime.datetime.now() - + datetime.timedelta(days=1), + '1': idle_mgr}, + } + + with self.app.test_request_context(): + if self.saved is not None: + session['__pgsql_server_managers'] = dict(self.saved) + driver = get_driver(PG_DEFAULT_DRIVER) + with patch.object(driver, 'managers', managers), \ + patch.object(psycopg3_driver, 'session', + MagicMock(sid='current')), \ + patch.object(driver, 'run_session_gc_callbacks'), \ + patch.object(ServerManager, 'stop_ssh_tunnel'): + driver.gc_timeout() + + self.assertEqual(session.get('__pgsql_server_managers'), + self.saved) + self.assertEqual(idle_mgr.connections, {}) + self.assertFalse( + getattr(idle_mgr, 'releasing_for_other_session', False)) From 5d54e0a989d1b6113711d69dacb8c4a5aa700d69 Mon Sep 17 00:00:00 2001 From: Dave Page Date: Tue, 1 Dec 2026 11:55:32 +0000 Subject: [PATCH 2/2] Scope the idle-session release marker to the sweeping thread. A flag on the shared ServerManager could be cleared by a concurrent sweep whilst another was still releasing the same manager, and would also stop the manager's own session saving its state if it came back mid-sweep. --- web/pgadmin/utils/driver/psycopg3/__init__.py | 8 +--- .../utils/driver/psycopg3/server_manager.py | 34 ++++++++++---- .../tests/test_gc_timeout_session_state.py | 45 ++++++++++++++++++- 3 files changed, 70 insertions(+), 17 deletions(-) diff --git a/web/pgadmin/utils/driver/psycopg3/__init__.py b/web/pgadmin/utils/driver/psycopg3/__init__.py index 8282f0db7ae..b71a27263b1 100644 --- a/web/pgadmin/utils/driver/psycopg3/__init__.py +++ b/web/pgadmin/utils/driver/psycopg3/__init__.py @@ -516,14 +516,8 @@ def gc_timeout(self): m for m in sess_mgr.values() if isinstance(m, ServerManager) ]: - # Releasing would otherwise record the manager's state - # in this request's Flask session rather than in the - # idle session that owns it. - mgr.releasing_for_other_session = True - try: + with mgr.releasing_for_other_session(): mgr.release() - finally: - mgr.releasing_for_other_session = False # Expired sessions stay in self.managers, so only run the # callbacks once per idle period rather than on every sweep. if not sess_mgr.get('gc_callbacks_run'): diff --git a/web/pgadmin/utils/driver/psycopg3/server_manager.py b/web/pgadmin/utils/driver/psycopg3/server_manager.py index 36dc51ff368..9d8ee485630 100644 --- a/web/pgadmin/utils/driver/psycopg3/server_manager.py +++ b/web/pgadmin/utils/driver/psycopg3/server_manager.py @@ -14,7 +14,9 @@ import os import config import logging +import threading import warnings +from contextlib import contextmanager from flask import current_app, session from flask_security import current_user from flask_babel import gettext @@ -55,6 +57,13 @@ DB_STRING = 'DB:{0}' +# ids of the managers that this thread is releasing on behalf of another +# session; see ServerManager.releasing_for_other_session(). It is per +# thread because a manager is shared by the requests of its own session +# and by any other request's idle-session sweep. +_other_session_releases = threading.local() + + class ServerManager(object): """ class ServerManager @@ -74,9 +83,6 @@ def __init__(self, server): # fs_uniquifier of the pgAdmin user this manager was built for; # set by the driver, see Driver._current_pga_user. self.pga_user = None - # Set whilst Driver.gc_timeout() releases this manager on behalf - # of another session; see update_session(). - self.releasing_for_other_session = False self.update(server) @@ -573,12 +579,24 @@ def _update_password(self, passwd): if conn.conn is not None or conn.wasConnected is True: conn.password = passwd + @contextmanager + def releasing_for_other_session(self): + """ + Used by Driver.gc_timeout() whilst it releases this manager during + another session's request. The Flask session then belongs to that + request rather than to the session that owns this manager, so + update_session() must not write to it, or it would overwrite or + drop that user's own saved state for a server with the same id. + """ + ids = _other_session_releases.__dict__.setdefault('ids', set()) + ids.add(id(self)) + try: + yield + finally: + ids.discard(id(self)) + def update_session(self): - if getattr(self, 'releasing_for_other_session', False): - # The Flask session belongs to the request that is cleaning - # up idle sessions, not to the session that owns this - # manager, so writing to it would overwrite or drop that - # user's own saved state for a server with the same id. + if id(self) in getattr(_other_session_releases, 'ids', ()): return managers = session['__pgsql_server_managers'] \ diff --git a/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py b/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py index 6b17c68176c..2eb8264249b 100644 --- a/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py +++ b/web/pgadmin/utils/driver/psycopg3/tests/test_gc_timeout_session_state.py @@ -12,6 +12,7 @@ session of the request that runs the sweep.""" import datetime +import threading from unittest.mock import MagicMock, patch from flask import session @@ -60,5 +61,45 @@ def runTest(self): self.assertEqual(session.get('__pgsql_server_managers'), self.saved) self.assertEqual(idle_mgr.connections, {}) - self.assertFalse( - getattr(idle_mgr, 'releasing_for_other_session', False)) + + # Once the sweep is done, the manager's own session can save + # its state again. + idle_mgr.ver = 'idle' + idle_mgr.connections = {'CONN:1': MagicMock()} + with patch.object(ServerManager, 'as_dict', + return_value={'sid': 1, 'ver': 'idle'}): + idle_mgr.update_session() + self.assertEqual(session['__pgsql_server_managers'][1], + {'sid': 1, 'ver': 'idle'}) + + +class OtherSessionMarkerIsPerThreadTest(BaseTestGenerator): + """Whilst one thread releases a manager for another session, a request + of the manager's own session on another thread still saves its + state.""" + + scenarios = [ + ('Marker does not affect other threads', dict()), + ] + + def runTest(self): + mgr = ServerManager.__new__(ServerManager) + mgr.sid = 1 + saved = {} + + def own_session_request(): + with self.app.test_request_context(): + mgr.update_session() + saved.update(session['__pgsql_server_managers']) + + with patch.object(ServerManager, 'as_dict', + return_value={'sid': 1}), \ + self.app.test_request_context(): + with mgr.releasing_for_other_session(): + mgr.update_session() + other = threading.Thread(target=own_session_request) + other.start() + other.join() + self.assertNotIn('__pgsql_server_managers', session) + + self.assertEqual(saved, {1: {'sid': 1}})