[jboss-cvs] JBossAS SVN: r114775 - in branches/JBPAPP_5/testsuite: src/main/org/jboss/test/security and 4 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Mon Mar 24 10:30:55 EDT 2014


Author: zroubali
Date: 2014-03-24 10:30:55 -0400 (Mon, 24 Mar 2014)
New Revision: 114775

Added:
   branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/
   branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/FakePasswordProvider.java
   branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/LDAPServerControl.java
   branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/test/LdapExtLoginModuleTestCase.java
   branches/JBPAPP_5/testsuite/src/resources/security/ldapext/
   branches/JBPAPP_5/testsuite/src/resources/security/ldapext/test.ldif
Modified:
   branches/JBPAPP_5/testsuite/build.xml
Log:
JBQA-8610 - Test cache of passwords from external source for LdapExt login module

Modified: branches/JBPAPP_5/testsuite/build.xml
===================================================================
--- branches/JBPAPP_5/testsuite/build.xml	2014-03-24 13:56:24 UTC (rev 114774)
+++ branches/JBPAPP_5/testsuite/build.xml	2014-03-24 14:30:55 UTC (rev 114775)
@@ -685,6 +685,8 @@
    -->
    <property name="kerberosControl.port" value="10951" />
    <property name="gsstestserver.port" value="10952" />
+
+    <property name="ldapControl.port" value="10953" />
 	
    <!-- Import the jboss server run targets -->
    <import file="imports/server-config.xml"/>
@@ -1740,6 +1742,7 @@
       <antcall target="tests-jacc-securitymgr"/>
       <antcall target="tests-jacc-security-allstarrole"/>
       <antcall target="tests-jboss-negotiation"/>
+      <antcall target="tests-ldapext"/>
 <!--
       <antcall target="tests-security-jaspi-unit"/>
 -->
@@ -5441,8 +5444,8 @@
 				<include name="lib/**" />
 			</patternset>
 		</create-config>
-	
-		<!-- Setup Negotiation configuration. We need to retrieve cannonical host 
+
+		<!-- Setup Negotiation configuration. We need to retrieve cannonical host
 			name, therefor the Java is used for the configuration. -->
 		<java classname="org.jboss.test.security.negotiation.NegotiationSetup" fork="true">
 			<sysproperty key="build.testlog" value="${build.testlog}" />
@@ -5508,10 +5511,10 @@
 				</waitfor>
 	
 				<server:start name="negotiation" />
-	
+
 				<junit dir="${module.output}" printsummary="true" haltonerror="false"
 					haltonfailure="false" fork="true" timeout="200000" jvm="${junit.jvm}">
-					<!-- 
+					<!--
 					<jvmarg value="-Xdebug" /> <jvmarg value="-Xnoagent" /> <jvmarg 
 						value="-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8686" /> 
 					-->
@@ -5632,4 +5635,108 @@
 		<!-- TODO test when Kerberos server is down -->
 	</target>
 
