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
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,24 @@ public void evaluate(Evaluation evaluation) {
DecisionResultCollector decision = new DecisionResultCollector() {
@Override
protected void onComplete(Result result) {
if (isGranted(result.getResults().iterator().next())) {
Result.PolicyResult 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();
}
}
};
AuthorizationProvider authorization = evaluation.getAuthorizationProvider();
Policy policy = evaluation.getPolicy();
DefaultEvaluation defaultEvaluation = DefaultEvaluation.class.cast(evaluation);
DefaultEvaluation defaultEvaluation = (DefaultEvaluation) 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 8000 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,20 +178,35 @@ 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++;
}
} else {
forceDeny++;
if (associatedPolicy.getLogic() == Logic.NEGATIVE) {
explicitDenial = true;
}
}
}

if (grants > 0 && decisionStrategy == DecisionStrategy.AFFIRMATIVE) {
return Outcome.GRANT;
}
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 thread
Copilot marked this conversation as resolved.
Resolved
}
if (evaluated == 0) {
return forceDeny == 0 ? Outcome.SKIP: Outcome.FORCE_DENY;
}

Outcome denial = explicitDenial ? Outcome.EXPLICIT_DENY : Outcome.DENY;
if (grants == 0) {
return Outcome.DENY;
return denial;
Comment thread
vramik marked this conversation as resolved.
Resolved
}

// uses total policy count, not just evaluated, so skipped and unsupported children count against unanimity/consensus;
Expand All @@ -186,6 +218,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 @@ -55,9 +55,8 @@
import static org.keycloak.authorization.fgap.evaluation.partial.PartialEvaluationPolicyProvider.Outcome.DENY;
import static org.keycloak.authorization.fgap.evaluation.partial.PartialEvaluationPolicyProvider.Outcome.GRANT;
import static org.keycloak.authorization.fgap.evaluation.partial.PartialEvaluationPolicyProvider.Outcome.INVALID;
import static org.keycloak.authorization.fgap.evaluation.partial.PartialEvaluationPolicyProvider.Outcome.SKIP;
import static org.keycloak.models.utils.ModelToRepresentation.buildGroupPath;
import static org.keycloak.models.utils.RoleUtils.isDirectMember;


/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
Expand Down Expand Up @@ -96,7 +95,7 @@ public void evaluate(Evaluation evaluation) {
}

KeycloakSession session = authorizationProvider.getKeycloakSession();
Outcome outcome = evaluateGroups(session, realm, null, policy, groupsClaim,
Outcome outcome = evaluateGroups(session, realm, policy, groupsClaim,
Logic.NEGATIVE.equals(evaluation.getPolicy().getLogic()));

if (INVALID.equals(outcome)) {
Expand All @@ -108,8 +107,7 @@ public void evaluate(Evaluation evaluation) {
logger.debugf("Groups policy %s evaluated to %s with identity groups %s", policy.getName(), evaluation.getEffect(), groupsClaim);
}

private Outcome evaluateGroups(KeycloakSession session, RealmModel realm, UserModel subject, GroupPolicyRepresentation policy, Entry groupsClaim, boolean negative) {
boolean skipped = false;
private Outcome evaluateGroups(KeycloakSession session, RealmModel realm, GroupPolicyRepresentation policy, Entry groupsClaim, boolean negative) {
boolean granted = false;
boolean hasResolvedGroup = false;

Expand All @@ -127,11 +125,6 @@ private Outcome evaluateGroups(KeycloakSession session, RealmModel realm, UserMo
continue;
}

if (subject != null && !definition.isExtendChildren() && !isDirectMember(subject.getGroupsStream(), allowedGroup)) {
skipped = true;
continue;
}

if (matchesGroup(session, realm, allowedGroup, definition.isExtendChildren(), groupsClaim)) {
if (!negative) {
return GRANT;
Expand All @@ -143,14 +136,8 @@ private Outcome evaluateGroups(KeycloakSession session, RealmModel realm, UserMo
if (!hasResolvedGroup) {
return INVALID;
}
if (granted) {
return GRANT;
}
if (skipped) {
return SKIP;
}

return DENY;
return granted ? GRANT : DENY;
}

private boolean matchesGroup(KeycloakSession session, RealmModel realm, GroupModel allowedGroup, boolean extendChildren, Entry groupsClaim) {
Expand Down Expand Up @@ -224,11 +211,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, 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,13 @@ 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 should support partial evaluation for user queries to resolve the membership decision.
If an aggregated policy uses the `Affirmative` decision strategy, a single supported policy that grants is sufficient; unsupported children do not block the grant.
For `Unanimous` or `Consensus` strategies, an unsupported policy with negative logic causes the query to conservatively exclude users protected by that membership, even when another membership would grant access.
An unsupported positive policy does not create an explicit denial but counts against unanimity and consensus.
The direct permission check can still evaluate all policy types at runtime.

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 +370,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
Loading
Loading
0