Search in sources :

Example 11 with SearchRequest

use of com.unboundid.ldap.sdk.SearchRequest in project zm-mailbox by Zimbra.

the class UBIDLdapContext method deleteChildren.

@Override
public void deleteChildren(String dn) throws ServiceException {
    try {
        // use ZLdapFilter instead of just the native Filter so it's
        // convenient for stating
        ZLdapFilter filter = ZLdapFilterFactory.getInstance().anyEntry();
        // Filter filter = Filter.createPresenceFilter(LdapConstants.ATTR_OBJECTCLASS);
        SearchRequest searchRequest = new SearchRequest(dn, SearchScope.ONE, derefAliasPolicy, // size limit
        0, // time limit
        0, // getTypesOnly
        false, ((UBIDLdapFilter) filter).getNative());
        searchRequest.setAttributes("dn");
        SearchResult result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
        List<SearchResultEntry> entries = result.getSearchEntries();
        for (SearchResultEntry entry : entries) {
            deleteEntry(entry.getDN());
        }
    } catch (LDAPException e) {
        throw mapToLdapException("unable to delete children", e);
    }
}
Also used : ZLdapFilter(com.zimbra.cs.ldap.ZLdapFilter) SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchResult(com.unboundid.ldap.sdk.SearchResult) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 12 with SearchRequest

use of com.unboundid.ldap.sdk.SearchRequest in project zm-mailbox by Zimbra.

the class UBIDLdapContext method searchPaged.