+
+    <target name="tests-ldapext" description="Tests LdapExtLoginModule"
+            depends="init">
+
+        <delete dir="${jboss.dist}${/}server${/}ldapext" quiet="true" />
+
+        <create-config baseconf="default" newconf="ldapext">
+            <patternset>
+                <include name="conf/**" />
+                <include name="deployers/**" />
+                <include name="deploy/**" />
+                <include name="lib/**" />
+            </patternset>
+        </create-config>
+
+        <parallel>
+            <!-- Start LDAP Server -->
+            <java classname="org.jboss.test.security.ldapext.LDAPServerControl" fork="true">
+                <sysproperty key="build.testlog" value="${build.testlog}" />
+                <sysproperty key="ldap.bind.address" value="${node0}" />
+                <classpath>
+                    <pathelement location="${build.resources}" />
+                    <pathelement location="${build.classes}" />
+                    <path refid="thirdparty.classpath" />
+                </classpath>
+                <!-- LDIF file to import -->
+                <arg value="${build.resources}/security/ldapext/test.ldif" />
+            </java>
+
+            <sequential>
+                <!-- wait for LDAP control task  -->
+                <waitfor maxwait="10" maxwaitunit="second" checkevery="1" checkeveryunit="second">
+                    <and>
+                        <socket server="${node0}" port="${ldapControl.port}" />
+                    </and>
+                </waitfor>
+
+                <server:start name="all" />
+
+                <junit dir="${module.output}" printsummary="true" haltonerror="false"
+                       haltonfailure="false" fork="true" timeout="200000" jvm="${junit.jvm}">
+                    <jvmarg line="${junit.jvm.options}" />
+
+                    <sysproperty key="jboss.server.home.dir" value="${jboss.dist}${/}server${/}ldapext" />
+                    <sysproperty key="java.naming.provider.url" value="${node0.jndi.url}" />
+                    <sysproperty key="jbosstest.server.host" value="${node0}" />
+                    <sysproperty key="jboss.home" file="${project.root}" />
+                    <sysproperty key="jboss.thirdparty.dir" file="${project.root}/thirdparty" />
+                    <sysproperty key="jboss.tools.dir" file="${project.root}/tools" />
+                    <sysproperty key="jbosstest.deploy.dir" file="${build.lib}" />
+                    <sysproperty key="build.testlog" value="${build.testlog}" />
+                    <sysproperty key="log4j.configuration" value="file:${build.resources}/log4j.xml" />
+
+                    <sysproperty key="sun.security.krb5.debug" value="true" />
+
+
+                    <classpath>
+                        <pathelement location="${build.resources}" />
+                        <pathelement location="${build.classes}" />
+                        <path refid="apache.httpcomponents.classpath" />
+                        <fileset dir="${jboss.dist.client}">
+                            <include name="**/*.jar" />
+                        </fileset>
+                        <fileset dir="${jboss.dist.common.lib}">
+                            <include name="**/*.jar" />
+                        </fileset>
+                        <fileset dir="${jboss.dist.lib}">
+                            <include name="**/jbosssx.jar" />
+                        </fileset>
+                        <pathelement path="${jboss.test.lib}/jboss-test.jar" />
+                        <path refid="apache.codec.classpath" />
+                        <path refid="apache.lang.classpath" />
+                        <path refid="junit.junit.classpath" />
+                    </classpath>
+
+                    <formatter classname="org.jboss.ant.taskdefs.XMLJUnitMultipleResultFormatter"
+                               usefile="${junit.formatter.usefile}" extension="-tests.xml" />
+
+                    <batchtest todir="${build.reports}" haltonerror="false" haltonfailure="false" fork="true">
+                        <fileset dir="${build.classes}">
+                            <include name="**/LdapExtLoginModuleTestCase.class" />
+                        </fileset>
+                    </batchtest>
+                </junit>
+
+                <echo>Waiting for server to shutdown...</echo>
+                <server:stop name="all" />
+
+                <!-- stop LDAP server -->
+                <java classname="org.jboss.test.security.ldapext.LDAPServerControl">
+                    <sysproperty key="build.testlog" value="${build.testlog}" />
+                    <sysproperty key="ldapControl.port" value="${ldapControl.port}" />
+                    <classpath>
+                        <pathelement location="${build.resources}" />
+                        <pathelement location="${build.classes}" />
+                        <path refid="thirdparty.classpath" />
+                    </classpath>
+                    <arg value="stop" />
+                </java>
+            </sequential>
+        </parallel>
+
+    </target>
+
 </project>

