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

vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 890c98757ab Keep FAB public user lookup off the API server event loop 
(#77599)
890c98757ab is described below

commit 890c98757ab9c70d4f0bc95aedd8c79296f0d2bf
Author: ChickenBenny <[email protected]>
AuthorDate: Thu Nov 26 22:58:59 2026 +0800

    Keep FAB public user lookup off the API server event loop (#77599)
---
 .../providers/fab/auth_manager/fab_auth_manager.py |  6 ++--
 .../providers/fab/auth_manager/middleware.py       |  2 +-
 .../unit/fab/auth_manager/test_fab_auth_manager.py | 42 +++++++++++++++++-----
 .../tests/unit/fab/auth_manager/test_middleware.py | 14 ++++----
 .../unit/fab/auth_manager/test_public_access.py    |  4 ++-
 5 files changed, 47 insertions(+), 21 deletions(-)

diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py
index 14a251a7764..ebb2b2c011d 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py
@@ -455,8 +455,7 @@ class FabAuthManager(BaseAuthManager[User]):
             return self.flask_app.config.get("AUTH_ROLE_PUBLIC")
         return None
 
-    @provide_session
-    def build_public_user(self, *, session: Session = NEW_SESSION) -> 
AnonymousUser | None:
+    async def build_public_user(self) -> AnonymousUser | None:
         """
         Build an :class:`AnonymousUser` pre-populated with the configured 
public role.
 
@@ -473,7 +472,8 @@ class FabAuthManager(BaseAuthManager[User]):
             return None
 
         user = AnonymousUser()
-        role = session.scalar(select(Role).where(Role.name == 
public_role_name))
+        async with create_session_async() as session:
+            role = await session.scalar(select(Role).where(Role.name == 
public_role_name))
         # ``AnonymousUser.roles``/``perms`` normally resolve lazily through 
Flask's
         # ``current_app``. Writing ``_roles``/``_perms`` directly freezes a 
snapshot for
         # the lifetime of a single FastAPI authorization check.
diff --git a/providers/fab/src/airflow/providers/fab/auth_manager/middleware.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/middleware.py
index e16b1af85bb..5338cf61f7d 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/middleware.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/middleware.py
@@ -46,7 +46,7 @@ class FabAuthRolePublicMiddleware(BaseHTTPMiddleware):
         if not self._has_auth_token(request):
             auth_manager = cast("FabAuthManager", get_auth_manager())
 
-            public_user = auth_manager.build_public_user()
+            public_user = await auth_manager.build_public_user()
             if public_user is not None:
                 request.state.user = public_user
 
diff --git a/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py 
b/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py
index 020d12aa7c2..c2bedbd5dc7 100644
--- a/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py
+++ b/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py
@@ -30,7 +30,8 @@ from cachetools import TTLCache
 from flask import g
 from flask_appbuilder.const import AUTH_DB, AUTH_LDAP, AUTH_OAUTH, 
AUTH_REMOTE_USER
 from pydantic import SecretStr
-from sqlalchemy import select, update
+from sqlalchemy import event, select, update
+from sqlalchemy.engine import Engine
 from sqlalchemy.exc import OperationalError, PendingRollbackError
 from sqlalchemy.orm import Session
 
@@ -570,25 +571,27 @@ class TestFabAuthManager:
         finally:
             flask_app.config["AUTH_ROLE_PUBLIC"] = previous
 
-    def test_build_public_user_returns_none_when_not_configured(
+    @pytest.mark.asyncio
+    async def test_build_public_user_returns_none_when_not_configured(
         self, flask_app, auth_manager_with_appbuilder
     ):
         """Without ``AUTH_ROLE_PUBLIC`` set on the Flask app, there is no 
public user."""
         previous = flask_app.config.get("AUTH_ROLE_PUBLIC")
         flask_app.config["AUTH_ROLE_PUBLIC"] = None
         try:
-            assert auth_manager_with_appbuilder.build_public_user() is None
+            assert await auth_manager_with_appbuilder.build_public_user() is 
None
         finally:
             flask_app.config["AUTH_ROLE_PUBLIC"] = previous
 
-    def test_build_public_user_returns_anonymous_user(self, flask_app, 
auth_manager_with_appbuilder):
+    @pytest.mark.asyncio
+    async def test_build_public_user_returns_anonymous_user(self, flask_app, 
auth_manager_with_appbuilder):
         """``AUTH_ROLE_PUBLIC`` yields an :class:`AnonymousUser` with the role 
resolved from the DB."""
         from airflow.providers.fab.auth_manager.models.anonymous_user import 
AnonymousUser
 
         previous = flask_app.config.get("AUTH_ROLE_PUBLIC")
         flask_app.config["AUTH_ROLE_PUBLIC"] = "Admin"
         try:
-            user = auth_manager_with_appbuilder.build_public_user()
+            user = await auth_manager_with_appbuilder.build_public_user()
         finally:
             flask_app.config["AUTH_ROLE_PUBLIC"] = previous
 
@@ -599,7 +602,8 @@ class TestFabAuthManager:
         # Flask request/app context.
         assert user._perms, "Expected permissions to be pre-populated on the 
public user"
 
-    def test_build_public_user_with_unknown_role_returns_user_with_empty_perms(
+    @pytest.mark.asyncio
+    async def 
test_build_public_user_with_unknown_role_returns_user_with_empty_perms(
         self, flask_app, auth_manager_with_appbuilder
     ):
         """A misconfigured role name still yields an :class:`AnonymousUser` 
with empty perms."""
@@ -608,7 +612,7 @@ class TestFabAuthManager:
         previous = flask_app.config.get("AUTH_ROLE_PUBLIC")
         flask_app.config["AUTH_ROLE_PUBLIC"] = "DoesNotExist"
         try:
-            user = auth_manager_with_appbuilder.build_public_user()
+            user = await auth_manager_with_appbuilder.build_public_user()
         finally:
             flask_app.config["AUTH_ROLE_PUBLIC"] = previous
 
@@ -616,6 +620,25 @@ class TestFabAuthManager:
         # Role not found in the DB, so no pre-populated perms.
         assert user._perms == set()
 
+    @pytest.mark.asyncio
+    async def test_build_public_user_does_not_use_sync_engine(self, 
auth_manager_with_appbuilder):
+        """The public role lookup must not run on a sync engine (it would 
block the event loop)."""
+        sync_statements = []
+
+        def record_sync_statement(conn, cursor, statement, parameters, 
context, executemany):
+            if not conn.dialect.is_async:
+                sync_statements.append(statement)
+
+        event.listen(Engine, "before_cursor_execute", record_sync_statement)
+        try:
+            with conf_vars({("fab", "auth_role_public"): "Admin"}):
+                user = await auth_manager_with_appbuilder.build_public_user()
+        finally:
+            event.remove(Engine, "before_cursor_execute", 
record_sync_statement)
+
+        assert sync_statements == []
+        assert user._perms
+
     def test_get_fastapi_middlewares_disabled(self, flask_app, 
auth_manager_with_appbuilder):
         """No middleware is registered when public access is not configured."""
         previous = flask_app.config.get("AUTH_ROLE_PUBLIC")
@@ -1287,7 +1310,8 @@ class TestFabAuthManager:
         ],
     )
     @pytest.mark.parametrize("as_public_user", [False, True], ids=["db-user", 
"public-user"])
-    def test_get_authorized_dag_ids(
+    @pytest.mark.asyncio
+    async def test_get_authorized_dag_ids(
         self,
         method,
         user_permissions,
@@ -1319,7 +1343,7 @@ class TestFabAuthManager:
             delete_role(flask_app, "test")
             create_role(flask_app, "test", user_permissions)
             with conf_vars({("fab", "auth_role_public"): "test"}):
-                user = auth_manager_with_appbuilder.build_public_user()
+                user = await auth_manager_with_appbuilder.build_public_user()
         else:
             user = create_user(
                 flask_app,
diff --git a/providers/fab/tests/unit/fab/auth_manager/test_middleware.py 
b/providers/fab/tests/unit/fab/auth_manager/test_middleware.py
index b6dc2665531..a8aa54da237 100644
--- a/providers/fab/tests/unit/fab/auth_manager/test_middleware.py
+++ b/providers/fab/tests/unit/fab/auth_manager/test_middleware.py
@@ -38,7 +38,7 @@ class TestFabAuthRolePublicMiddleware:
     async def test_sets_public_user_when_no_auth_present(self, 
mock_get_auth_manager):
         public_user = Mock(name="public_user")
         auth_manager = Mock()
-        auth_manager.build_public_user = Mock(return_value=public_user)
+        auth_manager.build_public_user = AsyncMock(return_value=public_user)
         mock_get_auth_manager.return_value = auth_manager
 
         middleware = FabAuthRolePublicMiddleware(app=Mock())
@@ -60,13 +60,13 @@ class TestFabAuthRolePublicMiddleware:
         else:
             assert not hasattr(request.state, "user_authenticated_via")
 
-        auth_manager.build_public_user.assert_called_once_with()
+        auth_manager.build_public_user.assert_awaited_once_with()
         call_next.assert_awaited_once_with(request)
 
     @patch("airflow.providers.fab.auth_manager.middleware.get_auth_manager")
     async def test_skips_when_authorization_header_present(self, 
mock_get_auth_manager):
         auth_manager = Mock()
-        auth_manager.build_public_user = Mock()
+        auth_manager.build_public_user = AsyncMock()
         mock_get_auth_manager.return_value = auth_manager
 
         middleware = FabAuthRolePublicMiddleware(app=Mock())
@@ -75,13 +75,13 @@ class TestFabAuthRolePublicMiddleware:
 
         await middleware.dispatch(request, call_next)
 
-        auth_manager.build_public_user.assert_not_called()
+        auth_manager.build_public_user.assert_not_awaited()
         assert not hasattr(request.state, "user")
 
     @patch("airflow.providers.fab.auth_manager.middleware.get_auth_manager")
     async def test_skips_when_jwt_cookie_present(self, mock_get_auth_manager):
         auth_manager = Mock()
-        auth_manager.build_public_user = Mock()
+        auth_manager.build_public_user = AsyncMock()
         mock_get_auth_manager.return_value = auth_manager
 
         middleware = FabAuthRolePublicMiddleware(app=Mock())
@@ -90,12 +90,12 @@ class TestFabAuthRolePublicMiddleware:
 
         await middleware.dispatch(request, call_next)
 
-        auth_manager.build_public_user.assert_not_called()
+        auth_manager.build_public_user.assert_not_awaited()
 
     @patch("airflow.providers.fab.auth_manager.middleware.get_auth_manager")
     async def test_does_nothing_when_auth_manager_has_no_public_user(self, 
mock_get_auth_manager):
         auth_manager = Mock()
-        auth_manager.build_public_user = Mock(return_value=None)
+        auth_manager.build_public_user = AsyncMock(return_value=None)
         mock_get_auth_manager.return_value = auth_manager
 
         middleware = FabAuthRolePublicMiddleware(app=Mock())
diff --git a/providers/fab/tests/unit/fab/auth_manager/test_public_access.py 
b/providers/fab/tests/unit/fab/auth_manager/test_public_access.py
index 75f627a50eb..9be80a57486 100644
--- a/providers/fab/tests/unit/fab/auth_manager/test_public_access.py
+++ b/providers/fab/tests/unit/fab/auth_manager/test_public_access.py
@@ -53,7 +53,9 @@ def run_api_server(tmp_path, *, webserver_config: str, 
auth_role_public: str = "
         }
     ):
         auth_manager = cast("FabAuthManager", create_auth_manager())
-        yield auth_manager, TestClient(create_app(apps="core"), 
raise_server_exceptions=False)
+        # One event loop for every request, as in the API server: pooled async 
connections are bound to it.
+        with TestClient(create_app(apps="core"), 
raise_server_exceptions=False) as client:
+            yield auth_manager, client
 
 
 def 
test_legacy_auth_role_public_grants_its_role_to_anonymous_requests(tmp_path):

Reply via email to