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 64afc264b5e Fix FAB public access in the API server without a Flask 
app context (#77538)
64afc264b5e is described below

commit 64afc264b5eb589dcfe0341178352fea9a1c9f9d
Author: ChickenBenny <[email protected]>
AuthorDate: Wed Nov 25 23:00:00 2026 +0800

    Fix FAB public access in the API server without a Flask app context (#77538)
---
 .../docs/auth-manager/webserver-authentication.rst | 15 +++--
 .../providers/fab/auth_manager/fab_auth_manager.py | 37 ++++++-----
 .../fab/auth_manager/models/anonymous_user.py      | 20 ++++--
 .../fab/auth_manager/models/test_anonymous_user.py | 16 +++++
 .../unit/fab/auth_manager/test_public_access.py    | 72 ++++++++++++++++++++++
 5 files changed, 134 insertions(+), 26 deletions(-)

diff --git a/providers/fab/docs/auth-manager/webserver-authentication.rst 
b/providers/fab/docs/auth-manager/webserver-authentication.rst
index dac507c1cc8..cda921a92b8 100644
--- a/providers/fab/docs/auth-manager/webserver-authentication.rst
+++ b/providers/fab/docs/auth-manager/webserver-authentication.rst
@@ -42,13 +42,20 @@ following CLI commands to create an account:
         --role Admin \
         --email [email protected]
 
-To deactivate the authentication and allow users to be identified as 
Anonymous, the following entry
-in ``$AIRFLOW_HOME/webserver_config.py`` needs to be set with the desired role 
that the Anonymous
-user will have by default:
+To deactivate the authentication and allow users to be identified as 
Anonymous, set
+``[fab] auth_role_public`` to the role that the Anonymous user will have by 
default:
 
 .. code-block:: ini
 
-    AUTH_ROLE_PUBLIC = 'Admin'
+    [fab]
+    auth_role_public = Viewer
+
+The legacy ``AUTH_ROLE_PUBLIC`` entry in ``$AIRFLOW_HOME/webserver_config.py`` 
is still honored,
+but ``[fab] auth_role_public`` takes precedence when both are set:
+
+.. code-block:: python
+
+    AUTH_ROLE_PUBLIC = "Viewer"
 
 .. note::
 
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 c781cac23a0..14a251a7764 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
@@ -30,7 +30,7 @@ from weakref import WeakValueDictionary
 from cachetools import TTLCache
 from fastapi import FastAPI
 from fastapi.middleware.wsgi import WSGIMiddleware
-from flask import current_app, g
+from flask import current_app, g, has_app_context
 from flask_appbuilder.const import AUTH_DB, AUTH_LDAP
 from sqlalchemy import select
 from sqlalchemy.exc import SQLAlchemyError
@@ -438,23 +438,22 @@ class FabAuthManager(BaseAuthManager[User]):
         """
         Return the role granted to anonymous users, or ``None`` if public 
access is disabled.
 
-        Reads ``[fab] auth_role_public`` from the Airflow config first so this 
works
-        during FastAPI startup, before any Flask application context exists. 
Falls back
-        to ``AUTH_ROLE_PUBLIC`` on the Flask app config when an app context is 
available,
-        which covers the legacy ``AUTH_ROLE_PUBLIC`` entry in 
``webserver_config.py``.
+        Reads ``[fab] auth_role_public`` from the Airflow config first, then 
falls back to
+        ``AUTH_ROLE_PUBLIC`` on the Flask app config, which covers the legacy 
entry in
+        ``webserver_config.py``.
         """
         role_public = conf.get("fab", "auth_role_public", fallback="") or None
         if role_public:
             return role_public
         if self.appbuilder is None:
             return None
-        try:
-            return self.appbuilder.app.config.get("AUTH_ROLE_PUBLIC", None)
-        except RuntimeError:
-            # ``appbuilder.app`` is a werkzeug ``LocalProxy``; accessing it 
outside a
-            # Flask application context raises ``RuntimeError``. This happens 
during
-            # FastAPI startup when ``get_fastapi_middlewares`` is invoked.
-            return None
+        # The API server runs FastAPI requests and startup without a Flask app 
context, where
+        # ``current_app`` raises, so read the Flask app it built in 
``get_fastapi_app``.
+        if has_app_context():
+            return current_app.config.get("AUTH_ROLE_PUBLIC")
+        if self.flask_app is not None:
+            return self.flask_app.config.get("AUTH_ROLE_PUBLIC")
+        return None
 
     @provide_session
     def build_public_user(self, *, session: Session = NEW_SESSION) -> 
AnonymousUser | None:
@@ -475,10 +474,16 @@ class FabAuthManager(BaseAuthManager[User]):
 
         user = AnonymousUser()
         role = session.scalar(select(Role).where(Role.name == 
public_role_name))
-        if role is not None:
-            # ``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.
+        # ``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.
+        if role is None:
+            log.debug(
+                "The public role %r does not exist, so anonymous users get no 
permissions", public_role_name
+            )
+            user._roles = set()
+            user._perms = set()
+        else:
             user._roles = {role}
             user._perms = {(perm.action.name, perm.resource.name) for perm in 
role.permissions}
         return user
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/models/anonymous_user.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/models/anonymous_user.py
index f50341b2304..612f098911a 100644
--- 
a/providers/fab/src/airflow/providers/fab/auth_manager/models/anonymous_user.py
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/models/anonymous_user.py
@@ -17,32 +17,40 @@
 # under the License.
 from __future__ import annotations
 
+from typing import TYPE_CHECKING
+
 from flask import current_app
 from flask_login import AnonymousUserMixin
 
 from airflow.api_fastapi.auth.managers.models.base_user import BaseUser
 
+if TYPE_CHECKING:
+    from airflow.providers.fab.auth_manager.models import Role
+
 
 class AnonymousUser(AnonymousUserMixin, BaseUser):
     """User object used when no active user is logged in."""
 
-    _roles: set[tuple[str, str]] = set()
-    _perms: set[tuple[str, str]] = set()
+    # ``None`` means not loaded yet; an empty set means loaded with nothing 
granted, so a
+    # missing public role does not fall back to ``current_app``, which FastAPI 
does not have.
+    _roles: set[Role] | None = None
+    _perms: set[tuple[str, str]] | None = None
 
     first_name = "Anonymous"
     last_name = ""
 
     @property
     def roles(self):
-        if not self._roles:
+        if self._roles is None:
             public_role = current_app.config.get("AUTH_ROLE_PUBLIC", None)
-            self._roles = {current_app.appbuilder.sm.find_role(public_role)} 
if public_role else set()
+            role = current_app.appbuilder.sm.find_role(public_role) if 
public_role else None
+            self._roles = {role} if role is not None else set()
         return list(self._roles)
 
     @roles.setter
     def roles(self, roles):
         self._roles = roles
-        self._perms = set()
+        self._perms = None
 
     @property
     def groups(self):
@@ -50,7 +58,7 @@ class AnonymousUser(AnonymousUserMixin, BaseUser):
 
     @property
     def perms(self):
-        if not self._perms:
+        if self._perms is None:
             self._perms = {
                 (perm.action.name, perm.resource.name) for role in self.roles 
for perm in role.permissions
             }
diff --git 
a/providers/fab/tests/unit/fab/auth_manager/models/test_anonymous_user.py 
b/providers/fab/tests/unit/fab/auth_manager/models/test_anonymous_user.py
index 44f3d606fdf..a78cfc57fec 100644
--- a/providers/fab/tests/unit/fab/auth_manager/models/test_anonymous_user.py
+++ b/providers/fab/tests/unit/fab/auth_manager/models/test_anonymous_user.py
@@ -17,6 +17,8 @@
 # under the License.
 from __future__ import annotations
 
+import pytest
+
 from airflow.providers.fab.auth_manager.models.anonymous_user import 
AnonymousUser
 
 
@@ -32,3 +34,17 @@ class TestAnonymousUser:
         user = AnonymousUser()
         user._perms = perms
         assert user.perms == perms
+
+    @pytest.mark.db_test
+    def test_unknown_public_role_grants_nothing_in_an_app_context(self, 
minimal_app_for_auth_api):
+        """A Flask view resolving a public role that does not exist grants 
nothing instead of failing."""
+        app = minimal_app_for_auth_api
+        previous = app.config.get("AUTH_ROLE_PUBLIC")
+        app.config["AUTH_ROLE_PUBLIC"] = "DoesNotExist"
+        try:
+            with app.app_context():
+                user = AnonymousUser()
+                assert user.roles == []
+                assert user.perms == set()
+        finally:
+            app.config["AUTH_ROLE_PUBLIC"] = previous
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
new file mode 100644
index 00000000000..75f627a50eb
--- /dev/null
+++ b/providers/fab/tests/unit/fab/auth_manager/test_public_access.py
@@ -0,0 +1,72 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Public access in an API server started as ``airflow api-server`` starts it, 
with no Flask app context."""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from typing import TYPE_CHECKING, cast
+
+import pytest
+from fastapi.testclient import TestClient
+
+from airflow.api_fastapi.app import create_app, create_auth_manager
+
+from tests_common.test_utils.config import conf_vars
+from tests_common.test_utils.version_compat import AIRFLOW_V_3_3_PLUS
+
+if TYPE_CHECKING:
+    from airflow.providers.fab.auth_manager.fab_auth_manager import 
FabAuthManager
+
+pytestmark = [
+    pytest.mark.db_test,
+    # The API server registers auth manager middlewares through 
get_fastapi_middlewares since 3.3.
+    pytest.mark.skipif(
+        not AIRFLOW_V_3_3_PLUS, reason="Public access in the API server 
requires Airflow 3.3+"
+    ),
+]
+
+
+@contextmanager
+def run_api_server(tmp_path, *, webserver_config: str, auth_role_public: str = 
""):
+    config_file = tmp_path / "webserver_config.py"
+    config_file.write_text(webserver_config)
+    with conf_vars(
+        {
+            ("core", "auth_manager"): 
"airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager",
+            ("fab", "config_file"): str(config_file),
+            ("fab", "auth_role_public"): auth_role_public,
+        }
+    ):
+        auth_manager = cast("FabAuthManager", create_auth_manager())
+        yield auth_manager, TestClient(create_app(apps="core"), 
raise_server_exceptions=False)
+
+
+def 
test_legacy_auth_role_public_grants_its_role_to_anonymous_requests(tmp_path):
+    with run_api_server(tmp_path, webserver_config="AUTH_ROLE_PUBLIC = 
'Viewer'\n") as (_, client):
+        assert client.get("/api/v2/pools").status_code == 200
+        assert client.delete("/api/v2/pools/default_pool").status_code == 403
+
+
+def 
test_anonymous_requests_are_denied_after_the_public_role_is_deleted(tmp_path):
+    # The API server creates the public role at startup, so it is missing only 
once deleted, for
+    # example through DELETE /auth/fab/v1/roles/{name}, which calls the same 
security manager method.
+    with run_api_server(tmp_path, webserver_config="", 
auth_role_public="Guests") as (auth_manager, client):
+        with auth_manager.flask_app.app_context():
+            auth_manager.security_manager.delete_role("Guests")
+
+        assert client.get("/api/v2/pools").status_code == 403

Reply via email to