Added: branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/FakePasswordProvider.java
===================================================================
--- branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/FakePasswordProvider.java	                        (rev 0)
+++ branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/FakePasswordProvider.java	2014-03-24 14:30:55 UTC (rev 114775)
@@ -0,0 +1,100 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2014, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.ldapext;
+
+import java.io.*;
+
+/**
+ * @author zroubali at redhat.com
+ */
+public class FakePasswordProvider {
+
+    private static String counterName = "counter.tmp";
+    private static File counterFile = new File(System.getProperty("java.io.tmpdir"), counterName);
+    //private static File counterFile = new File("/home/zroubali/counter.tmp");
+    private static String PASSWORD = "secret";
+
+    public static void main(String[] args) {
+
+        String output = PASSWORD;
+
+        if (args != null && args.length == 1) {
+            output = args[0];
+        }
+
+        reportAccess();
+
+        System.out.println(output);
+        System.out.flush();
+    }
+
+
+    private static void reportAccess() {
+
+        int accessCounter = -1;
+
+        try{
+            FileReader reader = new FileReader(counterFile);
+            accessCounter = reader.read();
+            reader.close();
+
+            accessCounter++;
+
+            FileWriter writer = new FileWriter(counterFile);
+            writer.write(accessCounter);
+            writer.close();
+
+        }catch(IOException ex){
+            throw new RuntimeException("Problem with IO on a temporary access counter file.", ex);
+        }
+    }
+
+    public static void resetAccessCounter(){
+
+        try{
+            FileWriter writer = new FileWriter(counterFile);
+            writer.write(0);
+            writer.flush();
+            writer.close();
+
+        }catch(IOException ex){
+            throw new RuntimeException("Problem with IO on a temporary access counter file.", ex);
+        }
+    }
+
+    public static int getAccessCounter(){
+
+        int callsCounter = -1 ;
+
+        try{
+            FileReader reader = new FileReader(counterFile);
+            callsCounter = reader.read();
+            reader.close();
+
+        }catch(IOException ex){
+            throw new RuntimeException("Problem with IO on a temporary access counter file.", ex);
+        }
+        return callsCounter;
+    }
+
+
+}

