Skip to content

Commit a655527

Browse files
authored
Logout the user when the refresh token is no longer valid (#60781) (#60881)
1 parent 656a5be commit a655527

3 files changed

Lines changed: 43 additions & 16 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#
2+
# Licensed to the Apache Software Foundation (ASF) under one
3+
# or more contributor license agreements. See the NOTICE file
4+
# distributed with this work for additional information
5+
# regarding copyright ownership. The ASF licenses this file
6+
# to you under the Apache License, Version 2.0 (the
7+
# "License"); you may not use this file except in compliance
8+
# with the License. You may obtain a copy of the License at
9+
#
10+
# http://www.apache.org/licenses/LICENSE-2.0
11+
#
12+
# Unless required by applicable law or agreed to in writing,
13+
# software distributed under the License is distributed on an
14+
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
# KIND, either express or implied. See the License for the
16+
# specific language governing permissions and limitations
17+
# under the License.
18+
from __future__ import annotations
19+
20+
21+
class AuthManagerRefreshTokenExpiredException(Exception):
22+
"""Exception to throw when the user refresh token is expired."""

airflow-core/src/airflow/api_fastapi/auth/middlewares/refresh_token.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
from airflow.api_fastapi.app import get_auth_manager
2525
from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN
26+
from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException
2627
from airflow.api_fastapi.auth.managers.models.base_user import BaseUser
2728
from airflow.api_fastapi.core_api.security import resolve_user_from_token
2829
from airflow.configuration import conf
@@ -40,26 +41,34 @@ class JWTRefreshMiddleware(BaseHTTPMiddleware):
4041
"""
4142

4243
async def dispatch(self, request: Request, call_next):
43-
new_user = None
44+
new_token = None
4445
current_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
4546
try:
46-
if current_token:
47-
new_user, current_user = await self._refresh_user(current_token)
48-
if user := (new_user or current_user):
49-
request.state.user = user
47+
if current_token is not None:
48+
try:
49+
new_user, current_user = await self._refresh_user(current_token)
50+
if user := (new_user or current_user):
51+
request.state.user = user
52+
if new_user:
53+
# If we created a new user, serialize it and set it as a cookie
54+
new_token = get_auth_manager().generate_jwt(new_user)
55+
except (HTTPException, AuthManagerRefreshTokenExpiredException):
56+
# Receive a HTTPException when the Airflow token is expired
57+
# Receive a AuthManagerRefreshTokenExpiredException when the potential underlying refresh
58+
# token used by the auth manager is expired
59+
new_token = ""
5060

5161
response = await call_next(request)
5262

53-
if new_user:
54-
# If we created a new user, serialize it and set it as a cookie
55-
new_token = get_auth_manager().generate_jwt(new_user)
63+
if new_token is not None:
5664
secure = bool(conf.get("api", "ssl_cert", fallback=""))
5765
response.set_cookie(
5866
COOKIE_NAME_JWT_TOKEN,
5967
new_token,
6068
httponly=True,
6169
secure=secure,
6270
samesite="lax",
71+
max_age=0 if new_token == "" else None,
6372
)
6473
except HTTPException as exc:
6574
# If any HTTPException is raised during user resolution or refresh, return it as response
@@ -68,9 +77,5 @@ async def dispatch(self, request: Request, call_next):
6877

6978
@staticmethod
7079
async def _refresh_user(current_token: str) -> tuple[BaseUser | None, BaseUser | None]:
71-
try:
72-
user = await resolve_user_from_token(current_token)
73-
except HTTPException:
74-
return None, None
75-
80+
user = await resolve_user_from_token(current_token)
7681
return get_auth_manager().refresh_user(user=user), user

airflow-core/tests/unit/api_fastapi/auth/middlewares/test_refresh_token.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,11 +61,11 @@ async def test_dispatch_no_token(self, mock_refresh_user, middleware, mock_reque
6161
@pytest.mark.asyncio
6262
async def test_dispatch_invalid_token(self, mock_refresh_user, middleware, mock_request):
6363
mock_request.cookies = {COOKIE_NAME_JWT_TOKEN: "valid_token"}
64-
call_next = AsyncMock(return_value=Response())
64+
call_next = AsyncMock(return_value=Response(status_code=401))
6565

6666
response = await middleware.dispatch(mock_request, call_next)
67-
assert response.status_code == 403
68-
assert response.body == b'{"detail":"Invalid JWT token"}'
67+
assert response.status_code == 401
68+
assert '_token=""; HttpOnly; Max-Age=0; Path=/; SameSite=lax' in response.headers.get("set-cookie")
6969

7070
@patch("airflow.api_fastapi.auth.middlewares.refresh_token.get_auth_manager")
7171
@patch("airflow.api_fastapi.auth.middlewares.refresh_token.resolve_user_from_token")

0 commit comments

Comments
 (0)