You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "Jgprog117 (via GitHub)" <gi...@apache.org> on 2026/01/31 12:43:07 UTC
[PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Jgprog117 opened a new pull request, #61287:
URL: https://github.com/apache/airflow/pull/61287
Fixes #57981
When users authenticate via Azure OAuth SSO (and other OAuth providers), the UI briefly displays an authentication error message during the OAuth redirect flow. The error appears for approximately 1 second before disappearing once authentication successfully completes.
Root Cause:
The issue stems from a race condition during the OAuth authentication flow. After the OAuth callback completes and the user is authenticated, the Flask session containing OAuth tokens and user data may not be fully committed to the session backend (cookie or database) before the redirect response is sent to the client. When the UI loads and immediately makes API requests (like /ui/config), these requests arrive before the session is available, causing temporary 401 Unauthorized errors.
Solution:
This commit introduces a CustomAuthOAuthView that extends Flask-AppBuilder's AuthOAuthView to explicitly ensure the session is committed before redirecting. The fix:
1. Created providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py with CustomAuthOAuthView class
2. Override oauth_authorized() method to mark session.modified = True after parent's OAuth callback handling completes
3. Updated security_manager/override.py to use CustomAuthOAuthView instead of the default AuthOAuthView
This ensures Flask's session interface saves the session via the after_request handler before the HTTP redirect response is sent to the client, eliminating the race condition.
The fix addresses the root cause as suggested by maintainer feedback on PR #58037, rather than masking the error in the UI.
Testing:
- Syntax validated with py_compile
- Works with both session backends (database and securecookie)
- Maintains backward compatibility with existing OAuth flows
Related Issues:
- #55612 - Airflow UI initial XHR returns 401 before session cookie is set
- #57534 - Airflow 3.1.1 oauth login failure
- #57485 - Airflow 3.1.1 oauth login broken
- PR #58037 - Previous UI-based workaround attempt (closed)
<!--
Thank you for contributing!
Please provide above a brief description of the changes made in this pull request.
Write a good git commit message following this guide: http://chris.beams.io/posts/git-commit/
Please make sure that your code changes are covered with tests.
And in case of new features or big changes remember to adjust the documentation.
Feel free to ping (in general) for the review if you do not see reaction for a few days
(72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications.
In case of an existing issue, reference it using one of the following:
* closes: #ISSUE
* related: #ISSUE
-->
---
##### Was generative AI tooling used to co-author this PR?
<!--
If generative AI tooling has been used in the process of authoring this PR, please
change below checkbox to `[X]` followed by the name of the tool, uncomment the "Generated-by".
-->
- [ X] Yes (please specify the tool below)
Claude code was to fetch additional information regarding the issue and to document the solution.
<!--
Generated-by: [Tool Name] following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
-->
---
* Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
* For fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
* When adding dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
* For significant user-facing changes create newsfragment: `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Posted by "Jgprog117 (via GitHub)" <gi...@apache.org>.
Jgprog117 commented on PR #61287:
URL: https://github.com/apache/airflow/pull/61287#issuecomment-3833851700
@SameerMesiah97
Good comments, amended PR with your improvements. Thanks :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #61287:
URL: https://github.com/apache/airflow/pull/61287#issuecomment-3837752239
Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #61287:
URL: https://github.com/apache/airflow/pull/61287#discussion_r2752088108
##########
providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py:
##########
@@ -0,0 +1,85 @@
+# 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.
+
+"""Custom OAuth authentication view to fix session timing race condition."""
+
+from __future__ import annotations
+
+import logging
+
+from flask import session
+from flask_appbuilder.security.views import AuthOAuthView
+
+from airflow.configuration import conf
+
+log = logging.getLogger(__name__)
+
+
+class CustomAuthOAuthView(AuthOAuthView):
+ """
+ Custom OAuth authentication view that ensures session is committed before redirect.
+
+ Fixes issue #57981 where UI requests fail with 401 during OAuth flow because
+ the Flask session is not yet committed when the redirect response is sent.
+ """
+
+ def oauth_authorized(self, provider):
+ """
+ OAuth callback handler that explicitly commits session before redirect.
+
+ This method overrides the parent's oauth_authorized to ensure that the
+ Flask session (containing OAuth tokens and user authentication) is fully
+ committed to the session backend (cookie or database) before redirecting
+ the user to the UI.
+
+ This prevents the race condition where the UI makes API requests before
+ the session is available, causing temporary 401 errors during login.
+
+ Args:
+ provider: OAuth provider name (e.g., 'azure', 'google', 'github')
+
+ Returns:
+ Flask response object (redirect to original URL or home page)
+ """
+ log.debug("OAuth callback received for provider: %s", provider)
+
+ # Call parent's OAuth callback handling
+ # This processes the OAuth response, authenticates the user, and sets session data
+ response = super().oauth_authorized(provider)
+
+ # Explicitly commit the Flask session to ensure it's persisted
+ # This is critical for the race condition fix
+ session_backend = conf.get("fab", "SESSION_BACKEND", fallback="securecookie")
+
+ if session_backend == "database":
+ # For database sessions, Flask-Session automatically handles commit
+ # but we explicitly mark the session as modified to ensure it's saved
+ session.modified = True
+ log.debug("Marked session as modified for database backend")
+ else:
+ # For securecookie sessions, session is automatically encoded into cookie
+ # but we still mark it as modified to ensure fresh encoding
+ session.modified = True
+ log.debug("Marked session as modified for securecookie backend")
+
Review Comment:
Seems like the branching here is redundant. Is logging the only reason for doing this? If that is the case, I would recommend the following in place of lines 68-77:
```
session.modified = True
log.debug ("Marked session as modified for %s backend", session_backend)
```
##########
providers/fab/tests/unit/fab/auth_manager/views/test_auth_oauth.py:
##########
@@ -0,0 +1,88 @@
+# 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
+
+from unittest import mock
+
+from airflow.providers.fab.auth_manager.views.auth_oauth import CustomAuthOAuthView
+
+
+class TestCustomAuthOAuthView:
+ """Test CustomAuthOAuthView."""
+
+ @mock.patch("airflow.providers.fab.auth_manager.views.auth_oauth.conf")
+ @mock.patch("airflow.providers.fab.auth_manager.views.auth_oauth.session")
+ def test_oauth_authorized_marks_session_modified_database_backend(self, mock_session, mock_conf):
+ """Test that oauth_authorized marks session as modified for database backend."""
+ # Setup
+ mock_conf.get.return_value = "database"
+ view = CustomAuthOAuthView()
+
+ # Mock parent's oauth_authorized to return a mock response
+ with mock.patch.object(
+ view.__class__.__bases__[0], "oauth_authorized", return_value=mock.Mock()
+ ) as mock_parent:
Review Comment:
Why not patch `AuthOAuthView` instead of `view.__class__.__bases__[0]`? It would be more explicit and less brittle.
##########
providers/fab/tests/unit/fab/auth_manager/views/test_auth_oauth.py:
##########
@@ -0,0 +1,88 @@
+# 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
+
+from unittest import mock
+
+from airflow.providers.fab.auth_manager.views.auth_oauth import CustomAuthOAuthView
+
+
+class TestCustomAuthOAuthView:
+ """Test CustomAuthOAuthView."""
+
+ @mock.patch("airflow.providers.fab.auth_manager.views.auth_oauth.conf")
+ @mock.patch("airflow.providers.fab.auth_manager.views.auth_oauth.session")
+ def test_oauth_authorized_marks_session_modified_database_backend(self, mock_session, mock_conf):
+ """Test that oauth_authorized marks session as modified for database backend."""
+ # Setup
+ mock_conf.get.return_value = "database"
+ view = CustomAuthOAuthView()
+
+ # Mock parent's oauth_authorized to return a mock response
+ with mock.patch.object(
+ view.__class__.__bases__[0], "oauth_authorized", return_value=mock.Mock()
+ ) as mock_parent:
+ # Execute
+ view.oauth_authorized("test_provider")
+
+ # Verify parent was called
+ mock_parent.assert_called_once_with("test_provider")
+
+ # Verify session.modified was set to True
+ assert mock_session.modified is True
+
+ # Verify conf.get was called to check backend type
+ mock_conf.get.assert_called_once_with("fab", "SESSION_BACKEND", fallback="securecookie")
+
+ @mock.patch("airflow.providers.fab.auth_manager.views.auth_oauth.conf")
+ @mock.patch("airflow.providers.fab.auth_manager.views.auth_oauth.session")
+ def test_oauth_authorized_marks_session_modified_securecookie_backend(self, mock_session, mock_conf):
+ """Test that oauth_authorized marks session as modified for securecookie backend."""
+ # Setup
+ mock_conf.get.return_value = "securecookie"
+ view = CustomAuthOAuthView()
+
+ # Mock parent's oauth_authorized to return a mock response
+ with mock.patch.object(
+ view.__class__.__bases__[0], "oauth_authorized", return_value=mock.Mock()
+ ) as mock_parent:
+ # Execute
+ view.oauth_authorized("azure")
+
+ # Verify parent was called
+ mock_parent.assert_called_once_with("azure")
+
+ # Verify session.modified was set to True
+ assert mock_session.modified is True
+
Review Comment:
The 2 tests above can be collapsed into one.
##########
providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py:
##########
@@ -0,0 +1,85 @@
+# 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.
+
+"""Custom OAuth authentication view to fix session timing race condition."""
+
+from __future__ import annotations
+
+import logging
+
+from flask import session
+from flask_appbuilder.security.views import AuthOAuthView
+
+from airflow.configuration import conf
+
+log = logging.getLogger(__name__)
+
+
+class CustomAuthOAuthView(AuthOAuthView):
+ """
+ Custom OAuth authentication view that ensures session is committed before redirect.
+
+ Fixes issue #57981 where UI requests fail with 401 during OAuth flow because
+ the Flask session is not yet committed when the redirect response is sent.
+ """
+
+ def oauth_authorized(self, provider):
+ """
+ OAuth callback handler that explicitly commits session before redirect.
+
+ This method overrides the parent's oauth_authorized to ensure that the
+ Flask session (containing OAuth tokens and user authentication) is fully
+ committed to the session backend (cookie or database) before redirecting
+ the user to the UI.
+
+ This prevents the race condition where the UI makes API requests before
+ the session is available, causing temporary 401 errors during login.
+
+ Args:
+ provider: OAuth provider name (e.g., 'azure', 'google', 'github')
+
+ Returns:
+ Flask response object (redirect to original URL or home page)
+ """
+ log.debug("OAuth callback received for provider: %s", provider)
+
+ # Call parent's OAuth callback handling
+ # This processes the OAuth response, authenticates the user, and sets session data
+ response = super().oauth_authorized(provider)
+
+ # Explicitly commit the Flask session to ensure it's persisted
+ # This is critical for the race condition fix
+ session_backend = conf.get("fab", "SESSION_BACKEND", fallback="securecookie")
+
+ if session_backend == "database":
+ # For database sessions, Flask-Session automatically handles commit
+ # but we explicitly mark the session as modified to ensure it's saved
+ session.modified = True
+ log.debug("Marked session as modified for database backend")
+ else:
+ # For securecookie sessions, session is automatically encoded into cookie
+ # but we still mark it as modified to ensure fresh encoding
+ session.modified = True
+ log.debug("Marked session as modified for securecookie backend")
+
+ # The session will be saved when this request completes, before the redirect
+ # response is sent to the client. Flask's session interface handles this
+ # automatically via the after_request handler
+
+ log.debug("OAuth authentication completed successfully for provider: %s", provider)
+
Review Comment:
Looks like this message will be logged even when when authentication fails. `oauth_authorized` might not always raise in that scenario. Perhaps, this would be more accurate:
`log.debug("OAuth callback handling completed for provider: %s", provider)`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #61287:
URL: https://github.com/apache/airflow/pull/61287#issuecomment-3909491774
This PR might have introduced a bug, can you please take a look at #62028?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on PR #61287:
URL: https://github.com/apache/airflow/pull/61287#issuecomment-3837638102
@vincbeck
Looks good to me.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix OAuth session race condition causing false 401 errors during login [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck merged PR #61287:
URL: https://github.com/apache/airflow/pull/61287
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org