Added: branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/LDAPServerControl.java
===================================================================
--- branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/LDAPServerControl.java	                        (rev 0)
+++ branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/ldapext/LDAPServerControl.java	2014-03-24 14:30:55 UTC (rev 114775)
@@ -0,0 +1,217 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2014, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.ldapext;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.text.StrSubstitutor;
+import org.apache.directory.server.annotations.CreateLdapServer;
+import org.apache.directory.server.annotations.CreateTransport;
+import org.apache.directory.server.core.annotations.*;
+import org.apache.directory.server.core.api.DirectoryService;
+import org.apache.directory.server.core.factory.DSAnnotationProcessor;
+import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
+import org.apache.directory.server.factory.ServerAnnotationProcessor;
+import org.apache.directory.server.ldap.LdapServer;
+import org.apache.directory.shared.ldap.model.entry.DefaultEntry;
+import org.apache.directory.shared.ldap.model.ldif.LdifEntry;
+import org.apache.directory.shared.ldap.model.ldif.LdifReader;
+import org.apache.directory.shared.ldap.model.schema.SchemaManager;
+import org.jboss.logging.Logger;
+
+import java.io.*;
+import java.net.*;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Small application which starts/stops ApacheDS and LDAP and imports LDIFs provided as program
+ * arguments.
+ * <p/>
+ * Use system property <code>ldapControl.port</code> to change port on which is running this control process. The default is
+ * 10953.
+ *
+ * @author zroubali at redhat.com
+ */
+//@formatter:off
+public class LDAPServerControl {
+
+    private static Logger LOGGER = Logger.getLogger(LDAPServerControl.class);
+
+    private static final int SOCKET_TIMEOUT = 2000; // 2 seconds
+    public static final String STOP_CMD = "stop";
+    public static final int SERVER_PORT = Integer.getInteger("ldapControl.port", 10953);
+
+    static final String SECURITY_CREDENTIALS = "secret";
+    static final String SECURITY_PRINCIPAL = "uid=admin,ou=system";
+
+    static final String KEYSTORE_FILENAME = "ldaps.jks";
+    static final int LDAP_PORT = 10389;
+    static final int LDAPS_PORT = 10636;
+
+    private final String hostname;
+
+    private DirectoryService directoryService;
+    private LdapServer ldapServer;
+
+
+    public LDAPServerControl() {
+        hostname = System.getProperty("ldap.bind.address", "localhost");
+    }
+
+
+    public static void main(String[] args) {
+        try {
+            if (args.length == 1 && STOP_CMD.equals(args[0])) {
+                System.out.println("Sending STOP command to LDAP server control process.");
+                SocketAddress sockaddr = new InetSocketAddress(InetAddress.getLocalHost(), SERVER_PORT);
+                // Create an unbound socket
+                Socket sock = new Socket();
+                sock.connect(sockaddr, SOCKET_TIMEOUT);
+                BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
+                wr.write(STOP_CMD);
+                wr.close();
+                sock.close();
+            } else {
+                System.out.println("Starting LDAP server control process.");
+                LDAPServerControl ldapServerControl = new LDAPServerControl();
+                ldapServerControl.createLdap(args);
+                ldapServerControl.waitForStop();
+                ldapServerControl.stopLdap();
+            }
+
+        } catch (Exception e) {
+            e.printStackTrace();
+            System.exit(1);
+        }
+    }
+
+
+    //@formatter:off
+    @CreateDS(
+        name = "JBossDS",
+        partitions =
+        {
+            @CreatePartition(
+                name = "jboss",
+                suffix = "dc=jboss,dc=org",
+                contextEntry = @ContextEntry(
+                    entryLdif =
+                        "dn: dc=jboss,dc=org\n" +
+                        "dc: jboss\n" +
+                        "objectClass: top\n" +
+                        "objectClass: domain\n\n" ),
+                indexes =
+                {
+                    @CreateIndex( attribute = "objectClass" ),
+                    @CreateIndex( attribute = "dc" ),
+                    @CreateIndex( attribute = "ou" )
+                })
+        },
+        additionalInterceptors = { KeyDerivationInterceptor.class })
+    @CreateLdapServer (
+        transports =
+        {
+            @CreateTransport( protocol = "LDAP",  port = LDAP_PORT),
+            @CreateTransport( protocol = "LDAPS", port = LDAPS_PORT)
+        },
+        certificatePassword="secret")
+    //@formatter:on
+    public void createLdap(final String[] args) throws Exception, IOException, ClassNotFoundException, FileNotFoundException {
+
+        directoryService = DSAnnotationProcessor.getDirectoryService();
+
+        if (args != null && args.length > 0)
+        {
+            final Map<String, String> map = new HashMap<String, String>();
+            for (String ldifFile : args)
+            {
+
+                final String ldifContent = StrSubstitutor.replace(FileUtils.readFileToString(new File(ldifFile), "UTF-8"),
+                        map);
+                LOGGER.debug(ldifContent);
+                final SchemaManager schemaManager = directoryService.getSchemaManager();
+                try
+                {
+                    for (LdifEntry ldifEntry : new LdifReader(IOUtils.toInputStream(ldifContent)))
+                    {
+                        directoryService.getAdminSession().add(new DefaultEntry(schemaManager, ldifEntry.getEntry()));
+                    }
+                }
+                catch (Exception e)
+                {
+                    e.printStackTrace();
+                    throw e;
+                }
+            }
+        }
+
+        final CreateLdapServer createLdapServer = (CreateLdapServer) AnnotationUtils.getInstance(CreateLdapServer.class);
+        ldapServer = ServerAnnotationProcessor.instantiateLdapServer(createLdapServer, directoryService);
+        ldapServer.start();
+
+    }
+
+    /**
+     * Stops LDAP server and shuts down the directory service.
+     *
+     * @throws Exception
+     */
+    public void stopLdap() throws Exception {
+
+        ldapServer.stop();
+        directoryService.shutdown();
+        FileUtils.deleteDirectory(directoryService.getInstanceLayout().getInstanceDirectory());
+    }
+
+
+    /**
+     * Creates a server socket and only waits for the stop command from a client.
+     *
+     * @throws Exception
+     */
+    protected void waitForStop() throws Exception
+    {
+        final ServerSocket srv = new ServerSocket(SERVER_PORT);
+        boolean isStop = false;
+        do
+        {
+            // Wait for connection from client.
+            Socket socket = srv.accept();
+            System.out.println("Incomming connection.");
+            socket.setSoTimeout(SOCKET_TIMEOUT);
+            BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+            try
+            {
+                isStop = STOP_CMD.equals(rd.readLine());
+            }
+            finally
+            {
+                rd.close();
+            }
+            System.out.println("Stop command: " + isStop);
+            socket.close();
+        }
+        while (!isStop);
+    }
+
+}