@Override
public void searchPaged(SearchLdapOptions searchOptions) throws ServiceException {
    int maxResults = searchOptions.getMaxResults();
    String base = searchOptions.getSearchBase();
    ZLdapFilter filter = searchOptions.getFilter();
    Set<String> binaryAttrs = searchOptions.getBinaryAttrs();
    SearchScope searchScope = ((UBIDSearchScope) searchOptions.getSearchScope()).getNative();
    SearchLdapOptions.SearchLdapVisitor visitor = searchOptions.getVisitor();
    SearchGalResult searchGalResult = searchOptions.getSearchGalResult();
    int pageSize = searchOptions.getResultPageSize();
    int offset = 0;
    boolean pagination = false;
    int limit = 0;
    String prevLastReturnedItemCreateDate = null;
    if (searchGalResult != null) {
        offset = searchGalResult.getLdapMatchCount();
        prevLastReturnedItemCreateDate = searchGalResult.getLdapTimeStamp();
        pagination = searchGalResult.getHadMore();
        limit = searchGalResult.getLimit();
    }
    if (GalOp.sync == searchOptions.getGalOp() && !pagination) {
        limit = 0;
    }
    if (limit == 0) {
        limit = Integer.MAX_VALUE;
    }
    int pageCount = 0;
    int pageOffset = 0;
    int currentPage = 0;
    int index = 0;
    if (offset > 0) {
        pageCount = offset / pageSize;
        pageOffset = offset % pageSize;
    }
    String newToken = "";
    // TODO: this is the legacy behavior, we can make it a param
    boolean wantPartialResult = true;
    try {
        SearchRequest searchRequest = new SearchRequest(base, searchScope, derefAliasPolicy, maxResults, 0, false, ((UBIDLdapFilter) filter).getNative());
        searchRequest.setAttributes(searchOptions.getReturnAttrs());
        // Set the page size and initialize the cookie that we pass back in subsequent pages
        ASN1OctetString cookie = null;
        int count = offset;
        do {
            List<Control> controls = Lists.newArrayListWithCapacity(2);
            if (searchOptions.isUseControl()) {
                controls.add(new SimplePagedResultsControl(pageSize, cookie));
            }
            if (searchOptions.isManageDSAit()) {
                controls.add(new ManageDsaITRequestControl(false));
            }
            searchRequest.setControls(controls.toArray(new Control[0]));
            SearchResult result = null;
            try {
                result = UBIDLdapOperation.SEARCH.execute(this, searchRequest, filter);
            } catch (LDAPException e) {
                if (ResultCode.SIZE_LIMIT_EXCEEDED == e.getResultCode() && wantPartialResult) {
                    // if callsite wants partial result, return them
                    LDAPResult ldapResult = e.toLDAPResult();
                    if (ldapResult instanceof SearchResult) {
                        SearchResult searchResult = (SearchResult) ldapResult;
                        for (SearchResultEntry entry : searchResult.getSearchEntries()) {
                            String dn = entry.getDN();
                            UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
                            if (visitor.wantAttrMapOnVisit()) {
                                visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
                            } else {
                                visitor.visit(dn, ubidAttrs);
                            }
                            newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
                        }
                        if (searchGalResult != null) {
                            searchGalResult.setLdapTimeStamp(newToken);
                            searchGalResult.setLdapMatchCount(1);
                            searchGalResult.setHadMore(true);
                        }
                    }
                }
                // always re-throw
                throw e;
            }
            List<SearchResultEntry> entries = result.getSearchEntries();
            boolean hasMore = false;
            int resultSize = entries.size();
            if (resultSize > (limit + pageOffset)) {
                hasMore = true;
            }
            String leCreateDate = null;
            if (currentPage >= pageCount) {
                leCreateDate = getLastEntryCreationDate(limit + pageOffset, entries);
                if (prevLastReturnedItemCreateDate != null && !prevLastReturnedItemCreateDate.equals(leCreateDate)) {
                    count = 0;
                }
                for (index = pageOffset; index < entries.size() && limit > 0; index++) {
                    SearchResultEntry entry = entries.get(index);
                    String dn = entry.getDN();
                    UBIDAttributes ubidAttrs = new UBIDAttributes(entry);
                    if (visitor.wantAttrMapOnVisit()) {
                        visitor.visit(dn, ubidAttrs.getAttrs(binaryAttrs), ubidAttrs);
                    } else {
                        visitor.visit(dn, ubidAttrs);
                    }
                    limit--;
                    newToken = ubidAttrs.getAttrString("whenCreated") != null ? ubidAttrs.getAttrString("whenCreated") : ubidAttrs.getAttrString("createTimeStamp");
                    if (newToken != null && newToken.equals(leCreateDate)) {
                        count++;
                    }
                }
                prevLastReturnedItemCreateDate = leCreateDate;
                pageOffset = 0;
            }
            cookie = null;
            for (Control c : result.getResponseControls()) {
                if (c instanceof SimplePagedResultsControl) {
                    cookie = ((SimplePagedResultsControl) c).getCookie();
                }
            }
            if (searchGalResult != null && (GalOp.sync == searchOptions.getGalOp())) {
                if (limit == 0 && (((cookie != null) && (cookie.getValueLength() > 0)) || hasMore)) {
                    searchGalResult.setHadMore(true);
                    searchGalResult.setLdapTimeStamp(newToken);
                    searchGalResult.setLdapMatchCount(count);
                } else if (((cookie != null) && (cookie.getValueLength() == 0))) {
                    searchGalResult.setHadMore(false);
                    searchGalResult.setLdapMatchCount(0);
                }
            }
            currentPage++;
        } while ((cookie != null) && (cookie.getValueLength() > 0) && limit > 0);
    } catch (SearchLdapOptions.StopIteratingException e) {
    // break out of the loop and close the ne
    } catch (LDAPException e) {
        throw mapToLdapException("unable to search ldap", e);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SearchRequest(com.unboundid.ldap.sdk.SearchRequest) LDAPResult(com.unboundid.ldap.sdk.LDAPResult) SearchResult(com.unboundid.ldap.sdk.SearchResult) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) SearchGalResult(com.zimbra.cs.account.Provisioning.SearchGalResult) SearchLdapOptions(com.zimbra.cs.ldap.SearchLdapOptions) ZLdapFilter(com.zimbra.cs.ldap.ZLdapFilter) Control(com.unboundid.ldap.sdk.Control) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) AssertionRequestControl(com.unboundid.ldap.sdk.controls.AssertionRequestControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) LDAPException(com.unboundid.ldap.sdk.LDAPException) SearchScope(com.unboundid.ldap.sdk.SearchScope) SimplePagedResultsControl(com.unboundid.ldap.sdk.controls.SimplePagedResultsControl) ManageDsaITRequestControl(com.unboundid.ldap.sdk.controls.ManageDsaITRequestControl) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 13 with SearchRequest

