Search in sources :

Example 1 with Decision

use of org.keycloak.authorization.Decision in project keycloak by keycloak.

the class ScopePolicyProvider method evaluate.

@Override
public void evaluate(Evaluation evaluation) {
    DefaultEvaluation defaultEvaluation = DefaultEvaluation.class.cast(evaluation);
    Map<Policy, Map<Object, Decision.Effect>> decisionCache = defaultEvaluation.getDecisionCache();
    Policy policy = defaultEvaluation.getParentPolicy();
    Map<Object, Decision.Effect> decisions = decisionCache.computeIfAbsent(policy, p -> new HashMap<>());
    ResourcePermission permission = evaluation.getPermission();
    Decision.Effect effect = decisions.get(permission);
    if (effect != null) {
        defaultEvaluation.setEffect(effect);
        return;
    }
    Decision.Effect decision = defaultEvaluation.getEffect();
    if (decision == null) {
        super.evaluate(evaluation);
        decisions.put(permission, defaultEvaluation.getEffect());
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) Map(java.util.Map) HashMap(java.util.HashMap) DefaultEvaluation(org.keycloak.authorization.policy.evaluation.DefaultEvaluation) Decision(org.keycloak.authorization.Decision) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 2 with Decision

use of org.keycloak.authorization.Decision in project keycloak by keycloak.

the class AggregatePolicyProvider method evaluate.

@Override
public void evaluate(Evaluation evaluation) {
    DecisionResultCollector decision = new DecisionResultCollector() {

        @Override
        protected void onComplete(Result result) {
            if (isGranted(result.getResults().iterator().next())) {
                evaluation.grant();
            } else {
                evaluation.deny();
            }
        }
    };
    AuthorizationProvider authorization = evaluation.getAuthorizationProvider();
    Policy policy = evaluation.getPolicy();
    DefaultEvaluation defaultEvaluation = DefaultEvaluation.class.cast(evaluation);
    Map<Policy, Map<Object, Decision.Effect>> decisionCache = defaultEvaluation.getDecisionCache();
    ResourcePermission permission = evaluation.getPermission();
    for (Policy associatedPolicy : policy.getAssociatedPolicies()) {
        Map<Object, Decision.Effect> decisions = decisionCache.computeIfAbsent(associatedPolicy, p -> new HashMap<>());
        Decision.Effect effect = decisions.get(permission);
        DefaultEvaluation eval = new DefaultEvaluation(evaluation.getPermission(), evaluation.getContext(), policy, associatedPolicy, decision, authorization, decisionCache);
        if (effect == null) {
            PolicyProvider policyProvider = authorization.getProvider(associatedPolicy.getType());
            policyProvider.evaluate(eval);
            eval.denyIfNoEffect();
            decisions.put(permission, eval.getEffect());
        } else {
            eval.setEffect(effect);
        }
    }
    decision.onComplete(permission);
}
Also used : Policy(org.keycloak.authorization.model.Policy) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) DecisionResultCollector(org.keycloak.authorization.policy.evaluation.DecisionResultCollector) DefaultEvaluation(org.keycloak.authorization.policy.evaluation.DefaultEvaluation) Decision(org.keycloak.authorization.Decision) Result(org.keycloak.authorization.policy.evaluation.Result) PolicyProvider(org.keycloak.authorization.policy.provider.PolicyProvider) HashMap(java.util.HashMap) Map(java.util.Map) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 3 with Decision

use of org.keycloak.authorization.Decision in project keycloak by keycloak.

the class IterablePermissionEvaluator method evaluate.

@Override
public Decision evaluate(Decision decision) {
    StoreFactory storeFactory = authorizationProvider.getStoreFactory();
    try {
        Map<Policy, Map<Object, Decision.Effect>> decisionCache = new HashMap<>();
        storeFactory.setReadOnly(true);
        Iterator<ResourcePermission> permissions = getPermissions();
        while (permissions.hasNext()) {
            this.policyEvaluator.evaluate(permissions.next(), authorizationProvider, executionContext, decision, decisionCache);
        }
        decision.onComplete();
    } catch (Throwable cause) {
        decision.onError(cause);
    } finally {
        storeFactory.setReadOnly(false);
    }
    return decision;
}
Also used : Policy(org.keycloak.authorization.model.Policy) HashMap(java.util.HashMap) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) Map(java.util.Map) Decision(org.keycloak.authorization.Decision) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 4 with Decision

