private Map<String, Object>[] getRoles(Policy policy) { String roles = policy.getConfig().get("roles"); if (roles != null) { try { return JsonSerialization.readValue(roles.getBytes(), Map[].class); } catch (IOException e) { throw new RuntimeException("Could not parse roles [" + roles + "] from policy config [" + policy.getName() + ".", e); } } return new Map[] {}; } }
static String[] getUsers(Policy policy) { String users = policy.getConfig().get("users"); if (users != null) { try { return JsonSerialization.readValue(users.getBytes(), String[].class); } catch (IOException e) { throw new RuntimeException("Could not parse users [" + users + "] from policy config [" + policy.getName() + ".", e); } } return new String[0]; } }
private String[] getClients(Policy policy) { String clients = policy.getConfig().get("clients"); if (clients != null) { try { return JsonSerialization.readValue(clients.getBytes(), String[].class); } catch (IOException e) { throw new RuntimeException("Could not parse clients [" + clients + "] from policy config [" + policy.getName() + "].", e); } } return new String[]{}; } }
@Override public String getName() { if (isUpdated()) return updated.getName(); return cached.getName(); }
@Override public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) { ClientPolicyRepresentation userRep = toRepresentation(policy, authorization); Map<String, String> config = new HashMap<>(); try { RealmModel realm = authorization.getRealm(); config.put("clients", JsonSerialization.writeValueAsString(userRep.getClients().stream().map(id -> realm.getClientById(id).getClientId()).collect(Collectors.toList()))); } catch (IOException cause) { throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause); } representation.setConfig(config); }
private void verifyCircularReference(Policy policy, List<String> ids) { if (!policy.getType().equals("aggregate")) { return; } if (ids.contains(policy.getId())) { throw new RuntimeException("Circular reference found [" + policy.getName() + "]."); } ids.add(policy.getId()); for (Policy associated : policy.getAssociatedPolicies()) { verifyCircularReference(associated, ids); } }
private ScriptModel getScriptModel(final Policy policy, final RealmModel realm, final ScriptingProvider scripting) { String scriptName = policy.getName(); String scriptCode = policy.getConfig().get("code"); String scriptDescription = policy.getDescription(); //TODO lookup script by scriptId instead of creating it every time return scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, scriptName, scriptCode, scriptDescription); }
@Override public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) { UserPolicyRepresentation userRep = toRepresentation(policy, authorizationProvider); Map<String, String> config = new HashMap<>(); try { UserProvider userProvider = authorizationProvider.getKeycloakSession().users(); RealmModel realm = authorizationProvider.getRealm(); config.put("users", JsonSerialization.writeValueAsString(userRep.getUsers().stream().map(id -> userProvider.getUserById(id, realm).getUsername()).collect(Collectors.toList()))); } catch (IOException cause) { throw new RuntimeException("Failed to export user policy [" + policy.getName() + "]", cause); } representation.setConfig(config); }
private void updateClients(Policy policy, Set<String> clients, AuthorizationProvider authorization) { RealmModel realm = authorization.getRealm(); if (clients == null || clients.isEmpty()) { throw new RuntimeException("No client provided."); } Set<String> updatedClients = new HashSet<>(); for (String id : clients) { ClientModel client = realm.getClientByClientId(id); if (client == null) { client = realm.getClientById(id); } if (client == null) { throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. Client [" + id + "] could not be found."); } updatedClients.add(client.getId()); } try { policy.putConfig("clients", JsonSerialization.writeValueAsString(updatedClients)); } catch (IOException cause) { throw new RuntimeException("Failed to serialize clients", cause); } }
@Override public void evaluate(Evaluation evaluation) { Policy policy = evaluation.getPolicy(); AuthorizationProvider authorization = evaluation.getAuthorizationProvider(); EvaluatableScriptAdapter adapter = evaluatableScript.apply(authorization, policy); try { SimpleScriptContext context = new SimpleScriptContext(); context.setAttribute("$evaluation", evaluation, ScriptContext.ENGINE_SCOPE); adapter.eval(context); } catch (Exception e) { throw new RuntimeException("Error evaluating JS Policy [" + policy.getName() + "].", e); } }
@Override public void delete(String id) { if (id == null) return; Policy policy = findById(id, null); if (policy == null) return; cache.invalidateObject(id); Set<String> resources = policy.getResources().stream().map(resource -> resource.getId()).collect(Collectors.toSet()); ResourceServer resourceServer = policy.getResourceServer(); Set<String> resourceTypes = getResourceTypes(resources, resourceServer.getId()); String defaultResourceType = policy.getConfig().get("defaultResourceType"); if (Objects.nonNull(defaultResourceType)) { resourceTypes.add(defaultResourceType); } Set<String> scopes = policy.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()); invalidationEvents.add(PolicyRemovedEvent.create(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId())); cache.policyRemoval(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId(), invalidations); getPolicyStoreDelegate().delete(id); }
private void updateResourceServer(ClientModel clientModel, RoleModel removedRole, ResourceServerStore resourceServerStore, PolicyStore policyStore) { ResourceServer resourceServer = resourceServerStore.findById(clientModel.getId()); if (resourceServer != null) { policyStore.findByType(getId(), resourceServer.getId()).forEach(policy -> { List<Map> roles = new ArrayList<>(); for (Map<String,Object> role : getRoles(policy)) { if (!role.get("id").equals(removedRole.getId())) { Map updated = new HashMap(); updated.put("id", role.get("id")); Object required = role.get("required"); if (required != null) { updated.put("required", required); } roles.add(updated); } } try { if (roles.isEmpty()) { policyStore.delete(policy.getId()); } else { policy.putConfig("roles", JsonSerialization.writeValueAsString(roles)); } } catch (IOException e) { throw new RuntimeException("Error while synchronizing roles with policy [" + policy.getName() + "].", e); } }); } }
this.decisionStrategy = policy.getDecisionStrategy(); this.logic = policy.getLogic(); this.name = policy.getName(); this.description = policy.getDescription(); this.resourceServerId = policy.getResourceServer().getId();
throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. Role [" + roleName + "] could not be found.");
private void updateUsers(Policy policy, AuthorizationProvider authorization, Set<String> users) { KeycloakSession session = authorization.getKeycloakSession(); RealmModel realm = authorization.getRealm(); UserProvider userProvider = session.users(); Set<String> updatedUsers = new HashSet<>(); if (users != null) { for (String userId : users) { UserModel user = null; try { user = userProvider.getUserByUsername(userId, realm); } catch (Exception ignore) { } if (user == null) { user = userProvider.getUserById(userId, realm); } if (user == null) { throw new RuntimeException("Error while updating policy [" + policy.getName() + "]. User [" + userId + "] could not be found."); } updatedUsers.add(user.getId()); } } try { policy.putConfig("users", JsonSerialization.writeValueAsString(updatedUsers)); } catch (IOException cause) { throw new RuntimeException("Failed to serialize users", cause); } }
@Override public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorization) { Map<String, String> config = new HashMap<>(); GroupPolicyRepresentation groupPolicy = toRepresentation(policy, authorization); Set<GroupPolicyRepresentation.GroupDefinition> groups = groupPolicy.getGroups(); for (GroupPolicyRepresentation.GroupDefinition definition: groups) { GroupModel group = authorization.getRealm().getGroupById(definition.getId()); definition.setId(null); definition.setPath(ModelToRepresentation.buildGroupPath(group)); } try { String groupsClaim = groupPolicy.getGroupsClaim(); if (groupsClaim != null) { config.put("groupsClaim", groupsClaim); } config.put("groups", JsonSerialization.writeValueAsString(groups)); } catch (IOException cause) { throw new RuntimeException("Failed to export group policy [" + policy.getName() + "]", cause); } representation.setConfig(config); }
@Override public void onExport(Policy policy, PolicyRepresentation representation, AuthorizationProvider authorizationProvider) { Map<String, String> config = new HashMap<>(); Set<RolePolicyRepresentation.RoleDefinition> roles = toRepresentation(policy, authorizationProvider).getRoles(); for (RolePolicyRepresentation.RoleDefinition roleDefinition : roles) { RoleModel role = authorizationProvider.getRealm().getRoleById(roleDefinition.getId()); if (role.isClientRole()) { roleDefinition.setId(ClientModel.class.cast(role.getContainer()).getClientId() + "/" + role.getName()); } else { roleDefinition.setId(role.getName()); } } try { config.put("roles", JsonSerialization.writeValueAsString(roles)); } catch (IOException cause) { throw new RuntimeException("Failed to export role policy [" + policy.getName() + "]", cause); } representation.setConfig(config); }
throw new RuntimeException("Could not evaluate time-based policy [" + policy.getName() + "].", e);
throw new RuntimeException("Error while synchronizing clients with policy [" + policy.getName() + "].", e);
throw new RuntimeException("Error while synchronizing users with policy [" + policy.getName() + "].", e);