use of com.unboundid.ldap.sdk.SearchRequest in project gitblit by gitblit.

the class LdapConnectionTest method testSearchRequest.

@Test
public void testSearchRequest() throws LDAPException {
    LdapConnection conn = new LdapConnection(settings);
    try {
        assertTrue(conn.connect());
        BindResult br = conn.bind();
        assertNotNull(br);
        SearchRequest req;
        SearchResult result;
        SearchResultEntry entry;
        req = new SearchRequest(ACCOUNT_BASE, SearchScope.BASE, "(CN=UserOne)");
        result = conn.search(req);
        assertNotNull(result);
        assertEquals(0, result.getEntryCount());
        req = new SearchRequest(ACCOUNT_BASE, SearchScope.ONE, "(CN=UserTwo)");
        result = conn.search(req);
        assertNotNull(result);
        assertEquals(0, result.getEntryCount());
        req = new SearchRequest(ACCOUNT_BASE, SearchScope.SUB, "(CN=UserThree)");
        result = conn.search(req);
        assertNotNull(result);
        assertEquals(1, result.getEntryCount());
        entry = result.getSearchEntries().get(0);
        assertEquals("CN=UserThree,OU=Canada," + ACCOUNT_BASE, entry.getDN());
        req = new SearchRequest(ACCOUNT_BASE, SearchScope.SUBORDINATE_SUBTREE, "(CN=UserFour)");
        result = conn.search(req);
        assertNotNull(result);
        assertEquals(1, result.getEntryCount());
        entry = result.getSearchEntries().get(0);
        assertEquals("CN=UserFour,OU=Canada," + ACCOUNT_BASE, entry.getDN());
    } finally {
        conn.close();
    }
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) BindResult(com.unboundid.ldap.sdk.BindResult) SearchResult(com.unboundid.ldap.sdk.SearchResult) LdapConnection(com.gitblit.ldap.LdapConnection) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry) Test(org.junit.Test)

Example 14 with SearchRequest

use of com.unboundid.ldap.sdk.SearchRequest in project keywhiz by square.

the class LdapAuthenticator method rolesFromDN.

private Set<String> rolesFromDN(String userDN) throws LDAPException, GeneralSecurityException {
    SearchRequest searchRequest = new SearchRequest(config.getRoleBaseDN(), SearchScope.SUB, Filter.createEqualityFilter("uniqueMember", userDN));
    Set<String> roles = Sets.newLinkedHashSet();
    LDAPConnection connection = connectionFactory.getLDAPConnection();
    try {
        SearchResult sr = connection.search(searchRequest);
        for (SearchResultEntry sre : sr.getSearchEntries()) {
            X500Name x500Name = new X500Name(sre.getDN());
            RDN[] rdns = x500Name.getRDNs(BCStyle.CN);
            if (rdns.length == 0) {
                logger.error("Could not create X500 Name for role:" + sre.getDN());
            } else {
                String commonName = IETFUtils.valueToString(rdns[0].getFirst().getValue());
                roles.add(commonName);
            }
        }
    } finally {
        connection.close();
    }
    return roles;
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) SearchResult(com.unboundid.ldap.sdk.SearchResult) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 15 with SearchRequest

use of com.unboundid.ldap.sdk.SearchRequest in project keywhiz by square.

