Search in sources :

Example 1 with CachePolicy

use of password.pwm.svc.cache.CachePolicy in project pwm by pwm-project.

the class LdapProfile method readCanonicalDN.

public String readCanonicalDN(final PwmApplication pwmApplication, final String dnValue) throws PwmUnrecoverableException {
    {
        final boolean doCanonicalDnResolve = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_RESOLVE_CANONICAL_DN));
        if (!doCanonicalDnResolve) {
            return dnValue;
        }
    }
    final boolean enableCanonicalCache = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_CANONICAL_ENABLE));
    String canonicalValue = null;
    final CacheKey cacheKey = CacheKey.makeCacheKey(LdapPermissionTester.class, null, "canonicalDN-" + this.getIdentifier() + "-" + dnValue);
    if (enableCanonicalCache) {
        final String cachedDN = pwmApplication.getCacheService().get(cacheKey);
        if (cachedDN != null) {
            canonicalValue = cachedDN;
        }
    }
    if (canonicalValue == null) {
        try {
            final ChaiProvider chaiProvider = this.getProxyChaiProvider(pwmApplication);
            final ChaiEntry chaiEntry = chaiProvider.getEntryFactory().newChaiEntry(dnValue);
            canonicalValue = chaiEntry.readCanonicalDN();
            if (enableCanonicalCache) {
                final long cacheSeconds = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_CANONICAL_SECONDS));
                final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpiration(new TimeDuration(cacheSeconds, TimeUnit.SECONDS));
                pwmApplication.getCacheService().put(cacheKey, cachePolicy, canonicalValue);
            }
            LOGGER.trace("read and cached canonical ldap DN value for input '" + dnValue + "' as '" + canonicalValue + "'");
        } catch (ChaiUnavailableException | ChaiOperationException e) {
            LOGGER.error("error while reading canonicalDN for dn value '" + dnValue + "', error: " + e.getMessage());
            return dnValue;
        }
    }
    return canonicalValue;
}
Also used : ChaiUnavailableException(com.novell.ldapchai.exception.ChaiUnavailableException) CachePolicy(password.pwm.svc.cache.CachePolicy) ChaiProvider(com.novell.ldapchai.provider.ChaiProvider) ChaiEntry(com.novell.ldapchai.ChaiEntry) TimeDuration(password.pwm.util.java.TimeDuration) ChaiOperationException(com.novell.ldapchai.exception.ChaiOperationException) CacheKey(password.pwm.svc.cache.CacheKey)

Example 2 with CachePolicy

use of password.pwm.svc.cache.CachePolicy in project pwm by pwm-project.

the class LdapOperationsHelper method readLdapGuidValue.

public static String readLdapGuidValue(final PwmApplication pwmApplication, final SessionLabel sessionLabel, final UserIdentity userIdentity, final boolean throwExceptionOnError) throws ChaiUnavailableException, PwmUnrecoverableException {
    final boolean enableCache = Boolean.parseBoolean(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_USER_GUID_ENABLE));
    final CacheKey cacheKey = CacheKey.makeCacheKey(LdapOperationsHelper.class, null, "guidValue-" + userIdentity.toDelimitedKey());
    if (enableCache) {
        final String cachedValue = pwmApplication.getCacheService().get(cacheKey);
        if (cachedValue != null) {
            return NULL_CACHE_GUID.equals(cachedValue) ? null : cachedValue;
        }
    }
    final String existingValue = GUIDHelper.readExistingGuidValue(pwmApplication, sessionLabel, userIdentity, throwExceptionOnError);
    final LdapProfile ldapProfile = pwmApplication.getConfig().getLdapProfiles().get(userIdentity.getLdapProfileID());
    final String guidAttributeName = ldapProfile.readSettingAsString(PwmSetting.LDAP_GUID_ATTRIBUTE);
    if (StringUtil.isEmpty(existingValue)) {
        if (!"DN".equalsIgnoreCase(guidAttributeName) && !"VENDORGUID".equalsIgnoreCase(guidAttributeName)) {
            if (ldapProfile.readSettingAsBoolean(PwmSetting.LDAP_GUID_AUTO_ADD)) {
                LOGGER.trace("assigning new GUID to user " + userIdentity);
                return GUIDHelper.assignGuidToUser(pwmApplication, sessionLabel, userIdentity, guidAttributeName);
            }
        }
        final String errorMsg = "unable to resolve GUID value for user " + userIdentity.toString();
        GUIDHelper.processError(errorMsg, throwExceptionOnError);
    }
    if (enableCache) {
        final long cacheSeconds = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.LDAP_CACHE_USER_GUID_SECONDS));
        final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpiration(new TimeDuration(cacheSeconds, TimeUnit.SECONDS));
        final String cacheValue = existingValue == null ? NULL_CACHE_GUID : existingValue;
        pwmApplication.getCacheService().put(cacheKey, cachePolicy, cacheValue);
    }
    return existingValue;
}
Also used : CachePolicy(password.pwm.svc.cache.CachePolicy) TimeDuration(password.pwm.util.java.TimeDuration) LdapProfile(password.pwm.config.profile.LdapProfile) CacheKey(password.pwm.svc.cache.CacheKey)

