8000 FGAP v2: allow delegated admins to access users who also belong to groups delegated to other admins (parity with v1) by vramik · Pull Request #55622 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,14 @@ public void evaluate(Evaluation evaluation) {
DecisionResultCollector decision = new DecisionResultCollector() {
@Override
protected void onComplete(Result result) {
if (isGranted(result.getResults().iterator().next())) {
var aggregate = result.getResults().iterator().next();
if (isGranted(aggregate)) {
evaluation.grant();
} else {
if (aggregate.getPolicy().getLogic() == Logic.POSITIVE && aggregate.getAssociatedPolicies().stream()
.anyMatch(child -> result.getPermission().isExplicitDenial(child.getPolicy(), child.getEffect()))) {
result.getPermission().setExplicitAggregateDenial(aggregate.getPolicy(), true);
}
evaluation.deny();
}
}
Expand All @@ -69,6 +74,7 @@ protected void onComplete(Result result) {
DefaultEvaluation defaultEvaluation = DefaultEvaluation.class.cast(evaluation);
Map<Policy, Map<Object, Decision.Effect>> decisionCache = defaultEvaluation.getDecisionCache();
ResourcePermission permission = evaluation.getPermission();
permission.setExplicitAggregateDenial(policy, false);

for (Policy associatedPolicy : policy.getAssociatedPolicies()) {
Map<Object, Decision.Effect> decisions = decisionCache.computeIfAbsent(associatedPolicy, p -> new HashMap<>());
Expand Down Expand Up @@ -123,12 +129,22 @@ public boolean evaluate(KeycloakSession session, Policy policy, UserModel subjec

@Override
public Outcome evaluateOutcome(KeycloakSession session, Policy policy, UserModel subject) {
return evaluateChildren(session, policy, subject, false);
}

@Override
public Outcome evaluateMemberOutcome(KeycloakSession session, Policy policy, UserModel subject) {
return evaluateChildren(session, policy, subject, true);
}

private Outcome evaluateChildren(KeycloakSession session, Policy policy, UserModel subject, boolean memberScope) {
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
DecisionStrategy decisionStrategy = policy.getDecisionStrategy();
Set<Policy> associatedPolicies = policy.getAssociatedPolicies();
int grants = 0;
int evaluated = 0;
int forceDeny = 0;
boolean explicitDenial = false;

for (Policy associatedPolicy : associatedPolicies) {
PolicyProvider policyProvider = authorization.getProvider(associatedPolicy.getType());
Expand All @@ -138,7 +154,8 @@ public Outcome evaluateOutcome(KeycloakSession session, Policy policy, UserModel
}

if (policyProvider instanceof PartialEvaluationPolicyProvider partialPolicyProvider) {
Outcome childOutcome = partialPolicyProvider.evaluateOutcome(session, associatedPolicy, subject);
Outcome childOutcome = memberScope ? partialPolicyProvider.evaluateMemberOutcome(session, associatedPolicy, subject)
: partialPolicyProvider.evaluateOutcome(session, associatedPolicy, subject);

if (Outcome.INVALID.equals(childOutcome)) {
return Outcome.INVALID;
Expand All @@ -161,6 +178,9 @@ public Outcome evaluateOutcome(KeycloakSession session, Policy policy, UserModel
childGranted = !childGranted;
}

if (!childGranted && (associatedPolicy.getLogic() == Logic.NEGATIVE || childOutcome == Outcome.EXPLICIT_DENY)) {
explicitDenial = true;
}
if (childGranted) {
grants++;
}
Expand All @@ -169,12 +189,18 @@ public Outcome evaluateOutcome(KeycloakSession session, Policy policy, UserModel
}
}

if (memberScope && evaluated < associatedPolicies.size() && explicitDenial) {
// An unresolved child combined with an explicit denial may change
// whether that denial propagates to another membership.
return Outcome.FORCE_DENY;
Comment on lines +192 to +195
}
if (evaluated == 0) {
return forceDeny == 0 ? Outcome.SKIP: Outcome.FORCE_DENY;
}

Outcome denial = memberScope && explicitDenial ? Outcome.EXPLICIT_DENY : Outcome.DENY;
if (grants == 0) {
return Outcome.DENY;
return denial;
}

// uses total policy count, not just evaluated, so skipped and unsupported children count against unanimity/consensus;
Expand All @@ -186,6 +212,6 @@ public Outcome evaluateOutcome(KeycloakSession session, Policy policy, UserModel
case CONSENSUS -> grants > associatedPolicies.size() - grants;
};

return granted ? Outcome.GRANT : Outcome.DENY;
return granted ? Outcome.GRANT : denial;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,26 @@ public boolean evaluate(KeycloakSession session, Policy policy, UserModel subjec

@Override
public Outcome evaluateOutcome(KeycloakSession session, Policy policy, UserModel subject) {
return evaluateSubjectGroups(session, policy, subject, false);
}

@Override
public Outcome evaluateMemberOutcome(KeycloakSession session, Policy policy, UserModel subject) {
// All member permissions are candidates, including policies for a different group of administrators.
return evaluateSubjectGroups(session, policy, subject, true);
}

private Outcome evaluateSubjectGroups(KeycloakSession session, Policy policy, UserModel subject, boolean memberScope) {
RealmModel realm = session.getContext().getRealm();
AuthorizationProvider authorizationProvider = session.getProvider(AuthorizationProvider.class);
GroupPolicyRepresentation groupPolicy = representationFunction.apply(policy, authorizationProvider);
List<String> userGroups = resolveSubjectGroupPaths(session, subject);
return evaluateGroups(session, realm, subject, groupPolicy, new Entry(groupPolicy.getGroupsClaim(), userGroups),
String claim = groupPolicy.getGroupsClaim();
// Always resolve from actual memberships. The runtime evaluate() path reads the
// identity token claim, but partial evaluation has no token. Reading the user
// attribute named after groupsClaim would be untrusted — the admin can edit their
// own unmanaged attributes through the account console.
List<String> groups = resolveSubjectGroupPaths(session, subject);
return evaluateGroups(session, realm, memberScope ? null : subject, groupPolicy, new Entry(claim, groups),
Logic.NEGATIVE.equals(policy.getLogic()));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ public static class PolicyResultRepresentation {
private List<PolicyResultRepresentation> associatedPolicies;
private Set<String> scopes = new HashSet<>();
private String resourceType;
private String memberScopeDecision;

public String getMemberScopeDecision() {
return memberScopeDecision;
}

public void setMemberScopeDecision(String memberScopeDecision) {
this.memberScopeDecision = memberScopeDecision;
}

public PolicyRepresentation getPolicy() {
return policy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,21 +160,34 @@ To create a new user directly as a member of a group, the delegated administrato

The `view-members`, `manage-members`, and `impersonate-members` scopes cascade through the group hierarchy. When you grant or deny one of these scopes on a group, the permission applies to all descendant groups unless a more specific permission exists on a descendant.

*Deny cascading:* A deny on a parent group prevents access to members of the parent and all its descendant groups (children, grandchildren, and so on).
*Deny cascading:* An explicit denial on a parent group protects members of the parent and all its descendant groups (children, grandchildren, and so on).

*Allow carve-outs:* You can override a parent deny by granting an explicit allow for the same scope on a specific child group. The allow applies only to direct members of that child group. It does not cascade further to the child's own descendants. Members of deeper descendant groups remain denied unless they also have an explicit allow.

A direct `view` permission on a specific user does not override a group membership deny that uses a member scope. Denies on the member scopes (`view-members`, `manage-members`, and `impersonate-members`)
take precedence over user-level permissions. The only way to restore access to a user in a denied group subtree is to grant an explicit allow for a member scope (such as `view-members`)
on the specific group the user belongs to.
A positive policy that does not match the administrator prevents its permission from granting the member scope on that group.
A different group or a Users permission can still grant access to the shared user.
All permissions for the same group and member scope must grant before that group supplies a grant.
Viewing a shared user exposes only memberships visible to the administrator, and changing membership requires permission on the target group.

A negative policy whose condition matches the administrator produces an explicit denial.
An explicit denial on a specific group's member scope takes precedence over grants through other memberships and Users permissions.
Within a group hierarchy, a successful direct grant on the child's member scope can override an inherited explicit denial for direct members of that child.
An unmatched child permission cannot create this exception.

For an aggregate policy, {project_name} applies its decision strategy and logic first.
An aggregate that grants access contributes a grant, including when an evaluated child explicitly denied.
A negative aggregate that evaluates to deny contributes an explicit denial.
A positive aggregate that evaluates to deny contributes an explicit denial only if one of its evaluated children contributed an explicit denial.
These rules apply recursively to nested aggregates.
The Evaluation tab shows each group permission's member-scope decision alongside the final user scopes.

Only the member scopes protect a group's members. A group permission that denies only a `view` or `manage` scope,
does not block a user-level operation on a member of that group. In that case the user remains accessible through the
corresponding user-level permission, and the group the administrator cannot access is simply filtered out from the user's
group memberships.
For example, an administrator with `view` on all users can still view a user who also belongs to a group they cannot access.
Only the groups the administrator is allowed to see are returned for that user.
Denying `view-members` (or `manage-members`) on that group is what protects its members and denies access to the user.
Explicitly denying `view-members` (or `manage-members`) on that group protects its members and denies access to the user.

For example, given a hierarchy `Department > Team A > Subteam X`:

Expand All @@ -185,9 +198,9 @@ For example, given a hierarchy `Department > Team A > Subteam X`:

====== Search visibility for group member permissions

When `view-members` is granted on a parent group, members of child groups are accessible via direct user lookup (for example, `GET /admin/realms/{realm}/users/{userId}`) but may not appear in user search or count results. The search mechanism uses a partial evaluation that matches users against the specific groups referenced in the permission, not against their descendants.

To ensure that members of child groups appear in search and count results, grant `view-members` on each child group explicitly.
User search, counts, and group member listings apply the effective `view-members` permissions to memberships before pagination.
For supported policies and storage providers, a grant inherited from a parent group makes descendant members visible in both search results and direct user lookups.
Explicit denials on another effective membership still protect shared users.

When a delegated administrator has `view` permission on a group but not on its ancestor groups, the Admin REST API returns the full group hierarchy so the administrator can understand where the group belongs. Ancestor groups without `view` permission are returned as stripped representations containing only `id`, `name`, `path`, `parentId`, and `description`. Sensitive fields such as `attributes`, `realmRoles`, `clientRoles`, and `access` are omitted from these ancestors.

Expand Down Expand Up @@ -317,8 +330,9 @@ Keep that fact in mind when creating and updating permissions in production.
===== Defining permissions for viewing realm resources

This feature relies on a partial evaluation mechanism to partially evaluate the permissions that a realm administrator has
when listing and viewing realm resources. This mechanism will pre-fetch all the permissions set for view-related scopes where the realm administrator
is referenced either directly or indirectly.
when listing and viewing realm resources.
For user queries, it considers the permissions for `view` on Users and `view-members` on Groups, including permissions that match a different administrator.
For other resource types, it pre-fetches view-related permissions that reference the administrator directly or indirectly.

Permissions that grant access to `view` a realm resource of a certain type must use one of the following policies to
make them available from queries:
Expand All @@ -328,7 +342,11 @@ make them available from queries:
* `Role`
* `Aggregated`

When using an `Aggregated` policy, underlying policies that support partial evaluation (`User`, `Group`, `Role`, or nested `Aggregated`)
For a Groups `view-members` permission, all underlying policies must support partial evaluation for user queries to resolve the membership decision.
If an underlying policy cannot be evaluated, the query excludes users protected by that membership, even when another membership would grant access.
The direct permission check can still evaluate the policy.

For other view-related permissions using an `Aggregated` policy, underlying policies that support partial evaluation (`User`, `Group`, `Role`, or nested `Aggregated`)
are evaluated during partial evaluation. Underlying policies of other types (such as `Time` or `JavaScript`) are skipped
because they cannot be pre-evaluated at the database level. If an aggregated policy contains only unsupported policy types,
the entire aggregated policy is excluded from partial evaluation.
Expand All @@ -350,7 +368,7 @@ with the `admin` role at the master realm (server administrators), or realm admi

When querying resources, the partial evaluation mechanism works as follows:

* Resolve all the permissions for a certain resource type that reference the realm administrator
* Resolve the view-related permissions for the resource type as described above
* Pre-evaluate each permission to check if the realm administrator does or does not have access to the resources associated with the permission
* Decorate database queries based on the resources granted or denied

Expand Down
12 changes: 12 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
Breaking changes are identified as those that might require changes for existing users to their configurations or applications.
In minor or patch releases, {project_name} will only introduce breaking changes to fix bugs.

=== Delegated administration of users in multiple groups
// https://github.com/keycloak/keycloak/issues/54405

With fine-grained admin permissions v2, administrators can access a user through a grant on any of the user's groups or an applicable Users permission.
A positive policy on another group's member scope that does not match that administrator no longer blocks the grant.
For example, delegating Sales to Alice and Support to Bob allows each administrator to manage a user who belongs to both groups.

Before upgrading, review group member permissions where a positive allowlist is intended to protect members from administrators with independent grants, including grants to impersonate users.
To exclude a set of administrators from viewing members of a protected group, keep the allowlist and add a negative policy matching the excluded administrators to the group's `view-members` permission.
Test the excluded administrator and an authorized administrator with a user who also belongs to another delegated group.
Repeat for each protected member scope.

=== Authorization policies with deleted references

Role policies with a missing required role and negative role, group, user, client, or client scope policies with unresolved references now evaluate as invalid.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4002,6 +4002,10 @@ resourceTypeSelectHelp=Select a resource type that is going to be used to query
grantedScope=Granted scope:
deniedScope=Denied scope:
evaluatedPolicy={{name}} voted to {{status}}
memberScopeDecision.GRANT=grant the member scope
memberScopeDecision.NO_GRANT=withhold its grant
memberScopeDecision.EXPLICIT_DENY=explicitly deny the member scope
memberScopeDecision.INDETERMINATE=deny because the policy could not be evaluated
permissionEvaluationAlertTitle=The selected user does not have access to the selected resource(s)
deleteConfirmRealm_one=Delete realm {{name}}?
deleteConfirmRealm_other=Delete {{count}} realms?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ export const PermissionEvaluationResult = ({
<ListItem key={p.policy?.id}>
{t("evaluatedPolicy", {
name: p.policy?.name,
status: p.status,
status: p.memberScopeDecision
? t(`memberScopeDecision.${p.memberScopeDecision}`)
: p.status,
})}
</ListItem>
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import type { DecisionEffect } from "./policyRepresentation.js";
export default interface PolicyResultRepresentation {
policy?: PolicyRepresentation;
status?: DecisionEffect;
memberScopeDecision?:
| "GRANT"
| "NO_GRANT"
| "EXPLICIT_DENY"
| "INDETERMINATE";
associatedPolicies?: PolicyResultRepresentation[];
scopes?: string[];
}
Loading
Loading
0