You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/08/09 15:55:27 UTC

(superset) 02/03: fix(database): bind permission-sync task to user id instead of username

This is an automated email from the ASF dual-hosted git repository.

rusackas pushed a commit to branch fix-identity-cache-robustness
in repository https://gitbox.apache.org/repos/asf/superset.git

commit c8828cc87b6df4fb5ecb40c7f79933b950ea0b06
Author: Amin Ghadersohi <am...@gmail.com>
AuthorDate: Sun Aug 9 08:21:58 2026 -0700

    fix(database): bind permission-sync task to user id instead of username
    
    sync_database_permissions_task resolved its acting identity from a
    username string at execution time. Since that resolution happens after
    the enqueue/execute boundary, a username change in between (e.g. a
    rename, or a subsequent reassignment of the old name) would silently
    change which user's account the async sync runs under -- including for
    OAuth2 token lookup and impersonate_user connections, which key off the
    bound g.user.
    
    Resolve the user id once at enqueue time and carry that immutable value
    across the Celery boundary instead, resolving it with
    get_user_by_id at execution time. This matches the convention already
    used by other identity-carrying Celery tasks in this codebase (e.g.
    export_dashboard_excel).
---
 superset/commands/database/sync_permissions.py     | 19 +++--
 tests/integration_tests/databases/api_tests.py     |  3 +-
 .../databases/sync_permissions_identity_test.py    | 82 ++++++++++------------
 .../commands/databases/sync_permissions_test.py    | 10 +--
 tests/unit_tests/commands/databases/update_test.py |  4 +-
 5 files changed, 61 insertions(+), 57 deletions(-)

diff --git a/superset/commands/database/sync_permissions.py b/superset/commands/database/sync_permissions.py
index af5064ad3ea..e7790e25140 100644
--- a/superset/commands/database/sync_permissions.py
+++ b/superset/commands/database/sync_permissions.py
@@ -73,6 +73,7 @@ class SyncPermissionsCommand(BaseCommand):
         self.username = username
         self._old_db_connection_name: str | None = old_db_connection_name
         self._db_connection: Database | None = db_connection
+        self._user_id: int | None = None
 
         self.async_mode: bool = app.config["SYNC_DB_PERMISSIONS_IN_ASYNC_MODE"]
 
@@ -99,11 +100,15 @@ class SyncPermissionsCommand(BaseCommand):
         if not self._db_connection:
             raise DatabaseNotFoundError()
 
