Search in sources :

Example 1 with AbstractPolicy

use of org.wso2.balana.AbstractPolicy in project carbon-identity-framework by wso2.

the class PAPPolicyStoreReader method readPolicyDTO.

/**
 * Reads PolicyDTO for given registry resource
 *
 * @param resource Registry resource
 * @return PolicyDTO
 * @throws EntitlementException throws, if fails
 */
public PolicyDTO readPolicyDTO(Resource resource) throws EntitlementException {
    String policy = null;
    String policyId = null;
    AbstractPolicy absPolicy = null;
    PolicyDTO dto = null;
    try {
        policy = new String((byte[]) resource.getContent(), Charset.forName("UTF-8"));
        absPolicy = PAPPolicyReader.getInstance(null).getPolicy(policy);
        policyId = absPolicy.getId().toASCIIString();
        dto = new PolicyDTO();
        dto.setPolicyId(policyId);
        dto.setPolicy(policy);
        dto.setActive(Boolean.parseBoolean(resource.getProperty(PDPConstants.ACTIVE_POLICY)));
        String policyOrder = resource.getProperty(PDPConstants.POLICY_ORDER);
        if (policyOrder != null) {
            dto.setPolicyOrder(Integer.parseInt(policyOrder));
        } else {
            dto.setPolicyOrder(0);
        }
        String version = resource.getProperty(PDPConstants.POLICY_VERSION);
        if (version != null) {
            dto.setVersion(version);
        }
        String lastModifiedTime = resource.getProperty(PDPConstants.LAST_MODIFIED_TIME);
        if (lastModifiedTime != null) {
            dto.setLastModifiedTime(lastModifiedTime);
        }
        String lastModifiedUser = resource.getProperty(PDPConstants.LAST_MODIFIED_USER);
        if (lastModifiedUser != null) {
            dto.setLastModifiedUser(lastModifiedUser);
        }
        dto.setPolicyType(resource.getProperty(PDPConstants.POLICY_TYPE));
        String policyReferences = resource.getProperty(PDPConstants.POLICY_REFERENCE);
        if (policyReferences != null && policyReferences.trim().length() > 0) {
            dto.setPolicyIdReferences(policyReferences.split(PDPConstants.ATTRIBUTE_SEPARATOR));
        }
        String policySetReferences = resource.getProperty(PDPConstants.POLICY_SET_REFERENCE);
        if (policySetReferences != null && policySetReferences.trim().length() > 0) {
            dto.setPolicySetIdReferences(policySetReferences.split(PDPConstants.ATTRIBUTE_SEPARATOR));
        }
        // read policy meta data that is used for basic policy editor
        dto.setPolicyEditor(resource.getProperty(PDPConstants.POLICY_EDITOR_TYPE));
        String basicPolicyEditorMetaDataAmount = resource.getProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA_AMOUNT);
        if (basicPolicyEditorMetaDataAmount != null) {
            int amount = Integer.parseInt(basicPolicyEditorMetaDataAmount);
            String[] basicPolicyEditorMetaData = new String[amount];
            for (int i = 0; i < amount; i++) {
                basicPolicyEditorMetaData[i] = resource.getProperty(PDPConstants.BASIC_POLICY_EDITOR_META_DATA + i);
            }
            dto.setPolicyEditorData(basicPolicyEditorMetaData);
        }
        PolicyAttributeBuilder policyAttributeBuilder = new PolicyAttributeBuilder();
        dto.setAttributeDTOs(policyAttributeBuilder.getPolicyMetaDataFromRegistryProperties(resource.getProperties()));
        return dto;
    } catch (RegistryException e) {
        log.error("Error while loading entitlement policy " + policyId + " from PAP policy store", e);
        throw new EntitlementException("Error while loading entitlement policy " + policyId + " from PAP policy store");
    }
}
Also used : EntitlementException(org.wso2.carbon.identity.entitlement.EntitlementException) PolicyDTO(org.wso2.carbon.identity.entitlement.dto.PolicyDTO) AbstractPolicy(org.wso2.balana.AbstractPolicy) PolicyAttributeBuilder(org.wso2.carbon.identity.entitlement.policy.PolicyAttributeBuilder) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 2 with AbstractPolicy

use of org.wso2.balana.AbstractPolicy in project carbon-identity-framework by wso2.

the class DefaultPolicyCollection method getPolicy.

/**
 * Attempts to retrieve a policy based on the given identifier and other constraints. If there
 * are multiple versions of the identified policy that meet the version constraints, then the
 * most recent version is returned.
 *
 * @param identifier
 * @param type
 * @param constraints
 * @return
 */
