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 f2ea94cc4b4 Reject empty-like passwords in FAB auth manager (#77660)
f2ea94cc4b4 is described below

commit f2ea94cc4b46b6f744a72fa98d60ff43387ede4d
Author: Kevin Yang <[email protected]>
AuthorDate: Fri Nov 27 13:39:27 2026 -0500

    Reject empty-like passwords in FAB auth manager (#77660)
---
 .../providers/fab/auth_manager/fab_auth_manager.py |  4 +-
 .../fab/auth_manager/security_manager/override.py  | 33 ++++++---
 .../fab/auth_manager/security_manager/passwords.py | 28 ++++++++
 .../auth_manager/security_manager/test_override.py | 20 ++++++
 .../security_manager/test_passwords.py             | 38 ++++++++++
 .../tests/unit/fab/auth_manager/test_security.py   | 83 ++++++++++++++++++++++
 .../tests/unit/fab/www/views/test_views_login.py   | 34 +++++++++
 7 files changed, 230 insertions(+), 10 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 ebb2b2c011d..51ba3d54a15 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
@@ -65,6 +65,7 @@ from airflow.providers.common.compat.security.access_view 
import (
 )
 from airflow.providers.fab.auth_manager.models import Role, User
 from airflow.providers.fab.auth_manager.models.anonymous_user import 
AnonymousUser
+from airflow.providers.fab.auth_manager.security_manager.passwords import 
is_empty_password
 from airflow.providers.fab.version_compat import AIRFLOW_V_3_1_PLUS
 from airflow.providers.fab.www.app import create_app
 from airflow.providers.fab.www.security import permissions
@@ -509,12 +510,11 @@ class FabAuthManager(BaseAuthManager[User]):
         """
         username = body.get("username")
         password = body.get("password")
-        # Treat a password made only of NUL bytes as empty, as 
Flask-AppBuilder's login API does.
         if (
             not isinstance(username, str)
             or not isinstance(password, str)
             or not username
-            or not password.strip("\x00")
+            or is_empty_password(password)
         ):
             raise ValueError("Username and password must be provided")
 
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
 
b/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
index 80454c6d0be..3a00754b6c7 100644
--- 
a/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
@@ -85,6 +85,7 @@ from airflow.providers.fab.auth_manager.models import (
 )
 from airflow.providers.fab.auth_manager.models.anonymous_user import 
AnonymousUser
 from airflow.providers.fab.auth_manager.security_manager.constants import 
EXISTING_ROLES
+from airflow.providers.fab.auth_manager.security_manager.passwords import 
is_empty_password
 from airflow.providers.fab.auth_manager.views.auth_login import 
CustomAuthDBView, CustomAuthLDAPView
 from airflow.providers.fab.auth_manager.views.auth_oauth import 
CustomAuthOAuthView
 from airflow.providers.fab.auth_manager.views.permissions import (
@@ -621,7 +622,7 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
         Nothing is committed: the caller persists both changes together, 
normally with
         ``update_user``.
         """
-        user.password = self._hash_password(password)
+        user.password = None if is_empty_password(password) else 
self._hash_password(password)
         # Incremented in SQL so that concurrent password changes cannot write 
the same value.
         user.token_generation = self.user_model.token_generation + 1
 
@@ -1604,6 +1605,8 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
             user.groups = groups or []
             if hashed_password:
                 user.password = hashed_password
+            elif is_empty_password(password):
+                user.password = None
             else:
                 user.password = self._hash_password(password)
             self.session.commit()
@@ -1673,6 +1676,8 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
         register_user.last_name = last_name
         if hashed_password:
             register_user.password = hashed_password
+        elif is_empty_password(password):
+            register_user.password = None
         else:
             register_user.password = self._hash_password(password)
         register_user.registration_hash = str(uuid.uuid4())
@@ -2302,6 +2307,18 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
             log.error(e)
             return None
 
+    def _verify_password(self, user: User, password: str) -> bool:
+        """
+        Return whether the password matches the user's stored password.
+
+        An empty password, or a user without a stored password, never matches, 
and still runs
+        the fake hash check.
+        """
+        if user.password is None or is_empty_password(password):
+            
check_password_hash(current_app.config["AUTH_DB_FAKE_PASSWORD_HASH_CHECK"], 
"password")
+            return False
+        return check_password_hash(user.password, password)
+
     def check_password(self, username, password) -> bool:
         """
         Check if the password is correct for the username.
@@ -2312,9 +2329,7 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
         user = self.find_user(username=username)
         if user is None:
             user = self.find_user(email=username)
-        if user is None or user.password is None:
-            return False
-        return check_password_hash(user.password, password)
+        return user is not None and self._verify_password(user, password)
 
     def auth_user_db(self, username, password, rotate_session_id=True) -> User 
| None:
         """
@@ -2340,14 +2355,16 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
             )
             log.info(LOGMSG_WAR_SEC_LOGIN_FAILED, username)
             return None
-        if user.password is None:
-            return None
-        if check_password_hash(user.password, password):
+        if self._verify_password(user, password):
             if rotate_session_id:
                 self._rotate_session_id()
             self.update_user_auth_stat(user, True)
             return user
-        self.update_user_auth_stat(user, False)
+        # A user without a local password has nothing to guess here. When 
auth_user_db is a
+        # fallback after another method, as in basic_auth with LDAP, that 
method has already
+        # counted the failure.
+        if user.password is not None:
+            self.update_user_auth_stat(user, False)
         log.info(LOGMSG_WAR_SEC_LOGIN_FAILED, username)
         return None
 
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/passwords.py
 
b/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/passwords.py
new file mode 100644
index 00000000000..055c2650215
--- /dev/null
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/passwords.py
@@ -0,0 +1,28 @@
+#
+# 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.
+from __future__ import annotations
+
+
+def is_empty_password(password: str) -> bool:
+    """
+    Return whether the password is empty or made only of NUL bytes.
+
+    A password made only of NUL bytes counts as empty because ``scrypt`` and 
PBKDF2 hash it like the
+    empty password.
+    """
+    return not password.strip("\x00")
diff --git 
a/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py 
b/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
index 1a6779e5c7e..64d6f0c651d 100644
--- 
a/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
+++ 
b/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
@@ -449,6 +449,26 @@ class TestFabAirflowSecurityManagerOverride:
         check_password.return_value = False
         assert not sm.check_password("test_user", "test_password")
 
+    @mock.patch.object(EmptySecurityManager, "update_user_auth_stat", 
autospec=True)
+    @mock.patch.object(EmptySecurityManager, "find_user", autospec=True)
+    @mock.patch(
+        
"airflow.providers.fab.auth_manager.security_manager.override.check_password_hash",
 autospec=True
+    )
+    def 
test_auth_user_db_fails_user_without_password_without_counting_a_failed_login(
+        self, mock_check_password_hash, mock_find_user, 
mock_update_user_auth_stat
+    ):
+        sm = EmptySecurityManager()
+        user = Mock(spec=User, password=None, is_active=True)
+        mock_find_user.return_value = user
+        app = Flask(__name__)
+        app.config["AUTH_DB_FAKE_PASSWORD_HASH_CHECK"] = "fake-hash"
+
+        with app.app_context():
+            assert sm.auth_user_db("test_user", "test_password") is None
+
+        mock_check_password_hash.assert_called_once_with("fake-hash", 
"password")
+        mock_update_user_auth_stat.assert_not_called()
+
     def test_update_user_clears_cached_permissions(self):
         sm = EmptySecurityManager()
         user = Mock(
diff --git 
a/providers/fab/tests/unit/fab/auth_manager/security_manager/test_passwords.py 
b/providers/fab/tests/unit/fab/auth_manager/security_manager/test_passwords.py
new file mode 100644
index 00000000000..de56de1c8cc
--- /dev/null
+++ 
b/providers/fab/tests/unit/fab/auth_manager/security_manager/test_passwords.py
@@ -0,0 +1,38 @@
+#
+# 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.
+from __future__ import annotations
+
+import pytest
+
+from airflow.providers.fab.auth_manager.security_manager.passwords import 
is_empty_password
+
+
[email protected](
+    ("password", "expected"),
+    [
+        pytest.param("", True, id="empty"),
+        pytest.param("\x00", True, id="nul"),
+        pytest.param("\x00" * 8, True, id="nul-only"),
+        pytest.param(" ", False, id="space"),
+        pytest.param("a", False, id="plain"),
+        pytest.param("\x00a", False, id="leading-nul"),
+        pytest.param("a\x00", False, id="trailing-nul"),
+    ],
+)
+def test_is_empty_password(password, expected):
+    assert is_empty_password(password) is expected
diff --git a/providers/fab/tests/unit/fab/auth_manager/test_security.py 
b/providers/fab/tests/unit/fab/auth_manager/test_security.py
index c021394257d..10c13177a10 100644
--- a/providers/fab/tests/unit/fab/auth_manager/test_security.py
+++ b/providers/fab/tests/unit/fab/auth_manager/test_security.py
@@ -19,6 +19,7 @@ from __future__ import annotations
 
 import contextlib
 import datetime
+import importlib.metadata
 import json
 import logging
 from typing import TYPE_CHECKING
@@ -30,7 +31,9 @@ import time_machine
 from flask_appbuilder import expose, has_access
 from flask_appbuilder.models.sqla.interface import SQLAInterface
 from flask_appbuilder.views import BaseView, ModelView
+from packaging.version import Version
 from sqlalchemy import Date, Float, Integer, String, delete
+from werkzeug.security import generate_password_hash
 
 try:
     from sqlalchemy.orm import DeclarativeBase, Mapped
@@ -1377,6 +1380,86 @@ def test_add_user_uses_configured_hash_method(mock_hash, 
app, security_manager):
                 delete_user(app, "hash_method_add_test")
 
 
+USERNAME_WITHOUT_PASSWORD = "user_without_password"
+
+
[email protected]("password", ["", "\x00"])
+def test_reset_password_to_blank_stores_no_password_hash(password, app, 
security_manager):
+    try:
+        user = create_user(app, USERNAME_WITHOUT_PASSWORD)
+        with app.test_request_context():
+            assert security_manager.reset_password(user.id, password)
+            assert 
security_manager.find_user(username=USERNAME_WITHOUT_PASSWORD).password is None
+    finally:
+        delete_user(app, USERNAME_WITHOUT_PASSWORD)
+
+
[email protected](
+    "hash_method",
+    [
+        pytest.param(
+            "scrypt",
+            marks=pytest.mark.skipif(
+                Version(importlib.metadata.version("werkzeug")) < 
Version("3.0.0"),
+                reason="werkzeug < 3 has no scrypt",
+            ),
+        ),
+        "pbkdf2:sha256",
+    ],
+)
[email protected]("password", ["", "\x00", "\x00" * 8])
+def test_blank_password_does_not_match_hash_of_empty_password(password, 
hash_method, app, security_manager):
+    email = f"{USERNAME_WITHOUT_PASSWORD}@example.org"
+    with app.test_request_context():
+        delete_user(app, USERNAME_WITHOUT_PASSWORD)
+        security_manager.add_user(
+            username=USERNAME_WITHOUT_PASSWORD,
+            first_name="No",
+            last_name="Password",
+            email=email,
+            hashed_password=generate_password_hash("", method=hash_method),
+        )
+        try:
+            assert security_manager.auth_user_db(USERNAME_WITHOUT_PASSWORD, 
password) is None
+            assert security_manager.auth_user_db(email, password) is None
+            assert not 
security_manager.check_password(USERNAME_WITHOUT_PASSWORD, password)
+        finally:
+            delete_user(app, USERNAME_WITHOUT_PASSWORD)
+
+
[email protected]("password", ["", "\x00"])
+def test_add_user_without_password_stores_no_password_hash(password, app, 
security_manager):
+    with app.test_request_context():
+        delete_user(app, USERNAME_WITHOUT_PASSWORD)
+        try:
+            user = security_manager.add_user(
+                username=USERNAME_WITHOUT_PASSWORD,
+                first_name="No",
+                last_name="Password",
+                email=f"{USERNAME_WITHOUT_PASSWORD}@example.org",
+                password=password,
+            )
+            assert user.password is None
+        finally:
+            delete_user(app, USERNAME_WITHOUT_PASSWORD)
+
+
[email protected]("password", ["", "\x00"])
+def test_add_register_user_without_password_stores_no_password_hash(password, 
app, security_manager):
+    with app.test_request_context():
+        register_user = security_manager.add_register_user(
+            USERNAME_WITHOUT_PASSWORD,
+            "No",
+            "Password",
+            f"{USERNAME_WITHOUT_PASSWORD}@example.org",
+            password=password,
+        )
+        try:
+            assert register_user.password is None
+        finally:
+            security_manager.del_register_user(register_user)
+
+
 def test_resource_name_does_not_collide_with_reserved_resource_names():
     # Regression: a Dag literally named "DAGs" (the global resource name, and 
a valid
     # dag_id) must resolve to its own per-DAG resource, never the global one.
diff --git a/providers/fab/tests/unit/fab/www/views/test_views_login.py 
b/providers/fab/tests/unit/fab/www/views/test_views_login.py
index bb54bcafc93..f8cf06f4a9d 100644
--- a/providers/fab/tests/unit/fab/www/views/test_views_login.py
+++ b/providers/fab/tests/unit/fab/www/views/test_views_login.py
@@ -18,6 +18,7 @@
 from __future__ import annotations
 
 import pytest
+from werkzeug.security import generate_password_hash
 
 from airflow.api_fastapi.auth.managers.base_auth_manager import 
COOKIE_NAME_JWT_TOKEN
 from airflow.providers.fab.www import app as application
@@ -30,6 +31,7 @@ from unit.fab.utils import client_with_login
 pytestmark = pytest.mark.db_test
 
 USERNAME = "test_login_next"
+USERNAME_WITHOUT_PASSWORD = "test_login_without_password"
 
 
 @pytest.fixture
@@ -88,3 +90,35 @@ class TestLoginWhenAuthenticated:
 
         assert response.status_code == 302
         assert "evil.example.com" not in response.location
+
+
+class TestLoginWithoutPassword:
+    @pytest.mark.parametrize(
+        "hashed_password",
+        [
+            pytest.param("", id="added-without-password"),
+            pytest.param(generate_password_hash(""), 
id="stored-hash-of-empty-password"),
+        ],
+    )
+    def test_nul_password_does_not_sign_in(self, app, hashed_password):
+        with app.app_context():
+            delete_user(app, USERNAME_WITHOUT_PASSWORD)
+            app.appbuilder.sm.add_user(
+                username=USERNAME_WITHOUT_PASSWORD,
+                first_name=USERNAME_WITHOUT_PASSWORD,
+                last_name=USERNAME_WITHOUT_PASSWORD,
+                email=f"{USERNAME_WITHOUT_PASSWORD}@example.org",
+                hashed_password=hashed_password,
+            )
+            try:
+                client = app.test_client()
+                response = client.post(
+                    "/login/", data={"username": USERNAME_WITHOUT_PASSWORD, 
"password": "\x00"}
+                )
+                with client.session_transaction() as session:
+                    signed_in = "_user_id" in session
+            finally:
+                delete_user(app, USERNAME_WITHOUT_PASSWORD)
+
+        assert not signed_in
+        assert not _sets_token_cookie(response)

Reply via email to