-        # Need user info to impersonate for OAuth2 connections
-        if not self.username or not security_manager.get_user_by_username(
-            self.username
+        # Need user info to impersonate for OAuth2 connections. The id is
+        # captured here, at validation/enqueue time, so that an async run of
+        # this command binds to whoever held the username right now, rather
+        # than re-resolving the (mutable) username at execution time.
+        if not self.username or not (
+            user := security_manager.get_user_by_username(self.username)
         ):
             raise UserNotFoundInSessionError()
+        self._user_id = user.id
 
         with self.db_connection.get_sqla_engine() as engine:
             try:
@@ -126,7 +131,7 @@ class SyncPermissionsCommand(BaseCommand):
         self.validate()
         if self.async_mode:
             sync_database_permissions_task.delay(
-                self.db_connection_id, self.username, self.old_db_connection_name
+                self.db_connection_id, self._user_id, self.old_db_connection_name
             )
             return
 
@@ -313,14 +318,14 @@ class SyncPermissionsCommand(BaseCommand):
 
 @celery_app.task(name="sync_database_permissions", soft_time_limit=600)
 def sync_database_permissions_task(
-    database_id: int, username: str, old_db_connection_name: str
+    database_id: int, user_id: int, old_db_connection_name: str
 ) -> None:
     """
     Celery task that triggers the SyncPermissionsCommand in async mode.
     """
     with app.test_request_context():
         try:
-            user = security_manager.get_user_by_username(username)
+            user = security_manager.get_user_by_id(user_id)
             if not user:
                 raise UserNotFoundInSessionError()
             g.user = user
@@ -336,7 +341,7 @@ def sync_database_permissions_task(
 
             SyncPermissionsCommand(
                 database_id,
-                username,
+                user.username,
                 old_db_connection_name=old_db_connection_name,
                 db_connection=db_connection,
             ).sync_database_permissions()
diff --git a/tests/integration_tests/databases/api_tests.py b/tests/integration_tests/databases/api_tests.py
index 76a2517e814..426bfdf91de 100644
--- a/tests/integration_tests/databases/api_tests.py
+++ b/tests/integration_tests/databases/api_tests.py
@@ -4563,8 +4563,9 @@ class TestDatabaseApi(SupersetTestCase):
         assert rv.status_code == 202
         response = json.loads(rv.data.decode("utf-8"))
         assert response == {"message": "Async task created to sync permissions"}
+        admin_user = security_manager.find_user(username=ADMIN_USERNAME)
         mock_task.assert_called_once_with(
-            test_database.id, ADMIN_USERNAME, test_database.database_name
+            test_database.id, admin_user.id, test_database.database_name
         )
 
         # Cleanup
diff --git a/tests/unit_tests/commands/databases/sync_permissions_identity_test.py b/tests/unit_tests/commands/databases/sync_permissions_identity_test.py
index c5ca259b31a..43c950204b1 100644
--- a/tests/unit_tests/commands/databases/sync_permissions_identity_test.py
+++ b/tests/unit_tests/commands/databases/sync_permissions_identity_test.py
@@ -17,21 +17,21 @@
 """
 Traces how ``sync_database_permissions_task`` binds an acting identity.
 
-The Celery task only ever receives a ``username`` string (the async
-enqueue-to-execute boundary does not carry the enqueuing user's immutable
-id). At execution time it resolves that string to a user record via
-``security_manager.get_user_by_username`` and binds the result to
-``flask.g.user`` for the duration of the sync. Whoever currently holds that
-username at *execution* time -- not whoever held it at *enqueue* time -- is
-the identity the rest of the sync runs under.
+The Celery task receives the immutable ``id`` of the user who enqueued it
+(captured at enqueue time by ``SyncPermissionsCommand.validate``), not a
+mutable username string. At execution time it resolves that id to a user
+record via ``security_manager.get_user_by_id`` and binds the result to
+``flask.g.user`` for the duration of the sync. Because resolution is by id,
+a username change between enqueue and execution has no effect on which user
+record the task acts as.
 
 That identity is not just used for logging: ``Database._get_sqla_engine``
 reads ``g.user.id`` to look up a per-user OAuth2 access token, and, for
 databases with ``impersonate_user`` enabled, ``Database.get_effective_user``
 reads ``g.user.username`` (via ``get_username()``) to pick the identity the
 outgoing connection impersonates at the external database. These tests pin
-down both halves of that chain: the mutable-username resolution in the task,
-and the fact that the resolved user is what a privileged, identity-sensitive
+down both halves of that chain: the id-based resolution in the task, and the
+fact that the resolved user is what a privileged, identity-sensitive
 codepath consumes downstream.
 """
 
@@ -48,33 +48,25 @@ from superset.commands.database.sync_permissions import (
 from superset.models.core import Database
 
 
-def test_task_binds_g_user_to_whoever_currently_holds_the_username(
+def test_task_binds_g_user_to_whoever_held_the_id_at_enqueue_time(
     mocker: MockerFixture,
 ) -> None:
     """
-    The task resolves its acting identity from the username string at
-    execution time. If a different user now holds that username than the
-    one who held it when the task was enqueued, the task binds ``g.user``
-    to that *different*, current user -- not to any identity captured at
-    enqueue time (no user id ever crosses the enqueue/execute boundary).
+    The task resolves its acting identity from the user id captured at
+    enqueue time, via ``security_manager.get_user_by_id``. A username change
+    that happens between enqueue and execution has no effect on which user
+    record the task binds ``g.user`` to, because the id -- not the mutable
+    username -- is what crosses the enqueue/execute boundary.
     """
-    # Whoever enqueued the task saw this identity for "alice" at enqueue
-    # time. It is never passed to the task -- only the string "alice" is.
-    original_alice = MagicMock()
-    original_alice.id = 101
-    original_alice.username = "alice"
-
-    # By the time the task executes, "alice" resolves to a different user
-    # record (e.g. the original account was renamed and the username was
-    # subsequently reassigned).
-    reassigned_alice = MagicMock()
-    reassigned_alice.id = 999
-    reassigned_alice.username = "alice"
+    # Whoever enqueued the task saw this identity at enqueue time. Its id is
+    # what's passed to the task.
+    enqueuing_user = MagicMock()
+    enqueuing_user.id = 101
+    enqueuing_user.username = "alice"
 
     get_user_mock = mocker.patch(
-        "superset.commands.database.sync_permissions.security_manager"
-        ".get_user_by_username",
-        return_value=reassigned_alice,
+        "superset.commands.database.sync_permissions.security_manager.get_user_by_id",
+        return_value=enqueuing_user,
     )
 
     mock_db_connection = MagicMock()
@@ -97,14 +89,19 @@ def test_task_binds_g_user_to_whoever_currently_holds_the_username(
         side_effect=capture_g_user,
     )
 
-    sync_database_permissions_task(1, "alice", "old_db_name")
+    # By the time the task executes, "alice" has been renamed (and the
+    # username could even have been reassigned to someone else) -- but the
+    # task was enqueued with id 101, so the rename doesn't affect resolution.
+    enqueuing_user.username = "alice_renamed"
 
-    # Resolution happened purely off the mutable username string...
-    get_user_mock.assert_called_once_with("alice")
-    # ...and the sync ran under whichever user currently holds "alice" at
-    # execution time -- the reassigned user, not the original enqueuer.
-    assert observed_g_user == [reassigned_alice]
-    assert observed_g_user[0].id != original_alice.id
+    sync_database_permissions_task(1, 101, "old_db_name")
+
+    # Resolution happened purely off the immutable id...
+    get_user_mock.assert_called_once_with(101)
+    # ...and the sync ran under the same user captured at enqueue time,
+    # regardless of the username change in between.
+    assert observed_g_user == [enqueuing_user]
+    assert observed_g_user[0].id == 101
 
 
 def test_g_user_bound_by_the_task_drives_external_db_impersonation_identity(
@@ -115,10 +112,9 @@ def test_g_user_bound_by_the_task_drives_external_db_impersonation_identity(
     decide which identity an outgoing, ``impersonate_user``-enabled
     connection impersonates at the external database -- reads
     ``g.user.username``. Whatever user object the task bound to ``g.user``
-    (per the previous test, the *current* holder of the username, which can
-    differ from the task's original enqueuer) is therefore the identity
-    used to connect to the external database, not a fixed identity captured
-    when the task was queued.
+    (per the previous test, the user resolved from the id captured at
+    enqueue time) is therefore the identity used to connect to the external
+    database.
     """
     database = MagicMock(spec=Database)
     database.impersonate_user = True
@@ -135,8 +131,8 @@ def test_g_user_bound_by_the_task_drives_external_db_impersonation_identity(
     mocker.patch("superset.utils.core.g", MagicMock(user=user_a))
     assert Database.get_effective_user(database, object_url) == "user_a"
 
-    # A different user bound to g.user (as would happen if the task
-    # resolved a reassigned username) changes the impersonated identity
+    # A different user bound to g.user (as would happen if a different id
+    # had been captured at enqueue time) changes the impersonated identity
     # for the exact same database configuration and target URL.
     user_b = MagicMock()
     user_b.username = "user_b"
diff --git a/tests/unit_tests/commands/databases/sync_permissions_test.py b/tests/unit_tests/commands/databases/sync_permissions_test.py
index 2400c726d03..f6b462b8131 100644
--- a/tests/unit_tests/commands/databases/sync_permissions_test.py
+++ b/tests/unit_tests/commands/databases/sync_permissions_test.py
@@ -100,7 +100,7 @@ def test_sync_permissions_command_async_mode(
         "superset.commands.database.sync_permissions.DatabaseDAO"
     )
     mock_database_dao.find_by_id.return_value = database_with_catalog
-    mocker.patch(
+    mock_user = mocker.patch(
         "superset.commands.database.sync_permissions.security_manager.get_user_by_username"
     )
     async_task_mock = mocker.patch(
@@ -110,7 +110,7 @@ def test_sync_permissions_command_async_mode(
 
     cmmd = SyncPermissionsCommand(1, "admin")
     cmmd.run()
-    async_task_mock.delay.assert_called_once_with(1, "admin", "my_db")
+    async_task_mock.delay.assert_called_once_with(1, mock_user.return_value.id, "my_db")
 
 
 @with_config({"SYNC_DB_PERMISSIONS_IN_ASYNC_MODE": False})
@@ -219,7 +219,7 @@ def test_sync_permissions_command_async_mode_new_db_name(
     Test ``SyncPermissionsCommand`` in async mode when the
     database name changed.
     """
-    mocker.patch(
+    mock_user = mocker.patch(
         "superset.commands.database.sync_permissions.security_manager.get_user_by_username"
     )
     async_task_mock = mocker.patch(
@@ -233,7 +233,9 @@ def test_sync_permissions_command_async_mode_new_db_name(
     )
     cmmd.run()
 
-    async_task_mock.delay.assert_called_once_with(1, "admin", "Old Name")
+    async_task_mock.delay.assert_called_once_with(
+        1, mock_user.return_value.id, "Old Name"
+    )
 
 
 def test_sync_permissions_command_get_catalogs(database_with_catalog: MagicMock):
diff --git a/tests/unit_tests/commands/databases/update_test.py b/tests/unit_tests/commands/databases/update_test.py
index 32b816295be..07663df2450 100644
--- a/tests/unit_tests/commands/databases/update_test.py
+++ b/tests/unit_tests/commands/databases/update_test.py
@@ -122,11 +122,11 @@ def test_update_sync_perms_in_async_mode(
         "superset.commands.database.sync_permissions.sync_database_permissions_task.delay"
     )
     mocker.patch("superset.commands.database.update.get_username", return_value="admin")
-    mocker.patch("superset.security_manager.get_user_by_username")
+    mock_user = mocker.patch("superset.security_manager.get_user_by_username")
 
     UpdateDatabaseCommand(1, {}).run()
 
-    sync_task.assert_called_once_with(1, "admin", "my_db")
+    sync_task.assert_called_once_with(1, mock_user.return_value.id, "my_db")
 
 
 def test_update_without_catalog(