Copilot commented on code in PR #13945:
URL: https://github.com/apache/cloudstack/pull/13945#discussion_r3967923259


##########
plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImpl.java:
##########
@@ -327,27 +342,30 @@ public List<LdapUser> searchUsers(final String username, 
final LdapContext conte
         final List<LdapUser> users = new ArrayList<LdapUser>();
         NamingEnumeration<SearchResult> results;
         do {
-            results = context.search(basedn, generateSearchFilter(username, 
domainId), searchControls);
+            results = context.search(basedn, generateSearchFilter(username, 
domainId, restrictToLinkedGroups), searchControls);
             while (results.hasMoreElements()) {
                 final SearchResult result = results.nextElement();
                 if (!isUserDisabled(result)) {
                     users.add(createUser(result, domainId));
                 }
             }
-            Control[] contextControls = context.getResponseControls();
-            if (contextControls != null) {
-                for (Control control : contextControls) {
-                    if (control instanceof PagedResultsResponseControl) {
-                        PagedResultsResponseControl prrc = 
(PagedResultsResponseControl) control;
-                        cookie = prrc.getCookie();
-                    }
-                }
-            } else {
-                logger.info("No controls were sent from the ldap server");
-            }
+            cookie = extractPagedResultsCookie(context.getResponseControls());
             context.setRequestControls(new Control[] {new 
PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
         } while (cookie != null);
 
         return users;
     }
+
+    private byte[] extractPagedResultsCookie(Control[] contextControls) {
+        if (contextControls == null) {
+            logger.info("No controls were sent from the ldap server");
+            return null;
+        }
+        for (Control control : contextControls) {
+            if (control instanceof PagedResultsResponseControl) {
+                return ((PagedResultsResponseControl) control).getCookie();
+            }
+        }
+        return null;
+    }

Review Comment:
   LDAP paging commonly signals ‘no more pages’ with an empty cookie 
(zero-length byte array), not only `null`. With the current `do { ... } while 
(cookie != null)` condition, an empty cookie would keep the loop running and 
can cause repeated page fetches (potential infinite loop). Treat empty cookies 
as terminal (e.g., normalize `cookie` to `null` when `cookie.length == 0`) and 
add a unit test to cover the empty-cookie case.



##########
plugins/user-authenticators/ldap/src/main/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImpl.java:
##########
@@ -327,27 +342,30 @@ public List<LdapUser> searchUsers(final String username, 
final LdapContext conte
         final List<LdapUser> users = new ArrayList<LdapUser>();
         NamingEnumeration<SearchResult> results;
         do {
-            results = context.search(basedn, generateSearchFilter(username, 
domainId), searchControls);
+            results = context.search(basedn, generateSearchFilter(username, 
domainId, restrictToLinkedGroups), searchControls);
             while (results.hasMoreElements()) {
                 final SearchResult result = results.nextElement();
                 if (!isUserDisabled(result)) {
                     users.add(createUser(result, domainId));
                 }
             }
-            Control[] contextControls = context.getResponseControls();
-            if (contextControls != null) {
-                for (Control control : contextControls) {
-                    if (control instanceof PagedResultsResponseControl) {
-                        PagedResultsResponseControl prrc = 
(PagedResultsResponseControl) control;
-                        cookie = prrc.getCookie();
-                    }
-                }
-            } else {
-                logger.info("No controls were sent from the ldap server");
-            }
+            cookie = extractPagedResultsCookie(context.getResponseControls());
             context.setRequestControls(new Control[] {new 
PagedResultsControl(pageSize, cookie, Control.CRITICAL)});
         } while (cookie != null);

Review Comment:
   LDAP paging commonly signals ‘no more pages’ with an empty cookie 
(zero-length byte array), not only `null`. With the current `do { ... } while 
(cookie != null)` condition, an empty cookie would keep the loop running and 
can cause repeated page fetches (potential infinite loop). Treat empty cookies 
as terminal (e.g., normalize `cookie` to `null` when `cookie.length == 0`) and 
add a unit test to cover the empty-cookie case.



##########
plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImplTest.java:
##########
@@ -0,0 +1,170 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package org.apache.cloudstack.ldap;
+
+import com.cloud.user.Account;
+import org.apache.cloudstack.ldap.dao.LdapTrustMapDao;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.Control;
+import javax.naming.ldap.LdapContext;
+import javax.naming.ldap.PagedResultsResponseControl;
+
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Regression tests: creating an ldap account must not fail just because 
another
+ * account is already linked to an ldap group in the domain; browsing/importing
+ * still honours that group scope.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class OpenLdapUserManagerImplTest {
+
+    private static final Long DOMAIN_ID = 1L;
+    private static final String LINKED_GROUP = "cn=test 
admins,ou=groups,dc=my,dc=domain,dc=com";
+
+    private OpenLdapUserManagerImpl openLdapUserManager;
+
+    private MockedStatic<LdapConfiguration> ldapConfigurationMockedStatic;
+
+    @Mock
+    private LdapConfiguration ldapConfigurationMock;
+
+    @Mock
+    private LdapTrustMapDao ldapTrustMapDaoMock;
+
+    @Mock
+    private LdapContext ldapContextMock;
+
+    @Before
+    public void setup() throws Exception {
+        // getUserMemberOfAttribute is static, unlike its LdapConfiguration 
siblings; mock statically.
+        ldapConfigurationMockedStatic = 
Mockito.mockStatic(LdapConfiguration.class, Mockito.CALLS_REAL_METHODS);
+        
when(LdapConfiguration.getUserMemberOfAttribute(any())).thenReturn("memberOf");
+
+        openLdapUserManager = new 
OpenLdapUserManagerImpl(ldapConfigurationMock);
+        openLdapUserManager._ldapTrustMapDao = ldapTrustMapDaoMock;
+
+        
when(ldapConfigurationMock.getScope()).thenReturn(SearchControls.SUBTREE_SCOPE);
+        when(ldapConfigurationMock.getReturnAttributes(any())).thenReturn(new 
String[]{"uid"});
+        
when(ldapConfigurationMock.getSearchGroupPrinciple(any())).thenReturn(null);
+        
when(ldapConfigurationMock.getBaseDn(any())).thenReturn("dc=my,dc=domain,dc=com");
+        
when(ldapConfigurationMock.getUsernameAttribute(any())).thenReturn("uid");
+        
when(ldapConfigurationMock.getUserObject(any())).thenReturn("inetOrgPerson");
+        when(ldapConfigurationMock.getLdapPageSize(any())).thenReturn(1000);
+
+        LdapTrustMapVO linkedGroup = new LdapTrustMapVO(DOMAIN_ID, 
LdapManager.LinkType.GROUP, LINKED_GROUP, Account.Type.NORMAL, 5L);
+        
when(ldapTrustMapDaoMock.searchByDomainId(anyLong())).thenReturn(Collections.singletonList(linkedGroup));
+
+        NamingEnumeration<SearchResult> noResults = 
mock(NamingEnumeration.class);
+        when(noResults.hasMoreElements()).thenReturn(false);
+        when(ldapContextMock.search(any(String.class), any(String.class), 
any(SearchControls.class))).thenReturn(noResults);
+        when(ldapContextMock.getResponseControls()).thenReturn(null);
+    }
+
+    @After
+    public void tearDown() {
+        ldapConfigurationMockedStatic.close();

Review Comment:
   Using a long-lived static mock that’s created in `@Before` and closed in 
`@After` can leak across the test suite if `setup()` fails before 
assigning/initializing the static mock (JUnit4 won’t run `@After` when 
`@Before` fails). Consider scoping the static mock with try-with-resources 
inside each test (or guarding `close()` with a null check) to avoid cross-test 
contamination and brittle failures.



##########
plugins/user-authenticators/ldap/src/test/java/org/apache/cloudstack/ldap/OpenLdapUserManagerImplTest.java:
##########
@@ -0,0 +1,170 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+package org.apache.cloudstack.ldap;
+
+import com.cloud.user.Account;
+import org.apache.cloudstack.ldap.dao.LdapTrustMapDao;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.Control;
+import javax.naming.ldap.LdapContext;
+import javax.naming.ldap.PagedResultsResponseControl;
+
+import java.util.Collections;
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Regression tests: creating an ldap account must not fail just because 
another
+ * account is already linked to an ldap group in the domain; browsing/importing
+ * still honours that group scope.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class OpenLdapUserManagerImplTest {
+
+    private static final Long DOMAIN_ID = 1L;
+    private static final String LINKED_GROUP = "cn=test 
admins,ou=groups,dc=my,dc=domain,dc=com";
+
+    private OpenLdapUserManagerImpl openLdapUserManager;
+
+    private MockedStatic<LdapConfiguration> ldapConfigurationMockedStatic;
+
+    @Mock
+    private LdapConfiguration ldapConfigurationMock;
+
+    @Mock
+    private LdapTrustMapDao ldapTrustMapDaoMock;
+
+    @Mock
+    private LdapContext ldapContextMock;
+
+    @Before
+    public void setup() throws Exception {
+        // getUserMemberOfAttribute is static, unlike its LdapConfiguration 
siblings; mock statically.
+        ldapConfigurationMockedStatic = 
Mockito.mockStatic(LdapConfiguration.class, Mockito.CALLS_REAL_METHODS);
+        
when(LdapConfiguration.getUserMemberOfAttribute(any())).thenReturn("memberOf");

Review Comment:
   Using a long-lived static mock that’s created in `@Before` and closed in 
`@After` can leak across the test suite if `setup()` fails before 
assigning/initializing the static mock (JUnit4 won’t run `@After` when 
`@Before` fails). Consider scoping the static mock with try-with-resources 
inside each test (or guarding `close()` with a null check) to avoid cross-test 
contamination and brittle failures.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to