]> source.dussan.org Git - archiva.git/commitdiff
move ldap role mapper to ldap common
authorOlivier Lamy <olamy@apache.org>
Fri, 4 Jan 2013 19:00:15 +0000 (19:00 +0000)
committerOlivier Lamy <olamy@apache.org>
Fri, 4 Jan 2013 19:00:15 +0000 (19:00 +0000)
git-svn-id: https://svn.apache.org/repos/asf/archiva/redback/redback-core/trunk@1429033 13f79535-47bb-0310-9956-ffa450edef68

redback-common/redback-common-ldap/pom.xml
redback-common/redback-common-ldap/src/main/java/org/apache/archiva/redback/common/ldap/role/DefaultLdapRoleMapper.java [new file with mode: 0644]
redback-common/redback-common-ldap/src/main/java/org/apache/archiva/redback/common/ldap/role/LdapRoleMapper.java [new file with mode: 0644]
redback-common/redback-common-ldap/src/test/java/org/apache/archiva/redback/common/ldap/role/TestLdapRoleMapper.java [new file with mode: 0644]
redback-common/redback-common-ldap/src/test/resources/spring-context-role-mapper.xml [new file with mode: 0755]
redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/main/java/org/apache/archiva/redback/rbac/ldap/DefaultLdapRoleMapper.java [deleted file]
redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/main/java/org/apache/archiva/redback/rbac/ldap/LdapRoleMapper.java [deleted file]
redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/test/java/org/apache/archiva/redback/rbac/ldap/TestLdapRoleMapper.java [deleted file]
redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/test/resources/spring-context.xml

index b54570171e2ac393805cce84dc63ffb9676ef13d..7f945e6d821a5008d7f8310ff9f9db62612affee 100644 (file)
       <groupId>commons-lang</groupId>
       <artifactId>commons-lang</artifactId>
     </dependency>
