You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "anishgirianish (via GitHub)" <gi...@apache.org> on 2026/02/01 21:25:40 UTC

[PR] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

anishgirianish opened a new pull request, #61339:
URL: https://github.com/apache/airflow/pull/61339

   <!--
   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
   -->
   
   ## Summary                                                                                              
                                                                                                             
    - Adds a `revoked_token` table to persist revoked JWT token JTIs on logout                              
   - On logout, the token's `jti` is extracted and stored with its `exp` timestamp                         
    - On every authenticated request, `get_user_from_token` checks if the `jti` has been revoked before     
     allowing access                                                                                         
    - Expired revoked tokens are automatically cleaned up via the existing `db_cleanup` mechanism           
                                                                                                             
   ## Design decisions                                                                                     
                                                                                                             
    - **No in-memory cache**: The current implementation checks the DB on every request. For most Airflow deployments this is sufficient given the low request volume relative to high-traffic APIs. If this becomes a bottleneck, we can add an LRU cache or Redis-backed lookup — happy to discuss the right caching strategy in a follow-up if the community has preferences.                                       
    - **Inclusive naming**: Uses `RevokedToken` / `revoke()` / `is_revoked()` instead of blocklist/denylist 
     terminology.                                                                                            
   - **Sync `revoke()` / async `is_revoked()`**: `revoke()` is sync because the logout endpoint is sync.   
   - `is_revoked()` is async because `get_user_from_token` is async.      
   
   * closes: #47952                                
                                                                                                                                                                                                        
   * 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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "bugraoz93 (via GitHub)" <gi...@apache.org>.
bugraoz93 commented on PR #61339:
URL: https://github.com/apache/airflow/pull/61339#issuecomment-3849798186

   I would like to call this PR for the `protm` if no one disagrees :)
   
   #protm, which is solving a good problem for the token lifecycle. Additionally, it opens the door for great security improvement(s), such as a token invalidation endpoint for administrators in case of a token leak.


-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #61339:
URL: https://github.com/apache/airflow/pull/61339#discussion_r2754741541


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -55,6 +62,25 @@ def logout(request: Request, auth_manager: AuthManagerDep) -> RedirectResponse:
     if logout_url:
         return RedirectResponse(logout_url)
 
+    # Revoke the current token before deleting the cookie
+    token_str = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+    if token_str:
+        try:
+            header = jwt.get_unverified_header(token_str)
+            claims = jwt.decode(
+                token_str,
+                options={"verify_exp": False, "verify_signature": False},
+                algorithms=[header.get("alg", "HS256")],
+            )
+            jti = claims.get("jti")
+            exp = claims.get("exp")
+            if jti and exp:
+                from airflow.models.revoked_token import RevokedToken
+
+                RevokedToken.revoke(jti, datetime.fromtimestamp(exp, tz=timezone.utc))
+        except (jwt.InvalidTokenError, SQLAlchemyError):
+            log.warning("Failed to revoke token during logout", exc_info=True)

Review Comment:
   Agree



