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 68d142a8439 Raise specific exceptions when Keycloak rejects an
authorization request (#77568)
68d142a8439 is described below
commit 68d142a84395ea5b7ef3f612da900fdc5dd22040
Author: Baptiste Gouhoury <[email protected]>
AuthorDate: Wed Nov 25 15:52:49 2026 +0100
Raise specific exceptions when Keycloak rejects an authorization request
(#77568)
Callers had to catch the broad AirflowException to tell a Keycloak
authorization failure apart from any other Airflow error, and could not
tell an invalid request from an unexpected Keycloak response. The new
exceptions still subclass AirflowException, so existing handlers keep
working.
Signed-off-by: Baptiste Gouhoury <[email protected]>
---
generated/known_airflow_exceptions.txt | 1 -
.../providers/keycloak/auth_manager/exceptions.py | 22 +++++++++++++++-
.../keycloak/auth_manager/keycloak_auth_manager.py | 14 ++++++----
.../auth_manager/test_keycloak_auth_manager.py | 30 +++++++++++-----------
4 files changed, 45 insertions(+), 22 deletions(-)
diff --git a/generated/known_airflow_exceptions.txt
b/generated/known_airflow_exceptions.txt
index 4fcd2656dc1..c0a75d018d5 100644
--- a/generated/known_airflow_exceptions.txt
+++ b/generated/known_airflow_exceptions.txt
@@ -329,7 +329,6 @@ providers/http/tests/unit/http/sensors/test_http.py::2
providers/imap/src/airflow/providers/imap/hooks/imap.py::1
providers/jenkins/src/airflow/providers/jenkins/operators/jenkins_job_trigger.py::4
providers/jenkins/src/airflow/providers/jenkins/sensors/jenkins.py::1
-providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py::4
providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/adx.py::4
providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/base_azure.py::1
providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/batch.py::1
diff --git
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
index 288ae61734f..0bc8166bdfa 100644
---
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
+++
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/exceptions.py
@@ -19,6 +19,8 @@ from __future__ import annotations
from keycloak import KeycloakConnectionError, KeycloakError
+from airflow.providers.common.compat.sdk import AirflowException
+
try:
from airflow.api_fastapi.auth.managers.exceptions import
AuthManagerRefreshTokenExpiredException
except ImportError:
@@ -27,9 +29,27 @@ except ImportError:
"""In case it is using a version of Airflow without
``AuthManagerRefreshTokenExpiredException``."""
+class KeycloakAuthorizationError(AirflowException):
+ """Keycloak could not answer an authorization request."""
+
+
+class KeycloakAuthorizationRequestError(KeycloakAuthorizationError):
+ """Keycloak rejected an authorization request as invalid."""
+
+
+class KeycloakUnexpectedResponseError(KeycloakAuthorizationError):
+ """Keycloak answered an authorization request with an unexpected HTTP
status."""
+
+
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"]
+__all__ = [
+ "AuthManagerRefreshTokenExpiredException",
+ "KeycloakAuthorizationError",
+ "KeycloakAuthorizationRequestError",
+ "KeycloakUnexpectedResponseError",
+ "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 15fce0b8bf9..69118a26b90 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
@@ -58,7 +58,7 @@ 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.common.compat.sdk import 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,
@@ -73,6 +73,10 @@ from airflow.providers.keycloak.auth_manager.constants
import (
CONF_TEAM_LEVEL_AUTHORIZATION_KEY,
DEVICE_CODE_GRANT_TYPE,
)
+from airflow.providers.keycloak.auth_manager.exceptions import (
+ KeycloakAuthorizationRequestError,
+ KeycloakUnexpectedResponseError,
+)
from airflow.providers.keycloak.auth_manager.resources import KeycloakResource
from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_3_PLUS
@@ -584,10 +588,10 @@ class
KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
"Keycloak authorization resource is missing; denying
access. Response: %s", resp.text
)
return False
- raise AirflowException(
+ raise KeycloakAuthorizationRequestError(
f"Request not recognized by Keycloak. {error.get('error')}.
{error.get('error_description')}"
)
- raise AirflowException(f"Unexpected error: {resp.status_code} -
{resp.text}")
+ raise KeycloakUnexpectedResponseError(f"Unexpected error:
{resp.status_code} - {resp.text}")
def filter_authorized_dag_ids(
self,
@@ -825,10 +829,10 @@ class
KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
if error.get("error") == "invalid_grant":
log.debug("Received invalid_grant from Keycloak: %s",
resp.text)
return set()
- raise AirflowException(
+ raise KeycloakAuthorizationRequestError(
f"Request not recognized by Keycloak. {error.get('error')}.
{error.get('error_description')}"
)
- raise AirflowException(f"Unexpected error: {resp.status_code} -
{resp.text}")
+ raise KeycloakUnexpectedResponseError(f"Unexpected error:
{resp.status_code} - {resp.text}")
def _get_teams(self) -> set[str]:
realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY)
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 fed9fda71ea..b00017dfd4e 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
@@ -61,11 +61,6 @@ else:
from airflow.api_fastapi.auth.managers.base_auth_manager import BaseAuthManager
from airflow.api_fastapi.common.types import MenuItem
from airflow.exceptions import AirflowProviderDeprecationWarning
-
-try:
- from airflow.providers.common.compat.sdk import AirflowException
-except ModuleNotFoundError:
- from airflow.exceptions import AirflowException
from airflow.providers.keycloak.auth_manager import cache as cache_module
from airflow.providers.keycloak.auth_manager.constants import (
CONF_CLIENT_ID_KEY,
@@ -76,6 +71,10 @@ from airflow.providers.keycloak.auth_manager.constants
import (
CONF_SERVER_URL_KEY,
CONF_TEAM_LEVEL_AUTHORIZATION_KEY,
)
+from airflow.providers.keycloak.auth_manager.exceptions import (
+ KeycloakAuthorizationRequestError,
+ KeycloakUnexpectedResponseError,
+)
from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import (
RESOURCE_ID_ATTRIBUTE_NAME,
CliLoginMethods,
@@ -652,11 +651,9 @@ class TestKeycloakAuthManager:
)
)
- with pytest.raises(AirflowException) as e:
+ with pytest.raises(KeycloakUnexpectedResponseError,
match="Unexpected error"):
getattr(auth_manager, function)(method="GET", user=user)
- assert "Unexpected error" in str(e.value)
-
@pytest.mark.skipif(not AIRFLOW_V_3_2_PLUS, reason="team_name not
supported before Airflow 3.2.0")
@conf_vars({("core", "multi_team"): "True"})
def test_is_authorized_missing_keycloak_resource(self, auth_manager, user,
caplog):
@@ -713,11 +710,12 @@ class TestKeycloakAuthManager:
)
)
- with pytest.raises(AirflowException) as e:
+ with pytest.raises(
+ KeycloakAuthorizationRequestError,
+ match="Request not recognized by Keycloak. invalid_scope.
Invalid scopes: GET",
+ ):
getattr(auth_manager, function)(method="GET", user=user)
- assert "Request not recognized by Keycloak. invalid_scope. Invalid
scopes: GET" in str(e.value)
-
@pytest.mark.parametrize(
("method", "access_entity", "details", "permission", "attributes"),
[
@@ -1163,10 +1161,12 @@ class TestKeycloakAuthManager:
assert set(result) == expected
@pytest.mark.parametrize(
- "status_code",
- [400, 500],
+ ("status_code", "expected_exception"),
+ [(400, KeycloakAuthorizationRequestError), (500,
KeycloakUnexpectedResponseError)],
)
- def test_filter_authorized_menu_items_with_failure(self, status_code,
auth_manager, user):
+ def test_filter_authorized_menu_items_with_failure(
+ self, status_code, expected_exception, auth_manager, user
+ ):
resp = Mock()
resp.status_code = status_code
resp.text = json.dumps({})
@@ -1174,7 +1174,7 @@ class TestKeycloakAuthManager:
menu_items = [MenuItem.ASSETS, MenuItem.CONNECTIONS]
- with pytest.raises(AirflowException):
+ with pytest.raises(expected_exception):
auth_manager.filter_authorized_menu_items(menu_items, user=user)
token_url = auth_manager._get_token_url("server_url", "realm")