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


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py:
##########
@@ -186,27 +266,102 @@ def create_client_credentials_token(
         client_secret=client_secret,
     )
 
+    with translate_keycloak_outage():
+        try:
+            tokens = client.token(grant_type="client_credentials")
+        except KeycloakAuthenticationError:
+            raise HTTPException(
+                status_code=status.HTTP_403_FORBIDDEN,
+                detail="Client credentials authentication failed",
+            )
+        return _create_api_jwt_from_keycloak_tokens(
+            client, tokens, expiration_time_in_seconds, is_service_account=True
+        )
+
+
+def create_token_from_authorization_code(
+    code: str,
+    code_verifier: str,
+    redirect_uri: str,
+    expiration_time_in_seconds: int,
+) -> str:
+    """
+    Create a CLI token from an authorization code obtained through 
``/login/cli``.
+
+    Keycloak checks ``code_verifier`` against the challenge ``/login/cli`` 
forwarded, so
+    the code is useless to anyone who intercepted it on the loopback redirect.
+    """
+    if not is_cli_authorization_code_enabled():
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail="The authorization_code grant is not enabled for 
command-line clients",
+        )
+    if not is_cli_loopback_redirect_uri(redirect_uri):
+        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, 
detail="Invalid redirect_uri")
+
+    client = KeycloakAuthManager.get_keycloak_client()
+    with translate_keycloak_outage():
+        try:
+            tokens = client.token(
+                grant_type="authorization_code",
+                code=code,
+                redirect_uri=redirect_uri,
+                code_verifier=code_verifier,
+                scope="openid",
+            )
+        except KeycloakError as e:
+            if is_keycloak_outage(e):
+                raise
+            raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid authorization code")

Review Comment:
   nit: same block as in `create_jwt_federated_token`. Maybe 
`translate_keycloak_outage` could take the 403 detail to use for the other 
Keycloak errors?



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -269,6 +294,9 @@ def refresh_tokens(self, *, user: KeycloakAuthManagerUser) 
-> dict[str, str]:
             client = self.get_keycloak_client()
             return client.refresh_token(user.refresh_token)
         except KeycloakPostError as exc:
+            if is_keycloak_outage(exc):
+                # The session may still be valid: ending it would log users 
out on a Keycloak blip.
+                raise

Review Comment:
   This still gives a 500 before Airflow 3.3. Core only calls 
`get_fastapi_middlewares` from 3.3, so on 3.1 and 3.2 `KeycloakJWTMiddleware` 
is never installed and core's `JWTRefreshMiddleware` calls `refresh_user` 
itself. It only catches `HTTPException` and 
`AuthManagerRefreshTokenExpiredException`, so on a Keycloak 5xx every browser 
request with an expired access token fails with a 500. Fix: only re-raise on 
Airflow 3.3+.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -80,6 +76,11 @@ async def dispatch(self, request: Request, call_next):
             try:
                 new_user, current_user = await self._refresh_user(request)
                 user = new_user or current_user
+            except KeycloakError as exc:
+                if not is_keycloak_outage(exc):
+                    raise
+                # Keep the cookies: the session is still valid once Keycloak 
is back.
+                raise build_keycloak_unavailable_error(exc) from exc

Review Comment:
   This also blocks logout during an outage: `/api/v2/auth/logout` gets the 503 
before the route runs, so the Airflow JWT is never revoked. Should the logout 
route go through? `_is_logout` is already there.



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