Example 3 with CachePolicy

use of password.pwm.svc.cache.CachePolicy in project pwm by pwm-project.

the class PeopleSearchDataReader method storeDataInCache.

private static void storeDataInCache(final PwmApplication pwmApplication, final CacheKey cacheKey, final Serializable data) throws PwmUnrecoverableException {
    final long maxCacheSeconds = pwmApplication.getConfig().readSettingAsLong(PwmSetting.PEOPLE_SEARCH_MAX_CACHE_SECONDS);
    if (maxCacheSeconds > 0) {
        final CachePolicy cachePolicy = CachePolicy.makePolicyWithExpirationMS(maxCacheSeconds * 1000);
        pwmApplication.getCacheService().put(cacheKey, cachePolicy, JsonUtil.serialize(data));
    }
}
Also used : CachePolicy(password.pwm.svc.cache.CachePolicy)

Example 4 with CachePolicy

use of password.pwm.svc.cache.CachePolicy 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 5 with CachePolicy

use of password.pwm.svc.cache.CachePolicy in project pwm by pwm-project.

the class PasswordUtility method checkEnteredPassword.

public static PasswordCheckInfo checkEnteredPassword(final PwmApplication pwmApplication, final Locale locale, final ChaiUser user, final UserInfo userInfo, final LoginInfoBean loginInfoBean, final PasswordData password, final PasswordData confirmPassword) throws PwmUnrecoverableException, ChaiUnavailableException {
    if (userInfo == null) {
        throw new NullPointerException("userInfoBean cannot be null");
    }
    boolean pass = false;
    String userMessage = "";
    int errorCode = 0;
    final boolean passwordIsCaseSensitive = userInfo.getPasswordPolicy() == null || userInfo.getPasswordPolicy().getRuleHelper().readBooleanValue(PwmPasswordRule.CaseSensitive);
    final CachePolicy cachePolicy;
    {
        final long cacheLifetimeMS = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.CACHE_PWRULECHECK_LIFETIME_MS));
        cachePolicy = CachePolicy.makePolicyWithExpirationMS(cacheLifetimeMS);
    }
    if (password == null) {
        userMessage = new ErrorInformation(PwmError.PASSWORD_MISSING).toUserStr(locale, pwmApplication.getConfig());
    } else {
        final CacheService cacheService = pwmApplication.getCacheService();
        final CacheKey cacheKey = user != null && userInfo.getUserIdentity() != null ? CacheKey.makeCacheKey(PasswordUtility.class, userInfo.getUserIdentity(), user.getEntryDN() + ":" + password.hash()) : null;
        if (pwmApplication.getConfig().isDevDebugMode()) {
            LOGGER.trace("generated cacheKey for password check request: " + cacheKey);
        }
        try {
            if (cacheService != null && cacheKey != null) {
                final String cachedValue = cacheService.get(cacheKey);
                if (cachedValue != null) {
                    if (NEGATIVE_CACHE_HIT.equals(cachedValue)) {
                        pass = true;
                    } else {
                        LOGGER.trace("cache hit!");
                        final ErrorInformation errorInformation = JsonUtil.deserialize(cachedValue, ErrorInformation.class);
                        throw new PwmDataValidationException(errorInformation);
                    }
                }
            }
            if (!pass) {
                final PwmPasswordRuleValidator pwmPasswordRuleValidator = new PwmPasswordRuleValidator(pwmApplication, userInfo.getPasswordPolicy(), locale);
                final PasswordData oldPassword = loginInfoBean == null ? null : loginInfoBean.getUserCurrentPassword();
                pwmPasswordRuleValidator.testPassword(password, oldPassword, userInfo, user);
                pass = true;
                if (cacheService != null && cacheKey != null) {
                    cacheService.put(cacheKey, cachePolicy, NEGATIVE_CACHE_HIT);
                }
            }
        } catch (PwmDataValidationException e) {
            errorCode = e.getError().getErrorCode();
            userMessage = e.getErrorInformation().toUserStr(locale, pwmApplication.getConfig());
            pass = false;
            if (cacheService != null && cacheKey != null) {
                final String jsonPayload = JsonUtil.serialize(e.getErrorInformation());
                cacheService.put(cacheKey, cachePolicy, jsonPayload);
            }
        }
    }
    final PasswordCheckInfo.MatchStatus matchStatus = figureMatchStatus(passwordIsCaseSensitive, password, confirmPassword);
    if (pass) {
        switch(matchStatus) {
            case EMPTY:
                userMessage = new ErrorInformation(PwmError.PASSWORD_MISSING_CONFIRM).toUserStr(locale, pwmApplication.getConfig());
                break;
            case MATCH:
                userMessage = new ErrorInformation(PwmError.PASSWORD_MEETS_RULES).toUserStr(locale, pwmApplication.getConfig());
                break;
            case NO_MATCH:
                userMessage = new ErrorInformation(PwmError.PASSWORD_DOESNOTMATCH).toUserStr(locale, pwmApplication.getConfig());
                break;
            default:
                userMessage = "";
        }
    }
    final int strength = judgePasswordStrength(pwmApplication.getConfig(), password == null ? null : password.getStringValue());
    return new PasswordCheckInfo(userMessage, pass, strength, matchStatus, errorCode);
}
Also used : ErrorInformation(password.pwm.error.ErrorInformation) PwmDataValidationException(password.pwm.error.PwmDataValidationException) PwmPasswordRuleValidator(password.pwm.util.PwmPasswordRuleValidator) CachePolicy(password.pwm.svc.cache.CachePolicy) PasswordData(password.pwm.util.PasswordData) CacheKey(password.pwm.svc.cache.CacheKey) CacheService(password.pwm.svc.cache.CacheService)

Aggregations

CachePolicy (password.pwm.svc.cache.CachePolicy)5 CacheKey (password.pwm.svc.cache.CacheKey)4 ChaiOperationException (com.novell.ldapchai.exception.ChaiOperationException)2 ChaiUnavailableException (com.novell.ldapchai.exception.ChaiUnavailableException)2 ErrorInformation (password.pwm.error.ErrorInformation)2 PwmDataValidationException (password.pwm.error.PwmDataValidationException)2 CacheService (password.pwm.svc.cache.CacheService)2 TimeDuration (password.pwm.util.java.TimeDuration)2 ChaiEntry (com.novell.ldapchai.ChaiEntry)1 ChaiUser (com.novell.ldapchai.ChaiUser)1 ChaiProvider (com.novell.ldapchai.provider.ChaiProvider)1 SearchHelper (com.novell.ldapchai.util.SearchHelper)1 HashMap (java.util.HashMap)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 UserIdentity (password.pwm.bean.UserIdentity)1 LdapProfile (password.pwm.config.profile.LdapProfile)1 FormConfiguration (password.pwm.config.value.data.FormConfiguration)1 PwmError (password.pwm.error.PwmError)1 PwmOperationalException (password.pwm.error.PwmOperationalException)1