public AbstractPolicy getPolicy(URI identifier, int type, VersionConstraints constraints) {
    TreeSet<AbstractPolicy> set = policies.get(identifier.toString());
    // if we don't know about this identifier then there's nothing to do
    if (set == null)
        return null;
    // walk through the set starting with the most recent version, looking
    // for a match until we exhaust all known versions
    Iterator<AbstractPolicy> it = set.iterator();
    while (it.hasNext()) {
        AbstractPolicy policy = (AbstractPolicy) (it.next());
        if (constraints.meetsConstraint(policy.getVersion())) {
            // and if it is then we return it
            if (type == PolicyReference.POLICY_REFERENCE) {
                if (policy instanceof Policy)
                    return policy;
            } else {
                if (policy instanceof PolicySet)
                    return policy;
            }
        }
    }
    // we didn't find a match
    return null;
}
Also used : Policy(org.wso2.balana.Policy) AbstractPolicy(org.wso2.balana.AbstractPolicy) AbstractPolicy(org.wso2.balana.AbstractPolicy) PolicySet(org.wso2.balana.PolicySet)

Example 3 with AbstractPolicy

use of org.wso2.balana.AbstractPolicy in project carbon-identity-framework by wso2.

the class DefaultPolicyCollection method getEffectivePolicy.

/**
 * Attempts to retrieve a policy based on the given context. If multiple policies match then
 * this will either throw an exception or wrap the policies under a new PolicySet (depending on
 * how this instance was constructed). If no policies match, then this will return null. See the
 * comment in the class header about how this behaves when multiple versions of the same policy
 * exist.
 *
 * @param context
 * @return
 * @throws EntitlementException
 */
public AbstractPolicy getEffectivePolicy(EvaluationCtx context) throws EntitlementException {
    // setup a list of matching policies
    ArrayList<AbstractPolicy> list = new ArrayList<AbstractPolicy>();
    // get an iterator over all the identifiers
    Iterator<TreeSet<AbstractPolicy>> it = policies.values().iterator();
    while (it.hasNext()) {
        // for each identifier, get only the most recent policy
        AbstractPolicy policy = it.next().first();
        // see if we match
        MatchResult match = policy.match(context);
        int result = match.getResult();
        // if there was an error, we stop right away
        if (result == MatchResult.INDETERMINATE) {
            log.error(match.getStatus().getMessage());
            throw new EntitlementException(match.getStatus().getMessage());
        }
        // if we matched, we keep track of the matching policy...
        if (result == MatchResult.MATCH) {
            if (log.isDebugEnabled()) {
                log.debug("Matching XACML policy found " + policy.getId().toString());
            }
            if ((combiningAlg == null) && (list.size() > 0)) {
                ArrayList<String> code = new ArrayList<String>();
                code.add(Status.STATUS_PROCESSING_ERROR);
                Status status = new Status(code, "too many applicable top-level policies");
            // throw new EntitlementException(status);     // TODO
            }
            list.add(policy);
        }
    }
    // action based on how many policies we found
    switch(list.size()) {
        case 0:
            if (log.isDebugEnabled()) {
                log.debug("No matching XACML policy found");
            }
            return null;
        case 1:
            return ((AbstractPolicy) (list.get(0)));
        default:
            return new PolicySet(parentId, combiningAlg, null, list);
    }
}
Also used : Status(org.wso2.balana.ctx.Status) EntitlementException(org.wso2.carbon.identity.entitlement.EntitlementException) TreeSet(java.util.TreeSet) AbstractPolicy(org.wso2.balana.AbstractPolicy) ArrayList(java.util.ArrayList) MatchResult(org.wso2.balana.MatchResult) PolicySet(org.wso2.balana.PolicySet)

Example 4 with AbstractPolicy

use of org.wso2.balana.AbstractPolicy in project carbon-identity-framework by wso2.

the class CarbonPolicyFinder method init.

