Paul Martin
2016-04-27 c2188a840bc4153ae92112b04b2e06a90d3944aa
src/test/java/com/gitblit/tests/LdapAuthenticationTest.java
@@ -16,23 +16,36 @@
 */
package com.gitblit.tests;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.gitblit.Constants.AccountType;
import com.gitblit.IStoredSettings;
import com.gitblit.Keys;
import com.gitblit.auth.LdapAuthProvider;
import com.gitblit.manager.AuthenticationManager;
import com.gitblit.manager.IUserManager;
import com.gitblit.manager.RuntimeManager;
import com.gitblit.manager.UserManager;
import com.gitblit.models.TeamModel;
import com.gitblit.models.UserModel;
import com.gitblit.tests.mock.MemorySettings;
import com.gitblit.utils.XssFilter;
import com.gitblit.utils.XssFilter.AllowXssFilter;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchScope;
import com.unboundid.ldif.LDIFReader;
/**
@@ -43,12 +56,24 @@
 *
 */
public class LdapAuthenticationTest extends GitblitUnitTest {
    @Rule
    public TemporaryFolder folder = new TemporaryFolder();
   private static final String RESOURCE_DIR = "src/test/resources/ldap/";
   private LdapAuthProvider ldap;
    private File usersConf;
    private LdapAuthProvider ldap;
   static int ldapPort = 1389;
   private static InMemoryDirectoryServer ds;
   private IUserManager userManager;
   private AuthenticationManager auth;
   private MemorySettings settings;
   @BeforeClass
   public static void createInMemoryLdapServer() throws Exception {
@@ -57,40 +82,55 @@
      config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("default", ldapPort));
      config.setSchema(null);
      InMemoryDirectoryServer ds = new InMemoryDirectoryServer(config);
      ds.importFromLDIF(true, new LDIFReader(new FileInputStream(RESOURCE_DIR + "sampledata.ldif")));
      ds = new InMemoryDirectoryServer(config);
      ds.startListening();
   }
   @Before
   public void newLdapAuthentication() {
      ldap = newLdapAuthentication(getSettings());
   public void init() throws Exception {
      ds.clear();
      ds.importFromLDIF(true, new LDIFReader(new FileInputStream(RESOURCE_DIR + "sampledata.ldif")));
      usersConf = folder.newFile("users.conf");
      FileUtils.copyFile(new File(RESOURCE_DIR + "users.conf"), usersConf);
      settings = getSettings();
      ldap = newLdapAuthentication(settings);
      auth = newAuthenticationManager(settings);
   }
   public LdapAuthProvider newLdapAuthentication(IStoredSettings settings) {
      RuntimeManager runtime = new RuntimeManager(settings, GitBlitSuite.BASEFOLDER).start();
      UserManager users = new UserManager(runtime).start();
   private LdapAuthProvider newLdapAuthentication(IStoredSettings settings) {
      XssFilter xssFilter = new AllowXssFilter();
      RuntimeManager runtime = new RuntimeManager(settings, xssFilter, GitBlitSuite.BASEFOLDER).start();
      userManager = new UserManager(runtime, null).start();
      LdapAuthProvider ldap = new LdapAuthProvider();
      ldap.setup(runtime, users);
      ldap.setup(runtime, userManager);
      return ldap;
   }
   private AuthenticationManager newAuthenticationManager(IStoredSettings settings) {
      XssFilter xssFilter = new AllowXssFilter();
      RuntimeManager runtime = new RuntimeManager(settings, xssFilter, GitBlitSuite.BASEFOLDER).start();
      AuthenticationManager auth = new AuthenticationManager(runtime, userManager);
      auth.addAuthenticationProvider(newLdapAuthentication(settings));
      return auth;
   }
   private MemorySettings getSettings() {
      Map<String, Object> backingMap = new HashMap<String, Object>();
      backingMap.put("realm.userService", RESOURCE_DIR + "users.conf");
      backingMap.put("realm.ldap.server", "ldap://localhost:" + ldapPort);
      backingMap.put("realm.ldap.domain", "");
      backingMap.put("realm.ldap.username", "cn=Directory Manager");
      backingMap.put("realm.ldap.password", "password");
      backingMap.put("realm.ldap.backingUserService", "users.conf");
      backingMap.put("realm.ldap.maintainTeams", "true");
      backingMap.put("realm.ldap.accountBase", "OU=Users,OU=UserControl,OU=MyOrganization,DC=MyDomain");
      backingMap.put("realm.ldap.accountPattern", "(&(objectClass=person)(sAMAccountName=${username}))");
      backingMap.put("realm.ldap.groupBase", "OU=Groups,OU=UserControl,OU=MyOrganization,DC=MyDomain");
      backingMap.put("realm.ldap.groupPattern", "(&(objectClass=group)(member=${dn}))");
      backingMap.put("realm.ldap.admins", "UserThree @Git_Admins \"@Git Admins\"");
      backingMap.put("realm.ldap.displayName", "displayName");
      backingMap.put("realm.ldap.email", "email");
      backingMap.put(Keys.realm.userService, usersConf.getAbsolutePath());
      backingMap.put(Keys.realm.ldap.server, "ldap://localhost:" + ldapPort);
//      backingMap.put(Keys.realm.ldap.domain, "");
      backingMap.put(Keys.realm.ldap.username, "cn=Directory Manager");
      backingMap.put(Keys.realm.ldap.password, "password");
//      backingMap.put(Keys.realm.ldap.backingUserService, "users.conf");
      backingMap.put(Keys.realm.ldap.maintainTeams, "true");
      backingMap.put(Keys.realm.ldap.accountBase, "OU=Users,OU=UserControl,OU=MyOrganization,DC=MyDomain");
      backingMap.put(Keys.realm.ldap.accountPattern, "(&(objectClass=person)(sAMAccountName=${username}))");
      backingMap.put(Keys.realm.ldap.groupBase, "OU=Groups,OU=UserControl,OU=MyOrganization,DC=MyDomain");
      backingMap.put(Keys.realm.ldap.groupMemberPattern, "(&(objectClass=group)(member=${dn}))");
      backingMap.put(Keys.realm.ldap.admins, "UserThree @Git_Admins \"@Git Admins\"");
      backingMap.put(Keys.realm.ldap.displayName, "displayName");
      backingMap.put(Keys.realm.ldap.email, "email");
      backingMap.put(Keys.realm.ldap.uid, "sAMAccountName");
      MemorySettings ms = new MemorySettings(backingMap);
      return ms;
@@ -162,4 +202,98 @@
      assertNull(userOneModel);
   }
   @Test
   public void checkIfUsersConfContainsAllUsersFromSampleDataLdif() throws Exception {
      SearchResult searchResult = ds.search("OU=Users,OU=UserControl,OU=MyOrganization,DC=MyDomain", SearchScope.SUB, "objectClass=person");
      assertEquals("Number of ldap users in gitblit user model", searchResult.getEntryCount(), countLdapUsersInUserManager());
   }
   @Test
   public void addingUserInLdapShouldNotUpdateGitBlitUsersAndGroups() throws Exception {
      ds.addEntries(LDIFReader.readEntries(RESOURCE_DIR + "adduser.ldif"));
      ldap.sync();
      assertEquals("Number of ldap users in gitblit user model", 5, countLdapUsersInUserManager());
   }
   @Test
   public void addingUserInLdapShouldUpdateGitBlitUsersAndGroups() throws Exception {
      settings.put(Keys.realm.ldap.synchronize, "true");
      ds.addEntries(LDIFReader.readEntries(RESOURCE_DIR + "adduser.ldif"));
      ldap.sync();
      assertEquals("Number of ldap users in gitblit user model", 6, countLdapUsersInUserManager());
   }
   @Test
   public void addingGroupsInLdapShouldNotUpdateGitBlitUsersAndGroups() throws Exception {
      ds.addEntries(LDIFReader.readEntries(RESOURCE_DIR + "addgroup.ldif"));
      ldap.sync();
      assertEquals("Number of ldap groups in gitblit team model", 0, countLdapTeamsInUserManager());
   }
   @Test
   public void addingGroupsInLdapShouldUpdateGitBlitUsersAndGroups() throws Exception {
      settings.put(Keys.realm.ldap.synchronize, "true");
      ds.addEntries(LDIFReader.readEntries(RESOURCE_DIR + "addgroup.ldif"));
      ldap.sync();
      assertEquals("Number of ldap groups in gitblit team model", 1, countLdapTeamsInUserManager());
   }
   @Test
   public void testAuthenticationManager() {
      UserModel userOneModel = auth.authenticate("UserOne", "userOnePassword".toCharArray(), null);
      assertNotNull(userOneModel);
      assertNotNull(userOneModel.getTeam("git_admins"));
      assertNotNull(userOneModel.getTeam("git_users"));
      assertTrue(userOneModel.canAdmin);
      UserModel userOneModelFailedAuth = auth.authenticate("UserOne", "userTwoPassword".toCharArray(), null);
      assertNull(userOneModelFailedAuth);
      UserModel userTwoModel = auth.authenticate("UserTwo", "userTwoPassword".toCharArray(), null);
      assertNotNull(userTwoModel);
      assertNotNull(userTwoModel.getTeam("git_users"));
      assertNull(userTwoModel.getTeam("git_admins"));
      assertNotNull(userTwoModel.getTeam("git admins"));
      assertTrue(userTwoModel.canAdmin);
      UserModel userThreeModel = auth.authenticate("UserThree", "userThreePassword".toCharArray(), null);
      assertNotNull(userThreeModel);
      assertNotNull(userThreeModel.getTeam("git_users"));
      assertNull(userThreeModel.getTeam("git_admins"));
      assertTrue(userThreeModel.canAdmin);
   }
   @Test
   public void testBindWithUser() {
      settings.put(Keys.realm.ldap.bindpattern, "CN=${username},OU=US,OU=Users,OU=UserControl,OU=MyOrganization,DC=MyDomain");
      settings.put(Keys.realm.ldap.username, "");
      settings.put(Keys.realm.ldap.password, "");
      UserModel userOneModel = auth.authenticate("UserOne", "userOnePassword".toCharArray(), null);
      assertNotNull(userOneModel);
      UserModel userOneModelFailedAuth = auth.authenticate("UserOne", "userTwoPassword".toCharArray(), null);
      assertNull(userOneModelFailedAuth);
   }
   private int countLdapUsersInUserManager() {
      int ldapAccountCount = 0;
      for (UserModel userModel : userManager.getAllUsers()) {
         if (AccountType.LDAP.equals(userModel.accountType)) {
            ldapAccountCount++;
         }
      }
      return ldapAccountCount;
   }
   private int countLdapTeamsInUserManager() {
      int ldapAccountCount = 0;
      for (TeamModel teamModel : userManager.getAllTeams()) {
         if (AccountType.LDAP.equals(teamModel.accountType)) {
            ldapAccountCount++;
         }
      }
      return ldapAccountCount;
   }
}