vincbeck commented on code in PR #76353:
URL: https://github.com/apache/airflow/pull/76353#discussion_r4591481080


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -80,8 +81,17 @@ async def dispatch(self, request: Request, call_next):
             except (
                 AuthManagerRefreshTokenExpiredException,
                 HTTPException,
-            ):
+            ) as exc:
                 new_token = ""
+                # The session ends here and the response clears the Airflow 
JWT. Hide it
+                # from the inner middlewares and the route too: resolving it 
again without
+                # the Keycloak tokens yields no user, which ``get_user`` would 
hand to the
+                # authorization checks instead of answering 401. The logout 
route then has
+                # no token left to revoke, so a JWT that was not rejected 
itself is revoked
+                # here first.
+                if not isinstance(exc.__cause__, InvalidTokenError):
+                    await self._revoke_jwt(request)

Review Comment:
   With refresh token rotation on in Keycloak ("Revoke Refresh Token"), 
parallel requests now log the user out each time the access token expires. 
Example: requests A and B arrive with the same expired access token. A 
refreshes and rotates the refresh token. B sends the old refresh token, gets 
`AuthManagerRefreshTokenExpiredException` and revokes the shared JWT. A then 
finds it revoked in `_is_jwt_still_valid` and clears all the session cookies 
instead of setting the refreshed ones. Before this PR it depended on which 
response arrived last, now it always happens. Fix: only revoke on the logout 
route, which is the case this was added for.



##########
providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py:
##########
@@ -496,3 +510,117 @@ async def test_dispatch_invalid_token_clears_root_cookie(
         response.set_cookie.assert_any_call(
             "_token", "", path="/", secure=secure, samesite="lax", 
httponly=True, max_age=0
         )
+
+
+def keycloak_access_token(*, expires_in: int) -> str:
+    """Build a JWT-shaped Keycloak access token for ``user_id``; only its 
payload is read."""
+    payload = json.dumps({"sub": "user_id", "exp": int(time.time()) + 
expires_in})
+    return 
f"header.{base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=')}.signature"
+
+
[email protected](not AIRFLOW_V_3_3_PLUS, reason="The Keycloak JWTs travel 
in their own cookies since 3.3")
+class TestKeycloakJWTMiddlewareInTheApiServer:
+    """The middlewares as the API server installs them, in front of a route 
that needs the user."""
+
+    @pytest.fixture
+    def token_validator(self):
+        token_validator = Mock(spec=JWTValidator)
+        token_validator.avalidated_claims.return_value = {"user_id": 
"user_id", "name": "name"}
+        return token_validator
+
+    @pytest.fixture
+    def revoke_token(self):
+        with patch.object(KeycloakAuthManager, "revoke_token", autospec=True) 
as revoke_token:
+            yield revoke_token
+
+    @pytest.fixture
+    def client(self, token_validator, revoke_token):
+        from airflow.api_fastapi.core_api.app import init_middlewares
+        from airflow.api_fastapi.core_api.security import get_user
+
+        with conf_vars(
+            {
+                (CONF_SECTION_NAME, CONF_CLIENT_ID_KEY): "client_id",
+                (CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY): "client_secret",
+                (CONF_SECTION_NAME, CONF_REALM_KEY): "realm",
+                (CONF_SECTION_NAME, CONF_SERVER_URL_KEY): "server_url",
+            }
+        ):
+            auth_manager = KeycloakAuthManager()
+
+        app = FastAPI()
+
+        @app.get("/user")
+        def read_user(user=Depends(get_user)):
+            return {"name": user.get_name()}
+
+        get_auth_manager = create_autospec(api_fastapi_app.get_auth_manager, 
return_value=auth_manager)
+        with (
+            patch("airflow.api_fastapi.app.get_auth_manager", 
get_auth_manager),
+            
patch("airflow.api_fastapi.auth.middlewares.refresh_token.get_auth_manager", 
get_auth_manager),
+            patch("airflow.api_fastapi.core_api.security.get_auth_manager", 
get_auth_manager),
+            
patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager", 
get_auth_manager),
+            patch.object(KeycloakAuthManager, "_get_token_validator", 
return_value=token_validator),
+            patch.object(
+                KeycloakAuthManager,
+                "refresh_tokens",
+                autospec=True,
+                side_effect=AuthManagerRefreshTokenExpiredException("Refresh 
token expired"),
+            ),
+        ):
+            init_middlewares(app)
+            yield TestClient(app)
+
+    @staticmethod
+    def cleared_jwt_cookies(response) -> list[str]:
+        return [
+            cookie
+            for cookie in response.headers.get_list("set-cookie")
+            if cookie.startswith(f"{COOKIE_NAME_JWT_TOKEN}=") and "Max-Age=0" 
in cookie
+        ]
+
+    def test_session_with_keycloak_tokens_keeps_its_cookie(self, client, 
revoke_token):
+        client.cookies.set(COOKIE_NAME_JWT_TOKEN, "token")
+        client.cookies.set(COOKIE_NAME_ACCESS_TOKEN, 
keycloak_access_token(expires_in=300))
+        client.cookies.set(COOKIE_NAME_REFRESH_TOKEN, "refresh_token")
+
+        response = client.get("/user")
+
+        assert response.status_code == 200
+        assert response.json() == {"name": "name"}
+        assert self.cleared_jwt_cookies(response) == []
+        revoke_token.assert_not_called()
+
+    def test_expired_keycloak_session_answers_401_and_clears_the_cookie(self, 
client, revoke_token):

Review Comment:
   nit: this test and 
`test_session_without_keycloak_cookies_answers_401_and_clears_the_cookie` only 
differ by the cookies, maybe use `pytest.mark.parametrize`?



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -235,6 +245,28 @@ async def _set_new_token(
             )
         return response
 
+    @staticmethod
+    async def _revoke_jwt(request: Request) -> None:
+        """Revoke the Airflow JWT sent with the request, where Airflow can 
revoke tokens (3.2+)."""
+        revoke_token = getattr(get_auth_manager(), "revoke_token", None)
+        if revoke_token is not None:
+            # Validates the token and writes to the database: keep it off the 
event loop.
+            await run_in_threadpool(revoke_token, 
request.cookies[COOKIE_NAME_JWT_TOKEN])

Review Comment:
   nit: this middleware is only installed on Airflow 3.3+ 
(`get_fastapi_middlewares`), where `revoke_token` always exists, so no need for 
the `getattr`
   
   ```suggestion
           """Revoke the Airflow JWT sent with the request."""
           # Validates the token and writes to the database: keep it off the 
event loop.
           await run_in_threadpool(get_auth_manager().revoke_token, 
request.cookies[COOKIE_NAME_JWT_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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to