-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "anishgirianish (via GitHub)" <gi...@apache.org>.
anishgirianish commented on code in PR #61339:
URL: https://github.com/apache/airflow/pull/61339#discussion_r2755063281


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_auth.py:
##########
@@ -100,3 +101,39 @@ def test_should_respond_307(
         if delete_cookies:
             cookies = response.headers.get_list("set-cookie")
             assert any(f"{COOKIE_NAME_JWT_TOKEN}=" in c for c in cookies)
+

Review Comment:
   These added tests were already part of the existing TestLogout class.,



-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #61339:
URL: https://github.com/apache/airflow/pull/61339#issuecomment-3841971125

   Nice. Tests need to be fixed of course, and I think we should also add another thing - auto cleanup not only on clean_db but run (not always - just from time to time - we could store in memory last time when it was run and run it after an hour passes or so - when a token is checked. 
   
   That will slightly slow down some login attempts - but it will also auto-clean the db when `airflow db cleanup` is not run periodically. simply those expired tokens are not useful immediately after they expired.
   
   


-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #61339:
URL: https://github.com/apache/airflow/pull/61339#issuecomment-3849909056

   > I would like to call this PR for the `protm` if no one disagrees :)
   > 
   > #protm, which is solving a good problem for the token lifecycle. Additionally, it opens the door for great security improvement(s), such as a token invalidation endpoint for administrators in case of a token leak.
   
   Agree!


-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #61339:
URL: https://github.com/apache/airflow/pull/61339#discussion_r2756242052


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -55,6 +58,10 @@ def logout(request: Request, auth_manager: AuthManagerDep) -> RedirectResponse:
     if logout_url:
         return RedirectResponse(logout_url)
 
+    # Revoke the current token before deleting the cookie
+    if token_str := request.cookies.get(COOKIE_NAME_JWT_TOKEN):
+        auth_manager._get_token_validator().revoke_token(token_str)

Review Comment:
   I am not a super big fan of using a private method, maybe you can create a public method in `base_auth_manager`: `revoke_token`?



-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on code in PR #61339:
URL: https://github.com/apache/airflow/pull/61339#discussion_r2762666650


##########
airflow-core/src/airflow/models/revoked_token.py:
##########
@@ -0,0 +1,79 @@
+#
+# 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 time
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING
+
+import structlog
+from sqlalchemy import String, delete, exists, select
+from sqlalchemy.orm import Mapped
+
+from airflow.models.base import Base
+from airflow.utils.session import NEW_SESSION, provide_session
+from airflow.utils.sqlalchemy import UtcDateTime, mapped_column
+
+if TYPE_CHECKING:
+    from sqlalchemy.orm import Session
+
+log = structlog.get_logger(__name__)
+
+# Track last cleanup time to avoid running cleanup on every request
+_last_cleanup_time: float = 0.0
+# Run cleanup approximately every hour (3600 seconds)
+_CLEANUP_INTERVAL_SECONDS: int = 3600
+
+
+class RevokedToken(Base):
+    """Stores revoked JWT token JTIs to support token invalidation on logout."""
+
+    __tablename__ = "revoked_token"
+
+    jti: Mapped[str] = mapped_column(String(32), primary_key=True)
+    exp: Mapped[datetime] = mapped_column(UtcDateTime, nullable=False, index=True)
+
+    @classmethod
+    @provide_session
+    def revoke(cls, jti: str, exp: datetime, session: Session = NEW_SESSION) -> None:
+        """Add a token JTI to the revoked tokens."""
+        session.merge(cls(jti=jti, exp=exp))
+
+    @classmethod
+    @provide_session
+    def is_revoked(cls, jti: str, session: Session = NEW_SESSION) -> bool:
+        """Check if a token JTI has been revoked."""
+        cls._maybe_cleanup_expired(session)
+        return bool(session.scalar(select(exists().where(cls.jti == jti))))
+
+    @classmethod
+    def _maybe_cleanup_expired(cls, session: Session) -> None:
+        """
+        Periodically clean up expired revoked tokens.
+
+        Runs approximately once per hour during token validation to prevent
+        unbounded table growth. Uses monotonic time to track intervals.
+        """
+        global _last_cleanup_time

Review Comment:
   We are removing the global variable when possible. It would be better to use a class attribute instead of global variable for `_last_cleanup_time `, like:
   
   https://github.com/apache/airflow/blob/bccf1807dc8c25ef94dc4de038dbc210928ab14b/airflow-core/src/airflow/api_fastapi/app.py#L58-L59



##########
airflow-core/src/airflow/models/revoked_token.py:
##########
@@ -0,0 +1,79 @@
+#
+# 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 time
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING
+
+import structlog
+from sqlalchemy import String, delete, exists, select
+from sqlalchemy.orm import Mapped
+
+from airflow.models.base import Base
+from airflow.utils.session import NEW_SESSION, provide_session
+from airflow.utils.sqlalchemy import UtcDateTime, mapped_column
+
+if TYPE_CHECKING:
+    from sqlalchemy.orm import Session
+
+log = structlog.get_logger(__name__)
+
+# Track last cleanup time to avoid running cleanup on every request
+_last_cleanup_time: float = 0.0
+# Run cleanup approximately every hour (3600 seconds)
+_CLEANUP_INTERVAL_SECONDS: int = 3600

Review Comment:
   Should we respect `conf.getint("api_auth", "jwt_expiration_time")` instead of hardcode time as `_CLEANUP_INTERVAL_SECONDS ` here?
   
   e.g. double or triple times of `[api_auth/jwt_expiration_time]`.
   
   But anyway, the interval seconds should be larger than `[api_auth/jwt_expiration_time]`.



-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck merged PR #61339:
URL: https://github.com/apache/airflow/pull/61339


-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "anishgirianish (via GitHub)" <gi...@apache.org>.
anishgirianish commented on code in PR #61339:
URL: https://github.com/apache/airflow/pull/61339#discussion_r2755064479


##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_auth.py:
##########
@@ -100,3 +101,39 @@ def test_should_respond_307(
         if delete_cookies:
             cookies = response.headers.get_list("set-cookie")
             assert any(f"{COOKIE_NAME_JWT_TOKEN}=" in c for c in cookies)
+
+    @patch("airflow.models.revoked_token.RevokedToken")
+    def test_logout_blacklists_token(self, mock_revoked_token, test_client):
+        """Test that logout blacklists the JWT token's jti."""
+        test_client.app.state.auth_manager.get_url_logout.return_value = None
+        token_payload = {"sub": "admin", "jti": "test-jti-123", "exp": 9999999999}
+        token_str = jwt.encode(token_payload, "secret", algorithm="HS256")
+
+        test_client.cookies.set(COOKIE_NAME_JWT_TOKEN, token_str)
+        response = test_client.get("/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        mock_revoked_token.revoke.assert_called_once()
+        call_args = mock_revoked_token.revoke.call_args
+        assert call_args[0][0] == "test-jti-123"
+
+    @patch("airflow.models.revoked_token.RevokedToken")
+    def test_logout_without_cookie_does_not_blacklist(self, mock_revoked_token, test_client):
+        """Test that logout without a cookie does not attempt to blacklist."""
+        test_client.app.state.auth_manager.get_url_logout.return_value = None
+
+        response = test_client.get("/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        mock_revoked_token.revoke.assert_not_called()
+
+    @patch("airflow.models.revoked_token.RevokedToken")
+    def test_logout_with_malformed_cookie_does_not_blacklist(self, mock_revoked_token, test_client):
+        """Test that logout with a malformed cookie does not raise and does not blacklist."""
+        test_client.app.state.auth_manager.get_url_logout.return_value = None
+        test_client.cookies.set(COOKIE_NAME_JWT_TOKEN, "not-a-valid-jwt")
+
+        response = test_client.get("/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        mock_revoked_token.revoke.assert_not_called()

Review Comment:
   removed mock



-- 
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] AIP-84 : Add JWT token revokation for logout invalidation (#47952) [airflow]

Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on code in PR #61339:
URL: https://github.com/apache/airflow/pull/61339#discussion_r2753115355


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -16,15 +16,22 @@
 # under the License.
 from __future__ import annotations
 
+import logging

Review Comment:
   ```suggestion
   import structlog
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -55,6 +62,25 @@ def logout(request: Request, auth_manager: AuthManagerDep) -> RedirectResponse:
     if logout_url:
         return RedirectResponse(logout_url)
 
+    # Revoke the current token before deleting the cookie
+    token_str = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+    if token_str:
+        try:
+            header = jwt.get_unverified_header(token_str)
+            claims = jwt.decode(
+                token_str,
+                options={"verify_exp": False, "verify_signature": False},
+                algorithms=[header.get("alg", "HS256")],
+            )
+            jti = claims.get("jti")
+            exp = claims.get("exp")
+            if jti and exp:
+                from airflow.models.revoked_token import RevokedToken
+
+                RevokedToken.revoke(jti, datetime.fromtimestamp(exp, tz=timezone.utc))
+        except (jwt.InvalidTokenError, SQLAlchemyError):
+            log.warning("Failed to revoke token during logout", exc_info=True)

Review Comment:
   So maybe we could move this part as a new method of `JWTValidator`.



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -55,6 +62,25 @@ def logout(request: Request, auth_manager: AuthManagerDep) -> RedirectResponse:
     if logout_url:
         return RedirectResponse(logout_url)
 
+    # Revoke the current token before deleting the cookie
+    token_str = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+    if token_str:

Review Comment:
   ```suggestion
       if(token_str := request.cookies.get(COOKIE_NAME_JWT_TOKEN)):
   ```



##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_auth.py:
##########
@@ -100,3 +101,39 @@ def test_should_respond_307(
         if delete_cookies:
             cookies = response.headers.get_list("set-cookie")
             assert any(f"{COOKIE_NAME_JWT_TOKEN}=" in c for c in cookies)
+

Review Comment:
   We could separate the new tests to `TestLogout` class.
   
   ```suggestion
   class TestLogout(TestAuthEndpoint):
   ```



##########
airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py:
##########
@@ -139,6 +139,12 @@ async def get_user_from_token(self, token: str) -> BaseUser:
             log.error("JWT token is not valid: %s", e)
             raise e
 
+        from airflow.models.revoked_token import RevokedToken

Review Comment:
   It's fine to move to top level as `RevokedToken` will be used for each request, so we don't need `RevokedToken` at all.



##########
airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py:
##########
@@ -139,6 +139,12 @@ async def get_user_from_token(self, token: str) -> BaseUser:
             log.error("JWT token is not valid: %s", e)
             raise e
 
+        from airflow.models.revoked_token import RevokedToken
+
+        jti = payload.get("jti")
+        if jti and RevokedToken.is_revoked(jti):
+            raise InvalidTokenError("Token has been revoked")

Review Comment:
   ```suggestion
           if (jti := payload.get("jti")) and RevokedToken.is_revoked(jti):
               raise InvalidTokenError("Token has been revoked")
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -16,15 +16,22 @@
 # under the License.
 from __future__ import annotations
 
+import logging
+from datetime import datetime, timezone
+
+import jwt
 from fastapi import HTTPException, Request, status
 from fastapi.responses import RedirectResponse
+from sqlalchemy.exc import SQLAlchemyError
 
 from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN
 from airflow.api_fastapi.common.router import AirflowRouter
 from airflow.api_fastapi.core_api.openapi.exceptions import create_openapi_http_exception_doc
 from airflow.api_fastapi.core_api.security import AuthManagerDep, is_safe_url
 from airflow.configuration import conf
 
+log = logging.getLogger(__name__)

Review Comment:
   ```suggestion
   log = structlog.getLogger(__name__)
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/public/auth.py:
##########
@@ -55,6 +62,25 @@ def logout(request: Request, auth_manager: AuthManagerDep) -> RedirectResponse:
     if logout_url:
         return RedirectResponse(logout_url)
 
+    # Revoke the current token before deleting the cookie
+    token_str = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+    if token_str:
+        try:
+            header = jwt.get_unverified_header(token_str)
+            claims = jwt.decode(
+                token_str,
+                options={"verify_exp": False, "verify_signature": False},
+                algorithms=[header.get("alg", "HS256")],
+            )
+            jti = claims.get("jti")
+            exp = claims.get("exp")

Review Comment:
   It seems to be duplicated of what `JWTValidator.validated_claims` has implemented.



##########
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_auth.py:
##########
@@ -100,3 +101,39 @@ def test_should_respond_307(
         if delete_cookies:
             cookies = response.headers.get_list("set-cookie")
             assert any(f"{COOKIE_NAME_JWT_TOKEN}=" in c for c in cookies)
+
+    @patch("airflow.models.revoked_token.RevokedToken")
+    def test_logout_blacklists_token(self, mock_revoked_token, test_client):
+        """Test that logout blacklists the JWT token's jti."""
+        test_client.app.state.auth_manager.get_url_logout.return_value = None
+        token_payload = {"sub": "admin", "jti": "test-jti-123", "exp": 9999999999}
+        token_str = jwt.encode(token_payload, "secret", algorithm="HS256")
+
+        test_client.cookies.set(COOKIE_NAME_JWT_TOKEN, token_str)
+        response = test_client.get("/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        mock_revoked_token.revoke.assert_called_once()
+        call_args = mock_revoked_token.revoke.call_args
+        assert call_args[0][0] == "test-jti-123"
+
+    @patch("airflow.models.revoked_token.RevokedToken")
+    def test_logout_without_cookie_does_not_blacklist(self, mock_revoked_token, test_client):
+        """Test that logout without a cookie does not attempt to blacklist."""
+        test_client.app.state.auth_manager.get_url_logout.return_value = None
+
+        response = test_client.get("/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        mock_revoked_token.revoke.assert_not_called()
+
+    @patch("airflow.models.revoked_token.RevokedToken")
+    def test_logout_with_malformed_cookie_does_not_blacklist(self, mock_revoked_token, test_client):
+        """Test that logout with a malformed cookie does not raise and does not blacklist."""
+        test_client.app.state.auth_manager.get_url_logout.return_value = None
+        test_client.cookies.set(COOKIE_NAME_JWT_TOKEN, "not-a-valid-jwt")
+
+        response = test_client.get("/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        mock_revoked_token.revoke.assert_not_called()

Review Comment:
   Additionally, it would be nice to add test cases that don't mock the `airflow.models.revoked_token.RevokedToken` and check the real behavior of with DB, so we need to add `clear_db_revoke_token` in `devel-common/src/tests_common/test_utils/db.py`.
   
   



-- 
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