the class LdapAuthenticatorTest method setup.

@Before
public void setup() throws Exception {
    LdapLookupConfig config = new LdapLookupConfig("ou=users,dc=example,dc=com", "uid", ImmutableSet.of("admin"), "ou=roles,dc=example,dc=com");
    ldapAuthenticator = new LdapAuthenticator(ldapConnectionFactory, config);
    List<SearchResultEntry> dnResults = Arrays.asList(new SearchResultEntry(PEOPLE_DN, new Attribute[] {}));
    List<SearchResultEntry> roleResults = Arrays.asList(new SearchResultEntry("cn=admin,ou=roles", new Attribute[] {}));
    when(ldapConnectionFactory.getLDAPConnection()).thenReturn(ldapConnection);
    doAnswer(invocation -> dnSearchResult).when(ldapConnection).search(argThat(searchRequest -> Optional.ofNullable(searchRequest).map(SearchRequest::getBaseDN).map(o -> o.equals("ou=users,dc=example,dc=com")).orElse(false)));
    // when(ldapConnection.search(argThat(new IsDnSearch()))).thenReturn(dnSearchResult);
    when(dnSearchResult.getEntryCount()).thenReturn(1);
    when(dnSearchResult.getSearchEntries()).thenReturn(dnResults);
    doAnswer(invocation -> roleSearchResult).when(ldapConnection).search(argThat(searchRequest -> Optional.ofNullable(searchRequest).map(SearchRequest::getBaseDN).map(o -> o.equals("ou=roles,dc=example,dc=com")).orElse(false)));
    // when(ldapConnection.search(argThat(new IsRoleSearch()))).thenReturn(roleSearchResult);
    when(roleSearchResult.getEntryCount()).thenReturn(1);
    when(roleSearchResult.getSearchEntries()).thenReturn(roleResults);
}
Also used : LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) Arrays(java.util.Arrays) ImmutableSet(com.google.common.collect.ImmutableSet) BasicCredentials(io.dropwizard.auth.basic.BasicCredentials) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Mock(org.mockito.Mock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Attribute(com.unboundid.ldap.sdk.Attribute) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) User(keywhiz.auth.User) SearchResult(com.unboundid.ldap.sdk.SearchResult) List(java.util.List) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry) Ignore(org.junit.Ignore) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Optional(java.util.Optional) SearchRequest(com.unboundid.ldap.sdk.SearchRequest) Before(org.junit.Before) SearchRequest(com.unboundid.ldap.sdk.SearchRequest) Attribute(com.unboundid.ldap.sdk.Attribute) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry) Before(org.junit.Before)

Aggregations

SearchRequest (com.unboundid.ldap.sdk.SearchRequest)16 SearchResult (com.unboundid.ldap.sdk.SearchResult)16 LDAPException (com.unboundid.ldap.sdk.LDAPException)13 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)8 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)5 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)4 SimplePagedResultsControl (com.unboundid.ldap.sdk.controls.SimplePagedResultsControl)4 InvalidSimplePageControlException (org.gluu.persist.ldap.exception.InvalidSimplePageControlException)4 LDAPSearchException (com.unboundid.ldap.sdk.LDAPSearchException)3 ZLdapFilter (com.zimbra.cs.ldap.ZLdapFilter)3 MappingException (org.gluu.persist.exception.mapping.MappingException)3 ConnectionException (org.gluu.persist.exception.operation.ConnectionException)3 DuplicateEntryException (org.gluu.persist.exception.operation.DuplicateEntryException)3 SearchException (org.gluu.persist.exception.operation.SearchException)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Attribute (com.unboundid.ldap.sdk.Attribute)2 BindResult (com.unboundid.ldap.sdk.BindResult)2 SearchResultReference (com.unboundid.ldap.sdk.SearchResultReference)2 SearchScope (com.unboundid.ldap.sdk.SearchScope)2 ArrayList (java.util.ArrayList)2