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 9452876d653 Add device code login for command-line clients to the
Keycloak auth manager (#77443)
9452876d653 is described below
commit 9452876d653ef12e0c2ed111c04c380e43c5c428
Author: Baptiste Gouhoury <[email protected]>
AuthorDate: Wed Nov 25 15:48:44 2026 +0100
Add device code login for command-line clients to the Keycloak auth manager
(#77443)
Browser login for airflowctl needs a browser on the machine that runs
airflowctl, because Keycloak redirects back to 127.0.0.1. Over SSH, in a
container or on a remote host there is none, and users of realms with
MFA, passkeys or an external identity provider cannot use the password
grant either, so they could not log in from the command line at all.
The device authorization grant lets them approve the login from any
device instead. It is off by default because a device code can be sent
to someone else to approve, which makes it a phishing vector.
---
.../keycloak/docs/auth-manager/manage/login.rst | 2 +-
providers/keycloak/docs/auth-manager/token.rst | 34 ++++-
providers/keycloak/provider.yaml | 10 ++
.../providers/keycloak/auth_manager/constants.py | 3 +
.../keycloak/auth_manager/datamodels/token.py | 27 +++-
.../keycloak/auth_manager/keycloak_auth_manager.py | 27 ++--
.../v2-keycloak-auth-manager-generated.yaml | 83 ++++++++++
.../keycloak/auth_manager/routes/token.py | 17 +++
.../keycloak/auth_manager/services/token.py | 67 +++++++++
.../providers/keycloak/get_provider_info.py | 7 +
.../keycloak/auth_manager/routes/test_token.py | 51 +++++++
.../keycloak/auth_manager/services/test_token.py | 167 +++++++++++++++++++++
.../auth_manager/test_keycloak_auth_manager.py | 46 +++++-
13 files changed, 523 insertions(+), 18 deletions(-)
diff --git a/providers/keycloak/docs/auth-manager/manage/login.rst
b/providers/keycloak/docs/auth-manager/manage/login.rst
index 42e622edbb4..9d7140c92d6 100644
--- a/providers/keycloak/docs/auth-manager/manage/login.rst
+++ b/providers/keycloak/docs/auth-manager/manage/login.rst
@@ -53,7 +53,7 @@ Login settings (After Client is Created)
* - Service accounts roles
- ON (by default if configuration overridden from Keycloak)
* - OAuth 2.0 Device Authorization Grant
- - OFF
+ - OFF (ON if ``cli_device_code_enabled`` is set, see
:doc:`/auth-manager/token`)
* - OIDC CIBA Grant
- OFF
diff --git a/providers/keycloak/docs/auth-manager/token.rst
b/providers/keycloak/docs/auth-manager/token.rst
index d76d2d631b1..44abd81abd2 100644
--- a/providers/keycloak/docs/auth-manager/token.rst
+++ b/providers/keycloak/docs/auth-manager/token.rst
@@ -147,16 +147,19 @@ 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:
+this endpoint offers three 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.
+- **Device code login**: log in through Keycloak on another device, for
example when the client runs over SSH. 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.
+ The metadata route exists on Airflow 3.5 and later. On earlier versions,
refresh, browser and device code login
+ still work when called directly, but clients such as ``airflowctl`` cannot
discover them, so they cannot offer
+ browser or device code login.
Refresh
~~~~~~~
@@ -212,3 +215,28 @@ A login then goes like this:
Airflow refuses any challenge method other than ``S256``, and any
``redirect_uri`` that is not a loopback callback
like the one above.
+
+Device code login
+~~~~~~~~~~~~~~~~~
+
+Device code login uses the OAuth 2.0 device authorization grant (RFC 8628). To
turn it on:
+
+1. Set ``[keycloak_auth_manager] cli_device_code_enabled = True``.
+2. In the Keycloak client, turn on "OAuth 2.0 Device Authorization Grant".
+
+A login then goes like this:
+
+1. The client calls ``POST /auth/token/cli/device``, with no body, and gets
``device_code``, ``user_code``,
+ ``verification_uri``, ``verification_uri_complete``, ``expires_in`` and
``interval``.
+2. The user opens ``verification_uri`` on any device, enters ``user_code`` and
logs in to Keycloak.
+3. Every ``interval`` seconds, the client sends
``grant_type=urn:ietf:params:oauth:grant-type:device_code`` and
+ ``device_code`` to ``/auth/token/cli``, until it gets its CLI token.
+
+Until then, ``/auth/token/cli`` answers ``400`` with the RFC 8628 error code
as ``detail``:
+``authorization_pending`` while the user has not approved the login yet,
``slow_down`` when the client polls too
+often, ``access_denied`` when the user refuses it and ``expired_token`` when
the code expired. It answers ``403``
+for an unknown or already used device code, and ``503`` when Keycloak cannot
be reached.
+
+.. warning::
+ Anyone can start a device code login and send the code to someone else,
who would log them in by approving it.
+ Users should only approve codes they started themselves.
diff --git a/providers/keycloak/provider.yaml b/providers/keycloak/provider.yaml
index 22e6109dc3b..2bb9a788e29 100644
--- a/providers/keycloak/provider.yaml
+++ b/providers/keycloak/provider.yaml
@@ -108,6 +108,16 @@ config:
version_added: 0.14.0
example: ~
default: "False"
+ cli_device_code_enabled:
+ description: |
+ Let command-line clients such as ``airflowctl`` log in by entering a
code on another
+ device (OAuth 2.0 device authorization grant), for example over SSH.
Turn on
+ "OAuth 2.0 Device Authorization Grant" in 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/src/airflow/providers/keycloak/auth_manager/constants.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
index 2530e4e6257..61b472b9769 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py
@@ -32,6 +32,9 @@ CONF_REQUESTS_RETRIES_KEY = "requests_retries"
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"
+CONF_CLI_DEVICE_CODE_ENABLED_KEY = "cli_device_code_enabled"
+
+DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
# 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 6c95585e196..514734a08e5 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
@@ -27,6 +27,7 @@ from airflow.providers.keycloak.auth_manager.services.token
import (
create_jwt_federated_token,
create_token_for,
create_token_from_authorization_code,
+ create_token_from_device_code,
refresh_cli_token,
)
@@ -121,6 +122,30 @@ class TokenAuthorizationCodeBody(StrictBaseModel):
)
+class TokenDeviceCodeBody(StrictBaseModel):
+ """Device code grant serializer for post bodies, used by the device code
login of CLI clients."""
+
+ grant_type: Literal["urn:ietf:params:oauth:grant-type:device_code"]
+ device_code: str = Field()
+
+ def create_token(self, expiration_time_in_seconds: int) -> str:
+ """Create token from a device code that the user approved."""
+ return create_token_from_device_code(
+ self.device_code,
expiration_time_in_seconds=expiration_time_in_seconds
+ )
+
+
+class DeviceAuthorizationResponse(BaseModel):
+ """Device authorization response (RFC 8628 section 3.2) for the device
code login of CLI clients."""
+
+ device_code: str
+ user_code: str
+ verification_uri: str
+ verification_uri_complete: str | None = None
+ expires_in: int
+ interval: int = 5
+
+
TokenUnion = Annotated[
TokenPasswordBody | TokenClientCredentialsBody | TokenJwtFederatedBody,
Field(discriminator="grant_type"),
@@ -137,7 +162,7 @@ class TokenBody(RootModel[TokenUnion]):
TokenCliUnion = Annotated[
- TokenPasswordBody | TokenRefreshBody | TokenAuthorizationCodeBody,
+ TokenPasswordBody | TokenRefreshBody | TokenAuthorizationCodeBody |
TokenDeviceCodeBody,
Field(discriminator="grant_type"),
]
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 eb4d3e7c6fc..15fce0b8bf9 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
@@ -62,6 +62,7 @@ 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_CLI_DEVICE_CODE_ENABLED_KEY,
CONF_CLIENT_ID_KEY,
CONF_CLIENT_SECRET_KEY,
CONF_REALM_KEY,
@@ -70,6 +71,7 @@ from airflow.providers.keycloak.auth_manager.constants import
(
CONF_SECTION_NAME,
CONF_SERVER_URL_KEY,
CONF_TEAM_LEVEL_AUTHORIZATION_KEY,
+ DEVICE_CODE_GRANT_TYPE,
)
from airflow.providers.keycloak.auth_manager.resources import KeycloakResource
from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
@@ -122,6 +124,10 @@ def is_cli_authorization_code_enabled() -> bool:
return conf.getboolean(CONF_SECTION_NAME,
CONF_CLI_AUTHORIZATION_CODE_ENABLED_KEY, fallback=False)
+def is_cli_device_code_enabled() -> bool:
+ return conf.getboolean(CONF_SECTION_NAME,
CONF_CLI_DEVICE_CODE_ENABLED_KEY, fallback=False)
+
+
class KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
"""
Keycloak auth manager.
@@ -242,16 +248,17 @@ class
KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
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,
- )
+ methods = CliLoginMethods(
+ grant_types_supported=["password", "refresh_token"],
token_endpoint=token_endpoint
+ )
+ if is_cli_authorization_code_enabled():
+ methods.grant_types_supported.append("authorization_code")
+ methods.code_challenge_methods_supported = ["S256"]
+ methods.authorization_endpoint =
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/login/cli"
+ if is_cli_device_code_enabled():
+ methods.grant_types_supported.append(DEVICE_CODE_GRANT_TYPE)
+ methods.device_authorization_endpoint = f"{token_endpoint}/device"
+ return methods
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
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 1d9874e4b95..af776c99760 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
@@ -214,8 +214,72 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /auth/token/cli/device:
+ post:
+ tags:
+ - KeycloakAuthManagerToken
+ summary: Create Device Authorization Cli
+ description: Start the device code login of a command-line client.
+ operationId: create_device_authorization_cli
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeviceAuthorizationResponse'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
+ '503':
+ description: Service Unavailable
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPExceptionResponse'
components:
schemas:
+ DeviceAuthorizationResponse:
+ properties:
+ device_code:
+ type: string
+ title: Device Code
+ user_code:
+ type: string
+ title: User Code
+ verification_uri:
+ type: string
+ title: Verification Uri
+ verification_uri_complete:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Verification Uri Complete
+ expires_in:
+ type: integer
+ title: Expires In
+ interval:
+ type: integer
+ title: Interval
+ default: 5
+ type: object
+ required:
+ - device_code
+ - user_code
+ - verification_uri
+ - expires_in
+ title: DeviceAuthorizationResponse
+ description: Device authorization response (RFC 8628 section 3.2) for
the device
+ code login of CLI clients.
HTTPExceptionResponse:
properties:
detail:
@@ -283,6 +347,7 @@ components:
- $ref: '#/components/schemas/TokenPasswordBody'
- $ref: '#/components/schemas/TokenRefreshBody'
- $ref: '#/components/schemas/TokenAuthorizationCodeBody'
+ - $ref: '#/components/schemas/TokenDeviceCodeBody'
title: TokenCliBody
description: Token request body for command-line clients.
discriminator:
@@ -291,6 +356,7 @@ components:
authorization_code: '#/components/schemas/TokenAuthorizationCodeBody'
password: '#/components/schemas/TokenPasswordBody'
refresh_token: '#/components/schemas/TokenRefreshBody'
+ urn:ietf:params:oauth:grant-type:device_code:
'#/components/schemas/TokenDeviceCodeBody'
TokenClientCredentialsBody:
properties:
grant_type:
@@ -311,6 +377,23 @@ components:
- client_secret
title: TokenClientCredentialsBody
description: Client credentials grant token serializer for post bodies.
+ TokenDeviceCodeBody:
+ properties:
+ grant_type:
+ type: string
+ const: urn:ietf:params:oauth:grant-type:device_code
+ title: Grant Type
+ device_code:
+ type: string
+ title: Device Code
+ additionalProperties: false
+ type: object
+ required:
+ - grant_type
+ - device_code
+ title: TokenDeviceCodeBody
+ description: Device code grant serializer for post bodies, used by the
device
+ code login of CLI clients.
TokenJwtFederatedBody:
properties:
grant_type:
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 3cc7aec1112..d6edc954d12 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
@@ -25,10 +25,12 @@ from airflow.api_fastapi.common.router import AirflowRouter
from airflow.api_fastapi.core_api.openapi.exceptions import
create_openapi_http_exception_doc
from airflow.providers.common.compat.sdk import conf
from airflow.providers.keycloak.auth_manager.datamodels.token import (
+ DeviceAuthorizationResponse,
TokenBody,
TokenCliBody,
TokenResponse,
)
+from airflow.providers.keycloak.auth_manager.services.token import
start_device_authorization
log = logging.getLogger(__name__)
token_router = AirflowRouter(tags=["KeycloakAuthManagerToken"])
@@ -60,3 +62,18 @@ def create_token_cli(body: TokenCliBody) -> TokenResponse:
expiration_time_in_seconds=int(conf.getint("api_auth",
"jwt_cli_expiration_time"))
)
return TokenResponse(access_token=token)
+
+
+@token_router.post(
+ "/token/cli/device",
+ responses=create_openapi_http_exception_doc(
+ [
+ status.HTTP_400_BAD_REQUEST,
+ status.HTTP_500_INTERNAL_SERVER_ERROR,
+ status.HTTP_503_SERVICE_UNAVAILABLE,
+ ]
+ ),
+)
+def create_device_authorization_cli() -> DeviceAuthorizationResponse:
+ """Start the device code login of a command-line client."""
+ return
DeviceAuthorizationResponse.model_validate(start_device_authorization())
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 42eaab5fce8..0fbd07662bc 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
@@ -40,6 +40,7 @@ from airflow.providers.keycloak.auth_manager.constants import
(
CONF_REALM_KEY,
CONF_SECTION_NAME,
CONF_SERVER_URL_KEY,
+ DEVICE_CODE_GRANT_TYPE,
)
from airflow.providers.keycloak.auth_manager.exceptions import (
AuthManagerRefreshTokenExpiredException,
@@ -48,6 +49,7 @@ from airflow.providers.keycloak.auth_manager.exceptions
import (
from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import (
KeycloakAuthManager,
is_cli_authorization_code_enabled,
+ is_cli_device_code_enabled,
)
from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_2_PLUS
@@ -56,6 +58,10 @@ from airflow.providers.keycloak.version_compat import
AIRFLOW_V_3_2_PLUS
# to a non-loopback interface.
CLI_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1"})
CLI_CALLBACK_PATH = "/callback"
+# RFC 8628 section 3.5 errors that the polling client acts on, so they are
passed on as-is.
+DEVICE_CODE_CLIENT_ERRORS = frozenset(
+ {"authorization_pending", "slow_down", "access_denied", "expired_token"}
+)
log = logging.getLogger(__name__)
@@ -310,6 +316,67 @@ def create_token_from_authorization_code(
return _create_api_jwt_from_keycloak_tokens(client, tokens,
expiration_time_in_seconds)
+def _require_cli_device_code_enabled() -> None:
+ if not is_cli_device_code_enabled():
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="Device code login is not enabled for command-line clients",
+ )
+
+
+def _find_oauth_error(error: KeycloakError) -> str | None:
+ """Return the RFC 6749 ``error`` code of a Keycloak error response, or
``None``."""
+ try:
+ body = json.loads(error.response_body or b"")
+ except (TypeError, ValueError):
+ return None
+ code = body.get("error") if isinstance(body, dict) else None
+ return code if isinstance(code, str) else None
+
+
+def start_device_authorization() -> dict:
+ """Start a device code login of a command-line client and return
Keycloak's RFC 8628 response."""
+ _require_cli_device_code_enabled()
+ client = KeycloakAuthManager.get_keycloak_client()
+ try:
+ with translate_keycloak_outage():
+ return client.device(scope="openid")
+ except KeycloakError as e:
+ # Usually the Keycloak client does not have the OAuth 2.0 Device
Authorization Grant turned on.
+ log.error("Keycloak refused the device authorization request: %s",
_find_oauth_error(e) or e)
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="Keycloak refused the device authorization request",
+ )
+
+
+def create_token_from_device_code(device_code: str,
expiration_time_in_seconds: int) -> str:
+ """
+ Create a CLI token from a device code that the user approved.
+
+ While the login is not approved, this raises a ``400`` whose ``detail`` is
the RFC 8628 error code.
+ """
+ _require_cli_device_code_enabled()
+ client = KeycloakAuthManager.get_keycloak_client()
+ try:
+ with translate_keycloak_outage():
+ tokens = client.token(grant_type=DEVICE_CODE_GRANT_TYPE,
device_code=device_code, scope="openid")
+ except KeycloakError as e:
+ error = _find_oauth_error(e)
+ if error in DEVICE_CODE_CLIENT_ERRORS:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
detail=error)
+ if error == "invalid_grant":
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid device code")
+ # Not the user's fault: e.g. a wrong client secret or the device grant
turned off in Keycloak.
+ log.error("Keycloak refused the device code token request: %s", error
or e)
+ raise HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail="Keycloak refused the device code token request",
+ )
+ 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.
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 44021296b27..bd9e2e04135 100644
--- a/providers/keycloak/src/airflow/providers/keycloak/get_provider_info.py
+++ b/providers/keycloak/src/airflow/providers/keycloak/get_provider_info.py
@@ -78,6 +78,13 @@ def get_provider_info():
"example": None,
"default": "False",
},
+ "cli_device_code_enabled": {
+ "description": 'Let command-line clients such as
``airflowctl`` log in by entering a code on another\ndevice (OAuth 2.0 device
authorization grant), for example over SSH. Turn on\n"OAuth 2.0 Device
Authorization Grant" in the Keycloak client. Clients discover this\nlogin 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/tests/unit/keycloak/auth_manager/routes/test_token.py
b/providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_token.py
index 69ce4cefd6a..fbd79406fb7 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
@@ -18,6 +18,7 @@ from __future__ import annotations
from unittest.mock import patch
+import fastapi
import pytest
from airflow.api_fastapi.app import AUTH_MANAGER_FASTAPI_APP_PREFIX
@@ -219,3 +220,53 @@ class TestTokenRouter:
response = client.post(AUTH_MANAGER_FASTAPI_APP_PREFIX + "/token/cli",
json=body)
assert response.status_code == 422
+
+ @conf_vars({("api_auth", "jwt_cli_expiration_time"): "10"})
+
@patch("airflow.providers.keycloak.auth_manager.datamodels.token.create_token_from_device_code")
+ def test_create_token_cli_device_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":
"urn:ietf:params:oauth:grant-type:device_code", "device_code": "device"},
+ )
+
+ assert response.status_code == 201
+ assert response.json() == {"access_token": self.token}
+ mock_create_token.assert_called_once_with("device",
expiration_time_in_seconds=10)
+
+
@patch("airflow.providers.keycloak.auth_manager.datamodels.token.create_token_from_device_code")
+ def test_create_token_rejects_device_code_grant(self, mock_create_token,
client):
+ response = client.post(
+ AUTH_MANAGER_FASTAPI_APP_PREFIX + "/token",
+ json={"grant_type":
"urn:ietf:params:oauth:grant-type:device_code", "device_code": "device"},
+ )
+
+ assert response.status_code == 422
+ mock_create_token.assert_not_called()
+
+
@patch("airflow.providers.keycloak.auth_manager.routes.token.start_device_authorization")
+ def test_create_device_authorization_cli(self,
mock_start_device_authorization, client):
+ mock_start_device_authorization.return_value = {
+ "device_code": "device",
+ "user_code": "WDJB-MJHT",
+ "verification_uri": "https://keycloak/realms/airflow/device",
+ "verification_uri_complete":
"https://keycloak/realms/airflow/device?user_code=WDJB-MJHT",
+ "expires_in": 600,
+ "interval": 5,
+ }
+
+ response = client.post(AUTH_MANAGER_FASTAPI_APP_PREFIX +
"/token/cli/device")
+
+ assert response.status_code == 200
+ assert response.json() == mock_start_device_authorization.return_value
+
+
@patch("airflow.providers.keycloak.auth_manager.routes.token.start_device_authorization")
+ def test_create_device_authorization_cli_error(self,
mock_start_device_authorization, client):
+ mock_start_device_authorization.side_effect = fastapi.HTTPException(
+ status_code=400, detail="disabled"
+ )
+
+ response = client.post(AUTH_MANAGER_FASTAPI_APP_PREFIX +
"/token/cli/device")
+
+ assert response.status_code == 400
+ assert response.json() == {"detail": "disabled"}
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 6523177adf4..08bb510ec6f 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
@@ -32,12 +32,15 @@ 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 (
+ _find_oauth_error,
create_client_credentials_token,
create_jwt_federated_token,
create_token_for,
create_token_from_authorization_code,
+ create_token_from_device_code,
is_cli_loopback_redirect_uri,
refresh_cli_token,
+ start_device_authorization,
)
from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
@@ -919,3 +922,167 @@ class TestCliTokenService:
assert exc_info.value.status_code == expected_status
auth_manager.generate_api_jwt.assert_not_called()
+
+
+def _keycloak_oauth_error(error: str) -> KeycloakPostError:
+ return KeycloakPostError(
+ error, response_code=400, response_body=f'{{"error": "{error}",
"error_description": "x"}}'.encode()
+ )
+
+
+class TestDeviceCodeService:
+ @pytest.mark.parametrize(
+ ("error", "expected"),
+ [
+ pytest.param(_keycloak_oauth_error("slow_down"), "slow_down",
id="oauth-error"),
+ pytest.param(
+ KeycloakPostError("x", response_code=400, response_body=b"not
json"), None, id="text"
+ ),
+ pytest.param(KeycloakPostError("x", response_code=400,
response_body=b"[1]"), None, id="list"),
+ pytest.param(
+ KeycloakPostError("x", response_code=400,
response_body=b'{"error": 1}'), None, id="int"
+ ),
+ pytest.param(KeycloakConnectionError("Can't connect to server"),
None, id="no-body"),
+ ],
+ )
+ def test_find_oauth_error(self, error, expected):
+ assert _find_oauth_error(error) == expected
+
+ @conf_vars({("keycloak_auth_manager", "cli_device_code_enabled"): "True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_start_device_authorization(self, mock_get_keycloak_client):
+ mock_get_keycloak_client.return_value = Mock(spec=KeycloakOpenID)
+ mock_get_keycloak_client.return_value.device.return_value =
{"device_code": "device"}
+
+ assert start_device_authorization() == {"device_code": "device"}
+
mock_get_keycloak_client.return_value.device.assert_called_once_with(scope="openid")
+
+ @pytest.mark.parametrize(
+ ("error", "expected_status"),
+ [
+ pytest.param(_keycloak_oauth_error("unauthorized_client"), 500,
id="grant-off-in-keycloak"),
+ 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_device_code_enabled"): "True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_start_device_authorization_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.device.side_effect = error
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ start_device_authorization()
+
+ assert exc_info.value.status_code == expected_status
+
+ @pytest.mark.parametrize(
+ "call",
+ [
+ pytest.param(start_device_authorization, id="start"),
+ pytest.param(partial(create_token_from_device_code, "device", 10),
id="token"),
+ ],
+ )
+ @conf_vars({("keycloak_auth_manager", "cli_device_code_enabled"): "False"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_device_code_disabled(self, mock_get_keycloak_client, call):
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ call()
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "Device code login is not enabled for
command-line clients"
+ mock_get_keycloak_client.assert_not_called()
+
+ @conf_vars({("keycloak_auth_manager", "cli_device_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_device_code(self, mock_get_keycloak_client,
mock_get_auth_manager):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token": "access",
"refresh_token": "refresh"}
+ 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 =
"token"
+
+ assert create_token_from_device_code("device",
expiration_time_in_seconds=10) == "token"
+
+ mock_keycloak_client.token.assert_called_once_with(
+ grant_type="urn:ietf:params:oauth:grant-type:device_code",
device_code="device", scope="openid"
+ )
+ user =
mock_get_auth_manager.return_value.generate_api_jwt.call_args.args[0]
+ assert (user.get_id(), user.get_name(), user.access_token,
user.refresh_token) == (
+ "sub",
+ "username",
+ "access",
+ "refresh",
+ )
+
mock_get_auth_manager.return_value.generate_api_jwt.assert_called_once_with(
+ user, expiration_time_in_seconds=10
+ )
+
+ @pytest.mark.parametrize(
+ ("error", "expected_status", "expected_detail"),
+ [
+ pytest.param(
+ _keycloak_oauth_error("authorization_pending"), 400,
"authorization_pending", id="pending"
+ ),
+ pytest.param(_keycloak_oauth_error("slow_down"), 400, "slow_down",
id="slow-down"),
+ pytest.param(_keycloak_oauth_error("access_denied"), 400,
"access_denied", id="denied"),
+ pytest.param(_keycloak_oauth_error("expired_token"), 400,
"expired_token", id="expired"),
+ pytest.param(_keycloak_oauth_error("invalid_grant"), 403, "Invalid
device code", id="invalid"),
+ pytest.param(
+ _keycloak_oauth_error("unauthorized_client"),
+ 500,
+ "Keycloak refused the device code token request",
+ id="grant-off-in-keycloak",
+ ),
+ pytest.param(
+ KeycloakAuthenticationError("unauthorized", response_code=401),
+ 500,
+ "Keycloak refused the device code token request",
+ id="client-auth-failed",
+ ),
+ pytest.param(
+ KeycloakConnectionError("Can't connect to server"), 503,
"Keycloak is unavailable", id="down"
+ ),
+ pytest.param(
+ KeycloakPostError("Unavailable", response_code=503), 503,
"Keycloak is unavailable", id="5xx"
+ ),
+ ],
+ )
+ @conf_vars({("keycloak_auth_manager", "cli_device_code_enabled"): "True"})
+ @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_from_device_code_keycloak_error(
+ self,
+ mock_get_keycloak_client,
+ mock_get_auth_manager,
+ mock_log,
+ error,
+ expected_status,
+ expected_detail,
+ ):
+ 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_device_code("device",
expiration_time_in_seconds=10)
+
+ assert (exc_info.value.status_code, exc_info.value.detail) ==
(expected_status, expected_detail)
+ mock_get_auth_manager.return_value.generate_api_jwt.assert_not_called()
+ assert mock_log.error.called is (expected_status == 500)
+
+ @conf_vars({("keycloak_auth_manager", "cli_device_code_enabled"): "True"})
+
@patch("airflow.providers.keycloak.auth_manager.services.token.KeycloakAuthManager.get_keycloak_client")
+ def test_create_token_from_device_code_userinfo_keycloak_down(self,
mock_get_keycloak_client):
+ mock_keycloak_client = Mock(spec=KeycloakOpenID)
+ mock_keycloak_client.token.return_value = {"access_token": "access"}
+ mock_keycloak_client.userinfo.side_effect =
KeycloakConnectionError("Can't connect to server")
+ mock_get_keycloak_client.return_value = mock_keycloak_client
+
+ with pytest.raises(fastapi.exceptions.HTTPException) as exc_info:
+ create_token_from_device_code("device",
expiration_time_in_seconds=10)
+
+ assert exc_info.value.status_code == 503
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 5acf0b9347a..fed9fda71ea 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
@@ -357,9 +357,10 @@ class TestKeycloakAuthManager:
CliLoginMethods is None, reason="CLI login discovery is not available
in this Airflow"
)
@pytest.mark.parametrize(
- ("authorization_code_enabled", "expected"),
+ ("authorization_code_enabled", "device_code_enabled", "expected"),
[
(
+ "False",
"False",
{
"grant_types_supported": ["password", "refresh_token"],
@@ -371,6 +372,7 @@ class TestKeycloakAuthManager:
),
(
"True",
+ "False",
{
"grant_types_supported": ["password", "refresh_token",
"authorization_code"],
"code_challenge_methods_supported": ["S256"],
@@ -379,10 +381,48 @@ class TestKeycloakAuthManager:
"token_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli",
},
),
+ (
+ "False",
+ "True",
+ {
+ "grant_types_supported": [
+ "password",
+ "refresh_token",
+ "urn:ietf:params:oauth:grant-type:device_code",
+ ],
+ "code_challenge_methods_supported": [],
+ "authorization_endpoint": None,
+ "device_authorization_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli/device",
+ "token_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli",
+ },
+ ),
+ (
+ "True",
+ "True",
+ {
+ "grant_types_supported": [
+ "password",
+ "refresh_token",
+ "authorization_code",
+ "urn:ietf:params:oauth:grant-type:device_code",
+ ],
+ "code_challenge_methods_supported": ["S256"],
+ "authorization_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/login/cli",
+ "device_authorization_endpoint":
f"{AUTH_MANAGER_FASTAPI_APP_PREFIX}/token/cli/device",
+ "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}):
+ def test_get_cli_login_methods(
+ self, auth_manager, authorization_code_enabled, device_code_enabled,
expected
+ ):
+ with conf_vars(
+ {
+ (CONF_SECTION_NAME, "cli_authorization_code_enabled"):
authorization_code_enabled,
+ (CONF_SECTION_NAME, "cli_device_code_enabled"):
device_code_enabled,
+ }
+ ):
assert dataclasses.asdict(auth_manager.get_cli_login_methods()) ==
expected
@patch.object(KeycloakAuthManager, "_token_expired")