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


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py:
##########
@@ -34,8 +38,78 @@
     CONF_SECTION_NAME,
     CONF_SERVER_URL_KEY,
 )
-from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import 
KeycloakAuthManager
+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
+
+try:
+    from airflow.api_fastapi.auth.managers.exceptions import 
AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+    class AuthManagerRefreshTokenExpiredException(Exception):  # type: 
ignore[no-redef]

Review Comment:
   nit: `routes/login.py` and `middleware.py` already define this same 
fallback. Can you move it to one place and import it from there?



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py:
##########
@@ -194,19 +248,90 @@ def create_client_credentials_token(
             detail="Client credentials authentication failed",
         )
 
-    # For client_credentials, get the service account user info
-    # The token represents the service account associated with the client
-    userinfo_raw: dict | bytes = client.userinfo(tokens["access_token"])
-    # Decode bytes to dict if necessary
-    userinfo: dict = json.loads(userinfo_raw) if isinstance(userinfo_raw, 
bytes) else userinfo_raw
-
-    user = KeycloakAuthManagerUser(
-        user_id=userinfo["sub"],
-        name=userinfo.get("preferred_username", userinfo.get("clientId", 
"service-account")),
-        access_token=tokens["access_token"],
-        refresh_token=tokens.get(
-            "refresh_token"
-        ),  # client_credentials may not return refresh_token (RFC6749 section 
4.4.3)
+    return _create_api_jwt_from_keycloak_tokens(
+        client, tokens, expiration_time_in_seconds, is_service_account=True
     )
 
-    return get_auth_manager().generate_api_jwt(user, 
expiration_time_in_seconds=expiration_time_in_seconds)
+
+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()
+    try:
+        tokens = client.token(
+            grant_type="authorization_code",
+            code=code,
+            redirect_uri=redirect_uri,
+            code_verifier=code_verifier,
+            scope="openid",
+        )
+    except KeycloakConnectionError:
+        raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, 
detail="Keycloak is unavailable")
+    except KeycloakError:
+        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid authorization code")
+
+    return _create_api_jwt_from_keycloak_tokens(client, tokens, 
expiration_time_in_seconds)
+
+
+def refresh_cli_token(token: str) -> str:
+    """
+    Create a CLI token with fresh Keycloak tokens from a CLI token that is 
still valid.
+
+    The new token expires with the old one, so refreshing never extends a CLI 
session. On Airflow 3.2+
+    the old token is revoked; earlier versions have no token revocation, so it 
stays usable until it
+    expires. Expired and revoked tokens are refused by ``get_user_from_token``.
+    """
+    auth_manager = cast("KeycloakAuthManager", get_auth_manager())
+    try:
+        user = cast("KeycloakAuthManagerUser | None", 
async_to_sync(auth_manager.get_user_from_token)(token))
+    except jwt.PyJWTError:
+        user = None
+    if not user:
+        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid token")
+    if not user.refresh_token:
+        raise HTTPException(
+            status_code=status.HTTP_400_BAD_REQUEST,
+            detail="This token cannot be refreshed because Keycloak issued it 
without a refresh token",
+        )
+
+    # get_user_from_token allows [api_auth] jwt_leeway past exp.
+    expires_at = jwt.decode(token, options={"verify_signature": False})["exp"]
+    expiration_time_in_seconds = int(expires_at - time.time())
+    if expiration_time_in_seconds <= 0:
+        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid token")
+
+    try:
+        # Airflow before 3.1.7 has no AuthManagerRefreshTokenExpiredException, 
so refresh_tokens returns {} there.
+        tokens = auth_manager.refresh_tokens(user=user)
+    except AuthManagerRefreshTokenExpiredException:
+        tokens = {}
+    except KeycloakConnectionError:
+        raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, 
detail="Keycloak is unavailable")
+    if not tokens:
+        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid token")
+
+    user.access_token = tokens["access_token"]
+    # RFC 6749 section 6: a refresh response may omit a new refresh token, and 
the old one stays valid.
+    user.refresh_token = tokens.get("refresh_token", user.refresh_token)
+    new_token = auth_manager.generate_api_jwt(user, 
expiration_time_in_seconds=expiration_time_in_seconds)

Review Comment:
   Each refresh can add a new entry to an unbounded cache. `generate_api_jwt` 
goes through `BaseAuthManager._get_token_signer`, which is `@cache`d on 
`expiration_time_in_seconds`. Here that value is the seconds left on the old 
token, so almost every refresh builds and keeps a new `JWTGenerator` (and 
reloads the signing key). With many CLI users refreshing, the cache grows up to 
one entry per second of `jwt_cli_expiration_time` until the API server 
restarts. Fix: round the remaining lifetime down, e.g. to the minute, which 
still never extends the session.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py:
##########
@@ -194,19 +248,90 @@ def create_client_credentials_token(
             detail="Client credentials authentication failed",
         )
 
-    # For client_credentials, get the service account user info
-    # The token represents the service account associated with the client
-    userinfo_raw: dict | bytes = client.userinfo(tokens["access_token"])
-    # Decode bytes to dict if necessary
-    userinfo: dict = json.loads(userinfo_raw) if isinstance(userinfo_raw, 
bytes) else userinfo_raw
-
-    user = KeycloakAuthManagerUser(
-        user_id=userinfo["sub"],
-        name=userinfo.get("preferred_username", userinfo.get("clientId", 
"service-account")),
-        access_token=tokens["access_token"],
-        refresh_token=tokens.get(
-            "refresh_token"
-        ),  # client_credentials may not return refresh_token (RFC6749 section 
4.4.3)
+    return _create_api_jwt_from_keycloak_tokens(
+        client, tokens, expiration_time_in_seconds, is_service_account=True
     )
 
-    return get_auth_manager().generate_api_jwt(user, 
expiration_time_in_seconds=expiration_time_in_seconds)
+
+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()
+    try:
+        tokens = client.token(
+            grant_type="authorization_code",
+            code=code,
+            redirect_uri=redirect_uri,
+            code_verifier=code_verifier,
+            scope="openid",
+        )
+    except KeycloakConnectionError:
+        raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, 
detail="Keycloak is unavailable")
+    except KeycloakError:
+        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid authorization code")
+
+    return _create_api_jwt_from_keycloak_tokens(client, tokens, 
expiration_time_in_seconds)

Review Comment:
   nit: only the code exchange is wrapped. If `client.userinfo` fails right 
after it (e.g. Keycloak goes down), this returns a 500 instead of the 
documented 503, and the code is already spent so the CLI can't retry.



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