Added: branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/test/LdapExtLoginModuleTestCase.java
===================================================================
--- branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/test/LdapExtLoginModuleTestCase.java	                        (rev 0)
+++ branches/JBPAPP_5/testsuite/src/main/org/jboss/test/security/test/LdapExtLoginModuleTestCase.java	2014-03-24 14:30:55 UTC (rev 114775)
@@ -0,0 +1,286 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2014, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.test;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+import org.jboss.logging.Logger;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.auth.callback.UsernamePasswordHandler;
+import org.jboss.test.JBossTestCase;
+import org.jboss.test.security.ldapext.FakePasswordProvider;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.FailedLoginException;
+import javax.security.auth.login.LoginContext;
+import java.io.File;
+import java.lang.reflect.Method;
+import java.security.acl.Group;
+import java.util.HashMap;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import static org.jboss.test.HttpInvokerHelper.withHttpHAInvoker;
+
+/**
+ * @author zroubali at redhat.com
+ */
+public class LdapExtLoginModuleTestCase extends JBossTestCase {
+
+    private static Logger log = Logger.getLogger(LdapExtLoginModuleTestCase.class);
+
+    private static final Long TIMEOUT = new Long(5000);
+
+    private static final long WAIT_TIMEOUT = TIMEOUT * 4;
+
+
+    protected void setUp() throws Exception {
+
+        Configuration.setConfiguration(new TestConfig());
+        super.setUp();
+        log = getLog();
+    }
+
+    public static Test suite() throws Exception {
+        return getDeploySetup(LdapExtLoginModuleTestCase.class, withHttpHAInvoker());
+    }
+
+
+    static class TestConfig extends Configuration {
+        public void refresh() {
+        }
+
+        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
+            AppConfigurationEntry[] entry = null;
+            try {
+                Class[] parameterTypes = {};
+                Method m = getClass().getDeclaredMethod(name, parameterTypes);
+                Object[] args = {};
+                entry = (AppConfigurationEntry[]) m.invoke(this, args);
+            } catch (Exception e) {
+            }
+            return entry;
+        }
+
+
+        AppConfigurationEntry[] testCorrectCredentials() {
+            AppConfigurationEntry[] entry = {generateLoginModuleConfiguration(null)};
+            return entry;
+        }
+
+        AppConfigurationEntry[] testWrongCredentials() {
+            AppConfigurationEntry[] entry = {generateLoginModuleConfiguration(null)};
+            return entry;
+        }
+
+        AppConfigurationEntry[] testCommandEXT() {
+            AppConfigurationEntry[] entry = {generateLoginModuleConfiguration(generateCommand("EXT"))};
+            return entry;
+        }
+
+        AppConfigurationEntry[] testCommandEXTC() {
+            AppConfigurationEntry[] entry = {generateLoginModuleConfiguration(generateCommand("EXTC"))};
+            return entry;
+        }
+
+        AppConfigurationEntry[] testCommandEXTCWithExpiration() {
+            AppConfigurationEntry[] entry = {generateLoginModuleConfiguration(generateCommand("EXTC:"+TIMEOUT.toString(), "fake 1"))};
+            return entry;
+        }
+
+
+        private AppConfigurationEntry generateLoginModuleConfiguration(String bindCredentialValue) {
+
+            if (bindCredentialValue == null) {
+                bindCredentialValue = "secret";
+            }
+
+            String name = "org.jboss.security.auth.spi.LdapExtLoginModule";
+            HashMap options = new HashMap();
+            options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
+            options.put("java.naming.provider.url", "ldap://localhost:10389/");
+            options.put("java.naming.security.authentication", "simple");
+            options.put("throwValidateError", "true");
+
+            options.put("bindDN", "uid=admin,ou=system");
+            options.put("bindCredential", bindCredentialValue);
+            options.put("baseCtxDN", "ou=People,dc=jboss,dc=org");
+            options.put("baseFilter", "(uid={0})");
+
+            options.put("rolesCtxDN", "ou=Roles,dc=jboss,dc=org");
+            options.put("roleFilter", "(|(objectClass=referral)(member={1}))");
+            options.put("roleAttributeID", "cn");
+
+            return new AppConfigurationEntry(name,
+                    AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
+        }
+
+    }
+
+
+    public LdapExtLoginModuleTestCase(String testName) {
+        super(testName);
+    }
+
+    public void testCorrectCredentials() throws Exception {
+
+        Subject subject = doLogin("testCorrectCredentials", "jduke", "theduke");
+
+        Set groups = subject.getPrincipals(Group.class);
+        Set principals = subject.getPrincipals();
+        assertTrue("Principals contains Roles", groups.contains(new SimplePrincipal("Roles")));
+        Group roles = (Group) groups.iterator().next();
+        assertTrue("Echo is a role", roles.isMember(new SimplePrincipal("Echo")));
+        assertTrue("TheDuke is a role", roles.isMember(new SimplePrincipal("TheDuke")));
+
+    }
+
+
+    public void testWrongCredentials() throws Exception {
+
+        try {
+            doLogin("testWrongCredentials", "jduke", "wrong");
+
+            // we should'n get here -> fail
+            fail("User jduke should not be authorized with wrong password.");
+        } catch (FailedLoginException exp) {
+            // user wasn't authorized -> OK
+        }
+    }
+
+    public void testCommandEXT() throws Exception {
+
+        FakePasswordProvider.resetAccessCounter();
+
+        // Access #1
+        doLogin("testCommandEXT");
+        assertEquals("Access #1 should not be cached.", 1, FakePasswordProvider.getAccessCounter());
+
+        // Access #2
+        doLogin("testCommandEXT");
+        assertEquals("Access #2 should not be cached.", 2, FakePasswordProvider.getAccessCounter());
+
+        // Access #3
+        doLogin("testCommandEXT");
+        assertEquals("Access #3 should not be cached.", 3, FakePasswordProvider.getAccessCounter());
+
+
+        FakePasswordProvider.resetAccessCounter();
+    }
+
+    public void testCommandEXTC() throws Exception {
+
+        FakePasswordProvider.resetAccessCounter();
+
+        // Access #1
+        doLogin("testCommandEXTC");
+        assertEquals("Access #1 should not be cached.", 1, FakePasswordProvider.getAccessCounter());
+
+        // Access #2
+        doLogin("testCommandEXTC");
+        assertEquals("Access #2 should be cached.", 1, FakePasswordProvider.getAccessCounter());
+
+        // Access #3
+        doLogin("testCommandEXTC");
+        assertEquals("Access #3 should be cached.", 1, FakePasswordProvider.getAccessCounter());
+
+        FakePasswordProvider.resetAccessCounter();
+    }
+
+
+    public void testCommandEXTCWithExpiration() throws Exception {
+
+        FakePasswordProvider.resetAccessCounter();
+
+        // Access #1
+        doLogin("testCommandEXTCWithExpiration", "jbean", "thebean");
+        assertEquals("Access #1 should not be cached.", 1, FakePasswordProvider.getAccessCounter());
+
+        // Access #2
+        doLogin("testCommandEXTCWithExpiration", "jbean", "thebean");
+        assertEquals("Access #2 should be cached.", 1, FakePasswordProvider.getAccessCounter());
+
+        // wait for timeout expiration
+        Thread.sleep(WAIT_TIMEOUT);
+
+        // Access #3
+        doLogin("testCommandEXTCWithExpiration", "jbean", "thebean");
+        assertEquals("Access #3 should not be cached.", 2, FakePasswordProvider.getAccessCounter());
+
+
+        FakePasswordProvider.resetAccessCounter();
+    }
+
+
+    public Subject doLogin(String loginContextName) throws Exception{
+
+        return doLogin(loginContextName, "jduke", "theduke");
+    }
+
+
+    public Subject doLogin(String loginContextName, String user, String password) throws  Exception{
+
+        UsernamePasswordHandler handler = new UsernamePasswordHandler(user, password.toCharArray());
+        LoginContext lc = new LoginContext(loginContextName, handler);
+
+        lc.login();
+        Subject subject = lc.getSubject();
+        System.out.println("Subject: " + subject);
+        lc.logout();
+
+        return subject;
+    }
+
+    public static String generateCommand(String option){
+        return  generateCommand(option, "");
+    }
+
+    public static String generateCommand(String option, String param){
+
+        // First check for java.exe or java as the binary
+        File java = new File(System.getProperty("java.home"), "/bin/java");
+        File javaExe = new File(System.getProperty("java.home"), "/bin/java.exe");
+        String jre;
+        if (java.exists())
+            jre = java.getAbsolutePath();
+        else
+            jre = javaExe.getAbsolutePath();
+        // Build the command to run this jre
+        String cmd = jre + " -cp "
+                + FakePasswordProvider.class.getProtectionDomain().getCodeSource().getLocation().getPath()
+                + " org.jboss.test.security.ldapext.FakePasswordProvider " + param;
+
+
+        String out =  "{" + option + "}" + cmd;
+        System.out.println(out);
+        return  out;
+    }
+
+    public static void main(java.lang.String[] args) {
+
+        TestSuite suite = new TestSuite(LdapExtLoginModuleTestCase.class);
+        junit.textui.TestRunner.run(suite);
+    }
+
+}

