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


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py:
##########
@@ -34,45 +40,117 @@
     CONF_SECTION_NAME,
     CONF_SERVER_URL_KEY,
 )
-from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import 
KeycloakAuthManager
+from airflow.providers.keycloak.auth_manager.exceptions import 
AuthManagerRefreshTokenExpiredException
+from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import (
+    KeycloakAuthManager,
+    is_cli_authorization_code_enabled,
+)
 from airflow.providers.keycloak.auth_manager.user import 
KeycloakAuthManagerUser
+from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_2_PLUS
 
+# RFC 8252 section 7.3 loopback redirects. ``localhost`` is left out because 
it can resolve
+# to a non-loopback interface.
+CLI_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1"})
+CLI_CALLBACK_PATH = "/callback"
 
-@cache
-def _get_jwks_client(issuer: str) -> PyJWKClient:
-    """Return the cached JWK client for a Keycloak realm issuer."""
-    return PyJWKClient(f"{issuer}/protocol/openid-connect/certs")
 
+def build_keycloak_unavailable_error() -> HTTPException:
+    return HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, 
detail="Keycloak is unavailable")
+
+
+def is_keycloak_outage(error: KeycloakError) -> bool:
+    """Return whether ``error`` means Keycloak could not be reached or failed 
on its side."""
+    return isinstance(error, KeycloakConnectionError) or (error.response_code 
or 0) >= 500
 
-def create_token_for(
-    username: str,
-    password: str,
-    expiration_time_in_seconds: int = conf.getint("api_auth", 
"jwt_expiration_time"),
-) -> str:
-    client = KeycloakAuthManager.get_keycloak_client()
 
+@contextmanager
+def translate_keycloak_outage() -> Iterator[None]:
+    """Raise a ``503`` instead of a Keycloak error that 
:func:`is_keycloak_outage` matches."""
     try:
-        tokens = client.token(username, password)
-    except KeycloakAuthenticationError:
-        raise HTTPException(
-            status_code=status.HTTP_403_FORBIDDEN,
-            detail="Invalid credentials",
-        )
+        yield
+    except KeycloakError as e:
+        if is_keycloak_outage(e):
+            raise build_keycloak_unavailable_error() from e

Review Comment:
   nit: maybe log the Keycloak error before raising the 503? Otherwise a 
Keycloak that keeps answering 500 (bad config, DB down) leaves nothing in the 
API server logs.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -276,7 +300,7 @@ def refresh_tokens(self, *, user: KeycloakAuthManagerUser) 
-> dict[str, str]:
             except ImportError:
                 return {}
             else:
-                raise AuthManagerRefreshTokenExpiredException(exc)
+                raise AuthManagerRefreshTokenExpiredException(exc) from exc

Review Comment:
   Why not handle it in `refresh_tokens` directly? Re-raise the 
`KeycloakPostError` when `is_keycloak_outage(exc)` and only wrap the 4xx ones. 
Today a Keycloak 5xx during a refresh still logs out browser users (the 
middleware treats it as an expired session), and on Airflow < 3.1.7 the CLI 
refresh still gets a 403 because of the `return {}` branch, while the docs now 
promise a 503. It would also remove the `__cause__` check in 
`refresh_cli_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