-    <!--
-    <dependency>
-      <groupId>org.apache.directory.shared</groupId>
-      <artifactId>shared-ldap-client-api</artifactId>
-    </dependency>
-    -->
+
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.easytesting</groupId>
+      <artifactId>fest-assert</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.archiva.redback.components</groupId>
+      <artifactId>spring-apacheds</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.archiva.redback</groupId>
+      <artifactId>redback-policy</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 
   <build>
           </instructions>
         </configuration>
       </plugin>
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>allocate-ldap-port</id>
+            <phase>process-classes</phase>
+            <goals>
+              <goal>reserve-network-port</goal>
+            </goals>
+            <configuration>
+              <portNames>
+                <portName>ldapPort</portName>
+              </portNames>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-surefire-plugin</artifactId>
+        <configuration>
+          <systemPropertyVariables>
+            <ldapPort>${ldapPort}</ldapPort>
+            <basedir>${basedir}</basedir>
+          </systemPropertyVariables>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
diff --git a/redback-common/redback-common-ldap/src/main/java/org/apache/archiva/redback/common/ldap/role/DefaultLdapRoleMapper.java b/redback-common/redback-common-ldap/src/main/java/org/apache/archiva/redback/common/ldap/role/DefaultLdapRoleMapper.java
new file mode 100644 (file)
index 0000000..721ea61
--- /dev/null
@@ -0,0 +1,386 @@
+package org.apache.archiva.redback.common.ldap.role;
+/*
+ * 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.
+ */
+
+import org.apache.archiva.redback.common.ldap.MappingException;
+import org.apache.archiva.redback.common.ldap.connection.LdapConnection;
+import org.apache.archiva.redback.common.ldap.connection.LdapConnectionFactory;
+import org.apache.archiva.redback.common.ldap.connection.LdapException;
+import org.apache.archiva.redback.configuration.UserConfiguration;
+import org.apache.archiva.redback.configuration.UserConfigurationKeys;
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Olivier Lamy
+ * @since 2.1
+ */
+@Service( "ldapRoleMapper#default" )
+public class DefaultLdapRoleMapper
+    implements LdapRoleMapper
+{
+
+    private Logger log = LoggerFactory.getLogger( getClass() );
+
+    @Inject
+    private LdapConnectionFactory ldapConnectionFactory;
+
+    @Inject
+    @Named( value = "userConfiguration#default" )
+    private UserConfiguration userConf;
+
+    //---------------------------
+    // fields
+    //---------------------------
+
+    private String ldapGroupClass = "groupOfUniqueNames";
+
+    private String groupsDn;
+
+    private String baseDn;
+
+    @PostConstruct
+    public void initialize()
+    {
+        this.ldapGroupClass = userConf.getString( UserConfigurationKeys.LDAP_GROUPS_CLASS, this.ldapGroupClass );
+
+        this.groupsDn = userConf.getString( UserConfigurationKeys.LDAP_GROUPS_BASEDN, this.groupsDn );
+
+        this.baseDn = userConf.getString( UserConfigurationKeys.LDAP_BASEDN, this.baseDn );
+    }
+
+    public String getLdapGroup( String role )
+    {
+        return userConf.getString( UserConfigurationKeys.LDAP_GROUPS_ROLE_START_KEY + role );
+    }
+
+    public List<String> getAllGroups()
+        throws MappingException
+    {
+        LdapConnection ldapConnection = null;
+
+        NamingEnumeration<SearchResult> namingEnumeration = null;
+        try
+        {
+            ldapConnection = ldapConnectionFactory.getConnection();
+
+            DirContext context = ldapConnection.getDirContext();
+
+            SearchControls searchControls = new SearchControls();
+
+            searchControls.setDerefLinkFlag( true );
+            searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE );
+
+            String filter = "objectClass=" + getLdapGroupClass();
+
+            namingEnumeration = context.search( getGroupsDn(), filter, searchControls );
+
+            List<String> allGroups = new ArrayList<String>();
+
+            while ( namingEnumeration.hasMore() )
+            {
+                SearchResult searchResult = namingEnumeration.next();
+
+                String groupName = searchResult.getName();
+                // cn=blabla we only want bla bla
+                groupName = StringUtils.substringAfter( groupName, "=" );
+
+                log.debug( "found groupName: '{}", groupName );
+
+                allGroups.add( groupName );
+
+            }
+
+            return allGroups;
+        }
+        catch ( LdapException e )
+        {
+            throw new MappingException( e.getMessage(), e );
+        }
+        catch ( NamingException e )
+        {
+            throw new MappingException( e.getMessage(), e );
+        }
+
+        finally
+        {
+            if ( ldapConnection != null )
+            {
+                ldapConnection.close();
+            }
+            if ( namingEnumeration != null )
+            {
+                try
+                {
+                    namingEnumeration.close();
+                }
+                catch ( NamingException e )
+                {
+                    log.warn( "failed to close search results", e );
+                }
+            }
+        }
+    }
+
+    public List<String> getGroupsMember( String group )
+        throws MappingException
+    {
+        LdapConnection ldapConnection = null;
+
+        NamingEnumeration<SearchResult> namingEnumeration = null;
+        try
+        {
+            ldapConnection = ldapConnectionFactory.getConnection();
+
+            DirContext context = ldapConnection.getDirContext();
+
+            SearchControls searchControls = new SearchControls();
+
+            searchControls.setDerefLinkFlag( true );
+            searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE );
+
+            String filter = "objectClass=" + getLdapGroupClass();
+
+            namingEnumeration = context.search( "cn=" + group + "," + getGroupsDn(), filter, searchControls );
+
+            List<String> allMembers = new ArrayList<String>();
+
+            while ( namingEnumeration.hasMore() )
+            {
+                SearchResult searchResult = namingEnumeration.next();
+
+                Attribute uniqueMemberAttr = searchResult.getAttributes().get( "uniquemember" );
+
+                if ( uniqueMemberAttr != null )
+                {
+                    NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr.getAll();
+                    while ( allMembersEnum.hasMore() )
+                    {
+                        String userName = allMembersEnum.next();
+                        // uid=blabla we only want bla bla
+                        userName = StringUtils.substringAfter( userName, "=" );
+                        userName = StringUtils.substringBefore( userName, "," );
+                        log.debug( "found userName for group {}: '{}", group, userName );
+
+                        allMembers.add( userName );
+                    }
+                    close( allMembersEnum );
+                }
+
+
+            }
+
+            return allMembers;
+        }
+        catch ( LdapException e )
+        {
+            throw new MappingException( e.getMessage(), e );
+        }
+        catch ( NamingException e )
+        {
+            throw new MappingException( e.getMessage(), e );
+        }
+
+        finally
+        {
+            if ( ldapConnection != null )
+            {
+                ldapConnection.close();
+            }
+            close( namingEnumeration );
+        }
+    }
+
+    public List<String> getGroups( String username )
+        throws MappingException
+    {
+
+        List<String> userGroups = new ArrayList<String>();
+
+        LdapConnection ldapConnection = null;
+
+        NamingEnumeration<SearchResult> namingEnumeration = null;
+        try
+        {
+            ldapConnection = ldapConnectionFactory.getConnection();
+
+            DirContext context = ldapConnection.getDirContext();
+
+            SearchControls searchControls = new SearchControls();
+
+            searchControls.setDerefLinkFlag( true );
+            searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE );
+
+            String filter =
+                new StringBuilder().append( "(&" ).append( "(objectClass=" + getLdapGroupClass() + ")" ).append(
+                    "(uniquemember=" ).append( "uid=" + username + "," + this.getBaseDn() ).append( ")" ).append(
+                    ")" ).toString();
+
+            log.debug( "filter: {}", filter );
+
+            namingEnumeration = context.search( getGroupsDn(), filter, searchControls );
+
+            while ( namingEnumeration.hasMore() )
+            {
+                SearchResult searchResult = namingEnumeration.next();
+
+                List<String> allMembers = new ArrayList<String>();
+
+                Attribute uniqueMemberAttr = searchResult.getAttributes().get( "uniquemember" );
+
+                if ( uniqueMemberAttr != null )
+                {
+                    NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr.getAll();
+                    while ( allMembersEnum.hasMore() )
+                    {
+                        String userName = allMembersEnum.next();
+                        // uid=blabla we only want bla bla
+                        userName = StringUtils.substringAfter( userName, "=" );
+                        userName = StringUtils.substringBefore( userName, "," );
+                        allMembers.add( userName );
+                    }
+                    close( allMembersEnum );
+                }
+
+                if ( allMembers.contains( username ) )
+                {
+                    String groupName = searchResult.getName();
+                    // cn=blabla we only want bla bla
+                    groupName = StringUtils.substringAfter( groupName, "=" );
+                    userGroups.add( groupName );
+
+                }
+
+
+            }
+
+            return userGroups;
+        }
+        catch ( LdapException e )
+        {
+            throw new MappingException( e.getMessage(), e );
+        }
+        catch ( NamingException e )
+        {
+            throw new MappingException( e.getMessage(), e );
+        }
+
+        finally
+        {
+            if ( ldapConnection != null )
+            {
+                ldapConnection.close();
+            }
+            close( namingEnumeration );
+        }
+
+    }
+
+    private void close( NamingEnumeration namingEnumeration )
+    {
+        if ( namingEnumeration != null )
+        {
+            try
+            {
+                namingEnumeration.close();
+            }
+            catch ( NamingException e )
+            {
+                log.warn( "fail to close namingEnumeration: {}", e.getMessage() );
+            }
+        }
+    }
+
+    public String getGroupsDn()
+    {
+        return this.groupsDn;
+    }
+
+    public String getLdapGroupClass()
+    {
+        return this.ldapGroupClass;
+    }
+
+    public void addLdapMapping( String role, String ldapGroup )
+    {
+        log.warn( "addLdapMapping not implemented" );
+    }
+
+    public void removeLdapMapping( String role )
+    {
+        log.warn( "removeLdapMapping not implemented" );
+    }
+
+    public Map<String, String> getLdapGroupMappings()
+    {
+        log.warn( "getLdapGroupMappings not implemented" );
+        return Collections.emptyMap();
+    }
+
+    //---------------------------------
+    // setters for unit tests
+    //---------------------------------
+
+
+    public void setGroupsDn( String groupsDn )
+    {
+        this.groupsDn = groupsDn;
+    }
+
+    public void setLdapGroupClass( String ldapGroupClass )
+    {
+        this.ldapGroupClass = ldapGroupClass;
+    }
+
+    public void setUserConf( UserConfiguration userConf )
+    {
+        this.userConf = userConf;
+    }
+
+    public void setLdapConnectionFactory( LdapConnectionFactory ldapConnectionFactory )
+    {
+        this.ldapConnectionFactory = ldapConnectionFactory;
+    }
+
+    public String getBaseDn()
+    {
+        return baseDn;
+    }
+
+    public void setBaseDn( String baseDn )
+    {
+        this.baseDn = baseDn;
+    }
+}
diff --git a/redback-common/redback-common-ldap/src/main/java/org/apache/archiva/redback/common/ldap/role/LdapRoleMapper.java b/redback-common/redback-common-ldap/src/main/java/org/apache/archiva/redback/common/ldap/role/LdapRoleMapper.java
new file mode 100644 (file)
index 0000000..e37cfa3
--- /dev/null
@@ -0,0 +1,96 @@
+package org.apache.archiva.redback.common.ldap.role;
+/*
+ * 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.
+ */
+
+import org.apache.archiva.redback.common.ldap.MappingException;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * will map ldap group to redback role
+ *
+ * @author Olivier Lamy
+ * @since 2.1
+ */
+public interface LdapRoleMapper
+{
+    /**
+     * @param role redback role
+     * @return corresponding LDAP group
+     */
+    String getLdapGroup( String role )
+        throws MappingException;
+
+    // for continuum ?
+    //String getLdapGroup( String role, String resource );
+
+
+    /**
+     * @return all LDAP groups
+     */
+    List<String> getAllGroups()
+        throws MappingException;
+
+
+    /**
+     * @return the base dn which contains all ldap groups
+     */
+    String getGroupsDn();
+
+    /**
+     * @return the class used for group usually groupOfUniqueNames
+     */
+    String getLdapGroupClass();
+
+    /**
+     * @param group ldap group
+     * @return uids of group members
+     * @throws MappingException
+     */
+    List<String> getGroupsMember( String group )
+        throws MappingException;
+
+    List<String> getGroups( String username )
+        throws MappingException;
+
+    /**
+     * add mapping redback role <-> ldap group
+     *
+     * @param role      redback role
+     * @param ldapGroup ldap group
+     */
+    void addLdapMapping( String role, String ldapGroup )
+        throws MappingException;
+
+    /**
+     * remove a mapping
+     *
+     * @param role redback role
+     */
+    void removeLdapMapping( String role )
+        throws MappingException;
+
+    /**
+     * @return Map of corresponding Redback role (key) and LDAP group (value)
+     */
+    Map<String, String> getLdapGroupMappings()
+        throws MappingException;
+
+}
diff --git a/redback-common/redback-common-ldap/src/test/java/org/apache/archiva/redback/common/ldap/role/TestLdapRoleMapper.java b/redback-common/redback-common-ldap/src/test/java/org/apache/archiva/redback/common/ldap/role/TestLdapRoleMapper.java
new file mode 100644 (file)
index 0000000..c519784
--- /dev/null
@@ -0,0 +1,314 @@
+package org.apache.archiva.redback.common.ldap.role;
+/*
+ * 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.
+ */
+
+import junit.framework.TestCase;
+import org.apache.archiva.redback.components.apacheds.ApacheDs;
+import org.apache.archiva.redback.policy.PasswordEncoder;
+import org.apache.archiva.redback.policy.encoders.SHA1PasswordEncoder;
+import org.fest.assertions.Assertions;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attribute;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.BasicAttribute;
+import javax.naming.directory.BasicAttributes;
+import javax.naming.directory.DirContext;
+import javax.naming.directory.InitialDirContext;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author Olivier Lamy
+ */
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(
+    locations = { "classpath*:/META-INF/spring-context.xml", "classpath:/spring-context-role-mapper.xml" })
+@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
+public class TestLdapRoleMapper
+    extends TestCase
+{
+
+    Logger log = LoggerFactory.getLogger( getClass() );
+
+    @Inject
+    @Named( value = "apacheDS#test" )
+    private ApacheDs apacheDs;
+
+    private String suffix;
+
+    private String groupSuffix;
+
+    private PasswordEncoder passwordEncoder;
+
+    //@Inject
+    //private LdapCacheService ldapCacheService;
+
+    @Inject
+    @Named(value = "ldapRoleMapper#test")
+    LdapRoleMapper ldapRoleMapper;
+
+    private Map<String, List<String>> usersPerGroup;
+
+    private List<String> users;
+
+    @Before
+    public void setUp()
+        throws Exception
+    {
+        super.setUp();
+
+        usersPerGroup = new HashMap<String, List<String>>( 3 );
+
+        usersPerGroup.put( "internal-repo-manager", Arrays.asList( "admin", "user.9" ) );
+        usersPerGroup.put( "internal-repo-observer", Arrays.asList( "admin", "user.7", "user.8" ) );
+        usersPerGroup.put( "archiva-admin", Arrays.asList( "admin", "user.7" ) );
+
+        users = new ArrayList<String>( 4 );
+        users.add( "admin" );
+        users.add( "user.7" );
+        users.add( "user.8" );
+        users.add( "user.9" );
+
+        passwordEncoder = new SHA1PasswordEncoder();
+
+        groupSuffix = apacheDs.addSimplePartition( "test", new String[]{ "archiva", "apache", "org" } ).getSuffix();
+
+        log.info( "groupSuffix: {}", groupSuffix );
+
+        suffix = "ou=People,dc=archiva,dc=apache,dc=org";
+
+        log.info( "DN Suffix: {}", suffix );
+
+        apacheDs.startServer();
+
+        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
+        objectClass.add( "top" );
+        objectClass.add( "organizationalUnit" );
+
+        Attributes attributes = new BasicAttributes( true );
+        attributes.put( objectClass );
+        attributes.put( "organizationalUnitName", "foo" );
+        //attributes.put( "ou", "People" );
+
+        apacheDs.getAdminContext().createSubcontext( suffix, attributes );
+
+        makeUsers();
+
+        createGroups();
+    }
+
+    @After
+    public void tearDown()
+        throws Exception
+    {
+        // clear cache
+        //ldapCacheService.removeAllUsers();
+
+        InitialDirContext context = apacheDs.getAdminContext();
+
+        for ( String uid : users )
+        {
+            context.unbind( createDn( uid ) );
+        }
+
+        for ( Map.Entry<String, List<String>> group : usersPerGroup.entrySet() )
+        {
+            context.unbind( createGroupDn( group.getKey() ) );
+        }
+
+        context.unbind( suffix );
+
+        apacheDs.stopServer();
+
+        super.tearDown();
+    }
+
+    private void createGroups()
+        throws Exception
+    {
+        InitialDirContext context = apacheDs.getAdminContext();
+
+        for ( Map.Entry<String, List<String>> group : usersPerGroup.entrySet() )
+        {
+            createGroup( context, group.getKey(), createGroupDn( group.getKey() ), group.getValue() );
+        }
+
+    }
+
+    private void createGroup( DirContext context, String groupName, String dn, List<String> users )
+        throws Exception
+    {
+
+        Attributes attributes = new BasicAttributes( true );
+        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
+        objectClass.add( "top" );
+        objectClass.add( "groupOfUniqueNames" );
+        attributes.put( objectClass );
+        attributes.put( "cn", groupName );
+        BasicAttribute basicAttribute = new BasicAttribute( "uniquemember" );
+        for ( String user : users )
+        {
+            basicAttribute.add( "uid=" + user + "," + suffix );// dc=archiva,dc=apache,dc=org" );
+        }
+
+        attributes.put( basicAttribute );
+        context.createSubcontext( dn, attributes );
+    }
+
+    private void bindUserObject( DirContext context, String cn, String dn )
+        throws Exception
+    {
+        Attributes attributes = new BasicAttributes( true );
+        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
+        objectClass.add( "top" );
+        objectClass.add( "inetOrgPerson" );
+        objectClass.add( "person" );
+        objectClass.add( "organizationalperson" );
+        attributes.put( objectClass );
+        attributes.put( "cn", cn );
+        attributes.put( "sn", "foo" );
+        attributes.put( "mail", cn + "@apache.org" );
+        attributes.put( "userPassword", passwordEncoder.encodePassword( "foo" ) );
+        attributes.put( "givenName", "foo" );
+        context.createSubcontext( dn, attributes );
+    }
+
+    private void makeUsers()
+        throws Exception
+    {
+
+        for ( String uid : users )
+        {
+            makeUser( uid );
+        }
+
+    }
+
+    private void makeUser( String uid )
+        throws Exception
+    {
+        InitialDirContext context = apacheDs.getAdminContext();
+
+        bindUserObject( context, uid, createDn( uid ) );
+        assertExist( context, createDn( uid ), "cn", uid );
+    }
+
+
+    private void assertExist( DirContext context, String dn, String attribute, String value )
+        throws NamingException
+    {
+        SearchControls ctls = new SearchControls();
+
+        ctls.setDerefLinkFlag( true );
+        ctls.setSearchScope( SearchControls.ONELEVEL_SCOPE );
+        ctls.setReturningAttributes( new String[]{ "*" } );
+
+        BasicAttributes matchingAttributes = new BasicAttributes();
+        matchingAttributes.put( attribute, value );
+        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
+        objectClass.add( "inetOrgPerson" );
+        matchingAttributes.put( objectClass );
+
+        NamingEnumeration<SearchResult> results = context.search( suffix, matchingAttributes );
+
+        assertTrue( results.hasMoreElements() );
+        SearchResult result = results.nextElement();
+        Attributes attrs = result.getAttributes();
+        Attribute testAttr = attrs.get( attribute );
+        assertEquals( value, testAttr.get() );
+
+    }
+
+    private String createDn( String cn )
+    {
+        return "cn=" + cn + "," + suffix;
+    }
+
+    private String createGroupDn( String cn )
+    {
+        return "cn=" + cn + "," + groupSuffix;
+    }
+
+    @Test
+    public void getAllGroups()
+        throws Exception
+    {
+        List<String> allGroups = ldapRoleMapper.getAllGroups();
+
+        log.info( "allGroups: {}", allGroups );
+
+        Assertions.assertThat( allGroups ).isNotNull().isNotEmpty().contains( "archiva-admin",
+                                                                              "internal-repo-manager" );
+    }
+
+    @Test
+    public void getGroupsMember()
+        throws Exception
+    {
+        List<String> users = ldapRoleMapper.getGroupsMember( "archiva-admin" );
+
+        log.info( "users for archiva-admin: {}", users );
+
+        Assertions.assertThat( users ).isNotNull().isNotEmpty().hasSize( 2 ).contains( "admin", "user.7" );
+
+        users = ldapRoleMapper.getGroupsMember( "internal-repo-observer" );
+
+        Assertions.assertThat( users ).isNotNull().isNotEmpty().hasSize( 3 ).contains( "admin", "user.7", "user.8" );
+    }
+
+    @Test
+    public void getGroups()
+        throws Exception
+    {
+        List<String> roles = ldapRoleMapper.getGroups( "admin" );
+
+        log.info( "roles for admin: {}", roles );
+
+        Assertions.assertThat( roles ).isNotNull().isNotEmpty().hasSize( 3 ).contains( "archiva-admin",
+                                                                                       "internal-repo-manager",
+                                                                                       "internal-repo-observer" );
+
+        roles = ldapRoleMapper.getGroups( "user.8" );
+
+        Assertions.assertThat( roles ).isNotNull().isNotEmpty().hasSize( 1 ).contains( "internal-repo-observer" );
+
+        roles = ldapRoleMapper.getGroups( "user.7" );
+
+        Assertions.assertThat( roles ).isNotNull().isNotEmpty().hasSize( 2 ).contains( "archiva-admin",
+                                                                                       "internal-repo-observer" );
+    }
+}
diff --git a/redback-common/redback-common-ldap/src/test/resources/spring-context-role-mapper.xml b/redback-common/redback-common-ldap/src/test/resources/spring-context-role-mapper.xml
new file mode 100755 (executable)
index 0000000..c303080
--- /dev/null
@@ -0,0 +1,62 @@
+<?xml version="1.0"?>
+
+<!--
+  ~ 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.
+  -->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+           http://www.springframework.org/schema/context
+           http://www.springframework.org/schema/context/spring-context-3.0.xsd"
+       default-lazy-init="false">
+  <context:property-placeholder system-properties-mode="OVERRIDE"/>
+
+  <alias name="userConfiguration#redback" alias="userConfiguration#default"/>
+
+  <bean name="apacheDS#test" class="org.apache.archiva.redback.components.apacheds.DefaultApacheDs"
+        scope="prototype">
+    <property name="basedir" value="${basedir}/target/apacheds"/>
+    <property name="port" value="${ldapPort}"/>
+    <property name="enableNetworking" value="true"/>
+    <property name="password" value="secret"/>
+  </bean>
+
+  <bean name="ldapConnectionFactory#configurable"
+        class="org.apache.archiva.redback.common.ldap.connection.ConfigurableLdapConnectionFactory">
+    <property name="hostname" value="localhost"/>
+    <property name="port" value="${ldapPort}"/>
+    <!--property name="baseDn" value="dc=redback,dc=plexus,dc=codehaus,dc=org"/-->
+    <property name="baseDn" value="dc=archiva,dc=apache,dc=org"/>
+    <property name="contextFactory" value="com.sun.jndi.ldap.LdapCtxFactory"/>
+    <property name="password" value="secret"/>
+    <property name="bindDn" value="uid=admin,ou=system"/>
+    <property name="userConf" ref="userConfiguration#default"/>
+  </bean>
+
+
+  <bean name="ldapRoleMapper#test" class="org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper">
+    <property name="groupsDn" value="dc=archiva,dc=apache,dc=org"/>
+    <property name="ldapGroupClass" value="groupOfUniqueNames"/>
+    <property name="baseDn" value="ou=People,dc=archiva,dc=apache,dc=org"/>
+    <property name="ldapConnectionFactory" ref="ldapConnectionFactory#configurable"/>
+    <property name="userConf" ref="userConfiguration#default"/>
+  </bean>
+
+</beans>
\ No newline at end of file
diff --git a/redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/main/java/org/apache/archiva/redback/rbac/ldap/DefaultLdapRoleMapper.java b/redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/main/java/org/apache/archiva/redback/rbac/ldap/DefaultLdapRoleMapper.java
deleted file mode 100644 (file)
index 466ad2e..0000000
+++ /dev/null
@@ -1,386 +0,0 @@
-package org.apache.archiva.redback.rbac.ldap;
-/*
- * 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.
- */
-
-import org.apache.archiva.redback.common.ldap.MappingException;
-import org.apache.archiva.redback.common.ldap.connection.LdapConnection;
-import org.apache.archiva.redback.common.ldap.connection.LdapConnectionFactory;
-import org.apache.archiva.redback.common.ldap.connection.LdapException;
-import org.apache.archiva.redback.configuration.UserConfiguration;
-import org.apache.archiva.redback.configuration.UserConfigurationKeys;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Olivier Lamy
- * @since 2.1
- */
-@Service( "ldapRoleMapper#default" )
-public class DefaultLdapRoleMapper
-    implements LdapRoleMapper
-{
-
-    private Logger log = LoggerFactory.getLogger( getClass() );
-
-    @Inject
-    private LdapConnectionFactory ldapConnectionFactory;
-
-    @Inject
-    @Named( value = "userConfiguration#default" )
-    private UserConfiguration userConf;
-
-    //---------------------------
-    // fields
-    //---------------------------
-
-    private String ldapGroupClass = "groupOfUniqueNames";
-
-    private String groupsDn;
-
-    private String baseDn;
-
-    @PostConstruct
-    public void initialize()
-    {
-        this.ldapGroupClass = userConf.getString( UserConfigurationKeys.LDAP_GROUPS_CLASS, this.ldapGroupClass );
-
-        this.groupsDn = userConf.getString( UserConfigurationKeys.LDAP_GROUPS_BASEDN, this.groupsDn );
-
-        this.baseDn = userConf.getString( UserConfigurationKeys.LDAP_BASEDN, this.baseDn );
-    }
-
-    public String getLdapGroup( String role )
-    {
-        return userConf.getString( UserConfigurationKeys.LDAP_GROUPS_ROLE_START_KEY + role );
-    }
-
-    public List<String> getAllGroups()
-        throws MappingException
-    {
-        LdapConnection ldapConnection = null;
-
-        NamingEnumeration<SearchResult> namingEnumeration = null;
-        try
-        {
-            ldapConnection = ldapConnectionFactory.getConnection();
-
-            DirContext context = ldapConnection.getDirContext();
-
-            SearchControls searchControls = new SearchControls();
-
-            searchControls.setDerefLinkFlag( true );
-            searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE );
-
-            String filter = "objectClass=" + getLdapGroupClass();
-
-            namingEnumeration = context.search( getGroupsDn(), filter, searchControls );
-
-            List<String> allGroups = new ArrayList<String>();
-
-            while ( namingEnumeration.hasMore() )
-            {
-                SearchResult searchResult = namingEnumeration.next();
-
-                String groupName = searchResult.getName();
-                // cn=blabla we only want bla bla
-                groupName = StringUtils.substringAfter( groupName, "=" );
-
-                log.debug( "found groupName: '{}", groupName );
-
-                allGroups.add( groupName );
-
-            }
-
-            return allGroups;
-        }
-        catch ( LdapException e )
-        {
-            throw new MappingException( e.getMessage(), e );
-        }
-        catch ( NamingException e )
-        {
-            throw new MappingException( e.getMessage(), e );
-        }
-
-        finally
-        {
-            if ( ldapConnection != null )
-            {
-                ldapConnection.close();
-            }
-            if ( namingEnumeration != null )
-            {
-                try
-                {
-                    namingEnumeration.close();
-                }
-                catch ( NamingException e )
-                {
-                    log.warn( "failed to close search results", e );
-                }
-            }
-        }
-    }
-
-    public List<String> getGroupsMember( String group )
-        throws MappingException
-    {
-        LdapConnection ldapConnection = null;
-
-        NamingEnumeration<SearchResult> namingEnumeration = null;
-        try
-        {
-            ldapConnection = ldapConnectionFactory.getConnection();
-
-            DirContext context = ldapConnection.getDirContext();
-
-            SearchControls searchControls = new SearchControls();
-
-            searchControls.setDerefLinkFlag( true );
-            searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE );
-
-            String filter = "objectClass=" + getLdapGroupClass();
-
-            namingEnumeration = context.search( "cn=" + group + "," + getGroupsDn(), filter, searchControls );
-
-            List<String> allMembers = new ArrayList<String>();
-
-            while ( namingEnumeration.hasMore() )
-            {
-                SearchResult searchResult = namingEnumeration.next();
-
-                Attribute uniqueMemberAttr = searchResult.getAttributes().get( "uniquemember" );
-
-                if ( uniqueMemberAttr != null )
-                {
-                    NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr.getAll();
-                    while ( allMembersEnum.hasMore() )
-                    {
-                        String userName = allMembersEnum.next();
-                        // uid=blabla we only want bla bla
-                        userName = StringUtils.substringAfter( userName, "=" );
-                        userName = StringUtils.substringBefore( userName, "," );
-                        log.debug( "found userName for group {}: '{}", group, userName );
-
-                        allMembers.add( userName );
-                    }
-                    close( allMembersEnum );
-                }
-
-
-            }
-
-            return allMembers;
-        }
-        catch ( LdapException e )
-        {
-            throw new MappingException( e.getMessage(), e );
-        }
-        catch ( NamingException e )
-        {
-            throw new MappingException( e.getMessage(), e );
-        }
-
-        finally
-        {
-            if ( ldapConnection != null )
-            {
-                ldapConnection.close();
-            }
-            close( namingEnumeration );
-        }
-    }
-
-    public List<String> getGroups( String username )
-        throws MappingException
-    {
-
-        List<String> userGroups = new ArrayList<String>();
-
-        LdapConnection ldapConnection = null;
-
-        NamingEnumeration<SearchResult> namingEnumeration = null;
-        try
-        {
-            ldapConnection = ldapConnectionFactory.getConnection();
-
-            DirContext context = ldapConnection.getDirContext();
-
-            SearchControls searchControls = new SearchControls();
-
-            searchControls.setDerefLinkFlag( true );
-            searchControls.setSearchScope( SearchControls.SUBTREE_SCOPE );
-
-            String filter =
-                new StringBuilder().append( "(&" ).append( "(objectClass=" + getLdapGroupClass() + ")" ).append(
-                    "(uniquemember=" ).append( "uid=" + username + "," + this.getBaseDn() ).append( ")" ).append(
-                    ")" ).toString();
-
-            log.debug( "filter: {}", filter );
-
-            namingEnumeration = context.search( getGroupsDn(), filter, searchControls );
-
-            while ( namingEnumeration.hasMore() )
-            {
-                SearchResult searchResult = namingEnumeration.next();
-
-                List<String> allMembers = new ArrayList<String>();
-
-                Attribute uniqueMemberAttr = searchResult.getAttributes().get( "uniquemember" );
-
-                if ( uniqueMemberAttr != null )
-                {
-                    NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr.getAll();
-                    while ( allMembersEnum.hasMore() )
-                    {
-                        String userName = allMembersEnum.next();
-                        // uid=blabla we only want bla bla
-                        userName = StringUtils.substringAfter( userName, "=" );
-                        userName = StringUtils.substringBefore( userName, "," );
-                        allMembers.add( userName );
-                    }
-                    close( allMembersEnum );
-                }
-
-                if ( allMembers.contains( username ) )
-                {
-                    String groupName = searchResult.getName();
-                    // cn=blabla we only want bla bla
-                    groupName = StringUtils.substringAfter( groupName, "=" );
-                    userGroups.add( groupName );
-
-                }
-
-
-            }
-
-            return userGroups;
-        }
-        catch ( LdapException e )
-        {
-            throw new MappingException( e.getMessage(), e );
-        }
-        catch ( NamingException e )
-        {
-            throw new MappingException( e.getMessage(), e );
-        }
-
-        finally
-        {
-            if ( ldapConnection != null )
-            {
-                ldapConnection.close();
-            }
-            close( namingEnumeration );
-        }
-
-    }
-
-    private void close( NamingEnumeration namingEnumeration )
-    {
-        if ( namingEnumeration != null )
-        {
-            try
-            {
-                namingEnumeration.close();
-            }
-            catch ( NamingException e )
-            {
-                log.warn( "fail to close namingEnumeration: {}", e.getMessage() );
-            }
-        }
-    }
-
-    public String getGroupsDn()
-    {
-        return this.groupsDn;
-    }
-
-    public String getLdapGroupClass()
-    {
-        return this.ldapGroupClass;
-    }
-
-    public void addLdapMapping( String role, String ldapGroup )
-    {
-        log.warn( "addLdapMapping not implemented" );
-    }
-
-    public void removeLdapMapping( String role )
-    {
-        log.warn( "removeLdapMapping not implemented" );
-    }
-
-    public Map<String, String> getLdapGroupMappings()
-    {
-        log.warn( "getLdapGroupMappings not implemented" );
-        return Collections.emptyMap();
-    }
-
-    //---------------------------------
-    // setters for unit tests
-    //---------------------------------
-
-
-    public void setGroupsDn( String groupsDn )
-    {
-        this.groupsDn = groupsDn;
-    }
-
-    public void setLdapGroupClass( String ldapGroupClass )
-    {
-        this.ldapGroupClass = ldapGroupClass;
-    }
-
-    public void setUserConf( UserConfiguration userConf )
-    {
-        this.userConf = userConf;
-    }
-
-    public void setLdapConnectionFactory( LdapConnectionFactory ldapConnectionFactory )
-    {
-        this.ldapConnectionFactory = ldapConnectionFactory;
-    }
-
-    public String getBaseDn()
-    {
-        return baseDn;
-    }
-
-    public void setBaseDn( String baseDn )
-    {
-        this.baseDn = baseDn;
-    }
-}
diff --git a/redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/main/java/org/apache/archiva/redback/rbac/ldap/LdapRoleMapper.java b/redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/main/java/org/apache/archiva/redback/rbac/ldap/LdapRoleMapper.java
deleted file mode 100644 (file)
index 949e9b5..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-package org.apache.archiva.redback.rbac.ldap;
-/*
- * 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.
- */
-
-import org.apache.archiva.redback.common.ldap.MappingException;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * will map ldap group to redback role
- *
- * @author Olivier Lamy
- * @since 2.1
- */
-public interface LdapRoleMapper
-{
-    /**
-     * @param role redback role
-     * @return corresponding LDAP group
-     */
-    String getLdapGroup( String role )
-        throws MappingException;
-
-    // for continuum ?
-    //String getLdapGroup( String role, String resource );
-
-
-    /**
-     * @return all LDAP groups
-     */
-    List<String> getAllGroups()
-        throws MappingException;
-
-
-    /**
-     * @return the base dn which contains all ldap groups
-     */
-    String getGroupsDn();
-
-    /**
-     * @return the class used for group usually groupOfUniqueNames
-     */
-    String getLdapGroupClass();
-
-    /**
-     * @param group ldap group
-     * @return uids of group members
-     * @throws MappingException
-     */
-    List<String> getGroupsMember( String group )
-        throws MappingException;
-
-    List<String> getGroups( String username )
-        throws MappingException;
-
-    /**
-     * add mapping redback role <-> ldap group
-     *
-     * @param role      redback role
-     * @param ldapGroup ldap group
-     */
-    void addLdapMapping( String role, String ldapGroup )
-        throws MappingException;
-
-    /**
-     * remove a mapping
-     *
-     * @param role redback role
-     */
-    void removeLdapMapping( String role )
-        throws MappingException;
-
-    /**
-     * @return Map of corresponding Redback role (key) and LDAP group (value)
-     */
-    Map<String, String> getLdapGroupMappings()
-        throws MappingException;
-
-}
diff --git a/redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/test/java/org/apache/archiva/redback/rbac/ldap/TestLdapRoleMapper.java b/redback-rbac/redback-rbac-providers/redback-rbac-ldap/src/test/java/org/apache/archiva/redback/rbac/ldap/TestLdapRoleMapper.java
deleted file mode 100644 (file)
index bf977ea..0000000
+++ /dev/null
@@ -1,320 +0,0 @@
-package org.apache.archiva.redback.rbac.ldap;
-/*
- * 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.
- */
-
-import junit.framework.TestCase;
-import org.apache.archiva.redback.components.apacheds.ApacheDs;
-import org.apache.archiva.redback.policy.PasswordEncoder;
-import org.apache.archiva.redback.policy.encoders.SHA1PasswordEncoder;
-import org.apache.archiva.redback.users.UserManager;
-import org.apache.archiva.redback.users.ldap.service.LdapCacheService;
-import org.fest.assertions.Assertions;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.test.annotation.DirtiesContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import javax.inject.Inject;
-import javax.inject.Named;
-import javax.naming.NameClassPair;
-import javax.naming.NamingEnumeration;
-import javax.naming.NamingException;
-import javax.naming.directory.Attribute;
-import javax.naming.directory.Attributes;
-import javax.naming.directory.BasicAttribute;
-import javax.naming.directory.BasicAttributes;
-import javax.naming.directory.DirContext;
-import javax.naming.directory.InitialDirContext;
-import javax.naming.directory.SearchControls;
-import javax.naming.directory.SearchResult;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Olivier Lamy
- */
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "classpath*:/META-INF/spring-context.xml", "classpath*:/spring-context.xml" })
-@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
-public class TestLdapRoleMapper
-    extends TestCase
-{
-
-    Logger log = LoggerFactory.getLogger( getClass() );
-
-    @Inject
-    @Named(value = "userManager#ldap")
-    private UserManager userManager;
-
-    @Inject
-    @Named(value = "apacheDS#test")
-    private ApacheDs apacheDs;
-
-    private String suffix;
-
-    private String groupSuffix;
-
-    private PasswordEncoder passwordEncoder;
-
-    @Inject
-    private LdapCacheService ldapCacheService;
-
-    @Inject
-    @Named(value = "ldapRoleMapper#test")
-    LdapRoleMapper ldapRoleMapper;
-
-    private Map<String, List<String>> usersPerGroup;
-
-    private List<String> users;
-
-    @Before
-    public void setUp()
-        throws Exception
-    {
-        super.setUp();
-
-        usersPerGroup = new HashMap<String, List<String>>( 3 );
-
-        usersPerGroup.put( "internal-repo-manager", Arrays.asList( "admin", "user.9" ) );
-        usersPerGroup.put( "internal-repo-observer", Arrays.asList( "admin", "user.7", "user.8" ) );
-        usersPerGroup.put( "archiva-admin", Arrays.asList( "admin", "user.7" ) );
-
-        users = new ArrayList<String>( 4 );
-        users.add( "admin" );
-        users.add( "user.7" );
-        users.add( "user.8" );
-        users.add( "user.9" );
-
-        passwordEncoder = new SHA1PasswordEncoder();
-
-        groupSuffix = apacheDs.addSimplePartition( "test", new String[]{ "archiva", "apache", "org" } ).getSuffix();
-
-        log.info( "groupSuffix: {}", groupSuffix );
-
-        suffix = "ou=People,dc=archiva,dc=apache,dc=org";
-
-        log.info( "DN Suffix: {}", suffix );
-
-        apacheDs.startServer();
-
-        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
-        objectClass.add( "top" );
-        objectClass.add( "organizationalUnit" );
-
-        Attributes attributes = new BasicAttributes( true );
-        attributes.put( objectClass );
-        attributes.put( "organizationalUnitName", "foo" );
-        //attributes.put( "ou", "People" );
-
-        apacheDs.getAdminContext().createSubcontext( suffix, attributes );
-
-        makeUsers();
-
-        createGroups();
-    }
-
-    @After
-    public void tearDown()
-        throws Exception
-    {
-        // clear cache
-        ldapCacheService.removeAllUsers();
-
-        InitialDirContext context = apacheDs.getAdminContext();
-
-        for ( String uid : users )
-        {
-            context.unbind( createDn( uid ) );
-        }
-
-        for ( Map.Entry<String, List<String>> group : usersPerGroup.entrySet() )
-        {
-            context.unbind( createGroupDn( group.getKey() ) );
-        }
-
-        context.unbind( suffix );
-
-        apacheDs.stopServer();
-
-        super.tearDown();
-    }
-
-    private void createGroups()
-        throws Exception
-    {
-        InitialDirContext context = apacheDs.getAdminContext();
-
-        for ( Map.Entry<String, List<String>> group : usersPerGroup.entrySet() )
-        {
-            createGroup( context, group.getKey(), createGroupDn( group.getKey() ), group.getValue() );
-        }
-
-    }
-
-    private void createGroup( DirContext context, String groupName, String dn, List<String> users )
-        throws Exception
-    {
-
-        Attributes attributes = new BasicAttributes( true );
-        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
-        objectClass.add( "top" );
-        objectClass.add( "groupOfUniqueNames" );
-        attributes.put( objectClass );
-        attributes.put( "cn", groupName );
-        BasicAttribute basicAttribute = new BasicAttribute( "uniquemember" );
-        for ( String user : users )
-        {
-            basicAttribute.add( "uid=" + user + "," + suffix );// dc=archiva,dc=apache,dc=org" );
-        }
-
-        attributes.put( basicAttribute );
-        context.createSubcontext( dn, attributes );
-    }
-
-    private void bindUserObject( DirContext context, String cn, String dn )
-        throws Exception
-    {
-        Attributes attributes = new BasicAttributes( true );
-        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
-        objectClass.add( "top" );
-        objectClass.add( "inetOrgPerson" );
-        objectClass.add( "person" );
-        objectClass.add( "organizationalperson" );
-        attributes.put( objectClass );
-        attributes.put( "cn", cn );
-        attributes.put( "sn", "foo" );
-        attributes.put( "mail", cn + "@apache.org" );
-        attributes.put( "userPassword", passwordEncoder.encodePassword( "foo" ) );
-        attributes.put( "givenName", "foo" );
-        context.createSubcontext( dn, attributes );
-    }
-
-    private void makeUsers()
-        throws Exception
-    {
-
-        for ( String uid : users )
-        {
-            makeUser( uid );
-        }
-
-    }
-
-    private void makeUser( String uid )
-        throws Exception
-    {
-        InitialDirContext context = apacheDs.getAdminContext();
-
-        bindUserObject( context, uid, createDn( uid ) );
-        assertExist( context, createDn( uid ), "cn", uid );
-    }
-
-
-    private void assertExist( DirContext context, String dn, String attribute, String value )
-        throws NamingException
-    {
-        SearchControls ctls = new SearchControls();
-
-        ctls.setDerefLinkFlag( true );
-        ctls.setSearchScope( SearchControls.ONELEVEL_SCOPE );
-        ctls.setReturningAttributes( new String[]{ "*" } );
-
-        BasicAttributes matchingAttributes = new BasicAttributes();
-        matchingAttributes.put( attribute, value );
-        BasicAttribute objectClass = new BasicAttribute( "objectClass" );
-        objectClass.add( "inetOrgPerson" );
-        matchingAttributes.put( objectClass );
-
-        NamingEnumeration<SearchResult> results = context.search( suffix, matchingAttributes );
-
-        assertTrue( results.hasMoreElements() );
-        SearchResult result = results.nextElement();
-        Attributes attrs = result.getAttributes();
-        Attribute testAttr = attrs.get( attribute );
-        assertEquals( value, testAttr.get() );
-
-    }
-
-    private String createDn( String cn )
-    {
-        return "cn=" + cn + "," + suffix;
-    }
-
-    private String createGroupDn( String cn )
-    {
-        return "cn=" + cn + "," + groupSuffix;
-    }
-
-    @Test
-    public void getAllGroups()
-        throws Exception
-    {
-        List<String> allGroups = ldapRoleMapper.getAllGroups();
-
-        log.info( "allGroups: {}", allGroups );
-
-        Assertions.assertThat( allGroups ).isNotNull().isNotEmpty().contains( "archiva-admin",
-                                                                              "internal-repo-manager" );
-    }
-
-    @Test
-    public void getGroupsMember()
-        throws Exception
-    {
-        List<String> users = ldapRoleMapper.getGroupsMember( "archiva-admin" );
-
-        log.info( "users for archiva-admin: {}", users );
-
-        Assertions.assertThat( users ).isNotNull().isNotEmpty().hasSize( 2 ).contains( "admin", "user.7" );
-
-        users = ldapRoleMapper.getGroupsMember( "internal-repo-observer" );
-
-        Assertions.assertThat( users ).isNotNull().isNotEmpty().hasSize( 3 ).contains( "admin", "user.7", "user.8" );
-    }
-
-    @Test
-    public void getGroups()
-        throws Exception
-    {
-        List<String> roles = ldapRoleMapper.getGroups( "admin" );
-
-        log.info( "roles for admin: {}", roles );
-
-        Assertions.assertThat( roles ).isNotNull().isNotEmpty().hasSize( 3 ).contains( "archiva-admin",
-                                                                                       "internal-repo-manager",
-                                                                                       "internal-repo-observer" );
-
-        roles = ldapRoleMapper.getGroups( "user.8" );
-
-        Assertions.assertThat( roles ).isNotNull().isNotEmpty().hasSize( 1 ).contains( "internal-repo-observer" );
-
-        roles = ldapRoleMapper.getGroups( "user.7" );
-
-        Assertions.assertThat( roles ).isNotNull().isNotEmpty().hasSize( 2 ).contains( "archiva-admin",
-                                                                                       "internal-repo-observer" );
-    }
-}
index c87f86ddc50179066f7b2543e74e27d4983a5ff6..c30308064b48ad7ecf1927fc03df826e9c1bc17a 100755 (executable)
@@ -51,7 +51,7 @@
   </bean>
 
 
-  <bean name="ldapRoleMapper#test" class="org.apache.archiva.redback.rbac.ldap.DefaultLdapRoleMapper">
+  <bean name="ldapRoleMapper#test" class="org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper">
     <property name="groupsDn" value="dc=archiva,dc=apache,dc=org"/>
     <property name="ldapGroupClass" value="groupOfUniqueNames"/>
     <property name="baseDn" value="ou=People,dc=archiva,dc=apache,dc=org"/>