dabla commented on code in PR #76353:
URL: https://github.com/apache/airflow/pull/76353#discussion_r4591649114
##########
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:
You're right, thanks. `refresh_tokens` reports a rotated-out refresh token
the same way as an expired one, so request B revoked the JWT it shares with A,
and A then dropped its refreshed session in `_is_jwt_still_valid`.
Fixed in cf8845c955: the middleware no longer revokes anything. On the core
logout route it now leaves the JWT in the request, so the route revokes it
itself as it does on `main`; that route needs no user, so the `None` user this
PR is about cannot occur there. On every other route the JWT is still hidden,
without revocation. I preferred that over revoking in the middleware on the
logout path, since the route already owns the revocation and this avoids a
second copy of it.
The middleware has to know the route for that (`LOGOUT_PATH`, matched
relative to the root path like the skipped paths of `JWTRefreshMiddleware`).
The test goes through the real `auth_router`, so it fails if the route moves.
Not changed here: with rotation on, B still clears the session cookies on
its own response, as on `main`, so the outcome still depends on which response
the browser applies last.
##########
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:
Right, core only installs it from 3.3. The method is gone with the change
above (cf8845c955), so there is nothing left to guard.
##########
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:
Done in cf8845c955: one test parametrized over the expired refresh token and
the missing Keycloak cookies, and the logout test runs over the same two cases.
--
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]