use of org.keycloak.authorization.Decision in project keycloak by keycloak.

the class UnboundedPermissionEvaluator method evaluate.

@Override
public Decision evaluate(Decision decision) {
    StoreFactory storeFactory = authorizationProvider.getStoreFactory();
    try {
        Map<Policy, Map<Object, Decision.Effect>> decisionCache = new HashMap<>();
        storeFactory.setReadOnly(true);
        Permissions.all(resourceServer, executionContext.getIdentity(), authorizationProvider, request, permission -> policyEvaluator.evaluate(permission, authorizationProvider, executionContext, decision, decisionCache));
        decision.onComplete();
    } catch (Throwable cause) {
        decision.onError(cause);
    } finally {
        storeFactory.setReadOnly(false);
    }
    return decision;
}
Also used : Policy(org.keycloak.authorization.model.Policy) HashMap(java.util.HashMap) StoreFactory(org.keycloak.authorization.store.StoreFactory) HashMap(java.util.HashMap) Map(java.util.Map) Decision(org.keycloak.authorization.Decision)

Example 5 with Decision

use of org.keycloak.authorization.Decision in project keycloak by keycloak.

the class PolicyEvaluationResponseBuilder method build.

public static PolicyEvaluationResponse build(PolicyEvaluationService.EvaluationDecisionCollector decision, ResourceServer resourceServer, AuthorizationProvider authorization, KeycloakIdentity identity) {
    PolicyEvaluationResponse response = new PolicyEvaluationResponse();
    List<PolicyEvaluationResponse.EvaluationResultRepresentation> resultsRep = new ArrayList<>();
    AccessToken accessToken = identity.getAccessToken();
    AccessToken.Authorization authorizationData = new AccessToken.Authorization();
    authorizationData.setPermissions(decision.results());
    accessToken.setAuthorization(authorizationData);
    ClientModel clientModel = authorization.getRealm().getClientById(resourceServer.getId());
    if (!accessToken.hasAudience(clientModel.getClientId())) {
        accessToken.audience(clientModel.getClientId());
    }
    response.setRpt(accessToken);
    Collection<Result> results = decision.getResults();
    if (results.stream().anyMatch(evaluationResult -> evaluationResult.getEffect().equals(Decision.Effect.DENY))) {
        response.setStatus(DecisionEffect.DENY);
    } else {
        response.setStatus(DecisionEffect.PERMIT);
    }
    for (Result result : results) {
        PolicyEvaluationResponse.EvaluationResultRepresentation rep = new PolicyEvaluationResponse.EvaluationResultRepresentation();
        if (result.getEffect() == Decision.Effect.DENY) {
            rep.setStatus(DecisionEffect.DENY);
        } else {
            rep.setStatus(DecisionEffect.PERMIT);
        }
        resultsRep.add(rep);
        if (result.getPermission().getResource() != null) {
            ResourceRepresentation resource = new ResourceRepresentation();
            resource.setId(result.getPermission().getResource().getId());
            resource.setName(result.getPermission().getResource().getName());
            rep.setResource(resource);
        } else {
            ResourceRepresentation resource = new ResourceRepresentation();
            resource.setName("Any Resource with Scopes " + result.getPermission().getScopes().stream().map(Scope::getName).collect(Collectors.toList()));
            rep.setResource(resource);
        }
        rep.setScopes(result.getPermission().getScopes().stream().map(scope -> {
            ScopeRepresentation representation = new ScopeRepresentation();
            representation.setId(scope.getId());
            representation.setName(scope.getName());
            return representation;
        }).collect(Collectors.toList()));
        List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = new ArrayList<>();
        for (Result.PolicyResult policy : result.getResults()) {
            PolicyResultRepresentation policyRep = toRepresentation(policy, authorization);
            if ("resource".equals(policy.getPolicy().getType())) {
                policyRep.getPolicy().setScopes(result.getPermission().getResource().getScopes().stream().map(Scope::getName).collect(Collectors.toSet()));
            }
            policies.add(policyRep);
        }
        rep.setPolicies(policies);
    }
    resultsRep.sort(Comparator.comparing(o -> o.getResource().getName()));
    Map<String, PolicyEvaluationResponse.EvaluationResultRepresentation> groupedResults = new HashMap<>();
    resultsRep.forEach(evaluationResultRepresentation -> {
        PolicyEvaluationResponse.EvaluationResultRepresentation result = groupedResults.get(evaluationResultRepresentation.getResource().getId());
        ResourceRepresentation resource = evaluationResultRepresentation.getResource();
        if (result == null) {
            groupedResults.put(resource.getId(), evaluationResultRepresentation);
            result = evaluationResultRepresentation;
        }
        if (result.getStatus().equals(DecisionEffect.PERMIT) || (evaluationResultRepresentation.getStatus().equals(DecisionEffect.PERMIT) && result.getStatus().equals(DecisionEffect.DENY))) {
            result.setStatus(DecisionEffect.PERMIT);
        }
        List<ScopeRepresentation> scopes = result.getScopes();
        if (DecisionEffect.PERMIT.equals(result.getStatus())) {
            result.setAllowedScopes(scopes);
        }
        if (resource.getId() != null) {
            if (!scopes.isEmpty()) {
                result.getResource().setName(evaluationResultRepresentation.getResource().getName() + " with scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
            } else {
                result.getResource().setName(evaluationResultRepresentation.getResource().getName());
            }
        } else {
            result.getResource().setName("Any Resource with Scopes " + scopes.stream().flatMap((Function<ScopeRepresentation, Stream<?>>) scopeRepresentation -> Arrays.asList(scopeRepresentation.getName()).stream()).collect(Collectors.toList()));
        }
        List<PolicyEvaluationResponse.PolicyResultRepresentation> policies = result.getPolicies();
        for (PolicyEvaluationResponse.PolicyResultRepresentation policy : new ArrayList<>(evaluationResultRepresentation.getPolicies())) {
            if (!policies.contains(policy)) {
                policies.add(policy);
            }
        }
    });
    response.setResults(groupedResults.values().stream().collect(Collectors.toList()));
    return response;
}
Also used : ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) Arrays(java.util.Arrays) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) HashMap(java.util.HashMap) Function(java.util.function.Function) PolicyRepresentation(org.keycloak.representations.idm.authorization.PolicyRepresentation) PermissionTicket(org.keycloak.authorization.model.PermissionTicket) ArrayList(java.util.ArrayList) PolicyEvaluationService(org.keycloak.authorization.admin.PolicyEvaluationService) UserModel(org.keycloak.models.UserModel) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ResourceServer(org.keycloak.authorization.model.ResourceServer) RealmModel(org.keycloak.models.RealmModel) EnumMap(java.util.EnumMap) Collection(java.util.Collection) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) Decision(org.keycloak.authorization.Decision) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) Stream(java.util.stream.Stream) Result(org.keycloak.authorization.policy.evaluation.Result) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) DecisionEffect(org.keycloak.representations.idm.authorization.DecisionEffect) Comparator(java.util.Comparator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation) Result(org.keycloak.authorization.policy.evaluation.Result) ResourceRepresentation(org.keycloak.representations.idm.authorization.ResourceRepresentation) ClientModel(org.keycloak.models.ClientModel) Function(java.util.function.Function) Scope(org.keycloak.authorization.model.Scope) AccessToken(org.keycloak.representations.AccessToken) PolicyEvaluationResponse(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse) ScopeRepresentation(org.keycloak.representations.idm.authorization.ScopeRepresentation) PolicyResultRepresentation(org.keycloak.representations.idm.authorization.PolicyEvaluationResponse.PolicyResultRepresentation)

Aggregations

HashMap (java.util.HashMap)5 Map (java.util.Map)5 Decision (org.keycloak.authorization.Decision)5 Policy (org.keycloak.authorization.model.Policy)5 ResourcePermission (org.keycloak.authorization.permission.ResourcePermission)3 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)2 DefaultEvaluation (org.keycloak.authorization.policy.evaluation.DefaultEvaluation)2 Result (org.keycloak.authorization.policy.evaluation.Result)2 StoreFactory (org.keycloak.authorization.store.StoreFactory)2 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Comparator (java.util.Comparator)1 EnumMap (java.util.EnumMap)1 List (java.util.List)1 Set (java.util.Set)1 Function (java.util.function.Function)1 Collectors (java.util.stream.Collectors)1 Stream (java.util.stream.Stream)1 PolicyEvaluationService (org.keycloak.authorization.admin.PolicyEvaluationService)1