This is an automated email from the ASF dual-hosted git repository.
vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 2cf9195e036 Add Keycloak browser login and token refresh for CLI
clients (#75913)
2cf9195e036 is described below
commit 2cf9195e036cacdd4bede10f9ecddec09d71f3c7
Author: Baptiste Gouhoury <[email protected]>
AuthorDate: Fri Nov 20 00:25:12 2026 +0100
Add Keycloak browser login and token refresh for CLI clients (#75913)
Command-line clients could only log in to the Keycloak auth manager with
a username and password, which does not work for users who sign in
through SSO or with a second factor. The CLI login discovery route lets
an auth manager advertise other login methods, and Keycloak is the first
to offer one.
The CLI token embeds a Keycloak access token that usually expires within
minutes, so a CLI session also needs a way to get fresh Keycloak tokens
without ever outliving the original CLI token.
The airflowctl side follows in a separate change.
Generated-by: Claude Code (Opus 5.5)
Signed-off-by: Baptiste Gouhoury <[email protected]>
---
.../docs/core-concepts/auth-manager/index.rst | 7 +-
providers/keycloak/README.rst | 2 +-
providers/keycloak/docs/auth-manager/token.rst | 79 ++-
providers/keycloak/docs/index.rst | 2 +-
providers/keycloak/provider.yaml | 10 +
providers/keycloak/pyproject.toml | 2 +-
.../providers/keycloak/auth_manager/constants.py | 1 +
.../keycloak/auth_manager/datamodels/token.py | 63 ++-
.../providers/keycloak/auth_manager/exceptions.py | 35 ++
.../keycloak/auth_manager/keycloak_auth_manager.py | 24 +
.../providers/keycloak/auth_manager/middleware.py | 11 +-
.../v2-keycloak-auth-manager-generated.yaml | 137 +++++-
.../keycloak/auth_manager/routes/login.py | 78 ++-
.../keycloak/auth_manager/routes/token.py | 14 +-
.../keycloak/auth_manager/services/token.py | 264 +++++++---
.../providers/keycloak/get_provider_info.py | 7 +
.../airflow/providers/keycloak/version_compat.py | 1 +
.../keycloak/auth_manager/routes/test_login.py | 70 +++
.../keycloak/auth_manager/routes/test_token.py | 76 +++
.../keycloak/auth_manager/services/test_token.py | 546 ++++++++++++++++++++-
.../unit/keycloak/auth_manager/test_exceptions.py | 42 ++
.../auth_manager/test_keycloak_auth_manager.py | 34 ++
uv.lock | 2 +-
23 files changed, 1394 insertions(+), 113 deletions(-)
diff --git a/airflow-core/docs/core-concepts/auth-manager/index.rst
b/airflow-core/docs/core-concepts/auth-manager/index.rst
index c828c5213a6..9795a6d07fb 100644
--- a/airflow-core/docs/core-concepts/auth-manager/index.rst
+++ b/airflow-core/docs/core-concepts/auth-manager/index.rst
@@ -130,9 +130,10 @@ Each advertised grant must follow the contract below, so
that clients work with
to ``token_endpoint`` returns ``201`` with ``{"access_token": ...}``, valid
for ``[api_auth] jwt_cli_expiration_time``.
* ``password``: the client sends ``username`` and ``password``. This is the
default when ``grant_type`` is omitted.
-* ``authorization_code``: the browser opens ``authorization_endpoint`` with
``redirect_uri`` (``http`` loopback
- only), ``state`` and a required ``S256`` ``code_challenge``. The client then
sends ``code``, ``code_verifier`` and
- ``redirect_uri``.
+* ``authorization_code``: the browser opens ``authorization_endpoint`` with
``redirect_uri``, ``state`` and a
+ required ``S256`` ``code_challenge``. ``redirect_uri`` must be
``http://127.0.0.1:<port>/callback`` or
+ ``http://[::1]:<port>/callback``, with any port, so admins can register one
fixed URI in the identity provider.
+ The client then sends ``code``, ``code_verifier`` and ``redirect_uri``.
* ``urn:ietf:params:oauth:grant-type:device_code``:
``device_authorization_endpoint`` returns the RFC 8628 fields.
The client polls with ``device_code``, and gets ``400`` with
``authorization_pending`` or ``slow_down`` until the
user approves.
diff --git a/providers/keycloak/README.rst b/providers/keycloak/README.rst
index d1841ae480a..5ccab5a79c4 100644
--- a/providers/keycloak/README.rst
+++ b/providers/keycloak/README.rst
@@ -55,7 +55,7 @@ PIP package Version required
========================================== ==================
``apache-airflow`` ``>=3.0.0``
``apache-airflow-providers-common-compat`` ``>=1.18.0``
-``python-keycloak`` ``>=5.0.0``
+``python-keycloak`` ``>=5.12.0``
========================================== ==================
The changelog for the provider package can be found in the
diff --git a/providers/keycloak/docs/auth-manager/token.rst
b/providers/keycloak/docs/auth-manager/token.rst
index 491797e32cc..d76d2d631b1 100644
--- a/providers/keycloak/docs/auth-manager/token.rst
+++ b/providers/keycloak/docs/auth-manager/token.rst
@@ -30,7 +30,11 @@ Several endpoints exist to create tokens depending on the
authentication method
If a user or service needs to interact with the Airflow public API, they can
create a token using their credentials.
- ``/auth/token``: Create token using username and password, client
credentials, or a Keycloak-issued JWT assertion, with a
``[config][api_auth]jwt_expiration_time`` expiration time.
-- ``/auth/token/cli``: Create token for Airflow CLI using username and
password with a ``[config][api_auth]jwt_cli_expiration_time`` expiration time.
+- ``/auth/token/cli``: Create token for command-line clients such as
``airflowctl``, with a ``[config][api_auth]jwt_cli_expiration_time`` expiration
time.
+ Besides username and password, it supports token refresh and browser login,
see :ref:`keycloak-cli-browser-login`.
+
+Both endpoints return ``503`` when Keycloak cannot be reached or answers with
a server error. The client can try again
+later.
Example
@@ -135,3 +139,76 @@ token for subsequent public API calls:
curl -s "${ENDPOINT_URL}/api/v2/dags" \
-H "Authorization: Bearer ${AIRFLOW_TOKEN}"
+
+
+.. _keycloak-cli-browser-login:
+
+Command-line clients
+''''''''''''''''''''
+
+Command-line clients such as ``airflowctl`` get their token from
``/auth/token/cli``. Besides username and password,
+this endpoint offers two more ways to get a token:
+
+- **Refresh**: get fresh Keycloak tokens without logging in again.
+- **Browser login**: log in through Keycloak in the browser. It is turned off
by default.
+
+Clients find out which of these the server offers by calling ``GET
/api/v2/auth/cli/metadata``.
+
+.. note::
+ The metadata route exists on Airflow 3.5 and later. On earlier versions,
refresh and browser login still work
+ when called directly, but clients such as ``airflowctl`` cannot discover
them, so they cannot offer browser login.
+
+Refresh
+~~~~~~~
+
+A CLI token contains a Keycloak access token, which usually expires after a
few minutes. To keep calling the API, the
+client exchanges its current CLI token for a new one:
+
+.. code-block:: bash
+
+ curl -X 'POST' \
+ "${ENDPOINT_URL}/auth/token/cli" \
+ -H 'Content-Type: application/json' \
+ -d '{"grant_type": "refresh_token", "token": "<current CLI token>"}'
+
+The new token:
+
+- never expires later than the current one, so refreshing never extends a
session.
+- lasts at most ``[api_auth] jwt_cli_expiration_time``, so refreshing a
longer-lived token from ``/auth/token``
+ shortens it.
+- can expire up to a minute earlier than the current one, because its lifetime
is rounded down to the minute. These
+ minutes add up, so frequent refreshes end the session sooner.
+
+On Airflow 3.2 and later, the current token is revoked once the new one is
issued. Airflow 3.0 and 3.1 cannot revoke
+tokens, so there the current token keeps working until it expires, even after
logging out.
+
+A refresh fails with:
+
+- ``403`` when the token is expired or revoked, or the Keycloak session has
ended. The user has to log in again.
+- ``400`` when Keycloak issued the token without a refresh token, which
happens when "Use Refresh Tokens" is turned
+ off in the Keycloak client. The user has to log in again.
+- ``503`` when Keycloak cannot be reached or answers with a server error. The
client can try again later. Before
+ Airflow 3.1.7, a server error returns ``403`` instead.
+
+Browser login
+~~~~~~~~~~~~~
+
+Browser login uses the OAuth 2.0 authorization code flow with PKCE. To turn it
on:
+
+1. Set ``[keycloak_auth_manager] cli_authorization_code_enabled = True``.
+2. In the Keycloak client, add ``http://127.0.0.1/callback`` and
``http://[::1]/callback`` to the valid redirect
+ URIs. Keycloak ignores the port of loopback redirect URIs, as RFC 8252
requires, so the client can listen on any
+ port.
+3. Leave PKCE turned off in the Keycloak client. Airflow requires it for
command-line clients, and turning it on in
+ Keycloak would break the web login, which does not use it.
+
+A login then goes like this:
+
+1. The client listens on ``http://127.0.0.1:<port>/callback`` (or ``[::1]``)
and opens ``/auth/login/cli`` in the
+ browser, with ``redirect_uri``, ``state``, ``code_challenge`` and
``code_challenge_method=S256``.
+2. The user logs in to Keycloak, which redirects the browser to the client's
callback with ``code`` and ``state``.
+3. The client sends ``grant_type=authorization_code``, ``code``,
``code_verifier`` and ``redirect_uri`` to
+ ``/auth/token/cli``, and gets its CLI token.
+
+Airflow refuses any challenge method other than ``S256``, and any
``redirect_uri`` that is not a loopback callback
+like the one above.
diff --git a/providers/keycloak/docs/index.rst
b/providers/keycloak/docs/index.rst
index 4346ec696f1..9d5c70e4dfb 100644
--- a/providers/keycloak/docs/index.rst
+++ b/providers/keycloak/docs/index.rst
@@ -102,7 +102,7 @@ PIP package Version required
========================================== ==================
``apache-airflow`` ``>=3.0.0``
``apache-airflow-providers-common-compat`` ``>=1.18.0``
-``python-keycloak`` ``>=5.0.0``
+``python-keycloak`` ``>=5.12.0``
========================================== ==================
Downloading official packages
diff --git a/providers/keycloak/provider.yaml b/providers/keycloak/provider.yaml
index b101c7798be..22e6109dc3b 100644
--- a/providers/keycloak/provider.yaml
+++ b/providers/keycloak/provider.yaml
@@ -98,6 +98,16 @@ config:
version_added: 0.0.1
example: ~
default: ~
+ cli_authorization_code_enabled:
+ description: |
+ Let command-line clients such as ``airflowctl`` log in through the
browser
+ (authorization code flow with PKCE). Add
``http://127.0.0.1/callback`` and
+ ``http://[::1]/callback`` to the valid redirect URIs of the Keycloak
client. Clients
+ discover this login on Airflow 3.5 and later.
+ type: boolean
+ version_added: 0.14.0
+ example: ~
+ default: "False"
jwt_federated_client_ids:
description: |
Comma-separated allow-list of Keycloak client ids (``azp`` claim)
permitted to
diff --git a/providers/keycloak/pyproject.toml
b/providers/keycloak/pyproject.toml
index 9948335d4ad..d6edf991d45 100644
--- a/providers/keycloak/pyproject.toml
+++ b/providers/keycloak/pyproject.toml
@@ -60,7 +60,7 @@ requires-python = ">=3.11"
dependencies = [
"apache-airflow>=3.0.0",
"apache-airflow-providers-common-compat>=1.18.0",
- "python-keycloak>=5.0.0",
+ "python-keycloak>=5.12.0",
]
[dependency-groups]
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
index 2b6dde15b6d..2530e4e6257 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
@@ -31,6 +31,7 @@ CONF_REQUESTS_RETRIES_KEY = "requests_retries"
# to use the jwt-bearer grant. Empty/unset denies all callers.
CONF_JWT_FEDERATED_CLIENT_IDS_KEY = "jwt_federated_client_ids"
CONF_TEAM_LEVEL_AUTHORIZATION_KEY = "team_level_authorization"
+CONF_CLI_AUTHORIZATION_CODE_ENABLED_KEY = "cli_authorization_code_enabled"
# Extra Cookie names
COOKIE_NAME_ACCESS_TOKEN = "_access_token"
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/datamodels/token.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/datamodels/token.py
index f61fdd3615c..6c95585e196 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/datamodels/token.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/datamodels/token.py
@@ -17,7 +17,7 @@
# under the License.
from __future__ import annotations
-from typing import Annotated, Literal
+from typing import Annotated, Any, Literal
from pydantic import Field, RootModel, model_validator
@@ -26,9 +26,18 @@ from airflow.providers.keycloak.auth_manager.services.token
import (
create_client_credentials_token,
create_jwt_federated_token,
create_token_for,
+ create_token_from_authorization_code,
+ refresh_cli_token,
)
+def default_to_password_grant(data: Any) -> Any:
+ """Add the default ``password`` grant_type, leaving a malformed body to
the union."""
+ if isinstance(data, dict) and "grant_type" not in data:
+ return {**data, "grant_type": "password"}
+ return data
+
+
class TokenResponse(BaseModel):
"""Token serializer for responses."""
@@ -82,6 +91,36 @@ class TokenJwtFederatedBody(StrictBaseModel):
)
+class TokenRefreshBody(StrictBaseModel):
+ """Refresh grant serializer for post bodies; ``token`` is the current CLI
token."""
+
+ grant_type: Literal["refresh_token"]
+ token: str = Field()
+
+ def create_token(self, expiration_time_in_seconds: int) -> str:
+ """Create token from a CLI token that is still valid, expiring no
later than it."""
+ return refresh_cli_token(self.token,
expiration_time_in_seconds=expiration_time_in_seconds)
+
+
+class TokenAuthorizationCodeBody(StrictBaseModel):
+ """Authorization code grant serializer for post bodies, used by the
browser login of CLI clients."""
+
+ grant_type: Literal["authorization_code"]
+ code: str = Field()
+ # RFC 7636 section 4.1 length bounds.
+ code_verifier: str = Field(min_length=43, max_length=128)
+ redirect_uri: str = Field()
+
+ def create_token(self, expiration_time_in_seconds: int) -> str:
+ """Create token from an authorization code and its PKCE verifier."""
+ return create_token_from_authorization_code(
+ self.code,
+ self.code_verifier,
+ self.redirect_uri,
+ expiration_time_in_seconds=expiration_time_in_seconds,
+ )
+
+
TokenUnion = Annotated[
TokenPasswordBody | TokenClientCredentialsBody | TokenJwtFederatedBody,
Field(discriminator="grant_type"),
@@ -93,8 +132,20 @@ class TokenBody(RootModel[TokenUnion]):
@model_validator(mode="before")
@classmethod
- def default_grant_type(cls, data):
- """Add default grant_type for discrimination."""
- if "grant_type" not in data:
- data["grant_type"] = "password"
- return data
+ def default_grant_type(cls, data: Any) -> Any:
+ return default_to_password_grant(data)
+
+
+TokenCliUnion = Annotated[
+ TokenPasswordBody | TokenRefreshBody | TokenAuthorizationCodeBody,
+ Field(discriminator="grant_type"),
+]
+
+
+class TokenCliBody(RootModel[TokenCliUnion]):
+ """Token request body for command-line clients."""
+
+ @model_validator(mode="before")
+ @classmethod
+ def default_grant_type(cls, data: Any) -> Any:
+ return default_to_password_grant(data)
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
new file mode 100644
index 00000000000..288ae61734f
--- /dev/null
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from keycloak import KeycloakConnectionError, KeycloakError
+
+try:
+ from airflow.api_fastapi.auth.managers.exceptions import
AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+ class AuthManagerRefreshTokenExpiredException(Exception): # type:
ignore[no-redef]
+ """In case it is using a version of Airflow without
``AuthManagerRefreshTokenExpiredException``."""
+
+
+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
+
+
+__all__ = ["AuthManagerRefreshTokenExpiredException", "is_keycloak_outage"]
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
index 524a2565ca8..fe61518335f 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
@@ -51,10 +51,17 @@ except ImportError:
from airflow.api_fastapi.auth.managers.base_auth_manager import
ResourceMethod as ExtendedResourceMethod
from airflow.api_fastapi.common.types import MenuItem
+
+try:
+ from airflow.api_fastapi.common.types import CliLoginMethods
+except ImportError:
+ # Airflow versions without CLI login discovery never call
``get_cli_login_methods``.
+ CliLoginMethods = None # type: ignore[assignment,misc]
from airflow.cli.cli_config import CLICommand
from airflow.providers.common.compat.sdk import AirflowException, conf
from airflow.providers.keycloak.auth_manager.cache import single_flight
from airflow.providers.keycloak.auth_manager.constants import (
+ CONF_CLI_AUTHORIZATION_CODE_ENABLED_KEY,
CONF_CLIENT_ID_KEY,
CONF_CLIENT_SECRET_KEY,
CONF_REALM_KEY,
@@ -109,6 +116,10 @@ TEAM_SCOPED_RESOURCES = frozenset(
)
+def is_cli_authorization_code_enabled() -> bool:
+ return conf.getboolean(CONF_SECTION_NAME,
CONF_CLI_AUTHORIZATION_CODE_ENABLED_KEY, fallback=False)
+
+
class KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
"""
Keycloak auth manager.
@@ -241,6 +252,19 @@ class
KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
base_url = conf.get("api", "base_url", fallback="/")
return urljoin(base_url, f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/logout")
+ def get_cli_login_methods(self) -> CliLoginMethods:
+ token_endpoint = f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli"
+ if not is_cli_authorization_code_enabled():
+ return CliLoginMethods(
+ grant_types_supported=["password", "refresh_token"],
token_endpoint=token_endpoint
+ )
+ return CliLoginMethods(
+ grant_types_supported=["password", "refresh_token",
"authorization_code"],
+ code_challenge_methods_supported=["S256"],
+
authorization_endpoint=f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/login/cli",
+ token_endpoint=token_endpoint,
+ )
+
def refresh_user(self, *, user: KeycloakAuthManagerUser | None) ->
KeycloakAuthManagerUser | None:
# According to RFC6749 section 4.4.3, a refresh token should not be
included when using
# the Service accounts/client_credentials flow.
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
index d81eaf2f450..b65cbe65a16 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
@@ -32,18 +32,9 @@ from airflow.providers.keycloak.auth_manager.constants
import (
COOKIE_NAME_ACCESS_TOKEN,
COOKIE_NAME_REFRESH_TOKEN,
)
+from airflow.providers.keycloak.auth_manager.exceptions import
AuthManagerRefreshTokenExpiredException
from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS
-try:
- from airflow.api_fastapi.auth.managers.exceptions import
AuthManagerRefreshTokenExpiredException
-except ImportError:
-
- class AuthManagerRefreshTokenExpiredException(Exception): # type:
ignore[no-redef]
- """In case it is using a version of Airflow without
``AuthManagerRefreshTokenExpiredException``."""
-
- pass
-
-
if AIRFLOW_V_3_1_8_PLUS:
from airflow.api_fastapi.app import get_cookie_path
else:
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/openapi/v2-keycloak-auth-manager-generated.yaml
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/openapi/v2-keycloak-auth-manager-generated.yaml
index 2158cc3a65b..1d9874e4b95 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/openapi/v2-keycloak-auth-manager-generated.yaml
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/openapi/v2-keycloak-auth-manager-generated.yaml
@@ -19,6 +19,72 @@ paths:
content:
application/json:
schema: {}
+ /auth/login/cli:
+ get:
+ tags:
+ - KeycloakAuthManagerLogin
+ summary: Login Cli
+ description: Start the browser login of a command-line client.
+ operationId: login_cli
+ parameters:
+ - name: redirect_uri
+ in: query
+ required: true
+ schema:
+ type: string
+ title: Redirect Uri
+ - name: state
+ in: query
+ required: true
+ schema:
+ type: string
+ minLength: 1
+ maxLength: 512
+ title: State
+ - name: code_challenge
+ in: query
+ required: true
+ schema:
+ type: string
+ pattern: ^[A-Za-z0-9_-]{43}$
+ title: Code Challenge
+ - name: code_challenge_method
+ in: query
+ required: true
+ schema:
+ const: S256
+ type: string
+ title: Code Challenge Method
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema: {}
+ '307':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
+ description: Temporary Redirect
+ '400':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
+ description: Bad Request
+ '503':
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
+ description: Service Unavailable
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/auth/login_callback:
get:
tags:
@@ -93,6 +159,12 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPExceptionResponse'
+ '503':
+ description: Service Unavailable
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
'422':
description: Validation Error
content:
@@ -109,7 +181,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/TokenPasswordBody'
+ $ref: '#/components/schemas/TokenCliBody'
required: true
responses:
'201':
@@ -130,6 +202,12 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPExceptionResponse'
+ '503':
+ description: Service Unavailable
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
'422':
description: Validation Error
content:
@@ -160,6 +238,33 @@ components:
title: Detail
type: object
title: HTTPValidationError
+ TokenAuthorizationCodeBody:
+ properties:
+ grant_type:
+ type: string
+ const: authorization_code
+ title: Grant Type
+ code:
+ type: string
+ title: Code
+ code_verifier:
+ type: string
+ maxLength: 128
+ minLength: 43
+ title: Code Verifier
+ redirect_uri:
+ type: string
+ title: Redirect Uri
+ additionalProperties: false
+ type: object
+ required:
+ - grant_type
+ - code
+ - code_verifier
+ - redirect_uri
+ title: TokenAuthorizationCodeBody
+ description: Authorization code grant serializer for post bodies, used
by the
+ browser login of CLI clients.
TokenBody:
oneOf:
- $ref: '#/components/schemas/TokenPasswordBody'
@@ -173,6 +278,19 @@ components:
client_credentials: '#/components/schemas/TokenClientCredentialsBody'
password: '#/components/schemas/TokenPasswordBody'
urn:ietf:params:oauth:grant-type:jwt-bearer:
'#/components/schemas/TokenJwtFederatedBody'
+ TokenCliBody:
+ oneOf:
+ - $ref: '#/components/schemas/TokenPasswordBody'
+ - $ref: '#/components/schemas/TokenRefreshBody'
+ - $ref: '#/components/schemas/TokenAuthorizationCodeBody'
+ title: TokenCliBody
+ description: Token request body for command-line clients.
+ discriminator:
+ propertyName: grant_type
+ mapping:
+ authorization_code: '#/components/schemas/TokenAuthorizationCodeBody'
+ password: '#/components/schemas/TokenPasswordBody'
+ refresh_token: '#/components/schemas/TokenRefreshBody'
TokenClientCredentialsBody:
properties:
grant_type:
@@ -237,6 +355,23 @@ components:
- password
title: TokenPasswordBody
description: Password grant token serializer for post bodies.
+ TokenRefreshBody:
+ properties:
+ grant_type:
+ type: string
+ const: refresh_token
+ title: Grant Type
+ token:
+ type: string
+ title: Token
+ additionalProperties: false
+ type: object
+ required:
+ - grant_type
+ - token
+ title: TokenRefreshBody
+ description: Refresh grant serializer for post bodies; ``token`` is the
current
+ CLI token.
TokenResponse:
properties:
access_token:
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/login.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/login.py
index 4408a12304a..78b8e400501 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/login.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/login.py
@@ -17,13 +17,12 @@
from __future__ import annotations
-import json
import logging
import secrets
-from typing import cast
+from typing import Annotated, Literal, cast
from urllib.parse import quote, urljoin
-from fastapi import Request # noqa: TC002
+from fastapi import HTTPException, Query, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse
from airflow.api_fastapi.app import AUTH_MANAGER_FASTAPI_APP_PREFIX,
get_auth_manager
@@ -39,17 +38,8 @@ if AIRFLOW_V_3_1_8_PLUS:
else:
get_cookie_path = lambda: "/"
-try:
- from airflow.api_fastapi.auth.managers.exceptions import
AuthManagerRefreshTokenExpiredException
-except ImportError:
-
- class AuthManagerRefreshTokenExpiredException(Exception): # type:
ignore[no-redef]
- """In case it is using a version of Airflow without
``AuthManagerRefreshTokenExpiredException``."""
-
- pass
-
-
from airflow.api_fastapi.common.router import AirflowRouter
+from airflow.api_fastapi.core_api.openapi.exceptions import
create_openapi_http_exception_doc
from airflow.api_fastapi.core_api.security import is_safe_url
from airflow.providers.common.compat.sdk import conf
from airflow.providers.keycloak.auth_manager.constants import (
@@ -59,8 +49,15 @@ from airflow.providers.keycloak.auth_manager.constants
import (
COOKIE_NAME_OAUTH_STATE,
COOKIE_NAME_REFRESH_TOKEN,
)
-from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import
KeycloakAuthManager
-from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
+from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import (
+ KeycloakAuthManager,
+ is_cli_authorization_code_enabled,
+)
+from airflow.providers.keycloak.auth_manager.services.token import (
+ build_user_from_userinfo,
+ is_cli_loopback_redirect_uri,
+ translate_keycloak_outage,
+)
log = logging.getLogger(__name__)
login_router = AirflowRouter(tags=["KeycloakAuthManagerLogin"])
@@ -112,6 +109,46 @@ def login(request: Request) -> RedirectResponse:
return response
+@login_router.get(
+ "/login/cli",
+ responses=create_openapi_http_exception_doc(
+ [
+ status.HTTP_307_TEMPORARY_REDIRECT,
+ status.HTTP_400_BAD_REQUEST,
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ ]
+ ),
+)
+def login_cli(
+ redirect_uri: str,
+ state: Annotated[str, Query(min_length=1, max_length=512)],
+ # An S256 challenge is 43 base64url characters. ``auth_url`` does not
encode its parameters,
+ # so nothing else may reach it.
+ code_challenge: Annotated[str, Query(pattern=r"^[A-Za-z0-9_-]{43}$")],
+ code_challenge_method: Literal["S256"],
+) -> RedirectResponse:
+ """Start the browser login of a command-line client."""
+ if not is_cli_authorization_code_enabled():
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Browser login 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()
+ # auth_url fetches Keycloak's OpenID configuration.
+ with translate_keycloak_outage():
+ auth_url = client.auth_url(
+ redirect_uri=quote(redirect_uri, safe=""),
+ scope="openid",
+ state=quote(state, safe=""),
+ code_challenge=code_challenge,
+ code_challenge_method=code_challenge_method,
+ )
+ return RedirectResponse(auth_url)
+
+
@login_router.get("/login_callback")
def login_callback(request: Request):
"""Authenticate the user."""
@@ -131,16 +168,7 @@ def login_callback(request: Request):
code=code,
redirect_uri=str(redirect_uri),
)
- 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["preferred_username"],
- access_token=tokens["access_token"],
- refresh_token=tokens.get("refresh_token"),
- )
+ user = build_user_from_userinfo(client, tokens)
token = get_auth_manager().generate_jwt(user)
request.state.jwt_token_issued = True
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/token.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/token.py
index 11b40f5c265..3cc7aec1112 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/token.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/routes/token.py
@@ -26,7 +26,7 @@ from airflow.api_fastapi.core_api.openapi.exceptions import
create_openapi_http_
from airflow.providers.common.compat.sdk import conf
from airflow.providers.keycloak.auth_manager.datamodels.token import (
TokenBody,
- TokenPasswordBody,
+ TokenCliBody,
TokenResponse,
)
@@ -37,7 +37,9 @@ token_router =
AirflowRouter(tags=["KeycloakAuthManagerToken"])
@token_router.post(
"/token",
status_code=status.HTTP_201_CREATED,
- responses=create_openapi_http_exception_doc([status.HTTP_400_BAD_REQUEST,
status.HTTP_403_FORBIDDEN]),
+ responses=create_openapi_http_exception_doc(
+ [status.HTTP_400_BAD_REQUEST, status.HTTP_403_FORBIDDEN,
status.HTTP_503_SERVICE_UNAVAILABLE]
+ ),
)
def create_token(body: TokenBody) -> TokenResponse:
token = body.root.create_token(
@@ -49,10 +51,12 @@ def create_token(body: TokenBody) -> TokenResponse:
@token_router.post(
"/token/cli",
status_code=status.HTTP_201_CREATED,
- responses=create_openapi_http_exception_doc([status.HTTP_400_BAD_REQUEST,
status.HTTP_403_FORBIDDEN]),
+ responses=create_openapi_http_exception_doc(
+ [status.HTTP_400_BAD_REQUEST, status.HTTP_403_FORBIDDEN,
status.HTTP_503_SERVICE_UNAVAILABLE]
+ ),
)
-def create_token_cli(body: TokenPasswordBody) -> TokenResponse:
- token = body.create_token(
+def create_token_cli(body: TokenCliBody) -> TokenResponse:
+ token = body.root.create_token(
expiration_time_in_seconds=int(conf.getint("api_auth",
"jwt_cli_expiration_time"))
)
return TokenResponse(access_token=token)
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py
index 2f57e080efa..42eaab5fce8 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/services/token.py
@@ -18,12 +18,19 @@
from __future__ import annotations
import json
+import logging
+import time
+from collections.abc import Iterator
+from contextlib import contextmanager
from functools import cache
+from typing import cast
+from urllib.parse import urlsplit
import jwt
+from asgiref.sync import async_to_sync
from fastapi import HTTPException, status
from jwt import PyJWKClient
-from keycloak import KeycloakAuthenticationError, KeycloakError
+from keycloak import KeycloakAuthenticationError, KeycloakError, KeycloakOpenID
from airflow.api_fastapi.app import get_auth_manager
from airflow.providers.common.compat.sdk import conf
@@ -34,45 +41,128 @@ from airflow.providers.keycloak.auth_manager.constants
import (
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,
+ is_keycloak_outage,
+)
+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")
+log = logging.getLogger(__name__)
-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()
+def build_keycloak_unavailable_error(error: Exception) -> HTTPException:
+ log.warning(
+ "Keycloak is unavailable (%s, response code %s)",
+ type(error).__name__,
+ getattr(error, "response_code", None),
+ )
+ return HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Keycloak is unavailable")
+
+
+@contextmanager
+def translate_keycloak_outage(rejected_detail: str | None = None) ->
Iterator[None]:
+ """
+ Raise a ``503`` instead of a Keycloak error that
:func:`is_keycloak_outage` matches.
+ With ``rejected_detail``, any other Keycloak error becomes a ``403`` with
that detail.
+ """
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(e) from e
+ if rejected_detail is None:
+ raise
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail=rejected_detail)
+
+def is_cli_loopback_redirect_uri(redirect_uri: str) -> bool:
+ """Return whether ``redirect_uri`` is a loopback callback a command-line
client listens on."""
+ try:
+ parts = urlsplit(redirect_uri)
+ port = parts.port
+ except ValueError:
+ return False
+ return (
+ parts.scheme == "http"
+ and parts.hostname in CLI_LOOPBACK_HOSTS
+ and port is not None
+ # Reject userinfo: ``:[email protected]:1`` still has a loopback hostname.
+ and "@" not in parts.netloc
+ and parts.path == CLI_CALLBACK_PATH
+ and not parts.query
+ and not parts.fragment
+ )
+
+
+def build_user_from_userinfo(
+ client: KeycloakOpenID, tokens: dict, *, is_service_account: bool = False
+) -> KeycloakAuthManagerUser:
+ """Build the Airflow user that Keycloak's UserInfo endpoint describes for
``tokens``."""
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(
+ # The fallback is for machine clients only: a real user must never appear
as "service-account".
+ name = (
+ userinfo.get("preferred_username", userinfo.get("clientId",
"service-account"))
+ if is_service_account
+ else userinfo["preferred_username"]
+ )
+
+ return KeycloakAuthManagerUser(
user_id=userinfo["sub"],
- name=userinfo["preferred_username"],
+ name=name,
access_token=tokens["access_token"],
+ # Absent for client_credentials and clients with "Use Refresh Tokens"
off.
refresh_token=tokens.get("refresh_token"),
)
+
+def _create_api_jwt_from_keycloak_tokens(
+ client: KeycloakOpenID,
+ tokens: dict,
+ expiration_time_in_seconds: int,
+ *,
+ is_service_account: bool = False,
+) -> str:
+ user = build_user_from_userinfo(client, tokens,
is_service_account=is_service_account)
return get_auth_manager().generate_api_jwt(user,
expiration_time_in_seconds=expiration_time_in_seconds)
+@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 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()
+
+ with translate_keycloak_outage():
+ try:
+ tokens = client.token(username, password)
+ except KeycloakAuthenticationError:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Invalid credentials",
+ )
+ return _create_api_jwt_from_keycloak_tokens(client, tokens,
expiration_time_in_seconds)
+
+
def create_jwt_federated_token(
assertion: str,
expiration_time_in_seconds: int = conf.getint("api_auth",
"jwt_expiration_time"),
@@ -111,6 +201,8 @@ def create_jwt_federated_token(
audience=client_id,
issuer=issuer,
)
+ except jwt.PyJWKClientConnectionError as e:
+ raise build_keycloak_unavailable_error(e) from e
except jwt.PyJWTError:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
@@ -129,25 +221,11 @@ def create_jwt_federated_token(
detail="Invalid Keycloak assertion",
)
- # Confirm the assertion is still live (not revoked) and fetch the same
shape of
- # user info create_client_credentials_token uses, rather than trusting the
JWT's
+ # Confirm the assertion is still live (not revoked) rather than trusting
the JWT's
# own claims alone.
client = KeycloakAuthManager.get_keycloak_client()
- try:
- userinfo_raw: dict | bytes = client.userinfo(assertion)
- except KeycloakError:
- raise HTTPException(
- status_code=status.HTTP_403_FORBIDDEN,
- detail="Invalid Keycloak assertion",
- )
- 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=assertion,
- refresh_token=None,
- )
+ with translate_keycloak_outage(rejected_detail="Invalid Keycloak
assertion"):
+ user = build_user_from_userinfo(client, {"access_token": assertion},
is_service_account=True)
return get_auth_manager().generate_api_jwt(user,
expiration_time_in_seconds=expiration_time_in_seconds)
@@ -186,27 +264,101 @@ 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(rejected_detail="Invalid authorization
code"):
+ tokens = client.token(
+ grant_type="authorization_code",
+ code=code,
+ redirect_uri=redirect_uri,
+ code_verifier=code_verifier,
+ scope="openid",
+ )
+ with translate_keycloak_outage():
+ return _create_api_jwt_from_keycloak_tokens(client, tokens,
expiration_time_in_seconds)
+
+
+def refresh_cli_token(token: str, expiration_time_in_seconds: int) -> str:
+ """
+ Create a CLI token with fresh Keycloak tokens from a CLI token that is
still valid.
+
+ The new token expires no later than the old one, so refreshing never
extends a CLI session, and
+ lasts at most ``expiration_time_in_seconds``, so a longer-lived API token
does not refresh into a
+ CLI token outliving ``[api_auth] jwt_cli_expiration_time``. 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:
- tokens = client.token(grant_type="client_credentials")
- except KeycloakAuthenticationError:
+ 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_403_FORBIDDEN,
- detail="Client credentials authentication failed",
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="This token cannot be refreshed because Keycloak issued it
without a refresh token",
)
- # 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
+ # 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 = min(int(expires_at - time.time()),
expiration_time_in_seconds)
+ # BaseAuthManager._get_token_signer caches one signer per lifetime: keep
the distinct lifetimes few.
+ if expiration_time_in_seconds > 60:
+ expiration_time_in_seconds -= expiration_time_in_seconds % 60
+ if expiration_time_in_seconds <= 0:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid token")
- 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)
- )
+ try:
+ with translate_keycloak_outage():
+ tokens = auth_manager.refresh_tokens(user=user)
+ except AuthManagerRefreshTokenExpiredException as e:
+ # refresh_tokens raises this for every Keycloak error it gets back,
outages included.
+ if isinstance(e.__context__, KeycloakError) and
is_keycloak_outage(e.__context__):
+ raise build_keycloak_unavailable_error(e.__context__) from e
+ tokens = {}
+ # Before Airflow 3.1.7 there is no
AuthManagerRefreshTokenExpiredException: refresh_tokens returns {}.
+ if not tokens:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid token")
- return get_auth_manager().generate_api_jwt(user,
expiration_time_in_seconds=expiration_time_in_seconds)
+ 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)
+ if AIRFLOW_V_3_2_PLUS:
+ # Otherwise the old token stays usable and refreshable until it
expires.
+ auth_manager.revoke_token(token)
+ return new_token
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/get_provider_info.py
b/providers/keycloak/src/airflow/providers/keycloak/get_provider_info.py
index 0deaf841bb4..44021296b27 100644
--- a/providers/keycloak/src/airflow/providers/keycloak/get_provider_info.py
+++ b/providers/keycloak/src/airflow/providers/keycloak/get_provider_info.py
@@ -71,6 +71,13 @@ def get_provider_info():
"example": None,
"default": None,
},
+ "cli_authorization_code_enabled": {
+ "description": "Let command-line clients such as
``airflowctl`` log in through the browser\n(authorization code flow with PKCE).
Add ``http://127.0.0.1/callback`` and\n``http://[::1]/callback`` to the valid
redirect URIs of the Keycloak client. Clients\ndiscover this login on Airflow
3.5 and later.\n",
+ "type": "boolean",
+ "version_added": "0.14.0",
+ "example": None,
+ "default": "False",
+ },
"jwt_federated_client_ids": {
"description": "Comma-separated allow-list of Keycloak
client ids (``azp`` claim) permitted to\nexchange a Keycloak-issued access
token for an Airflow token via
the\n``urn:ietf:params:oauth:grant-type:jwt-bearer`` grant at ``/auth/token``.
Unset\nor empty denies every caller.\n",
"type": "string",
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/version_compat.py
b/providers/keycloak/src/airflow/providers/keycloak/version_compat.py
index d87042a9edb..c1f8ab2c464 100644
--- a/providers/keycloak/src/airflow/providers/keycloak/version_compat.py
+++ b/providers/keycloak/src/airflow/providers/keycloak/version_compat.py
@@ -35,4 +35,5 @@ def get_base_airflow_version_tuple() -> tuple[int, int, int]:
AIRFLOW_V_3_1_1_PLUS = get_base_airflow_version_tuple() >= (3, 1, 1)
AIRFLOW_V_3_1_7_PLUS = get_base_airflow_version_tuple() >= (3, 1, 7)
AIRFLOW_V_3_1_8_PLUS = get_base_airflow_version_tuple() >= (3, 1, 8)
+AIRFLOW_V_3_2_PLUS = get_base_airflow_version_tuple() >= (3, 2, 0)
AIRFLOW_V_3_3_PLUS = get_base_airflow_version_tuple() >= (3, 3, 0)
diff --git
a/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_login.py
b/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_login.py
index b579e5f0cd3..95b00bbf94b 100644
--- a/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_login.py
+++ b/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_login.py
@@ -20,14 +20,84 @@ from http.cookies import SimpleCookie
from unittest.mock import ANY, Mock, patch
import pytest
+from keycloak import KeycloakConnectionError, KeycloakGetError
from airflow.api_fastapi.app import AUTH_MANAGER_FASTAPI_APP_PREFIX
from tests_common.test_utils.config import conf_vars
from tests_common.test_utils.version_compat import AIRFLOW_V_3_3_PLUS
+CLI_LOGIN_PARAMS = {
+ "redirect_uri": "http://127.0.0.1:53682/callback",
+ "state": "a&b=c",
+ "code_challenge": "c" * 43,
+ "code_challenge_method": "S256",
+}
+
class TestLoginRouter:
+ @conf_vars({("keycloak_auth_manager", "cli_authorization_code_enabled"):
"True"})
+
@patch("airflow.providers.keycloak.auth_manager.routes.login.KeycloakAuthManager.get_keycloak_client")
+ def test_login_cli(self, mock_get_keycloak_client, client):
+ mock_get_keycloak_client.return_value.auth_url.return_value =
"https://keycloak/auth"
+
+ response = client.get(
+ AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login/cli",
params=CLI_LOGIN_PARAMS, follow_redirects=False
+ )
+
+ assert response.status_code == 307
+ assert response.headers["location"] == "https://keycloak/auth"
+ mock_get_keycloak_client.return_value.auth_url.assert_called_once_with(
+ # auth_url does not encode its parameters, so the route has to.
+ redirect_uri="http%3A%2F%2F127.0.0.1%3A53682%2Fcallback",
+ scope="openid",
+ state="a%26b%3Dc",
+ code_challenge="c" * 43,
+ code_challenge_method="S256",
+ )
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(KeycloakConnectionError("Can't connect"),
id="unreachable"),
+ pytest.param(KeycloakGetError("Unavailable", response_code=503),
id="server-error"),
+ ],
+ )
+ @conf_vars({("keycloak_auth_manager", "cli_authorization_code_enabled"):
"True"})
+
@patch("airflow.providers.keycloak.auth_manager.routes.login.KeycloakAuthManager.get_keycloak_client")
+ def test_login_cli_keycloak_down(self, mock_get_keycloak_client, client,
error):
+ mock_get_keycloak_client.return_value.auth_url.side_effect = error
+
+ response = client.get(
+ AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login/cli",
params=CLI_LOGIN_PARAMS, follow_redirects=False
+ )
+
+ assert response.status_code == 503
+ assert response.json() == {"detail": "Keycloak is unavailable"}
+
+ @pytest.mark.parametrize(
+ ("enabled", "overrides", "expected_status"),
+ [
+ pytest.param("False", {}, 400, id="disabled"),
+ pytest.param(
+ "True", {"redirect_uri": "https://evil.example.com/callback"},
400, id="not-loopback"
+ ),
+ pytest.param("True", {"code_challenge_method": "plain"}, 422,
id="plain-challenge"),
+ pytest.param("True", {"code_challenge": "c" * 42 + "&"}, 422,
id="challenge-injection"),
+ pytest.param("True", {"code_challenge": None}, 422,
id="missing-challenge"),
+ ],
+ )
+
@patch("airflow.providers.keycloak.auth_manager.routes.login.KeycloakAuthManager.get_keycloak_client")
+ def test_login_cli_rejected(self, mock_get_keycloak_client, client,
enabled, overrides, expected_status):
+ params = {k: v for k, v in {**CLI_LOGIN_PARAMS, **overrides}.items()
if v is not None}
+ with conf_vars({("keycloak_auth_manager",
"cli_authorization_code_enabled"): enabled}):
+ response = client.get(
+ AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login/cli", params=params,
follow_redirects=False
+ )
+
+ assert response.status_code == expected_status
+ mock_get_keycloak_client.assert_not_called()
+
@patch("airflow.providers.keycloak.auth_manager.routes.login.KeycloakAuthManager.get_keycloak_client")
def test_login(self, mock_get_keycloak_client, client):
redirect_url = "redirect_url"
diff --git
a/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_token.py
b/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_token.py
index d7903ca4879..69ce4cefd6a 100644
--- a/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_token.py
+++ b/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_token.py
@@ -126,6 +126,10 @@ class TestTokenRouter:
{"grant_type": "client_credentials", "username": "username",
"client_secret": "client_secret"},
{"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"},
{"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"username": "username"},
+ # A body that is valid JSON but not an object reaches the
grant_type default
+ "username",
+ ["username"],
+ 1,
],
)
@conf_vars(
@@ -143,3 +147,75 @@ class TestTokenRouter:
assert response.status_code == 422
mock_create_client_credentials_token.assert_not_called()
+
+ @conf_vars({("api_auth", "jwt_cli_expiration_time"): "10"})
+
@patch("airflow.providers.keycloak.auth_manager.datamodels.token.refresh_cli_token")
+ def test_create_token_cli_refresh_grant(self, mock_refresh_cli_token,
client):
+ mock_refresh_cli_token.return_value = self.token
+ response = client.post(
+ AUTH_MANAGER_FASTAPI_APP_PREFIX + "/token/cli",
+ json={"grant_type": "refresh_token", "token": "old"},
+ )
+
+ assert response.status_code == 201
+ assert response.json() == {"access_token": self.token}
+ mock_refresh_cli_token.assert_called_once_with("old",
expiration_time_in_seconds=10)
+
+ @conf_vars({("api_auth", "jwt_cli_expiration_time"): "10"})
+
@patch("airflow.providers.keycloak.auth_manager.datamodels.token.create_token_from_authorization_code")
+ def test_create_token_cli_authorization_code_grant(self,
mock_create_token, client):
+ mock_create_token.return_value = self.token
+ response = client.post(
+ AUTH_MANAGER_FASTAPI_APP_PREFIX + "/token/cli",
+ json={
+ "grant_type": "authorization_code",
+ "code": "code",
+ "code_verifier": "v" * 43,
+ "redirect_uri": "http://127.0.0.1:53682/callback",
+ },
+ )
+
+ assert response.status_code == 201
+ assert response.json() == {"access_token": self.token}
+ mock_create_token.assert_called_once_with(
+ "code", "v" * 43, "http://127.0.0.1:53682/callback",
expiration_time_in_seconds=10
+ )
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ pytest.param(
+ {"grant_type": "client_credentials", "client_id": "id",
"client_secret": "secret"},
+ id="client-credentials",
+ ),
+ pytest.param(
+ {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": "assertion"},
+ id="jwt-bearer",
+ ),
+ pytest.param(
+ {
+ "grant_type": "authorization_code",
+ "code": "code",
+ "redirect_uri": "http://127.0.0.1:53682/callback",
+ },
+ id="missing-code-verifier",
+ ),
+ pytest.param(
+ {
+ "grant_type": "authorization_code",
+ "code": "code",
+ "code_verifier": "short",
+ "redirect_uri": "http://127.0.0.1:53682/callback",
+ },
+ id="short-code-verifier",
+ ),
+ # A body that is valid JSON but not an object reaches the
grant_type default
+ pytest.param("token", id="json-string"),
+ pytest.param(["token"], id="json-list"),
+ pytest.param(1, id="json-number"),
+ ],
+ )
+ def test_create_token_cli_rejects_body(self, client, body):
+ response = client.post(AUTH_MANAGER_FASTAPI_APP_PREFIX + "/token/cli",
json=body)
+
+ assert response.status_code == 422
diff --git
a/providers/keycloak/tests/unit/keycloak/auth_manager/services/test_token.py
b/providers/keycloak/tests/unit/keycloak/auth_manager/services/test_token.py
index ada21b9b8db..6523177adf4 100644
--- a/providers/keycloak/tests/unit/keycloak/auth_manager/services/test_token.py
+++ b/providers/keycloak/tests/unit/keycloak/auth_manager/services/test_token.py
@@ -16,22 +16,33 @@
# under the License.
from __future__ import annotations
+import logging
+import time
+from functools import partial
from unittest.mock import Mock, patch
import fastapi
import jwt
import pytest
-from keycloak import KeycloakAuthenticationError
-from keycloak.exceptions import KeycloakGetError
+import time_machine
+from keycloak import KeycloakAuthenticationError, KeycloakOpenID
+from keycloak.exceptions import KeycloakConnectionError, KeycloakGetError,
KeycloakPostError
from airflow.providers.common.compat.sdk import conf
+from airflow.providers.keycloak.auth_manager.exceptions import
AuthManagerRefreshTokenExpiredException
+from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import
KeycloakAuthManager
from airflow.providers.keycloak.auth_manager.services.token import (
create_client_credentials_token,
create_jwt_federated_token,
create_token_for,
+ create_token_from_authorization_code,
+ is_cli_loopback_redirect_uri,
+ refresh_cli_token,
)
+from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
from tests_common.test_utils.config import conf_vars
+from tests_common.test_utils.version_compat import AIRFLOW_V_3_1_7_PLUS
class TestTokenService:
@@ -112,6 +123,78 @@ class TestTokenService:
expiration_time_in_seconds=conf.getint("api_auth",
"jwt_cli_expiration_time"),
)
+ @pytest.mark.parametrize(
+ ("failing_call", "error"),
+ [
+ pytest.param("token", KeycloakConnectionError("Can't connect"),
id="token-unreachable"),
+ pytest.param("token", KeycloakPostError("Unavailable",
response_code=503), id="token-5xx"),
+ pytest.param("userinfo", KeycloakConnectionError("Can't connect"),
id="userinfo-unreachable"),
+ pytest.param("userinfo", KeycloakGetError("Unavailable",
response_code=502), id="userinfo-5xx"),
+ ],
+ )
+ @conf_vars({("api_auth", "jwt_expiration_time"): "10"})
+ @patch("airflow.providers.keycloak.auth_manager.services.token.log",
spec=logging.Logger)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_keycloak_down(
+ self, mock_get_keycloak_client, mock_get_auth_manager, mock_log,
failing_call, error
+ ):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token":
self.test_access_token}
+ getattr(mock_keycloak_client, failing_call).side_effect = error
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_token_for(username=self.test_username,
password=self.test_password)
+
+ assert exc_info.value.status_code == 503
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+ mock_log.warning.assert_called_once_with(
+ "Keycloak is unavailable (%s, response code %s)",
type(error).__name__, error.response_code
+ )
+
+ @conf_vars({("api_auth", "jwt_expiration_time"): "10"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_requires_preferred_username(self,
mock_get_keycloak_client, mock_get_auth_manager):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token":
self.test_access_token}
+ mock_keycloak_client.userinfo.return_value = {"sub": "sub",
"clientId": "client"}
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ with pytest.raises(KeyError, match="preferred_username"):
+ create_token_for(username=self.test_username,
password=self.test_password)
+
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("userinfo", "expected_name"),
+ [
+ pytest.param({"sub": "sub", "clientId": "client"}, "client",
id="client_id"),
+ pytest.param({"sub": "sub"}, "service-account", id="default"),
+ ],
+ )
+ @conf_vars(
+ {
+ ("api_auth", "jwt_expiration_time"): "10",
+ ("keycloak_auth_manager", "client_id"): "test_client",
+ }
+ )
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_client_credentials_name_fallback(
+ self, mock_get_keycloak_client, mock_get_auth_manager, userinfo,
expected_name
+ ):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token":
self.test_access_token}
+ mock_keycloak_client.userinfo.return_value = userinfo
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ create_client_credentials_token(client_id="test_client",
client_secret="test_secret")
+
+ user =
mock_get_auth_manager.return_value.generate_api_jwt.call_args.args[0]
+ assert user.get_name() == expected_name
+
@conf_vars(
{
("api_auth", "jwt_expiration_time"): "10",
@@ -208,6 +291,31 @@ class TestTokenService:
assert wrong_secret.value.status_code == wrong_client.value.status_code
assert wrong_secret.value.detail == wrong_client.value.detail
+ @pytest.mark.parametrize(
+ ("failing_call", "error"),
+ [
+ pytest.param("token", KeycloakConnectionError("Can't connect"),
id="token-unreachable"),
+ pytest.param("token", KeycloakPostError("Unavailable",
response_code=503), id="token-5xx"),
+ pytest.param("userinfo", KeycloakGetError("Unavailable",
response_code=502), id="userinfo-5xx"),
+ ],
+ )
+ @conf_vars({("keycloak_auth_manager", "client_id"): "airflow"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_client_credentials_keycloak_down(
+ self, mock_get_keycloak_client, mock_get_auth_manager, failing_call,
error
+ ):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token":
self.test_access_token}
+ getattr(mock_keycloak_client, failing_call).side_effect = error
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_client_credentials_token(client_id="airflow",
client_secret="secret")
+
+ assert exc_info.value.status_code == 503
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+
class TestCreateJwtFederatedToken:
token = "token"
@@ -259,6 +367,46 @@ class TestCreateJwtFederatedToken:
mock_keycloak_client.userinfo.assert_called_once_with(self.test_assertion)
mock_auth_manager.generate_api_jwt.assert_called_once()
+ @pytest.mark.parametrize(
+ ("userinfo", "expected_name"),
+ [
+ pytest.param({"sub": "sub", "clientId": "client"}, "client",
id="client_id"),
+ pytest.param({"sub": "sub"}, "service-account", id="default"),
+ ],
+ )
+ @conf_vars(
+ {
+ ("api_auth", "jwt_expiration_time"): "10",
+ ("keycloak_auth_manager", "client_id"): "airflow",
+ ("keycloak_auth_manager", "realm"): "airflow",
+ ("keycloak_auth_manager", "server_url"):
"https://keycloak.example.com",
+ ("keycloak_auth_manager", "jwt_federated_client_ids"):
"team-platform-admin-sa",
+ }
+ )
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ @patch("airflow.providers.keycloak.auth_manager.services.token.jwt.decode")
+
@patch("airflow.providers.keycloak.auth_manager.services.token._get_jwks_client")
+ def test_create_jwt_federated_token_name_fallback(
+ self,
+ mock_jwks_client_cls,
+ mock_jwt_decode,
+ mock_get_keycloak_client,
+ mock_get_auth_manager,
+ userinfo,
+ expected_name,
+ ):
+
mock_jwks_client_cls.return_value.get_signing_key_from_jwt.return_value =
Mock(key="fake-key")
+ mock_jwt_decode.return_value = {"azp": "team-platform-admin-sa",
"aud": ["airflow"]}
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.userinfo.return_value = userinfo
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ create_jwt_federated_token(assertion=self.test_assertion)
+
+ user =
mock_get_auth_manager.return_value.generate_api_jwt.call_args.args[0]
+ assert user.get_name() == expected_name
+
@conf_vars(
{
("api_auth", "jwt_expiration_time"): "10",
@@ -377,3 +525,397 @@ class TestCreateJwtFederatedToken:
create_jwt_federated_token(assertion=self.test_assertion)
assert exc_info.value.status_code == 403
+
+ @pytest.mark.parametrize(
+ "userinfo_error",
+ [
+ pytest.param(KeycloakConnectionError("Can't connect"),
id="unreachable"),
+ pytest.param(KeycloakGetError("Unavailable", response_code=503),
id="5xx"),
+ ],
+ )
+ @conf_vars(
+ {
+ ("keycloak_auth_manager", "client_id"): "airflow",
+ ("keycloak_auth_manager", "realm"): "airflow",
+ ("keycloak_auth_manager", "server_url"):
"https://keycloak.example.com",
+ ("keycloak_auth_manager", "jwt_federated_client_ids"):
"team-platform-admin-sa",
+ }
+ )
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ @patch("airflow.providers.keycloak.auth_manager.services.token.jwt.decode")
+
@patch("airflow.providers.keycloak.auth_manager.services.token._get_jwks_client")
+ def test_create_jwt_federated_token_userinfo_keycloak_down(
+ self,
+ mock_jwks_client_cls,
+ mock_jwt_decode,
+ mock_get_keycloak_client,
+ mock_get_auth_manager,
+ userinfo_error,
+ ):
+
mock_jwks_client_cls.return_value.get_signing_key_from_jwt.return_value =
Mock(key="fake-key")
+ mock_jwt_decode.return_value = {"sub": "sub", "azp":
"team-platform-admin-sa", "aud": ["airflow"]}
+ mock_get_keycloak_client.return_value = Mock(spec=KeycloakOpenID)
+ mock_get_keycloak_client.return_value.userinfo.side_effect =
userinfo_error
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_jwt_federated_token(assertion=self.test_assertion)
+
+ assert exc_info.value.status_code == 503
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+
+ @conf_vars(
+ {
+ ("keycloak_auth_manager", "client_id"): "airflow",
+ ("keycloak_auth_manager", "realm"): "airflow",
+ ("keycloak_auth_manager", "server_url"):
"https://keycloak.example.com",
+ }
+ )
+
@patch("airflow.providers.keycloak.auth_manager.services.token._get_jwks_client")
+ def test_create_jwt_federated_token_jwks_keycloak_down(self,
mock_jwks_client_cls):
+ mock_jwks_client_cls.return_value.get_signing_key_from_jwt.side_effect
= (
+ jwt.PyJWKClientConnectionError("Fail to fetch data from the url")
+ )
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_jwt_federated_token(assertion=self.test_assertion)
+
+ assert exc_info.value.status_code == 503
+
+
+class TestCliLoopbackRedirectUri:
+ @pytest.mark.parametrize(
+ ("redirect_uri", "expected"),
+ [
+ ("http://127.0.0.1:53682/callback", True),
+ ("http://[::1]:53682/callback", True),
+ ("http://127.0.0.1/callback", False),
+ ("http://localhost:53682/callback", False),
+ ("https://127.0.0.1:53682/callback", False),
+ ("http://evil.example.com:53682/callback", False),
+ ("http://[email protected]:53682/callback", False),
+ # Userinfo whose username is empty still leaves a loopback
``hostname``
+
("http://:x&code_challenge=evil&[email protected]:5/callback",
False),
+ ("http://127.0.0.1:53682/other", False),
+ ("http://127.0.0.1:53682/callback?next=x", False),
+ ("http://127.0.0.1:53682/callback#x", False),
+ ("http://127.0.0.1:99999/callback", False),
+ ],
+ )
+ def test_is_cli_loopback_redirect_uri(self, redirect_uri, expected):
+ assert is_cli_loopback_redirect_uri(redirect_uri) is expected
+
+
+CLI_EXPIRATION = 3600
+
+
+class TestCliTokenService:
+ token = "token"
+ redirect_uri = "http://127.0.0.1:53682/callback"
+ code_verifier = "v" * 43
+
+ @staticmethod
+ def cli_token(expires_in: int) -> str:
+ """Build a CLI token expiring ``expires_in`` seconds from now;
negative values are past."""
+ return jwt.encode({"exp": int(time.time()) + expires_in}, "secret",
algorithm="HS256")
+
+ @pytest.mark.parametrize(
+ ("tokens", "expected_refresh_token"),
+ [
+ pytest.param(
+ {"access_token": "access", "refresh_token": "refresh"},
"refresh", id="with_refresh"
+ ),
+ # Keycloak clients with "Use Refresh Tokens" disabled return no
refresh_token
+ pytest.param({"access_token": "access"}, None,
id="without_refresh"),
+ ],
+ )
+ @conf_vars({("keycloak_auth_manager", "cli_authorization_code_enabled"):
"True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_from_authorization_code(
+ self, mock_get_keycloak_client, mock_get_auth_manager, tokens,
expected_refresh_token
+ ):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = tokens
+ mock_keycloak_client.userinfo.return_value = {"sub": "sub",
"preferred_username": "username"}
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+ mock_get_auth_manager.return_value.generate_api_jwt.return_value =
self.token
+
+ token = create_token_from_authorization_code(
+ "code", self.code_verifier, self.redirect_uri,
expiration_time_in_seconds=10
+ )
+
+ assert token == self.token
+ mock_keycloak_client.token.assert_called_once_with(
+ grant_type="authorization_code",
+ code="code",
+ redirect_uri=self.redirect_uri,
+ code_verifier=self.code_verifier,
+ scope="openid",
+ )
+ user =
mock_get_auth_manager.return_value.generate_api_jwt.call_args.args[0]
+ assert (user.get_id(), user.access_token, user.refresh_token) == (
+ "sub",
+ "access",
+ expected_refresh_token,
+ )
+
mock_get_auth_manager.return_value.generate_api_jwt.assert_called_once_with(
+ user, expiration_time_in_seconds=10
+ )
+
+ @conf_vars({("keycloak_auth_manager", "cli_authorization_code_enabled"):
"True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_from_authorization_code_requires_preferred_username(
+ self, mock_get_keycloak_client, mock_get_auth_manager
+ ):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token": "access"}
+ mock_keycloak_client.userinfo.return_value = {"sub": "sub",
"clientId": "client"}
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ with pytest.raises(KeyError, match="preferred_username"):
+ create_token_from_authorization_code(
+ "code", self.code_verifier, self.redirect_uri,
expiration_time_in_seconds=10
+ )
+
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("enabled", "redirect_uri", "expected_detail"),
+ [
+ (
+ "False",
+ "http://127.0.0.1:53682/callback",
+ "The authorization_code grant is not enabled for command-line
clients",
+ ),
+ ("True", "https://evil.example.com/callback", "Invalid
redirect_uri"),
+ ],
+ )
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_from_authorization_code_rejected(
+ self, mock_get_keycloak_client, enabled, redirect_uri, expected_detail
+ ):
+ with conf_vars({("keycloak_auth_manager",
"cli_authorization_code_enabled"): enabled}):
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_token_from_authorization_code(
+ "code", self.code_verifier, redirect_uri,
expiration_time_in_seconds=10
+ )
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == expected_detail
+ mock_get_keycloak_client.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("error", "expected_status"),
+ [
+ pytest.param(KeycloakPostError("invalid_grant",
response_code=400), 403, id="invalid-code"),
+ pytest.param(KeycloakConnectionError("Can't connect to server"),
503, id="keycloak-down"),
+ pytest.param(KeycloakPostError("Unavailable", response_code=503),
503, id="keycloak-5xx"),
+ ],
+ )
+ @conf_vars({("keycloak_auth_manager", "cli_authorization_code_enabled"):
"True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_from_authorization_code_keycloak_error(
+ self, mock_get_keycloak_client, error, expected_status
+ ):
+ mock_get_keycloak_client.return_value = Mock(spec=KeycloakOpenID)
+ mock_get_keycloak_client.return_value.token.side_effect = error
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_token_from_authorization_code(
+ "code", self.code_verifier, self.redirect_uri,
expiration_time_in_seconds=10
+ )
+
+ assert exc_info.value.status_code == expected_status
+
+ @conf_vars({("keycloak_auth_manager", "cli_authorization_code_enabled"):
"True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ @pytest.mark.parametrize(
+ "error",
+ [
+ pytest.param(KeycloakConnectionError("Can't connect to server"),
id="unreachable"),
+ pytest.param(KeycloakGetError("Unavailable", response_code=503),
id="server-error"),
+ ],
+ )
+ def test_create_token_from_authorization_code_userinfo_keycloak_down(
+ self, mock_get_keycloak_client, mock_get_auth_manager, error
+ ):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token": "access"}
+ mock_keycloak_client.userinfo.side_effect = error
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_token_from_authorization_code(
+ "code", self.code_verifier, self.redirect_uri,
expiration_time_in_seconds=10
+ )
+
+ assert exc_info.value.status_code == 503
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+
+ @staticmethod
+ def mock_auth_manager(mock_get_auth_manager, refresh_token: str | None =
"old_refresh") -> Mock:
+ auth_manager = Mock(spec=KeycloakAuthManager)
+ # BaseAuthManager.revoke_token only exists from Airflow 3.2, so the
spec lacks it before.
+ auth_manager.revoke_token = Mock()
+ auth_manager.get_user_from_token.return_value =
KeycloakAuthManagerUser(
+ user_id="sub", name="username", access_token="old_access",
refresh_token=refresh_token
+ )
+ auth_manager.generate_api_jwt.return_value = TestCliTokenService.token
+ mock_get_auth_manager.return_value = auth_manager
+ return auth_manager
+
+
@patch("airflow.providers.keycloak.auth_manager.services.token.AIRFLOW_V_3_2_PLUS",
False)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_before_airflow_3_2_does_not_revoke(self,
mock_get_auth_manager):
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+ auth_manager.refresh_tokens.return_value = {"access_token":
"new_access"}
+
+ assert (
+ refresh_cli_token(self.cli_token(expires_in=600),
expiration_time_in_seconds=CLI_EXPIRATION)
+ == self.token
+ )
+
+ auth_manager.revoke_token.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("expires_in", "expected_expiration"),
+ [
+ pytest.param(600, 600, id="whole-minutes"),
+ pytest.param(659, 600, id="rounded-down-to-the-minute"),
+ pytest.param(59, 59, id="last-minute"),
+ pytest.param(86400, CLI_EXPIRATION, id="capped-at-cli-lifetime"),
+ ],
+ )
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.AIRFLOW_V_3_2_PLUS",
True)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_never_extends_original_expiry(
+ self, mock_get_auth_manager, expires_in, expected_expiration
+ ):
+ old_token = self.cli_token(expires_in=expires_in)
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+ auth_manager.refresh_tokens.return_value = {
+ "access_token": "new_access",
+ "refresh_token": "new_refresh",
+ }
+
+ assert refresh_cli_token(old_token,
expiration_time_in_seconds=CLI_EXPIRATION) == self.token
+
+ user = auth_manager.generate_api_jwt.call_args.args[0]
+ auth_manager.refresh_tokens.assert_called_once_with(user=user)
+ assert (user.access_token, user.refresh_token) == ("new_access",
"new_refresh")
+ auth_manager.generate_api_jwt.assert_called_once_with(
+ user, expiration_time_in_seconds=expected_expiration
+ )
+ auth_manager.revoke_token.assert_called_once_with(old_token)
+
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def
test_refresh_cli_token_keeps_refresh_token_keycloak_did_not_replace(self,
mock_get_auth_manager):
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+ auth_manager.refresh_tokens.return_value = {"access_token":
"new_access"}
+
+ assert (
+ refresh_cli_token(self.cli_token(expires_in=600),
expiration_time_in_seconds=CLI_EXPIRATION)
+ == self.token
+ )
+
+ user = auth_manager.generate_api_jwt.call_args.args[0]
+ assert (user.access_token, user.refresh_token) == ("new_access",
"old_refresh")
+
+ @pytest.mark.parametrize(
+ "get_user_from_token",
+ [
+ pytest.param({"side_effect": jwt.ExpiredSignatureError()},
id="expired"),
+ pytest.param({"side_effect": jwt.InvalidTokenError("Token has been
revoked")}, id="revoked"),
+ pytest.param({"return_value": None}, id="no-keycloak-tokens"),
+ ],
+ )
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_rejected(self, mock_get_auth_manager,
get_user_from_token):
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+ auth_manager.get_user_from_token.configure_mock(**get_user_from_token)
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ refresh_cli_token(self.token,
expiration_time_in_seconds=CLI_EXPIRATION)
+
+ assert exc_info.value.status_code == 403
+ auth_manager.refresh_tokens.assert_not_called()
+ auth_manager.revoke_token.assert_not_called()
+
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_without_refresh_token(self,
mock_get_auth_manager):
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager,
refresh_token=None)
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ refresh_cli_token(self.token,
expiration_time_in_seconds=CLI_EXPIRATION)
+
+ assert exc_info.value.status_code == 400
+ assert "without a refresh token" in exc_info.value.detail
+ auth_manager.refresh_tokens.assert_not_called()
+
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_within_leeway_of_expiry(self,
mock_get_auth_manager):
+ """A token [api_auth] jwt_leeway still accepts must not refresh into a
negative lifetime."""
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ refresh_cli_token(self.cli_token(expires_in=-5),
expiration_time_in_seconds=CLI_EXPIRATION)
+
+ assert exc_info.value.status_code == 403
+ auth_manager.refresh_tokens.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("refresh_tokens", "expected_status"),
+ [
+ pytest.param(
+ {"side_effect":
AuthManagerRefreshTokenExpiredException("invalid_grant")},
+ 403,
+ id="session-expired",
+ ),
+ # Airflow before 3.1.7 has no
AuthManagerRefreshTokenExpiredException
+ pytest.param({"return_value": {}}, 403,
id="session-expired-before-3-1-7"),
+ ],
+ )
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_keycloak_refresh_fails(
+ self, mock_get_auth_manager, refresh_tokens, expected_status
+ ):
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+ auth_manager.refresh_tokens.configure_mock(**refresh_tokens)
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ refresh_cli_token(self.cli_token(expires_in=600),
expiration_time_in_seconds=CLI_EXPIRATION)
+
+ assert exc_info.value.status_code == expected_status
+ auth_manager.generate_api_jwt.assert_not_called()
+ auth_manager.revoke_token.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("error", "expected_status"),
+ [
+ pytest.param(KeycloakPostError("invalid_grant",
response_code=400), 403, id="session-ended"),
+ pytest.param(KeycloakConnectionError("Can't connect"), 503,
id="unreachable"),
+ # Before Airflow 3.1.7, refresh_tokens returns {} for every
Keycloak error it gets back.
+ pytest.param(
+ KeycloakPostError("Down", response_code=503), 503 if
AIRFLOW_V_3_1_7_PLUS else 403, id="5xx"
+ ),
+ ],
+ )
+ @time_machine.travel("2026-01-01 00:00:00", tick=False)
+
@patch("airflow.providers.keycloak.auth_manager.services.token.get_auth_manager")
+ def test_refresh_cli_token_keycloak_error(self, mock_get_auth_manager,
error, expected_status):
+ auth_manager = self.mock_auth_manager(mock_get_auth_manager)
+
auth_manager.get_keycloak_client.return_value.refresh_token.side_effect = error
+ auth_manager.refresh_tokens =
partial(KeycloakAuthManager.refresh_tokens, auth_manager)
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ refresh_cli_token(self.cli_token(expires_in=600),
expiration_time_in_seconds=CLI_EXPIRATION)
+
+ assert exc_info.value.status_code == expected_status
+ auth_manager.generate_api_jwt.assert_not_called()
diff --git
a/providers/keycloak/tests/unit/keycloak/auth_manager/test_exceptions.py
b/providers/keycloak/tests/unit/keycloak/auth_manager/test_exceptions.py
new file mode 100644
index 00000000000..45d89daeb75
--- /dev/null
+++ b/providers/keycloak/tests/unit/keycloak/auth_manager/test_exceptions.py
@@ -0,0 +1,42 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import pytest
+from keycloak.exceptions import (
+ KeycloakAuthenticationError,
+ KeycloakConnectionError,
+ KeycloakGetError,
+ KeycloakPostError,
+)
+
+from airflow.providers.keycloak.auth_manager.exceptions import
is_keycloak_outage
+
+
[email protected](
+ ("error", "expected"),
+ [
+ pytest.param(KeycloakConnectionError("Can't connect"), True,
id="unreachable"),
+ pytest.param(KeycloakPostError("Unavailable", response_code=503),
True, id="5xx"),
+ pytest.param(KeycloakGetError("Server error", response_code=500),
True, id="500"),
+ pytest.param(KeycloakPostError("Bad request", response_code=400),
False, id="4xx"),
+ pytest.param(KeycloakAuthenticationError("Unauthorized",
response_code=401), False, id="401"),
+ pytest.param(KeycloakPostError("No code"), False,
id="no-response-code"),
+ ],
+)
+def test_is_keycloak_outage(error, expected):
+ assert is_keycloak_outage(error) is expected
diff --git
a/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
b/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
index 920bcad894a..997ade16c07 100644
---
a/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
+++
b/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
@@ -17,6 +17,7 @@
from __future__ import annotations
import base64
+import dataclasses
import json
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
@@ -77,6 +78,7 @@ from airflow.providers.keycloak.auth_manager.constants import
(
)
from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import (
RESOURCE_ID_ATTRIBUTE_NAME,
+ CliLoginMethods,
KeycloakAuthManager,
)
from airflow.providers.keycloak.auth_manager.middleware import
KeycloakJWTMiddleware
@@ -381,6 +383,38 @@ class TestKeycloakAuthManager:
result = auth_manager.get_url_logout()
assert result == f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/logout"
+ @pytest.mark.skipif(
+ CliLoginMethods is None, reason="CLI login discovery is not available
in this Airflow"
+ )
+ @pytest.mark.parametrize(
+ ("authorization_code_enabled", "expected"),
+ [
+ (
+ "False",
+ {
+ "grant_types_supported": ["password", "refresh_token"],
+ "code_challenge_methods_supported": [],
+ "authorization_endpoint": None,
+ "device_authorization_endpoint": None,
+ "token_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli",
+ },
+ ),
+ (
+ "True",
+ {
+ "grant_types_supported": ["password", "refresh_token",
"authorization_code"],
+ "code_challenge_methods_supported": ["S256"],
+ "authorization_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/login/cli",
+ "device_authorization_endpoint": None,
+ "token_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli",
+ },
+ ),
+ ],
+ )
+ def test_get_cli_login_methods(self, auth_manager,
authorization_code_enabled, expected):
+ with conf_vars({(CONF_SECTION_NAME, "cli_authorization_code_enabled"):
authorization_code_enabled}):
+ assert dataclasses.asdict(auth_manager.get_cli_login_methods()) ==
expected
+
@patch.object(KeycloakAuthManager, "_token_expired")
def test_refresh_user_not_expired(self, mock_token_expired, auth_manager):
mock_token_expired.return_value = False
diff --git a/uv.lock b/uv.lock
index e722dc60451..4df2e2a012f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -6950,7 +6950,7 @@ docs = [
requires-dist = [
{ name = "apache-airflow", editable = "." },
{ name = "apache-airflow-providers-common-compat", editable =
"providers/common/compat" },
- { name = "python-keycloak", specifier = ">=5.0.0" },
+ { name = "python-keycloak", specifier = ">=5.12.0" },
]
[package.metadata.requires-dev]