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 d4533154ab8 Add a CLI command to create the Keycloak auth manager 
roles (#77585)
d4533154ab8 is described below

commit d4533154ab8fd2808c4bac90a4cdede165835ef1
Author: Baptiste Gouhoury <[email protected]>
AuthorDate: Thu Nov 26 15:57:22 2026 +0100

    Add a CLI command to create the Keycloak auth manager roles (#77585)
    
    The permission commands build their role policies from the Viewer, User,
    Op, Admin and SuperAdmin roles, but nothing created them and the docs did
    not say they had to exist. On a fresh realm, create-permissions and
    create-all failed with a bare Keycloak error, and so did their dry run.
---
 .../docs/auth-manager/manage/permissions.rst       |  21 +++--
 .../keycloak/auth_manager/cli/commands.py          |  57 +++++++++++-
 .../airflow/providers/keycloak/cli/definition.py   |   8 +-
 .../keycloak/auth_manager/cli/test_commands.py     | 100 +++++++++++++++++++++
 .../tests/unit/keycloak/cli/test_definition.py     |   6 +-
 5 files changed, 179 insertions(+), 13 deletions(-)

diff --git a/providers/keycloak/docs/auth-manager/manage/permissions.rst 
b/providers/keycloak/docs/auth-manager/manage/permissions.rst
index c9a05b986c9..e7559d959c7 100644
--- a/providers/keycloak/docs/auth-manager/manage/permissions.rst
+++ b/providers/keycloak/docs/auth-manager/manage/permissions.rst
@@ -31,8 +31,8 @@ They can create the permissions and needed resources easily.
 
 There are two options to create the permissions:
 
-* Create all permissions (Scopes, Resources, Permissions) in one go using one 
CLI command
-* Create all permissions (Scopes, Resources, Permissions) step-by-step using 
the CLI commands
+* Create all permissions (Scopes, Resources, Roles, Permissions) in one go 
using one CLI command
+* Create all permissions (Scopes, Resources, Roles, Permissions) step-by-step 
using the CLI commands
 
 CLI commands take the following parameters:
 
@@ -53,7 +53,7 @@ One-go creation of permissions
 
 There is a single command do all the magic for you.
 
-This command will create scopes, resources and permissions in one-go.
+This command will create scopes, resources, roles and permissions in one-go.
 
 .. code-block:: bash
 
@@ -82,7 +82,18 @@ This command will create resources for certain types of 
permissions.
 
   airflow keycloak-auth-manager create-resources --teams team-a,team-b
 
-Finally, with the command below, we create the permissions using the 
previously created scopes and resources.
+This command will create the ``Viewer``, ``User``, ``Op``, ``Admin`` and 
``SuperAdmin`` roles as client
+roles of the Airflow client. A role that already exists, as a realm role or as 
a client role, is left unchanged.
+
+.. code-block:: bash
+
+  airflow keycloak-auth-manager create-roles
+
+The permissions use the realm role of that name when one exists, and the 
client role of the
+Airflow client otherwise. When both exist, the policy uses the realm role 
only, so a user that has
+only the client role does not get the permissions of that role.
+
+Finally, with the command below, we create the permissions using the 
previously created scopes, resources and roles.
 
 .. code-block:: bash
 
@@ -115,7 +126,7 @@ When using team-scoped permissions, the model is:
 * Team policies require both group membership and role membership
 * A separate ``SuperAdmin`` role can be used for global admin access across 
all teams
 
-Note: the CLI creates groups, resources, permissions, and policies, but **does 
not assign roles to users**.
+Note: the CLI creates groups, roles, resources, permissions, and policies, but 
**does not assign roles to users**.
 You must assign the appropriate Keycloak roles (Admin/Op/User/Viewer or 
SuperAdmin) to each user separately.
 In multi-team mode, the ``Admin`` role is **team-scoped** (group + role). Only 
``SuperAdmin`` grants global
 admin access across all teams.
diff --git 
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py
 
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py
index 8a9e20b9887..c0058d0f968 100644
--- 
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py
+++ 
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py
@@ -127,6 +127,17 @@ def create_resources_command(args):
     _create_resources(client, client_uuid, teams=teams, _dry_run=args.dry_run)
 
 
+@cli_utils.action_cli
+@providers_configuration_loaded
+@dry_run_message_wrap
+def create_roles_command(args):
+    """Create Keycloak auth manager roles in Keycloak."""
+    client = _get_client(args)
+    client_uuid = _get_client_uuid(args)
+
+    _create_roles(client, client_uuid, _dry_run=args.dry_run)
+
+
 @cli_utils.action_cli
 @providers_configuration_loaded
 @dry_run_message_wrap
@@ -137,6 +148,12 @@ def create_permissions_command(args):
 
     teams = _parse_teams(args.teams)
     _ensure_multi_team_enabled(teams=teams, command_name="create-permissions")
+    missing_roles = _get_roles_to_create(client, client_uuid)
+    if missing_roles:
+        raise ValueError(
+            f"Roles {', '.join(missing_roles)} not found. "
+            "Run `airflow keycloak-auth-manager create-roles` first."
+        )
     if teams:
         # Role policies are only needed for team-scoped (group+role) 
authorization.
         for role_name in TEAM_ROLE_NAMES:
@@ -161,6 +178,7 @@ def create_all_command(args):
 
     _create_scopes(client, client_uuid, _dry_run=args.dry_run)
     _create_resources(client, client_uuid, teams=teams, _dry_run=args.dry_run)
+    _create_roles(client, client_uuid, _dry_run=args.dry_run)
     _create_group_membership_mapper(client, client_uuid, _dry_run=args.dry_run)
     if teams:
         # Role policies are only needed for team-scoped (group+role) 
authorization.
@@ -365,6 +383,37 @@ def _create_scopes(client: KeycloakAdmin, client_uuid: 
str, *, _dry_run: bool =
     print("Scopes created successfully.")
 
 
+def _get_roles_to_create(client: KeycloakAdmin, client_uuid: str) -> list[str]:
+    """Get the names of the roles to be created, skipping those that exist as 
realm or client roles."""
+    existing_roles = {role["name"] for role in client.get_realm_roles()}
+    existing_roles |= {role["name"] for role in 
client.get_client_roles(client_uuid)}
+    return [
+        role_name
+        for role_name in (*TEAM_ROLE_NAMES, SUPER_ADMIN_ROLE_NAME)
+        if role_name not in existing_roles
+    ]
+
+
+def _preview_roles(client: KeycloakAdmin, client_uuid: str):
+    """Preview roles that would be created."""
+    roles = _get_roles_to_create(client, client_uuid)
+    print("Roles to be created:")
+    for role_name in roles:
+        print(f"  - {role_name}")
+    print()
+
+
+@dry_run_preview(_preview_roles)
+def _create_roles(client: KeycloakAdmin, client_uuid: str, *, _dry_run: bool = 
False):
+    """Create Keycloak client roles."""
+    roles = _get_roles_to_create(client, client_uuid)
+
+    for role_name in roles:
+        client.create_client_role(client_role_id=client_uuid, payload={"name": 
role_name}, skip_exists=True)
+
+    print("Roles created successfully.")
+
+
 def _get_resources_to_create(
     client: KeycloakAdmin,
     client_uuid: str,
@@ -1132,6 +1181,10 @@ def _ensure_role_policy(
     if _get_policy_id(client, client_uuid, policy_name, policy_type="role"):
         return
 
+    if _dry_run:
+        print(f"Would create role policy '{policy_name}'.")
+        return
+
     role_id = _get_role_id(client, client_uuid, role_name)
     payload = {
         "name": policy_name,
@@ -1141,10 +1194,6 @@ def _ensure_role_policy(
         "roles": [{"id": role_id}],
     }
 
-    if _dry_run:
-        print(f"Would create role policy '{policy_name}'.")
-        return
-
     try:
         client.create_client_authz_role_based_policy(client_id=client_uuid, 
payload=payload, skip_exists=True)
     except KeycloakError as exc:
diff --git 
a/providers/keycloak/src/airflow/providers/keycloak/cli/definition.py 
b/providers/keycloak/src/airflow/providers/keycloak/cli/definition.py
index dbeb71ca908..36b1ef818d7 100644
--- a/providers/keycloak/src/airflow/providers/keycloak/cli/definition.py
+++ b/providers/keycloak/src/airflow/providers/keycloak/cli/definition.py
@@ -86,6 +86,12 @@ KEYCLOAK_AUTH_MANAGER_COMMANDS = (
         ),
         args=(ARG_USERNAME, ARG_PASSWORD, ARG_USER_REALM, ARG_CLIENT_ID, 
ARG_TEAMS, ARG_DRY_RUN),
     ),
+    ActionCommand(
+        name="create-roles",
+        help="Create roles in Keycloak",
+        
func=lazy_load_command("airflow.providers.keycloak.auth_manager.cli.commands.create_roles_command"),
+        args=(ARG_USERNAME, ARG_PASSWORD, ARG_USER_REALM, ARG_CLIENT_ID, 
ARG_DRY_RUN),
+    ),
     ActionCommand(
         name="create-permissions",
         help="Create permissions in Keycloak",
@@ -96,7 +102,7 @@ KEYCLOAK_AUTH_MANAGER_COMMANDS = (
     ),
     ActionCommand(
         name="create-all",
-        help="Create all entities (scopes, resources and permissions) in 
Keycloak",
+        help="Create all entities (scopes, resources, roles and permissions) 
in Keycloak",
         
func=lazy_load_command("airflow.providers.keycloak.auth_manager.cli.commands.create_all_command"),
         args=(ARG_USERNAME, ARG_PASSWORD, ARG_USER_REALM, ARG_CLIENT_ID, 
ARG_TEAMS, ARG_DRY_RUN),
     ),
diff --git 
a/providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py 
b/providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py
index 3d2451f6d86..d235e98c7aa 100644
--- a/providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py
+++ b/providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py
@@ -20,6 +20,8 @@ import importlib
 from unittest.mock import Mock, call, patch
 
 import pytest
+from keycloak import KeycloakAdmin
+from keycloak.exceptions import KeycloakGetError
 
 from airflow.api_fastapi.auth.managers.models.resource_details import 
AccessView
 from airflow.api_fastapi.common.types import MenuItem
@@ -28,6 +30,7 @@ from airflow.providers.keycloak.auth_manager.cli.commands 
import (
     SUPER_ADMIN_ROLE_NAME,
     TEAM_ROLE_NAMES,
     TEAM_SCOPED_RESOURCE_NAMES,
+    _ensure_role_policy,
     _get_extended_resource_methods,
     _get_resource_methods,
     _update_admin_permission_resources,
@@ -36,6 +39,7 @@ from airflow.providers.keycloak.auth_manager.cli.commands 
import (
     create_all_command,
     create_permissions_command,
     create_resources_command,
+    create_roles_command,
     create_scopes_command,
     create_team_command,
 )
@@ -48,6 +52,7 @@ from tests_common.test_utils.version_compat import 
AIRFLOW_V_3_2_PLUS
 DAG_BUNDLES_MENU = (
     ["Dag Bundles"] if hasattr(MenuItem, "DAG_BUNDLES") and not 
hasattr(AccessView, "DAG_BUNDLES") else []
 )
+EXISTING_ROLES = [{"name": role_name} for role_name in (*TEAM_ROLE_NAMES, 
SUPER_ADMIN_ROLE_NAME)]
 EXPECTED_TEAM_MENU_RESOURCES = sorted(["Assets", "Dags", "Docs", 
*DAG_BUNDLES_MENU])
 EXPECTED_TEAM_ADMIN_MENU_RESOURCES = sorted(
     ["Assets", "Connections", "Dags", "Docs", "Pools", "Variables", "XComs", 
*DAG_BUNDLES_MENU]
@@ -227,6 +232,50 @@ class TestCommands:
         }
         assert expected_team_resources.issubset(created_resource_names)
 
+    @pytest.mark.parametrize(
+        ("dry_run", "expected_created_roles"),
+        [
+            pytest.param(False, ["User", "Op", SUPER_ADMIN_ROLE_NAME], 
id="create"),
+            pytest.param(True, [], id="dry-run"),
+        ],
+    )
+    @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
+    def test_create_roles(self, mock_get_client, dry_run, 
expected_created_roles):
+        client = Mock(spec=KeycloakAdmin)
+        mock_get_client.return_value = client
+
+        client.get_clients.return_value = [
+            {"id": "dummy-id", "clientId": "dummy-client"},
+            {"id": "test-id", "clientId": "test_client_id"},
+        ]
+        client.get_realm_roles.return_value = [{"name": "Admin"}, {"name": 
"offline_access"}]
+        client.get_client_roles.return_value = [{"name": "Viewer"}]
+
+        params = [
+            "keycloak-auth-manager",
+            "create-roles",
+            "--username",
+            "test",
+            "--password",
+            "test",
+        ]
+        if dry_run:
+            params.append("--dry-run")
+        with conf_vars(
+            {
+                ("keycloak_auth_manager", "client_id"): "test_client_id",
+            }
+        ):
+            create_roles_command(self.arg_parser.parse_args(params))
+
+        client.get_clients.assert_called_once_with()
+        client.get_realm_roles.assert_called_once_with()
+        client.get_client_roles.assert_called_once_with("test-id")
+        assert client.create_client_role.call_args_list == [
+            call(client_role_id="test-id", payload={"name": role_name}, 
skip_exists=True)
+            for role_name in expected_created_roles
+        ]
+
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._attach_default_role_permissions")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._ensure_default_role_policies")
     @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
@@ -238,6 +287,8 @@ class TestCommands:
     ):
         client = Mock()
         mock_get_client.return_value = client
+        client.get_realm_roles.return_value = EXISTING_ROLES
+        client.get_client_roles.return_value = []
         scopes = [{"id": "1", "name": "GET"}, {"id": "2", "name": "MENU"}, 
{"id": "3", "name": "LIST"}]
         resources = [
             {"_id": "r1", "name": "Dag"},
@@ -334,6 +385,8 @@ class TestCommands:
     def test_create_permissions_with_teams(self, mock_get_client):
         client = Mock()
         mock_get_client.return_value = client
+        client.get_realm_roles.return_value = EXISTING_ROLES
+        client.get_client_roles.return_value = []
         scopes = [
             {"id": "1", "name": "GET"},
             {"id": "2", "name": "MENU"},
@@ -543,6 +596,8 @@ class TestCommands:
     ):
         client = Mock()
         mock_get_client.return_value = client
+        client.get_realm_roles.return_value = EXISTING_ROLES
+        client.get_client_roles.return_value = []
         client.get_clients.return_value = [
             {"id": "test-id", "clientId": "test_client_id"},
         ]
@@ -837,6 +892,7 @@ class TestCommands:
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._attach_default_role_permissions")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._ensure_default_role_policies")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_permissions")
+    
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_roles")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_resources")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_scopes")
     @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
@@ -845,6 +901,7 @@ class TestCommands:
         mock_get_client,
         mock_create_scopes,
         mock_create_resources,
+        mock_create_roles,
         mock_create_permissions,
         mock_ensure_default_role_policies,
         mock_attach_default_role_permissions,
@@ -864,6 +921,9 @@ class TestCommands:
             return_value=Mock(status_code=201, 
json=Mock(return_value={"message": ""}), text="{}")
         )
         client.connection.realm_name = "test-realm"
+        manager = Mock()
+        manager.attach_mock(mock_create_roles, "create_roles")
+        manager.attach_mock(mock_ensure_default_role_policies, 
"ensure_default_role_policies")
 
         params = [
             "keycloak-auth-manager",
@@ -883,9 +943,11 @@ class TestCommands:
         client.get_clients.assert_called_once_with()
         mock_create_scopes.assert_called_once_with(client, "test-id", 
_dry_run=False)
         mock_create_resources.assert_called_once_with(client, "test-id", 
teams=[], _dry_run=False)
+        mock_create_roles.assert_called_once_with(client, "test-id", 
_dry_run=False)
         mock_create_permissions.assert_called_once_with(client, "test-id", 
teams=[], _dry_run=False)
         mock_ensure_default_role_policies.assert_called_once_with(client, 
"test-id", _dry_run=False)
         mock_attach_default_role_permissions.assert_called_once_with(client, 
"test-id", _dry_run=False)
+        assert [c[0] for c in manager.mock_calls] == ["create_roles", 
"ensure_default_role_policies"]
 
     @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
     def test_create_scopes_dry_run(self, mock_get_client):
@@ -950,6 +1012,39 @@ class TestCommands:
         # In dry-run mode, no resources should be created
         client.create_client_authz_resource.assert_not_called()
 
+    @pytest.mark.parametrize("dry_run", [False, True])
+    
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_permissions")
+    @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
+    def test_create_permissions_missing_roles(self, mock_get_client, 
mock_create_permissions, dry_run):
+        client = Mock(spec=KeycloakAdmin)
+        mock_get_client.return_value = client
+        client.get_clients.return_value = [{"id": "test-id", "clientId": 
"test_client_id"}]
+        client.get_realm_roles.return_value = [{"name": "Admin"}]
+        client.get_client_roles.return_value = []
+
+        params = ["keycloak-auth-manager", "create-permissions", "--username", 
"test", "--password", "test"]
+        if dry_run:
+            params.append("--dry-run")
+        with conf_vars({("keycloak_auth_manager", "client_id"): 
"test_client_id"}):
+            with pytest.raises(ValueError, match="Roles Viewer, User, Op, 
SuperAdmin not found"):
+                create_permissions_command(self.arg_parser.parse_args(params))
+
+        mock_create_permissions.assert_not_called()
+        client.create_client_authz_role_based_policy.assert_not_called()
+
+    def test_ensure_role_policy_dry_run_does_not_need_the_role(self):
+        client = Mock(spec=KeycloakAdmin)
+        client.connection.realm_name = "test-realm"
+        client.connection.raw_get.return_value = Mock(text="[]")
+        client.get_realm_role.side_effect = KeycloakGetError(response_code=404)
+        client.get_client_role.side_effect = 
KeycloakGetError(response_code=404)
+
+        _ensure_role_policy(client, "test-id", "Viewer", _dry_run=True)
+
+        client.get_realm_role.assert_not_called()
+        client.get_client_role.assert_not_called()
+        client.create_client_authz_role_based_policy.assert_not_called()
+
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._attach_default_role_permissions")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._ensure_default_role_policies")
     @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
@@ -958,6 +1053,8 @@ class TestCommands:
     ):
         client = Mock()
         mock_get_client.return_value = client
+        client.get_realm_roles.return_value = EXISTING_ROLES
+        client.get_client_roles.return_value = []
         scopes = [{"id": "1", "name": "GET"}, {"id": "2", "name": "MENU"}, 
{"id": "3", "name": "LIST"}]
         resources = [
             {"_id": "r1", "name": "Dag"},
@@ -999,6 +1096,7 @@ class TestCommands:
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._attach_default_role_permissions")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._ensure_default_role_policies")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_permissions")
+    
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_roles")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_resources")
     
@patch("airflow.providers.keycloak.auth_manager.cli.commands._create_scopes")
     @patch("airflow.providers.keycloak.auth_manager.cli.commands._get_client")
@@ -1007,6 +1105,7 @@ class TestCommands:
         mock_get_client,
         mock_create_scopes,
         mock_create_resources,
+        mock_create_roles,
         mock_create_permissions,
         mock_ensure_default_role_policies,
         mock_attach_default_role_permissions,
@@ -1045,6 +1144,7 @@ class TestCommands:
         # In dry-run mode, all helper functions should be called with 
dry_run=True
         mock_create_scopes.assert_called_once_with(client, "test-id", 
_dry_run=True)
         mock_create_resources.assert_called_once_with(client, "test-id", 
teams=[], _dry_run=True)
+        mock_create_roles.assert_called_once_with(client, "test-id", 
_dry_run=True)
         mock_create_permissions.assert_called_once_with(client, "test-id", 
teams=[], _dry_run=True)
         mock_ensure_default_role_policies.assert_called_once_with(client, 
"test-id", _dry_run=True)
         mock_attach_default_role_permissions.assert_called_once_with(client, 
"test-id", _dry_run=True)
diff --git a/providers/keycloak/tests/unit/keycloak/cli/test_definition.py 
b/providers/keycloak/tests/unit/keycloak/cli/test_definition.py
index fd85e99479a..15985df4f17 100644
--- a/providers/keycloak/tests/unit/keycloak/cli/test_definition.py
+++ b/providers/keycloak/tests/unit/keycloak/cli/test_definition.py
@@ -48,11 +48,11 @@ class TestKeycloakCliDefinition:
                 self.arg_parser = cli_parser.get_parser()
 
     def test_keycloak_auth_manager_cli_commands(self):
-        assert len(KEYCLOAK_AUTH_MANAGER_COMMANDS) == 6
+        assert len(KEYCLOAK_AUTH_MANAGER_COMMANDS) == 7
 
     @pytest.mark.parametrize(
         "command",
-        ["create-scopes", "create-resources", "create-permissions", 
"create-all"],
+        ["create-scopes", "create-resources", "create-roles", 
"create-permissions", "create-all"],
     )
     def test_password_with_explicit_value(self, command):
         """Test commands are defined correctly to allow passing password 
explicitly via --password value."""
@@ -69,7 +69,7 @@ class TestKeycloakCliDefinition:
 
     @pytest.mark.parametrize(
         "command",
-        ["create-scopes", "create-resources", "create-permissions", 
"create-all"],
+        ["create-scopes", "create-resources", "create-roles", 
"create-permissions", "create-all"],
     )
     @patch("getpass.getpass", return_value="stdin_password")
     def test_password_from_stdin(self, mock_getpass, command):

Reply via email to