You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "anzinmhd (via GitHub)" <gi...@apache.org> on 2026/10/06 19:45:54 UTC

[PR] Fix Keycloak default role permission hierarchy [airflow]

anzinmhd opened a new pull request, #74371:
URL: https://github.com/apache/airflow/pull/74371

   # Fix Keycloak default role permission hierarchy
   
   The Keycloak auth manager's default role permissions do not currently preserve the expected permission hierarchy between `User`, `Op`, and `Admin`.
   
   An `Admin` user can therefore be denied access to resources granted through the `Op` permission. For example, an `Admin` attempting to list pools can be denied because the `Op` permission only contains the `Allow-Op` policy. With the resource server using `UNANIMOUS`, that denied permission causes the overall authorization decision to be denied even though the `Admin` permission itself permits the request.
   
   This PR updates the default role permission configuration so higher roles are included in the permissions granted to lower roles:
   
   - `User` permission: `Allow-User`, `Allow-Op`, and `Allow-Admin`
   - `Op` permission: `Allow-Op` and `Allow-Admin`
   
   These hierarchical resource permissions use the `AFFIRMATIVE` decision strategy. This allows a higher role to satisfy the permission without also having to satisfy every lower-role policy.
   
   The resource server can therefore retain its existing `UNANIMOUS` decision strategy while an `Admin` is correctly authorized for resources available to `Op`.
   
   The existing unit test for default role permission attachment has been updated to cover both the role hierarchy and the `AFFIRMATIVE` decision strategy.
   
   ### Verification
   
   Reproduced the issue against the current `main` branch using a local Keycloak environment.
   
   Before the change, evaluating an `Admin` user for `Pool` with the `LIST` scope resulted in:
   
   ```text
   Op       -> DENY
   ReadOnly -> PERMIT
   Admin    -> PERMIT
   Overall  -> DENY
   ```
   
   After applying the change and regenerating the Keycloak permissions:
   
   ```text
   Op       -> PERMIT
   ReadOnly -> PERMIT
   Admin    -> PERMIT
   Overall  -> PERMIT
   ```
   
   The top-level Keycloak resource-server decision strategy remained `UNANIMOUS` during verification.
   
   Tests:
   
   ```text
   providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py
   16 passed
   ```
   
   Related to #74357
   
   This PR currently addresses the default role-hierarchy portion of the issue.
   
   The separate `MENU` permission interaction described in #74357 is still under investigation and is not addressed by the current change.
   
   ---
   
   <!-- SPDX-License-Identifier: Apache-2.0
        https://www.apache.org/licenses/LICENSE-2.0 -->
   
   <!--
   Thank you for contributing!
   
   Please provide above a brief description of the changes made in this pull request.
   Write a good git commit message following this guide: https://chris.beams.io/posts/git-commit/
   
   Please make sure that your code changes are covered with tests.
   And in case of new features or big changes remember to adjust the documentation.
   
   For user-facing UI changes, please attach before/after screenshots (or a short
   screen recording) so reviewers can assess the visual impact.
   
   Feel free to ping (in general) for the review if you do not see reaction for a few days
   (72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications.
   
   In case of an existing issue, reference it using one of the following:
   
   * closes: #ISSUE
   * related: #ISSUE
   -->
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [x] Yes (ChatGPT)
   
   
   ---
   
   * Read the **[[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
   * For fundamental code changes, an Airflow Improvement Proposal ([[AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   * When adding dependency, check compliance with the [[ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x)](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: `{pr_number}.significant.rst`, in [[airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments)](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments). You can add this file in a follow-up commit after the PR is created so you know the PR number.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "anzinmhd (via GitHub)" <gi...@apache.org>.
anzinmhd commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6290861233

   @vincbeck Addressed the points from the agent’s findings: team-transition handling, client-wide strategy messaging and documentation, outdated permission guidance, redundant validation, attachment request batching, and the dry-run nits. The changes are pushed, and manual Keycloak transition checks passed.
   Could you take another look when you have time? Thanks for sharing the findings.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "anzinmhd (via GitHub)" <gi...@apache.org>.
anzinmhd commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6291564565

   @vincbeck Removed the mode-transition handling and its tests, and documented the limitation. The changes are pushed; 86 CLI tests and targeted mypy passed. After this merges, I plan to open the separate operational/audit access PR discussed earlier, keeping transition support outside its scope. Does that separation sound right? Thanks—could you take another look when you have time?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "stegololz (via GitHub)" <gi...@apache.org>.
stegololz commented on code in PR #74371:
URL: https://github.com/apache/airflow/pull/74371#discussion_r4257982176


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -449,46 +657,43 @@ def _create_resources(client: KeycloakAdmin, client_uuid: str, *, teams: list[st
     print("Resources created successfully.")
 
 
-def _get_permissions_to_create(
-    client: KeycloakAdmin,
-    client_uuid: str,
+def _validate_required_authz_objects(
+    permission_configs: list[dict],
+    *,
+    scopes: list[dict],
+    resources: list[dict],
+) -> None:
+    """Validate that permission prerequisites exist."""
+    available_resources = {resource["name"] for resource in resources}
+    available_scopes = {scope["name"] for scope in scopes}
+
+    required_resources = {
+        name for permission in permission_configs for name in permission.get("resources", [])
+    }
+    required_scopes = {
+        name for permission in permission_configs for name in permission.get("scope_names", [])
+    }
+
+    missing_resources = required_resources - available_resources
+    missing_scopes = required_scopes - available_scopes
+
+    if missing_resources or missing_scopes:
+        raise ValueError(

Review Comment:
   nit: In team mode the missing resources are the team ones (Dag:<team>, etc.), so the hint could say `create-resources --teams <team>`. 
   As written, following it doesn't fix the error.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6269431522

   The length of the PR makes it hard to review it by myself, so I ran my agent on it and here is what I got:
   
   ```
   Must fix
   1. New non-team grants stay active after switching to team mode.
      - create-team only narrows ReadOnly and Admin (commands.py _update_read_only_permission_resources / _update_admin_permission_resources).
      - It never narrows the 25 new permissions, which are attached to plain role policies (Allow-Viewer, …).
      - Because the resource server is now forced to AFFIRMATIVE, those grants take effect on their own:
        - AdminViewRead gives every Viewer access to AdminView, which is supposed to be SuperAdmin-only in multi-team mode. is_authorized_view checks the unsuffixed AdminView resource.
        - ConnectionWrite, PoolWrite and VariableWrite let any Op write team-less connections, pools and variables. In team mode only SuperAdmin should be able to.
   2. The decision-strategy change is client-wide and silent. _ensure_resource_server_decision_strategy switches existing clients, team or not, to AFFIRMATIVE and prints nothing on a real run. Custom permissions that used UNANIMOUS to deny access stop working. This needs a printed message plus a changelog and docs note.
   
   Should fix
   3. The docs are out of date. permissions.rst still lists the old four permissions. The 0.9.0 changelog note says re-running create-permissions updates ReadOnly and Admin, but now it creates new permissions instead.
   4. The _validate_permission_creation_plan(teams) check in create-all builds both sides from the same constants, so it can never fail. Only the create-team call, which uses live scopes, checks anything real.
   5. A real run of _attach_default_role_permissions makes about 120 attach calls of roughly 6 HTTP requests each, so around 700 requests. Attaching all of a permission's policies in one update would cut that sharply.
   
   Nits:
   - Two back-to-back if args.dry_run / if not args.dry_run blocks in create_all_command can be merged.
   - _get_permissions_to_create is called only for its validation and its return value is thrown away.
   - Each dry-run attach call now downloads the full authz export.
   - The PR body says Ruff and the unit tests haven't been re-run since the split.
   ```
   
   What do you think?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "anzinmhd (via GitHub)" <gi...@apache.org>.
anzinmhd commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6140505712

   The latest update restricts operational reads and menus to Op or above, and audit access to Admin/SuperAdmin. Validation completed: 383 unit tests passed (2 skipped), and all 582 manual role-matrix checks passed across the five default roles and the no-role case.
   The PR description now includes the final access matrix and UI/API verification. Existing legacy grants remain preserved; guidance on whether their migration belongs in this PR would be appreciated.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6290972428

   Sorry I forgot to follow-up. We had a discussion with @stegololz and we agree I do not think we should handle the transition for single team environment to multi team environment. This is too complex and that would create too much complexity in the code. Which I think this is actually what is happening now just looking at the PR size. Maybe you can trim it then?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "anzinmhd (via GitHub)" <gi...@apache.org>.
anzinmhd commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6129616422

   I've updated the implementation and PR description following the review, including explicit resource-server `AFFIRMATIVE` configuration, removal of unused generic Menu permissions, the `DefaultMenuAccess` name, prerequisite validation, and improved dry-run previews.
   
   Validation completed:
   - Ruff checks passed.
   - Keycloak CLI unit tests: 79 passed.
   - Fresh non-team client on Keycloak 23.0.6: 480/480 manually executed authorization checks passed across Viewer, User, Op, Admin, SuperAdmin, and no role.
   - Airflow Pools UI: Viewer could read pools but creation returned 403; Op could create, update, and delete a temporary pool.
   
   I'd appreciate guidance on three remaining points:
   
   1. **Existing realms and migration:** this PR does not remove legacy/custom permissions or automatically migrate realms during a provider upgrade. Existing grants may still affect effective access. Should migration/cleanup be included here, or handled separately? Our live verification covered a fresh client, not an upgraded realm.
   
   2. **Automated behavioral coverage:** the independent role × resource × scope matrix was run manually; the local harness is not included in this PR. Would you prefer a live Keycloak integration test in this PR to address the requested behavioral coverage?
   
   3. **Menu visibility:** the generated defaults still allow all five roles to read resources and access menu entries. Write permissions are restricted, but stricter Admin-only menu visibility from the linked issue is not implemented. Is retaining those read/menu defaults appropriate for this PR's scope?
   
   The PR description now documents the access matrix, manual verification results, and these limitations.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #74371:
URL: https://github.com/apache/airflow/pull/74371#discussion_r4337617033


##########
providers/keycloak/docs/changelog.rst:
##########
@@ -28,6 +28,27 @@ Changelog
 0.11.1

Review Comment:
   Just below `Changelog`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6120075379

   @stegololz, could you look at this one please?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "stegololz (via GitHub)" <gi...@apache.org>.
stegololz commented on code in PR #74371:
URL: https://github.com/apache/airflow/pull/74371#discussion_r4337530089


##########
providers/keycloak/docs/changelog.rst:
##########
@@ -28,6 +28,27 @@ Changelog
 0.11.1

Review Comment:
   0.1.1 is already released. @vincbeck where to put the changelog of this? in a new section or will it be gernerated?



##########
providers/keycloak/docs/changelog.rst:
##########
@@ -28,6 +28,27 @@ Changelog
 0.11.1

Review Comment:
   0.1.1 is already released. @vincbeck where to put the changelog of this? in a new section or will it be generated?



##########
providers/keycloak/docs/changelog.rst:
##########
@@ -28,6 +28,27 @@ Changelog
 0.11.1

Review Comment:
   0.11.1 is already released. @vincbeck where to put the changelog of this? in a new section or will it be generated?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "SameerMesiah97 (via GitHub)" <gi...@apache.org>.
SameerMesiah97 commented on code in PR #74371:
URL: https://github.com/apache/airflow/pull/74371#discussion_r4200799992


##########
providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py:
##########
@@ -585,22 +585,26 @@ def test_create_permissions_attaches_default_role_policies(
                 decision_strategy="AFFIRMATIVE",
                 _dry_run=False,
             )
-        mock_attach_resource_policy.assert_any_call(
-            client,
-            "test-id",
-            permission_name="User",
-            policy_name="Allow-User",
-            resource_names=["Dag", "Asset"],
-            _dry_run=False,
-        )
-        mock_attach_resource_policy.assert_any_call(
-            client,
-            "test-id",
-            permission_name="Op",
-            policy_name="Allow-Op",
-            resource_names=["Connection", "Pool", "Variable", "Backfill"],
-            _dry_run=False,
-        )
+        for role_name in ("User", "Op", "Admin"):
+            mock_attach_resource_policy.assert_any_call(
+                client,
+                "test-id",
+                permission_name="User",
+                policy_name=f"Allow-{role_name}",
+                resource_names=["Dag", "Asset"],
+                decision_strategy="AFFIRMATIVE",
+                _dry_run=False,
+            )
+        for role_name in ("Op", "Admin"):
+            mock_attach_resource_policy.assert_any_call(
+                client,
+                "test-id",
+                permission_name="Op",
+                policy_name=f"Allow-{role_name}",
+                resource_names=["Connection", "Pool", "Variable", "Backfill"],
+                decision_strategy="AFFIRMATIVE",
+                _dry_run=False,
+            )

Review Comment:
   Not sure if the existing tests cover the enforcment of the permissions hierarchy.
   
   Could we add a parametrized test covering the different roles and their expected access, including both positive and negative scenarios? For example, User should satisfy the User permission but not Op or Admin, Op should satisfy User and Op but not Admin, and Admin should satisfy all three.
   
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6291875752

   Will do, @stegololz can you take a look as well? Thanks!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "stegololz (via GitHub)" <gi...@apache.org>.
stegololz commented on code in PR #74371:
URL: https://github.com/apache/airflow/pull/74371#discussion_r4246477931


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -263,53 +263,81 @@ def _ensure_default_role_policies(client: KeycloakAdmin, client_uuid: str, *, _d
         _ensure_role_policy(client, client_uuid, role_name, _dry_run=_dry_run)
 
 
-def _attach_default_role_permissions(
-    client: KeycloakAdmin, client_uuid: str, *, _dry_run: bool = False
-) -> None:
-    for role_name in TEAM_ROLE_NAMES:
-        _attach_policy_to_scope_permission(
-            client,
-            client_uuid,
-            permission_name="ReadOnly",
-            policy_name=_role_policy_name(role_name),
-            scope_names=["GET", "MENU", "LIST"],
-            resource_names=[],
-            decision_strategy="AFFIRMATIVE",
-            _dry_run=_dry_run,
+def _get_default_permission_configs() -> list[dict]:
+    """Build resource-scoped permissions for non-team installations."""
+    read_roles = [*TEAM_ROLE_NAMES, SUPER_ADMIN_ROLE_NAME]
+    user_roles = ["User", "Op", "Admin", SUPER_ADMIN_ROLE_NAME]
+    op_roles = ["Op", "Admin", SUPER_ADMIN_ROLE_NAME]
+    admin_roles = ["Admin", SUPER_ADMIN_ROLE_NAME]
+
+    user_resources = {
+        KeycloakResource.DAG,
+        KeycloakResource.ASSET,
+    }
+    op_resources = {
+        KeycloakResource.CONNECTION,
+        KeycloakResource.POOL,
+        KeycloakResource.VARIABLE,
+        KeycloakResource.BACKFILL,
+    }
+
+    permission_configs = []
+
+    for resource in KeycloakResource:
+        if resource in user_resources:
+            write_roles = user_roles
+        elif resource in op_resources:
+            write_roles = op_roles
+        else:
+            write_roles = admin_roles
+
+        permission_configs.extend(
+            [
+                {
+                    "name": f"{resource.value}Read",
+                    "type": "scope-based",
+                    "resources": [resource.value],
+                    "scope_names": ["GET", "LIST"],
+                    "role_names": read_roles,
+                },
+                {
+                    "name": f"{resource.value}Write",
+                    "type": "scope-based",
+                    "resources": [resource.value],
+                    "scope_names": ["POST", "PUT", "DELETE"],
+                    "role_names": write_roles,
+                },
+            ]
         )
 
-    _attach_policy_to_resource_permission(
-        client,
-        client_uuid,
-        permission_name="User",
-        policy_name=_role_policy_name("User"),
-        resource_names=[KeycloakResource.DAG.value, KeycloakResource.ASSET.value],
-        _dry_run=_dry_run,
+    permission_configs.append(
+        {
+            "name": "MenuAccess",
+            "type": "scope-based",
+            "resources": [item.value for item in MenuItem],
+            "scope_names": ["MENU"],
+            "role_names": read_roles,
+        }
     )
-    _attach_policy_to_resource_permission(
-        client,
-        client_uuid,
-        permission_name="Op",
-        policy_name=_role_policy_name("Op"),
-        resource_names=[
-            KeycloakResource.CONNECTION.value,
-            KeycloakResource.POOL.value,
-            KeycloakResource.VARIABLE.value,
-            KeycloakResource.BACKFILL.value,
-        ],
-        _dry_run=_dry_run,
-    )
-    for role_name in ("Admin", SUPER_ADMIN_ROLE_NAME):
-        _attach_policy_to_scope_permission(
-            client,
-            client_uuid,
-            permission_name="Admin",
-            policy_name=_role_policy_name(role_name),
-            scope_names=_get_extended_resource_methods() + ["LIST"],
-            resource_names=[],
-            decision_strategy="AFFIRMATIVE",
-            _dry_run=_dry_run,
-        )
+
+    return permission_configs
+
+
+def _attach_default_role_permissions(
+    client: KeycloakAdmin, client_uuid: str, *, _dry_run: bool = False
+) -> None:
+    for permission in _get_default_permission_configs():
+        for role_name in permission["role_names"]:
+            _attach_policy_to_scope_permission(
+                client,
+                client_uuid,
+                permission_name=permission["name"],
+                policy_name=_role_policy_name(role_name),
+                scope_names=permission["scope_names"],
+                resource_names=permission["resources"],
+                decision_strategy="AFFIRMATIVE",

Review Comment:
   Every permission is now `AFFIRMATIVE` internally, but the CLI never sets the **resource server's** decision strategy, so realms run on Keycloak's default `UNANIMOUS`. Suggestion: have `create-all` / `create-permissions` (and `create-team`) PUT `decisionStrategy: AFFIRMATIVE` on `authz/resource-server` explicitly.
   
   - **Free on fresh realms:** with these per-resource permissions, the results are identical under both strategies.
   - **Fixes upgraded realms with no cleanup:** `main` + this PR under `AFFIRMATIVE` gives the same results as a fresh realm.
   - **Multi-team only works under `AFFIRMATIVE`.** Under `UNANIMOUS`, every `<Res>:<team>` request is denied for every user, SuperAdmin included. The global `Admin` (SuperAdmin-only) and the overlapping `User-/Op-/Admin-<team>` permissions block each other. Today the two modes need opposite server strategies on one realm, which is weird.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -263,53 +263,81 @@ def _ensure_default_role_policies(client: KeycloakAdmin, client_uuid: str, *, _d
         _ensure_role_policy(client, client_uuid, role_name, _dry_run=_dry_run)
 
 
-def _attach_default_role_permissions(
-    client: KeycloakAdmin, client_uuid: str, *, _dry_run: bool = False
-) -> None:
-    for role_name in TEAM_ROLE_NAMES:
-        _attach_policy_to_scope_permission(
-            client,
-            client_uuid,
-            permission_name="ReadOnly",
-            policy_name=_role_policy_name(role_name),
-            scope_names=["GET", "MENU", "LIST"],
-            resource_names=[],
-            decision_strategy="AFFIRMATIVE",
-            _dry_run=_dry_run,
+def _get_default_permission_configs() -> list[dict]:
+    """Build resource-scoped permissions for non-team installations."""
+    read_roles = [*TEAM_ROLE_NAMES, SUPER_ADMIN_ROLE_NAME]
+    user_roles = ["User", "Op", "Admin", SUPER_ADMIN_ROLE_NAME]
+    op_roles = ["Op", "Admin", SUPER_ADMIN_ROLE_NAME]
+    admin_roles = ["Admin", SUPER_ADMIN_ROLE_NAME]
+
+    user_resources = {
+        KeycloakResource.DAG,
+        KeycloakResource.ASSET,
+    }
+    op_resources = {
+        KeycloakResource.CONNECTION,
+        KeycloakResource.POOL,
+        KeycloakResource.VARIABLE,
+        KeycloakResource.BACKFILL,
+    }
+
+    permission_configs = []
+
+    for resource in KeycloakResource:

Review Comment:
   Nit: this also creates `MenuRead` / `MenuWrite` on the `Menu` resource. The auth manager never checks that resource (menus use `<MenuItem>#MENU`), so these are unused. Suggest skipping `KeycloakResource.MENU` here.
   



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -263,53 +263,81 @@ def _ensure_default_role_policies(client: KeycloakAdmin, client_uuid: str, *, _d
         _ensure_role_policy(client, client_uuid, role_name, _dry_run=_dry_run)
 
 
-def _attach_default_role_permissions(
-    client: KeycloakAdmin, client_uuid: str, *, _dry_run: bool = False
-) -> None:
-    for role_name in TEAM_ROLE_NAMES:
-        _attach_policy_to_scope_permission(
-            client,
-            client_uuid,
-            permission_name="ReadOnly",
-            policy_name=_role_policy_name(role_name),
-            scope_names=["GET", "MENU", "LIST"],
-            resource_names=[],
-            decision_strategy="AFFIRMATIVE",
-            _dry_run=_dry_run,
+def _get_default_permission_configs() -> list[dict]:
+    """Build resource-scoped permissions for non-team installations."""
+    read_roles = [*TEAM_ROLE_NAMES, SUPER_ADMIN_ROLE_NAME]
+    user_roles = ["User", "Op", "Admin", SUPER_ADMIN_ROLE_NAME]
+    op_roles = ["Op", "Admin", SUPER_ADMIN_ROLE_NAME]
+    admin_roles = ["Admin", SUPER_ADMIN_ROLE_NAME]
+
+    user_resources = {
+        KeycloakResource.DAG,
+        KeycloakResource.ASSET,
+    }
+    op_resources = {
+        KeycloakResource.CONNECTION,
+        KeycloakResource.POOL,
+        KeycloakResource.VARIABLE,
+        KeycloakResource.BACKFILL,
+    }
+
+    permission_configs = []
+
+    for resource in KeycloakResource:
+        if resource in user_resources:
+            write_roles = user_roles
+        elif resource in op_resources:
+            write_roles = op_roles
+        else:
+            write_roles = admin_roles
+
+        permission_configs.extend(
+            [
+                {
+                    "name": f"{resource.value}Read",
+                    "type": "scope-based",
+                    "resources": [resource.value],
+                    "scope_names": ["GET", "LIST"],
+                    "role_names": read_roles,
+                },
+                {
+                    "name": f"{resource.value}Write",
+                    "type": "scope-based",
+                    "resources": [resource.value],
+                    "scope_names": ["POST", "PUT", "DELETE"],
+                    "role_names": write_roles,
+                },
+            ]
         )
 
-    _attach_policy_to_resource_permission(
-        client,
-        client_uuid,
-        permission_name="User",
-        policy_name=_role_policy_name("User"),
-        resource_names=[KeycloakResource.DAG.value, KeycloakResource.ASSET.value],
-        _dry_run=_dry_run,
+    permission_configs.append(
+        {
+            "name": "MenuAccess",

Review Comment:
   This gives a name collision on a multiteam mode as it also creates a permission called `MenuAccess` (SuperAdmin-only).
   



##########
providers/keycloak/tests/unit/keycloak/auth_manager/cli/test_commands.py:
##########
@@ -55,6 +58,116 @@
 )
 
 
+@pytest.mark.parametrize(
+    ("permission_name", "resources", "scopes", "roles"),
+    [
+        (
+            "PoolRead",
+            ["Pool"],
+            ["GET", "LIST"],
+            ["Viewer", "User", "Op", "Admin", "SuperAdmin"],
+        ),
+        (
+            "PoolWrite",
+            ["Pool"],
+            ["POST", "PUT", "DELETE"],
+            ["Op", "Admin", "SuperAdmin"],
+        ),
+        (
+            "DagWrite",
+            ["Dag"],
+            ["POST", "PUT", "DELETE"],
+            ["User", "Op", "Admin", "SuperAdmin"],
+        ),
+        (
+            "ConfigurationWrite",
+            ["Configuration"],
+            ["POST", "PUT", "DELETE"],
+            ["Admin", "SuperAdmin"],
+        ),
+        (
+            "MenuAccess",
+            [item.value for item in MenuItem],
+            ["MENU"],
+            ["Viewer", "User", "Op", "Admin", "SuperAdmin"],
+        ),
+    ],
+)
+def test_get_default_permission_configs(permission_name, resources, scopes, roles):

Review Comment:
   +1 to @SameerMesiah97. These tests mostly restate the config. A parametrized **role × (resource, scope) → allowed / denied** table, with negative cases, would test what we actually care about.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -575,6 +577,24 @@ def _get_permissions_to_create(
     all_scopes = client.get_client_authz_scopes(client_uuid)
     all_resources = client.get_client_authz_resources(client_uuid)
 
+    if not teams:
+        available_resources = {resource["name"] for resource in all_resources}
+        available_scopes = {scope["name"] for scope in all_scopes}
+
+        required_resources = {name for permission in perm_configs for name in permission["resources"]}
+        required_scopes = {name for permission in perm_configs for name in permission["scope_names"]}
+
+        missing_resources = required_resources - available_resources
+        missing_scopes = required_scopes - available_scopes
+
+        if missing_resources or missing_scopes:

Review Comment:
   Good addition. A few suggestions to make it more robust:
   
   - **Validate before writing anything.** `create_permissions_command` calls `_ensure_default_role_policies` before this check runs, so a failed run is partly applied. Could the check be pulled into a small helper (e.g. `_validate_required_authz_objects(client, client_uuid, perm_configs)`) and called at the top of `create_permissions_command` / `create_all_command`, before any write?
   - **Apply it to team mode too.** The check is under `if not teams:`, so team mode still silently creates permissions without the resources that are missing. The same helper could run on the team `perm_configs`.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -605,6 +625,18 @@ def _get_permissions_to_create(
 
 def _preview_permissions(client: KeycloakAdmin, client_uuid: str, teams: list[str]):
     """Preview permissions that would be created."""
+    if not teams:

Review Comment:
   The non-team preview returns before `_get_permissions_to_create`, so dry-run never evaluates the new missing-resources check:
   
   - On an **empty realm**, `--dry-run` lists all 27 permissions and exits 0, while the real run exits 1.
   - On an **already-provisioned realm**, it still lists 27 "to be created" and 104 "Would attach" lines when nothing would change.
   
   Ideally dry-run would show the difference against what's already in Keycloak.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "anzinmhd (via GitHub)" <gi...@apache.org>.
anzinmhd commented on PR #74371:
URL: https://github.com/apache/airflow/pull/74371#issuecomment-6162814805

   @stegololz  I’ve narrowed this PR to the CLI permission-generation, validation, and dry-run changes, including the team-specific recovery hint, and updated the description accordingly.
   Once this PR merges, I’ll open a separate PR against the updated main for the auth-manager changes and their corresponding CLI grants, tests, and documentation, including OpView and the operational/audit access restrictions.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Fix Keycloak default role permission hierarchy [airflow]

Posted by "vincbeck (via GitHub) via commits" <co...@airflow.apache.org>.
vincbeck commented on code in PR #74371:
URL: https://github.com/apache/airflow/pull/74371#discussion_r4630415987


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -570,10 +754,49 @@ def _get_permissions_to_create(
                 "resources": [item.value for item in MenuItem],
             }
         )
+    return perm_configs
+
+
+def _validate_permission_prerequisites(
+    client: KeycloakAdmin,
+    client_uuid: str,
+    *,
+    teams: list[str],
+) -> None:
+    """Check live scopes and resources before policy writes."""
+    permission_configs = _get_permission_configs(teams)
+    scopes = client.get_client_authz_scopes(client_uuid)
+    resources = client.get_client_authz_resources(client_uuid)
+    _validate_required_authz_objects(
+        permission_configs,
+        scopes=scopes,
+        resources=resources,
+        teams=teams,
+    )
 
+
+def _get_permissions_to_create(
+    client: KeycloakAdmin,
+    client_uuid: str,
+    teams: list[str],
+    *,
+    include_global_admin: bool = True,
+) -> list[dict]:
+    """Validate permission prerequisites and resolve names to Keycloak IDs."""
+    perm_configs = _get_permission_configs(
+        teams,
+        include_global_admin=include_global_admin,
+    )
     all_scopes = client.get_client_authz_scopes(client_uuid)
     all_resources = client.get_client_authz_resources(client_uuid)
 
+    _validate_required_authz_objects(

Review Comment:
   `create-all` and `create-permissions` already call `_validate_permission_prerequisites` before this, so the same check runs twice. Can we keep it in only one place?



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -257,57 +279,169 @@ def _ensure_multi_team_enabled(*, teams: list[str], command_name: str) -> None:
         raise SystemExit(f"{command_name} requires core.multi_team=True when --teams is used.")
 
 
+def _ensure_resource_server_decision_strategy(
+    client: KeycloakAdmin,
+    client_uuid: str,
+    *,
+    _dry_run: bool = False,
+) -> None:
+    realm = client.connection.realm_name
+    url = f"admin/realms/{realm}/clients/{client_uuid}/authz/resource-server"
+
+    response = client.connection.raw_get(url)
+    settings = raise_error_from_response(
+        response,
+        KeycloakGetError,
+        expected_codes=[200],
+    )
+
+    if not isinstance(settings, dict):

Review Comment:
   Is that needed? Keycloak always returns a JSON object here. Same for the type checks in `_get_exported_permission_names`. Removing them would also remove a few tests, which helps with the PR size.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -977,10 +1275,22 @@ def _attach_team_menu_permissions(
 
 
 def _attach_superadmin_permissions(
-    client: KeycloakAdmin, client_uuid: str, team: str, *, _dry_run: bool = False
+    client: KeycloakAdmin,
+    client_uuid: str,
+    team: str,
+    *,
+    _dry_run: bool = False,
+    authz_settings: dict | None = None,
 ) -> None:
+    if _dry_run and authz_settings is None:
+        authz_settings = client.get_client_authz_settings(client_id=client_uuid)
+    attach_scope = (
+        partial(_attach_policy_to_scope_permission, authz_settings=authz_settings)
+        if _dry_run
+        else _attach_policy_to_scope_permission
+    )
     team_scoped_resources = [f"{resource}:{team}" for resource in sorted(TEAM_SCOPED_RESOURCE_NAMES)]
-    _attach_policy_to_scope_permission(
+    attach_scope(
         client,
         client_uuid,
         permission_name="Admin",

Review Comment:
   `create-team --dry-run` always reports a change on the global `Admin` permission, even when nothing would change. The preview here compares against `AFFIRMATIVE` and this team's resources only, but the real run then calls `_update_admin_permission_resources`, which puts it back to `UNANIMOUS` with every team's resources. Example: re-run `create-team team-a --dry-run` on a client already provisioned with team-a and team-b, it prints "Would configure permission 'Admin': decisionStrategy=AFFIRMATIVE, resources=[...]" with team-a resources only, which reads as if team-b would lose SuperAdmin access. Fix: for `Admin`, only preview the policy attachment here and leave the scopes/resources/strategy preview to `_update_admin_permission_resources`.



##########
providers/keycloak/docs/auth-manager/manage/permissions.rst:
##########
@@ -88,12 +103,48 @@ Finally, with the command below, we create the permissions using the previously
 
   airflow keycloak-auth-manager create-permissions --teams team-a,team-b
 
-This will create
-
-* read-only permissions (per-team when ``--teams`` is provided)
-* admin permissions (global)
-* user permissions (per-team when ``--teams`` is provided)
-* operations permissions (per-team when ``--teams`` is provided)
+Without ``--teams``, the CLI creates resource-specific permissions for non-team installations.
+It generates a ``<Resource>Read`` permission with ``GET`` and ``LIST`` scopes and a
+``<Resource>Write`` permission with ``POST``, ``PUT``, and ``DELETE`` scopes for each resource
+except the generic ``Menu`` resource. The current model has 24 read/write permissions for

Review Comment:
   nit: I would not put the numbers here, they will get outdated as soon as we add a resource



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -829,8 +1091,25 @@ def _ensure_team_policies(
 
 
 def _attach_team_permissions(
-    client: KeycloakAdmin, client_uuid: str, team: str, *, _dry_run: bool = False
+    client: KeycloakAdmin,
+    client_uuid: str,
+    team: str,
+    *,
+    _dry_run: bool = False,
+    authz_settings: dict | None = None,
 ) -> None:
+    if _dry_run and authz_settings is None:
+        authz_settings = client.get_client_authz_settings(client_id=client_uuid)
+    attach_scope = (
+        partial(_attach_policy_to_scope_permission, authz_settings=authz_settings)
+        if _dry_run
+        else _attach_policy_to_scope_permission
+    )
+    attach_resource = (
+        partial(_attach_policy_to_resource_permission, authz_settings=authz_settings)
+        if _dry_run
+        else _attach_policy_to_resource_permission
+    )

Review Comment:
   Why the `partial`? `_attach_policy_to_scope_permission` and `_attach_policy_to_resource_permission` only read `authz_settings` in dry-run, so you can pass `authz_settings=authz_settings` directly. The `authz_settings is None` fallback is also never used since `create_team_command` always passes it. Same in the 3 other functions.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/cli/commands.py:
##########
@@ -365,6 +499,48 @@ def _create_scopes(client: KeycloakAdmin, client_uuid: str, *, _dry_run: bool =
     print("Scopes created successfully.")
 
 
+def _get_resource_names_to_create(
+    teams: list[str],
+) -> tuple[list[str], list[str]]:
+    """Build standard and menu resource names without querying Keycloak."""
+    standard_names = [resource.value for resource in KeycloakResource]
+    existing = set(standard_names)
+
+    for team in teams:
+        for resource_name in TEAM_SCOPED_RESOURCE_NAMES:
+            name = f"{resource_name}:{team}"
+            if name not in existing:
+                standard_names.append(name)
+                existing.add(name)
+
+    menu_names = [item.value for item in MenuItem]
+    return standard_names, menu_names
+
+
+def _validate_permission_creation_plan(
+    teams: list[str],
+    *,
+    include_global_admin: bool = True,
+    scopes: list[dict] | None = None,
+) -> None:
+    """Validate permission prerequisites against a provisioning plan."""
+    standard_names, menu_names = _get_resource_names_to_create(teams)
+    resources = [{"name": name} for name in standard_names + menu_names]
+
+    if scopes is None:

Review Comment:
   nit: the only caller always passes `scopes`, so this branch is never used



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org