User: stark   
  Date: 01/03/05 02:11:09

  Added:       src/main/org/jboss/test/security/test
                        AppCallbackHandler.java Deploy.java
                        NamespacePermission.java
                        NamespacePermissionCollection.java
                        PermissionName.java StatelessSessionClient.java
                        TestEJBAccess.java TestEJBSpec.java
                        TestLoginContext.java TestNamespacePermissions.java
                        TestPermissionName.java TestProjRepository.java
  Log:
  Tests of the JBossSX security framework
  
  Revision  Changes    Path
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/AppCallbackHandler.java
  
  Index: AppCallbackHandler.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.IOException;
  import javax.security.auth.callback.Callback;
  import javax.security.auth.callback.CallbackHandler;
  import javax.security.auth.callback.NameCallback;
  import javax.security.auth.callback.PasswordCallback;
  import javax.security.auth.callback.UnsupportedCallbackException;
  
  /**
  
  @author  [EMAIL PROTECTED]
  @version $Revision: 1.1 $
  */
  public class AppCallbackHandler implements CallbackHandler
  {
      private String username;
      private char[] password;
  
      public AppCallbackHandler(String username, char[] password)
      {
          this.username = username;
          this.password = password;
      }
  
      public void handle(Callback[] callbacks) throws
          IOException, UnsupportedCallbackException
      {
          for(int i = 0; i < callbacks.length; i++)
          {
              if (callbacks[i] instanceof NameCallback)
              {
                  NameCallback nc = (NameCallback) callbacks[i];
                  nc.setName(username);
              }
              else if(callbacks[i] instanceof PasswordCallback)
              {
                  PasswordCallback pc = (PasswordCallback) callbacks[i];
                  pc.setPassword(password);
              }
              else
              {
                  throw new UnsupportedCallbackException(callbacks[i], "Unrecognized 
Callback");
              }
          }
      }
  }
  
  
  
  
  1.1                  jbosstest/src/main/org/jboss/test/security/test/Deploy.java
  
  Index: Deploy.java
  ===================================================================
  package org.jboss.test.security.test;
  
  /** A singleton for deploying the common security.jar
  
  @author [EMAIL PROTECTED]
  @version $Revision: 1.1 $
  */
  public class Deploy
  {
      public static boolean deployed;
  
      /** Deploy the security ejb jar one time
       */
      static void deploy(String jarName) throws Exception
      {
          String noDeploy = System.getProperty("no-deploy");
          if( noDeploy != null || deployed )
              return;
  
          String deployDir = System.getProperty("jbosstest.deploy.dir");
          if( deployDir == null )
              deployDir = "../deploy";
  
        System.out.println("Deploying: "+ jarName);
        new org.jboss.jmx.client.Deployer().deploy(deployDir+'/' + jarName);
        deployed = true;
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/NamespacePermission.java
  
  Index: NamespacePermission.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.security.BasicPermission;
  import java.security.Permission;
  import java.security.PermissionCollection;
  import javax.naming.Name;
  
  /** A path like heirarchical permission.
  
  @author  [EMAIL PROTECTED]
  @version $Revsiion:$
  */
  public class NamespacePermission extends BasicPermission
  {
      private PermissionName fullName;
      private String actions;
  
      /** Creates new NamespacePermission */
      public NamespacePermission(String name, String actions)
      {
          super(name, actions);
          this.actions = actions;
          fullName = new PermissionName(name);
      }
      public NamespacePermission(Name name, String actions)
      {
          super(name.toString(), actions);
          this.actions = actions;
          fullName = new PermissionName(name);
      }
  
      public String getActions()
      {
          return actions;
      }
  
      public PermissionName getFullName()
      {
          return fullName;
      }
  
      public boolean implies(Permission p)
      {
          String pactions = p.getActions();
          boolean implied = true;
          for(int n = 0; n < actions.length(); n ++)
          {
              char a = actions.charAt(n);
              char pa = pactions.charAt(n);
              if( (a != '-' && pa != '-' && pa != a) )
              {
                  implied = false;
                  break;
              }
              else if( a == '-' && pa != '-' )
              {
                  implied = false;
                  break;
              }
          }
          return implied;
      }
  
      public PermissionCollection newPermissionCollection()
      {
        return new NamespacePermissionCollection();
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/NamespacePermissionCollection.java
  
  Index: NamespacePermissionCollection.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.security.Permission;
  import java.security.PermissionCollection;
  import java.util.ArrayList;
  import java.util.Enumeration;
  import java.util.Iterator;
  import java.util.Map;
  import java.util.NoSuchElementException;
  import java.util.Set;
  import java.util.SortedMap;
  import java.util.TreeMap;
  
  /** The PermissionCollection object for NamespacePermissions.
  
  @author  [EMAIL PROTECTED]
  @version $Revision: 1.1 $
  */
  public class NamespacePermissionCollection extends PermissionCollection
  {
      private TreeMap namespacePerms = new TreeMap();
      private TreeMap namespaceKeys = new TreeMap(new 
PermissionName.NameLengthComparator());
  
      /** Creates new NamespacePermission */
      public NamespacePermissionCollection()
      {
      }
  
      public void add(Permission permission)
      {
          if( this.isReadOnly() )
              throw new SecurityException("Cannot add permission to read-only 
collection");
          if( (permission instanceof NamespacePermission) == false )
              throw new IllegalArgumentException("Only NamespacePermission can be 
added, invalid="+permission);
          NamespacePermission np = (NamespacePermission) permission;
          PermissionName key = np.getFullName();
          ArrayList tmp = (ArrayList) namespacePerms.get(key);
          if( tmp == null )
          {
              tmp = new ArrayList();
              namespacePerms.put(key, tmp);
              namespaceKeys.put(key, key);
          }
          tmp.add(np);
      }
  
      /** Locate the closest permissions assigned to the namespace. This is based
       *on the viewing the permission name as a heirarchical PermissionName and
       */
      public boolean implies(Permission permission)
      {
          boolean implies = false;
          if( namespacePerms.isEmpty() == true )
              return false;
  
          NamespacePermission np = (NamespacePermission) permission;
          // See if there is an exact permission for the name
          PermissionName key = np.getFullName();
          ArrayList tmp = (ArrayList) namespacePerms.get(key);
          if( tmp == null )
          {   // Find the closest parent position.
              SortedMap headMap = namespacePerms.headMap(key);
              try
              {
                  PermissionName lastKey = (PermissionName) headMap.lastKey();
                  if( lastKey.isParent(key) == true )
                      tmp = (ArrayList) namespacePerms.get(lastKey);
                  else
                  {
                      PermissionName[] keys = {};
                      keys = (PermissionName[]) headMap.keySet().toArray(keys);
                      for(int k = keys.length-1; k >= 0; k --)
                      {
                          lastKey = keys[k];
                          if( lastKey.isParent(key) == true )
                          {
                              tmp = (ArrayList) namespacePerms.get(lastKey);
                              break;
                          }
                      }
                  }
              }
              catch(NoSuchElementException e)
              {   /* Assign the first permission
                  Object firstKey = namespacePerms.firstKey();
                  tmp = (ArrayList) namespacePerms.get(firstKey);
                */
              }
          }
  
          // See if the permission is implied by any we found
          if( tmp != null )
              implies = isImplied(tmp, np);
  //System.out.println("NPC["+this+"].implies("+np+") -> "+implies);
          return implies;
      }
  
      public Enumeration elements()
      {
          Set s = namespaceKeys.keySet();
          final Iterator iter = s.iterator();
          Enumeration elements = new Enumeration()
          {
              ArrayList activeEntry;
              int index;
              public boolean hasMoreElements()
              {
                  boolean hasMoreElements = true;
                  if( activeEntry == null || index >= activeEntry.size() )
                  {
                      hasMoreElements = iter.hasNext();
                      activeEntry = null;
                  }
                  return hasMoreElements;
              }
              public Object nextElement()
              {
                  Object next = null;
                  if( activeEntry == null )
                  {
                      Object key = iter.next();
                      activeEntry = (ArrayList) namespacePerms.get(key);
                      index = 0;
                      next = activeEntry.get(index ++);
                  }
                  else
                  {
                      next = activeEntry.get(index ++);
                  }
                  return next;
              }
          };
          return elements;
      }
  
  
      private boolean isImplied(ArrayList permissions, NamespacePermission np)
      {
          boolean isImplied = false;
          for(int p = 0; p < permissions.size(); p ++)
          {
              Permission perm = (Permission) permissions.get(p);
              isImplied |= perm.implies(np);
              if( isImplied == true )
                  break;
          }
          return isImplied;
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/PermissionName.java
  
  Index: PermissionName.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.Serializable;
  import java.security.BasicPermission;
  import java.util.Comparator;
  import java.util.Properties;
  import javax.naming.CompoundName;
  import javax.naming.Name;
  import javax.naming.NamingException;
  
  /** A javax.naming.Name based key class used as the name attribute
  by NamespacePermissions.
  
  @author [EMAIL PROTECTED]
  @version $Revision: 1.1 $
  */
  public class PermissionName implements Comparable, Serializable
  {
        /** The Properties used for the project directory heirarchical names */
        static Name emptyName;
        static Properties nameSyntax = new Properties();
        static
        {
                nameSyntax.put("jndi.syntax.direction", "left_to_right");
                nameSyntax.put("jndi.syntax.separator", "/");
                try
                {
                        emptyName = new CompoundName("", nameSyntax);
                }
                catch(NamingException e)
                {
                }       
        }
      private Name name;
  
      /** An alternate PermissionName comparator that first orders names by
          length(longer names before shorter names) to ensure that the most
          precise names are seen first.
      */
      public static class NameLengthComparator implements Comparator
      {
          public int compare(Object o1, Object o2)
          {
              PermissionName p1 = (PermissionName) o1;
              PermissionName p2 = (PermissionName) o2;
              // if p1 is longer than p2, its < p2 -> < 0
              int compare = p2.size() - p1.size();
              if( compare == 0 )
                  compare = p1.compareTo(p2);
              return compare;
          }
      }
  
      /** Creates new NamespacePermission */
      public PermissionName(String name) throws IllegalArgumentException
      {
          try
          {
              this.name = new CompoundName(name, nameSyntax);
          }
          catch(NamingException e)
          {
              throw new IllegalArgumentException(e.toString(true));
          }
      }
      public PermissionName(Name name)
      {
          this.name = name;
      }
  
      public int compareTo(Object obj)
      {
          PermissionName pn = (PermissionName) obj;
          /* Each level must be compared. The first level to not be equals
           determines the ordering of the names.
          */
          int compare = name.size() - pn.name.size();
          int length = Math.min(name.size(), pn.name.size());
          for(int n = 0; compare == 0 && n < length; n ++)
          {
              String atom0 = name.get(n);
              String atom1 = pn.name.get(n);
              compare = atom0.compareTo(atom1);
          }
          return compare;
      }
  
      public boolean equals(Object obj)
      {
          return compareTo(obj) == 0;
      }
  
      public int hashCode()
      {
          return name.hashCode();
      }
  
      public int size()
      {
          return name.size();
      }
  
      public boolean isParent(PermissionName childName)
      {
          boolean isParent = childName.name.startsWith(name);
          return isParent;
      }
  
      public String toString()
      {
          return name.toString();
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/StatelessSessionClient.java
  
  Index: StatelessSessionClient.java
  ===================================================================
  package org.jboss.test.security.test;
  
  import java.io.IOException;
  import java.rmi.RemoteException;
  import java.util.Properties;
  import javax.ejb.CreateException;
  import javax.naming.Context;
  import javax.naming.InitialContext;
  import javax.naming.NamingException;
  import javax.security.auth.callback.*;
  import javax.security.auth.login.*;
  
  import org.jboss.test.security.interfaces.StatelessSession;
  import org.jboss.test.security.interfaces.StatelessSessionHome;
  
  /** Run with -Djava.security.auth.login.config=url_to_jaas_login_conf
  
  @author [EMAIL PROTECTED]
  @version $Revision: 1.1 $
  */
  public class StatelessSessionClient
  {
      static void runMT()
      {
          Thread t0 = new Thread()
          {
              public void run()
              {
                  try
                  {
                      runAs("scott", "echoman".toCharArray());
                  }
                  catch(Exception e)
                  {
                  }
              }
          };
          Thread t1 = new Thread()
          {
              public void run()
              {
                  try
                  {
                      runAs("stark", "javaman".toCharArray());
                  }
                  catch(Exception e)
                  {
                  }
              }
          };
          t0.start();
          t1.start();
      }
  
      static void runAs(String username, char[] password) throws Exception
      {
          LoginContext lc = null;
          String confName = System.getProperty("conf.name", "other");
          boolean loggedIn = false;
          try
          {
              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;
  
              /* The properties are for passing credentials to j2ee-ri which
                 are not used with jboss */
              Properties props = new Properties();
              props.setProperty(Context.SECURITY_PRINCIPAL, username);
              props.setProperty(Context.SECURITY_CREDENTIALS, new String(password));
              props.setProperty(Context.SECURITY_PROTOCOL, "simple");
              InitialContext jndiContext = new InitialContext(props);
              Object obj = jndiContext.lookup("StatelessSession2");
              Class[] ifaces = obj.getClass().getInterfaces();
              StatelessSessionHome home = (StatelessSessionHome) obj;
              System.out.println("Found StatelessSessionHome");
              StatelessSession bean = home.create();
              System.out.println("Created StatelessSession");
              System.out.println("Bean.echo('Hello') -> "+bean.echo("Hello"));
          }
          finally
          {
              if( lc != null && loggedIn )
                  lc.logout();
          }
      }
  
      public static void main(String args[]) throws Exception
      {
          if( args.length == 1 && args[0].equals("-mt") )
          {
              System.out.println("Running multi-threaded with simultaneous logins");
              runMT();
          }
          else
          {
              System.out.println("Running single-threaded with sequential logins");
              runAs("scott", "echoman".toCharArray());
              runAs("stark", "javaman".toCharArray());
          }
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/TestEJBAccess.java
  
  Index: TestEJBAccess.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 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 TestEJBAccess extends junit.framework.TestCase
  {
      private boolean deployed;
  
      public TestEJBAccess(String name)
      {
        super(name);
      }
  
      /** 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/TestEJBSpec.java
  
  Index: TestEJBSpec.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 org.jboss.test.security.interfaces.StatelessSession;
  import org.jboss.test.security.interfaces.StatelessSessionHome;
  
  /** Test of EJB spec conformace using the security-spec.jar
  deployment unit.
  
  @author [EMAIL PROTECTED]
  @version $Revision: 1.1 $
  */
  public class TestEJBSpec extends junit.framework.TestCase
  {
      static String username = "scott";
      static char[] password = "echoman".toCharArray();
  
      LoginContext lc;
      boolean loggedIn;
  
      public TestEJBSpec(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();
          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");
              fail("Was able to call StatelessSession.echo");
          }
          catch(RemoteException e)
          {
              System.out.println("echo failed");
          }
          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);
          assert("username == echo", echo.equals(username));
          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
      {
          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 not allowed");
          }
          bean.remove();
      }
  
      /** Login as user scott using the conf.name login config or
          'other' if conf.name is not defined.
       */
      private void login() throws Exception
      {
          if( loggedIn )
              return;
  
          loggedIn = false;
          lc = null;
          String confName = System.getProperty("conf.name", "simple");
          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();
          }
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/TestLoginContext.java
  
  Index: TestLoginContext.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 TestLoginContext 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 TestLoginContext(String name)
      {
          super(name);
      }
  
      protected void setUp() throws Exception
      {
          Configuration.setConfiguration(new MyConfig());
      }
  
      protected void assertEquals(String msg, boolean expected, boolean actual)
      {
          assert(msg, (expected == actual));
      }
  
      public void testLogin1() throws Exception
      {
          subject1 = new Subject();
          LoginContext lc = new LoginContext("LoginContext", subject1);
          lc.login();
          Subject lcSubject = lc.getSubject();
          assert("subject == lcSubject",  subject1 == lcSubject );
      }
      public void testLogin2() throws Exception
      {
          subject2 = new Subject();
          LoginContext lc = new LoginContext("LoginContext", subject2);
          lc.login();
          Subject lcSubject = lc.getSubject();
          assert("subject == lcSubject",  subject2 == lcSubject );
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/TestNamespacePermissions.java
  
  Index: TestNamespacePermissions.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 TestNamespacePermissions extends junit.framework.TestCase
  {
      PermissionCollection pc;
  
      public TestNamespacePermissions(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;
      }
  
      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
      {
          TestNamespacePermissions tst = new TestNamespacePermissions("main");
          tst.setUp();
          tst.testImplied();
          tst.testNotImplied();
      }
  }
  
  
  
  1.1                  
jbosstest/src/main/org/jboss/test/security/test/TestPermissionName.java
  
  Index: TestPermissionName.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 TestPermissionName extends junit.framework.TestCase
  {
    public TestPermissionName(String name)
    {
        super(name);
    }
    protected void assertEquals(String msg, boolean expected, boolean actual)
    {
        assert(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);
  
      assert(n0.toString(), s0.equals(n0.toString()));
      assert(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/TestProjRepository.java
  
  Index: TestProjRepository.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 org.apache.log4j.Category;
  import org.apache.log4j.FileAppender;
  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;
  
  /** 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 do.
  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 TestProjRepository extends junit.framework.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 TestProjRepository(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 FileAppender(new PatternLayout("%x%m%n"), System.out));
        Deploy.deploy("security.jar");
      }
  
      /** 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();
      }
  
  }
  
  
  

Reply via email to