Search in sources :

Example 6 with SearchHelper

use of com.novell.ldapchai.util.SearchHelper in project pwm by pwm-project.

the class LdapOperationsHelper method readAllEntryAttributeValues.

public static Map<String, List<String>> readAllEntryAttributeValues(final ChaiEntry chaiEntry) throws ChaiUnavailableException, ChaiOperationException {
    final SearchHelper searchHelper = new SearchHelper();
    searchHelper.setSearchScope(SearchScope.BASE);
    searchHelper.setFilter("(objectClass=*)");
    final Map<String, Map<String, List<String>>> results = chaiEntry.getChaiProvider().searchMultiValues(chaiEntry.getEntryDN(), searchHelper);
    if (!results.isEmpty()) {
        return results.values().iterator().next();
    }
    return Collections.emptyMap();
}
Also used : SearchHelper(com.novell.ldapchai.util.SearchHelper) Map(java.util.Map) HashMap(java.util.HashMap)

Example 7 with SearchHelper

use of com.novell.ldapchai.util.SearchHelper in project pwm by pwm-project.

the class UserSearchEngine method executeSearch.

private Map<UserIdentity, Map<String, String>> executeSearch(final UserSearchJob userSearchJob, final SessionLabel sessionLabel, final int searchID, final int jobID) throws PwmOperationalException, PwmUnrecoverableException {
    debugOutputTask.conditionallyExecuteTask();
    final SearchHelper searchHelper = new SearchHelper();
    searchHelper.setMaxResults(userSearchJob.getMaxResults());
    searchHelper.setFilter(userSearchJob.getSearchFilter());
    searchHelper.setAttributes(userSearchJob.getReturnAttributes());
    searchHelper.setTimeLimit((int) userSearchJob.getTimeoutMs());
    final String debugInfo;
    {
        final Map<String, String> props = new LinkedHashMap<>();
        props.put("profile", userSearchJob.getLdapProfile().getIdentifier());
        props.put("base", userSearchJob.getContext());
        props.put("maxCount", String.valueOf(searchHelper.getMaxResults()));
        debugInfo = "[" + StringUtil.mapToString(props) + "]";
    }
    log(PwmLogLevel.TRACE, sessionLabel, searchID, jobID, "performing ldap search for user; " + debugInfo);
    final Instant startTime = Instant.now();
    final Map<String, Map<String, String>> results;
    try {
        results = userSearchJob.getChaiProvider().search(userSearchJob.getContext(), searchHelper);
    } catch (ChaiUnavailableException e) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_DIRECTORY_UNAVAILABLE, e.getMessage()));
    } catch (ChaiOperationException e) {
        throw new PwmOperationalException(PwmError.forChaiError(e.getErrorCode()), "ldap error during searchID=" + searchID + ", error=" + e.getMessage());
    }
    final TimeDuration searchDuration = TimeDuration.fromCurrent(startTime);
    if (pwmApplication.getStatisticsManager() != null && pwmApplication.getStatisticsManager().status() == PwmService.STATUS.OPEN) {
        pwmApplication.getStatisticsManager().updateAverageValue(Statistic.AVG_LDAP_SEARCH_TIME, searchDuration.getTotalMilliseconds());
    }
    if (results.isEmpty()) {
        log(PwmLogLevel.TRACE, sessionLabel, searchID, jobID, "no matches from search (" + searchDuration.asCompactString() + "); " + debugInfo);
        return Collections.emptyMap();
    }
    log(PwmLogLevel.TRACE, sessionLabel, searchID, jobID, "found " + results.size() + " results in " + searchDuration.asCompactString() + "; " + debugInfo);
    final Map<UserIdentity, Map<String, String>> returnMap = new LinkedHashMap<>();
    for (final Map.Entry<String, Map<String, String>> entry : results.entrySet()) {
        final String userDN = entry.getKey();
        final Map<String, String> attributeMap = entry.getValue();
        final UserIdentity userIdentity = new UserIdentity(userDN, userSearchJob.getLdapProfile().getIdentifier());
        returnMap.put(userIdentity, attributeMap);
    }
    return returnMap;
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) Instant(java.time.Instant) UserIdentity(password.pwm.bean.UserIdentity) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) PwmOperationalException(password.pwm.error.PwmOperationalException) LinkedHashMap(java.util.LinkedHashMap) ErrorInformation(password.pwm.error.ErrorInformation) TimeDuration(password.pwm.util.java.TimeDuration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 8 with SearchHelper

use of com.novell.ldapchai.util.SearchHelper in project pwm by pwm-project.

the class LdapBrowser method getChildEntries.

private Map<String, Boolean> getChildEntries(final String profile, final String dn) throws ChaiUnavailableException, PwmUnrecoverableException, ChaiOperationException {
    final HashMap<String, Boolean> returnMap = new HashMap<>();
    final ChaiProvider chaiProvider = getChaiProvider(profile);
    if ((dn == null || dn.isEmpty()) && chaiProvider.getDirectoryVendor() == DirectoryVendor.ACTIVE_DIRECTORY) {
        final Set<String> adRootDNList = adRootDNList(profile);
        for (final String rootDN : adRootDNList) {
            returnMap.put(rootDN, true);
        }
    } else {
        final Map<String, Map<String, List<String>>> results;
        {
            final SearchHelper searchHelper = new SearchHelper();
            searchHelper.setFilter("(objectclass=*)");
            searchHelper.setMaxResults(getMaxSizeLimit());
            searchHelper.setAttributes("subordinateCount");
            searchHelper.setSearchScope(SearchScope.ONE);
            results = chaiProvider.searchMultiValues(dn, searchHelper);
        }
        for (final Map.Entry<String, Map<String, List<String>>> entry : results.entrySet()) {
            final String resultDN = entry.getKey();
            final Map<String, List<String>> attributeResults = entry.getValue();
            boolean hasSubs = false;
            if (attributeResults.containsKey("subordinateCount")) {
                // only eDir actually returns this operational attribute
                final Integer subordinateCount = Integer.parseInt(attributeResults.get("subordinateCount").iterator().next());
                hasSubs = subordinateCount > 0;
            } else {
                final SearchHelper searchHelper = new SearchHelper();
                searchHelper.setFilter("(objectclass=*)");
                searchHelper.setMaxResults(1);
                searchHelper.setAttributes(Collections.emptyList());
                searchHelper.setSearchScope(SearchScope.ONE);
                try {
                    final Map<String, Map<String, String>> subSearchResults = chaiProvider.search(resultDN, searchHelper);
                    hasSubs = !subSearchResults.isEmpty();
                } catch (Exception e) {
                    LOGGER.debug("error during subordinate entry count of " + dn + ", error: " + e.getMessage());
                }
            }
            returnMap.put(resultDN, hasSubs);
        }
    }
    return returnMap;
}
Also used : HashMap(java.util.HashMap) SearchHelper(com.novell.ldapchai.util.SearchHelper) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 9 with SearchHelper

use of com.novell.ldapchai.util.SearchHelper in project pwm by pwm-project.

the class FormUtility method validateFormValueUniqueness.

@SuppressWarnings("checkstyle:MethodLength")
public static void validateFormValueUniqueness(final PwmApplication pwmApplication, final Map<FormConfiguration, String> formValues, final Locale locale, final Collection<UserIdentity> excludeDN, final ValidationFlag... validationFlags) throws PwmDataValidationException, PwmUnrecoverableException {
    final boolean allowResultCaching = JavaHelper.enumArrayContainsValue(validationFlags, ValidationFlag.allowResultCaching);
    final boolean checkReadOnlyAndHidden = JavaHelper.enumArrayContainsValue(validationFlags, ValidationFlag.checkReadOnlyAndHidden);
    final Map<String, String> filterClauses = new HashMap<>();
    final Map<String, String> labelMap = new HashMap<>();
    for (final Map.Entry<FormConfiguration, String> entry : formValues.entrySet()) {
        final FormConfiguration formItem = entry.getKey();
        if (formItem.isUnique()) {
            if (checkReadOnlyAndHidden || formItem.isReadonly()) {
                if (checkReadOnlyAndHidden || (formItem.getType() != FormConfiguration.Type.hidden)) {
                    final String value = entry.getValue();
                    if (value != null && value.length() > 0) {
                        filterClauses.put(formItem.getName(), value);
                        labelMap.put(formItem.getName(), formItem.getLabel(locale));
                    }
                }
            }
        }
    }
    if (filterClauses.isEmpty()) {
        // nothing to search
        return;
    }
    final StringBuilder filter = new StringBuilder();
    {
        // outer;
        filter.append("(&");
        // object classes;
        filter.append("(|");
        for (final String objectClass : pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES)) {
            filter.append("(objectClass=").append(objectClass).append(")");
        }
        filter.append(")");
        // attributes
        filter.append("(|");
        for (final Map.Entry<String, String> entry : filterClauses.entrySet()) {
            final String name = entry.getKey();
            final String value = entry.getValue();
            filter.append("(").append(name).append("=").append(StringUtil.escapeLdapFilter(value)).append(")");
        }
        filter.append(")");
        filter.append(")");
    }
    final CacheService cacheService = pwmApplication.getCacheService();
    final CacheKey cacheKey = CacheKey.makeCacheKey(Validator.class, null, "attr_unique_check_" + filter.toString());
    if (allowResultCaching && cacheService != null) {
        final String cacheValue = cacheService.get(cacheKey);
        if (cacheValue != null) {
            if (NEGATIVE_CACHE_HIT.equals(cacheValue)) {
                return;
            } else {
                final ErrorInformation errorInformation = JsonUtil.deserialize(cacheValue, ErrorInformation.class);
                throw new PwmDataValidationException(errorInformation);
            }
        }
    }
    final SearchHelper searchHelper = new SearchHelper();
    searchHelper.setFilterAnd(filterClauses);
    final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(filter.toString()).build();
    final int resultSearchSizeLimit = 1 + (excludeDN == null ? 0 : excludeDN.size());
    final long cacheLifetimeMS = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.CACHE_FORM_UNIQUE_VALUE_LIFETIME_MS));
    final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS);
    try {
        final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
        final Map<UserIdentity, Map<String, String>> results = new LinkedHashMap<>(userSearchEngine.performMultiUserSearch(searchConfiguration, resultSearchSizeLimit, Collections.emptyList(), SessionLabel.SYSTEM_LABEL));
        if (excludeDN != null && !excludeDN.isEmpty()) {
            for (final UserIdentity loopIgnoreIdentity : excludeDN) {
                results.keySet().removeIf(loopIgnoreIdentity::equals);
            }
        }
        if (!results.isEmpty()) {
            final UserIdentity userIdentity = results.keySet().iterator().next();
            if (labelMap.size() == 1) {
                // since only one value searched, it must be that one value
                final String attributeName = labelMap.values().iterator().next();
                LOGGER.trace("found duplicate value for attribute '" + attributeName + "' on entry " + userIdentity);
                final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null, new String[] { attributeName });
                throw new PwmDataValidationException(error);
            }
            // do a compare on a user values to find one that matches.
            for (final Map.Entry<String, String> entry : filterClauses.entrySet()) {
                final String name = entry.getKey();
                final String value = entry.getValue();
                final boolean compareResult;
                try {
                    final ChaiUser theUser = pwmApplication.getProxiedChaiUser(userIdentity);
                    compareResult = theUser.compareStringAttribute(name, value);
                } catch (ChaiOperationException | ChaiUnavailableException e) {
                    final PwmError error = PwmError.forChaiError(e.getErrorCode());
                    throw new PwmUnrecoverableException(error.toInfo());
                }
                if (compareResult) {
                    final String label = labelMap.get(name);
                    LOGGER.trace("found duplicate value for attribute '" + label + "' on entry " + userIdentity);
                    final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null, new String[] { label });
                    throw new PwmDataValidationException(error);
                }
            }
            // user didn't match on the compare.. shouldn't read here but just in case
            final ErrorInformation error = new ErrorInformation(PwmError.ERROR_FIELD_DUPLICATE, null);
            throw new PwmDataValidationException(error);
        }
    } catch (PwmOperationalException e) {
        if (cacheService != null) {
            final String jsonPayload = JsonUtil.serialize(e.getErrorInformation());
            cacheService.put(cacheKey, cachePolicy, jsonPayload);
        }
        throw new PwmDataValidationException(e.getErrorInformation());
    }
    if (allowResultCaching && cacheService != null) {
        cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT);
    }
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) LinkedHashMap(java.util.LinkedHashMap) PwmOperationalException(password.pwm.error.PwmOperationalException) ErrorInformation(password.pwm.error.ErrorInformation) FormConfiguration(password.pwm.config.value.data.FormConfiguration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) CacheKey(password.pwm.svc.cache.CacheKey) CacheService(password.pwm.svc.cache.CacheService) UserIdentity(password.pwm.bean.UserIdentity) PwmError(password.pwm.error.PwmError) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) PwmDataValidationException(password.pwm.error.PwmDataValidationException) CachePolicy(password.pwm.svc.cache.CachePolicy) ChaiUser(com.novell.ldapchai.ChaiUser) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 10 with SearchHelper