private synchronized void init() {
    if (initFinish) {
        return;
    }
    log.info("Initializing of policy store is started at :  " + new Date());
    String maxEntries = EntitlementServiceComponent.getEntitlementConfig().getEngineProperties().getProperty(PDPConstants.MAX_POLICY_REFERENCE_ENTRIES);
    if (maxEntries != null) {
        try {
            maxReferenceCacheEntries = Integer.parseInt(maxEntries.trim());
        } catch (Exception e) {
        // ignore
        }
    }
    policyReferenceCache = new LinkedHashMap<URI, AbstractPolicy>() {

        @Override
        protected boolean removeEldestEntry(Map.Entry eldest) {
            // oldest entry of the cache would be removed when max cache size become, i.e 50
            return size() > maxReferenceCacheEntries;
        }
    };
    PolicyCombiningAlgorithm policyCombiningAlgorithm = null;
    // get registered finder modules
    Map<PolicyFinderModule, Properties> finderModules = EntitlementServiceComponent.getEntitlementConfig().getPolicyFinderModules();
    if (finderModules != null) {
        this.finderModules = new ArrayList<PolicyFinderModule>(finderModules.keySet());
    }
    PolicyCollection tempPolicyCollection = null;
    // get policy collection
    Map<PolicyCollection, Properties> policyCollections = EntitlementServiceComponent.getEntitlementConfig().getPolicyCollections();
    if (policyCollections != null && policyCollections.size() > 0) {
        tempPolicyCollection = policyCollections.entrySet().iterator().next().getKey();
    } else {
        tempPolicyCollection = new SimplePolicyCollection();
    }
    // get policy reader
    policyReader = PolicyReader.getInstance(finder);
    if (this.finderModules != null && this.finderModules.size() > 0) {
        // find policy combining algorithm.
        // here we can get policy data store by using EntitlementAdminEngine. But we are not
        // use it here.  As we need not to have a dependant on EntitlementAdminEngine
        PolicyDataStore policyDataStore;
        Map<PolicyDataStore, Properties> dataStoreModules = EntitlementServiceComponent.getEntitlementConfig().getPolicyDataStore();
        if (dataStoreModules != null && dataStoreModules.size() > 0) {
            policyDataStore = dataStoreModules.entrySet().iterator().next().getKey();
        } else {
            policyDataStore = new DefaultPolicyDataStore();
        }
        policyCombiningAlgorithm = policyDataStore.getGlobalPolicyAlgorithm();
        tempPolicyCollection.setPolicyCombiningAlgorithm(policyCombiningAlgorithm);
        for (PolicyFinderModule finderModule : this.finderModules) {
            log.info("Start retrieving policies from " + finderModule + " at : " + new Date());
            String[] policies = finderModule.getActivePolicies();
            for (int a = 0; a < policies.length; a++) {
                String policy = policies[a];
                AbstractPolicy abstractPolicy = policyReader.getPolicy(policy);
                if (abstractPolicy != null) {
                    PolicyDTO policyDTO = new PolicyDTO();
                    policyDTO.setPolicyId(abstractPolicy.getId().toString());
                    policyDTO.setPolicyOrder(a);
                    policyCollectionOrder.add(policyDTO);
                    tempPolicyCollection.addPolicy(abstractPolicy);
                }
            }
            log.info("Finish retrieving policies from " + finderModule + " at : " + new Date());
        }
    } else {
        log.warn("No Carbon policy finder modules are registered");
    }
    policyCollection = tempPolicyCollection;
    initFinish = true;
    log.info("Initializing of policy store is finished at :  " + new Date());
}
Also used : DefaultPolicyDataStore(org.wso2.carbon.identity.entitlement.policy.store.DefaultPolicyDataStore) PolicyDataStore(org.wso2.carbon.identity.entitlement.policy.store.PolicyDataStore) PolicyCollection(org.wso2.carbon.identity.entitlement.policy.collection.PolicyCollection) SimplePolicyCollection(org.wso2.carbon.identity.entitlement.policy.collection.SimplePolicyCollection) Properties(java.util.Properties) URI(java.net.URI) PolicyCombiningAlgorithm(org.wso2.balana.combine.PolicyCombiningAlgorithm) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) EntitlementException(org.wso2.carbon.identity.entitlement.EntitlementException) PolicyDTO(org.wso2.carbon.identity.entitlement.dto.PolicyDTO) AbstractPolicy(org.wso2.balana.AbstractPolicy) SimplePolicyCollection(org.wso2.carbon.identity.entitlement.policy.collection.SimplePolicyCollection) DefaultPolicyDataStore(org.wso2.carbon.identity.entitlement.policy.store.DefaultPolicyDataStore) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 5 with AbstractPolicy

use of org.wso2.balana.AbstractPolicy in project carbon-identity-framework by wso2.

the class CarbonPolicyFinder method findPolicy.

