User: d_jencks
  Date: 01/09/11 21:55:41

  Added:       src/main/org/jboss/test/security/test
                        EJBAccessUnitTestCase.java EJBSpecUnitTestCase.java
                        LoginContextUnitTestCase.java
                        NamespacePermissionsUnitTestCase.java
                        PermissionNameUnitTestCase.java
                        ProjRepositoryUnitTestCase.java
                        SecurityProxyUnitTestCase.java
  Removed:     src/main/org/jboss/test/security/test TestEJBAccess.java
                        TestEJBSpec.java TestLoginContext.java
                        TestNamespacePermissions.java
                        TestPermissionName.java TestProjRepository.java
                        TestSecurityProxy.java
  Log:
  Changed naming scheme of tests to *UnitTestCase.java for short running tests and 
*StressTestCase.java for lengthy tests.  Made tests-unit and tests-stress targets in 
build.xml
  
  Revision  Changes    Path
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/EJBAccessUnitTestCase.java
  
  Index: EJBAccessUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.IOException;
  import java.rmi.RemoteException;
  import javax.ejb.CreateException;
  import javax.naming.InitialContext;
  import javax.naming.NamingException;
  import javax.rmi.PortableRemoteObject;
  import javax.security.auth.callback.*;
  import javax.security.auth.login.*;
  
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  
  import org.jboss.test.util.Deploy;
  
  import org.jboss.test.security.interfaces.StatelessSession;
  import org.jboss.test.security.interfaces.StatelessSessionHome;
  
  /**
   * Tests of the secure access to EJBs.
   * 
   * @author [EMAIL PROTECTED]
   */
  public class EJBAccessUnitTestCase
     extends TestCase
  {
     private boolean deployed;
  
     public EJBAccessUnitTestCase(String name)
     {
        super(name);
     }
  
     /**
      * Setup the test suite.
      */
     public static Test suite() {
        TestSuite suite = new TestSuite();
          
        // add a test case to deploy our support applications
        String filename = "security.jar";
        suite.addTest(new Deploy.Deployer(filename));
  
        suite.addTest(new TestSuite(EJBAccessUnitTestCase.class));
        
        // add a test case to undeploy our support applications
        suite.addTest(new Deploy.Undeployer(filename));
  
        return suite;
     }
     
     /** Deploy the security ejb jar one time
      */
     protected void setUp() throws Exception
     {
        //Deploy.deploy("security.jar");
     }
  
     public void testDeclarativeAccess() throws Exception
     {
        StatelessSessionClient.runAs("scott", "echoman".toCharArray());
        try
        {
           StatelessSessionClient.runAs("stark", "javaman".toCharArray());
           fail("stark should NOT be able to access StatelessSession bean");
        }
        catch(Exception e)
        {
        }
     }
  
     /** Test access to a stateless session bean that 
      */
     public void testUnsecureAccess() throws Exception
     {
        String securityDomain = System.getProperty("securityDomain");
        /* If the security ejbs are running with a global security-domain
           set, then every bean has a security manager regardless of
           what its container config is. In this case we expect the
           accessUnsecureStatelessSession method to fail and will fail
           the test if it does not.
        */
        if( securityDomain != null )
        {
           try
           {
              accessUnsecureStatelessSession();
              fail("UnsecureStatelessSession was accessible");
           }
           catch(Exception e)
           {
              System.out.println("UnsecureStatelessSession not accessible");
           }
        }
        else
        {    /* There is not global security-domain so the UnsecureStatelessSession
                bean should be accessible without any login
             */
           accessUnsecureStatelessSession();
        }
     }
  
     private void accessUnsecureStatelessSession() throws Exception
     {
        InitialContext jndiContext = new InitialContext();
        StatelessSession bean = null;
        Object obj = jndiContext.lookup("UnsecureStatelessSession");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found Unsecure StatelessSessionHome");
  
        try
        {
           bean = home.create();
           System.out.println("Created UnsecureStatelessSession");
           System.out.println("Bean.echo('Hello') -> "+bean.echo("Hello"));
           System.out.println("Bean.npeError() -> ");
           bean.npeError();
        }
        catch(Exception e)
        {
           System.out.println("Produced error as expected");
        }
     }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/EJBSpecUnitTestCase.java
  
  Index: EJBSpecUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.IOException;
  import java.net.InetAddress;
  import java.rmi.RemoteException;
  import javax.ejb.CreateException;
  import javax.ejb.Handle;
  import javax.management.ObjectName;
  import javax.naming.InitialContext;
  import javax.naming.NamingException;
  import javax.rmi.PortableRemoteObject;
  import javax.jms.Message;
  import javax.jms.Queue;
  import javax.jms.QueueConnection;
  import javax.jms.QueueConnectionFactory;
  import javax.jms.QueueReceiver;
  import javax.jms.QueueSender;
  import javax.jms.QueueSession;
  import javax.jms.Session;
  import javax.security.auth.login.*;
  
  import org.jboss.test.security.interfaces.StatelessSession;
  import org.jboss.test.security.interfaces.StatelessSessionHome;
  
  import junit.extensions.TestSetup;
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  
  import org.jboss.jmx.connector.rmi.RMIConnector;
  import org.jboss.test.util.AppCallbackHandler;
  import org.jboss.test.util.Deploy;
  
  /** Test of EJB spec conformace using the security-spec.jar
   deployment unit. These test the basic role based access model.
   
   @author [EMAIL PROTECTED]
   @version $Revision: 1.1 $
   */
  public class EJBSpecUnitTestCase
     extends TestCase
  {
     static String username = "scott";
     static char[] password = "echoman".toCharArray();
     static String QUEUE_FACTORY = "ConnectionFactory";
     
     LoginContext lc;
     boolean loggedIn;
     
     public EJBSpecUnitTestCase(String name)
     {
        super(name);
     }
     
     protected void setUp() throws Exception
     {
        // Deploy.deploy("security-spec.jar");
     }
     
     /** Test that:
      1. SecureBean returns a non-null principal when getCallerPrincipal
      is called with a security context and that this is propagated
      to its Entity bean ref.
      
      2. UnsecureBean throws an IllegalStateException when getCallerPrincipal
      is called without a security context.
      */
     public void testGetCallerPrincipal() throws Exception
     {
        logout();
        System.out.println("+++ testGetCallerPrincipal()");
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.UnsecureStatelessSession2");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found Unsecure StatelessSessionHome");
        StatelessSession bean = home.create();
        System.out.println("Created spec.UnsecureStatelessSession2");
        
        try
        {
           // This should fail because echo calls getCallerPrincipal()
           bean.echo("Hello from nobody?");
           fail("Was able to call StatelessSession.echo");
        }
        catch(RemoteException e)
        {
           System.out.println("echo failed as expected");
        }
        bean.remove();
        
        login();
        obj = jndiContext.lookup("spec.StatelessSession2");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        home = (StatelessSessionHome) obj;
        System.out.println("Found spec.StatelessSession2");
        bean = home.create();
        System.out.println("Created spec.StatelessSession2");
        // Test that the Entity bean sees username as its principal
        String echo = bean.echo(username);
        System.out.println("bean.echo(username) = "+echo);
        assertTrue("username == echo", echo.equals(username));
        bean.remove();
     }
     
     /** Test that the calling principal is propagated across bean calls.
      */
     public void testPrincipalPropagation() throws Exception
     {
        System.out.println("+++ testPrincipalPropagation");
        logout();
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.UnsecureStatelessSession2");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found Unsecure StatelessSessionHome");
        StatelessSession bean = home.create();
        System.out.println("Created spec.UnsecureStatelessSession2");
        System.out.println("Bean.forward('Hello') -> "+bean.forward("Hello"));
        bean.remove();
     }
     
     /** Test that the echo method is accessible by an Echo
      role. Since the noop() method of the StatelessSession
      bean was not assigned any permissions it should not be
      accessible by any user.
      */
     public void testMethodAccess() throws Exception
     {
        System.out.println("+++ testMethodAccess");
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.StatelessSession");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found StatelessSessionHome");
        StatelessSession bean = home.create();
        System.out.println("Created spec.StatelessSession");
        System.out.println("Bean.echo('Hello') -> "+bean.echo("Hello"));
        
        try
        {
           // This should not be allowed
           bean.noop();
           fail("Was able to call StatelessSession.noop");
        }
        catch(RemoteException e)
        {
           System.out.println("StatelessSession.noop failed as expected");
        }
        bean.remove();
     }
     
     /** Test that a user with a role that has not been assigned any
      method permissions in the ejb-jar descriptor is able to access a
      method that has been marked as unchecked.
      */
     public void testUnchecked() throws Exception
     {
        System.out.println("+++ testUnchecked");
        // Login as scott to create the bean
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.StatelessSession");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found spec.StatelessSession Home");
        StatelessSession bean = home.create();
        System.out.println("Created spec.StatelessSession");
        // Logout and login back in as stark to test access to the unchecked method
        logout();
        login("stark", "javaman".toCharArray());
        bean.unchecked();
        System.out.println("Called Bean.unchecked()");
        logout();
     }
     
     /** Test that user scott who has the Echo role is not able to
      access the StatelessSession2.excluded method even though
      the Echo role has been granted access to all methods of
      StatelessSession2 to test that the excluded-list takes
      precendence over the method-permissions.
      */
     public void testExcluded() throws Exception
     {
        System.out.println("+++ testExcluded");
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.StatelessSession2");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found spec.StatelessSession2 Home");
        StatelessSession bean = home.create();
        System.out.println("Created spec.StatelessSession2");
        try
        {
           bean.excluded();
           fail("Was able to call Bean.excluded()");
        }
        catch(Exception e)
        {
           System.out.println("Bean.excluded() failed as expected");
           // This is what we expect
        }
        logout();
     }
     
     /** This method tests the following call chains:
      1. RunAsStatelessSession.echo() -> PrivateEntity.echo()
      2. RunAsStatelessSession.noop() -> RunAsStatelessSession.excluded()
      3. RunAsStatelessSession.forward() -> StatelessSession.echo()
      1. Should succeed because the run-as identity of RunAsStatelessSession
      is valid for accessing PrivateEntity.
      2. Should succeed ecause the run-as identity of RunAsStatelessSession
      is valid for accessing RunAsStatelessSession.excluded().
      3. Should fail because the run-as identity of RunAsStatelessSession
      is not Echo.
      */
     public void testRunAs() throws Exception
     {
        System.out.println("+++ testRunAs");
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.RunAsStatelessSession");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found RunAsStatelessSession Home");
        StatelessSession bean = home.create();
        System.out.println("Created spec.RunAsStatelessSession");
        System.out.println("Bean.echo('Hello') -> "+bean.echo("Hello"));
        bean.noop();
        System.out.println("Bean.noop(), ok");
        
        try
        {
           // This should not be allowed
           bean.forward("Hello");
           fail("Was able to call RunAsStatelessSession.forward");
        }
        catch(RemoteException e)
        {
           System.out.println("StatelessSession.forward failed as expected");
        }
        bean.remove();
     }
  
     /** Test that an MDB with a run-as identity is able to access secure EJBs
      that require the identity.
      */
     public void testMDBRunAs() throws Exception
     {
        System.out.println("+++ testMDBRunAs");
        logout();
        InitialContext jndiContext = new InitialContext();
        QueueConnectionFactory queueFactory = (QueueConnectionFactory) 
jndiContext.lookup(QUEUE_FACTORY);
        Queue que = (Queue) jndiContext.lookup("queue/A");
        QueueConnection queueConn = queueFactory.createQueueConnection();
        QueueSession session = queueConn.createQueueSession(false, 
Session.AUTO_ACKNOWLEDGE);
        Message msg = session.createMessage();
        msg.setStringProperty("arg", "HelloMDB");
        QueueSender sender = session.createSender(que);
        sender.send(msg);
        sender.close();
        System.out.println("Sent msg to queue/A");
        QueueReceiver recv = session.createReceiver(que);
        msg = recv.receive(5000);
        System.out.println("Recv msg: "+msg);
        recv.close();
        session.close();
        queueConn.close();
     }
  
     /** Test the security behavior of handles. To obtain secured bean from
        a handle that the handle be 
      */
     public void testHandle() throws Exception
     {
        System.out.println("+++ testHandle");
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("spec.StatelessSession");
        obj = PortableRemoteObject.narrow(obj, StatelessSessionHome.class);
        StatelessSessionHome home = (StatelessSessionHome) obj;
        System.out.println("Found StatelessSessionHome");
        StatelessSession bean = home.create();
        System.out.println("Created spec.StatelessSession");
        Handle h = bean.getHandle();
        System.out.println("Obtained handle: "+h);
        bean = (StatelessSession) h.getEJBObject();
        System.out.println("Obtained bean from handle: "+bean);
        System.out.println("Bean.echo('Hello') -> "+bean.echo("Hello"));
        logout();
  
        /* Attempting to obtain the EJB fron the handle without security
         association present should fail
        */
        try
        {
           bean = (StatelessSession) h.getEJBObject();
           fail("Should not be able to obtain a bean without login info");
        }
        catch(Exception e)
        {
           System.out.println("Obtaining bean from handle failed as expected, 
e="+e.getMessage());
        }
  
        // One should be able to obtain a handle without a login
        h = bean.getHandle();
        login();
        // Now we should be able to obtain and use the secure bean
        bean = (StatelessSession) h.getEJBObject();
        System.out.println("Obtained bean from handle: "+bean);
        System.out.println("Bean.echo('Hello') -> "+bean.echo("Hello"));
        logout();
     }
  
     /** Login as user scott using the conf.name login config or
      'spec-test' if conf.name is not defined.
      */
     private void login() throws Exception
     {
        login(username, password);
     }
     private void login(String username, char[] password) throws Exception
     {
        if( loggedIn )
           return;
        
        lc = null;
        String confName = System.getProperty("conf.name", "spec-test");
        AppCallbackHandler handler = new AppCallbackHandler(username, password);
        System.out.println("Creating LoginContext("+confName+")");
        lc = new LoginContext(confName, handler);
        lc.login();
        System.out.println("Created LoginContext, subject="+lc.getSubject());
        loggedIn = true;
     }
     private void logout() throws Exception
     {
        if( loggedIn )
        {
           loggedIn = false;
           lc.logout();
        }
     }
  
     private static void flushAuthCache() throws Exception
     {
        String serverName = InetAddress.getLocalHost().getHostName();
        String connectorName = "jmx:" +serverName+ ":rmi";
        RMIConnector server = (RMIConnector) new 
InitialContext().lookup(connectorName);
        ObjectName jaasMgr = new ObjectName("Security:name=JaasSecurityManager");
        // Ask the deployer for the getWarDeployerName
        Object[] params = {"other"};
        String[] signature = {"java.lang.String"};
        server.invoke(jaasMgr, "flushAuthenticationCache", params, signature);
     }
  
     /**
      * Setup the test suite.
      */
     public static Test suite()
     {
        TestSuite suite = new TestSuite();
        suite.addTest(new TestSuite(EJBSpecUnitTestCase.class));
          
        final String filename = "security-spec.jar";
  
        // Create an initializer for the test suite
        TestSetup wrapper= new TestSetup(suite)
        {
            protected void setUp() throws Exception
            {
               Deploy.deploy(filename);
               flushAuthCache();
            }
            protected void tearDown() throws Exception
            {
               Deploy.undeploy(filename);
            }
        };
        return wrapper;
     }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/LoginContextUnitTestCase.java
  
  Index: LoginContextUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.util.HashMap;
  import java.security.CodeSource;
  import java.security.Permission;
  import java.security.PermissionCollection;
  import java.security.Policy;
  import javax.security.auth.Subject;
  import javax.security.auth.login.AppConfigurationEntry;
  import javax.security.auth.login.Configuration;
  import javax.security.auth.login.LoginContext;
  
  /**
   * A JUnit TestCase for the JAAS LoginContext usage.
   *
   * @author [EMAIL PROTECTED]
   * @version $Revision: 1.1 $
   */
  public class LoginContextUnitTestCase
     extends junit.framework.TestCase
  {
     Subject subject1;
     Subject subject2;
  
     static class MyConfig extends Configuration
     {
        AppConfigurationEntry[] entry;
        MyConfig()
        {
           entry = new AppConfigurationEntry[2];
           HashMap opt0 = new HashMap();
           opt0.put("principal", "starksm");
           entry[0] = new 
AppConfigurationEntry("org.jboss.security.plugins.samples.IdentityLoginModule", 
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, opt0);
           entry[1] = new 
AppConfigurationEntry("org.jboss.security.plugins.samples.RolesLoginModule", 
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap());
        }
  
        public AppConfigurationEntry[] getAppConfigurationEntry(String appName)
        {
           return entry;
        }
        public void refresh()
        {
        }
     }
  
     public LoginContextUnitTestCase(String name)
     {
        super(name);
     }
  
     protected void setUp() throws Exception
     {
        Configuration.setConfiguration(new MyConfig());
     }
  
     /**
      * This method caueses errors, because newer junit this is a static.
      * and thus can not be overridden.
      * 
     protected void assertEquals(String msg, boolean expected, boolean actual)
     {
        assertTrue(msg, (expected == actual));
     }
     */
    
     public void testLogin1() throws Exception
     {
        subject1 = new Subject();
        LoginContext lc = new LoginContext("LoginContext", subject1);
        lc.login();
        Subject lcSubject = lc.getSubject();
        assertTrue("subject == lcSubject",  subject1 == lcSubject );
     }
     public void testLogin2() throws Exception
     {
        subject2 = new Subject();
        LoginContext lc = new LoginContext("LoginContext", subject2);
        lc.login();
        Subject lcSubject = lc.getSubject();
        assertTrue("subject == lcSubject",  subject2 == lcSubject );
     }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/NamespacePermissionsUnitTestCase.java
  
  Index: NamespacePermissionsUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.FilePermission;
  import java.net.URL;
  import java.security.CodeSource;
  import java.security.Permission;
  import java.security.PermissionCollection;
  import java.security.Policy;
  
  /**
   * A JUnit TestCase for the NamespacePermissions and NamespacePermission
   * classes.
   *
   * @author [EMAIL PROTECTED]
   * @version $Revision: 1.1 $
   */
  public class NamespacePermissionsUnitTestCase
     extends junit.framework.TestCase
  {
     PermissionCollection pc;
  
     public NamespacePermissionsUnitTestCase(String name)
     {
        super(name);
     }
  
     protected void setUp() throws Exception
     {
        pc = new NamespacePermissionCollection();
        NamespacePermission p = new NamespacePermission("starksm/Project1", "r---");
        pc.add(p);
        p = new NamespacePermission("starksm/Project1/Documents/readme.html", "rw--");
        pc.add(p);
        p = new NamespacePermission("starksm/Project1/Documents/Public", "rw--");
        pc.add(p);
        p = new NamespacePermission("starksm/Project1/Documents/Public/Private", 
"----");
        pc.add(p);
        p = new NamespacePermission("Project1/Documents/Public", "r---");
        pc.add(p);
        p = new NamespacePermission("Project1/Documents/Public/starksm", "----");
        pc.add(p);
     }
     protected void tearDown()
     {
        pc = null;
     }
  
     /**
      * This method caueses errors, because newer junit this is a static.
      * and thus can not be overridden.
      * 
     protected void assertEquals(String msg, boolean expected, boolean actual)
     {
        assert(msg, (expected == actual));
     }
     */
     
     /**
      * Test the NamespacePermissionCollection implies method for various
      * permission that should be implied by the setup PermissionCollection.
      */
     public void testImplied()
     {
        NamespacePermission p = new 
NamespacePermission("Project1/Documents/Public/view1.jpg", "r---");
        boolean implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
          
        p = new NamespacePermission("starksm/Project1", "r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
        p = new NamespacePermission("starksm/Project1/Documents/Folder1", "r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
        p = new NamespacePermission("starksm/Project1/Documents/readme.html", "r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
        p = new NamespacePermission("starksm/Project1/Documents/readme.html", "rw--");
        implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
        p = new NamespacePermission("starksm/Project1/Documents/readme.html", "-w--");
        implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
        p = new NamespacePermission("starksm/Project1/Documents/Public/readme.html", 
"r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), true, implied);
        p = new NamespacePermission("starksm/Project1/Documents/Public/readme.html", 
"rw--");
        implied = pc.implies(p);
        //assertEquals(p.toString(), true, implied);
     }
  
     /**
      * Test the NamespacePermissionCollection implies method for various
      * permission that should NOT be implied by the setup PermissionCollection.
      */
     public void testNotImplied()
     {
        NamespacePermission p = new NamespacePermission("Project1/Drawings/view1.jpg", 
"r---");
        boolean implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new NamespacePermission("Project1/Documents/view1.jpg", "r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new NamespacePermission("starksm/Project1/Documents/readme.html", "rw-d");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new NamespacePermission("starksm/Project1/Documents", "rw--");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new 
NamespacePermission("starksm/Project1/Documents/Public/Private/readme.html", "r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new 
NamespacePermission("starksm/Project1/Documents/Public/Private/readme.html", "rw--");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new NamespacePermission("starksm/Project1/Documents/Folder1/readme.html", 
"rw--");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
        p = new NamespacePermission("Project1/Documents/Public/starksm/.bashrc", 
"r---");
        implied = pc.implies(p);
        assertEquals(p.toString(), false, implied);
     }
  
     public static void main(String[] args) throws Exception
     {
        NamespacePermissionsUnitTestCase tst = new 
NamespacePermissionsUnitTestCase("main");
        tst.setUp();
        tst.testImplied();
        tst.testNotImplied();
     }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/PermissionNameUnitTestCase.java
  
  Index: PermissionNameUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.FilePermission;
  import java.net.URL;
  import java.security.CodeSource;
  import java.security.Permission;
  import java.security.PermissionCollection;
  import java.security.Policy;
  
  /**
   * A JUnit TestCase for the PermissionNames class.
   *
   * @author [EMAIL PROTECTED]
   * @version $Revision: 1.1 $
   */
  public class PermissionNameUnitTestCase
     extends junit.framework.TestCase
  {
     public PermissionNameUnitTestCase(String name)
     {
        super(name);
     }
  
     /**
      * This method caueses errors, because newer junit this is a static.
      * and thus can not be overridden.
      * 
     protected void assertEquals(String msg, boolean expected, boolean actual)
     {
        assertTrue(msg, (expected == actual));
     }
     */
     
     /**
      * Test the order of PermissionNames
      */
     public void testOrdering()
     {
        String s0 = "starksm/Project1/Documents/readme.html";
        String s1 = "starksm/Project1/Documents/Folder1/readme.html";
        String s2 = "starksm/Project1/Documents";
        PermissionName n0 = new PermissionName(s0);
        PermissionName n1 = new PermissionName(s1);
        PermissionName n2 = new PermissionName(s2);
  
        assertTrue(n0.toString(), s0.equals(n0.toString()));
        assertTrue(n1.toString(), s1.equals(n1.toString()));
        assertEquals(s0, 4, n0.size());
        assertEquals(s1, 5, n1.size());
        assertEquals(s2, 3, n2.size());
        assertEquals("n0 < n1", true, (n0.compareTo(n1) < 0));
        assertEquals("n0 > n2", true, (n0.compareTo(n2) > 0));
     }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/ProjRepositoryUnitTestCase.java
  
  Index: ProjRepositoryUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.rmi.RemoteException;
  import javax.naming.InitialContext;
  import javax.naming.directory.Attributes;
  import javax.security.auth.Subject;
  import javax.security.auth.login.LoginContext;
  import javax.security.auth.login.LoginException;
  import javax.transaction.TransactionRolledbackException;
  
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  
  import org.apache.log4j.Category;
  import org.apache.log4j.WriterAppender;
  import org.apache.log4j.NDC;
  import org.apache.log4j.PatternLayout;
  import org.apache.log4j.Priority;
  
  import org.jboss.security.SimplePrincipal;
  import org.jboss.test.security.interfaces.ProjRepository;
  import org.jboss.test.security.interfaces.ProjRepositoryHome;
  import org.jboss.test.security.ejb.project.support.DefaultName;
  import org.jboss.test.util.AppCallbackHandler;
  import org.jboss.test.util.Deploy;
  
  /**
   * The client driver for testing secure access to the ProjRepository bean.
   * Each test runs as one of 4 different users who each have different
   * levels of access. All attempt to do something they should not be able
   * to do so that all should see a SecurityException. The tests succeed
   * or fail based on whether the user can do what they should be able
   * to do and are stopped from not doing what they should not do. A failure
   * of the test only occurs if a user sees a SecurityException when they
   * should not, or a user does not see a SecurityException when they should.
   * This requires that this test module's accessTest ecpected values
   * be kept in synch with the resources/security/sample_policy.xml that
   * is deployed.
   * 
   * @author [EMAIL PROTECTED]
   * @version $Revision: 1.1 $
   */
  public class ProjRepositoryUnitTestCase
     extends TestCase
  {
      static String[] users = {"scott", "starksm", "guest", "nobody"};
      static String[] passwds = {"stark", "scott_stark", "guest", "badpass"};
      static String[] paths = {
          "Project1/Drawings/view1.jpg",
          "Project1/readme.html",
          "Project1/Documents/Private/passwords",
          "Project1/Documents/Public/readme.txt",
          "Project1/Documents/Public/starksm/.bashrc",
      };
      /** The indicies into the accessTest[] array */
      static int LOGIN = 0;
      static int CREATE = 1;
      static int PATH0 = 2;
      static int PATH1 = 3;
      static int PATH2 = 4;
      static int PATH3 = 5;
      static int PATH4 = 6;
      static int DELETE0 = 7; // rm Project1/Documents/Public/readme.txt
      static int DELETE1 = 8; // rm Project1/Documents/Public/starksm/.bashrc
  
      /** The expected success/failure flag for each access by user */
      static boolean[][] accessTests = {
          {true, true, true, true, true, true, false, true, false}, // scott
          {true, true, false, false, false, true, true, false, true}, // starksm
          {true, false, false, false, false, false, false, false, false}, // guest
          {false, false, false, false, false, false, false, false, false}, // nobody
      };
  
      int userIndex;
      LoginContext lc;
      ProjRepository bean;
  
      public ProjRepositoryUnitTestCase(String name)
      {
          super(name);
      }
  
      void runAs(int userIndex) throws Exception
      {
          try
          {
              lc = null;
              this.userIndex = userIndex;
              System.out.print("expect: ");
              for(int t = 0; t < accessTests[userIndex].length; t ++)
                  System.out.print(accessTests[userIndex][t]+", ");
              System.out.println();
              runAs();
          }
          finally
          {
              if( lc != null )
                  lc.logout();
              System.out.println("User logged out");
          }
      }
      void runAs() throws Exception
      {
          String username = users[userIndex];
          char[] password = passwds[userIndex].toCharArray();
          AppCallbackHandler handler = new AppCallbackHandler(username, password);
          bean = null;
          try
          {
              lc = new LoginContext("test-domain", handler);
              System.out.println("Created LoginContext, username="+username);
              lc.login();
              if( accessTests[userIndex][LOGIN] == false )
                  fail("Was able to login");
          }
          catch(Exception e)
          {
              lc = null;
              if( accessTests[userIndex][LOGIN] == true )
                  throw e;
              return;
          }
          System.out.println("Login complete");
          InitialContext iniCtx = new InitialContext();
          Object ref = iniCtx.lookup("ProjRepository");
          ProjRepositoryHome home = (ProjRepositoryHome) ref;
          System.out.println("Found ProjRepositoryHome");
          DefaultName projectName = new DefaultName("Project1");
          try
          {
              bean = home.create(projectName);
              System.out.println("Created ProjRepository");
              if( accessTests[userIndex][CREATE] == false )
                  fail("Was able to create project");
          }
          catch(RemoteException e)
          {
              if( accessTests[userIndex][CREATE] == true )
              {
                  printException(e);
                  throw e;
              }
              return;
          }
  
          System.out.println("Test of getItem()");
          int pathIndex = PATH0;
          for(int p = 0; p < paths.length; p ++, pathIndex ++)
          {
              DefaultName name = new DefaultName(paths[p]);
              tryGetItem(name, pathIndex);
          }
  
          System.out.println("Test of deleteItem()");
          // Try to delete an item
          try
          {
              DefaultName name = new 
DefaultName("Project1/Documents/Public/readme.txt");
              bean.deleteItem(name);
              if( accessTests[userIndex][DELETE0] == false )
                  fail("Was able to delete: "+name.toString());
              System.out.println("deleteItem("+name+") succeeded");
          }
          catch(RemoteException e)
          {
              System.out.println("Failed to deleteItem");
              if( accessTests[userIndex][DELETE0] == true )
              {
                  printException(e);
                  throw e;
              }
              // Restore the bean since it has been discared by the server
              restoreProjectBean();
          }
  
          try
          {
              DefaultName name = new 
DefaultName("Project1/Documents/Public/starksm/.bashrc");
              bean.deleteItem(name);
              if( accessTests[userIndex][DELETE1] == false )
                  fail("Was able to delete: "+name.toString());
              System.out.println("deleteItem("+name+") succeeded");
          }
          catch(RemoteException e)
          {
              System.out.println("Failed to deleteItem");
              if( accessTests[userIndex][DELETE1] == true )
              {
                  printException(e);
                  throw e;
              }
          }
      }
  
      public void testAsScott() throws Exception
      {
          runAs(0);
      }
  
      public void testAsStarksm() throws Exception
      {
          runAs(1);
      }
      public void testAsGuest() throws Exception
      {
          runAs(2);
      }
      public void testAsNobody() throws Exception
      {
          runAs(3);
      }
  
      /** Deploy the security ejb jar one time
       */
      protected void setUp() throws Exception
      {
          // Set up a log4j configuration that logs on the console.
          Category root = Category.getRoot();
          root.setPriority(Priority.DEBUG);
          root.addAppender(new WriterAppender(new PatternLayout("%x%m%n"), 
System.out));
        // Deploy.deploy("security.jar");
      }
  
     /**
      * Setup the test suite.
      */
     public static Test suite() {
        TestSuite suite = new TestSuite();
          
        // add a test case to deploy our support applications
        String filename = "security.jar";
        suite.addTest(new Deploy.Deployer(filename));
  
        suite.addTest(new TestSuite(ProjRepositoryUnitTestCase.class));
        
        // add a test case to undeploy our support applications
        suite.addTest(new Deploy.Undeployer(filename));
  
        return suite;
     }
     
      /** Try to invoke getItem for the given name on the bean.
          If this fails the bean will be discarded by the server,
          so if we expect the failure we restore the bean to
          be able continuing testing.
       */
      private void tryGetItem(DefaultName name, int pathIndex) throws Exception
      {
          try
          {
              Attributes attrs = bean.getItem(name);
              if( accessTests[userIndex][pathIndex] == false )
                  fail("Was able to access: "+name.toString());
          }
          catch(RemoteException e)
          {
              System.out.println("Failed to getItem, name="+name.toString());
              if( accessTests[userIndex][pathIndex] == true )
              {
                  throw e;
              }
              // Restore the bean since it has been discared by the server
              restoreProjectBean();
          }
      }
  
      private void restoreProjectBean() throws Exception
      {
          InitialContext iniCtx = new InitialContext();
          Object ref = iniCtx.lookup("ProjRepository");
          ProjRepositoryHome home = (ProjRepositoryHome) ref;
          DefaultName projectName = new DefaultName("Project1");
          bean = home.create(projectName);
          System.out.println("Restored ProjRepository");
      }
  
      static void printException(RemoteException e)
      {
          Throwable d = e.detail;
          if( d instanceof TransactionRolledbackException )
          {
              TransactionRolledbackException tre = (TransactionRolledbackException) d;
              d = tre.detail;
          }
          if( d instanceof RemoteException )
          {
              RemoteException re = (RemoteException) d;
              d = re.detail;
          }
  
          if( d instanceof SecurityException )
              System.out.println("Security Failure: "+e.getMessage());
          else if( d != null )
              d.printStackTrace();
          else
              e.printStackTrace();
      }
  
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/SecurityProxyUnitTestCase.java
  
  Index: SecurityProxyUnitTestCase.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.IOException;
  import java.rmi.RemoteException;
  import javax.ejb.CreateException;
  import javax.naming.InitialContext;
  import javax.naming.NamingException;
  import javax.rmi.PortableRemoteObject;
  import javax.security.auth.login.*;
  
  import junit.framework.Test;
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  
  import org.jboss.test.security.interfaces.Entity;
  import org.jboss.test.security.interfaces.EntityHome;
  import org.jboss.test.security.interfaces.IOSession;
  import org.jboss.test.security.interfaces.IOSessionHome;
  import org.jboss.test.util.AppCallbackHandler;
  import org.jboss.test.util.Deploy;
  
  /**
   * Simple tests of security stateless, stateful and entity beans via custom
   * security proxies.
   * 
   * @author [EMAIL PROTECTED]
   * @version $Revision: 1.1 $
   */
  public class SecurityProxyUnitTestCase
     extends TestCase
  {
     static String username = "scott";
     static char[] password = "echoman".toCharArray();
  
     LoginContext lc;
     boolean loggedIn;
  
     public SecurityProxyUnitTestCase(String name)
     {
        super(name);
     }
  
     /**
      * Setup the test suite.
      */
     public static Test suite() {
        TestSuite suite = new TestSuite();
          
        // add a test case to deploy our support applications
        String filename = "security-proxy.jar";
        suite.addTest(new Deploy.Deployer(filename));
  
        suite.addTest(new TestSuite(SecurityProxyUnitTestCase.class));
        
        // add a test case to undeploy our support applications
        suite.addTest(new Deploy.Undeployer(filename));
  
        return suite;
     }
     
     protected void setUp() throws Exception
     {
        // Deploy.deploy("security-proxy.jar");
     }
  
     public void testProxiedStatelessBean() throws Exception
     {
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("ProxiedStatelessBean");
        obj = PortableRemoteObject.narrow(obj, IOSessionHome.class);
        IOSessionHome home = (IOSessionHome) obj;
        System.out.println("Found ProxiedStatelessBean");
        IOSession bean = home.create();
        System.out.println("Created ProxiedStatelessBean");
        System.out.println("ProxiedStatelessBean.read() -> 
"+bean.read("/user/scott/.password"));
        bean.write("/user/scott/.password");
        System.out.println("ProxiedStatelessBean.write()");
        bean.remove();
        logout();
     }
  
     public void testProxiedStatefulBean() throws Exception
     {
        login();
        InitialContext jndiContext = new InitialContext();
        Object obj = jndiContext.lookup("ProxiedStatefulBean");
        obj = PortableRemoteObject.narrow(obj, IOSessionHome.class);
        IOSessionHome home = (IOSessionHome) obj;
        System.out.println("Found ProxiedStatefulBean");
        IOSession bean = home.create();
        System.out.println("Created ProxiedStatefulBean");
        System.out.println("ProxiedStatefulBean.read() -> 
"+bean.read("/user/scott/.password"));
        bean.write("/user/scott/.password");
        System.out.println("ProxiedStatefulBean.write()");
        bean.remove();
        logout();
     }
  
     /** Login as user scott using the conf.name login config or
         'spec-test' if conf.name is not defined.
     */
     private void login() throws Exception
     {
        login(username, password);
     }
     private void login(String username, char[] password) throws Exception
     {
        if( loggedIn )
           return;
  
        lc = null;
        String confName = System.getProperty("conf.name", "spec-test");
        AppCallbackHandler handler = new AppCallbackHandler(username, password);
        System.out.println("Creating LoginContext("+confName+")");
        lc = new LoginContext(confName, handler);
        lc.login();
        System.out.println("Created LoginContext, subject="+lc.getSubject());
        loggedIn = true;
     }
     private void logout() throws Exception
     {
        if( loggedIn )
        {
           loggedIn = false;
           lc.logout();
        }
     }
  }
  
  
  

_______________________________________________
Jboss-development mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/jboss-development

Reply via email to