Added: branches/JBPAPP_5/testsuite/src/resources/security/ldapext/test.ldif
===================================================================
--- branches/JBPAPP_5/testsuite/src/resources/security/ldapext/test.ldif	                        (rev 0)
+++ branches/JBPAPP_5/testsuite/src/resources/security/ldapext/test.ldif	2014-03-24 14:30:55 UTC (rev 114775)
@@ -0,0 +1,56 @@
+# Example1: "jduke" - "TheDuke", "Echo", "Admin"
+#baseCtxDN= ou=People,dc=jboss,dc=org
+#baseFilter= (uid={0})
+#rolesCtxDN= ou=Roles,dc=jboss,dc=org
+#roleFilter= (|(objectClass=referral)(member={1}))
+#roleAttributeID= cn
+#java.naming.referral= follow
+
+dn: ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: organizationalUnit
+ou: People
+
+dn: uid=jduke,ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: uidObject
+objectclass: person
+uid: jduke
+cn: Java Duke
+sn: Duke
+userPassword: theduke
+
+dn: uid=jbean,ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: uidObject
+objectclass: person
+uid: jbean
+cn: Java Bean
+sn: Bean
+userPassword: thebean
+
+dn: ou=Roles,dc=jboss,dc=org
+objectclass: top
+objectclass: organizationalUnit
+ou: Roles
+
+dn: cn=Echo,ou=Roles,dc=jboss,dc=org
+objectClass: groupOfNames
+objectClass: top
+cn: Echo
+description: the JBossAdmin group
+member: uid=jduke,ou=People,dc=jboss,dc=org
+
+dn: cn=TheDuke,ou=Roles,dc=jboss,dc=org
+objectClass: groupOfNames
+objectClass: top
+cn: TheDuke
+description: TheDuke role context
+member: uid=jduke,ou=People,dc=jboss,dc=org
+
+dn: cn=JBean,ou=Roles,dc=jboss,dc=org
+objectClass: groupOfNames
+objectClass: top
+cn: JBean
+description: TheDuke role context
+member: uid=jbean,ou=People,dc=jboss,dc=org



More information about the jboss-cvs-commits mailing list