@Override
public PolicyFinderResult findPolicy(EvaluationCtx context) {
    if (EntitlementEngine.getInstance().getPolicyCache().isInvalidate()) {
        init(this.finder);
        policyReferenceCache.clear();
        EntitlementEngine.getInstance().clearDecisionCache();
        EntitlementEngine.getInstance().resetCacheInvalidateState();
        if (log.isDebugEnabled()) {
            int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
            log.debug("Invalidation cache message is received. " + "Re-initialized policy finder module of current node and invalidate decision " + "caching for tenantId : " + tenantId);
        }
    } else {
        Collection<PolicyStatus> policies = EntitlementEngine.getInstance().getPolicyCache().getInvalidatedPolicies();
        if (policies != null) {
            if (policies.size() > 0) {
                synchronized (policies) {
                    boolean isReorder = false;
                    policyReferenceCache.clear();
                    EntitlementEngine.getInstance().clearDecisionCache();
                    for (PolicyStatus policyStatus : policies) {
                        if (EntitlementConstants.PolicyPublish.ACTION_DELETE.equals(policyStatus.getPolicyAction())) {
                            policyCollection.deletePolicy(policyStatus.getPolicyId());
                            policyCollectionOrder.remove(new PolicyDTO(policyStatus.getPolicyId()));
                        } else if (EntitlementConstants.PolicyPublish.ACTION_UPDATE.equals(policyStatus.getPolicyAction())) {
                            AbstractPolicy abstractPolicy = loadPolicy(policyStatus.getPolicyId());
                            policyCollection.addPolicy(abstractPolicy);
                        } else if (EntitlementConstants.PolicyPublish.ACTION_CREATE.equals(policyStatus.getPolicyAction())) {
                            AbstractPolicy abstractPolicy = loadPolicy(policyStatus.getPolicyId());
                            policyCollection.addPolicy(abstractPolicy);
                            isReorder = true;
                        } else if (EntitlementConstants.PolicyPublish.ACTION_ORDER.equals(policyStatus.getPolicyAction())) {
                            int order = getPolicyOrder(policyStatus.getPolicyId());
                            if (order != -1) {
                                PolicyDTO policyDTO = new PolicyDTO(policyStatus.getPolicyId());
                                if (policyCollectionOrder.indexOf(policyDTO) != -1) {
                                    policyCollectionOrder.get(policyCollectionOrder.indexOf(policyDTO)).setPolicyOrder(order);
                                    isReorder = true;
                                }
                            }
                        }
                    }
                    if (isReorder) {
                        orderPolicyCache();
                    }
                    policies.clear();
                }
            }
        }
    }
    try {
        AbstractPolicy policy = policyCollection.getEffectivePolicy(context);
        if (policy == null) {
            return new PolicyFinderResult();
        } else {
            return new PolicyFinderResult(policy);
        }
    } catch (EntitlementException e) {
        ArrayList<String> code = new ArrayList<String>();
        code.add(Status.STATUS_PROCESSING_ERROR);
        Status status = new Status(code, e.getMessage());
        return new PolicyFinderResult(status);
    }
}
Also used : Status(org.wso2.balana.ctx.Status) PolicyStatus(org.wso2.carbon.identity.entitlement.cache.PolicyStatus) EntitlementException(org.wso2.carbon.identity.entitlement.EntitlementException) PolicyDTO(org.wso2.carbon.identity.entitlement.dto.PolicyDTO) PolicyFinderResult(org.wso2.balana.finder.PolicyFinderResult) PolicyStatus(org.wso2.carbon.identity.entitlement.cache.PolicyStatus) AbstractPolicy(org.wso2.balana.AbstractPolicy) ArrayList(java.util.ArrayList)

Aggregations

AbstractPolicy (org.wso2.balana.AbstractPolicy)14 EntitlementException (org.wso2.carbon.identity.entitlement.EntitlementException)8 ParsingException (org.wso2.balana.ParsingException)5 PolicyDTO (org.wso2.carbon.identity.entitlement.dto.PolicyDTO)5 ArrayList (java.util.ArrayList)4 PolicySet (org.wso2.balana.PolicySet)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 URI (java.net.URI)3 URISyntaxException (java.net.URISyntaxException)3 LinkedHashMap (java.util.LinkedHashMap)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 Element (org.w3c.dom.Element)3 MatchResult (org.wso2.balana.MatchResult)3 Status (org.wso2.balana.ctx.Status)3 PolicyFinderResult (org.wso2.balana.finder.PolicyFinderResult)3 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)3 Map (java.util.Map)2 Policy (org.wso2.balana.Policy)2 PAPPolicyStoreManager (org.wso2.carbon.identity.entitlement.pap.store.PAPPolicyStoreManager)2