use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.
the class RestUtility method resolveRequestedUsername.
public static RestServlet.TargetUserIdentity resolveRequestedUsername(final RestRequest restRequest, final String username) throws PwmUnrecoverableException {
final PwmApplication pwmApplication = restRequest.getPwmApplication();
if (StringUtil.isEmpty(username)) {
if (restRequest.getRestAuthentication().getType() == RestAuthenticationType.NAMED_SECRET) {
throw PwmUnrecoverableException.newException(PwmError.ERROR_REST_INVOCATION_ERROR, "username field required when using external web services secrets for authentication ");
}
} else {
if (!restRequest.getRestAuthentication().isThirdPartyEnabled()) {
throw PwmUnrecoverableException.newException(PwmError.ERROR_UNAUTHORIZED, "username specified in request, however third party permission is not granted to the authenticated login.");
}
}
if (StringUtil.isEmpty(username)) {
if (restRequest.getRestAuthentication().getType() == RestAuthenticationType.LDAP) {
return new RestServlet.TargetUserIdentity(restRequest, restRequest.getRestAuthentication().getLdapIdentity(), true);
}
}
final String ldapProfileID;
final String effectiveUsername;
if (username.contains("|")) {
final int pipeIndex = username.indexOf("|");
ldapProfileID = username.substring(0, pipeIndex);
effectiveUsername = username.substring(pipeIndex + 1, username.length());
} else {
ldapProfileID = null;
effectiveUsername = username;
}
try {
final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
final UserIdentity userIdentity = userSearchEngine.resolveUsername(effectiveUsername, null, ldapProfileID, restRequest.getSessionLabel());
final LdapProfile ldapProfile = pwmApplication.getConfig().getLdapProfiles().get(userIdentity.getLdapProfileID());
if (ldapProfile != null) {
{
final UserIdentity testUser = ldapProfile.getTestUser(pwmApplication);
if (testUser != null && testUser.canonicalEquals(userIdentity, pwmApplication)) {
final String msg = "rest services can not be invoked against the configured LDAP profile test user";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_REST_INVOCATION_ERROR, msg);
throw new PwmUnrecoverableException(errorInformation);
}
}
{
final UserIdentity proxyUser = ldapProfile.getProxyUser(pwmApplication);
if (proxyUser != null && proxyUser.canonicalEquals(userIdentity, pwmApplication)) {
final String msg = "rest services can not be invoked against the configured LDAP profile proxy user";
final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_REST_INVOCATION_ERROR, msg);
throw new PwmUnrecoverableException(errorInformation);
}
}
}
return new RestServlet.TargetUserIdentity(restRequest, userIdentity, false);
} catch (PwmOperationalException e) {
throw new PwmUnrecoverableException(e.getErrorInformation());
}
}
use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.
the class PeopleSearchDataReader method makeSearchResultsImpl.
private SearchResultBean makeSearchResultsImpl(final PwmRequest pwmRequest, final String username, final boolean includeDisplayName) throws ChaiUnavailableException, PwmUnrecoverableException {
final Instant startTime = Instant.now();
if (username == null || username.length() < 1) {
return new SearchResultBean();
}
final boolean useProxy = useProxy();
final UserSearchEngine userSearchEngine = pwmRequest.getPwmApplication().getUserSearchEngine();
final SearchConfiguration searchConfiguration;
{
final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder();
builder.contexts(pwmRequest.getConfig().readSettingAsStringArray(PwmSetting.PEOPLE_SEARCH_SEARCH_BASE));
builder.enableContextValidation(false);
builder.username(username);
builder.enableValueEscaping(false);
builder.filter(getSearchFilter(pwmRequest.getConfig()));
builder.enableSplitWhitespace(true);
if (!useProxy) {
builder.ldapProfile(pwmRequest.getPwmSession().getUserInfo().getUserIdentity().getLdapProfileID());
builder.chaiProvider(pwmRequest.getPwmSession().getSessionManager().getChaiProvider());
}
searchConfiguration = builder.build();
}
final UserSearchResults results;
final boolean sizeExceeded;
try {
final List<FormConfiguration> searchForm = pwmRequest.getConfig().readSettingAsForm(PwmSetting.PEOPLE_SEARCH_RESULT_FORM);
final int maxResults = (int) pwmRequest.getConfig().readSettingAsLong(PwmSetting.PEOPLE_SEARCH_RESULT_LIMIT);
final Locale locale = pwmRequest.getLocale();
results = userSearchEngine.performMultiUserSearchFromForm(locale, searchConfiguration, maxResults, searchForm, pwmRequest.getSessionLabel());
sizeExceeded = results.isSizeExceeded();
} catch (PwmOperationalException e) {
final ErrorInformation errorInformation = e.getErrorInformation();
LOGGER.error(pwmRequest.getSessionLabel(), errorInformation.toDebugStr());
throw new PwmUnrecoverableException(errorInformation);
}
final List<Map<String, Object>> resultOutput = new ArrayList<>(results.resultsAsJsonOutput(pwmRequest.getPwmApplication(), null));
if (includeDisplayName) {
for (final Map<String, Object> map : resultOutput) {
final String userKey = (String) map.get("userKey");
if (userKey != null) {
final UserIdentity userIdentity = UserIdentity.fromKey(userKey, pwmRequest.getPwmApplication());
final String displayValue = figureDisplaynameValue(pwmRequest, userIdentity);
map.put("_displayName", displayValue);
}
}
}
final TimeDuration searchDuration = TimeDuration.fromCurrent(startTime);
LOGGER.trace(pwmRequest.getPwmSession(), "finished rest peoplesearch search in " + searchDuration.asCompactString() + " not using cache, size=" + results.getResults().size());
final SearchResultBean searchResultBean = new SearchResultBean();
searchResultBean.setSearchResults(resultOutput);
searchResultBean.setSizeExceeded(sizeExceeded);
final String aboutMessage = LocaleHelper.getLocalizedMessage(pwmRequest.getLocale(), Display.Display_SearchResultsInfo.getKey(), pwmRequest.getConfig(), Display.class, new String[] { String.valueOf(results.getResults().size()), searchDuration.asLongString(pwmRequest.getLocale()) });
searchResultBean.setAboutResultMessage(aboutMessage);
return searchResultBean;
}
use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.
the class ExportResponsesCommand method doCommand.
@Override
void doCommand() throws Exception {
final PwmApplication pwmApplication = cliEnvironment.getPwmApplication();
final File outputFile = (File) cliEnvironment.getOptions().get(CliParameters.REQUIRED_NEW_OUTPUT_FILE.getName());
JavaHelper.pause(2000);
final long startTime = System.currentTimeMillis();
final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
final SearchConfiguration searchConfiguration = SearchConfiguration.builder().enableValueEscaping(false).username("*").build();
final String systemRecordDelimiter = System.getProperty("line.separator");
final Writer writer = new BufferedWriter(new PrintWriter(outputFile, PwmConstants.DEFAULT_CHARSET.toString()));
final Map<UserIdentity, Map<String, String>> results = userSearchEngine.performMultiUserSearch(searchConfiguration, Integer.MAX_VALUE, Collections.emptyList(), SessionLabel.SYSTEM_LABEL);
out("searching " + results.size() + " users for stored responses to write to " + outputFile.getAbsolutePath() + "....");
int counter = 0;
for (final UserIdentity identity : results.keySet()) {
final ChaiUser user = pwmApplication.getProxiedChaiUser(identity);
final ResponseSet responseSet = pwmApplication.getCrService().readUserResponseSet(null, identity, user);
if (responseSet != null) {
counter++;
out("found responses for '" + user + "', writing to output.");
final RestChallengesServer.JsonChallengesData outputData = new RestChallengesServer.JsonChallengesData();
outputData.challenges = responseSet.asChallengeBeans(true);
outputData.helpdeskChallenges = responseSet.asHelpdeskChallengeBeans(true);
outputData.minimumRandoms = responseSet.getChallengeSet().minimumResponses();
outputData.username = identity.toDelimitedKey();
writer.write(JsonUtil.serialize(outputData));
writer.write(systemRecordDelimiter);
} else {
out("skipping '" + user.toString() + "', no stored responses.");
}
}
writer.close();
out("output complete, " + counter + " responses exported in " + TimeDuration.fromCurrent(startTime).asCompactString());
}
use of password.pwm.ldap.search.UserSearchEngine in project pwm by pwm-project.
the class LdapPermissionTester method discoverMatchingUsers.
public static Map<UserIdentity, Map<String, String>> discoverMatchingUsers(final PwmApplication pwmApplication, final int maxResultSize, final List<UserPermission> userPermissions, final SessionLabel sessionLabel) throws Exception {
final UserSearchEngine userSearchEngine = pwmApplication.getUserSearchEngine();
final Map<UserIdentity, Map<String, String>> results = new TreeMap<>();
for (final UserPermission userPermission : userPermissions) {
if ((maxResultSize) - results.size() > 0) {
final SearchConfiguration.SearchConfigurationBuilder builder = SearchConfiguration.builder();
switch(userPermission.getType()) {
case ldapQuery:
{
builder.filter(userPermission.getLdapQuery());
if (userPermission.getLdapBase() != null && !userPermission.getLdapBase().isEmpty()) {
builder.enableContextValidation(false);
builder.contexts(Collections.singletonList(userPermission.getLdapBase()));
}
}
break;
case ldapGroup:
{
builder.groupDN(userPermission.getLdapBase());
}
break;
default:
throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unknown permission type: " + userPermission.getType()));
}
if (userPermission.getLdapProfileID() != null && !userPermission.getLdapProfileID().isEmpty() && !userPermission.getLdapProfileID().equals(PwmConstants.PROFILE_ID_ALL)) {
builder.ldapProfile(userPermission.getLdapProfileID());
}
final SearchConfiguration searchConfiguration = builder.build();
try {
results.putAll(userSearchEngine.performMultiUserSearch(searchConfiguration, (maxResultSize) - results.size(), Collections.emptyList(), sessionLabel));
} catch (PwmUnrecoverableException e) {
LOGGER.error("error reading matching users: " + e.getMessage());
throw new PwmOperationalException(e.getErrorInformation());
}
}
}
return results;
}
use of password.pwm.ldap.search.UserSearchEngine 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);
}
}
Aggregations