use of com.novell.ldapchai.util.SearchHelper in project pwm by pwm-project.

the class LdapTokenMachine method retrieveToken.

public TokenPayload retrieveToken(final TokenKey tokenKey) throws PwmOperationalException, PwmUnrecoverableException {
    final String searchFilter;
    {
        final String storedHash = tokenKey.getStoredHash();
        final SearchHelper tempSearchHelper = new SearchHelper();
        final Map<String, String> filterAttributes = new HashMap<>();
        for (final String loopStr : pwmApplication.getConfig().readSettingAsStringArray(PwmSetting.DEFAULT_OBJECT_CLASSES)) {
            filterAttributes.put("objectClass", loopStr);
        }
        filterAttributes.put(tokenAttribute, storedHash + "*");
        tempSearchHelper.setFilterAnd(filterAttributes);
        searchFilter = tempSearchHelper.getFilter();
    }
    try {
        final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
        final SearchConfiguration searchConfiguration = SearchConfiguration.builder().filter(searchFilter).build();
        final UserIdentity user = userSearchEngine.performSingleUserSearch(searchConfiguration, null);
        if (user == null) {
            return null;
        }
        final UserInfo userInfo = UserInfoFactory.newUserInfoUsingProxy(pwmApplication, null, user, null);
        final String tokenAttributeValue = userInfo.readStringAttribute(tokenAttribute);
        if (tokenAttribute != null && tokenAttributeValue.length() > 0) {
            final String[] splitString = tokenAttributeValue.split(KEY_VALUE_DELIMITER);
            if (splitString.length != 2) {
                final String errorMsg = "error parsing ldap stored token, not enough delimited values";
                final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
                throw new PwmOperationalException(errorInformation);
            }
            return tokenService.fromEncryptedString(splitString[1]);
        }
    } catch (PwmOperationalException e) {
        if (e.getError() == PwmError.ERROR_CANT_MATCH_USER) {
            return null;
        }
        throw e;
    } catch (PwmUnrecoverableException e) {
        final String errorMsg = "unexpected ldap error searching for token: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_TOKEN_INCORRECT, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    return null;
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) UserSearchEngine(password.pwm.ldap.search.UserSearchEngine) UserIdentity(password.pwm.bean.UserIdentity) SearchConfiguration(password.pwm.ldap.search.SearchConfiguration) UserInfo(password.pwm.ldap.UserInfo) PwmUnrecoverableException(password.pwm.error.PwmUnrecoverableException) SearchHelper(com.novell.ldapchai.util.SearchHelper) HashMap(java.util.HashMap) Map(java.util.Map) PwmOperationalException(password.pwm.error.PwmOperationalException)

Aggregations

SearchHelper (com.novell.ldapchai.util.SearchHelper)15 Map (java.util.Map)8 LinkedHashMap (java.util.LinkedHashMap)5 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)4 HashMap (java.util.HashMap)4 PwmUnrecoverableException (password.pwm.error.PwmUnrecoverableException)4 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)3 UserIdentity (password.pwm.bean.UserIdentity)3 ErrorInformation (password.pwm.error.ErrorInformation)3 PwmOperationalException (password.pwm.error.PwmOperationalException)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 TreeMap (java.util.TreeMap)2 SearchConfiguration (password.pwm.ldap.search.SearchConfiguration)2 UserSearchEngine (password.pwm.ldap.search.UserSearchEngine)2 LDAPAttribute (com.novell.ldap.LDAPAttribute)1 LDAPAttributeSet (com.novell.ldap.LDAPAttributeSet)1 LDAPEntry (com.novell.ldap.LDAPEntry)1 LDAPException (com.novell.ldap.LDAPException)1 LDAPSearchConstraints (com.novell.ldap.LDAPSearchConstraints)1