You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by je...@apache.org on 2015/12/21 18:21:29 UTC

[1/7] incubator-geode git commit: GEODE-663: add aditional security tests to the open source

Repository: incubator-geode
Updated Branches:
  refs/heads/develop 51ce64d81 -> 3720666f0


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java
deleted file mode 100644
index 0e1ccf6..0000000
--- a/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java
+++ /dev/null
@@ -1,465 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-import com.gemstone.gemfire.security.AccessControl;
-
-/**
- * Encapsulates obtaining authorized and unauthorized credentials for a given
- * operation in a region. Implementations will be for different kinds of
- * authorization scheme and authentication scheme combos.
- * 
- * @author sumedh
- * @since 5.5
- */
-public abstract class AuthzCredentialGenerator {
-
-  /**
-   * Enumeration for various {@link AuthzCredentialGenerator} implementations.
-   * 
-   * The following schemes are supported as of now:
-   * <ul>
-   * <li><code>DummyAuthorization</code> with <code>DummyAuthenticator</code></li>
-   * <li><code>XMLAuthorization</code> with <code>DummyAuthenticator</code></li>
-   * <li><code>XMLAuthorization</code> with <code>LDAPAuthenticator</code></li>
-   * <li><code>XMLAuthorization</code> with <code>PKCSAuthenticator</code></li>
-   * <li><code>XMLAuthorization</code> when using SSL sockets</li>
-   * </ul>
-   * 
-   * To add a new authorization scheme the following needs to be done:
-   * <ul>
-   * <li>Add implementation for {@link AccessControl}.</li>
-   * <li>Choose the authentication schemes that it shall work with from
-   * {@link CredentialGenerator.ClassCode}</li>
-   * <li>Add a new enumeration value for the scheme in this class. Notice the
-   * size of <code>VALUES</code> array and increase that if it is getting
-   * overflowed. Note the methods and fields for existing schemes and add for
-   * the new one in a similar manner.</li>
-   * <li>Add an implementation for {@link AuthzCredentialGenerator}. Note the
-   * {@link AuthzCredentialGenerator#init} method where different authentication
-   * schemes can be passed and initialize differently for the authentication
-   * schemes that shall be handled.</li>
-   * <li>Modify the {@link AuthzCredentialGenerator#create} method to add
-   * creation of an instance of the new implementation for the
-   * <code>ClassCode</code> enumeration value.</li>
-   * </ul>
-   * All dunit tests will automagically start testing the new implementation
-   * after this.
-   * 
-   * @author sumedh
-   * @since 5.5
-   */
-  public static final class ClassCode {
-
-    private static final byte ID_DUMMY = 1;
-
-    private static final byte ID_XML = 2;
-
-    private static byte nextOrdinal = 0;
-
-    private static final ClassCode[] VALUES = new ClassCode[10];
-
-    private static final Map CodeNameMap = new HashMap();
-
-    public static final ClassCode DUMMY = new ClassCode(
-        "templates.security.DummyAuthorization.create", ID_DUMMY);
-
-    public static final ClassCode XML = new ClassCode(
-        "templates.security.XmlAuthorization.create", ID_XML);
-
-    /** The name of this class. */
-    private final String name;
-
-    /** byte used as ordinal to represent this class */
-    private final byte ordinal;
-
-    /**
-     * One of the following: ID_DUMMY, ID_LDAP, ID_PKI
-     */
-    private final byte classType;
-
-    /** Creates a new instance of class code. */
-    private ClassCode(String name, byte classType) {
-      this.name = name;
-      this.classType = classType;
-      this.ordinal = nextOrdinal++;
-      VALUES[this.ordinal] = this;
-      CodeNameMap.put(name, this);
-    }
-
-    public boolean isDummy() {
-      return (this.classType == ID_DUMMY);
-    }
-
-    public boolean isXml() {
-      return (this.classType == ID_XML);
-    }
-
-    /**
-     * Returns the <code>ClassCode</code> represented by specified ordinal.
-     */
-    public static ClassCode fromOrdinal(byte ordinal) {
-      return VALUES[ordinal];
-    }
-
-    /**
-     * Returns the <code>ClassCode</code> represented by specified string.
-     */
-    public static ClassCode parse(String operationName) {
-      return (ClassCode)CodeNameMap.get(operationName);
-    }
-
-    /**
-     * Returns all the possible values.
-     */
-    public static List getAll() {
-      List codes = new ArrayList();
-      Iterator iter = CodeNameMap.values().iterator();
-      while (iter.hasNext()) {
-        codes.add(iter.next());
-      }
-      return codes;
-    }
-
-    /**
-     * Returns the ordinal for this class code.
-     * 
-     * @return the ordinal of this class code.
-     */
-    public byte toOrdinal() {
-      return this.ordinal;
-    }
-
-    /**
-     * Returns a string representation for this class code.
-     * 
-     * @return the name of this class code.
-     */
-    final public String toString() {
-      return this.name;
-    }
-
-    /**
-     * Indicates whether other object is same as this one.
-     * 
-     * @return true if other object is same as this one.
-     */
-    @Override
-    final public boolean equals(final Object obj) {
-      if (obj == this) {
-        return true;
-      }
-      if (!(obj instanceof ClassCode)) {
-        return false;
-      }
-      final ClassCode other = (ClassCode)obj;
-      return (other.ordinal == this.ordinal);
-    }
-
-    /**
-     * Indicates whether other <code>ClassCode</code> is same as this one.
-     * 
-     * @return true if other <code>ClassCode</code> is same as this one.
-     */
-    final public boolean equals(final ClassCode opCode) {
-      return (opCode != null && opCode.ordinal == this.ordinal);
-    }
-
-    /**
-     * Returns a hash code value for this <code>ClassCode</code> which is the
-     * same as its ordinal.
-     * 
-     * @return the ordinal of this <code>ClassCode</code>.
-     */
-    @Override
-    final public int hashCode() {
-      return this.ordinal;
-    }
-
-  }
-
-  /**
-   * The {@link CredentialGenerator} being used.
-   */
-  protected CredentialGenerator cGen;
-
-  /**
-   * A set of system properties that should be added to the gemfire system
-   * properties before using the authorization module.
-   */
-  private Properties sysProps;
-
-  /**
-   * A factory method to create a new instance of an
-   * {@link AuthzCredentialGenerator} for the given {@link ClassCode}. Caller
-   * is supposed to invoke {@link AuthzCredentialGenerator#init} immediately
-   * after obtaining the instance.
-   * 
-   * @param classCode
-   *                the <code>ClassCode</code> of the
-   *                <code>AuthzCredentialGenerator</code> implementation
-   * 
-   * @return an instance of <code>AuthzCredentialGenerator</code> for the
-   *         given class code
-   */
-  public static AuthzCredentialGenerator create(ClassCode classCode) {
-    switch (classCode.classType) {
-      case ClassCode.ID_DUMMY:
-        return new DummyAuthzCredentialGenerator();
-      case ClassCode.ID_XML:
-        return new XmlAuthzCredentialGenerator();
-      default:
-        return null;
-    }
-  }
-
-  /**
-   * Initialize the authorized credential generator.
-   * 
-   * @param cGen
-   *                an instance of {@link CredentialGenerator} of the credential
-   *                implementation for which to obtain authorized/unauthorized
-   *                credentials.
-   * 
-   * @return false when the given {@link CredentialGenerator} is incompatible
-   *         with this authorization module.
-   */
-  public boolean init(CredentialGenerator cGen) {
-    this.cGen = cGen;
-    try {
-      this.sysProps = init();
-    }
-    catch (IllegalArgumentException ex) {
-      return false;
-    }
-    return true;
-  }
-
-  /**
-   * 
-   * @return A set of extra properties that should be added to Gemfire system
-   *         properties when not null.
-   */
-  public Properties getSystemProperties() {
-    return this.sysProps;
-  }
-
-  /**
-   * Get the {@link CredentialGenerator} being used by this instance.
-   */
-  public CredentialGenerator getCredentialGenerator() {
-    return this.cGen;
-  }
-
-  /**
-   * The {@link ClassCode} of the particular implementation.
-   * 
-   * @return the <code>ClassCode</code>
-   */
-  public abstract ClassCode classCode();
-
-  /**
-   * The name of the {@link AccessControl} factory function that should be used
-   * as the authorization module on the server side.
-   * 
-   * @return name of the <code>AccessControl</code> factory function
-   */
-  public abstract String getAuthorizationCallback();
-
-  /**
-   * Get a set of credentials generated using the given index allowed to perform
-   * the given {@link OperationCode}s for the given regions.
-   * 
-   * @param opCodes
-   *                the list of {@link OperationCode}s of the operations
-   *                requiring authorization; should not be null
-   * @param regionNames
-   *                list of the region names requiring authorization; a value of
-   *                null indicates all regions
-   * @param index
-   *                used to generate multiple such credentials by passing
-   *                different values for this
-   * 
-   * @return the set of credentials authorized to perform the given operation in
-   *         the given regions
-   */
-  public Properties getAllowedCredentials(OperationCode[] opCodes,
-      String[] regionNames, int index) {
-
-    int numTries = getNumPrincipalTries(opCodes, regionNames);
-    if (numTries <= 0) {
-      numTries = 1;
-    }
-    for (int tries = 0; tries < numTries; tries++) {
-      Principal principal = getAllowedPrincipal(opCodes, regionNames,
-          (index + tries) % numTries);
-      try {
-        return this.cGen.getValidCredentials(principal);
-      }
-      catch (IllegalArgumentException ex) {
-      }
-    }
-    return null;
-  }
-
-  /**
-   * Get a set of credentials generated using the given index not allowed to
-   * perform the given {@link OperationCode}s for the given regions. The
-   * credentials are required to be valid for authentication.
-   * 
-   * @param opCode
-   *                the {@link OperationCode}s of the operations requiring
-   *                authorization failure; should not be null
-   * @param regionNames
-   *                list of the region names requiring authorization failure; a
-   *                value of null indicates all regions
-   * @param index
-   *                used to generate multiple such credentials by passing
-   *                different values for this
-   * 
-   * @return the set of credentials that are not authorized to perform the given
-   *         operation in the given region
-   */
-  public Properties getDisallowedCredentials(OperationCode[] opCodes,
-      String[] regionNames, int index) {
-
-    // This may not be very correct since we use the value of
-    // getNumPrincipalTries() but is used to avoid adding another method.
-    // Also something like getNumDisallowedPrincipals() will be normally always
-    // infinite, and the number here is just to perform some number of tries
-    // before giving up.
-    int numTries = getNumPrincipalTries(opCodes, regionNames);
-    if (numTries <= 0) {
-      numTries = 1;
-    }
-    for (int tries = 0; tries < numTries; tries++) {
-      Principal principal = getDisallowedPrincipal(opCodes, regionNames,
-          (index + tries) % numTries);
-      try {
-        return this.cGen.getValidCredentials(principal);
-      }
-      catch (IllegalArgumentException ex) {
-      }
-    }
-    return null;
-  }
-
-  /**
-   * Initialize the authorized credential generator.
-   * 
-   * Required to be implemented by concrete classes that implement this abstract
-   * class.
-   * 
-   * @return A set of extra properties that should be added to Gemfire system
-   *         properties when not null.
-   * 
-   * @throws IllegalArgumentException
-   *                 when the {@link CredentialGenerator} is incompatible with
-   *                 this authorization module.
-   */
-  protected abstract Properties init() throws IllegalArgumentException;
-
-  /**
-   * Get the number of tries to be done for obtaining valid credentials for the
-   * given operations in the given region. It is required that
-   * {@link #getAllowedPrincipal} method returns valid principals for values of
-   * <code>index</code> from 0 through (n-1) where <code>n</code> is the
-   * value returned by this method. It is recommended that the principals so
-   * returned be unique for efficiency.
-   * 
-   * This will be used by {@link #getAllowedCredentials} to step through
-   * different principals and obtain a set of valid credentials.
-   * 
-   * Required to be implemented by concrete classes that implement this abstract
-   * class.
-   * 
-   * @param opCodes
-   *                the {@link OperationCode}s of the operations requiring
-   *                authorization
-   * @param regionNames
-   *                list of the region names requiring authorization; a value of
-   *                null indicates all regions
-   * @param index
-   *                used to generate multiple such credentials by passing
-   *                different values for this
-   * 
-   * @return the number of principals allowed to perform the given operation in
-   *         the given region
-   */
-  protected abstract int getNumPrincipalTries(OperationCode[] opCodes,
-      String[] regionNames);
-
-  /**
-   * Get a {@link Principal} generated using the given index allowed to perform
-   * the given {@link OperationCode}s for the given region.
-   * 
-   * Required to be implemented by concrete classes that implement this abstract
-   * class.
-   * 
-   * @param opCodes
-   *                the {@link OperationCode}s of the operations requiring
-   *                authorization
-   * @param regionNames
-   *                list of the region names requiring authorization; a value of
-   *                null indicates all regions
-   * @param index
-   *                used to generate multiple such principals by passing
-   *                different values for this
-   * 
-   * @return the {@link Principal} authorized to perform the given operation in
-   *         the given region
-   */
-  protected abstract Principal getAllowedPrincipal(OperationCode[] opCodes,
-      String[] regionNames, int index);
-
-  /**
-   * Get a {@link Principal} generated using the given index not allowed to
-   * perform the given {@link OperationCode}s for the given region.
-   * 
-   * Required to be implemented by concrete classes that implement this abstract
-   * class.
-   * 
-   * @param opCodes
-   *                the {@link OperationCode}s of the operations requiring
-   *                authorization failure
-   * @param regionNames
-   *                list of the region names requiring authorization failure; a
-   *                value of null indicates all regions
-   * @param index
-   *                used to generate multiple such principals by passing
-   *                different values for this
-   * 
-   * @return a {@link Principal} not authorized to perform the given operation
-   *         in the given region
-   */
-  protected abstract Principal getDisallowedPrincipal(OperationCode[] opCodes,
-      String[] regionNames, int index);
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/CredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/CredentialGenerator.java b/gemfire-core/src/test/java/templates/security/CredentialGenerator.java
deleted file mode 100644
index 99d7e18..0000000
--- a/gemfire-core/src/test/java/templates/security/CredentialGenerator.java
+++ /dev/null
@@ -1,343 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import com.gemstone.gemfire.security.AuthInitialize;
-import com.gemstone.gemfire.security.Authenticator;
-
-/**
- * Encapsulates obtaining valid and invalid credentials. Implementations will be
- * for different kinds of authentication schemes.
- * 
- * @author sumedh
- * @since 5.5
- */
-public abstract class CredentialGenerator {
-
-  /**
-   * Enumeration for various {@link CredentialGenerator} implementations.
-   * 
-   * The following schemes are supported as of now:
-   * <code>DummyAuthenticator</code>, <code>LdapUserAuthenticator</code>,
-   * <code>PKCSAuthenticator</code>. In addition SSL socket mode with mutual
-   * authentication is also supported.
-   * 
-   * To add a new authentication scheme the following needs to be done:
-   * <ul>
-   * <li>Add implementations for {@link AuthInitialize} and
-   * {@link Authenticator} classes for clients/peers.</li>
-   * <li>Add a new enumeration value for the scheme in this class. Notice the
-   * size of <code>VALUES</code> array and increase that if it is getting
-   * overflowed. Note the methods and fields for existing schemes and add for
-   * the new one in a similar manner.</li>
-   * <li>Add an implementation for {@link CredentialGenerator}.</li>
-   * <li>Modify the {@link CredentialGenerator.Factory#create} method to add
-   * creation of an instance of the new implementation for the
-   * <code>ClassCode</code> enumeration value.</li>
-   * </ul>
-   * All security dunit tests will automagically start testing the new
-   * implementation after this.
-   * 
-   * @author sumedh
-   * @since 5.5
-   */
-  public static final class ClassCode {
-
-    private static final byte ID_DUMMY = 1;
-
-    private static final byte ID_LDAP = 2;
-
-    private static final byte ID_PKCS = 3;
-
-    private static final byte ID_SSL = 4;
-
-    private static byte nextOrdinal = 0;
-
-    private static final ClassCode[] VALUES = new ClassCode[10];
-
-    private static final Map CodeNameMap = new HashMap();
-
-    public static final ClassCode DUMMY = new ClassCode(
-        "templates.security.DummyAuthenticator.create", ID_DUMMY);
-
-    public static final ClassCode LDAP = new ClassCode(
-        "templates.security.LdapUserAuthenticator.create", ID_LDAP);
-
-    public static final ClassCode PKCS = new ClassCode(
-        "templates.security.PKCSAuthenticator.create", ID_PKCS);
-
-    public static final ClassCode SSL = new ClassCode("SSL", ID_SSL);
-
-    /** The name of this class. */
-    private final String name;
-
-    /** byte used as ordinal to represent this class */
-    private final byte ordinal;
-
-    /**
-     * One of the following: ID_DUMMY, ID_LDAP, ID_PKCS
-     */
-    private final byte classType;
-
-    /** Creates a new instance of class code. */
-    private ClassCode(String name, byte classType) {
-      this.name = name;
-      this.classType = classType;
-      this.ordinal = nextOrdinal++;
-      VALUES[this.ordinal] = this;
-      CodeNameMap.put(name, this);
-    }
-
-    public boolean isDummy() {
-      return (this.classType == ID_DUMMY);
-    }
-
-    public boolean isLDAP() {
-      return (this.classType == ID_LDAP);
-    }
-
-    public boolean isPKCS() {
-      return (this.classType == ID_PKCS);
-    }
-
-    public boolean isSSL() {
-      return (this.classType == ID_SSL);
-    }
-
-    /**
-     * Returns the <code>ClassCode</code> represented by specified ordinal.
-     */
-    public static ClassCode fromOrdinal(byte ordinal) {
-      return VALUES[ordinal];
-    }
-
-    /**
-     * Returns the <code>ClassCode</code> represented by specified string.
-     */
-    public static ClassCode parse(String operationName) {
-      return (ClassCode)CodeNameMap.get(operationName);
-    }
-
-    /**
-     * Returns all the possible values.
-     */
-    public static List getAll() {
-      List codes = new ArrayList();
-      Iterator iter = CodeNameMap.values().iterator();
-      while (iter.hasNext()) {
-        codes.add(iter.next());
-      }
-      return codes;
-    }
-
-    /**
-     * Returns the ordinal for this operation code.
-     * 
-     * @return the ordinal of this operation.
-     */
-    public byte toOrdinal() {
-      return this.ordinal;
-    }
-
-    /**
-     * Returns a string representation for this operation.
-     * 
-     * @return the name of this operation.
-     */
-    final public String toString() {
-      return this.name;
-    }
-
-    /**
-     * Indicates whether other object is same as this one.
-     * 
-     * @return true if other object is same as this one.
-     */
-    @Override
-    final public boolean equals(final Object obj) {
-      if (obj == this) {
-        return true;
-      }
-      if (!(obj instanceof ClassCode)) {
-        return false;
-      }
-      final ClassCode other = (ClassCode)obj;
-      return (other.ordinal == this.ordinal);
-    }
-
-    /**
-     * Indicates whether other <code>ClassCode</code> is same as this one.
-     * 
-     * @return true if other <code>ClassCode</code> is same as this one.
-     */
-    final public boolean equals(final ClassCode opCode) {
-      return (opCode != null && opCode.ordinal == this.ordinal);
-    }
-
-    /**
-     * Returns a hash code value for this <code>ClassCode</code> which is the
-     * same as its ordinal.
-     * 
-     * @return the ordinal of this operation.
-     */
-    @Override
-    final public int hashCode() {
-      return this.ordinal;
-    }
-
-  }
-
-  /**
-   * A set of properties that should be added to the Gemfire system properties
-   * before using the authentication module.
-   */
-  private Properties sysProps = null;
-
-  /**
-   * A set of properties that should be added to the java system properties
-   * before using the authentication module.
-   */
-  protected Properties javaProps = null;
-
-  /**
-   * A factory method to create a new instance of an {@link CredentialGenerator}
-   * for the given {@link ClassCode}. Caller is supposed to invoke
-   * {@link CredentialGenerator#init} immediately after obtaining the instance.
-   * 
-   * @param classCode
-   *                the <code>ClassCode</code> of the
-   *                <code>CredentialGenerator</code> implementation
-   * 
-   * @return an instance of <code>CredentialGenerator</code> for the given
-   *         class code
-   */
-  public static CredentialGenerator create(ClassCode classCode) {
-    switch (classCode.classType) {
-      // Removing dummy one to reduce test run times
-      // case ClassCode.ID_DUMMY:
-      // return new DummyCredentialGenerator();
-      case ClassCode.ID_LDAP:
-        return new LdapUserCredentialGenerator();
-        // case ClassCode.ID_SSL:ΓΈ
-        // return new SSLCredentialGenerator();
-      case ClassCode.ID_PKCS:
-        return new PKCSCredentialGenerator();
-      default:
-        return null;
-    }
-  }
-
-  /**
-   * Initialize the credential generator.
-   * 
-   * @throws IllegalArgumentException
-   *                 when there is a problem during initialization
-   */
-  public void init() throws IllegalArgumentException {
-    this.sysProps = initialize();
-  }
-
-  /**
-   * Initialize the credential generator. This is provided separately from the
-   * {@link #init} method for convenience of implementations so that they do not
-   * need to store in {@link #sysProps}. The latter is convenient for the users
-   * who do not need to store these properties rather can obtain it later by
-   * invoking {@link #getSystemProperties}
-   * 
-   * Required to be implemented by concrete classes that implement this abstract
-   * class.
-   * 
-   * @return A set of extra properties that should be added to Gemfire system
-   *         properties when not null.
-   * 
-   * @throws IllegalArgumentException
-   *                 when there is a problem during initialization
-   */
-  protected abstract Properties initialize() throws IllegalArgumentException;
-
-  /**
-   * 
-   * @return A set of extra properties that should be added to Gemfire system
-   *         properties when not null.
-   */
-  public Properties getSystemProperties() {
-    return this.sysProps;
-  }
-
-  /**
-   * 
-   * @return A set of extra properties that should be added to Gemfire system
-   *         properties when not null.
-   */
-  public Properties getJavaProperties() {
-    return this.javaProps;
-  }
-
-  /**
-   * The {@link ClassCode} of this particular implementation.
-   * 
-   * @return the <code>ClassCode</code>
-   */
-  public abstract ClassCode classCode();
-
-  /**
-   * The name of the {@link AuthInitialize} factory function that should be used
-   * in conjunction with the credentials generated by this generator.
-   * 
-   * @return name of the <code>AuthInitialize</code> factory function
-   */
-  public abstract String getAuthInit();
-
-  /**
-   * The name of the {@link Authenticator} factory function that should be used
-   * in conjunction with the credentials generated by this generator.
-   * 
-   * @return name of the <code>Authenticator</code> factory function
-   */
-  public abstract String getAuthenticator();
-
-  /**
-   * Get a set of valid credentials generated using the given index.
-   */
-  public abstract Properties getValidCredentials(int index);
-
-  /**
-   * Get a set of valid credentials for the given {@link Principal}.
-   * 
-   * @return credentials for the given <code>Principal</code> or null if none
-   *         possible.
-   */
-  public abstract Properties getValidCredentials(Principal principal);
-
-  /**
-   * Get a set of invalid credentials generated using the given index.
-   */
-  public abstract Properties getInvalidCredentials(int index);
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java
deleted file mode 100644
index 5c27d60..0000000
--- a/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java
+++ /dev/null
@@ -1,142 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-
-public class DummyAuthzCredentialGenerator extends AuthzCredentialGenerator {
-
-  public static final byte READER_ROLE = 1;
-
-  public static final byte WRITER_ROLE = 2;
-
-  public static final byte ADMIN_ROLE = 3;
-
-  private static Set readerOpsSet;
-
-  private static Set writerOpsSet;
-
-  static {
-
-    readerOpsSet = new HashSet();
-    for (int index = 0; index < DummyAuthorization.READER_OPS.length; index++) {
-      readerOpsSet.add(DummyAuthorization.READER_OPS[index]);
-    }
-    writerOpsSet = new HashSet();
-    for (int index = 0; index < DummyAuthorization.WRITER_OPS.length; index++) {
-      writerOpsSet.add(DummyAuthorization.WRITER_OPS[index]);
-    }
-  }
-
-  public DummyAuthzCredentialGenerator() {
-  }
-
-  protected Properties init() throws IllegalArgumentException {
-
-    if (!this.cGen.classCode().isDummy()) {
-      throw new IllegalArgumentException(
-          "DummyAuthorization module only works with DummyAuthenticator");
-    }
-    return null;
-  }
-
-  public ClassCode classCode() {
-    return ClassCode.DUMMY;
-  }
-
-  public String getAuthorizationCallback() {
-    return "templates.security.DummyAuthorization.create";
-  }
-
-  public static byte getRequiredRole(OperationCode[] opCodes) {
-
-    byte roleType = ADMIN_ROLE;
-    boolean requiresReader = true;
-    boolean requiresWriter = true;
-
-    for (int opNum = 0; opNum < opCodes.length; opNum++) {
-      if (requiresReader && !readerOpsSet.contains(opCodes[opNum])) {
-        requiresReader = false;
-      }
-      if (requiresWriter && !writerOpsSet.contains(opCodes[opNum])) {
-        requiresWriter = false;
-      }
-    }
-    if (requiresReader) {
-      roleType = READER_ROLE;
-    }
-    else if (requiresWriter) {
-      roleType = WRITER_ROLE;
-    }
-    return roleType;
-  }
-
-  private Principal getPrincipal(byte roleType, int index) {
-
-    String[] admins = new String[] { "root", "admin", "administrator" };
-    switch (roleType) {
-      case READER_ROLE:
-        return new UsernamePrincipal("reader" + index);
-      case WRITER_ROLE:
-        return new UsernamePrincipal("writer" + index);
-      default:
-        return new UsernamePrincipal(admins[index % admins.length]);
-    }
-  }
-
-  protected Principal getAllowedPrincipal(OperationCode[] opCodes,
-      String[] regionNames, int index) {
-
-    byte roleType = getRequiredRole(opCodes);
-    return getPrincipal(roleType, index);
-  }
-
-  protected Principal getDisallowedPrincipal(OperationCode[] opCodes,
-      String[] regionNames, int index) {
-
-    byte roleType = getRequiredRole(opCodes);
-    byte disallowedRoleType;
-    switch (roleType) {
-      case READER_ROLE:
-        disallowedRoleType = WRITER_ROLE;
-        break;
-      case WRITER_ROLE:
-        disallowedRoleType = READER_ROLE;
-        break;
-      default:
-        disallowedRoleType = READER_ROLE;
-        break;
-    }
-    return getPrincipal(disallowedRoleType, index);
-  }
-
-  protected int getNumPrincipalTries(OperationCode[] opCodes,
-      String[] regionNames) {
-    return 5;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java
deleted file mode 100644
index af6c6eb..0000000
--- a/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java
+++ /dev/null
@@ -1,90 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.util.Properties;
-
-public class DummyCredentialGenerator extends CredentialGenerator {
-
-  public DummyCredentialGenerator() {
-  }
-
-  protected Properties initialize() throws IllegalArgumentException {
-    return null;
-  }
-
-  public ClassCode classCode() {
-    return ClassCode.DUMMY;
-  }
-
-  public String getAuthInit() {
-    return "templates.security.UserPasswordAuthInit.create";
-  }
-
-  public String getAuthenticator() {
-    return "templates.security.DummyAuthenticator.create";
-  }
-
-  public Properties getValidCredentials(int index) {
-
-    String[] validGroups = new String[] { "admin", "user", "reader", "writer" };
-    String[] admins = new String[] { "root", "admin", "administrator" };
-
-    Properties props = new Properties();
-    int groupNum = (index % validGroups.length);
-    String userName;
-    if (groupNum == 0) {
-      userName = admins[index % admins.length];
-    }
-    else {
-      userName = validGroups[groupNum] + (index / validGroups.length);
-    }
-    props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
-    props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
-    return props;
-  }
-
-  public Properties getValidCredentials(Principal principal) {
-
-    String userName = principal.getName();
-    if (DummyAuthenticator.testValidName(userName)) {
-      Properties props = new Properties();
-      props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
-      props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
-      return props;
-    }
-    else {
-      throw new IllegalArgumentException("Dummy: [" + userName
-          + "] is not a valid user");
-    }
-  }
-
-  public Properties getInvalidCredentials(int index) {
-
-    Properties props = new Properties();
-    props.setProperty(UserPasswordAuthInit.USER_NAME, "invalid" + index);
-    props.setProperty(UserPasswordAuthInit.PASSWORD, "none");
-    return props;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java
deleted file mode 100644
index 816df63..0000000
--- a/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java
+++ /dev/null
@@ -1,158 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.util.Properties;
-
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.cache.tier.sockets.HandShake;
-import com.gemstone.gemfire.util.test.TestUtil;
-
-import java.util.Random;
-
-public class LdapUserCredentialGenerator extends CredentialGenerator {
-
-  private static final String USER_PREFIX = "gemfire";
-
-  private static boolean enableServerAuthentication = false;
-
-  private boolean serverAuthEnabled = false;
-
-  private static final Random prng = new Random();
-
-  private static final String[] algos = new String[] { "", "DESede", "AES:128",
-      "Blowfish:128" };
-
-  public LdapUserCredentialGenerator() {
-    // Toggle server authentication enabled for each test
-    // This is done instead of running all the tests with both
-    // server auth enabled/disabled to reduce test run time.
-    enableServerAuthentication = !enableServerAuthentication;
-    serverAuthEnabled = enableServerAuthentication;
-  }
-
-  @Override
-  protected Properties initialize() throws IllegalArgumentException {
-
-    Properties extraProps = new Properties();
-    String ldapServer = System.getProperty("gf.ldap.server", "ldap");
-    String ldapBaseDN = System.getProperty("gf.ldap.basedn", "ou=ldapTesting,dc=pune,dc=gemstone,dc=com");
-    String ldapUseSSL = System.getProperty("gf.ldap.usessl");
-    extraProps.setProperty(LdapUserAuthenticator.LDAP_SERVER_NAME, ldapServer);
-    extraProps.setProperty(LdapUserAuthenticator.LDAP_BASEDN_NAME, ldapBaseDN);
-    if (ldapUseSSL != null && ldapUseSSL.length() > 0) {
-      extraProps.setProperty(LdapUserAuthenticator.LDAP_SSL_NAME, ldapUseSSL);
-    }
-    if (serverAuthEnabled) {
-      String keyStoreFile = TestUtil.getResourcePath(LdapUserCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/gemfire1.keystore");
-      extraProps.setProperty(HandShake.PRIVATE_KEY_FILE_PROP, keyStoreFile);
-      extraProps.setProperty(HandShake.PRIVATE_KEY_ALIAS_PROP, "gemfire1");
-      extraProps.setProperty(HandShake.PRIVATE_KEY_PASSWD_PROP, "gemfire");
-    }
-    return extraProps;
-  }
-
-  @Override
-  public ClassCode classCode() {
-    return ClassCode.LDAP;
-  }
-
-  @Override
-  public String getAuthInit() {
-    return "templates.security.UserPasswordAuthInit.create";
-  }
-
-  @Override
-  public String getAuthenticator() {
-    return "templates.security.LdapUserAuthenticator.create";
-  }
-
-  @Override
-  public Properties getValidCredentials(int index) {
-
-    Properties props = new Properties();
-    props.setProperty(UserPasswordAuthInit.USER_NAME, USER_PREFIX
-        + ((index % 10) + 1));
-    props.setProperty(UserPasswordAuthInit.PASSWORD, USER_PREFIX
-        + ((index % 10) + 1));
-    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
-        algos[prng.nextInt(algos.length)]);
-    if (serverAuthEnabled) {
-      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
-      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
-      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
-    }
-    return props;
-  }
-
-  @Override
-  public Properties getValidCredentials(Principal principal) {
-
-    Properties props = null;
-    String userName = principal.getName();
-    if (userName != null && userName.startsWith(USER_PREFIX)) {
-      boolean isValid;
-      try {
-        int suffix = Integer.parseInt(userName.substring(USER_PREFIX.length()));
-        isValid = (suffix >= 1 && suffix <= 10);
-      }
-      catch (Exception ex) {
-        isValid = false;
-      }
-      if (isValid) {
-        props = new Properties();
-        props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
-        props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
-      }
-    }
-    if (props == null) {
-      throw new IllegalArgumentException("LDAP: [" + userName
-          + "] not a valid user");
-    }
-    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
-        algos[prng.nextInt(algos.length)]);
-    if (serverAuthEnabled) {
-      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
-      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
-      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
-    }
-    return props;
-  }
-
-  @Override
-  public Properties getInvalidCredentials(int index) {
-
-    Properties props = new Properties();
-    props.setProperty(UserPasswordAuthInit.USER_NAME, "invalid" + index);
-    props.setProperty(UserPasswordAuthInit.PASSWORD, "none");
-    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
-        algos[prng.nextInt(algos.length)]);
-    if (serverAuthEnabled) {
-      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
-      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
-      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
-    }
-    return props;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java
deleted file mode 100644
index fa4bf04..0000000
--- a/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java
+++ /dev/null
@@ -1,110 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.security.Provider;
-import java.security.Security;
-import java.util.Properties;
-
-import com.gemstone.gemfire.util.test.TestUtil;
-
-/**
- * @author kneeraj
- * 
- */
-public class PKCSCredentialGenerator extends CredentialGenerator {
-
-  public static String keyStoreDir = getKeyStoreDir();
-
-  public static boolean usesIBMJSSE;
-
-  // Checks if the current JVM uses only IBM JSSE providers.
-  private static boolean usesIBMProviders() {
-    Provider[] providers = Security.getProviders();
-    for (int index = 0; index < providers.length; ++index) {
-      if (!providers[index].getName().toLowerCase().startsWith("ibm")) {
-        return false;
-      }
-    }
-    return true;
-  }
-
-  private static String getKeyStoreDir() {
-    usesIBMJSSE = usesIBMProviders();
-    if (usesIBMJSSE) {
-      return "/lib/keys/ibm";
-    }
-    else {
-      return "/lib/keys";
-    }
-  }
-
-  public ClassCode classCode() {
-    return ClassCode.PKCS;
-  }
-
-  public String getAuthInit() {
-    return "templates.security.PKCSAuthInit.create";
-  }
-
-  public String getAuthenticator() {
-    return "templates.security.PKCSAuthenticator.create";
-  }
-
-  public Properties getInvalidCredentials(int index) {
-    Properties props = new Properties();
-    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/gemfire11.keystore");
-    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
-    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, "gemfire11");
-    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
-    return props;
-  }
-
-  public Properties getValidCredentials(int index) {
-    Properties props = new Properties();
-    int aliasnum = (index % 10) + 1;
-    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/gemfire" + aliasnum + ".keystore");
-    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
-    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, "gemfire" + aliasnum);
-    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
-    return props;
-  }
-
-  public Properties getValidCredentials(Principal principal) {
-    Properties props = new Properties();
-    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + principal.getName() + ".keystore");
-    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
-    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, principal.getName());
-    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
-    return props;
-  }
-
-  protected Properties initialize() throws IllegalArgumentException {
-    Properties props = new Properties();
-    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/publickeyfile");
-    props.setProperty(PKCSAuthenticator.PUBLIC_KEY_FILE, keyStoreFile);
-    props.setProperty(PKCSAuthenticator.PUBLIC_KEYSTORE_PASSWORD, "gemfire");
-    return props;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java
deleted file mode 100644
index 09367a2..0000000
--- a/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java
+++ /dev/null
@@ -1,116 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.io.File;
-import java.io.IOException;
-import java.security.Principal;
-import java.util.Properties;
-
-import com.gemstone.gemfire.security.AuthenticationFailedException;
-
-public class SSLCredentialGenerator extends CredentialGenerator {
-
-  private File findTrustedJKS() {
-    File ssldir = new File(System.getProperty("JTESTS") + "/ssl");
-    return new File(ssldir, "trusted.keystore");
-  }
-
-  private File findUntrustedJKS() {
-    File ssldir = new File(System.getProperty("JTESTS") + "/ssl");
-    return new File(ssldir, "untrusted.keystore");
-  }
-
-  private Properties getValidJavaSSLProperties() {
-    File jks = findTrustedJKS();
-    try {
-      Properties props = new Properties();
-      props.setProperty("javax.net.ssl.trustStore", jks.getCanonicalPath());
-      props.setProperty("javax.net.ssl.trustStorePassword", "password");
-      props.setProperty("javax.net.ssl.keyStore", jks.getCanonicalPath());
-      props.setProperty("javax.net.ssl.keyStorePassword", "password");
-      return props;
-    }
-    catch (IOException ex) {
-      throw new AuthenticationFailedException(
-          "SSL: Exception while opening the key store: " + ex);
-    }
-  }
-
-  private Properties getInvalidJavaSSLProperties() {
-    File jks = findUntrustedJKS();
-    try {
-      Properties props = new Properties();
-      props.setProperty("javax.net.ssl.trustStore", jks.getCanonicalPath());
-      props.setProperty("javax.net.ssl.trustStorePassword", "password");
-      props.setProperty("javax.net.ssl.keyStore", jks.getCanonicalPath());
-      props.setProperty("javax.net.ssl.keyStorePassword", "password");
-      return props;
-    }
-    catch (IOException ex) {
-      throw new AuthenticationFailedException(
-          "SSL: Exception while opening the key store: " + ex);
-    }
-  }
-
-  private Properties getSSLProperties() {
-    Properties props = new Properties();
-    props.setProperty("ssl-enabled", "true");
-    props.setProperty("ssl-require-authentication", "true");
-    props.setProperty("ssl-ciphers", "SSL_RSA_WITH_RC4_128_MD5");
-    props.setProperty("ssl-protocols", "TLSv1");
-    return props;
-  }
-
-  protected Properties initialize() throws IllegalArgumentException {
-    this.javaProps = getValidJavaSSLProperties();
-    return getSSLProperties();
-  }
-
-  public ClassCode classCode() {
-    return ClassCode.SSL;
-  }
-
-  public String getAuthInit() {
-    return null;
-  }
-
-  public String getAuthenticator() {
-    return null;
-  }
-
-  public Properties getValidCredentials(int index) {
-    this.javaProps = getValidJavaSSLProperties();
-    return getSSLProperties();
-  }
-
-  public Properties getValidCredentials(Principal principal) {
-    this.javaProps = getValidJavaSSLProperties();
-    return getSSLProperties();
-  }
-
-  public Properties getInvalidCredentials(int index) {
-    this.javaProps = getInvalidJavaSSLProperties();
-    return getSSLProperties();
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java b/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java
deleted file mode 100644
index 56dbf7d..0000000
--- a/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java
+++ /dev/null
@@ -1,76 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.util.Properties;
-import java.util.Iterator;
-
-import com.gemstone.gemfire.distributed.DistributedMember;
-import com.gemstone.gemfire.security.AuthInitialize;
-import com.gemstone.gemfire.security.AuthenticationFailedException;
-
-/**
- * An {@link AuthInitialize} implementation that obtains the user name and
- * password as the credentials from the given set of properties. If 
- * keep-extra-props property exits, it will copy rest of the
- * properties provided in getCredential props argument will also be 
- * copied as new credentials.
- * 
- * @author Soubhik
- * @since 5.5
- */
-public class UserPasswordWithExtraPropsAuthInit extends UserPasswordAuthInit {
-
-  public static final String EXTRA_PROPS = "security-keep-extra-props";
-
-  public static final String SECURITY_PREFIX = "security-";
-  
-  public static AuthInitialize create() {
-    return new UserPasswordWithExtraPropsAuthInit();
-  }
-
-  public UserPasswordWithExtraPropsAuthInit() {
-    super();
-  }
-
-  public Properties getCredentials(Properties props, DistributedMember server,
-      boolean isPeer) throws AuthenticationFailedException {
-
-    Properties newProps = super.getCredentials(props, server, isPeer);
-    String extraProps = props.getProperty(EXTRA_PROPS);
-    if(extraProps != null) {
-    	for(Iterator it = props.keySet().iterator(); it.hasNext();) {
-    		String key = (String)it.next();
-    		if( key.startsWith(SECURITY_PREFIX) && 
-    		    key.equalsIgnoreCase(USER_NAME) == false &&
-    		    key.equalsIgnoreCase(PASSWORD) == false &&
-    		    key.equalsIgnoreCase(EXTRA_PROPS) == false) {
-    			newProps.setProperty(key, props.getProperty(key));
-    		}
-    	}
-    	this.securitylog.fine("got everything and now have: "
-          + newProps.keySet().toString());
-    }
-    return newProps;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java
deleted file mode 100644
index 6b3f171..0000000
--- a/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java
+++ /dev/null
@@ -1,262 +0,0 @@
-
-package templates.security;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *   http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-import java.security.Principal;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-import com.gemstone.gemfire.util.test.TestUtil;
-
-public class XmlAuthzCredentialGenerator extends AuthzCredentialGenerator {
-
-  private static final String dummyXml = "authz-dummy.xml";
-
-  private static final String ldapXml = "authz-ldap.xml";
-
-  private static final String pkcsXml = "authz-pkcs.xml";
-
-  private static final String sslXml = "authz-ssl.xml";
-
-  private static final String[] QUERY_REGIONS = { "/Portfolios", "/Positions",
-      "/AuthRegion" };
-
-  public static OperationCode[] READER_OPS = { OperationCode.GET,
-      OperationCode.REGISTER_INTEREST, OperationCode.UNREGISTER_INTEREST,
-      OperationCode.KEY_SET, OperationCode.CONTAINS_KEY, OperationCode.EXECUTE_FUNCTION };
-
-  public static OperationCode[] WRITER_OPS = { OperationCode.PUT,
-      OperationCode.DESTROY, OperationCode.INVALIDATE, OperationCode.REGION_CLEAR };
-
-  public static OperationCode[] QUERY_OPS = { OperationCode.QUERY,
-      OperationCode.EXECUTE_CQ, OperationCode.STOP_CQ, OperationCode.CLOSE_CQ };
-
-  private static final byte READER_ROLE = 1;
-
-  private static final byte WRITER_ROLE = 2;
-
-  private static final byte QUERY_ROLE = 3;
-
-  private static final byte ADMIN_ROLE = 4;
-
-  private static Set readerOpsSet;
-
-  private static Set writerOpsSet;
-
-  private static Set queryOpsSet;
-
-  private static Set queryRegionSet;
-
-  static {
-
-    readerOpsSet = new HashSet();
-    for (int index = 0; index < READER_OPS.length; index++) {
-      readerOpsSet.add(READER_OPS[index]);
-    }
-    writerOpsSet = new HashSet();
-    for (int index = 0; index < WRITER_OPS.length; index++) {
-      writerOpsSet.add(WRITER_OPS[index]);
-    }
-    queryOpsSet = new HashSet();
-    for (int index = 0; index < QUERY_OPS.length; index++) {
-      queryOpsSet.add(QUERY_OPS[index]);
-    }
-    queryRegionSet = new HashSet();
-    for (int index = 0; index < QUERY_REGIONS.length; index++) {
-      queryRegionSet.add(QUERY_REGIONS[index]);
-    }
-  }
-
-  public XmlAuthzCredentialGenerator() {
-  }
-
-  protected Properties init() throws IllegalArgumentException {
-
-    Properties sysProps = new Properties();
-    String dirName = "/lib/";
-    if (this.cGen.classCode().isDummy()) {
-      String xmlFilename = TestUtil.getResourcePath(XmlAuthzCredentialGenerator.class, dirName + dummyXml);
-      sysProps.setProperty(XmlAuthorization.DOC_URI_PROP_NAME, xmlFilename);
-    }
-    else if (this.cGen.classCode().isLDAP()) {
-      String xmlFilename = TestUtil.getResourcePath(XmlAuthzCredentialGenerator.class, dirName + ldapXml);
-      sysProps.setProperty(XmlAuthorization.DOC_URI_PROP_NAME, xmlFilename);
-    }
-    // else if (this.cGen.classCode().isPKCS()) {
-    // sysProps
-    // .setProperty(XmlAuthorization.DOC_URI_PROP_NAME, dirName + pkcsXml);
-    // }
-    // else if (this.cGen.classCode().isSSL()) {
-    // sysProps
-    // .setProperty(XmlAuthorization.DOC_URI_PROP_NAME, dirName + sslXml);
-    // }
-    else {
-      throw new IllegalArgumentException(
-          "No XML defined for XmlAuthorization module to work with "
-              + this.cGen.getAuthenticator());
-    }
-    return sysProps;
-  }
-
-  public ClassCode classCode() {
-    return ClassCode.XML;
-  }
-
-  public String getAuthorizationCallback() {
-    return "templates.security.XmlAuthorization.create";
-  }
-
-  private Principal getDummyPrincipal(byte roleType, int index) {
-
-    String[] admins = new String[] { "root", "admin", "administrator" };
-    int numReaders = 3;
-    int numWriters = 3;
-
-    switch (roleType) {
-      case READER_ROLE:
-        return new UsernamePrincipal("reader" + (index % numReaders));
-      case WRITER_ROLE:
-        return new UsernamePrincipal("writer" + (index % numWriters));
-      case QUERY_ROLE:
-        return new UsernamePrincipal("reader" + ((index % 2) + 3));
-      default:
-        return new UsernamePrincipal(admins[index % admins.length]);
-    }
-  }
-
-  private Principal getLdapPrincipal(byte roleType, int index) {
-
-    final String userPrefix = "gemfire";
-    final int[] readerIndices = { 3, 4, 5 };
-    final int[] writerIndices = { 6, 7, 8 };
-    final int[] queryIndices = { 9, 10 };
-    final int[] adminIndices = { 1, 2 };
-
-    switch (roleType) {
-      case READER_ROLE:
-        int readerIndex = readerIndices[index % readerIndices.length];
-        return new UsernamePrincipal(userPrefix + readerIndex);
-      case WRITER_ROLE:
-        int writerIndex = writerIndices[index % writerIndices.length];
-        return new UsernamePrincipal(userPrefix + writerIndex);
-      case QUERY_ROLE:
-        int queryIndex = queryIndices[index % queryIndices.length];
-        return new UsernamePrincipal(userPrefix + queryIndex);
-      default:
-        int adminIndex = adminIndices[index % adminIndices.length];
-        return new UsernamePrincipal(userPrefix + adminIndex);
-    }
-  }
-
-  private byte getRequiredRole(OperationCode[] opCodes, String[] regionNames) {
-
-    byte roleType = ADMIN_ROLE;
-    boolean requiresReader = true;
-    boolean requiresWriter = true;
-    boolean requiresQuery = true;
-
-    for (int opNum = 0; opNum < opCodes.length; opNum++) {
-      OperationCode opCode = opCodes[opNum];
-      if (requiresReader && !readerOpsSet.contains(opCode)) {
-        requiresReader = false;
-      }
-      if (requiresWriter && !writerOpsSet.contains(opCode)) {
-        requiresWriter = false;
-      }
-      if (requiresQuery && !queryOpsSet.contains(opCode)) {
-        requiresQuery = false;
-      }
-    }
-    if (requiresReader) {
-      roleType = READER_ROLE;
-    }
-    else if (requiresWriter) {
-      roleType = WRITER_ROLE;
-    }
-    else if (requiresQuery) {
-      if (regionNames != null && regionNames.length > 0) {
-        for (int index = 0; index < regionNames.length; index++) {
-          String regionName = XmlAuthorization
-              .normalizeRegionName(regionNames[index]);
-          if (requiresQuery && !queryRegionSet.contains(regionName)) {
-            requiresQuery = false;
-            break;
-          }
-        }
-        if (requiresQuery) {
-          roleType = QUERY_ROLE;
-        }
-      }
-    }
-    return roleType;
-  }
-
-  protected Principal getAllowedPrincipal(OperationCode[] opCodes,
-      String[] regionNames, int index) {
-
-    if (this.cGen.classCode().isDummy()) {
-      byte roleType = getRequiredRole(opCodes, regionNames);
-      return getDummyPrincipal(roleType, index);
-    }
-    else if (this.cGen.classCode().isLDAP()) {
-      byte roleType = getRequiredRole(opCodes, regionNames);
-      return getLdapPrincipal(roleType, index);
-    }
-    return null;
-  }
-
-  protected Principal getDisallowedPrincipal(OperationCode[] opCodes,
-      String[] regionNames, int index) {
-
-    byte roleType = getRequiredRole(opCodes, regionNames);
-    byte disallowedRoleType = READER_ROLE;
-    switch (roleType) {
-      case READER_ROLE:
-        disallowedRoleType = WRITER_ROLE;
-        break;
-      case WRITER_ROLE:
-        disallowedRoleType = READER_ROLE;
-        break;
-      case QUERY_ROLE:
-        disallowedRoleType = READER_ROLE;
-        break;
-      case ADMIN_ROLE:
-        disallowedRoleType = READER_ROLE;
-        break;
-    }
-    if (this.cGen.classCode().isDummy()) {
-      return getDummyPrincipal(disallowedRoleType, index);
-    }
-    else if (this.cGen.classCode().isLDAP()) {
-      return getLdapPrincipal(disallowedRoleType, index);
-    }
-    return null;
-  }
-
-  protected int getNumPrincipalTries(OperationCode[] opCodes,
-      String[] regionNames) {
-    return 5;
-  }
-
-}


[6/7] incubator-geode git commit: GEM-164: move the security tests in gemfire-test module inside the com.gemstone.gemfire.security packages to the open side.

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
new file mode 100644
index 0000000..e89e0d3
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
@@ -0,0 +1,798 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+
+import templates.security.AuthzCredentialGenerator;
+import templates.security.CredentialGenerator;
+import templates.security.DummyCredentialGenerator;
+import templates.security.XmlAuthzCredentialGenerator;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.internal.AvailablePort;
+import templates.security.UserPasswordAuthInit;
+
+import dunit.Host;
+import dunit.VM;
+
+/**
+ * Tests for authorization from client to server. This tests for authorization
+ * of all operations with both valid and invalid credentials/modules with
+ * pre-operation callbacks. It also checks for authorization in case of
+ * failover.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public class ClientAuthorizationDUnitTest extends ClientAuthorizationTestBase {
+
+  /** constructor */
+  public ClientAuthorizationDUnitTest(String name) {
+    super(name);
+  }
+
+  @Override
+  public void setUp() throws Exception {
+
+    super.setUp();
+    final Host host = Host.getHost(0);
+    server1 = host.getVM(0);
+    server2 = host.getVM(1);
+    client1 = host.getVM(2);
+    client2 = host.getVM(3);
+
+    server1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    server2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    client1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+    client2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+    SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+  }
+
+  private Properties getUserPassword(String userName) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+    return props;
+  }
+
+  private void executeRIOpBlock(List opBlock, Integer port1, Integer port2,
+      String authInit, Properties extraAuthProps, Properties extraAuthzProps,
+      Properties javaProps) {
+
+    Iterator opIter = opBlock.iterator();
+    while (opIter.hasNext()) {
+      // Start client with valid credentials as specified in
+      // OperationWithAction
+      OperationWithAction currentOp = (OperationWithAction)opIter.next();
+      OperationCode opCode = currentOp.getOperationCode();
+      int opFlags = currentOp.getFlags();
+      int clientNum = currentOp.getClientNum();
+      VM clientVM = null;
+      boolean useThisVM = false;
+      switch (clientNum) {
+        case 1:
+          clientVM = client1;
+          break;
+        case 2:
+          clientVM = client2;
+          break;
+        case 3:
+          useThisVM = true;
+          break;
+        default:
+          fail("executeRIOpBlock: Unknown client number " + clientNum);
+          break;
+      }
+      getLogWriter().info(
+          "executeRIOpBlock: performing operation number ["
+              + currentOp.getOpNum() + "]: " + currentOp);
+      if ((opFlags & OpFlags.USE_OLDCONN) == 0) {
+        Properties opCredentials = null;
+        String currentRegionName = '/' + regionName;
+        if ((opFlags & OpFlags.USE_SUBREGION) > 0) {
+          currentRegionName += ('/' + subregionName);
+        }
+        String credentialsTypeStr;
+        OperationCode authOpCode = currentOp.getAuthzOperationCode();
+        if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0
+            || (opFlags & OpFlags.USE_NOTAUTHZ) > 0
+            || !authOpCode.equals(opCode)) {
+          credentialsTypeStr = " unauthorized " + authOpCode;
+          if (authOpCode.isRegisterInterest()) {
+            opCredentials = getUserPassword("reader7");
+          }
+          else if (authOpCode.isUnregisterInterest()) {
+            opCredentials = getUserPassword("reader6");
+          }
+          else {
+            fail("executeRIOpBlock: cannot determine credentials for"
+                + credentialsTypeStr);
+          }
+        }
+        else {
+          credentialsTypeStr = " authorized " + authOpCode;
+          if (authOpCode.isRegisterInterest()
+              || authOpCode.isUnregisterInterest()) {
+            opCredentials = getUserPassword("reader5");
+          }
+          else if (authOpCode.isPut()) {
+            opCredentials = getUserPassword("writer1");
+          }
+          else if (authOpCode.isGet()) {
+            opCredentials = getUserPassword("reader1");
+          }
+          else {
+            fail("executeRIOpBlock: cannot determine credentials for"
+                + credentialsTypeStr);
+          }
+        }
+        Properties clientProps = SecurityTestUtil
+            .concatProperties(new Properties[] { opCredentials, extraAuthProps,
+                extraAuthzProps });
+        // Start the client with valid credentials but allowed or disallowed to
+        // perform an operation
+        getLogWriter().info(
+            "executeRIOpBlock: For client" + clientNum + credentialsTypeStr
+                + " credentials: " + opCredentials);
+        if (useThisVM) {
+          createCacheClient(authInit, clientProps, javaProps, new Integer[] {
+              port1, port2 }, null, Boolean.valueOf(false), new Integer(
+              SecurityTestUtil.NO_EXCEPTION));
+        }
+        else {
+          clientVM.invoke(ClientAuthorizationTestBase.class,
+              "createCacheClient", new Object[] { authInit, clientProps,
+                  javaProps, new Integer[] { port1, port2 }, null,
+                  Boolean.valueOf(false),
+                  new Integer(SecurityTestUtil.NO_EXCEPTION) });
+        }
+      }
+      int expectedResult;
+      if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0) {
+        expectedResult = SecurityTestUtil.NOTAUTHZ_EXCEPTION;
+      }
+      else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
+        expectedResult = SecurityTestUtil.OTHER_EXCEPTION;
+      }
+      else {
+        expectedResult = SecurityTestUtil.NO_EXCEPTION;
+      }
+
+      // Perform the operation from selected client
+      if (useThisVM) {
+        doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), new Integer(
+            opFlags), new Integer(expectedResult));
+      }
+      else {
+        clientVM.invoke(ClientAuthorizationTestBase.class, "doOp",
+            new Object[] { new Byte(opCode.toOrdinal()),
+                currentOp.getIndices(), new Integer(opFlags),
+                new Integer(expectedResult) });
+      }
+    }
+  }
+
+  // Region: Tests
+
+  public void testAllowPutsGets() {
+      AuthzCredentialGenerator gen = getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testAllowPutsGets: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testAllowPutsGets: Using authenticator: " + authenticator);
+      getLogWriter().info("testAllowPutsGets: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+      Integer port2 = ((Integer)server2.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+
+      // Start client1 with valid CREATE credentials
+      Properties createCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.PUT },
+          new String[] { regionName }, 1);
+      javaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testAllowPutsGets: For first client credentials: "
+              + createCredentials);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, createCredentials, javaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Start client2 with valid GET credentials
+      Properties getCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 2);
+      javaProps = cGen.getJavaProperties();
+      getLogWriter()
+          .info(
+              "testAllowPutsGets: For second client credentials: "
+                  + getCredentials);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, javaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Verify that the gets succeed
+      client2.invoke(SecurityTestUtil.class, "doGets", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+  }
+
+  public void testDisallowPutsGets() {
+
+      AuthzCredentialGenerator gen = getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testDisallowPutsGets: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testDisallowPutsGets: Using authenticator: " + authenticator);
+      getLogWriter().info("testDisallowPutsGets: Using accessor: " + accessor);
+
+      // Check that we indeed can obtain valid credentials not allowed to do
+      // gets
+      Properties createCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.PUT },
+          new String[] { regionName }, 1);
+      Properties createJavaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testDisallowPutsGets: For first client credentials: "
+              + createCredentials);
+      Properties getCredentials = gen.getDisallowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 2);
+      Properties getJavaProps = cGen.getJavaProperties();
+
+      getLogWriter().info(
+          "testDisallowPutsGets: For second client disallowed GET credentials: "
+              + getCredentials);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+      Integer port2 = ((Integer)server2.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+
+      // Start client1 with valid CREATE credentials
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, createCredentials, createJavaProps, port1,
+              port2, null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Start client2 with invalid GET credentials
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, getJavaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Gets as normal user should throw exception
+      client2.invoke(SecurityTestUtil.class, "doGets", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) });
+
+      // Try to connect client2 with reader credentials
+      getCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 5);
+      getJavaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testDisallowPutsGets: For second client with GET credentials: "
+              + getCredentials);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, getJavaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Verify that the gets succeed
+      client2.invoke(SecurityTestUtil.class, "doGets", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Verify that the puts throw exception
+      client2.invoke(SecurityTestUtil.class, "doNPuts", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) });
+  }
+
+  public void testInvalidAccessor() {
+      AuthzCredentialGenerator gen = getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testInvalidAccessor: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testInvalidAccessor: Using authenticator: " + authenticator);
+
+      // Start server1 with invalid accessor
+      Properties serverProps = buildProperties(authenticator,
+          "com.gemstone.none", false, extraAuthProps, extraAuthzProps);
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+      Integer port2 = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+
+      // Client creation should throw exceptions
+      Properties createCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.PUT },
+          new String[] { regionName }, 3);
+      Properties createJavaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidAccessor: For first client CREATE credentials: "
+              + createCredentials);
+      Properties getCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 7);
+      Properties getJavaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidAccessor: For second client GET credentials: "
+              + getCredentials);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, createCredentials, createJavaProps, port1,
+              port2, null, Boolean.FALSE, Boolean.FALSE,
+              Integer.valueOf(SecurityTestUtil.NO_EXCEPTION) });
+      client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(1), new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, getJavaProps, port1, port2,
+              null, Boolean.FALSE, Boolean.FALSE,
+              Integer.valueOf(SecurityTestUtil.NO_EXCEPTION) });
+      client2.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(1), new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+
+      // Now start server2 that has valid accessor
+      getLogWriter().info("testInvalidAccessor: Using accessor: " + accessor);
+      serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      server2.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] { SecurityTestUtil.getLocatorPort(), port2, serverProps,
+              javaProps });
+      server1.invoke(SecurityTestUtil.class, "closeCache");
+
+      // Client creation should be successful now
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, createCredentials, createJavaProps, port1,
+              port2, null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, getJavaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Now perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Verify that the gets succeed
+      client2.invoke(SecurityTestUtil.class, "doGets", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+  }
+
+  public void testPutsGetsWithFailover() {
+      AuthzCredentialGenerator gen = getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info(
+          "testPutsGetsWithFailover: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testPutsGetsWithFailover: Using authenticator: " + authenticator);
+      getLogWriter().info(
+          "testPutsGetsWithFailover: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+      // Get a port for second server but do not start it
+      // This forces the clients to connect to the first server
+      Integer port2 = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+
+      // Start client1 with valid CREATE credentials
+      Properties createCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.PUT },
+          new String[] { regionName }, 1);
+      Properties createJavaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testPutsGetsWithFailover: For first client credentials: "
+              + createCredentials);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, createCredentials, createJavaProps, port1,
+              port2, null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Start client2 with valid GET credentials
+      Properties getCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 5);
+      Properties getJavaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testPutsGetsWithFailover: For second client credentials: "
+              + getCredentials);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, getJavaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      // Verify that the puts succeeded
+      client2.invoke(SecurityTestUtil.class, "doGets", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // start the second one and stop the first server to force a failover
+      server2.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] { SecurityTestUtil.getLocatorPort(), port2, serverProps,
+              javaProps });
+      server1.invoke(SecurityTestUtil.class, "closeCache");
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doNPuts", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      // Verify that the puts succeeded
+      client2.invoke(SecurityTestUtil.class, "doNGets", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Now re-connect with credentials not allowed to do gets
+      Properties noGetCredentials = gen.getDisallowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 9);
+      getJavaProps = cGen.getJavaProperties();
+
+      getLogWriter().info(
+          "testPutsGetsWithFailover: For second client disallowed GET credentials: "
+              + noGetCredentials);
+
+      // Re-connect client2 with invalid GET credentials
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, noGetCredentials, getJavaProps, port1,
+              port2, null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      // Gets as normal user should throw exception
+      client2.invoke(SecurityTestUtil.class, "doGets", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) });
+
+      // force a failover and do the drill again
+      server1.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] { SecurityTestUtil.getLocatorPort(), port1, serverProps,
+              javaProps });
+      server2.invoke(SecurityTestUtil.class, "closeCache");
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doNPuts", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      // Gets as normal user should throw exception
+      client2.invoke(SecurityTestUtil.class, "doNGets", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) });
+
+      // Try to connect client2 with reader credentials
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, getJavaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Verify that the gets succeed
+      client2.invoke(SecurityTestUtil.class, "doNGets", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Verify that the puts throw exception
+      client2.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+          new Integer(4), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) });
+  }
+
+  public void testUnregisterInterestWithFailover() {
+
+    OperationWithAction[] unregisterOps = {
+        // Register interest in all keys using one key at a time
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.UNREGISTER_INTEREST, 3, OpFlags.NONE, 4),
+        new OperationWithAction(OperationCode.REGISTER_INTEREST, 2),
+        // UPDATE and test with GET
+        new OperationWithAction(OperationCode.PUT),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        // Unregister interest in all keys using one key at a time
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 3,
+            OpFlags.USE_OLDCONN | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 2,
+            OpFlags.USE_OLDCONN, 4),
+        // UPDATE and test with GET for no updates
+        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Register interest in all keys using list
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.UNREGISTER_INTEREST, 3, OpFlags.USE_LIST, 4),
+        new OperationWithAction(OperationCode.REGISTER_INTEREST, 1,
+            OpFlags.USE_LIST, 4),
+        // UPDATE and test with GET
+        new OperationWithAction(OperationCode.PUT, 2),
+        new OperationWithAction(OperationCode.GET, 1, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        // Unregister interest in all keys using list
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 3,
+            OpFlags.USE_OLDCONN | OpFlags.USE_LIST | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 1,
+            OpFlags.USE_OLDCONN | OpFlags.USE_LIST, 4),
+        // UPDATE and test with GET for no updates
+        new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 1, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Register interest in all keys using regular expression
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.UNREGISTER_INTEREST, 3, OpFlags.USE_REGEX, 4),
+        new OperationWithAction(OperationCode.REGISTER_INTEREST, 2,
+            OpFlags.USE_REGEX, 4),
+        // UPDATE and test with GET
+        new OperationWithAction(OperationCode.PUT),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        // Unregister interest in all keys using regular expression
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 3,
+            OpFlags.USE_OLDCONN | OpFlags.USE_REGEX | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 2,
+            OpFlags.USE_OLDCONN | OpFlags.USE_REGEX, 4),
+        // UPDATE and test with GET for no updates
+        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        OperationWithAction.OPBLOCK_END };
+
+    AuthzCredentialGenerator gen = new XmlAuthzCredentialGenerator();
+    CredentialGenerator cGen = new DummyCredentialGenerator();
+    cGen.init();
+    gen.init(cGen);
+    Properties extraAuthProps = cGen.getSystemProperties();
+    Properties javaProps = cGen.getJavaProperties();
+    Properties extraAuthzProps = gen.getSystemProperties();
+    String authenticator = cGen.getAuthenticator();
+    String authInit = cGen.getAuthInit();
+    String accessor = gen.getAuthorizationCallback();
+
+    getLogWriter().info("testAllOpsWithFailover: Using authinit: " + authInit);
+    getLogWriter().info(
+        "testAllOpsWithFailover: Using authenticator: " + authenticator);
+    getLogWriter().info("testAllOpsWithFailover: Using accessor: " + accessor);
+
+    // Start servers with all required properties
+    Properties serverProps = buildProperties(authenticator, accessor, false,
+        extraAuthProps, extraAuthzProps);
+    // Get ports for the servers
+    Integer port1 = new Integer(AvailablePort
+        .getRandomAvailablePort(AvailablePort.SOCKET));
+    Integer port2 = new Integer(AvailablePort
+        .getRandomAvailablePort(AvailablePort.SOCKET));
+
+    // Perform all the ops on the clients
+    List opBlock = new ArrayList();
+    for (int opNum = 0; opNum < unregisterOps.length; ++opNum) {
+      // Start client with valid credentials as specified in
+      // OperationWithAction
+      OperationWithAction currentOp = unregisterOps[opNum];
+      if (currentOp.equals(OperationWithAction.OPBLOCK_END)
+          || currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+        // End of current operation block; execute all the operations
+        // on the servers with/without failover
+        if (opBlock.size() > 0) {
+          // Start the first server and execute the operation block
+          server1.invoke(ClientAuthorizationTestBase.class,
+              "createCacheServer", new Object[] {
+                  SecurityTestUtil.getLocatorPort(), port1, serverProps,
+                  javaProps });
+          server2.invoke(SecurityTestUtil.class, "closeCache");
+          executeRIOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
+              extraAuthzProps, javaProps);
+          if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+            // Failover to the second server and run the block again
+            server2.invoke(ClientAuthorizationTestBase.class,
+                "createCacheServer", new Object[] {
+                    SecurityTestUtil.getLocatorPort(), port2, serverProps,
+                    javaProps });
+            server1.invoke(SecurityTestUtil.class, "closeCache");
+            executeRIOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
+                extraAuthzProps, javaProps);
+          }
+          opBlock.clear();
+        }
+      }
+      else {
+        currentOp.setOpNum(opNum);
+        opBlock.add(currentOp);
+      }
+    }
+  }
+
+  
+  public void testAllOpsWithFailover() {
+    addExpectedException("Read timed out");
+
+    OperationWithAction[] allOps = {
+        // Test CREATE and verify with a GET
+        new OperationWithAction(OperationCode.PUT, 3, OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.PUT),
+        new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY
+            | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY, 4),
+
+        // OPBLOCK_END indicates end of an operation block; the above block of
+        // three operations will be first executed on server1 and then on
+        // server2 after failover
+        OperationWithAction.OPBLOCK_END,
+
+        // Test PUTALL and verify with GETs
+        new OperationWithAction(OperationCode.PUTALL, 3, OpFlags.USE_NEWVAL
+            | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.PUTALL, 1, OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+        OperationWithAction.OPBLOCK_END,
+        
+        // Test UPDATE and verify with a GET
+        new OperationWithAction(OperationCode.PUT, 3, OpFlags.USE_NEWVAL
+            | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Test DESTROY and verify with a GET and that key should not exist
+        new OperationWithAction(OperationCode.DESTROY, 3, OpFlags.USE_NEWVAL
+            | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.DESTROY),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.CHECK_FAIL, 4), // bruce: added check_nokey because we now bring tombstones to the client in 8.0
+        // Repopulate the region
+        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_NEWVAL, 4),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Check CONTAINS_KEY
+        new OperationWithAction(OperationCode.CONTAINS_KEY, 3,
+            OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.CONTAINS_KEY),
+        // Destroy the keys and check for failure in CONTAINS_KEY
+        new OperationWithAction(OperationCode.DESTROY, 2),
+        new OperationWithAction(OperationCode.CONTAINS_KEY, 3,
+            OpFlags.CHECK_FAIL | OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.CONTAINS_KEY, 1,
+            OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL, 4),
+        // Repopulate the region
+        new OperationWithAction(OperationCode.PUT),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Check KEY_SET
+        new OperationWithAction(OperationCode.KEY_SET, 3,
+            OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.KEY_SET, 2),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Check QUERY
+        new OperationWithAction(OperationCode.QUERY, 3, OpFlags.CHECK_NOTAUTHZ,
+            4),
+        new OperationWithAction(OperationCode.QUERY),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Register interest in all keys using one key at a time
+        new OperationWithAction(OperationCode.REGISTER_INTEREST, 3,
+            OpFlags.CHECK_NOTAUTHZ, 4),
+        new OperationWithAction(OperationCode.REGISTER_INTEREST, 2),
+        // UPDATE and test with GET
+        new OperationWithAction(OperationCode.PUT),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        // Unregister interest in all keys using one key at a time
+        new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 2,
+            OpFlags.USE_OLDCONN, 4),
+        // UPDATE and test with GET for no updates
+        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+
+        OperationWithAction.OPBLOCK_END,
+
+        // Test GET_ENTRY inside a TX, see #49951
+        new OperationWithAction(OperationCode.GET, 2,
+            OpFlags.USE_GET_ENTRY_IN_TX | OpFlags.CHECK_FAIL, 4),
+
+        OperationWithAction.OPBLOCK_END };
+
+    runOpsWithFailover(allOps, "testAllOpsWithFailover");
+  }
+
+  // End Region: Tests
+
+  @Override
+  public void tearDown2() throws Exception {
+
+    super.tearDown2();
+    // close the clients first
+    client1.invoke(SecurityTestUtil.class, "closeCache");
+    client2.invoke(SecurityTestUtil.class, "closeCache");
+    SecurityTestUtil.closeCache();
+    // then close the servers
+    server1.invoke(SecurityTestUtil.class, "closeCache");
+    server2.invoke(SecurityTestUtil.class, "closeCache");
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
new file mode 100644
index 0000000..ad6526a
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
@@ -0,0 +1,1384 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+
+import templates.security.AuthzCredentialGenerator;
+import templates.security.CredentialGenerator;
+import templates.security.AuthzCredentialGenerator.ClassCode;
+
+import com.gemstone.gemfire.cache.DynamicRegionFactory;
+import com.gemstone.gemfire.cache.InterestResultPolicy;
+import com.gemstone.gemfire.cache.Operation;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.Region.Entry;
+import com.gemstone.gemfire.cache.RegionDestroyedException;
+import com.gemstone.gemfire.cache.client.ServerConnectivityException;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.cache.query.CqAttributes;
+import com.gemstone.gemfire.cache.query.CqAttributesFactory;
+import com.gemstone.gemfire.cache.query.CqEvent;
+import com.gemstone.gemfire.cache.query.CqException;
+import com.gemstone.gemfire.cache.query.CqListener;
+import com.gemstone.gemfire.cache.query.CqQuery;
+import com.gemstone.gemfire.cache.query.QueryInvocationTargetException;
+import com.gemstone.gemfire.cache.query.QueryService;
+import com.gemstone.gemfire.cache.query.SelectResults;
+import com.gemstone.gemfire.cache.query.Struct;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.AvailablePort;
+import com.gemstone.gemfire.internal.AvailablePort.Keeper;
+import com.gemstone.gemfire.internal.cache.AbstractRegionEntry;
+import com.gemstone.gemfire.internal.cache.LocalRegion;
+import com.gemstone.gemfire.internal.util.Callable;
+
+import dunit.DistributedTestCase;
+import dunit.VM;
+import templates.security.DummyCredentialGenerator;
+import templates.security.XmlAuthzCredentialGenerator;
+
+/**
+ * Base class for tests for authorization from client to server. It contains
+ * utility functions for the authorization tests from client to server.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public class ClientAuthorizationTestBase extends DistributedTestCase {
+
+  /** constructor */
+  public ClientAuthorizationTestBase(String name) {
+    super(name);
+  }
+
+  protected static VM server1 = null;
+
+  protected static VM server2 = null;
+
+  protected static VM client1 = null;
+
+  protected static VM client2 = null;
+
+  protected static final String regionName = SecurityTestUtil.regionName;
+
+  protected static final String subregionName = "AuthSubregion";
+
+  protected static final String[] serverExpectedExceptions = {
+      "Connection refused",
+      AuthenticationRequiredException.class.getName(),
+      AuthenticationFailedException.class.getName(),
+      NotAuthorizedException.class.getName(),
+      GemFireSecurityException.class.getName(),
+      RegionDestroyedException.class.getName(),
+      ClassNotFoundException.class.getName() };
+
+  protected static final String[] clientExpectedExceptions = {
+      AuthenticationFailedException.class.getName(),
+      NotAuthorizedException.class.getName(),
+      RegionDestroyedException.class.getName() };
+
+  protected static Properties buildProperties(String authenticator,
+      String accessor, boolean isAccessorPP, Properties extraAuthProps,
+      Properties extraAuthzProps) {
+
+    Properties authProps = new Properties();
+    if (authenticator != null) {
+      authProps.setProperty(
+          DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
+    }
+    if (accessor != null) {
+      if (isAccessorPP) {
+        authProps.setProperty(
+            DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME, accessor);
+      }
+      else {
+        authProps.setProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME,
+            accessor);
+      }
+    }
+    return SecurityTestUtil.concatProperties(new Properties[] { authProps,
+        extraAuthProps, extraAuthzProps });
+  }
+
+  public static Integer createCacheServer(Integer locatorPort, Object authProps,
+      Object javaProps) {
+
+    if (locatorPort == null) {
+      locatorPort = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+    }
+    return SecurityTestUtil.createCacheServer((Properties)authProps, javaProps,
+        locatorPort, null, null, Boolean.TRUE, new Integer(
+            SecurityTestUtil.NO_EXCEPTION));
+  }
+
+  public static void createCacheServer(Integer locatorPort, Integer serverPort,
+      Object authProps, Object javaProps) {
+    if (locatorPort == null) {
+      locatorPort = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+    }
+    SecurityTestUtil.createCacheServer((Properties)authProps, javaProps,
+        locatorPort, null, serverPort, Boolean.TRUE, new Integer(
+            SecurityTestUtil.NO_EXCEPTION));
+  }
+
+  public static void createCacheClient(Object authInit, Object authProps,
+      Object javaProps, Integer[] ports, Integer numConnections,
+      Boolean setupDynamicRegionFactory, Integer expectedResult) {
+
+    String authInitStr = (authInit == null ? null : authInit.toString());
+    if (authProps == null) {
+      authProps = new Properties();
+    }
+    SecurityTestUtil.createCacheClient(authInitStr, (Properties)authProps,
+        (Properties)javaProps, ports, numConnections,
+        setupDynamicRegionFactory, expectedResult);
+  }
+
+  protected static Region getRegion() {
+    return SecurityTestUtil.getCache().getRegion(regionName);
+  }
+
+  protected static Region getSubregion() {
+    return SecurityTestUtil.getCache().getRegion(
+        regionName + '/' + subregionName);
+  }
+
+  private static Region createSubregion(Region region) {
+
+    Region subregion = getSubregion();
+    if (subregion == null) {
+      subregion = region.createSubregion(subregionName, region.getAttributes());
+    }
+    return subregion;
+  }
+
+  protected static String indicesToString(int[] indices) {
+
+    String str = "";
+    if (indices != null && indices.length > 0) {
+      str += indices[0];
+      for (int index = 1; index < indices.length; ++index) {
+        str += ",";
+        str += indices[index];
+      }
+    }
+    return str;
+  }
+
+  private static final int PAUSE = 5 * 1000;
+  
+  public static void doOp(Byte opCode, int[] indices, Integer flagsI,
+      Integer expectedResult) {
+
+    OperationCode op = OperationCode.fromOrdinal(opCode.byteValue());
+    boolean operationOmitted = false;
+    final int flags = flagsI.intValue();
+    Region region = getRegion();
+    if ((flags & OpFlags.USE_SUBREGION) > 0) {
+      assertNotNull(region);
+      Region subregion = null;
+      if ((flags & OpFlags.NO_CREATE_SUBREGION) > 0) {
+        if ((flags & OpFlags.CHECK_NOREGION) > 0) {
+          // Wait for some time for DRF update to come
+          SecurityTestUtil.waitForCondition(new Callable() {
+            public Object call() throws Exception {
+              return Boolean.valueOf(getSubregion() == null);
+            }
+          });
+          subregion = getSubregion();
+          assertNull(subregion);
+          return;
+        }
+        else {
+          // Wait for some time for DRF update to come
+          SecurityTestUtil.waitForCondition(new Callable() {
+            public Object call() throws Exception {
+              return Boolean.valueOf(getSubregion() != null);
+            }
+          });
+          subregion = getSubregion();
+          assertNotNull(subregion);
+        }
+      }
+      else {
+        subregion = createSubregion(region);
+      }
+      assertNotNull(subregion);
+      region = subregion;
+    }
+    else if ((flags & OpFlags.CHECK_NOREGION) > 0) {
+      // Wait for some time for region destroy update to come
+      SecurityTestUtil.waitForCondition(new Callable() {
+        public Object call() throws Exception {
+          return Boolean.valueOf(getRegion() == null);
+        }
+      });
+      region = getRegion();
+      assertNull(region);
+      return;
+    }
+    else {
+      assertNotNull(region);
+    }
+    final String[] keys = SecurityTestUtil.keys;
+    final String[] vals;
+    if ((flags & OpFlags.USE_NEWVAL) > 0) {
+      vals = SecurityTestUtil.nvalues;
+    }
+    else {
+      vals = SecurityTestUtil.values;
+    }
+    InterestResultPolicy policy = InterestResultPolicy.KEYS_VALUES;
+    if ((flags & OpFlags.REGISTER_POLICY_NONE) > 0) {
+      policy = InterestResultPolicy.NONE;
+    }
+    final int numOps = indices.length;
+    getLogWriter().info(
+        "Got doOp for op: " + op.toString() + ", numOps: " + numOps
+            + ", indices: " + indicesToString(indices) + ", expect: " + expectedResult);
+    boolean exceptionOccured = false;
+    boolean breakLoop = false;
+    if (op.isGet() || 
+        op.isContainsKey() || 
+        op.isKeySet() || 
+        op.isQuery() || 
+        op.isExecuteCQ()) {
+      try {
+        Thread.sleep(PAUSE);
+      }
+      catch (InterruptedException e) {
+        fail("interrupted");
+      }
+    }
+    for (int indexIndex = 0; indexIndex < numOps; ++indexIndex) {
+      if (breakLoop) {
+        break;
+      }
+      int index = indices[indexIndex];
+      try {
+        final Object key = keys[index];
+        final Object expectedVal = vals[index];
+        if (op.isGet()) {
+          Object value = null;
+          // this is the case for testing GET_ALL
+          if ((flags & OpFlags.USE_ALL_KEYS) > 0) {
+            breakLoop = true;
+            List keyList = new ArrayList(numOps);
+            Object searchKey;
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              searchKey = keys[keyNum];
+              keyList.add(searchKey);
+              // local invalidate some keys to force fetch of those keys from
+              // server
+              if ((flags & OpFlags.CHECK_NOKEY) > 0) {
+                AbstractRegionEntry entry = (AbstractRegionEntry)((LocalRegion)region).getRegionEntry(searchKey);
+                getLogWriter().info(""+keyNum+": key is " + searchKey + " and entry is " + entry);
+                assertFalse(region.containsKey(searchKey));
+              }
+              else {
+                if (keyNumIndex % 2 == 1) {
+                  assertTrue(region.containsKey(searchKey));
+                  region.localInvalidate(searchKey);
+                }
+              }
+            }
+            Map entries = region.getAll(keyList);
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              searchKey = keys[keyNum];
+              if ((flags & OpFlags.CHECK_FAIL) > 0) {
+                assertFalse(entries.containsKey(searchKey));
+              }
+              else {
+                assertTrue(entries.containsKey(searchKey));
+                value = entries.get(searchKey);
+                assertEquals(vals[keyNum], value);
+              }
+            }
+            break;
+          }
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            Callable cond = new Callable() {
+              private Region region;
+
+              public Object call() throws Exception {
+                Object value = SecurityTestUtil.getLocalValue(region, key);
+                return Boolean
+                    .valueOf((flags & OpFlags.CHECK_FAIL) > 0 ? !expectedVal
+                        .equals(value) : expectedVal.equals(value));
+              }
+
+              public Callable init(Region region) {
+                this.region = region;
+                return this;
+              }
+            }.init(region);
+            SecurityTestUtil.waitForCondition(cond);
+            value = SecurityTestUtil.getLocalValue(region, key);
+          }
+          else if ((flags & OpFlags.USE_GET_ENTRY_IN_TX) > 0) {
+            SecurityTestUtil.getCache().getCacheTransactionManager().begin();
+            Entry e = region.getEntry(key);
+            // Also, check getAll()
+            ArrayList a = new ArrayList();
+            a.addAll(a);
+            region.getAll(a);
+
+            SecurityTestUtil.getCache().getCacheTransactionManager().commit();
+            value = e.getValue();
+          }
+          else {
+            if ((flags & OpFlags.CHECK_NOKEY) > 0) {
+              assertFalse(region.containsKey(key));
+            }
+            else {
+              assertTrue(region.containsKey(key) || ((LocalRegion)region).getRegionEntry(key).isTombstone());
+              region.localInvalidate(key);
+            }
+            value = region.get(key);
+          }
+          if ((flags & OpFlags.CHECK_FAIL) > 0) {
+            assertFalse(expectedVal.equals(value));
+          }
+          else {
+            assertNotNull(value);
+            assertEquals(expectedVal, value);
+          }
+        }
+        else if (op.isPut()) {
+          region.put(key, expectedVal);
+        }
+        else if (op.isPutAll()) {
+          HashMap map = new HashMap();
+          for (int i=0; i<indices.length; i++) {
+            map.put(keys[indices[i]], vals[indices[i]]);
+          }
+          region.putAll(map);
+          breakLoop = true;
+        }
+        else if (op.isDestroy()) {
+          // if (!region.containsKey(key)) {
+          // // Since DESTROY will fail unless the value is present
+          // // in the local cache, this is a workaround for two cases:
+          // // 1. When the operation is supposed to succeed then in
+          // // the current AuthzCredentialGenerators the clients having
+          // // DESTROY permission also has CREATE/UPDATE permission
+          // // so that calling region.put() will work for that case.
+          // // 2. When the operation is supposed to fail with
+          // // NotAuthorizedException then in the current
+          // // AuthzCredentialGenerators the clients not
+          // // having DESTROY permission are those with reader role that have
+          // // GET permission.
+          // //
+          // // If either of these assumptions fails, then this has to be
+          // // adjusted or reworked accordingly.
+          // if ((flags & OpFlags.CHECK_NOTAUTHZ) > 0) {
+          // Object value = region.get(key);
+          // assertNotNull(value);
+          // assertEquals(vals[index], value);
+          // }
+          // else {
+          // region.put(key, vals[index]);
+          // }
+          // }
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            region.localDestroy(key);
+          }
+          else {
+            region.destroy(key);
+          }
+        }
+        else if (op.isInvalidate()) {
+          if (region.containsKey(key)) {
+            if ((flags & OpFlags.LOCAL_OP) > 0) {
+              region.localInvalidate(key);
+            }
+            else {
+              region.invalidate(key);
+            }
+          }
+        }
+        else if (op.isContainsKey()) {
+          boolean result;
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            result = region.containsKey(key);
+          }
+          else {
+            result = region.containsKeyOnServer(key);
+          }
+          if ((flags & OpFlags.CHECK_FAIL) > 0) {
+            assertFalse(result);
+          }
+          else {
+            assertTrue(result);
+          }
+        }
+        else if (op.isRegisterInterest()) {
+          if ((flags & OpFlags.USE_LIST) > 0) {
+            breakLoop = true;
+            // Register interest list in this case
+            List keyList = new ArrayList(numOps);
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              keyList.add(keys[keyNum]);
+            }
+            region.registerInterest(keyList, policy);
+          }
+          else if ((flags & OpFlags.USE_REGEX) > 0) {
+            breakLoop = true;
+            region.registerInterestRegex("key[1-" + numOps + ']', policy);
+          }
+          else if ((flags & OpFlags.USE_ALL_KEYS) > 0) {
+            breakLoop = true;
+            region.registerInterest("ALL_KEYS", policy);
+          }
+          else {
+            region.registerInterest(key, policy);
+          }
+        }
+        else if (op.isUnregisterInterest()) {
+          if ((flags & OpFlags.USE_LIST) > 0) {
+            breakLoop = true;
+            // Register interest list in this case
+            List keyList = new ArrayList(numOps);
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              keyList.add(keys[keyNum]);
+            }
+            region.unregisterInterest(keyList);
+          }
+          else if ((flags & OpFlags.USE_REGEX) > 0) {
+            breakLoop = true;
+            region.unregisterInterestRegex("key[1-" + numOps + ']');
+          }
+          else if ((flags & OpFlags.USE_ALL_KEYS) > 0) {
+            breakLoop = true;
+            region.unregisterInterest("ALL_KEYS");
+          }
+          else {
+            region.unregisterInterest(key);
+          }
+        }
+        else if (op.isKeySet()) {
+          breakLoop = true;
+          Set keySet;
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            keySet = region.keySet();
+          }
+          else {
+            keySet = region.keySetOnServer();
+          }
+          assertNotNull(keySet);
+          if ((flags & OpFlags.CHECK_FAIL) == 0) {
+            assertEquals(numOps, keySet.size());
+          }
+          for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+            int keyNum = indices[keyNumIndex];
+            if ((flags & OpFlags.CHECK_FAIL) > 0) {
+              assertFalse(keySet.contains(keys[keyNum]));
+            }
+            else {
+              assertTrue(keySet.contains(keys[keyNum]));
+            }
+          }
+        }
+        else if (op.isQuery()) {
+          breakLoop = true;
+          SelectResults queryResults = region.query("SELECT DISTINCT * FROM "
+              + region.getFullPath());
+          assertNotNull(queryResults);
+          Set queryResultSet = queryResults.asSet();
+          if ((flags & OpFlags.CHECK_FAIL) == 0) {
+            assertEquals(numOps, queryResultSet.size());
+          }
+          for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+            int keyNum = indices[keyNumIndex];
+            if ((flags & OpFlags.CHECK_FAIL) > 0) {
+              assertFalse(queryResultSet.contains(vals[keyNum]));
+            }
+            else {
+              assertTrue(queryResultSet.contains(vals[keyNum]));
+            }
+          }
+        }
+        else if (op.isExecuteCQ()) {
+          breakLoop = true;
+          QueryService queryService = SecurityTestUtil.getCache()
+              .getQueryService();
+          CqQuery cqQuery;
+          if ((cqQuery = queryService.getCq("cq1")) == null) {
+            CqAttributesFactory cqFact = new CqAttributesFactory();
+            cqFact.addCqListener(new AuthzCqListener());
+            CqAttributes cqAttrs = cqFact.create();
+            cqQuery = queryService.newCq("cq1", "SELECT * FROM "
+                + region.getFullPath(), cqAttrs);
+          }
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            // Interpret this as testing results using CqListener
+            final AuthzCqListener listener = (AuthzCqListener)cqQuery
+                .getCqAttributes().getCqListener();
+            WaitCriterion ev = new WaitCriterion() {
+              public boolean done() {
+                if ((flags & OpFlags.CHECK_FAIL) > 0) {
+                  return 0 == listener.getNumUpdates();
+                }
+                else {
+                  return numOps == listener.getNumUpdates();
+                }
+              }
+              public String description() {
+                return null;
+              }
+            };
+            DistributedTestCase.waitForCriterion(ev, 3 * 1000, 200, true);
+            if ((flags & OpFlags.CHECK_FAIL) > 0) {
+              assertEquals(0, listener.getNumUpdates());
+            }
+            else {
+              assertEquals(numOps, listener.getNumUpdates());
+              listener.checkPuts(vals, indices);
+            }
+            assertEquals(0, listener.getNumCreates());
+            assertEquals(0, listener.getNumDestroys());
+            assertEquals(0, listener.getNumOtherOps());
+            assertEquals(0, listener.getNumErrors());
+          }
+          else {
+            SelectResults cqResults = cqQuery.executeWithInitialResults();
+            assertNotNull(cqResults);
+            Set cqResultValues = new HashSet();
+            for (Object o : cqResults.asList()) {
+              Struct s = (Struct)o;
+              cqResultValues.add(s.get("value"));
+            }
+            Set cqResultSet = cqResults.asSet();
+            if ((flags & OpFlags.CHECK_FAIL) == 0) {
+              assertEquals(numOps, cqResultSet.size());
+            }
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              if ((flags & OpFlags.CHECK_FAIL) > 0) {
+                assertFalse(cqResultValues.contains(vals[keyNum]));
+              }
+              else {
+                assertTrue(cqResultValues.contains(vals[keyNum]));
+              }
+            }
+          }
+        }
+        else if (op.isStopCQ()) {
+          breakLoop = true;
+          CqQuery cqQuery = SecurityTestUtil.getCache().getQueryService()
+              .getCq("cq1");
+          ((AuthzCqListener)cqQuery.getCqAttributes().getCqListener()).reset();
+          cqQuery.stop();
+        }
+        else if (op.isCloseCQ()) {
+          breakLoop = true;
+          CqQuery cqQuery = SecurityTestUtil.getCache().getQueryService()
+              .getCq("cq1");
+          ((AuthzCqListener)cqQuery.getCqAttributes().getCqListener()).reset();
+          cqQuery.close();
+        }
+        else if (op.isRegionClear()) {
+          breakLoop = true;
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            region.localClear();
+          }
+          else {
+            region.clear();
+          }
+        }
+        else if (op.isRegionCreate()) {
+          breakLoop = true;
+          // Region subregion = createSubregion(region);
+          // subregion.createRegionOnServer();
+          // Create region on server using the DynamicRegionFactory
+          // Assume it has been already initialized
+          DynamicRegionFactory drf = DynamicRegionFactory.get();
+          Region subregion = drf.createDynamicRegion(regionName, subregionName);
+          assertEquals('/' + regionName + '/' + subregionName, subregion
+              .getFullPath());
+        }
+        else if (op.isRegionDestroy()) {
+          breakLoop = true;
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            region.localDestroyRegion();
+          }
+          else {
+            if ((flags & OpFlags.USE_SUBREGION) > 0) {
+              try {
+                DynamicRegionFactory.get().destroyDynamicRegion(
+                    region.getFullPath());
+              }
+              catch (RegionDestroyedException ex) {
+                // harmless to ignore this
+                getLogWriter().info(
+                    "doOp: sub-region " + region.getFullPath()
+                        + " already destroyed");
+                operationOmitted = true;
+              }
+            }
+            else {
+              region.destroyRegion();
+            }
+          }
+        }
+        else {
+          fail("doOp: Unhandled operation " + op);
+        }
+        if (expectedResult.intValue() != SecurityTestUtil.NO_EXCEPTION) {
+          if (!operationOmitted && !op.isUnregisterInterest()) {
+            fail("Expected an exception while performing operation op =" + op +
+                "flags = " + OpFlags.description(flags));
+          }
+        }
+      }
+      catch (Exception ex) {
+        exceptionOccured = true;
+        if ((ex instanceof ServerConnectivityException
+            || ex instanceof QueryInvocationTargetException || ex instanceof CqException)
+            && (expectedResult.intValue() == SecurityTestUtil.NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "doOp: Got expected NotAuthorizedException when doing operation ["
+                  + op + "] with flags " + OpFlags.description(flags) 
+                  + ": " + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+          getLogWriter().info(
+              "doOp: Got expected exception when doing operation: "
+                  + ex.toString());
+          continue;
+        }
+        else {
+          fail("doOp: Got unexpected exception when doing operation. Policy = " 
+              + policy + " flags = " + OpFlags.description(flags), ex);
+        }
+      }
+    }
+    if (!exceptionOccured && !operationOmitted
+        && expectedResult.intValue() != SecurityTestUtil.NO_EXCEPTION) {
+      fail("Expected an exception while performing operation: " + op + 
+          " flags = " + OpFlags.description(flags));
+    }
+  }
+
+  protected void executeOpBlock(List opBlock, Integer port1, Integer port2,
+      String authInit, Properties extraAuthProps, Properties extraAuthzProps,
+      TestCredentialGenerator gen, Random rnd) {
+
+    Iterator opIter = opBlock.iterator();
+    while (opIter.hasNext()) {
+      // Start client with valid credentials as specified in
+      // OperationWithAction
+      OperationWithAction currentOp = (OperationWithAction)opIter.next();
+      OperationCode opCode = currentOp.getOperationCode();
+      int opFlags = currentOp.getFlags();
+      int clientNum = currentOp.getClientNum();
+      VM clientVM = null;
+      boolean useThisVM = false;
+      switch (clientNum) {
+        case 1:
+          clientVM = client1;
+          break;
+        case 2:
+          clientVM = client2;
+          break;
+        case 3:
+          useThisVM = true;
+          break;
+        default:
+          fail("executeOpBlock: Unknown client number " + clientNum);
+          break;
+      }
+      getLogWriter().info(
+          "executeOpBlock: performing operation number ["
+              + currentOp.getOpNum() + "]: " + currentOp);
+      if ((opFlags & OpFlags.USE_OLDCONN) == 0) {
+        Properties opCredentials;
+        int newRnd = rnd.nextInt(100) + 1;
+        String currentRegionName = '/' + regionName;
+        if ((opFlags & OpFlags.USE_SUBREGION) > 0) {
+          currentRegionName += ('/' + subregionName);
+        }
+        String credentialsTypeStr;
+        OperationCode authOpCode = currentOp.getAuthzOperationCode();
+        int[] indices = currentOp.getIndices();
+        CredentialGenerator cGen = gen.getCredentialGenerator();
+        Properties javaProps = null;
+        if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0
+            || (opFlags & OpFlags.USE_NOTAUTHZ) > 0) {
+          opCredentials = gen.getDisallowedCredentials(
+              new OperationCode[] { authOpCode },
+              new String[] { currentRegionName }, indices, newRnd);
+          credentialsTypeStr = " unauthorized " + authOpCode;
+        }
+        else {
+          opCredentials = gen.getAllowedCredentials(new OperationCode[] {
+              opCode, authOpCode }, new String[] { currentRegionName },
+              indices, newRnd);
+          credentialsTypeStr = " authorized " + authOpCode;
+        }
+        if (cGen != null) {
+          javaProps = cGen.getJavaProperties();
+        }
+        Properties clientProps = SecurityTestUtil
+            .concatProperties(new Properties[] { opCredentials, extraAuthProps,
+                extraAuthzProps });
+        // Start the client with valid credentials but allowed or disallowed to
+        // perform an operation
+        getLogWriter().info(
+            "executeOpBlock: For client" + clientNum + credentialsTypeStr
+                + " credentials: " + opCredentials);
+        boolean setupDynamicRegionFactory = (opFlags & OpFlags.ENABLE_DRF) > 0;
+        if (useThisVM) {
+          createCacheClient(authInit, clientProps, javaProps, new Integer[] {
+              port1, port2 }, null, Boolean.valueOf(setupDynamicRegionFactory),
+              new Integer(SecurityTestUtil.NO_EXCEPTION));
+        }
+        else {
+          clientVM.invoke(ClientAuthorizationTestBase.class,
+              "createCacheClient", new Object[] { authInit, clientProps,
+                  javaProps, new Integer[] { port1, port2 }, null,
+                  Boolean.valueOf(setupDynamicRegionFactory),
+                  new Integer(SecurityTestUtil.NO_EXCEPTION) });
+        }
+      }
+      int expectedResult;
+      if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0) {
+        expectedResult = SecurityTestUtil.NOTAUTHZ_EXCEPTION;
+      }
+      else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
+        expectedResult = SecurityTestUtil.OTHER_EXCEPTION;
+      }
+      else {
+        expectedResult = SecurityTestUtil.NO_EXCEPTION;
+      }
+
+      // Perform the operation from selected client
+      if (useThisVM) {
+        doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), new Integer(
+            opFlags), new Integer(expectedResult));
+      }
+      else {
+        clientVM.invoke(ClientAuthorizationTestBase.class, "doOp",
+            new Object[] { new Byte(opCode.toOrdinal()),
+                currentOp.getIndices(), new Integer(opFlags),
+                new Integer(expectedResult) });
+      }
+    }
+  }
+
+  protected AuthzCredentialGenerator getXmlAuthzGenerator(){
+    AuthzCredentialGenerator authzGen = new XmlAuthzCredentialGenerator();
+    CredentialGenerator cGen = new DummyCredentialGenerator();
+    cGen.init();
+    authzGen.init(cGen);
+    return authzGen;
+  }
+
+  protected List getDummyGeneratorCombos() {
+    List generators = new ArrayList();
+    Iterator authzCodeIter = AuthzCredentialGenerator.ClassCode.getAll()
+            .iterator();
+    while (authzCodeIter.hasNext()) {
+      ClassCode authzClassCode = (ClassCode) authzCodeIter.next();
+      AuthzCredentialGenerator authzGen = AuthzCredentialGenerator
+              .create(authzClassCode);
+      if (authzGen != null) {
+        CredentialGenerator cGen = new DummyCredentialGenerator();
+        cGen.init();
+        if (authzGen.init(cGen)) {
+          generators.add(authzGen);
+        }
+      }
+    }
+
+    assertTrue(generators.size() > 0);
+    return generators;
+  }
+
+
+  protected void runOpsWithFailover(OperationWithAction[] opCodes,
+      String testName) {
+      AuthzCredentialGenerator gen = getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+      TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(gen);
+
+      getLogWriter().info(testName + ": Using authinit: " + authInit);
+      getLogWriter().info(testName + ": Using authenticator: " + authenticator);
+      getLogWriter().info(testName + ": Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      // Get ports for the servers
+      Keeper port1Keeper = AvailablePort.getRandomAvailablePortKeeper(AvailablePort.SOCKET);
+      Keeper port2Keeper = AvailablePort.getRandomAvailablePortKeeper(AvailablePort.SOCKET);
+      int port1 = port1Keeper.getPort();
+      int port2 = port2Keeper.getPort();
+
+      // Perform all the ops on the clients
+      List opBlock = new ArrayList();
+      Random rnd = new Random();
+      for (int opNum = 0; opNum < opCodes.length; ++opNum) {
+        // Start client with valid credentials as specified in
+        // OperationWithAction
+        OperationWithAction currentOp = opCodes[opNum];
+        if (currentOp.equals(OperationWithAction.OPBLOCK_END)
+            || currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+          // End of current operation block; execute all the operations
+          // on the servers with/without failover
+          if (opBlock.size() > 0) {
+            port1Keeper.release();
+            // Start the first server and execute the operation block
+            server1.invoke(ClientAuthorizationTestBase.class,
+                "createCacheServer", new Object[] {
+                    SecurityTestUtil.getLocatorPort(), port1, serverProps,
+                    javaProps });
+            server2.invoke(SecurityTestUtil.class, "closeCache");
+            executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
+                extraAuthzProps, tgen, rnd);
+            if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+              // Failover to the second server and run the block again
+              port2Keeper.release();
+              server2.invoke(ClientAuthorizationTestBase.class,
+                  "createCacheServer", new Object[] {
+                      SecurityTestUtil.getLocatorPort(), port2, serverProps,
+                      javaProps });
+              server1.invoke(SecurityTestUtil.class, "closeCache");
+              executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
+                  extraAuthzProps, tgen, rnd);
+            }
+            opBlock.clear();
+          }
+        }
+        else {
+          currentOp.setOpNum(opNum);
+          opBlock.add(currentOp);
+        }
+      }
+  }
+
+  /**
+   * Implements the {@link CqListener} interface and counts the number of
+   * different operations and also queues up the received updates to precise
+   * checking of each update.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static class AuthzCqListener implements CqListener {
+
+    private List eventList;
+
+    private int numCreates;
+
+    private int numUpdates;
+
+    private int numDestroys;
+
+    private int numOtherOps;
+
+    private int numErrors;
+
+    public AuthzCqListener() {
+      this.eventList = new ArrayList();
+      reset();
+    }
+
+    public void reset() {
+      this.eventList.clear();
+      this.numCreates = 0;
+      this.numUpdates = 0;
+      this.numErrors = 0;
+    }
+
+    public void onEvent(CqEvent aCqEvent) {
+      Operation op = aCqEvent.getBaseOperation();
+      if (op.isCreate()) {
+        ++this.numCreates;
+      }
+      else if (op.isUpdate()) {
+        ++this.numUpdates;
+      }
+      else if (op.isDestroy()) {
+        ++this.numDestroys;
+      }
+      else {
+        ++this.numOtherOps;
+      }
+      eventList.add(aCqEvent);
+    }
+
+    public void onError(CqEvent aCqEvent) {
+      ++this.numErrors;
+    }
+
+    public void close() {
+      this.eventList.clear();
+    }
+
+    public int getNumCreates() {
+      return this.numCreates;
+    }
+
+    public int getNumUpdates() {
+      return this.numUpdates;
+    }
+
+    public int getNumDestroys() {
+      return this.numDestroys;
+    }
+
+    public int getNumOtherOps() {
+      return this.numOtherOps;
+    }
+
+    public int getNumErrors() {
+      return this.numErrors;
+    }
+
+    public void checkPuts(String[] vals, int[] indices) {
+      for (int indexIndex = 0; indexIndex < indices.length; ++indexIndex) {
+        int index = indices[indexIndex];
+        Iterator eventIter = this.eventList.iterator();
+        boolean foundKey = false;
+        while (eventIter.hasNext()) {
+          CqEvent event = (CqEvent)eventIter.next();
+          if (SecurityTestUtil.keys[index].equals(event.getKey())) {
+            assertEquals(vals[index], event.getNewValue());
+            foundKey = true;
+            break;
+          }
+        }
+        assertTrue(foundKey);
+      }
+    }
+  }
+
+  /**
+   * This class specifies flags that can be used to alter the behaviour of
+   * operations being performed by the <code>doOp</code> function.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static class OpFlags {
+
+    /**
+     * Default behaviour.
+     */
+    public static final int NONE = 0x0;
+
+    /**
+     * Check that the operation should fail.
+     */
+    public static final int CHECK_FAIL = 0x1;
+
+    /**
+     * Check that the operation should throw <code>NotAuthorizedException</code>.
+     */
+    public static final int CHECK_NOTAUTHZ = 0x2;
+
+    /**
+     * Check that the region should not be available.
+     */
+    public static final int CHECK_NOREGION = 0x4;
+
+    /**
+     * Check that the operation should throw an exception other than the
+     * <code>NotAuthorizedException</code>.
+     */
+    public static final int CHECK_EXCEPTION = 0x8;
+
+    /**
+     * Check for nvalues[] instead of values[].
+     */
+    public static final int USE_NEWVAL = 0x10;
+
+    /**
+     * Register all keys. For GET operations indicates using getAll().
+     */
+    public static final int USE_ALL_KEYS = 0x20;
+
+    /**
+     * Register a regular expression.
+     */
+    public static final int USE_REGEX = 0x40;
+
+    /**
+     * Register a list of keys.
+     */
+    public static final int USE_LIST = 0x80;
+
+    /**
+     * Perform the local version of the operation.
+     */
+    public static final int LOCAL_OP = 0x100;
+
+    /**
+     * Check that the key for the operation should not be present.
+     */
+    public static final int CHECK_NOKEY = 0x200;
+
+    /**
+     * Use the sub-region for performing the operation.
+     */
+    public static final int USE_SUBREGION = 0x400;
+
+    /**
+     * Do not try to create the sub-region.
+     */
+    public static final int NO_CREATE_SUBREGION = 0x800;
+
+    /**
+     * Do not re-connect using new credentials rather use the previous
+     * connection.
+     */
+    public static final int USE_OLDCONN = 0x1000;
+
+    /**
+     * Do the connection with unauthorized credentials but do not check that the
+     * operation throws <code>NotAuthorizedException</code>.
+     */
+    public static final int USE_NOTAUTHZ = 0x2000;
+
+    /**
+     * Enable {@link DynamicRegionFactory} on the client.
+     */
+    public static final int ENABLE_DRF = 0x4000;
+
+    /**
+     * Use the {@link InterestResultPolicy#NONE} for register interest.
+     */
+    public static final int REGISTER_POLICY_NONE = 0x8000;
+    
+    /**
+     * Use the {@link LocalRegion#getEntry} under transaction.
+     */
+    public static final int USE_GET_ENTRY_IN_TX = 0x10000;
+    
+    static public String description(int f) {
+      StringBuffer sb = new StringBuffer();
+      sb.append("[");
+      if ((f & CHECK_FAIL) != 0) {
+        sb.append("CHECK_FAIL,");
+      }
+      if ((f & CHECK_NOTAUTHZ) != 0) {
+        sb.append("CHECK_NOTAUTHZ,");
+      }
+      if ((f & CHECK_NOREGION) != 0) {
+        sb.append("CHECK_NOREGION,");
+      }
+      if ((f & CHECK_EXCEPTION) != 0) {
+        sb.append("CHECK_EXCEPTION,");
+      }
+      if ((f & USE_NEWVAL) != 0) {
+        sb.append("USE_NEWVAL,");
+      }
+      if ((f & USE_ALL_KEYS) != 0) {
+        sb.append("USE_ALL_KEYS,");
+      }
+      if ((f & USE_REGEX) != 0) {
+        sb.append("USE_REGEX,");
+      }
+      if ((f & USE_LIST) != 0) {
+        sb.append("USE_LIST,");
+      }
+      if ((f & LOCAL_OP) != 0) {
+        sb.append("LOCAL_OP,");
+      }
+      if ((f & CHECK_NOKEY) != 0) {
+        sb.append("CHECK_NOKEY,");
+      }
+      if ((f & USE_SUBREGION) != 0) {
+        sb.append("USE_SUBREGION,");
+      }
+      if ((f & NO_CREATE_SUBREGION) != 0) {
+        sb.append("NO_CREATE_SUBREGION,");
+      }
+      if ((f & USE_OLDCONN) != 0) {
+        sb.append("USE_OLDCONN,");
+      }
+      if ((f & USE_NOTAUTHZ) != 0) {
+        sb.append("USE_NOTAUTHZ");
+      }
+      if ((f & ENABLE_DRF) != 0) {
+        sb.append("ENABLE_DRF,");
+      }
+      if ((f & REGISTER_POLICY_NONE) != 0) {
+        sb.append("REGISTER_POLICY_NONE,");
+      }
+      sb.append("]");
+      return sb.toString();
+    }
+  }
+
+  /**
+   * This class encapsulates an {@link OperationCode} with associated flags, the
+   * client to perform the operation, and the number of operations to perform.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static class OperationWithAction {
+
+    /**
+     * The operation to be performed.
+     */
+    private OperationCode opCode;
+
+    /**
+     * The operation for which authorized or unauthorized credentials have to be
+     * generated. This is the same as {@link #opCode} when not specified.
+     */
+    private OperationCode authzOpCode;
+
+    /**
+     * The client number on which the operation has to be performed.
+     */
+    private int clientNum;
+
+    /**
+     * Bitwise or'd {@link OpFlags} integer to change/specify the behaviour of
+     * the operations.
+     */
+    private int flags;
+
+    /**
+     * Indices of the keys array to be used for operations.
+     */
+    private int[] indices;
+
+    /**
+     * An index for the operation used for logging.
+     */
+    private int opNum;
+
+    /**
+     * Indicates end of an operation block which can be used for testing with
+     * failover
+     */
+    public static final OperationWithAction OPBLOCK_END = new OperationWithAction(
+        null, 4);
+
+    /**
+     * Indicates end of an operation block which should not be used for testing
+     * with failover
+     */
+    public static final OperationWithAction OPBLOCK_NO_FAILOVER = new OperationWithAction(
+        null, 5);
+
+    private void setIndices(int numOps) {
+
+      this.indices = new int[numOps];
+      for (int index = 0; index < numOps; ++index) {
+        this.indices[index] = index;
+      }
+    }
+
+    public OperationWithAction(OperationCode opCode) {
+
+      this.opCode = opCode;
+      this.authzOpCode = opCode;
+      this.clientNum = 1;
+      this.flags = OpFlags.NONE;
+      setIndices(4);
+      this.opNum = 0;
+    }
+
+    public OperationWithAction(OperationCode opCode, int clientNum) {
+
+      this.opCode = opCode;
+      this.authzOpCode = opCode;
+      this.clientNum = clientNum;
+      this.flags = OpFlags.NONE;
+      setIndices(4);
+      this.opNum = 0;
+    }
+
+    public OperationWithAction(OperationCode opCode, int clientNum, int flags,
+        int numOps) {
+
+      this.opCode = opCode;
+      this.authzOpCode = opCode;
+      this.clientNum = clientNum;
+      this.flags = flags;
+      setIndices(numOps);
+      this.opNum = 0;
+    }
+
+    public OperationWithAction(OperationCode opCode,
+        OperationCode deniedOpCode, int clientNum, int flags, int numOps) {
+
+      this.opCode = opCode;
+      this.authzOpCode = deniedOpCode;
+      this.clientNum = clientNum;
+      this.flags = flags;
+      setIndices(numOps);
+      this.opNum = 0;
+    }
+
+    public OperationWithAction(OperationCode opCode, int clientNum, int flags,
+        int[] indices) {
+
+      this.opCode = opCode;
+      this.authzOpCode = opCode;
+      this.clientNum = clientNum;
+      this.flags = flags;
+      this.indices = indices;
+      this.opNum = 0;
+    }
+
+    public OperationWithAction(OperationCode opCode,
+        OperationCode deniedOpCode, int clientNum, int flags, int[] indices) {
+
+      this.opCode = opCode;
+      this.authzOpCode = deniedOpCode;
+      this.clientNum = clientNum;
+      this.flags = flags;
+      this.indices = indices;
+      this.opNum = 0;
+    }
+
+    public OperationCode getOperationCode() {
+      return this.opCode;
+    }
+
+    public OperationCode getAuthzOperationCode() {
+      return this.authzOpCode;
+    }
+
+    public int getClientNum() {
+      return this.clientNum;
+    }
+
+    public int getFlags() {
+      return this.flags;
+    }
+
+    public int[] getIndices() {
+      return this.indices;
+    }
+
+    public int getOpNum() {
+      return this.opNum;
+    }
+
+    public void setOpNum(int opNum) {
+      this.opNum = opNum;
+    }
+
+    public String toString() {
+      return "opCode:" + this.opCode + ",authOpCode:" + this.authzOpCode
+          + ",clientNum:" + this.clientNum + ",flags:" + this.flags
+          + ",numOps:" + this.indices.length + ",indices:"
+          + indicesToString(this.indices);
+    }
+  }
+
+  /**
+   * Simple interface to generate credentials with authorization based on key
+   * indices also. This is utilized by the post-operation authorization tests
+   * where authorization is based on key indices.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public interface TestCredentialGenerator {
+
+    /**
+     * Get allowed credentials for the given set of operations in the given
+     * regions and indices of keys in the <code>keys</code> array
+     */
+    public Properties getAllowedCredentials(OperationCode[] opCodes,
+        String[] regionNames, int[] keyIndices, int num);
+
+    /**
+     * Get disallowed credentials for the given set of operations in the given
+     * regions and indices of keys in the <code>keys</code> array
+     */
+    public Properties getDisallowedCredentials(OperationCode[] opCodes,
+        String[] regionNames, int[] keyIndices, int num);
+
+    /**
+     * Get the {@link CredentialGenerator} if any.
+     */
+    public CredentialGenerator getCredentialGenerator();
+  }
+
+  /**
+   * Contains a {@link AuthzCredentialGenerator} and implements the
+   * {@link TestCredentialGenerator} interface.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  protected static class TestAuthzCredentialGenerator implements
+      TestCredentialGenerator {
+
+    private AuthzCredentialGenerator authzGen;
+
+    public TestAuthzCredentialGenerator(AuthzCredentialGenerator authzGen) {
+      this.authzGen = authzGen;
+    }
+
+    public Properties getAllowedCredentials(OperationCode[] opCodes,
+        String[] regionNames, int[] keyIndices, int num) {
+
+      return this.authzGen.getAllowedCredentials(opCodes, regionNames, num);
+    }
+
+    public Properties getDisallowedCredentials(OperationCode[] opCodes,
+        String[] regionNames, int[] keyIndices, int num) {
+
+      return this.authzGen.getDisallowedCredentials(opCodes, regionNames, num);
+    }
+
+    public CredentialGenerator getCredentialGenerator() {
+
+      return authzGen.getCredentialGenerator();
+    }
+  }
+
+}


[5/7] incubator-geode git commit: GEM-164: move the security tests in gemfire-test module inside the com.gemstone.gemfire.security packages to the open side.

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
new file mode 100644
index 0000000..ceeb989
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
@@ -0,0 +1,537 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.Iterator;
+import java.util.Properties;
+
+import templates.security.AuthzCredentialGenerator;
+import templates.security.CredentialGenerator;
+
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.execute.Function;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.internal.AvailablePort;
+import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.cache.execute.PRClientServerTestBase;
+import com.gemstone.gemfire.internal.cache.functions.TestFunction;
+
+import dunit.Host;
+
+public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestBase {
+
+  /** constructor */
+  public ClientMultiUserAuthzDUnitTest(String name) {
+    super(name);
+  }
+
+  public void setUp() throws Exception {
+
+    super.setUp();
+    final Host host = Host.getHost(0);
+    server1 = host.getVM(0);
+    server2 = host.getVM(1);
+    client1 = host.getVM(2);
+    client2 = host.getVM(3);
+
+    server1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    server2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    client2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+    SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+  }
+
+  // Tests with one user authorized to do puts/gets/containsKey/destroys and
+  // another not authorized for the same.
+  public void testOps1() throws Exception {
+    Iterator iter = getDummyGeneratorCombos().iterator();
+    while (iter.hasNext()) {
+      AuthzCredentialGenerator gen = (AuthzCredentialGenerator)iter.next();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testOps1: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testOps1: Using authenticator: " + authenticator);
+      getLogWriter().info("testOps1: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+      Integer port2 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+      server1.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] {SecurityTestUtil.getLocatorPort(), port1, serverProps,
+              javaProps});
+      server2.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] {SecurityTestUtil.getLocatorPort(), port2, serverProps,
+              javaProps});
+
+      if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
+          OperationCode.PUT, OperationCode.PUT}, new OperationCode[] {
+          OperationCode.GET, OperationCode.GET}, javaProps, authInit, port1,
+          port2)) {
+        continue;
+      }
+      verifyPutsGets();
+
+      if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
+          OperationCode.PUT, OperationCode.CONTAINS_KEY}, new OperationCode[] {
+          OperationCode.DESTROY, OperationCode.DESTROY},
+          javaProps, authInit, port1, port2)) {
+        continue;
+      }
+      verifyContainsKeyDestroys();
+
+      if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
+          OperationCode.PUT, OperationCode.CONTAINS_KEY}, new OperationCode[] {
+          OperationCode.INVALIDATE, OperationCode.INVALIDATE},
+          javaProps, authInit, port1, port2)) {
+        continue;
+      }
+      verifyContainsKeyInvalidates();
+
+      if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
+          OperationCode.GET, OperationCode.GET}, new OperationCode[] {
+          OperationCode.REGION_DESTROY, OperationCode.REGION_DESTROY},
+          javaProps, authInit, port1, port2)) {
+        continue;
+      }
+      verifyGetAllInTX();
+      verifyGetAllRegionDestroys();
+    }
+  }
+
+  private boolean prepareClientsForOps(AuthzCredentialGenerator gen,
+      CredentialGenerator cGen, OperationCode[] client1OpCodes,
+      OperationCode[] client2OpCodes, Properties javaProps, String authInit,
+      Integer port1, Integer port2) {
+    return prepareClientsForOps(gen, cGen, client1OpCodes, client2OpCodes,
+        javaProps, authInit, port1, port2, Boolean.TRUE /*
+                                                         * both clients in
+                                                         * multiuser mode
+                                                         */, Boolean.FALSE /* unused */);
+  }
+
+  private boolean prepareClientsForOps(AuthzCredentialGenerator gen,
+      CredentialGenerator cGen, OperationCode[] client1OpCodes,
+      OperationCode[] client2OpCodes, Properties javaProps, String authInit,
+      Integer port1, Integer port2, Boolean bothClientsInMultiuserMode,
+      Boolean allowOp) {
+    // Start client1 with valid/invalid client1OpCodes credentials
+    Properties[] client1Credentials = new Properties[] {
+        gen.getAllowedCredentials(client1OpCodes, new String[] {regionName}, 1),
+        gen.getDisallowedCredentials(new OperationCode[] {client1OpCodes[1]},
+            new String[] {regionName}, 1)};
+    if (client1Credentials[0] == null || client1Credentials[0].size() == 0) {
+      getLogWriter().info(
+          "testOps1: Unable to obtain valid credentials with "
+              + client1OpCodes[0].toString()
+              + " permission; skipping this combination.");
+      return false;
+    }
+    if (client1Credentials[1] == null || client1Credentials[1].size() == 0) {
+      getLogWriter().info(
+          "testOps1: Unable to obtain valid credentials with no "
+              + client1OpCodes[0].toString()
+              + " permission; skipping this combination.");
+      return false;
+    }
+    javaProps = cGen.getJavaProperties();
+    getLogWriter().info(
+        "testOps1: For first client credentials: " + client1Credentials[0]
+            + "\n" + client1Credentials[1]);
+    client1.invoke(SecurityTestUtil.class, "createCacheClientForMultiUserMode",
+        new Object[] {Integer.valueOf(2), authInit, client1Credentials,
+            javaProps, new Integer[] {port1, port2}, null, Boolean.FALSE,
+            SecurityTestUtil.NO_EXCEPTION});
+
+    // Start client2 with valid/invalid client2OpCodes credentials
+    Properties[] client2Credentials = new Properties[] {
+        gen.getAllowedCredentials(client2OpCodes,
+            new String[] {regionName}, 2),
+        gen.getDisallowedCredentials(client2OpCodes,
+            new String[] {regionName}, 9)};
+    if (client2Credentials[0] == null || client2Credentials[0].size() == 0) {
+      getLogWriter().info(
+          "testOps1: Unable to obtain valid credentials with "
+              + client2OpCodes[0].toString()
+              + " permission; skipping this combination.");
+      return false;
+    }
+    if (client2Credentials[1] == null || client2Credentials[1].size() == 0) {
+      getLogWriter().info(
+          "testOps1: Unable to obtain valid credentials with no "
+              + client2OpCodes[0].toString()
+              + " permission; skipping this combination.");
+      return false;
+    }
+    javaProps = cGen.getJavaProperties();
+    getLogWriter().info(
+        "testOps1: For second client credentials: " + client2Credentials[0]
+            + "\n" + client2Credentials[1]);
+    if (bothClientsInMultiuserMode) {
+      client2.invoke(SecurityTestUtil.class,
+          "createCacheClientForMultiUserMode", new Object[] {
+              Integer.valueOf(2), authInit, client2Credentials, javaProps,
+              new Integer[] {port1, port2}, null, Boolean.FALSE,
+              SecurityTestUtil.NO_EXCEPTION});
+    } else {
+      int credentialsIndex = allowOp ? 0 : 1;
+      client2.invoke(SecurityTestUtil.class, "createCacheClient", new Object[] {
+          authInit, client2Credentials[credentialsIndex], javaProps,
+          new Integer[] {port1, port2}, null, Boolean.FALSE, "false",
+          SecurityTestUtil.NO_EXCEPTION});
+    }
+    return true;
+  }
+
+  private void verifyPutsGets() throws Exception {
+    verifyPutsGets(true, false /*unused */);
+  }
+
+  private void verifyPutsGets(Boolean isMultiuser, Boolean opAllowed)
+      throws Exception {
+    // Perform some put operations from client1
+    client1.invoke(SecurityTestUtil.class, "doMultiUserPuts", new Object[] {
+        Integer.valueOf(2),
+        Integer.valueOf(2),
+        new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+            SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+
+    // Verify that the gets succeed/fail
+    if (isMultiuser) {
+    client2.invoke(SecurityTestUtil.class, "doMultiUserGets", new Object[] {
+        Integer.valueOf(2),
+        Integer.valueOf(2),
+        new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+            SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+    } else {
+      int expectedResult = (opAllowed) ? SecurityTestUtil.NO_EXCEPTION
+          : SecurityTestUtil.NOTAUTHZ_EXCEPTION;
+      client2.invoke(SecurityTestUtil.class, "doMultiUserGets", new Object[] {
+          Integer.valueOf(1), Integer.valueOf(1),
+          new Integer[] {expectedResult}});
+    }
+  }
+
+  private void verifyContainsKeyDestroys() throws Exception {
+    verifyContainsKeyDestroys(true, false /* unused */);
+  }
+
+  private void verifyContainsKeyDestroys(Boolean isMultiuser, Boolean opAllowed)
+      throws Exception {
+    // Do puts before verifying containsKey
+    client1.invoke(SecurityTestUtil.class, "doMultiUserPuts", new Object[] {
+        Integer.valueOf(2),
+        Integer.valueOf(2),
+        new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+            SecurityTestUtil.NO_EXCEPTION}});
+    client1.invoke(SecurityTestUtil.class, "doMultiUserContainsKeys",
+        new Object[] {
+            Integer.valueOf(1),
+            Integer.valueOf(2),
+            new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                SecurityTestUtil.NOTAUTHZ_EXCEPTION},
+            new Boolean[] {Boolean.TRUE, Boolean.FALSE}});
+
+    // Verify that the destroys succeed/fail
+    if (isMultiuser) {
+      client2.invoke(SecurityTestUtil.class, "doMultiUserDestroys",
+          new Object[] {
+              Integer.valueOf(2),
+              Integer.valueOf(2),
+              new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                  SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+    } else {
+      int expectedResult = (opAllowed) ? SecurityTestUtil.NO_EXCEPTION
+          : SecurityTestUtil.NOTAUTHZ_EXCEPTION;
+      client2.invoke(SecurityTestUtil.class, "doMultiUserDestroys",
+          new Object[] {Integer.valueOf(1), Integer.valueOf(1),
+              new Integer[] {expectedResult}});
+    }
+  }
+
+  private void verifyContainsKeyInvalidates() throws Exception {
+    verifyContainsKeyInvalidates(true, false /* unused */);
+  }
+
+  private void verifyContainsKeyInvalidates(Boolean isMultiuser, Boolean opAllowed)
+      throws Exception {
+    // Do puts before verifying containsKey
+    client1.invoke(SecurityTestUtil.class, "doMultiUserPuts", new Object[] {
+        Integer.valueOf(2),
+        Integer.valueOf(2),
+        new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+            SecurityTestUtil.NO_EXCEPTION}});
+    client1.invoke(SecurityTestUtil.class, "doMultiUserContainsKeys",
+        new Object[] {
+            Integer.valueOf(1),
+            Integer.valueOf(2),
+            new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                SecurityTestUtil.NOTAUTHZ_EXCEPTION},
+            new Boolean[] {Boolean.TRUE, Boolean.FALSE}});
+
+    // Verify that the invalidates succeed/fail
+    if (isMultiuser) {
+      client2.invoke(SecurityTestUtil.class, "doMultiUserInvalidates",
+          new Object[] {
+              Integer.valueOf(2),
+              Integer.valueOf(2),
+              new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                  SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+    } else {
+      int expectedResult = (opAllowed) ? SecurityTestUtil.NO_EXCEPTION
+          : SecurityTestUtil.NOTAUTHZ_EXCEPTION;
+      client2.invoke(SecurityTestUtil.class, "doMultiUserInvalidates",
+          new Object[] {Integer.valueOf(1), Integer.valueOf(1),
+              new Integer[] {expectedResult}});
+    }
+  }
+
+  private void verifyGetAllInTX() {
+    server1.invoke(ClientMultiUserAuthzDUnitTest.class, "doPuts");
+    client1.invoke(SecurityTestUtil.class, "doMultiUserGetAll", new Object[] {
+      Integer.valueOf(2),
+      new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+          SecurityTestUtil.NOTAUTHZ_EXCEPTION}, Boolean.TRUE/*use TX*/});
+  }
+
+  private void verifyGetAllRegionDestroys() {
+    server1.invoke(ClientMultiUserAuthzDUnitTest.class, "doPuts");
+    client1.invoke(SecurityTestUtil.class, "doMultiUserGetAll", new Object[] {
+      Integer.valueOf(2),
+      new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+          SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+
+    // Verify that the region destroys succeed/fail
+    client2.invoke(SecurityTestUtil.class, "doMultiUserRegionDestroys",
+        new Object[] {
+            Integer.valueOf(2),
+            new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+  }
+  
+  public static void doPuts() {
+    Region region = GemFireCacheImpl.getInstance().getRegion(SecurityTestUtil.regionName);
+    region.put("key1", "value1");
+    region.put("key2", "value2");
+  }
+
+  // Test query/function execute
+  public void testOps2() throws Exception {
+      AuthzCredentialGenerator gen = getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testOps2: Using authinit: " + authInit);
+      getLogWriter().info("testOps2: Using authenticator: " + authenticator);
+      getLogWriter().info("testOps2: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+      Integer port2 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+      server1.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] {SecurityTestUtil.getLocatorPort(), port1, serverProps,
+              javaProps});
+      server2.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] {SecurityTestUtil.getLocatorPort(), port2, serverProps,
+              javaProps});
+
+      // Start client1 with valid/invalid QUERY credentials
+      Properties[] client1Credentials = new Properties[] {
+          gen.getAllowedCredentials(
+                  new OperationCode[] {OperationCode.PUT, OperationCode.QUERY},
+                  new String[] {regionName},
+                  1),
+          gen.getDisallowedCredentials(
+                  new OperationCode[] {OperationCode.PUT, OperationCode.QUERY},
+                  new String[] {regionName},
+                  1)
+      };
+
+      javaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testOps2: For first client credentials: " + client1Credentials[0]
+              + "\n" + client1Credentials[1]);
+      client1.invoke(SecurityTestUtil.class,
+          "createCacheClientForMultiUserMode", new Object[] {
+              Integer.valueOf(2), authInit, client1Credentials, javaProps,
+              new Integer[] {port1, port2}, null, Boolean.FALSE,
+              SecurityTestUtil.NO_EXCEPTION});
+
+      // Start client2 with valid/invalid EXECUTE_FUNCTION credentials
+      Properties[] client2Credentials = new Properties[] {
+          gen.getAllowedCredentials(new OperationCode[] {OperationCode.EXECUTE_FUNCTION},
+              new String[] {regionName}, 2),
+          gen.getDisallowedCredentials(new OperationCode[] {OperationCode.EXECUTE_FUNCTION},
+              new String[] {regionName}, 9)};
+
+      javaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testOps2: For second client credentials: " + client2Credentials[0]
+              + "\n" + client2Credentials[1]);
+      client2.invoke(SecurityTestUtil.class,
+          "createCacheClientForMultiUserMode", new Object[] {
+              Integer.valueOf(2), authInit, client2Credentials, javaProps,
+              new Integer[] {port1, port2}, null, Boolean.FALSE,
+              SecurityTestUtil.NO_EXCEPTION});
+      Function function = new TestFunction(true,TestFunction.TEST_FUNCTION1);
+      server1.invoke(PRClientServerTestBase.class,
+          "registerFunction", new Object []{function});
+      
+      server2.invoke(PRClientServerTestBase.class,
+          "registerFunction", new Object []{function});
+      
+      // Perform some put operations before verifying queries
+      client1.invoke(SecurityTestUtil.class, "doMultiUserPuts", new Object[] {
+          Integer.valueOf(4),
+          Integer.valueOf(2),
+          new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+              SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+      client1.invoke(SecurityTestUtil.class, "doMultiUserQueries",
+          new Object[] {
+              Integer.valueOf(2),
+              new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                  SecurityTestUtil.NOTAUTHZ_EXCEPTION}, Integer.valueOf(4)});
+      client1.invoke(SecurityTestUtil.class, "doMultiUserQueryExecute",
+          new Object[] {
+              Integer.valueOf(2),
+              new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                  SecurityTestUtil.NOTAUTHZ_EXCEPTION}, Integer.valueOf(4)});
+
+      // Verify that the FE succeeds/fails
+      client2.invoke(SecurityTestUtil.class, "doMultiUserFE", new Object[] {
+          Integer.valueOf(2),
+          function,
+          new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+              SecurityTestUtil.NOTAUTHZ_EXCEPTION}, new Object[] {null, null},
+          Boolean.FALSE});
+
+      // Failover
+      server1.invoke(SecurityTestUtil.class, "closeCache");
+      Thread.sleep(2000);
+
+      client1.invoke(SecurityTestUtil.class, "doMultiUserPuts", new Object[] {
+          Integer.valueOf(4),
+          Integer.valueOf(2),
+          new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+              SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+
+      client1.invoke(SecurityTestUtil.class, "doMultiUserQueries",
+          new Object[] {
+              Integer.valueOf(2),
+              new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                  SecurityTestUtil.NOTAUTHZ_EXCEPTION}, Integer.valueOf(4)});
+      client1.invoke(SecurityTestUtil.class, "doMultiUserQueryExecute",
+          new Object[] {
+              Integer.valueOf(2),
+              new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+                  SecurityTestUtil.NOTAUTHZ_EXCEPTION}, Integer.valueOf(4)});
+
+      // Verify that the FE succeeds/fails
+      client2.invoke(SecurityTestUtil.class, "doMultiUserFE", new Object[] {
+          Integer.valueOf(2),
+          function,
+          new Integer[] {SecurityTestUtil.NO_EXCEPTION,
+              SecurityTestUtil.NOTAUTHZ_EXCEPTION}, new Object[] {null, null},
+          Boolean.TRUE});
+
+
+  }
+
+  public void testOpsWithClientsInDifferentModes() throws Exception {
+    Iterator iter = getDummyGeneratorCombos().iterator();
+    while (iter.hasNext()) {
+      AuthzCredentialGenerator gen = (AuthzCredentialGenerator)iter.next();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testOpsWithClientsInDifferentModes: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testOpsWithClientsInDifferentModes: Using authenticator: " + authenticator);
+      getLogWriter().info("testOpsWithClientsInDifferentModes: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+      Integer port2 = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+      server1.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] {SecurityTestUtil.getLocatorPort(), port1, serverProps,
+              javaProps});
+      server2.invoke(ClientAuthorizationTestBase.class, "createCacheServer",
+          new Object[] {SecurityTestUtil.getLocatorPort(), port2, serverProps,
+              javaProps});
+
+      if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
+          OperationCode.PUT, OperationCode.PUT}, new OperationCode[] {
+          OperationCode.GET, OperationCode.GET}, javaProps, authInit, port1,
+          port2, Boolean.FALSE, Boolean.TRUE)) {
+        continue;
+      }
+      verifyPutsGets(false, true);
+
+      if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
+          OperationCode.PUT, OperationCode.CONTAINS_KEY}, new OperationCode[] {
+          OperationCode.DESTROY, OperationCode.DESTROY},
+          javaProps, authInit, port1, port2, Boolean.FALSE, Boolean.FALSE)) {
+        continue;
+      }
+      verifyContainsKeyDestroys(false, false);
+    }
+  }
+
+  // End Region: Tests
+
+  public void tearDown2() throws Exception {
+
+    super.tearDown2();
+    // close the clients first
+    client1.invoke(SecurityTestUtil.class, "closeCache");
+    client2.invoke(SecurityTestUtil.class, "closeCache");
+    SecurityTestUtil.closeCache();
+    // then close the servers
+    server1.invoke(SecurityTestUtil.class, "closeCache");
+    server2.invoke(SecurityTestUtil.class, "closeCache");
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
new file mode 100644
index 0000000..16573c2
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
@@ -0,0 +1,336 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.Properties;
+
+import templates.security.AuthzCredentialGenerator;
+import templates.security.CredentialGenerator;
+
+import com.gemstone.gemfire.DeltaTestImpl;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.client.NoAvailableServersException;
+import com.gemstone.gemfire.cache.client.ServerConnectivityException;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.internal.cache.PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1;
+
+import dunit.Host;
+
+/**
+ * @since 6.1
+ */
+public class DeltaClientAuthorizationDUnitTest extends
+    ClientAuthorizationTestBase {
+
+  protected static final DeltaTestImpl[] deltas = new DeltaTestImpl[8];
+
+  static {
+    for (int i = 0; i < 8; i++) {
+      deltas[i] = new DeltaTestImpl(0, "0", new Double(0), new byte[0],
+          new TestObject1("0", 0));
+    }
+    deltas[1].setIntVar(5);
+    deltas[2].setIntVar(5);
+    deltas[3].setIntVar(5);
+    deltas[4].setIntVar(5);
+    deltas[5].setIntVar(5);
+    deltas[6].setIntVar(5);
+    deltas[7].setIntVar(5);
+
+    deltas[2].resetDeltaStatus();
+    deltas[2].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
+    deltas[3].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
+    deltas[4].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
+    deltas[5].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
+    //deltas[6].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
+    //deltas[7].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
+
+    deltas[3].resetDeltaStatus();
+    deltas[3].setDoubleVar(new Double(5));
+    deltas[4].setDoubleVar(new Double(5));
+    deltas[5].setDoubleVar(new Double(5));
+    deltas[6].setDoubleVar(new Double(5));
+    deltas[7].setDoubleVar(new Double(5));
+
+    deltas[4].resetDeltaStatus();
+    deltas[4].setStr("str changed");
+    deltas[5].setStr("str changed");
+    deltas[6].setStr("str changed");
+    //deltas[7].setStr("str changed");
+
+    deltas[5].resetDeltaStatus();
+    deltas[5].setIntVar(100);
+    deltas[5].setTestObj(new TestObject1("CHANGED", 100));
+    deltas[6].setTestObj(new TestObject1("CHANGED", 100));
+    deltas[7].setTestObj(new TestObject1("CHANGED", 100));
+
+    deltas[6].resetDeltaStatus();
+    deltas[6].setByteArr(new byte[] { 1, 2, 3 });
+    deltas[7].setByteArr(new byte[] { 1, 2, 3 });
+
+    deltas[7].resetDeltaStatus();
+    deltas[7].setStr("delta string");
+    
+  }
+
+  /** constructor */
+  public DeltaClientAuthorizationDUnitTest(String name) {
+    super(name);
+  }
+
+  public void setUp() throws Exception {
+    super.setUp();
+    final Host host = Host.getHost(0);
+    server1 = host.getVM(0);
+    server2 = host.getVM(1);
+    client1 = host.getVM(2);
+    client2 = host.getVM(3);
+
+    server1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    server2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    client2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+    SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+  }
+
+  public void tearDown2() throws Exception {
+    super.tearDown2();
+    // close the clients first
+    client1.invoke(SecurityTestUtil.class, "closeCache");
+    client2.invoke(SecurityTestUtil.class, "closeCache");
+    SecurityTestUtil.closeCache();
+    // then close the servers
+    server1.invoke(SecurityTestUtil.class, "closeCache");
+    server2.invoke(SecurityTestUtil.class, "closeCache");
+  }
+
+  public void testAllowPutsGets() throws Exception {
+      AuthzCredentialGenerator gen = this.getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+
+      getLogWriter().info("testAllowPutsGets: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testAllowPutsGets: Using authenticator: " + authenticator);
+      getLogWriter().info("testAllowPutsGets: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, false,
+          extraAuthProps, extraAuthzProps);
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+      Integer port2 = ((Integer)server2.invoke(
+          ClientAuthorizationTestBase.class, "createCacheServer", new Object[] {
+              SecurityTestUtil.getLocatorPort(), serverProps, javaProps }));
+
+      // Start client1 with valid CREATE credentials
+      Properties createCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.PUT },
+          new String[] { regionName }, 1);
+      javaProps = cGen.getJavaProperties();
+      getLogWriter().info(
+          "testAllowPutsGets: For first client credentials: "
+              + createCredentials);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, createCredentials, javaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Start client2 with valid GET credentials
+      Properties getCredentials = gen.getAllowedCredentials(
+          new OperationCode[] { OperationCode.GET },
+          new String[] { regionName }, 2);
+      javaProps = cGen.getJavaProperties();
+      getLogWriter()
+          .info(
+              "testAllowPutsGets: For second client credentials: "
+                  + getCredentials);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, getCredentials, javaProps, port1, port2,
+              null, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(DeltaClientAuthorizationDUnitTest.class, "doPuts", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION), Boolean.FALSE });
+      Thread.sleep(5000);
+      assertTrue("Delta feature NOT used", (Boolean)client1.invoke(DeltaTestImpl.class, "toDeltaFeatureUsed"));
+
+      // Verify that the gets succeed
+      client2.invoke(DeltaClientAuthorizationDUnitTest.class, "doGets", new Object[] {
+          new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION), Boolean.FALSE  });
+  }
+
+  public static void doPuts(Integer num, Integer expectedResult,
+      boolean newVals) {
+
+    assertTrue(num.intValue() <= SecurityTestUtil.keys.length);
+    Region region = null;
+    try {
+      region = SecurityTestUtil.getCache().getRegion(regionName);
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing puts: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing puts", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      region.put(SecurityTestUtil.keys[index], deltas[0]);
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      try {
+        region.put(SecurityTestUtil.keys[index], deltas[index]);
+        if (expectedResult.intValue() != SecurityTestUtil.NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing puts");
+        }
+      }
+      catch (NoAvailableServersException ex) {
+        if (expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == SecurityTestUtil.NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        if ((expectedResult.intValue() == SecurityTestUtil.AUTHREQ_EXCEPTION)
+            && (ex.getCause() instanceof AuthenticationRequiredException)) {
+          getLogWriter().info(
+              "Got expected AuthenticationRequiredException when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        if ((expectedResult.intValue() == SecurityTestUtil.AUTHFAIL_EXCEPTION)
+            && (ex.getCause() instanceof AuthenticationFailedException)) {
+          getLogWriter().info(
+              "Got expected AuthenticationFailedException when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing puts: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing puts: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+    }
+  }
+
+  public static void doGets(Integer num, Integer expectedResult,
+      boolean newVals) {
+
+    assertTrue(num.intValue() <= SecurityTestUtil.keys.length);
+    Region region = null;
+    try {
+      region = SecurityTestUtil.getCache().getRegion(regionName);
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing gets: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing gets", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      Object value = null;
+      try {
+        try {
+          region.localInvalidate(SecurityTestUtil.keys[index]);
+        }
+        catch (Exception ex) {
+        }
+        value = region.get(SecurityTestUtil.keys[index]);
+        if (expectedResult.intValue() != SecurityTestUtil.NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing gets");
+        }
+      }
+      catch(NoAvailableServersException ex) {
+        if(expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing puts: "
+              + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == SecurityTestUtil.NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing gets: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing gets: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing gets", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing gets: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing gets", ex);
+        }
+      }
+      assertNotNull(value);
+      assertEquals(deltas[index], value);
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
new file mode 100644
index 0000000..7cfa23d
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
@@ -0,0 +1,541 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Random;
+
+import templates.security.AuthzCredentialGenerator;
+import templates.security.CredentialGenerator;
+
+import com.gemstone.gemfire.DeltaTestImpl;
+import com.gemstone.gemfire.cache.InterestResultPolicy;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.client.ServerConnectivityException;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.cache.query.CqException;
+import com.gemstone.gemfire.cache.query.QueryInvocationTargetException;
+import com.gemstone.gemfire.internal.AvailablePort;
+import com.gemstone.gemfire.internal.util.Callable;
+
+import dunit.Host;
+import dunit.VM;
+
+/**
+ * @since 6.1
+ * 
+ */
+public class DeltaClientPostAuthorizationDUnitTest extends
+    ClientAuthorizationTestBase {
+  private static final int PAUSE = 5 * 1000;
+
+  /** constructor */
+  public DeltaClientPostAuthorizationDUnitTest(String name) {
+    super(name);
+  }
+
+  public void setUp() throws Exception {
+
+    super.setUp();
+    final Host host = Host.getHost(0);
+    server1 = host.getVM(0);
+    server2 = host.getVM(1);
+    client1 = host.getVM(2);
+    client2 = host.getVM(3);
+
+    server1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    server2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    client2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+    SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+  }
+
+  public void tearDown2() throws Exception {
+
+    super.tearDown2();
+    // close the clients first
+    client1.invoke(SecurityTestUtil.class, "closeCache");
+    client2.invoke(SecurityTestUtil.class, "closeCache");
+    SecurityTestUtil.closeCache();
+    // then close the servers
+    server1.invoke(SecurityTestUtil.class, "closeCache");
+    server2.invoke(SecurityTestUtil.class, "closeCache");
+  }
+
+  public void testPutPostOpNotifications() throws Exception {
+    addExpectedException("Unexpected IOException");
+    addExpectedException("SocketException");
+
+    OperationWithAction[] allOps = {
+        // Test CREATE and verify with a GET
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.GET, 2, OpFlags.USE_REGEX
+                | OpFlags.REGISTER_POLICY_NONE, 8),
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.GET, 3, OpFlags.USE_REGEX
+                | OpFlags.REGISTER_POLICY_NONE | OpFlags.USE_NOTAUTHZ, 8),
+        new OperationWithAction(OperationCode.PUT),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP, 4),
+        new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP | OpFlags.CHECK_FAIL, 4),
+
+        // OPBLOCK_END indicates end of an operation block that needs to
+        // be executed on each server when doing failover
+        OperationWithAction.OPBLOCK_END,
+
+        // Test UPDATE and verify with a GET
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.GET, 2, OpFlags.USE_REGEX
+                | OpFlags.REGISTER_POLICY_NONE, 8),
+        new OperationWithAction(OperationCode.REGISTER_INTEREST,
+            OperationCode.GET, 3, OpFlags.USE_REGEX
+                | OpFlags.REGISTER_POLICY_NONE | OpFlags.USE_NOTAUTHZ, 8),
+        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
+            | OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP | OpFlags.USE_NEWVAL, 4),
+        new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
+            | OpFlags.LOCAL_OP | OpFlags.USE_NEWVAL | OpFlags.CHECK_FAIL, 4),
+
+        OperationWithAction.OPBLOCK_END };
+
+      AuthzCredentialGenerator gen = this.getXmlAuthzGenerator();
+      CredentialGenerator cGen = gen.getCredentialGenerator();
+      Properties extraAuthProps = cGen.getSystemProperties();
+      Properties javaProps = cGen.getJavaProperties();
+      Properties extraAuthzProps = gen.getSystemProperties();
+      String authenticator = cGen.getAuthenticator();
+      String authInit = cGen.getAuthInit();
+      String accessor = gen.getAuthorizationCallback();
+      TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(gen);
+
+      getLogWriter().info(
+          "testAllOpsNotifications: Using authinit: " + authInit);
+      getLogWriter().info(
+          "testAllOpsNotifications: Using authenticator: " + authenticator);
+      getLogWriter().info(
+          "testAllOpsNotifications: Using accessor: " + accessor);
+
+      // Start servers with all required properties
+      Properties serverProps = buildProperties(authenticator, accessor, true,
+          extraAuthProps, extraAuthzProps);
+      // Get ports for the servers
+      Integer port1 = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+      Integer port2 = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+
+      // Perform all the ops on the clients
+      List opBlock = new ArrayList();
+      Random rnd = new Random();
+      for (int opNum = 0; opNum < allOps.length; ++opNum) {
+        // Start client with valid credentials as specified in
+        // OperationWithAction
+        OperationWithAction currentOp = allOps[opNum];
+        if (currentOp.equals(OperationWithAction.OPBLOCK_END)
+            || currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+          // End of current operation block; execute all the operations
+          // on the servers with failover
+          if (opBlock.size() > 0) {
+            // Start the first server and execute the operation block
+            server1.invoke(ClientAuthorizationTestBase.class,
+                "createCacheServer", new Object[] {
+                    SecurityTestUtil.getLocatorPort(), port1, serverProps,
+                    javaProps });
+            server2.invoke(SecurityTestUtil.class, "closeCache");
+            executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
+                extraAuthzProps, tgen, rnd);
+            if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+              // Failover to the second server and run the block again
+              server2.invoke(ClientAuthorizationTestBase.class,
+                  "createCacheServer", new Object[] {
+                      SecurityTestUtil.getLocatorPort(), port2, serverProps,
+                      javaProps });
+              server1.invoke(SecurityTestUtil.class, "closeCache");
+              executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
+                  extraAuthzProps, tgen, rnd);
+            }
+            opBlock.clear();
+          }
+        }
+        else {
+          currentOp.setOpNum(opNum);
+          opBlock.add(currentOp);
+        }
+      }
+  }
+
+  protected void executeOpBlock(List opBlock, Integer port1, Integer port2,
+      String authInit, Properties extraAuthProps, Properties extraAuthzProps,
+      TestCredentialGenerator gen, Random rnd) {
+    Iterator opIter = opBlock.iterator();
+    while (opIter.hasNext()) {
+      // Start client with valid credentials as specified in
+      // OperationWithAction
+      OperationWithAction currentOp = (OperationWithAction)opIter.next();
+      OperationCode opCode = currentOp.getOperationCode();
+      int opFlags = currentOp.getFlags();
+      int clientNum = currentOp.getClientNum();
+      VM clientVM = null;
+      boolean useThisVM = false;
+      switch (clientNum) {
+        case 1:
+          clientVM = client1;
+          break;
+        case 2:
+          clientVM = client2;
+          break;
+        case 3:
+          useThisVM = true;
+          break;
+        default:
+          fail("executeOpBlock: Unknown client number " + clientNum);
+          break;
+      }
+      getLogWriter().info(
+          "executeOpBlock: performing operation number ["
+              + currentOp.getOpNum() + "]: " + currentOp);
+      if ((opFlags & OpFlags.USE_OLDCONN) == 0) {
+        Properties opCredentials;
+        int newRnd = rnd.nextInt(100) + 1;
+        String currentRegionName = '/' + regionName;
+        if ((opFlags & OpFlags.USE_SUBREGION) > 0) {
+          currentRegionName += ('/' + subregionName);
+        }
+        String credentialsTypeStr;
+        OperationCode authOpCode = currentOp.getAuthzOperationCode();
+        int[] indices = currentOp.getIndices();
+        CredentialGenerator cGen = gen.getCredentialGenerator();
+        Properties javaProps = null;
+        if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0
+            || (opFlags & OpFlags.USE_NOTAUTHZ) > 0) {
+          opCredentials = gen.getDisallowedCredentials(
+              new OperationCode[] { authOpCode },
+              new String[] { currentRegionName }, indices, newRnd);
+          credentialsTypeStr = " unauthorized " + authOpCode;
+        }
+        else {
+          opCredentials = gen.getAllowedCredentials(new OperationCode[] {
+              opCode, authOpCode }, new String[] { currentRegionName },
+              indices, newRnd);
+          credentialsTypeStr = " authorized " + authOpCode;
+        }
+        if (cGen != null) {
+          javaProps = cGen.getJavaProperties();
+        }
+        Properties clientProps = SecurityTestUtil
+            .concatProperties(new Properties[] { opCredentials, extraAuthProps,
+                extraAuthzProps });
+        // Start the client with valid credentials but allowed or disallowed to
+        // perform an operation
+        getLogWriter().info(
+            "executeOpBlock: For client" + clientNum + credentialsTypeStr
+                + " credentials: " + opCredentials);
+        boolean setupDynamicRegionFactory = (opFlags & OpFlags.ENABLE_DRF) > 0;
+        if (useThisVM) {
+          createCacheClient(authInit, clientProps, javaProps, new Integer[] {
+              port1, port2 }, null, Boolean.valueOf(setupDynamicRegionFactory),
+              new Integer(SecurityTestUtil.NO_EXCEPTION));
+        }
+        else {
+          clientVM.invoke(ClientAuthorizationTestBase.class,
+              "createCacheClient", new Object[] { authInit, clientProps,
+                  javaProps, new Integer[] { port1, port2 }, null,
+                  Boolean.valueOf(setupDynamicRegionFactory),
+                  new Integer(SecurityTestUtil.NO_EXCEPTION) });
+        }
+      }
+      int expectedResult;
+      if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0) {
+        expectedResult = SecurityTestUtil.NOTAUTHZ_EXCEPTION;
+      }
+      else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
+        expectedResult = SecurityTestUtil.OTHER_EXCEPTION;
+      }
+      else {
+        expectedResult = SecurityTestUtil.NO_EXCEPTION;
+      }
+
+      // Perform the operation from selected client
+      if (useThisVM) {
+        doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), new Integer(
+            opFlags), new Integer(expectedResult));
+      }
+      else {
+        clientVM.invoke(DeltaClientPostAuthorizationDUnitTest.class, "doOp",
+            new Object[] { new Byte(opCode.toOrdinal()),
+                currentOp.getIndices(), new Integer(opFlags),
+                new Integer(expectedResult) });
+      }
+    }
+  }
+
+  private static Region createSubregion(Region region) {
+
+    Region subregion = getSubregion();
+    if (subregion == null) {
+      subregion = region.createSubregion(subregionName, region.getAttributes());
+    }
+    return subregion;
+  }
+
+  public static void doOp(Byte opCode, int[] indices, Integer flagsI,
+      Integer expectedResult) {
+
+    OperationCode op = OperationCode.fromOrdinal(opCode.byteValue());
+    boolean operationOmitted = false;
+    final int flags = flagsI.intValue();
+    Region region = getRegion();
+//    for (int i = 0; i < indices.length; i++) {
+//      region.put(SecurityTestUtil.keys[i],
+//          DeltaClientAuthorizationDUnitTest.deltas[i]);
+//    }
+    if ((flags & OpFlags.USE_SUBREGION) > 0) {
+      assertNotNull(region);
+      Region subregion = null;
+      if ((flags & OpFlags.NO_CREATE_SUBREGION) > 0) {
+        if ((flags & OpFlags.CHECK_NOREGION) > 0) {
+          // Wait for some time for DRF update to come
+          SecurityTestUtil.waitForCondition(new Callable() {
+            public Object call() throws Exception {
+              return Boolean.valueOf(getSubregion() == null);
+            }
+          });
+          subregion = getSubregion();
+          assertNull(subregion);
+          return;
+        }
+        else {
+          // Wait for some time for DRF update to come
+          SecurityTestUtil.waitForCondition(new Callable() {
+            public Object call() throws Exception {
+              return Boolean.valueOf(getSubregion() != null);
+            }
+          });
+          subregion = getSubregion();
+          assertNotNull(subregion);
+        }
+      }
+      else {
+        subregion = createSubregion(region);
+      }
+      assertNotNull(subregion);
+      region = subregion;
+    }
+    else if ((flags & OpFlags.CHECK_NOREGION) > 0) {
+      // Wait for some time for region destroy update to come
+      SecurityTestUtil.waitForCondition(new Callable() {
+        public Object call() throws Exception {
+          return Boolean.valueOf(getRegion() == null);
+        }
+      });
+      region = getRegion();
+      assertNull(region);
+      return;
+    }
+    else {
+      assertNotNull(region);
+    }
+    final String[] keys = SecurityTestUtil.keys;
+    final DeltaTestImpl[] vals;
+    if ((flags & OpFlags.USE_NEWVAL) > 0) {
+      vals = DeltaClientAuthorizationDUnitTest.deltas;
+    }
+    else {
+      vals = DeltaClientAuthorizationDUnitTest.deltas;
+    }
+    InterestResultPolicy policy = InterestResultPolicy.KEYS_VALUES;
+    if ((flags & OpFlags.REGISTER_POLICY_NONE) > 0) {
+      policy = InterestResultPolicy.NONE;
+    }
+    final int numOps = indices.length;
+    getLogWriter().info(
+        "Got doOp for op: " + op.toString() + ", numOps: " + numOps
+            + ", indices: " + indicesToString(indices) + ", expect: " + expectedResult);
+    boolean exceptionOccured = false;
+    boolean breakLoop = false;
+    if (op.isGet()) {
+      try {
+        Thread.sleep(PAUSE);
+      }
+      catch (InterruptedException e) {
+        fail("interrupted");
+      }
+    }
+    for (int indexIndex = 0; indexIndex < numOps; ++indexIndex) {
+      if (breakLoop) {
+        break;
+      }
+      int index = indices[indexIndex];
+      try {
+        final Object key = keys[index];
+        final Object expectedVal = vals[index];
+        if (op.isGet()) {
+          Object value = null;
+          // this is the case for testing GET_ALL
+          if ((flags & OpFlags.USE_ALL_KEYS) > 0) {
+            breakLoop = true;
+            List keyList = new ArrayList(numOps);
+            Object searchKey;
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              searchKey = keys[keyNum];
+              keyList.add(searchKey);
+              // local invalidate some keys to force fetch of those keys from
+              // server
+              if ((flags & OpFlags.CHECK_NOKEY) > 0) {
+                assertFalse(region.containsKey(searchKey));
+              }
+              else {
+                if (keyNumIndex % 2 == 1) {
+                  assertTrue(region.containsKey(searchKey));
+                  region.localInvalidate(searchKey);
+                }
+              }
+            }
+            Map entries = region.getAll(keyList);
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              searchKey = keys[keyNum];
+              if ((flags & OpFlags.CHECK_FAIL) > 0) {
+                assertFalse(entries.containsKey(searchKey));
+              }
+              else {
+                assertTrue(entries.containsKey(searchKey));
+                value = entries.get(searchKey);
+                assertEquals(vals[keyNum], value);
+              }
+            }
+            break;
+          }
+          if ((flags & OpFlags.LOCAL_OP) > 0) {
+            Callable cond = new Callable() {
+              private Region region;
+
+              public Object call() throws Exception {
+                Object value = SecurityTestUtil.getLocalValue(region, key);
+                return Boolean
+                    .valueOf((flags & OpFlags.CHECK_FAIL) > 0 ? !expectedVal
+                        .equals(value) : expectedVal.equals(value));
+              }
+
+              public Callable init(Region region) {
+                this.region = region;
+                return this;
+              }
+            }.init(region);
+            SecurityTestUtil.waitForCondition(cond);
+            value = SecurityTestUtil.getLocalValue(region, key);
+          }
+          else {
+            if ((flags & OpFlags.CHECK_NOKEY) > 0) {
+              assertFalse(region.containsKey(key));
+            }
+            else {
+              assertTrue(region.containsKey(key));
+              region.localInvalidate(key);
+            }
+            value = region.get(key);
+          }
+          if ((flags & OpFlags.CHECK_FAIL) > 0) {
+            assertFalse(expectedVal.equals(value));
+          }
+          else {
+            assertNotNull(value);
+            assertEquals(expectedVal, value);
+          }
+        }
+        else if (op.isPut()) {
+          region.put(key, expectedVal);
+        }
+        else if (op.isRegisterInterest()) {
+          if ((flags & OpFlags.USE_LIST) > 0) {
+            breakLoop = true;
+            // Register interest list in this case
+            List keyList = new ArrayList(numOps);
+            for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) {
+              int keyNum = indices[keyNumIndex];
+              keyList.add(keys[keyNum]);
+            }
+            region.registerInterest(keyList, policy);
+          }
+          else if ((flags & OpFlags.USE_REGEX) > 0) {
+            breakLoop = true;
+            region.registerInterestRegex("key[1-" + numOps + ']', policy);
+          }
+          else if ((flags & OpFlags.USE_ALL_KEYS) > 0) {
+            breakLoop = true;
+            region.registerInterest("ALL_KEYS", policy);
+          }
+          else {
+            region.registerInterest(key, policy);
+          }
+        }
+        else {
+          fail("doOp: Unhandled operation " + op);
+        }
+        if (expectedResult.intValue() != SecurityTestUtil.NO_EXCEPTION) {
+          if (!operationOmitted && !op.isUnregisterInterest()) {
+            fail("Expected an exception while performing operation op =" + op +
+                "flags = " + OpFlags.description(flags));
+          }
+        }
+      }
+      catch (Exception ex) {
+        exceptionOccured = true;
+        if ((ex instanceof ServerConnectivityException
+            || ex instanceof QueryInvocationTargetException || ex instanceof CqException)
+            && (expectedResult.intValue() == SecurityTestUtil.NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "doOp: Got expected NotAuthorizedException when doing operation ["
+                  + op + "] with flags " + OpFlags.description(flags) 
+                  + ": " + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
+          getLogWriter().info(
+              "doOp: Got expected exception when doing operation: "
+                  + ex.toString());
+          continue;
+        }
+        else {
+          fail("doOp: Got unexpected exception when doing operation. Policy = " 
+              + policy + " flags = " + OpFlags.description(flags), ex);
+        }
+      }
+    }
+    if (!exceptionOccured && !operationOmitted
+        && expectedResult.intValue() != SecurityTestUtil.NO_EXCEPTION) {
+      fail("Expected an exception while performing operation: " + op + 
+          " flags = " + OpFlags.description(flags));
+    }
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
new file mode 100644
index 0000000..0f83050
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
@@ -0,0 +1,622 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.io.File;
+import java.util.Properties;
+
+import javax.net.ssl.SSLHandshakeException;
+
+import templates.security.CredentialGenerator;
+import templates.security.DummyCredentialGenerator;
+import templates.security.LdapUserCredentialGenerator;
+
+import com.gemstone.gemfire.LogWriter;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.Locator;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.distributed.internal.membership.MembershipManager;
+import com.gemstone.gemfire.distributed.internal.membership.gms.MembershipManagerHelper;
+import com.gemstone.gemfire.internal.AvailablePort;
+
+import dunit.DistributedTestCase;
+import dunit.Host;
+import dunit.VM;
+
+/**
+ * Tests peer to peer authentication in Gemfire
+ * 
+ * @author Yogesh Mahajan
+ * @since 5.5
+ */
+public class P2PAuthenticationDUnitTest extends DistributedTestCase {
+
+  private static VM locatorVM = null;
+
+  public static final String USER_NAME = "security-username";
+
+  public static final String PASSWORD = "security-password";
+
+  private static final String[] expectedExceptions = {
+      AuthenticationRequiredException.class.getName(),
+      AuthenticationFailedException.class.getName(),
+      GemFireSecurityException.class.getName(),
+      SSLHandshakeException.class.getName(),
+      ClassNotFoundException.class.getName(),
+      "Authentication failed for",
+      "Failed to obtain credentials"};
+
+  public P2PAuthenticationDUnitTest(String name) {
+    super(name);
+  }
+
+  public void setUp() throws Exception {
+
+    super.setUp();
+    final Host host = Host.getHost(0);
+    locatorVM = host.getVM(0);
+  }
+
+  private void setProperty(Properties props, String key, String value) {
+
+    if (key != null && value != null) {
+      props.setProperty(key, value);
+    }
+  }
+
+  /**
+   * Check that mcast-port setting for discovery or with locator are
+   * incompatible with security
+   */
+  public void testIllegalPropertyCombos() throws Exception {
+
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    File logFile = new File(getUniqueName() + "-locator" + port + ".log");
+    Properties props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, 
+                      DistributedTestCase.getIPLiteral() + "[" + port + "]");
+    props.setProperty(DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        "templates.security.UserPasswordAuthInit.create");
+    props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+
+    try {
+      Locator.startLocatorAndDS(port, logFile, null, props);
+      fail("Expected an IllegalArgumentException while starting locator");
+    }
+    catch (IllegalArgumentException ex) {
+      // success
+    }
+
+    // Also try setting the authenticator
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, 
+                      DistributedTestCase.getIPLiteral() +"[" + port + "]");
+    props.setProperty(DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        "templates.security.LdapUserAuthenticator.create");
+    props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+    try {
+      Locator.startLocatorAndDS(port, logFile, null, props);
+      fail("Expected an IllegalArgumentException while starting locator");
+    }
+    catch (IllegalArgumentException ex) {
+      // success
+    }
+
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
+    props.setProperty(DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        "templates.security.UserPasswordAuthInit.create");
+    try {
+      getSystem(props);
+      fail("Expected an IllegalArgumentException while connection to DS");
+    }
+    catch (IllegalArgumentException ex) {
+      // success
+    }
+
+    // Also try setting the authenticator
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
+    props.setProperty(DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        "templates.security.LdapUserAuthenticator.create");
+    try {
+      getSystem(props);
+      fail("Expected an IllegalArgumentException while connection to DS");
+    }
+    catch (IllegalArgumentException ex) {
+      // success
+    }
+  }
+
+  // AuthInitialize is incorrect
+  public void testP2PAuthenticationWithInvalidAuthInitialize() throws Exception {
+
+    disconnectAllFromDS();
+    CredentialGenerator gen = new DummyCredentialGenerator();
+    Properties props = gen.getSystemProperties();
+    Properties javaProps = gen.getJavaProperties();
+    String authenticator = gen.getAuthenticator();
+    if (props == null) {
+      props = new Properties();
+    }
+    String authInit = " Incorrect_AuthInitialize";
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() + "[" + port + "]";
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+            authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+            authenticator);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[]{
+            getUniqueName(), new Integer(port), props, javaProps,
+            expectedExceptions});
+
+    LogWriter dsLogger = createLogWriter(props);
+    SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+    try {
+      new SecurityTestUtil("tmp").createSystem(props, null);
+      fail("AuthenticationFailedException was expected as the AuthInitialize object passed is incorrect");
+    } catch (AuthenticationFailedException expected) {
+      // success
+    } finally {
+      SecurityTestUtil.removeExpectedExceptions(expectedExceptions, dsLogger);
+      locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[]{
+              new Integer(port), expectedExceptions});
+    }
+
+  }
+
+  // Authenticator is incorrect
+  public void testP2PAuthenticationWithInvalidAuthenticator() throws Exception {
+    disconnectAllFromDS();
+    CredentialGenerator gen = new DummyCredentialGenerator();
+    Properties props = gen.getSystemProperties();
+    Properties javaProps = gen.getJavaProperties();
+    String authenticator = "xyz";
+    String authInit = gen.getAuthInit();
+    if (props == null) {
+      props = new Properties();
+    }
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() +"["+port+"]";
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+            authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+            authenticator);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[] {
+            getUniqueName(), new Integer(port), props, javaProps,
+            expectedExceptions });
+
+    LogWriter dsLogger = createLogWriter(props);
+    SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+    try {
+      new SecurityTestUtil("tmp").createSystem(props, javaProps);
+      fail("AuthenticationFailedException was expected as the Authenticator object passed is incorrect");
+    }
+    catch (AuthenticationFailedException expected) {
+      // success
+    }
+    finally {
+      SecurityTestUtil.removeExpectedExceptions(expectedExceptions, dsLogger);
+      locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[] {
+              new Integer(port), expectedExceptions });
+    }
+  }
+
+  public void testP2PAuthenticationWithNoCredentials() throws Exception {
+
+    disconnectAllFromDS();
+
+    CredentialGenerator gen = new DummyCredentialGenerator();
+    Properties props = gen.getSystemProperties();
+    Properties javaProps = gen.getJavaProperties();
+    String authenticator = gen.getAuthenticator();
+    String authInit = gen.getAuthInit();
+    if (props == null) {
+      props = new Properties();
+    }
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() +"["+port+"]";
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+            authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+            authenticator);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[] {
+            getUniqueName(), new Integer(port), props, javaProps,
+            expectedExceptions });
+
+    LogWriter dsLogger = createLogWriter(props);
+    SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+    try {
+      new SecurityTestUtil("tmp").createSystem(props, null);
+      fail("AuthenticationFailedException was expected as no credentials are set");
+    }
+    catch (AuthenticationFailedException expected) {
+      // success
+    }
+    finally {
+      SecurityTestUtil.removeExpectedExceptions(expectedExceptions, dsLogger);
+      locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[] {
+              new Integer(port), expectedExceptions });
+    }
+  }
+
+  public void testP2PAuthenticationWithValidCredentials() throws Exception {
+
+    disconnectAllFromDS();
+    CredentialGenerator gen = new DummyCredentialGenerator();
+    Properties props = gen.getSystemProperties();
+    String authenticator = gen.getAuthenticator();
+    String authInit = gen.getAuthInit();
+    if (props == null) {
+      props = new Properties();
+    }
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() +"["+port+"]";
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+            authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+            authenticator);
+    Properties credentials = gen.getValidCredentials(1);
+    Properties javaProps = gen.getJavaProperties();
+    props.putAll(credentials);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[] {
+            getUniqueName(), new Integer(port), props, javaProps,
+            expectedExceptions });
+    try {
+      createDS(props, javaProps);
+      verifyMembers(new Integer(2));
+      disconnectFromDS();
+
+    } finally {
+      locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[] {
+              new Integer(port), expectedExceptions });
+    }
+  }
+
+  public void testP2PAuthenticationWithBothValidAndInValidCredentials()
+      throws Exception {
+
+    disconnectAllFromDS();
+    addExpectedException("Authentication failed");
+
+    CredentialGenerator gen = new DummyCredentialGenerator();
+    Properties props = gen.getSystemProperties();
+    String authenticator = gen.getAuthenticator();
+    String authInit = gen.getAuthInit();
+    if (props == null) {
+      props = new Properties();
+    }
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() +"["+port+"]";
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+            authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+            authenticator);
+    // valid credentials for locator
+    Properties credentials = gen.getValidCredentials(1);
+    Properties javaProps = gen.getJavaProperties();
+    props.putAll(credentials);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[] {
+            getUniqueName(), new Integer(port), props, javaProps,
+            expectedExceptions });
+    try {
+      // invalid credentials for the peer
+      credentials = gen.getInvalidCredentials(1);
+      javaProps = gen.getJavaProperties();
+      props.putAll(credentials);
+
+      LogWriter dsLogger = createLogWriter(props);
+      SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+      try {
+        new SecurityTestUtil("tmp").createSystem(props, javaProps);
+        fail("AuthenticationFailedException was expected as wrong credentials were passed");
+      }
+      catch (AuthenticationFailedException expected) {
+        // success
+      }
+      finally {
+        SecurityTestUtil.removeExpectedExceptions(expectedExceptions, dsLogger);
+      }
+
+      credentials = gen.getValidCredentials(3);
+      javaProps = gen.getJavaProperties();
+      props.putAll(credentials);
+      createDS(props, javaProps);
+      verifyMembers(new Integer(2));
+      disconnectFromDS();
+
+    } finally {
+      locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[] {
+              new Integer(port), expectedExceptions });
+    }
+  }
+
+  /**
+   * The strategy is to test view change reject by having two different
+   * authenticators on different VMs.
+   * 
+   * Here locator will accept the credentials from peer2 but the first peer will
+   * reject them due to different authenticator. Hence the number of members
+   * reported by the first peer should be only two while others will report as
+   * three.
+   */
+  public void disabled_testP2PViewChangeReject() throws Exception {
+
+    disconnectAllFromDS();
+    final Host host = Host.getHost(0);
+    final VM peer2 = host.getVM(1);
+    final VM peer3 = host.getVM(2);
+
+    CredentialGenerator gen = new LdapUserCredentialGenerator();
+    gen.init();
+    Properties extraProps = gen.getSystemProperties();
+    String authenticator = gen.getAuthenticator();
+    String authInit = gen.getAuthInit();
+    if (extraProps == null) {
+      extraProps = new Properties();
+    }
+
+    CredentialGenerator gen2 = new DummyCredentialGenerator();
+    gen2.init();
+    Properties extraProps2 = gen2.getSystemProperties();
+    String authenticator2 = gen2.getAuthenticator();
+    if (extraProps2 == null) {
+      extraProps2 = new Properties();
+    }
+
+    // Start the locator with the LDAP authenticator
+    Properties props = new Properties();
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() +"["+port+"]";
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        authenticator);
+    Properties credentials = gen.getValidCredentials(1);
+    Properties javaProps = gen.getJavaProperties();
+    props.putAll(credentials);
+    props.putAll(extraProps);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[] {
+        getUniqueName(), new Integer(port), props, javaProps,
+        expectedExceptions });
+    try {
+
+    // Start the first peer with different authenticator
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        authenticator2);
+    credentials = gen.getValidCredentials(3);
+    Properties javaProps2 = gen2.getJavaProperties();
+    props.putAll(credentials);
+    props.putAll(extraProps2);
+    createDS(props, javaProps2);
+
+    // Start the second peer with the same authenticator as locator
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        authenticator);
+    credentials = gen.getValidCredentials(7);
+    javaProps = gen.getJavaProperties();
+    props.putAll(credentials);
+    props.putAll(extraProps);
+    peer2.invoke(P2PAuthenticationDUnitTest.class, "createDS", new Object[] {
+        props, javaProps });
+
+    // Start the third peer with the same authenticator as locator
+    peer3.invoke(P2PAuthenticationDUnitTest.class, "createDS", new Object[] {
+        props, javaProps });
+
+    // wait for view propagation
+    pause(2000);
+    // Verify the number of members on all peers and locator
+    locatorVM.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(4) });
+    verifyMembers(new Integer(2));
+    peer2.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(4) });
+    peer3.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(4) });
+
+    // Disconnect the first peer and check again
+    disconnectFromDS();
+    pause(2000);
+    locatorVM.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(3) });
+    peer2.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(3) });
+    peer3.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(3) });
+
+    // Disconnect the second peer and check again
+    peer2.invoke(DistributedTestCase.class, "disconnectFromDS");
+    pause(2000);
+    locatorVM.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(2) });
+    peer3.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(2) });
+
+    // Same for last peer
+    peer3.invoke(DistributedTestCase.class, "disconnectFromDS");
+    pause(2000);
+    locatorVM.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(1) });
+
+    } finally {
+    locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[] {
+        new Integer(port), expectedExceptions });
+    }
+  }
+
+  /**
+   * The strategy is to test credential size greater than UDP datagram size.
+   * 
+   * @see Bug # 38570.
+   * 
+   * Here locator will accept the credentials from peer2 and the large credential
+   * from the first peer. Number of members in the DS
+   * should be four
+   */
+  public void testP2PLargeCredentialSucceeds() throws Exception {
+
+    disconnectAllFromDS();
+    final Host host = Host.getHost(0);
+    final VM peer2 = host.getVM(1);
+    final VM peer3 = host.getVM(2);
+
+    CredentialGenerator gen = new DummyCredentialGenerator();
+    gen.init();
+    Properties extraProps = gen.getSystemProperties();
+    String authenticator = gen.getAuthenticator();
+    String authInit = "templates.security.UserPasswordWithExtraPropsAuthInit.create";
+    if (extraProps == null) {
+      extraProps = new Properties();
+    }
+
+    // Start the locator with the Dummy authenticator
+    Properties props = new Properties();
+    int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    final String locators = DistributedTestCase.getIPLiteral() +"["+port+"]";
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        authenticator);
+    Properties credentials = gen.getValidCredentials(1);
+    Properties javaProps = gen.getJavaProperties();
+    props.putAll(credentials);
+    props.putAll(extraProps);
+    locatorVM.invoke(SecurityTestUtil.class, "startLocator", new Object[] {
+        getUniqueName(), new Integer(port), props, javaProps,
+        expectedExceptions });
+    try {
+
+    // Start the first peer with huge credentials
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        authenticator);
+    credentials = gen.getValidCredentials(3);
+    javaProps = gen.getJavaProperties();
+    String hugeStr = "20KString";
+    for (int i = 0; i <= 20000; i++) {
+      hugeStr += "A";
+    }
+    credentials.setProperty("security-keep-extra-props", "-");
+    credentials.setProperty("security-hugeentryone", hugeStr);
+    credentials.setProperty("security-hugeentrytwo", hugeStr);
+    credentials.setProperty("security-hugeentrythree", hugeStr);
+
+    props.putAll(credentials);
+    props.putAll(extraProps);
+
+    LogWriter dsLogger = createLogWriter(props);
+    SecurityTestUtil.addExpectedExceptions(
+        new String[] { IllegalArgumentException.class.getName() }, dsLogger);
+    try {
+      createDS(props, javaProps);
+//      fail("AuthenticationFailedException was expected as credentials were passed beyond 50k");
+    }
+    finally {
+      SecurityTestUtil.removeExpectedExceptions(
+          new String[] { IllegalArgumentException.class.getName() }, dsLogger);
+    }
+
+    // Start the second peer with the same authenticator as locator
+    props = new Properties();
+    props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
+        authInit);
+    setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
+        authenticator);
+    credentials = gen.getValidCredentials(7);
+    javaProps = gen.getJavaProperties();
+    props.putAll(credentials);
+    props.putAll(extraProps);
+    peer2.invoke(P2PAuthenticationDUnitTest.class, "createDS", new Object[] {
+        props, javaProps });
+
+    // Start the third peer with the same authenticator as locator
+    peer3.invoke(P2PAuthenticationDUnitTest.class, "createDS", new Object[] {
+        props, javaProps });
+
+    // wait for view propagation
+    pause(2000);
+    // Verify the number of members on all peers and locator
+    locatorVM.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(4) });
+    peer2.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(4) });
+    peer3.invoke(P2PAuthenticationDUnitTest.class, "verifyMembers",
+        new Object[] { new Integer(4) });
+
+
+    // Disconnect the peers
+    disconnectFromDS();
+    peer2.invoke(DistributedTestCase.class, "disconnectFromDS");
+    peer3.invoke(DistributedTestCase.class, "disconnectFromDS");
+
+    } finally {
+    // Stopping the locator
+    locatorVM.invoke(SecurityTestUtil.class, "stopLocator", new Object[] {
+        new Integer(port), expectedExceptions });
+    }
+  }
+
+  public static void createDS(Properties props, Object javaProps) {
+
+    SecurityTestUtil tmpUtil = new SecurityTestUtil("tmp");
+    tmpUtil.createSystem(props, (Properties)javaProps);
+  }
+
+  public static void verifyMembers(Integer numExpectedMembers) {
+
+    DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
+    MembershipManager mgr = MembershipManagerHelper
+        .getMembershipManager(ds);
+    assertEquals(numExpectedMembers.intValue(), mgr.getView().size());
+  }
+
+}


[2/7] incubator-geode git commit: GEODE-663: add aditional security tests to the open source

Posted by je...@apache.org.
GEODE-663: add aditional security tests to the open source


Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/3720666f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/3720666f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/3720666f

Branch: refs/heads/develop
Commit: 3720666f0d1e7c6dedb3cb18a1a0952d7446ac31
Parents: a622d6e
Author: Jinmei Liao <ji...@pivotal.io>
Authored: Fri Dec 11 15:27:50 2015 -0800
Committer: Jens Deppe <jd...@pivotal.io>
Committed: Mon Dec 21 08:51:59 2015 -0800

----------------------------------------------------------------------
 .../security/ClientAuthenticationDUnitTest.java |   6 +-
 .../security/ClientAuthorizationDUnitTest.java  |   8 +-
 .../security/ClientAuthorizationTestBase.java   |  10 +-
 .../security/ClientMultiUserAuthzDUnitTest.java |   4 +-
 .../DeltaClientAuthorizationDUnitTest.java      |   4 +-
 .../DeltaClientPostAuthorizationDUnitTest.java  |   4 +-
 .../security/P2PAuthenticationDUnitTest.java    |   8 +-
 .../java/security/AuthzCredentialGenerator.java | 465 +++++++++++++++++++
 .../test/java/security/CredentialGenerator.java | 343 ++++++++++++++
 .../security/DummyAuthzCredentialGenerator.java | 145 ++++++
 .../java/security/DummyCredentialGenerator.java |  94 ++++
 .../security/LdapUserCredentialGenerator.java   | 160 +++++++
 .../java/security/PKCSCredentialGenerator.java  | 112 +++++
 .../java/security/SSLCredentialGenerator.java   | 117 +++++
 .../UserPasswordWithExtraPropsAuthInit.java     |  77 +++
 .../security/XmlAuthzCredentialGenerator.java   | 264 +++++++++++
 .../security/AuthzCredentialGenerator.java      | 465 -------------------
 .../templates/security/CredentialGenerator.java | 343 --------------
 .../security/DummyAuthzCredentialGenerator.java | 142 ------
 .../security/DummyCredentialGenerator.java      |  90 ----
 .../security/LdapUserCredentialGenerator.java   | 158 -------
 .../security/PKCSCredentialGenerator.java       | 110 -----
 .../security/SSLCredentialGenerator.java        | 116 -----
 .../UserPasswordWithExtraPropsAuthInit.java     |  76 ---
 .../security/XmlAuthzCredentialGenerator.java   | 262 -----------
 25 files changed, 1799 insertions(+), 1784 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
index 2fdbc05..2bd04e0 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
@@ -26,8 +26,8 @@ import java.util.Properties;
 import javax.net.ssl.SSLException;
 import javax.net.ssl.SSLHandshakeException;
 
-import templates.security.CredentialGenerator;
-import templates.security.CredentialGenerator.ClassCode;
+import security.CredentialGenerator;
+import security.CredentialGenerator.ClassCode;
 
 import com.gemstone.gemfire.cache.Region;
 import com.gemstone.gemfire.distributed.internal.DistributionConfig;
@@ -36,7 +36,7 @@ import com.gemstone.gemfire.internal.AvailablePort;
 import dunit.DistributedTestCase;
 import dunit.Host;
 import dunit.VM;
-import templates.security.DummyCredentialGenerator;
+import security.DummyCredentialGenerator;
 
 /**
  * Test for authentication from client to server. This tests for both valid and

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
index e89e0d3..b44ac33 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
@@ -26,10 +26,10 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Properties;
 
-import templates.security.AuthzCredentialGenerator;
-import templates.security.CredentialGenerator;
-import templates.security.DummyCredentialGenerator;
-import templates.security.XmlAuthzCredentialGenerator;
+import security.AuthzCredentialGenerator;
+import security.CredentialGenerator;
+import security.DummyCredentialGenerator;
+import security.XmlAuthzCredentialGenerator;
 
 import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
 import com.gemstone.gemfire.internal.AvailablePort;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
index ad6526a..e49f9ff 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
@@ -31,9 +31,9 @@ import java.util.Properties;
 import java.util.Random;
 import java.util.Set;
 
-import templates.security.AuthzCredentialGenerator;
-import templates.security.CredentialGenerator;
-import templates.security.AuthzCredentialGenerator.ClassCode;
+import security.AuthzCredentialGenerator;
+import security.CredentialGenerator;
+import security.AuthzCredentialGenerator.ClassCode;
 
 import com.gemstone.gemfire.cache.DynamicRegionFactory;
 import com.gemstone.gemfire.cache.InterestResultPolicy;
@@ -62,8 +62,8 @@ import com.gemstone.gemfire.internal.util.Callable;
 
 import dunit.DistributedTestCase;
 import dunit.VM;
-import templates.security.DummyCredentialGenerator;
-import templates.security.XmlAuthzCredentialGenerator;
+import security.DummyCredentialGenerator;
+import security.XmlAuthzCredentialGenerator;
 
 /**
  * Base class for tests for authorization from client to server. It contains

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
index ceeb989..627c415 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
@@ -24,8 +24,8 @@ package com.gemstone.gemfire.security;
 import java.util.Iterator;
 import java.util.Properties;
 
-import templates.security.AuthzCredentialGenerator;
-import templates.security.CredentialGenerator;
+import security.AuthzCredentialGenerator;
+import security.CredentialGenerator;
 
 import com.gemstone.gemfire.cache.Region;
 import com.gemstone.gemfire.cache.execute.Function;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
index 16573c2..37b46cc 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
@@ -23,8 +23,8 @@ package com.gemstone.gemfire.security;
 
 import java.util.Properties;
 
-import templates.security.AuthzCredentialGenerator;
-import templates.security.CredentialGenerator;
+import security.AuthzCredentialGenerator;
+import security.CredentialGenerator;
 
 import com.gemstone.gemfire.DeltaTestImpl;
 import com.gemstone.gemfire.cache.Region;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
index 7cfa23d..0a0a0b8 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
@@ -28,8 +28,8 @@ import java.util.Map;
 import java.util.Properties;
 import java.util.Random;
 
-import templates.security.AuthzCredentialGenerator;
-import templates.security.CredentialGenerator;
+import security.AuthzCredentialGenerator;
+import security.CredentialGenerator;
 
 import com.gemstone.gemfire.DeltaTestImpl;
 import com.gemstone.gemfire.cache.InterestResultPolicy;

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
index 0f83050..e4ce211 100644
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
@@ -26,9 +26,9 @@ import java.util.Properties;
 
 import javax.net.ssl.SSLHandshakeException;
 
-import templates.security.CredentialGenerator;
-import templates.security.DummyCredentialGenerator;
-import templates.security.LdapUserCredentialGenerator;
+import security.CredentialGenerator;
+import security.DummyCredentialGenerator;
+import security.LdapUserCredentialGenerator;
 
 import com.gemstone.gemfire.LogWriter;
 import com.gemstone.gemfire.distributed.DistributedSystem;
@@ -507,7 +507,7 @@ public class P2PAuthenticationDUnitTest extends DistributedTestCase {
     gen.init();
     Properties extraProps = gen.getSystemProperties();
     String authenticator = gen.getAuthenticator();
-    String authInit = "templates.security.UserPasswordWithExtraPropsAuthInit.create";
+    String authInit = "security.UserPasswordWithExtraPropsAuthInit.create";
     if (extraProps == null) {
       extraProps = new Properties();
     }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/AuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/AuthzCredentialGenerator.java b/gemfire-core/src/test/java/security/AuthzCredentialGenerator.java
new file mode 100644
index 0000000..d5e4915
--- /dev/null
+++ b/gemfire-core/src/test/java/security/AuthzCredentialGenerator.java
@@ -0,0 +1,465 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.security.AccessControl;
+
+/**
+ * Encapsulates obtaining authorized and unauthorized credentials for a given
+ * operation in a region. Implementations will be for different kinds of
+ * authorization scheme and authentication scheme combos.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public abstract class AuthzCredentialGenerator {
+
+  /**
+   * Enumeration for various {@link AuthzCredentialGenerator} implementations.
+   * 
+   * The following schemes are supported as of now:
+   * <ul>
+   * <li><code>DummyAuthorization</code> with <code>DummyAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> with <code>DummyAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> with <code>LDAPAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> with <code>PKCSAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> when using SSL sockets</li>
+   * </ul>
+   * 
+   * To add a new authorization scheme the following needs to be done:
+   * <ul>
+   * <li>Add implementation for {@link AccessControl}.</li>
+   * <li>Choose the authentication schemes that it shall work with from
+   * {@link CredentialGenerator.ClassCode}</li>
+   * <li>Add a new enumeration value for the scheme in this class. Notice the
+   * size of <code>VALUES</code> array and increase that if it is getting
+   * overflowed. Note the methods and fields for existing schemes and add for
+   * the new one in a similar manner.</li>
+   * <li>Add an implementation for {@link AuthzCredentialGenerator}. Note the
+   * {@link AuthzCredentialGenerator#init} method where different authentication
+   * schemes can be passed and initialize differently for the authentication
+   * schemes that shall be handled.</li>
+   * <li>Modify the {@link AuthzCredentialGenerator#create} method to add
+   * creation of an instance of the new implementation for the
+   * <code>ClassCode</code> enumeration value.</li>
+   * </ul>
+   * All dunit tests will automagically start testing the new implementation
+   * after this.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static final class ClassCode {
+
+    private static final byte ID_DUMMY = 1;
+
+    private static final byte ID_XML = 2;
+
+    private static byte nextOrdinal = 0;
+
+    private static final ClassCode[] VALUES = new ClassCode[10];
+
+    private static final Map CodeNameMap = new HashMap();
+
+    public static final ClassCode DUMMY = new ClassCode(
+        "templates.security.DummyAuthorization.create", ID_DUMMY);
+
+    public static final ClassCode XML = new ClassCode(
+        "templates.security.XmlAuthorization.create", ID_XML);
+
+    /** The name of this class. */
+    private final String name;
+
+    /** byte used as ordinal to represent this class */
+    private final byte ordinal;
+
+    /**
+     * One of the following: ID_DUMMY, ID_LDAP, ID_PKI
+     */
+    private final byte classType;
+
+    /** Creates a new instance of class code. */
+    private ClassCode(String name, byte classType) {
+      this.name = name;
+      this.classType = classType;
+      this.ordinal = nextOrdinal++;
+      VALUES[this.ordinal] = this;
+      CodeNameMap.put(name, this);
+    }
+
+    public boolean isDummy() {
+      return (this.classType == ID_DUMMY);
+    }
+
+    public boolean isXml() {
+      return (this.classType == ID_XML);
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified ordinal.
+     */
+    public static ClassCode fromOrdinal(byte ordinal) {
+      return VALUES[ordinal];
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified string.
+     */
+    public static ClassCode parse(String operationName) {
+      return (ClassCode)CodeNameMap.get(operationName);
+    }
+
+    /**
+     * Returns all the possible values.
+     */
+    public static List getAll() {
+      List codes = new ArrayList();
+      Iterator iter = CodeNameMap.values().iterator();
+      while (iter.hasNext()) {
+        codes.add(iter.next());
+      }
+      return codes;
+    }
+
+    /**
+     * Returns the ordinal for this class code.
+     * 
+     * @return the ordinal of this class code.
+     */
+    public byte toOrdinal() {
+      return this.ordinal;
+    }
+
+    /**
+     * Returns a string representation for this class code.
+     * 
+     * @return the name of this class code.
+     */
+    final public String toString() {
+      return this.name;
+    }
+
+    /**
+     * Indicates whether other object is same as this one.
+     * 
+     * @return true if other object is same as this one.
+     */
+    @Override
+    final public boolean equals(final Object obj) {
+      if (obj == this) {
+        return true;
+      }
+      if (!(obj instanceof ClassCode)) {
+        return false;
+      }
+      final ClassCode other = (ClassCode)obj;
+      return (other.ordinal == this.ordinal);
+    }
+
+    /**
+     * Indicates whether other <code>ClassCode</code> is same as this one.
+     * 
+     * @return true if other <code>ClassCode</code> is same as this one.
+     */
+    final public boolean equals(final ClassCode opCode) {
+      return (opCode != null && opCode.ordinal == this.ordinal);
+    }
+
+    /**
+     * Returns a hash code value for this <code>ClassCode</code> which is the
+     * same as its ordinal.
+     * 
+     * @return the ordinal of this <code>ClassCode</code>.
+     */
+    @Override
+    final public int hashCode() {
+      return this.ordinal;
+    }
+
+  }
+
+  /**
+   * The {@link CredentialGenerator} being used.
+   */
+  protected CredentialGenerator cGen;
+
+  /**
+   * A set of system properties that should be added to the gemfire system
+   * properties before using the authorization module.
+   */
+  private Properties sysProps;
+
+  /**
+   * A factory method to create a new instance of an
+   * {@link AuthzCredentialGenerator} for the given {@link ClassCode}. Caller
+   * is supposed to invoke {@link AuthzCredentialGenerator#init} immediately
+   * after obtaining the instance.
+   * 
+   * @param classCode
+   *                the <code>ClassCode</code> of the
+   *                <code>AuthzCredentialGenerator</code> implementation
+   * 
+   * @return an instance of <code>AuthzCredentialGenerator</code> for the
+   *         given class code
+   */
+  public static AuthzCredentialGenerator create(ClassCode classCode) {
+    switch (classCode.classType) {
+      case ClassCode.ID_DUMMY:
+        return new DummyAuthzCredentialGenerator();
+      case ClassCode.ID_XML:
+        return new XmlAuthzCredentialGenerator();
+      default:
+        return null;
+    }
+  }
+
+  /**
+   * Initialize the authorized credential generator.
+   * 
+   * @param cGen
+   *                an instance of {@link CredentialGenerator} of the credential
+   *                implementation for which to obtain authorized/unauthorized
+   *                credentials.
+   * 
+   * @return false when the given {@link CredentialGenerator} is incompatible
+   *         with this authorization module.
+   */
+  public boolean init(CredentialGenerator cGen) {
+    this.cGen = cGen;
+    try {
+      this.sysProps = init();
+    }
+    catch (IllegalArgumentException ex) {
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   */
+  public Properties getSystemProperties() {
+    return this.sysProps;
+  }
+
+  /**
+   * Get the {@link CredentialGenerator} being used by this instance.
+   */
+  public CredentialGenerator getCredentialGenerator() {
+    return this.cGen;
+  }
+
+  /**
+   * The {@link ClassCode} of the particular implementation.
+   * 
+   * @return the <code>ClassCode</code>
+   */
+  public abstract ClassCode classCode();
+
+  /**
+   * The name of the {@link AccessControl} factory function that should be used
+   * as the authorization module on the server side.
+   * 
+   * @return name of the <code>AccessControl</code> factory function
+   */
+  public abstract String getAuthorizationCallback();
+
+  /**
+   * Get a set of credentials generated using the given index allowed to perform
+   * the given {@link OperationCode}s for the given regions.
+   * 
+   * @param opCodes
+   *                the list of {@link OperationCode}s of the operations
+   *                requiring authorization; should not be null
+   * @param regionNames
+   *                list of the region names requiring authorization; a value of
+   *                null indicates all regions
+   * @param index
+   *                used to generate multiple such credentials by passing
+   *                different values for this
+   * 
+   * @return the set of credentials authorized to perform the given operation in
+   *         the given regions
+   */
+  public Properties getAllowedCredentials(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    int numTries = getNumPrincipalTries(opCodes, regionNames);
+    if (numTries <= 0) {
+      numTries = 1;
+    }
+    for (int tries = 0; tries < numTries; tries++) {
+      Principal principal = getAllowedPrincipal(opCodes, regionNames,
+          (index + tries) % numTries);
+      try {
+        return this.cGen.getValidCredentials(principal);
+      }
+      catch (IllegalArgumentException ex) {
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Get a set of credentials generated using the given index not allowed to
+   * perform the given {@link OperationCode}s for the given regions. The
+   * credentials are required to be valid for authentication.
+   * 
+   * @param opCode
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization failure; should not be null
+   * @param regionNames
+   *                list of the region names requiring authorization failure; a
+   *                value of null indicates all regions
+   * @param index
+   *                used to generate multiple such credentials by passing
+   *                different values for this
+   * 
+   * @return the set of credentials that are not authorized to perform the given
+   *         operation in the given region
+   */
+  public Properties getDisallowedCredentials(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    // This may not be very correct since we use the value of
+    // getNumPrincipalTries() but is used to avoid adding another method.
+    // Also something like getNumDisallowedPrincipals() will be normally always
+    // infinite, and the number here is just to perform some number of tries
+    // before giving up.
+    int numTries = getNumPrincipalTries(opCodes, regionNames);
+    if (numTries <= 0) {
+      numTries = 1;
+    }
+    for (int tries = 0; tries < numTries; tries++) {
+      Principal principal = getDisallowedPrincipal(opCodes, regionNames,
+          (index + tries) % numTries);
+      try {
+        return this.cGen.getValidCredentials(principal);
+      }
+      catch (IllegalArgumentException ex) {
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Initialize the authorized credential generator.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   * 
+   * @throws IllegalArgumentException
+   *                 when the {@link CredentialGenerator} is incompatible with
+   *                 this authorization module.
+   */
+  protected abstract Properties init() throws IllegalArgumentException;
+
+  /**
+   * Get the number of tries to be done for obtaining valid credentials for the
+   * given operations in the given region. It is required that
+   * {@link #getAllowedPrincipal} method returns valid principals for values of
+   * <code>index</code> from 0 through (n-1) where <code>n</code> is the
+   * value returned by this method. It is recommended that the principals so
+   * returned be unique for efficiency.
+   * 
+   * This will be used by {@link #getAllowedCredentials} to step through
+   * different principals and obtain a set of valid credentials.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @param opCodes
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization
+   * @param regionNames
+   *                list of the region names requiring authorization; a value of
+   *                null indicates all regions
+   * @param index
+   *                used to generate multiple such credentials by passing
+   *                different values for this
+   * 
+   * @return the number of principals allowed to perform the given operation in
+   *         the given region
+   */
+  protected abstract int getNumPrincipalTries(OperationCode[] opCodes,
+      String[] regionNames);
+
+  /**
+   * Get a {@link Principal} generated using the given index allowed to perform
+   * the given {@link OperationCode}s for the given region.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @param opCodes
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization
+   * @param regionNames
+   *                list of the region names requiring authorization; a value of
+   *                null indicates all regions
+   * @param index
+   *                used to generate multiple such principals by passing
+   *                different values for this
+   * 
+   * @return the {@link Principal} authorized to perform the given operation in
+   *         the given region
+   */
+  protected abstract Principal getAllowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index);
+
+  /**
+   * Get a {@link Principal} generated using the given index not allowed to
+   * perform the given {@link OperationCode}s for the given region.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @param opCodes
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization failure
+   * @param regionNames
+   *                list of the region names requiring authorization failure; a
+   *                value of null indicates all regions
+   * @param index
+   *                used to generate multiple such principals by passing
+   *                different values for this
+   * 
+   * @return a {@link Principal} not authorized to perform the given operation
+   *         in the given region
+   */
+  protected abstract Principal getDisallowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index);
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/CredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/CredentialGenerator.java b/gemfire-core/src/test/java/security/CredentialGenerator.java
new file mode 100644
index 0000000..c16a8a1
--- /dev/null
+++ b/gemfire-core/src/test/java/security/CredentialGenerator.java
@@ -0,0 +1,343 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import com.gemstone.gemfire.security.AuthInitialize;
+import com.gemstone.gemfire.security.Authenticator;
+
+/**
+ * Encapsulates obtaining valid and invalid credentials. Implementations will be
+ * for different kinds of authentication schemes.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public abstract class CredentialGenerator {
+
+  /**
+   * Enumeration for various {@link CredentialGenerator} implementations.
+   * 
+   * The following schemes are supported as of now:
+   * <code>DummyAuthenticator</code>, <code>LdapUserAuthenticator</code>,
+   * <code>PKCSAuthenticator</code>. In addition SSL socket mode with mutual
+   * authentication is also supported.
+   * 
+   * To add a new authentication scheme the following needs to be done:
+   * <ul>
+   * <li>Add implementations for {@link AuthInitialize} and
+   * {@link Authenticator} classes for clients/peers.</li>
+   * <li>Add a new enumeration value for the scheme in this class. Notice the
+   * size of <code>VALUES</code> array and increase that if it is getting
+   * overflowed. Note the methods and fields for existing schemes and add for
+   * the new one in a similar manner.</li>
+   * <li>Add an implementation for {@link CredentialGenerator}.</li>
+   * <li>Modify the {@link CredentialGenerator.Factory#create} method to add
+   * creation of an instance of the new implementation for the
+   * <code>ClassCode</code> enumeration value.</li>
+   * </ul>
+   * All security dunit tests will automagically start testing the new
+   * implementation after this.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static final class ClassCode {
+
+    private static final byte ID_DUMMY = 1;
+
+    private static final byte ID_LDAP = 2;
+
+    private static final byte ID_PKCS = 3;
+
+    private static final byte ID_SSL = 4;
+
+    private static byte nextOrdinal = 0;
+
+    private static final ClassCode[] VALUES = new ClassCode[10];
+
+    private static final Map CodeNameMap = new HashMap();
+
+    public static final ClassCode DUMMY = new ClassCode(
+        "templates.security.DummyAuthenticator.create", ID_DUMMY);
+
+    public static final ClassCode LDAP = new ClassCode(
+        "templates.security.LdapUserAuthenticator.create", ID_LDAP);
+
+    public static final ClassCode PKCS = new ClassCode(
+        "templates.security.PKCSAuthenticator.create", ID_PKCS);
+
+    public static final ClassCode SSL = new ClassCode("SSL", ID_SSL);
+
+    /** The name of this class. */
+    private final String name;
+
+    /** byte used as ordinal to represent this class */
+    private final byte ordinal;
+
+    /**
+     * One of the following: ID_DUMMY, ID_LDAP, ID_PKCS
+     */
+    private final byte classType;
+
+    /** Creates a new instance of class code. */
+    private ClassCode(String name, byte classType) {
+      this.name = name;
+      this.classType = classType;
+      this.ordinal = nextOrdinal++;
+      VALUES[this.ordinal] = this;
+      CodeNameMap.put(name, this);
+    }
+
+    public boolean isDummy() {
+      return (this.classType == ID_DUMMY);
+    }
+
+    public boolean isLDAP() {
+      return (this.classType == ID_LDAP);
+    }
+
+    public boolean isPKCS() {
+      return (this.classType == ID_PKCS);
+    }
+
+    public boolean isSSL() {
+      return (this.classType == ID_SSL);
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified ordinal.
+     */
+    public static ClassCode fromOrdinal(byte ordinal) {
+      return VALUES[ordinal];
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified string.
+     */
+    public static ClassCode parse(String operationName) {
+      return (ClassCode)CodeNameMap.get(operationName);
+    }
+
+    /**
+     * Returns all the possible values.
+     */
+    public static List getAll() {
+      List codes = new ArrayList();
+      Iterator iter = CodeNameMap.values().iterator();
+      while (iter.hasNext()) {
+        codes.add(iter.next());
+      }
+      return codes;
+    }
+
+    /**
+     * Returns the ordinal for this operation code.
+     * 
+     * @return the ordinal of this operation.
+     */
+    public byte toOrdinal() {
+      return this.ordinal;
+    }
+
+    /**
+     * Returns a string representation for this operation.
+     * 
+     * @return the name of this operation.
+     */
+    final public String toString() {
+      return this.name;
+    }
+
+    /**
+     * Indicates whether other object is same as this one.
+     * 
+     * @return true if other object is same as this one.
+     */
+    @Override
+    final public boolean equals(final Object obj) {
+      if (obj == this) {
+        return true;
+      }
+      if (!(obj instanceof ClassCode)) {
+        return false;
+      }
+      final ClassCode other = (ClassCode)obj;
+      return (other.ordinal == this.ordinal);
+    }
+
+    /**
+     * Indicates whether other <code>ClassCode</code> is same as this one.
+     * 
+     * @return true if other <code>ClassCode</code> is same as this one.
+     */
+    final public boolean equals(final ClassCode opCode) {
+      return (opCode != null && opCode.ordinal == this.ordinal);
+    }
+
+    /**
+     * Returns a hash code value for this <code>ClassCode</code> which is the
+     * same as its ordinal.
+     * 
+     * @return the ordinal of this operation.
+     */
+    @Override
+    final public int hashCode() {
+      return this.ordinal;
+    }
+
+  }
+
+  /**
+   * A set of properties that should be added to the Gemfire system properties
+   * before using the authentication module.
+   */
+  private Properties sysProps = null;
+
+  /**
+   * A set of properties that should be added to the java system properties
+   * before using the authentication module.
+   */
+  protected Properties javaProps = null;
+
+  /**
+   * A factory method to create a new instance of an {@link CredentialGenerator}
+   * for the given {@link ClassCode}. Caller is supposed to invoke
+   * {@link CredentialGenerator#init} immediately after obtaining the instance.
+   * 
+   * @param classCode
+   *                the <code>ClassCode</code> of the
+   *                <code>CredentialGenerator</code> implementation
+   * 
+   * @return an instance of <code>CredentialGenerator</code> for the given
+   *         class code
+   */
+  public static CredentialGenerator create(ClassCode classCode) {
+    switch (classCode.classType) {
+      // Removing dummy one to reduce test run times
+      // case ClassCode.ID_DUMMY:
+      // return new DummyCredentialGenerator();
+      case ClassCode.ID_LDAP:
+        return new LdapUserCredentialGenerator();
+        // case ClassCode.ID_SSL:ΓΈ
+        // return new SSLCredentialGenerator();
+      case ClassCode.ID_PKCS:
+        return new PKCSCredentialGenerator();
+      default:
+        return null;
+    }
+  }
+
+  /**
+   * Initialize the credential generator.
+   * 
+   * @throws IllegalArgumentException
+   *                 when there is a problem during initialization
+   */
+  public void init() throws IllegalArgumentException {
+    this.sysProps = initialize();
+  }
+
+  /**
+   * Initialize the credential generator. This is provided separately from the
+   * {@link #init} method for convenience of implementations so that they do not
+   * need to store in {@link #sysProps}. The latter is convenient for the users
+   * who do not need to store these properties rather can obtain it later by
+   * invoking {@link #getSystemProperties}
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   * 
+   * @throws IllegalArgumentException
+   *                 when there is a problem during initialization
+   */
+  protected abstract Properties initialize() throws IllegalArgumentException;
+
+  /**
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   */
+  public Properties getSystemProperties() {
+    return this.sysProps;
+  }
+
+  /**
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   */
+  public Properties getJavaProperties() {
+    return this.javaProps;
+  }
+
+  /**
+   * The {@link ClassCode} of this particular implementation.
+   * 
+   * @return the <code>ClassCode</code>
+   */
+  public abstract ClassCode classCode();
+
+  /**
+   * The name of the {@link AuthInitialize} factory function that should be used
+   * in conjunction with the credentials generated by this generator.
+   * 
+   * @return name of the <code>AuthInitialize</code> factory function
+   */
+  public abstract String getAuthInit();
+
+  /**
+   * The name of the {@link Authenticator} factory function that should be used
+   * in conjunction with the credentials generated by this generator.
+   * 
+   * @return name of the <code>Authenticator</code> factory function
+   */
+  public abstract String getAuthenticator();
+
+  /**
+   * Get a set of valid credentials generated using the given index.
+   */
+  public abstract Properties getValidCredentials(int index);
+
+  /**
+   * Get a set of valid credentials for the given {@link Principal}.
+   * 
+   * @return credentials for the given <code>Principal</code> or null if none
+   *         possible.
+   */
+  public abstract Properties getValidCredentials(Principal principal);
+
+  /**
+   * Get a set of invalid credentials generated using the given index.
+   */
+  public abstract Properties getInvalidCredentials(int index);
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/DummyAuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/DummyAuthzCredentialGenerator.java b/gemfire-core/src/test/java/security/DummyAuthzCredentialGenerator.java
new file mode 100644
index 0000000..7e40d13
--- /dev/null
+++ b/gemfire-core/src/test/java/security/DummyAuthzCredentialGenerator.java
@@ -0,0 +1,145 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import security.AuthzCredentialGenerator;
+import templates.security.DummyAuthorization;
+import templates.security.UsernamePrincipal;
+
+public class DummyAuthzCredentialGenerator extends AuthzCredentialGenerator {
+
+  public static final byte READER_ROLE = 1;
+
+  public static final byte WRITER_ROLE = 2;
+
+  public static final byte ADMIN_ROLE = 3;
+
+  private static Set readerOpsSet;
+
+  private static Set writerOpsSet;
+
+  static {
+
+    readerOpsSet = new HashSet();
+    for (int index = 0; index < DummyAuthorization.READER_OPS.length; index++) {
+      readerOpsSet.add(DummyAuthorization.READER_OPS[index]);
+    }
+    writerOpsSet = new HashSet();
+    for (int index = 0; index < DummyAuthorization.WRITER_OPS.length; index++) {
+      writerOpsSet.add(DummyAuthorization.WRITER_OPS[index]);
+    }
+  }
+
+  public DummyAuthzCredentialGenerator() {
+  }
+
+  protected Properties init() throws IllegalArgumentException {
+
+    if (!this.cGen.classCode().isDummy()) {
+      throw new IllegalArgumentException(
+          "DummyAuthorization module only works with DummyAuthenticator");
+    }
+    return null;
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.DUMMY;
+  }
+
+  public String getAuthorizationCallback() {
+    return "templates.security.DummyAuthorization.create";
+  }
+
+  public static byte getRequiredRole(OperationCode[] opCodes) {
+
+    byte roleType = ADMIN_ROLE;
+    boolean requiresReader = true;
+    boolean requiresWriter = true;
+
+    for (int opNum = 0; opNum < opCodes.length; opNum++) {
+      if (requiresReader && !readerOpsSet.contains(opCodes[opNum])) {
+        requiresReader = false;
+      }
+      if (requiresWriter && !writerOpsSet.contains(opCodes[opNum])) {
+        requiresWriter = false;
+      }
+    }
+    if (requiresReader) {
+      roleType = READER_ROLE;
+    }
+    else if (requiresWriter) {
+      roleType = WRITER_ROLE;
+    }
+    return roleType;
+  }
+
+  private Principal getPrincipal(byte roleType, int index) {
+
+    String[] admins = new String[] { "root", "admin", "administrator" };
+    switch (roleType) {
+      case READER_ROLE:
+        return new UsernamePrincipal("reader" + index);
+      case WRITER_ROLE:
+        return new UsernamePrincipal("writer" + index);
+      default:
+        return new UsernamePrincipal(admins[index % admins.length]);
+    }
+  }
+
+  protected Principal getAllowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    byte roleType = getRequiredRole(opCodes);
+    return getPrincipal(roleType, index);
+  }
+
+  protected Principal getDisallowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    byte roleType = getRequiredRole(opCodes);
+    byte disallowedRoleType;
+    switch (roleType) {
+      case READER_ROLE:
+        disallowedRoleType = WRITER_ROLE;
+        break;
+      case WRITER_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+      default:
+        disallowedRoleType = READER_ROLE;
+        break;
+    }
+    return getPrincipal(disallowedRoleType, index);
+  }
+
+  protected int getNumPrincipalTries(OperationCode[] opCodes,
+      String[] regionNames) {
+    return 5;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/DummyCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/DummyCredentialGenerator.java b/gemfire-core/src/test/java/security/DummyCredentialGenerator.java
new file mode 100644
index 0000000..86b26a7
--- /dev/null
+++ b/gemfire-core/src/test/java/security/DummyCredentialGenerator.java
@@ -0,0 +1,94 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import security.CredentialGenerator;
+import templates.security.DummyAuthenticator;
+import templates.security.UserPasswordAuthInit;
+
+import java.security.Principal;
+import java.util.Properties;
+
+public class DummyCredentialGenerator extends CredentialGenerator {
+
+  public DummyCredentialGenerator() {
+  }
+
+  protected Properties initialize() throws IllegalArgumentException {
+    return null;
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.DUMMY;
+  }
+
+  public String getAuthInit() {
+    return "templates.security.UserPasswordAuthInit.create";
+  }
+
+  public String getAuthenticator() {
+    return "templates.security.DummyAuthenticator.create";
+  }
+
+  public Properties getValidCredentials(int index) {
+
+    String[] validGroups = new String[] { "admin", "user", "reader", "writer" };
+    String[] admins = new String[] { "root", "admin", "administrator" };
+
+    Properties props = new Properties();
+    int groupNum = (index % validGroups.length);
+    String userName;
+    if (groupNum == 0) {
+      userName = admins[index % admins.length];
+    }
+    else {
+      userName = validGroups[groupNum] + (index / validGroups.length);
+    }
+    props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+    return props;
+  }
+
+  public Properties getValidCredentials(Principal principal) {
+
+    String userName = principal.getName();
+    if (DummyAuthenticator.testValidName(userName)) {
+      Properties props = new Properties();
+      props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+      props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+      return props;
+    }
+    else {
+      throw new IllegalArgumentException("Dummy: [" + userName
+          + "] is not a valid user");
+    }
+  }
+
+  public Properties getInvalidCredentials(int index) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, "invalid" + index);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, "none");
+    return props;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/LdapUserCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/LdapUserCredentialGenerator.java b/gemfire-core/src/test/java/security/LdapUserCredentialGenerator.java
new file mode 100644
index 0000000..12bcb62
--- /dev/null
+++ b/gemfire-core/src/test/java/security/LdapUserCredentialGenerator.java
@@ -0,0 +1,160 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.Properties;
+
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.cache.tier.sockets.HandShake;
+import com.gemstone.gemfire.util.test.TestUtil;
+import templates.security.LdapUserAuthenticator;
+import templates.security.UserPasswordAuthInit;
+
+import java.util.Random;
+
+public class LdapUserCredentialGenerator extends CredentialGenerator {
+
+  private static final String USER_PREFIX = "gemfire";
+
+  private static boolean enableServerAuthentication = false;
+
+  private boolean serverAuthEnabled = false;
+
+  private static final Random prng = new Random();
+
+  private static final String[] algos = new String[] { "", "DESede", "AES:128",
+      "Blowfish:128" };
+
+  public LdapUserCredentialGenerator() {
+    // Toggle server authentication enabled for each test
+    // This is done instead of running all the tests with both
+    // server auth enabled/disabled to reduce test run time.
+    enableServerAuthentication = !enableServerAuthentication;
+    serverAuthEnabled = enableServerAuthentication;
+  }
+
+  @Override
+  protected Properties initialize() throws IllegalArgumentException {
+
+    Properties extraProps = new Properties();
+    String ldapServer = System.getProperty("gf.ldap.server", "ldap");
+    String ldapBaseDN = System.getProperty("gf.ldap.basedn", "ou=ldapTesting,dc=pune,dc=gemstone,dc=com");
+    String ldapUseSSL = System.getProperty("gf.ldap.usessl");
+    extraProps.setProperty(LdapUserAuthenticator.LDAP_SERVER_NAME, ldapServer);
+    extraProps.setProperty(LdapUserAuthenticator.LDAP_BASEDN_NAME, ldapBaseDN);
+    if (ldapUseSSL != null && ldapUseSSL.length() > 0) {
+      extraProps.setProperty(LdapUserAuthenticator.LDAP_SSL_NAME, ldapUseSSL);
+    }
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(LdapUserCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/gemfire1.keystore");
+      extraProps.setProperty(HandShake.PRIVATE_KEY_FILE_PROP, keyStoreFile);
+      extraProps.setProperty(HandShake.PRIVATE_KEY_ALIAS_PROP, "gemfire1");
+      extraProps.setProperty(HandShake.PRIVATE_KEY_PASSWD_PROP, "gemfire");
+    }
+    return extraProps;
+  }
+
+  @Override
+  public ClassCode classCode() {
+    return ClassCode.LDAP;
+  }
+
+  @Override
+  public String getAuthInit() {
+    return "templates.security.UserPasswordAuthInit.create";
+  }
+
+  @Override
+  public String getAuthenticator() {
+    return "templates.security.LdapUserAuthenticator.create";
+  }
+
+  @Override
+  public Properties getValidCredentials(int index) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, USER_PREFIX
+        + ((index % 10) + 1));
+    props.setProperty(UserPasswordAuthInit.PASSWORD, USER_PREFIX
+        + ((index % 10) + 1));
+    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
+        algos[prng.nextInt(algos.length)]);
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
+      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
+      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
+    }
+    return props;
+  }
+
+  @Override
+  public Properties getValidCredentials(Principal principal) {
+
+    Properties props = null;
+    String userName = principal.getName();
+    if (userName != null && userName.startsWith(USER_PREFIX)) {
+      boolean isValid;
+      try {
+        int suffix = Integer.parseInt(userName.substring(USER_PREFIX.length()));
+        isValid = (suffix >= 1 && suffix <= 10);
+      }
+      catch (Exception ex) {
+        isValid = false;
+      }
+      if (isValid) {
+        props = new Properties();
+        props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+        props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+      }
+    }
+    if (props == null) {
+      throw new IllegalArgumentException("LDAP: [" + userName
+          + "] not a valid user");
+    }
+    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
+        algos[prng.nextInt(algos.length)]);
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
+      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
+      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
+    }
+    return props;
+  }
+
+  @Override
+  public Properties getInvalidCredentials(int index) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, "invalid" + index);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, "none");
+    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
+        algos[prng.nextInt(algos.length)]);
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
+      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
+      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
+    }
+    return props;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/PKCSCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/PKCSCredentialGenerator.java b/gemfire-core/src/test/java/security/PKCSCredentialGenerator.java
new file mode 100644
index 0000000..24c0100
--- /dev/null
+++ b/gemfire-core/src/test/java/security/PKCSCredentialGenerator.java
@@ -0,0 +1,112 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.security.Provider;
+import java.security.Security;
+import java.util.Properties;
+
+import com.gemstone.gemfire.util.test.TestUtil;
+import templates.security.PKCSAuthInit;
+import templates.security.PKCSAuthenticator;
+
+/**
+ * @author kneeraj
+ * 
+ */
+public class PKCSCredentialGenerator extends CredentialGenerator {
+
+  public static String keyStoreDir = getKeyStoreDir();
+
+  public static boolean usesIBMJSSE;
+
+  // Checks if the current JVM uses only IBM JSSE providers.
+  private static boolean usesIBMProviders() {
+    Provider[] providers = Security.getProviders();
+    for (int index = 0; index < providers.length; ++index) {
+      if (!providers[index].getName().toLowerCase().startsWith("ibm")) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private static String getKeyStoreDir() {
+    usesIBMJSSE = usesIBMProviders();
+    if (usesIBMJSSE) {
+      return "/lib/keys/ibm";
+    }
+    else {
+      return "/lib/keys";
+    }
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.PKCS;
+  }
+
+  public String getAuthInit() {
+    return "templates.security.PKCSAuthInit.create";
+  }
+
+  public String getAuthenticator() {
+    return "templates.security.PKCSAuthenticator.create";
+  }
+
+  public Properties getInvalidCredentials(int index) {
+    Properties props = new Properties();
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/gemfire11.keystore");
+    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
+    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, "gemfire11");
+    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+  public Properties getValidCredentials(int index) {
+    Properties props = new Properties();
+    int aliasnum = (index % 10) + 1;
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/gemfire" + aliasnum + ".keystore");
+    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
+    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, "gemfire" + aliasnum);
+    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+  public Properties getValidCredentials(Principal principal) {
+    Properties props = new Properties();
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + principal.getName() + ".keystore");
+    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
+    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, principal.getName());
+    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+  protected Properties initialize() throws IllegalArgumentException {
+    Properties props = new Properties();
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/publickeyfile");
+    props.setProperty(PKCSAuthenticator.PUBLIC_KEY_FILE, keyStoreFile);
+    props.setProperty(PKCSAuthenticator.PUBLIC_KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/SSLCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/SSLCredentialGenerator.java b/gemfire-core/src/test/java/security/SSLCredentialGenerator.java
new file mode 100644
index 0000000..29a1a30
--- /dev/null
+++ b/gemfire-core/src/test/java/security/SSLCredentialGenerator.java
@@ -0,0 +1,117 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.io.File;
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Properties;
+
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+import security.CredentialGenerator;
+
+public class SSLCredentialGenerator extends CredentialGenerator {
+
+  private File findTrustedJKS() {
+    File ssldir = new File(System.getProperty("JTESTS") + "/ssl");
+    return new File(ssldir, "trusted.keystore");
+  }
+
+  private File findUntrustedJKS() {
+    File ssldir = new File(System.getProperty("JTESTS") + "/ssl");
+    return new File(ssldir, "untrusted.keystore");
+  }
+
+  private Properties getValidJavaSSLProperties() {
+    File jks = findTrustedJKS();
+    try {
+      Properties props = new Properties();
+      props.setProperty("javax.net.ssl.trustStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.trustStorePassword", "password");
+      props.setProperty("javax.net.ssl.keyStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.keyStorePassword", "password");
+      return props;
+    }
+    catch (IOException ex) {
+      throw new AuthenticationFailedException(
+          "SSL: Exception while opening the key store: " + ex);
+    }
+  }
+
+  private Properties getInvalidJavaSSLProperties() {
+    File jks = findUntrustedJKS();
+    try {
+      Properties props = new Properties();
+      props.setProperty("javax.net.ssl.trustStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.trustStorePassword", "password");
+      props.setProperty("javax.net.ssl.keyStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.keyStorePassword", "password");
+      return props;
+    }
+    catch (IOException ex) {
+      throw new AuthenticationFailedException(
+          "SSL: Exception while opening the key store: " + ex);
+    }
+  }
+
+  private Properties getSSLProperties() {
+    Properties props = new Properties();
+    props.setProperty("ssl-enabled", "true");
+    props.setProperty("ssl-require-authentication", "true");
+    props.setProperty("ssl-ciphers", "SSL_RSA_WITH_RC4_128_MD5");
+    props.setProperty("ssl-protocols", "TLSv1");
+    return props;
+  }
+
+  protected Properties initialize() throws IllegalArgumentException {
+    this.javaProps = getValidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.SSL;
+  }
+
+  public String getAuthInit() {
+    return null;
+  }
+
+  public String getAuthenticator() {
+    return null;
+  }
+
+  public Properties getValidCredentials(int index) {
+    this.javaProps = getValidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+  public Properties getValidCredentials(Principal principal) {
+    this.javaProps = getValidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+  public Properties getInvalidCredentials(int index) {
+    this.javaProps = getInvalidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/UserPasswordWithExtraPropsAuthInit.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/UserPasswordWithExtraPropsAuthInit.java b/gemfire-core/src/test/java/security/UserPasswordWithExtraPropsAuthInit.java
new file mode 100644
index 0000000..a41f73a
--- /dev/null
+++ b/gemfire-core/src/test/java/security/UserPasswordWithExtraPropsAuthInit.java
@@ -0,0 +1,77 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.Properties;
+import java.util.Iterator;
+
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.security.AuthInitialize;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+import templates.security.UserPasswordAuthInit;
+
+/**
+ * An {@link AuthInitialize} implementation that obtains the user name and
+ * password as the credentials from the given set of properties. If 
+ * keep-extra-props property exits, it will copy rest of the
+ * properties provided in getCredential props argument will also be 
+ * copied as new credentials.
+ * 
+ * @author Soubhik
+ * @since 5.5
+ */
+public class UserPasswordWithExtraPropsAuthInit extends UserPasswordAuthInit {
+
+  public static final String EXTRA_PROPS = "security-keep-extra-props";
+
+  public static final String SECURITY_PREFIX = "security-";
+  
+  public static AuthInitialize create() {
+    return new UserPasswordWithExtraPropsAuthInit();
+  }
+
+  public UserPasswordWithExtraPropsAuthInit() {
+    super();
+  }
+
+  public Properties getCredentials(Properties props, DistributedMember server,
+      boolean isPeer) throws AuthenticationFailedException {
+
+    Properties newProps = super.getCredentials(props, server, isPeer);
+    String extraProps = props.getProperty(EXTRA_PROPS);
+    if(extraProps != null) {
+    	for(Iterator it = props.keySet().iterator(); it.hasNext();) {
+    		String key = (String)it.next();
+    		if( key.startsWith(SECURITY_PREFIX) && 
+    		    key.equalsIgnoreCase(USER_NAME) == false &&
+    		    key.equalsIgnoreCase(PASSWORD) == false &&
+    		    key.equalsIgnoreCase(EXTRA_PROPS) == false) {
+    			newProps.setProperty(key, props.getProperty(key));
+    		}
+    	}
+    	this.securitylog.fine("got everything and now have: "
+          + newProps.keySet().toString());
+    }
+    return newProps;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/3720666f/gemfire-core/src/test/java/security/XmlAuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/security/XmlAuthzCredentialGenerator.java b/gemfire-core/src/test/java/security/XmlAuthzCredentialGenerator.java
new file mode 100644
index 0000000..929eafb
--- /dev/null
+++ b/gemfire-core/src/test/java/security/XmlAuthzCredentialGenerator.java
@@ -0,0 +1,264 @@
+
+package security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.util.test.TestUtil;
+import templates.security.UsernamePrincipal;
+import templates.security.XmlAuthorization;
+
+public class XmlAuthzCredentialGenerator extends AuthzCredentialGenerator {
+
+  private static final String dummyXml = "authz-dummy.xml";
+
+  private static final String ldapXml = "authz-ldap.xml";
+
+  private static final String pkcsXml = "authz-pkcs.xml";
+
+  private static final String sslXml = "authz-ssl.xml";
+
+  private static final String[] QUERY_REGIONS = { "/Portfolios", "/Positions",
+      "/AuthRegion" };
+
+  public static OperationCode[] READER_OPS = { OperationCode.GET,
+      OperationCode.REGISTER_INTEREST, OperationCode.UNREGISTER_INTEREST,
+      OperationCode.KEY_SET, OperationCode.CONTAINS_KEY, OperationCode.EXECUTE_FUNCTION };
+
+  public static OperationCode[] WRITER_OPS = { OperationCode.PUT,
+      OperationCode.DESTROY, OperationCode.INVALIDATE, OperationCode.REGION_CLEAR };
+
+  public static OperationCode[] QUERY_OPS = { OperationCode.QUERY,
+      OperationCode.EXECUTE_CQ, OperationCode.STOP_CQ, OperationCode.CLOSE_CQ };
+
+  private static final byte READER_ROLE = 1;
+
+  private static final byte WRITER_ROLE = 2;
+
+  private static final byte QUERY_ROLE = 3;
+
+  private static final byte ADMIN_ROLE = 4;
+
+  private static Set readerOpsSet;
+
+  private static Set writerOpsSet;
+
+  private static Set queryOpsSet;
+
+  private static Set queryRegionSet;
+
+  static {
+
+    readerOpsSet = new HashSet();
+    for (int index = 0; index < READER_OPS.length; index++) {
+      readerOpsSet.add(READER_OPS[index]);
+    }
+    writerOpsSet = new HashSet();
+    for (int index = 0; index < WRITER_OPS.length; index++) {
+      writerOpsSet.add(WRITER_OPS[index]);
+    }
+    queryOpsSet = new HashSet();
+    for (int index = 0; index < QUERY_OPS.length; index++) {
+      queryOpsSet.add(QUERY_OPS[index]);
+    }
+    queryRegionSet = new HashSet();
+    for (int index = 0; index < QUERY_REGIONS.length; index++) {
+      queryRegionSet.add(QUERY_REGIONS[index]);
+    }
+  }
+
+  public XmlAuthzCredentialGenerator() {
+  }
+
+  protected Properties init() throws IllegalArgumentException {
+
+    Properties sysProps = new Properties();
+    String dirName = "/lib/";
+    if (this.cGen.classCode().isDummy()) {
+      String xmlFilename = TestUtil.getResourcePath(XmlAuthzCredentialGenerator.class, dirName + dummyXml);
+      sysProps.setProperty(XmlAuthorization.DOC_URI_PROP_NAME, xmlFilename);
+    }
+    else if (this.cGen.classCode().isLDAP()) {
+      String xmlFilename = TestUtil.getResourcePath(XmlAuthzCredentialGenerator.class, dirName + ldapXml);
+      sysProps.setProperty(XmlAuthorization.DOC_URI_PROP_NAME, xmlFilename);
+    }
+    // else if (this.cGen.classCode().isPKCS()) {
+    // sysProps
+    // .setProperty(XmlAuthorization.DOC_URI_PROP_NAME, dirName + pkcsXml);
+    // }
+    // else if (this.cGen.classCode().isSSL()) {
+    // sysProps
+    // .setProperty(XmlAuthorization.DOC_URI_PROP_NAME, dirName + sslXml);
+    // }
+    else {
+      throw new IllegalArgumentException(
+          "No XML defined for XmlAuthorization module to work with "
+              + this.cGen.getAuthenticator());
+    }
+    return sysProps;
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.XML;
+  }
+
+  public String getAuthorizationCallback() {
+    return "templates.security.XmlAuthorization.create";
+  }
+
+  private Principal getDummyPrincipal(byte roleType, int index) {
+
+    String[] admins = new String[] { "root", "admin", "administrator" };
+    int numReaders = 3;
+    int numWriters = 3;
+
+    switch (roleType) {
+      case READER_ROLE:
+        return new UsernamePrincipal("reader" + (index % numReaders));
+      case WRITER_ROLE:
+        return new UsernamePrincipal("writer" + (index % numWriters));
+      case QUERY_ROLE:
+        return new UsernamePrincipal("reader" + ((index % 2) + 3));
+      default:
+        return new UsernamePrincipal(admins[index % admins.length]);
+    }
+  }
+
+  private Principal getLdapPrincipal(byte roleType, int index) {
+
+    final String userPrefix = "gemfire";
+    final int[] readerIndices = { 3, 4, 5 };
+    final int[] writerIndices = { 6, 7, 8 };
+    final int[] queryIndices = { 9, 10 };
+    final int[] adminIndices = { 1, 2 };
+
+    switch (roleType) {
+      case READER_ROLE:
+        int readerIndex = readerIndices[index % readerIndices.length];
+        return new UsernamePrincipal(userPrefix + readerIndex);
+      case WRITER_ROLE:
+        int writerIndex = writerIndices[index % writerIndices.length];
+        return new UsernamePrincipal(userPrefix + writerIndex);
+      case QUERY_ROLE:
+        int queryIndex = queryIndices[index % queryIndices.length];
+        return new UsernamePrincipal(userPrefix + queryIndex);
+      default:
+        int adminIndex = adminIndices[index % adminIndices.length];
+        return new UsernamePrincipal(userPrefix + adminIndex);
+    }
+  }
+
+  private byte getRequiredRole(OperationCode[] opCodes, String[] regionNames) {
+
+    byte roleType = ADMIN_ROLE;
+    boolean requiresReader = true;
+    boolean requiresWriter = true;
+    boolean requiresQuery = true;
+
+    for (int opNum = 0; opNum < opCodes.length; opNum++) {
+      OperationCode opCode = opCodes[opNum];
+      if (requiresReader && !readerOpsSet.contains(opCode)) {
+        requiresReader = false;
+      }
+      if (requiresWriter && !writerOpsSet.contains(opCode)) {
+        requiresWriter = false;
+      }
+      if (requiresQuery && !queryOpsSet.contains(opCode)) {
+        requiresQuery = false;
+      }
+    }
+    if (requiresReader) {
+      roleType = READER_ROLE;
+    }
+    else if (requiresWriter) {
+      roleType = WRITER_ROLE;
+    }
+    else if (requiresQuery) {
+      if (regionNames != null && regionNames.length > 0) {
+        for (int index = 0; index < regionNames.length; index++) {
+          String regionName = XmlAuthorization
+              .normalizeRegionName(regionNames[index]);
+          if (requiresQuery && !queryRegionSet.contains(regionName)) {
+            requiresQuery = false;
+            break;
+          }
+        }
+        if (requiresQuery) {
+          roleType = QUERY_ROLE;
+        }
+      }
+    }
+    return roleType;
+  }
+
+  protected Principal getAllowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    if (this.cGen.classCode().isDummy()) {
+      byte roleType = getRequiredRole(opCodes, regionNames);
+      return getDummyPrincipal(roleType, index);
+    }
+    else if (this.cGen.classCode().isLDAP()) {
+      byte roleType = getRequiredRole(opCodes, regionNames);
+      return getLdapPrincipal(roleType, index);
+    }
+    return null;
+  }
+
+  protected Principal getDisallowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    byte roleType = getRequiredRole(opCodes, regionNames);
+    byte disallowedRoleType = READER_ROLE;
+    switch (roleType) {
+      case READER_ROLE:
+        disallowedRoleType = WRITER_ROLE;
+        break;
+      case WRITER_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+      case QUERY_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+      case ADMIN_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+    }
+    if (this.cGen.classCode().isDummy()) {
+      return getDummyPrincipal(disallowedRoleType, index);
+    }
+    else if (this.cGen.classCode().isLDAP()) {
+      return getLdapPrincipal(disallowedRoleType, index);
+    }
+    return null;
+  }
+
+  protected int getNumPrincipalTries(OperationCode[] opCodes,
+      String[] regionNames) {
+    return 5;
+  }
+
+}


[7/7] incubator-geode git commit: GEM-164: move the security tests in gemfire-test module inside the com.gemstone.gemfire.security packages to the open side.

Posted by je...@apache.org.
GEM-164: move the security tests in gemfire-test module inside the com.gemstone.gemfire.security packages to the open side.

GEM-164: remove the pivotal license header

GEM-164: add ASF license headers and have RAT ignore all subprojects' IDE files when checking license

GEM-164: remove the duplicate license


Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/a622d6ec
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/a622d6ec
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/a622d6ec

Branch: refs/heads/develop
Commit: a622d6ec7f8228443bb99249e08766bd74337c10
Parents: 51ce64d
Author: Jinmei Liao <ji...@pivotal.io>
Authored: Thu Dec 10 15:14:19 2015 -0800
Committer: Jens Deppe <jd...@pivotal.io>
Committed: Mon Dec 21 08:51:59 2015 -0800

----------------------------------------------------------------------
 .../security/ClientAuthenticationDUnitTest.java |  969 +++++++++
 .../ClientAuthenticationPart2DUnitTest.java     |   88 +
 .../security/ClientAuthorizationDUnitTest.java  |  798 ++++++++
 .../security/ClientAuthorizationTestBase.java   | 1384 +++++++++++++
 .../security/ClientMultiUserAuthzDUnitTest.java |  537 +++++
 .../DeltaClientAuthorizationDUnitTest.java      |  336 ++++
 .../DeltaClientPostAuthorizationDUnitTest.java  |  541 +++++
 .../security/P2PAuthenticationDUnitTest.java    |  622 ++++++
 .../gemfire/security/SecurityTestUtil.java      | 1871 ++++++++++++++++++
 .../security/AuthzCredentialGenerator.java      |  465 +++++
 .../templates/security/CredentialGenerator.java |  343 ++++
 .../security/DummyAuthzCredentialGenerator.java |  142 ++
 .../security/DummyCredentialGenerator.java      |   90 +
 .../security/LdapUserCredentialGenerator.java   |  158 ++
 .../security/PKCSCredentialGenerator.java       |  110 +
 .../security/SSLCredentialGenerator.java        |  116 ++
 .../UserPasswordWithExtraPropsAuthInit.java     |   76 +
 .../security/XmlAuthzCredentialGenerator.java   |  262 +++
 .../src/test/resources/lib/authz-dummy.xml      |  126 ++
 .../src/test/resources/lib/authz-ldap.xml       |   85 +
 .../resources/lib/authz-multiUser-dummy.xml     |  106 +
 .../test/resources/lib/authz-multiUser-ldap.xml |   83 +
 .../test/resources/lib/keys/gemfire1.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire10.keystore  |  Bin 0 -> 1546 bytes
 .../test/resources/lib/keys/gemfire11.keystore  |  Bin 0 -> 1546 bytes
 .../test/resources/lib/keys/gemfire2.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire3.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire4.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire5.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire6.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire7.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire8.keystore   |  Bin 0 -> 1536 bytes
 .../test/resources/lib/keys/gemfire9.keystore   |  Bin 0 -> 1536 bytes
 .../resources/lib/keys/ibm/gemfire1.keystore    |  Bin 0 -> 1426 bytes
 .../resources/lib/keys/ibm/gemfire10.keystore   |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire11.keystore   |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire2.keystore    |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire3.keystore    |  Bin 0 -> 1426 bytes
 .../resources/lib/keys/ibm/gemfire4.keystore    |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire5.keystore    |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire6.keystore    |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire7.keystore    |  Bin 0 -> 1426 bytes
 .../resources/lib/keys/ibm/gemfire8.keystore    |  Bin 0 -> 1434 bytes
 .../resources/lib/keys/ibm/gemfire9.keystore    |  Bin 0 -> 1426 bytes
 .../test/resources/lib/keys/ibm/publickeyfile   |  Bin 0 -> 4535 bytes
 .../src/test/resources/lib/keys/publickeyfile   |  Bin 0 -> 4535 bytes
 .../src/test/resources/ssl/untrusted.keystore   |  Bin 0 -> 1181 bytes
 gradle/rat.gradle                               |    2 +-
 48 files changed, 9309 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
new file mode 100644
index 0000000..2fdbc05
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
@@ -0,0 +1,969 @@
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.io.IOException;
+import java.util.Properties;
+
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLHandshakeException;
+
+import templates.security.CredentialGenerator;
+import templates.security.CredentialGenerator.ClassCode;
+
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.AvailablePort;
+
+import dunit.DistributedTestCase;
+import dunit.Host;
+import dunit.VM;
+import templates.security.DummyCredentialGenerator;
+
+/**
+ * Test for authentication from client to server. This tests for both valid and
+ * invalid credentials/modules. It also checks for authentication
+ * success/failure in case of failover and for the notification channel.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public class ClientAuthenticationDUnitTest extends DistributedTestCase {
+
+  /** constructor */
+  public ClientAuthenticationDUnitTest(String name) {
+    super(name);
+  }
+
+  private VM server1 = null;
+
+  private VM server2 = null;
+
+  private VM client1 = null;
+
+  private VM client2 = null;
+
+  private static final String[] serverExpectedExceptions = {
+      AuthenticationRequiredException.class.getName(),
+      AuthenticationFailedException.class.getName(),
+      GemFireSecurityException.class.getName(),
+      ClassNotFoundException.class.getName(), IOException.class.getName(),
+      SSLException.class.getName(), SSLHandshakeException.class.getName() };
+
+  private static final String[] clientExpectedExceptions = {
+      AuthenticationRequiredException.class.getName(),
+      AuthenticationFailedException.class.getName(),
+      SSLHandshakeException.class.getName() };
+
+  @Override
+  public void setUp() throws Exception {
+
+    super.setUp();
+    final Host host = Host.getHost(0);
+    server1 = host.getVM(0);
+    server2 = host.getVM(1);
+    client1 = host.getVM(2);
+    client2 = host.getVM(3);
+    
+    addExpectedException("Connection refused: connect");
+
+    server1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    server2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { serverExpectedExceptions });
+    client1.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+    client2.invoke(SecurityTestUtil.class, "registerExpectedExceptions",
+        new Object[] { clientExpectedExceptions });
+  }
+
+  // Region: Utility and static functions invoked by the tests
+
+  public static Integer createCacheServer(Object dsPort, Object locatorString,
+      Object authenticator, Object extraProps, Object javaProps) {
+
+    Properties authProps;
+    if (extraProps == null) {
+      authProps = new Properties();
+    }
+    else {
+      authProps = (Properties)extraProps;
+    }
+    if (authenticator != null) {
+      authProps.setProperty(
+          DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator
+              .toString());
+    }
+    return SecurityTestUtil.createCacheServer(authProps, javaProps,
+        (Integer)dsPort, (String)locatorString, null, new Integer(
+            SecurityTestUtil.NO_EXCEPTION));
+  }
+
+  public static void createCacheServer(Object dsPort, Object locatorString,
+      Integer serverPort, Object authenticator, Object extraProps,
+      Object javaProps) {
+
+    Properties authProps;
+    if (extraProps == null) {
+      authProps = new Properties();
+    }
+    else {
+      authProps = (Properties)extraProps;
+    }
+    if (authenticator != null) {
+      authProps.setProperty(
+          DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator
+              .toString());
+    }
+    SecurityTestUtil.createCacheServer(authProps, javaProps, (Integer)dsPort,
+        (String)locatorString, serverPort, new Integer(
+            SecurityTestUtil.NO_EXCEPTION));
+  }
+
+  private static void createCacheClient(Object authInit, Properties authProps,
+      Properties javaProps, Integer[] ports, Object numConnections,
+      Boolean multiUserMode, Boolean subscriptionEnabled, Integer expectedResult) {
+
+    String authInitStr = (authInit == null ? null : authInit.toString());
+    SecurityTestUtil.createCacheClient(authInitStr, authProps, javaProps,
+        ports, (Integer)numConnections, Boolean.FALSE,
+        multiUserMode.toString(), subscriptionEnabled, expectedResult);
+  }
+
+  public static void createCacheClient(Object authInit, Object authProps,
+      Object javaProps, Integer[] ports, Object numConnections,
+      Boolean multiUserMode, Integer expectedResult) {
+
+    createCacheClient(authInit, (Properties)authProps, (Properties)javaProps,
+        ports, numConnections, multiUserMode, Boolean.TRUE, expectedResult);
+  }
+
+  public static void createCacheClient(Object authInit, Object authProps,
+      Object javaProps, Integer port1, Object numConnections,
+      Integer expectedResult) {
+
+    createCacheClient(authInit, (Properties)authProps, (Properties)javaProps,
+        new Integer[] { port1 }, numConnections, Boolean.FALSE, Boolean.TRUE,
+        expectedResult);
+  }
+
+  public static void createCacheClient(Object authInit, Object authProps,
+      Object javaProps, Integer port1, Integer port2, Object numConnections,
+      Integer expectedResult) {
+    createCacheClient(authInit, authProps, javaProps, port1, port2,
+        numConnections, Boolean.FALSE, expectedResult);
+  }
+
+  public static void createCacheClient(Object authInit, Object authProps,
+      Object javaProps, Integer port1, Integer port2, Object numConnections,
+      Boolean multiUserMode, Integer expectedResult) {
+
+    createCacheClient(authInit, authProps, javaProps,
+        port1, port2, numConnections, multiUserMode, Boolean.TRUE,
+        expectedResult);
+  }
+
+  public static void createCacheClient(Object authInit, Object authProps,
+      Object javaProps, Integer port1, Integer port2, Object numConnections,
+      Boolean multiUserMode, Boolean subscriptionEnabled,
+      Integer expectedResult) {
+
+    createCacheClient(authInit, (Properties)authProps, (Properties)javaProps,
+        new Integer[] { port1, port2 }, numConnections, multiUserMode,
+        subscriptionEnabled, expectedResult);
+  }
+
+  public static void registerAllInterest() {
+
+    Region region = SecurityTestUtil.getCache().getRegion(
+        SecurityTestUtil.regionName);
+    assertNotNull(region);
+    region.registerInterestRegex(".*");
+  }
+
+  // End Region: Utility and static functions invoked by the tests
+
+  // Region: Tests
+
+  public void testValidCredentials() {
+    itestValidCredentials(Boolean.FALSE);
+  }
+
+  public void itestValidCredentials(Boolean multiUser) {
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter().info(
+          "testValidCredentials: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testValidCredentials: Using authenticator: " + authenticator);
+      getLogWriter().info("testValidCredentials: Using authinit: " + authInit);
+
+      // Start the servers
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = (Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps });
+      Integer port2 = (Integer)server2.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, authenticator, extraProps,
+              javaProps });
+
+      // Start the clients with valid credentials
+      Properties credentials1 = gen.getValidCredentials(1);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testValidCredentials: For first client credentials: " + credentials1
+              + " : " + javaProps1);
+      Properties credentials2 = gen.getValidCredentials(2);
+      Properties javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testValidCredentials: For second client credentials: "
+              + credentials2 + " : " + javaProps2);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials2, javaProps2, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts",
+          new Object[] { new Integer(2) });
+
+      // Verify that the puts succeeded
+      client2.invoke(SecurityTestUtil.class, "doGets",
+          new Object[] { new Integer(2) });
+      
+      if (multiUser) {
+        client1.invoke(SecurityTestUtil.class, "doProxyCacheClose");
+        client2.invoke(SecurityTestUtil.class, "doProxyCacheClose");
+        client1.invoke(SecurityTestUtil.class, "doSimplePut",
+            new Object[] {"CacheClosedException"});
+        client2.invoke(SecurityTestUtil.class, "doSimpleGet",
+            new Object[] {"CacheClosedException"});
+      }
+  }
+
+  public void testNoCredentials() {
+    itestNoCredentials(Boolean.FALSE);
+  }
+
+  public void itestNoCredentials(Boolean multiUser) {
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter()
+          .info("testNoCredentials: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testNoCredentials: Using authenticator: " + authenticator);
+      getLogWriter().info("testNoCredentials: Using authinit: " + authInit);
+
+      // Start the servers
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps }));
+      Integer port2 = ((Integer)server2.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, authenticator, extraProps,
+              javaProps }));
+
+      // Start first client with valid credentials
+      Properties credentials1 = gen.getValidCredentials(1);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testNoCredentials: For first client credentials: " + credentials1
+              + " : " + javaProps1);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts",
+          new Object[] { new Integer(2) });
+
+      // Trying to create the region on client2 
+      if (gen.classCode().equals(ClassCode.SSL)) {
+        // For SSL the exception may not come since the server can close socket
+        // before handshake message is sent from client. However exception
+        // should come in any region operations.
+        client2
+            .invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+                new Object[] { null, null, null, port1, port2, null, multiUser,
+                    new Integer(SecurityTestUtil.NO_EXCEPTION) });
+        client2.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+            new Integer(2), new Integer(SecurityTestUtil.OTHER_EXCEPTION) });
+      }
+      else {
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, null, null, port1, port2,
+                null, multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+      }
+  }
+
+  public void testInvalidCredentials() {
+    itestInvalidCredentials(Boolean.FALSE);
+  }
+
+  public void itestInvalidCredentials(Boolean multiUser) {
+
+
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter().info(
+          "testInvalidCredentials: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testInvalidCredentials: Using authenticator: " + authenticator);
+      getLogWriter()
+          .info("testInvalidCredentials: Using authinit: " + authInit);
+
+      // Start the servers
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps }));
+      Integer port2 = ((Integer)server2.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, authenticator, extraProps,
+              javaProps }));
+
+      // Start first client with valid credentials
+      Properties credentials1 = gen.getValidCredentials(1);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidCredentials: For first client credentials: "
+              + credentials1 + " : " + javaProps1);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts",
+          new Object[] { new Integer(2) });
+
+      // Start second client with invalid credentials
+      // Trying to create the region on client2 should throw a security
+      // exception
+      Properties credentials2 = gen.getInvalidCredentials(1);
+      Properties javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidCredentials: For second client credentials: "
+              + credentials2 + " : " + javaProps2);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials2, javaProps2, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+  }
+
+  public void testInvalidAuthInit() {
+    itestInvalidAuthInit(Boolean.FALSE);
+  }
+
+  public void itestInvalidAuthInit(Boolean multiUser) {
+
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+
+      getLogWriter().info(
+          "testInvalidAuthInit: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testInvalidAuthInit: Using authenticator: " + authenticator);
+
+      // Start the server
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps }));
+
+      Properties credentials = gen.getValidCredentials(1);
+      javaProps = gen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidAuthInit: For first client credentials: " + credentials
+              + " : " + javaProps);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { "com.gemstone.none", credentials, javaProps,
+            new Integer[] { port1 }, null, multiUser,
+            Integer.valueOf(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+  }
+
+  public void testNoAuthInitWithCredentials() {
+    itestNoAuthInitWithCredentials(Boolean.FALSE);
+  }
+
+  public void itestNoAuthInitWithCredentials(Boolean multiUser) {
+
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+
+
+      getLogWriter().info(
+          "testNoAuthInitWithCredentials: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testNoAuthInitWithCredentials: Using authenticator: "
+              + authenticator);
+
+      // Start the servers
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = ((Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps }));
+      Integer port2 = ((Integer)server2.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, authenticator, extraProps,
+              javaProps }));
+
+      // Start the clients with valid credentials
+      Properties credentials1 = gen.getValidCredentials(1);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testNoAuthInitWithCredentials: For first client credentials: "
+              + credentials1 + " : " + javaProps1);
+      Properties credentials2 = gen.getValidCredentials(2);
+      Properties javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testNoAuthInitWithCredentials: For second client credentials: "
+              + credentials2 + " : " + javaProps2);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { null, credentials1, javaProps1, port1, port2, null,
+          multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { null, credentials2, javaProps2, port1, port2, null,
+          multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+      client2.invoke(SecurityTestUtil.class, "closeCache");
+      
+
+      // Now also try with invalid credentials
+      credentials2 = gen.getInvalidCredentials(5);
+      javaProps2 = gen.getJavaProperties();
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { null, credentials2, javaProps2, port1, port2, null,
+          multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+  }
+
+  public void testInvalidAuthenticator() {
+    itestInvalidAuthenticator(Boolean.FALSE);
+  }
+
+  public void itestInvalidAuthenticator(Boolean multiUser) {
+
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter().info(
+          "testInvalidAuthenticator: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testInvalidAuthenticator: Using authinit: " + authInit);
+
+      // Start the server with invalid authenticator
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = (Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, "com.gemstone.gemfire.none",
+              extraProps, javaProps });
+
+      // Trying to create the region on client should throw a security exception
+      Properties credentials = gen.getValidCredentials(1);
+      javaProps = gen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidAuthenticator: For first client credentials: "
+              + credentials + " : " + javaProps);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials, javaProps, port1, null,
+              new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+      client1.invoke(SecurityTestUtil.class, "closeCache");
+      
+
+      // Also test with invalid credentials
+      credentials = gen.getInvalidCredentials(1);
+      javaProps = gen.getJavaProperties();
+      getLogWriter().info(
+          "testInvalidAuthenticator: For first client credentials: "
+              + credentials + " : " + javaProps);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials, javaProps, port1, null,
+              new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+  }
+
+  public void testNoAuthenticatorWithCredentials() {
+    itestNoAuthenticatorWithCredentials(Boolean.FALSE);
+  }
+
+  public void itestNoAuthenticatorWithCredentials(Boolean multiUser) {
+
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter().info(
+          "testNoAuthenticatorWithCredentials: Using scheme: "
+              + gen.classCode());
+      getLogWriter().info(
+          "testNoAuthenticatorWithCredentials: Using authinit: " + authInit);
+
+      // Start the servers with no authenticator
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = (Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, null, extraProps, javaProps });
+      Integer port2 = (Integer)server2.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, null, extraProps, javaProps });
+
+      // Clients should connect successfully and work properly with
+      // valid/invalid credentials when none are required on the server side
+      Properties credentials1 = gen.getValidCredentials(3);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testNoAuthenticatorWithCredentials: For first client credentials: "
+              + credentials1 + " : " + javaProps1);
+      Properties credentials2 = gen.getInvalidCredentials(5);
+      Properties javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testNoAuthenticatorWithCredentials: For second client credentials: "
+              + credentials2 + " : " + javaProps2);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials2, javaProps2, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts",
+          new Object[] { new Integer(2) });
+
+      // Verify that the puts succeeded
+      client2.invoke(SecurityTestUtil.class, "doGets",
+          new Object[] { new Integer(2) });
+  }
+
+  public void testCredentialsWithFailover() {
+    itestCredentialsWithFailover(Boolean.FALSE);
+  }
+
+  public void itestCredentialsWithFailover(Boolean multiUser) {
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter().info(
+          "testCredentialsWithFailover: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testCredentialsWithFailover: Using authenticator: " + authenticator);
+      getLogWriter().info(
+          "testCredentialsWithFailover: Using authinit: " + authInit);
+
+      // Start the first server
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = (Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps });
+      // Get a port for second server but do not start it
+      // This forces the clients to connect to the first server
+      Integer port2 = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+
+      // Start the clients with valid credentials
+      Properties credentials1 = gen.getValidCredentials(5);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testCredentialsWithFailover: For first client credentials: "
+              + credentials1 + " : " + javaProps1);
+      Properties credentials2 = gen.getValidCredentials(6);
+      Properties javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testCredentialsWithFailover: For second client credentials: "
+              + credentials2 + " : " + javaProps2);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials2, javaProps2, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts",
+          new Object[] { new Integer(2) });
+      // Verify that the puts succeeded
+      client2.invoke(SecurityTestUtil.class, "doGets",
+          new Object[] { new Integer(2) });
+
+      // start the second one and stop the first server to force a failover
+      server2.invoke(ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, port2, authenticator, extraProps,
+              javaProps });
+      server1.invoke(SecurityTestUtil.class, "closeCache");
+
+      // Perform some create/update operations from client1
+      client1.invoke(SecurityTestUtil.class, "doNPuts",
+          new Object[] { new Integer(4) });
+      // Verify that the creates/updates succeeded
+      client2.invoke(SecurityTestUtil.class, "doNGets",
+          new Object[] { new Integer(4) });
+
+      // Try to connect client2 with no credentials
+      // Verify that the creation of region throws security exception
+      if (gen.classCode().equals(ClassCode.SSL)) {
+        // For SSL the exception may not come since the server can close socket
+        // before handshake message is sent from client. However exception
+        // should come in any region operations.
+        client2
+            .invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+                new Object[] { null, null, null, port1, port2, null, multiUser,
+                    new Integer(SecurityTestUtil.NOFORCE_AUTHREQ_EXCEPTION) });
+        client2.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+            new Integer(2), new Integer(SecurityTestUtil.OTHER_EXCEPTION) });
+      }
+      else {
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, null, null, port1, port2,
+                null, multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+      }
+
+      // Now try to connect client1 with invalid credentials
+      // Verify that the creation of region throws security exception
+      credentials1 = gen.getInvalidCredentials(7);
+      javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testCredentialsWithFailover: For first client invalid credentials: "
+              + credentials1 + " : " + javaProps1);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+
+      if (multiUser) {
+        client1.invoke(SecurityTestUtil.class, "doProxyCacheClose");
+        client2.invoke(SecurityTestUtil.class, "doProxyCacheClose");
+        client1.invoke(SecurityTestUtil.class, "doSimplePut",
+            new Object[] {"CacheClosedException"});
+        client2.invoke(SecurityTestUtil.class, "doSimpleGet",
+            new Object[] {"CacheClosedException"});
+      }
+  }
+
+  public void testCredentialsForNotifications() {
+    itestCredentialsForNotifications(Boolean.FALSE);
+  }
+
+  public void itestCredentialsForNotifications(Boolean multiUser) {
+      CredentialGenerator gen = new DummyCredentialGenerator();
+      Properties extraProps = gen.getSystemProperties();
+      Properties javaProps = gen.getJavaProperties();
+      String authenticator = gen.getAuthenticator();
+      String authInit = gen.getAuthInit();
+
+      getLogWriter().info(
+          "testCredentialsForNotifications: Using scheme: " + gen.classCode());
+      getLogWriter().info(
+          "testCredentialsForNotifications: Using authenticator: "
+              + authenticator);
+      getLogWriter().info(
+          "testCredentialsForNotifications: Using authinit: " + authInit);
+
+      // Start the first server
+      Integer locPort1 = SecurityTestUtil.getLocatorPort();
+      Integer locPort2 = SecurityTestUtil.getLocatorPort();
+      String locString = SecurityTestUtil.getLocatorString();
+      Integer port1 = (Integer)server1.invoke(
+          ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, authenticator, extraProps,
+              javaProps });
+      // Get a port for second server but do not start it
+      // This forces the clients to connect to the first server
+      Integer port2 = new Integer(AvailablePort
+          .getRandomAvailablePort(AvailablePort.SOCKET));
+
+      // Start the clients with valid credentials
+      Properties credentials1 = gen.getValidCredentials(3);
+      Properties javaProps1 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testCredentialsForNotifications: For first client credentials: "
+              + credentials1 + " : " + javaProps1);
+      Properties credentials2 = gen.getValidCredentials(4);
+      Properties javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testCredentialsForNotifications: For second client credentials: "
+              + credentials2 + " : " + javaProps2);
+      client1.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials1, javaProps1, port1, port2,
+              null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+      // Set up zero forward connections to check notification handshake only
+      Object zeroConns = new Integer(0);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials2, javaProps2, port1, port2,
+              zeroConns, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+      // Register interest on all keys on second client
+      client2
+          .invoke(ClientAuthenticationDUnitTest.class, "registerAllInterest");
+
+      // Perform some put operations from client1
+      client1.invoke(SecurityTestUtil.class, "doPuts",
+          new Object[] { new Integer(2) });
+
+      // Verify that the puts succeeded
+      client2.invoke(SecurityTestUtil.class, "doLocalGets",
+          new Object[] { new Integer(2) });
+
+      // start the second one and stop the first server to force a failover
+      server2.invoke(ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort2, locString, port2, authenticator, extraProps,
+              javaProps });
+      server1.invoke(SecurityTestUtil.class, "closeCache");
+
+      // Wait for failover to complete
+      pause(500);
+
+      // Perform some create/update operations from client1
+      client1.invoke(SecurityTestUtil.class, "doNPuts",
+          new Object[] { new Integer(4) });
+      // Verify that the creates/updates succeeded
+      client2.invoke(SecurityTestUtil.class, "doNLocalGets",
+          new Object[] { new Integer(4) });
+
+      // Try to connect client1 with no credentials
+      // Verify that the creation of region throws security exception
+      server1.invoke(ClientAuthenticationDUnitTest.class, "createCacheServer",
+          new Object[] { locPort1, locString, port1, authenticator, extraProps,
+              javaProps });
+      if (gen.classCode().equals(ClassCode.SSL)) {
+        // For SSL the exception may not come since the server can close socket
+        // before handshake message is sent from client. However exception
+        // should come in any region operations.
+        client1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, null, null, port1, port2,
+                zeroConns, multiUser,
+                new Integer(SecurityTestUtil.NOFORCE_AUTHREQ_EXCEPTION) });
+        client1.invoke(SecurityTestUtil.class, "doPuts", new Object[] {
+            new Integer(2), new Integer(SecurityTestUtil.OTHER_EXCEPTION) });
+      }
+      else {
+        client1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, null, null, port1, port2,
+                zeroConns, multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+      }
+
+      // Now try to connect client2 with invalid credentials
+      // Verify that the creation of region throws security exception
+      credentials2 = gen.getInvalidCredentials(3);
+      javaProps2 = gen.getJavaProperties();
+      getLogWriter().info(
+          "testCredentialsForNotifications: For second client invalid credentials: "
+              + credentials2 + " : " + javaProps2);
+      client2.invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+          new Object[] { authInit, credentials2, javaProps2, port1, port2,
+              zeroConns, multiUser, new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+
+      // Now try to connect client2 with invalid auth-init method
+      // Trying to create the region on client with valid credentials should
+      // throw a security exception
+      client2
+          .invoke(ClientAuthenticationDUnitTest.class, "createCacheClient",
+              new Object[] { "com.gemstone.none", credentials1, javaProps1,
+                  port1, port2, zeroConns, multiUser, 
+                  new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+
+      // Now start the servers with invalid authenticator method.
+      // Skip this test for a scheme which does not have an authInit in the
+      // first place (e.g. SSL) since that will fail with AuthReqEx before
+      // authenticator is even invoked.
+      if (authInit != null && authInit.length() > 0) {
+        server1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheServer", new Object[] { locPort1, locString, port1,
+                "com.gemstone.gemfire.none", extraProps, javaProps });
+        server2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheServer", new Object[] { locPort2, locString, port2,
+                "com.gemstone.gemfire.none", extraProps, javaProps });
+
+        // Trying to create the region on client with valid/invalid credentials
+        // should throw a security exception
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { authInit, credentials1,
+                javaProps1, port1, port2, zeroConns, multiUser,
+                new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+        client1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { authInit, credentials2,
+                javaProps2, port1, port2, zeroConns, multiUser,
+                new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) });
+      }
+      else {
+        getLogWriter().info(
+            "testCredentialsForNotifications: Skipping invalid authenticator for scheme ["
+                + gen.classCode() + "] which has no authInit");
+      }
+
+      // Try connection with null auth-init on clients.
+      // Skip this test for a scheme which does not have an authInit in the
+      // first place (e.g. SSL).
+      if (authInit != null && authInit.length() > 0) {
+        server1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheServer", new Object[] { locPort1, locString, port1,
+                authenticator, extraProps, javaProps });
+        server2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheServer", new Object[] { locPort2, locString, port2,
+                authenticator, extraProps, javaProps });
+        client1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, credentials1, javaProps1,
+                port1, port2, null, multiUser,
+                new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, credentials2, javaProps2,
+                port1, port2, zeroConns, multiUser,
+                new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+
+        // Now also try with invalid credentials on client2
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { null, credentials2, javaProps2,
+                port1, port2, zeroConns, multiUser,
+                new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) });
+      }
+      else {
+        getLogWriter().info(
+            "testCredentialsForNotifications: Skipping null authInit for scheme ["
+                + gen.classCode() + "] which has no authInit");
+      }
+
+      // Try connection with null authenticator on server and sending
+      // valid/invalid credentials.
+      // If the scheme does not have an authenticator in the first place (e.g.
+      // SSL) then skip it since this test is useless.
+      if (authenticator != null && authenticator.length() > 0) {
+        server1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheServer", new Object[] { locPort1, locString, port1,
+                null, extraProps, javaProps });
+        server2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheServer", new Object[] { locPort2, locString, port2,
+                null, extraProps, javaProps });
+        client1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { authInit, credentials1,
+                javaProps1, port1, port2, null, multiUser,
+                new Integer(SecurityTestUtil.NO_EXCEPTION) });
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { authInit, credentials2,
+                javaProps2, port1, port2, zeroConns, multiUser,
+                new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+        // Register interest on all keys on second client
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "registerAllInterest");
+
+        // Perform some put operations from client1
+        client1.invoke(SecurityTestUtil.class, "doPuts",
+            new Object[] { new Integer(4) });
+
+        // Verify that the puts succeeded
+        client2.invoke(SecurityTestUtil.class, "doLocalGets",
+            new Object[] { new Integer(4) });
+
+        // Now also try with valid credentials on client2
+        client1.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { authInit, credentials2,
+                javaProps2, port1, port2, null, multiUser,
+                new Integer(SecurityTestUtil.NO_EXCEPTION) });
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "createCacheClient", new Object[] { authInit, credentials1,
+                javaProps1, port1, port2, zeroConns, multiUser,
+                new Integer(SecurityTestUtil.NO_EXCEPTION) });
+
+        // Register interest on all keys on second client
+        client2.invoke(ClientAuthenticationDUnitTest.class,
+            "registerAllInterest");
+
+        // Perform some put operations from client1
+        client1.invoke(SecurityTestUtil.class, "doNPuts",
+            new Object[] { new Integer(4) });
+
+        // Verify that the puts succeeded
+        client2.invoke(SecurityTestUtil.class, "doNLocalGets",
+            new Object[] { new Integer(4) });
+      }
+      else {
+        getLogWriter().info(
+            "testCredentialsForNotifications: Skipping scheme ["
+                + gen.classCode() + "] which has no authenticator");
+      }
+  }
+
+  //////////////////////////////////////////////////////////////////////////////
+  // Tests for MULTI_USER_MODE start here
+  //////////////////////////////////////////////////////////////////////////////
+
+  public void xtestValidCredentialsForMultipleUsers() {
+    itestValidCredentials(Boolean.TRUE);
+  }
+
+  //////////////////////////////////////////////////////////////////////////////
+  // Tests for MULTI_USER_MODE end here
+  //////////////////////////////////////////////////////////////////////////////
+  
+  @Override
+  public void tearDown2() throws Exception {
+
+    super.tearDown2();
+    // close the clients first
+    client1.invoke(SecurityTestUtil.class, "closeCache");
+    client2.invoke(SecurityTestUtil.class, "closeCache");
+    // then close the servers
+    server1.invoke(SecurityTestUtil.class, "closeCache");
+    server2.invoke(SecurityTestUtil.class, "closeCache");
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
new file mode 100644
index 0000000..138114a
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
@@ -0,0 +1,88 @@
+
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+/**
+ * this class contains test methods that used to be in its superclass but
+ * that test started taking too long and caused dunit runs to hang
+ */
+public class ClientAuthenticationPart2DUnitTest extends
+    ClientAuthenticationDUnitTest {
+
+  /** constructor */
+  public ClientAuthenticationPart2DUnitTest(String name) {
+    super(name);
+  }
+
+  // override inherited tests so they aren't executed again
+  
+  @Override
+  public void testValidCredentials() {  }
+  @Override
+  public void testNoCredentials() {  }
+  @Override
+  public void testInvalidCredentials() {  }
+  @Override
+  public void testInvalidAuthInit() {  }
+  @Override
+  public void testNoAuthInitWithCredentials() {  }
+  @Override
+  public void testInvalidAuthenticator() {  }
+  @Override
+  public void testNoAuthenticatorWithCredentials() {  }
+  @Override
+  public void testCredentialsWithFailover() {  }
+  @Override
+  public void testCredentialsForNotifications() {  }
+  //@Override
+  public void testValidCredentialsForMultipleUsers() {  }
+
+
+  
+  
+  
+  public void testNoCredentialsForMultipleUsers() {
+    itestNoCredentials(Boolean.TRUE);
+  }
+  public void testInvalidCredentialsForMultipleUsers() {
+    itestInvalidCredentials(Boolean.TRUE);
+  }
+  public void testInvalidAuthInitForMultipleUsers() {
+    itestInvalidAuthInit(Boolean.TRUE);
+  }
+  public void testNoAuthInitWithCredentialsForMultipleUsers() {
+    itestNoAuthInitWithCredentials(Boolean.TRUE);
+  }
+  public void testInvalidAuthenitcatorForMultipleUsers() {
+    itestInvalidAuthenticator(Boolean.TRUE);
+  }
+  public void testNoAuthenticatorWithCredentialsForMultipleUsers() {
+    itestNoAuthenticatorWithCredentials(Boolean.TRUE);
+  }
+  public void disabled_testCredentialsWithFailoverForMultipleUsers() {
+    itestCredentialsWithFailover(Boolean.TRUE);
+  }
+  public void __testCredentialsForNotificationsForMultipleUsers() {
+    itestCredentialsForNotifications(Boolean.TRUE);
+  }
+
+}


[3/7] incubator-geode git commit: GEM-164: move the security tests in gemfire-test module inside the com.gemstone.gemfire.security packages to the open side.

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/CredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/CredentialGenerator.java b/gemfire-core/src/test/java/templates/security/CredentialGenerator.java
new file mode 100644
index 0000000..99d7e18
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/CredentialGenerator.java
@@ -0,0 +1,343 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import com.gemstone.gemfire.security.AuthInitialize;
+import com.gemstone.gemfire.security.Authenticator;
+
+/**
+ * Encapsulates obtaining valid and invalid credentials. Implementations will be
+ * for different kinds of authentication schemes.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public abstract class CredentialGenerator {
+
+  /**
+   * Enumeration for various {@link CredentialGenerator} implementations.
+   * 
+   * The following schemes are supported as of now:
+   * <code>DummyAuthenticator</code>, <code>LdapUserAuthenticator</code>,
+   * <code>PKCSAuthenticator</code>. In addition SSL socket mode with mutual
+   * authentication is also supported.
+   * 
+   * To add a new authentication scheme the following needs to be done:
+   * <ul>
+   * <li>Add implementations for {@link AuthInitialize} and
+   * {@link Authenticator} classes for clients/peers.</li>
+   * <li>Add a new enumeration value for the scheme in this class. Notice the
+   * size of <code>VALUES</code> array and increase that if it is getting
+   * overflowed. Note the methods and fields for existing schemes and add for
+   * the new one in a similar manner.</li>
+   * <li>Add an implementation for {@link CredentialGenerator}.</li>
+   * <li>Modify the {@link CredentialGenerator.Factory#create} method to add
+   * creation of an instance of the new implementation for the
+   * <code>ClassCode</code> enumeration value.</li>
+   * </ul>
+   * All security dunit tests will automagically start testing the new
+   * implementation after this.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static final class ClassCode {
+
+    private static final byte ID_DUMMY = 1;
+
+    private static final byte ID_LDAP = 2;
+
+    private static final byte ID_PKCS = 3;
+
+    private static final byte ID_SSL = 4;
+
+    private static byte nextOrdinal = 0;
+
+    private static final ClassCode[] VALUES = new ClassCode[10];
+
+    private static final Map CodeNameMap = new HashMap();
+
+    public static final ClassCode DUMMY = new ClassCode(
+        "templates.security.DummyAuthenticator.create", ID_DUMMY);
+
+    public static final ClassCode LDAP = new ClassCode(
+        "templates.security.LdapUserAuthenticator.create", ID_LDAP);
+
+    public static final ClassCode PKCS = new ClassCode(
+        "templates.security.PKCSAuthenticator.create", ID_PKCS);
+
+    public static final ClassCode SSL = new ClassCode("SSL", ID_SSL);
+
+    /** The name of this class. */
+    private final String name;
+
+    /** byte used as ordinal to represent this class */
+    private final byte ordinal;
+
+    /**
+     * One of the following: ID_DUMMY, ID_LDAP, ID_PKCS
+     */
+    private final byte classType;
+
+    /** Creates a new instance of class code. */
+    private ClassCode(String name, byte classType) {
+      this.name = name;
+      this.classType = classType;
+      this.ordinal = nextOrdinal++;
+      VALUES[this.ordinal] = this;
+      CodeNameMap.put(name, this);
+    }
+
+    public boolean isDummy() {
+      return (this.classType == ID_DUMMY);
+    }
+
+    public boolean isLDAP() {
+      return (this.classType == ID_LDAP);
+    }
+
+    public boolean isPKCS() {
+      return (this.classType == ID_PKCS);
+    }
+
+    public boolean isSSL() {
+      return (this.classType == ID_SSL);
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified ordinal.
+     */
+    public static ClassCode fromOrdinal(byte ordinal) {
+      return VALUES[ordinal];
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified string.
+     */
+    public static ClassCode parse(String operationName) {
+      return (ClassCode)CodeNameMap.get(operationName);
+    }
+
+    /**
+     * Returns all the possible values.
+     */
+    public static List getAll() {
+      List codes = new ArrayList();
+      Iterator iter = CodeNameMap.values().iterator();
+      while (iter.hasNext()) {
+        codes.add(iter.next());
+      }
+      return codes;
+    }
+
+    /**
+     * Returns the ordinal for this operation code.
+     * 
+     * @return the ordinal of this operation.
+     */
+    public byte toOrdinal() {
+      return this.ordinal;
+    }
+
+    /**
+     * Returns a string representation for this operation.
+     * 
+     * @return the name of this operation.
+     */
+    final public String toString() {
+      return this.name;
+    }
+
+    /**
+     * Indicates whether other object is same as this one.
+     * 
+     * @return true if other object is same as this one.
+     */
+    @Override
+    final public boolean equals(final Object obj) {
+      if (obj == this) {
+        return true;
+      }
+      if (!(obj instanceof ClassCode)) {
+        return false;
+      }
+      final ClassCode other = (ClassCode)obj;
+      return (other.ordinal == this.ordinal);
+    }
+
+    /**
+     * Indicates whether other <code>ClassCode</code> is same as this one.
+     * 
+     * @return true if other <code>ClassCode</code> is same as this one.
+     */
+    final public boolean equals(final ClassCode opCode) {
+      return (opCode != null && opCode.ordinal == this.ordinal);
+    }
+
+    /**
+     * Returns a hash code value for this <code>ClassCode</code> which is the
+     * same as its ordinal.
+     * 
+     * @return the ordinal of this operation.
+     */
+    @Override
+    final public int hashCode() {
+      return this.ordinal;
+    }
+
+  }
+
+  /**
+   * A set of properties that should be added to the Gemfire system properties
+   * before using the authentication module.
+   */
+  private Properties sysProps = null;
+
+  /**
+   * A set of properties that should be added to the java system properties
+   * before using the authentication module.
+   */
+  protected Properties javaProps = null;
+
+  /**
+   * A factory method to create a new instance of an {@link CredentialGenerator}
+   * for the given {@link ClassCode}. Caller is supposed to invoke
+   * {@link CredentialGenerator#init} immediately after obtaining the instance.
+   * 
+   * @param classCode
+   *                the <code>ClassCode</code> of the
+   *                <code>CredentialGenerator</code> implementation
+   * 
+   * @return an instance of <code>CredentialGenerator</code> for the given
+   *         class code
+   */
+  public static CredentialGenerator create(ClassCode classCode) {
+    switch (classCode.classType) {
+      // Removing dummy one to reduce test run times
+      // case ClassCode.ID_DUMMY:
+      // return new DummyCredentialGenerator();
+      case ClassCode.ID_LDAP:
+        return new LdapUserCredentialGenerator();
+        // case ClassCode.ID_SSL:ΓΈ
+        // return new SSLCredentialGenerator();
+      case ClassCode.ID_PKCS:
+        return new PKCSCredentialGenerator();
+      default:
+        return null;
+    }
+  }
+
+  /**
+   * Initialize the credential generator.
+   * 
+   * @throws IllegalArgumentException
+   *                 when there is a problem during initialization
+   */
+  public void init() throws IllegalArgumentException {
+    this.sysProps = initialize();
+  }
+
+  /**
+   * Initialize the credential generator. This is provided separately from the
+   * {@link #init} method for convenience of implementations so that they do not
+   * need to store in {@link #sysProps}. The latter is convenient for the users
+   * who do not need to store these properties rather can obtain it later by
+   * invoking {@link #getSystemProperties}
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   * 
+   * @throws IllegalArgumentException
+   *                 when there is a problem during initialization
+   */
+  protected abstract Properties initialize() throws IllegalArgumentException;
+
+  /**
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   */
+  public Properties getSystemProperties() {
+    return this.sysProps;
+  }
+
+  /**
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   */
+  public Properties getJavaProperties() {
+    return this.javaProps;
+  }
+
+  /**
+   * The {@link ClassCode} of this particular implementation.
+   * 
+   * @return the <code>ClassCode</code>
+   */
+  public abstract ClassCode classCode();
+
+  /**
+   * The name of the {@link AuthInitialize} factory function that should be used
+   * in conjunction with the credentials generated by this generator.
+   * 
+   * @return name of the <code>AuthInitialize</code> factory function
+   */
+  public abstract String getAuthInit();
+
+  /**
+   * The name of the {@link Authenticator} factory function that should be used
+   * in conjunction with the credentials generated by this generator.
+   * 
+   * @return name of the <code>Authenticator</code> factory function
+   */
+  public abstract String getAuthenticator();
+
+  /**
+   * Get a set of valid credentials generated using the given index.
+   */
+  public abstract Properties getValidCredentials(int index);
+
+  /**
+   * Get a set of valid credentials for the given {@link Principal}.
+   * 
+   * @return credentials for the given <code>Principal</code> or null if none
+   *         possible.
+   */
+  public abstract Properties getValidCredentials(Principal principal);
+
+  /**
+   * Get a set of invalid credentials generated using the given index.
+   */
+  public abstract Properties getInvalidCredentials(int index);
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java
new file mode 100644
index 0000000..5c27d60
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/DummyAuthzCredentialGenerator.java
@@ -0,0 +1,142 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+
+public class DummyAuthzCredentialGenerator extends AuthzCredentialGenerator {
+
+  public static final byte READER_ROLE = 1;
+
+  public static final byte WRITER_ROLE = 2;
+
+  public static final byte ADMIN_ROLE = 3;
+
+  private static Set readerOpsSet;
+
+  private static Set writerOpsSet;
+
+  static {
+
+    readerOpsSet = new HashSet();
+    for (int index = 0; index < DummyAuthorization.READER_OPS.length; index++) {
+      readerOpsSet.add(DummyAuthorization.READER_OPS[index]);
+    }
+    writerOpsSet = new HashSet();
+    for (int index = 0; index < DummyAuthorization.WRITER_OPS.length; index++) {
+      writerOpsSet.add(DummyAuthorization.WRITER_OPS[index]);
+    }
+  }
+
+  public DummyAuthzCredentialGenerator() {
+  }
+
+  protected Properties init() throws IllegalArgumentException {
+
+    if (!this.cGen.classCode().isDummy()) {
+      throw new IllegalArgumentException(
+          "DummyAuthorization module only works with DummyAuthenticator");
+    }
+    return null;
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.DUMMY;
+  }
+
+  public String getAuthorizationCallback() {
+    return "templates.security.DummyAuthorization.create";
+  }
+
+  public static byte getRequiredRole(OperationCode[] opCodes) {
+
+    byte roleType = ADMIN_ROLE;
+    boolean requiresReader = true;
+    boolean requiresWriter = true;
+
+    for (int opNum = 0; opNum < opCodes.length; opNum++) {
+      if (requiresReader && !readerOpsSet.contains(opCodes[opNum])) {
+        requiresReader = false;
+      }
+      if (requiresWriter && !writerOpsSet.contains(opCodes[opNum])) {
+        requiresWriter = false;
+      }
+    }
+    if (requiresReader) {
+      roleType = READER_ROLE;
+    }
+    else if (requiresWriter) {
+      roleType = WRITER_ROLE;
+    }
+    return roleType;
+  }
+
+  private Principal getPrincipal(byte roleType, int index) {
+
+    String[] admins = new String[] { "root", "admin", "administrator" };
+    switch (roleType) {
+      case READER_ROLE:
+        return new UsernamePrincipal("reader" + index);
+      case WRITER_ROLE:
+        return new UsernamePrincipal("writer" + index);
+      default:
+        return new UsernamePrincipal(admins[index % admins.length]);
+    }
+  }
+
+  protected Principal getAllowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    byte roleType = getRequiredRole(opCodes);
+    return getPrincipal(roleType, index);
+  }
+
+  protected Principal getDisallowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    byte roleType = getRequiredRole(opCodes);
+    byte disallowedRoleType;
+    switch (roleType) {
+      case READER_ROLE:
+        disallowedRoleType = WRITER_ROLE;
+        break;
+      case WRITER_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+      default:
+        disallowedRoleType = READER_ROLE;
+        break;
+    }
+    return getPrincipal(disallowedRoleType, index);
+  }
+
+  protected int getNumPrincipalTries(OperationCode[] opCodes,
+      String[] regionNames) {
+    return 5;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java
new file mode 100644
index 0000000..af6c6eb
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/DummyCredentialGenerator.java
@@ -0,0 +1,90 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.Properties;
+
+public class DummyCredentialGenerator extends CredentialGenerator {
+
+  public DummyCredentialGenerator() {
+  }
+
+  protected Properties initialize() throws IllegalArgumentException {
+    return null;
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.DUMMY;
+  }
+
+  public String getAuthInit() {
+    return "templates.security.UserPasswordAuthInit.create";
+  }
+
+  public String getAuthenticator() {
+    return "templates.security.DummyAuthenticator.create";
+  }
+
+  public Properties getValidCredentials(int index) {
+
+    String[] validGroups = new String[] { "admin", "user", "reader", "writer" };
+    String[] admins = new String[] { "root", "admin", "administrator" };
+
+    Properties props = new Properties();
+    int groupNum = (index % validGroups.length);
+    String userName;
+    if (groupNum == 0) {
+      userName = admins[index % admins.length];
+    }
+    else {
+      userName = validGroups[groupNum] + (index / validGroups.length);
+    }
+    props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+    return props;
+  }
+
+  public Properties getValidCredentials(Principal principal) {
+
+    String userName = principal.getName();
+    if (DummyAuthenticator.testValidName(userName)) {
+      Properties props = new Properties();
+      props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+      props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+      return props;
+    }
+    else {
+      throw new IllegalArgumentException("Dummy: [" + userName
+          + "] is not a valid user");
+    }
+  }
+
+  public Properties getInvalidCredentials(int index) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, "invalid" + index);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, "none");
+    return props;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java
new file mode 100644
index 0000000..816df63
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/LdapUserCredentialGenerator.java
@@ -0,0 +1,158 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.Properties;
+
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.cache.tier.sockets.HandShake;
+import com.gemstone.gemfire.util.test.TestUtil;
+
+import java.util.Random;
+
+public class LdapUserCredentialGenerator extends CredentialGenerator {
+
+  private static final String USER_PREFIX = "gemfire";
+
+  private static boolean enableServerAuthentication = false;
+
+  private boolean serverAuthEnabled = false;
+
+  private static final Random prng = new Random();
+
+  private static final String[] algos = new String[] { "", "DESede", "AES:128",
+      "Blowfish:128" };
+
+  public LdapUserCredentialGenerator() {
+    // Toggle server authentication enabled for each test
+    // This is done instead of running all the tests with both
+    // server auth enabled/disabled to reduce test run time.
+    enableServerAuthentication = !enableServerAuthentication;
+    serverAuthEnabled = enableServerAuthentication;
+  }
+
+  @Override
+  protected Properties initialize() throws IllegalArgumentException {
+
+    Properties extraProps = new Properties();
+    String ldapServer = System.getProperty("gf.ldap.server", "ldap");
+    String ldapBaseDN = System.getProperty("gf.ldap.basedn", "ou=ldapTesting,dc=pune,dc=gemstone,dc=com");
+    String ldapUseSSL = System.getProperty("gf.ldap.usessl");
+    extraProps.setProperty(LdapUserAuthenticator.LDAP_SERVER_NAME, ldapServer);
+    extraProps.setProperty(LdapUserAuthenticator.LDAP_BASEDN_NAME, ldapBaseDN);
+    if (ldapUseSSL != null && ldapUseSSL.length() > 0) {
+      extraProps.setProperty(LdapUserAuthenticator.LDAP_SSL_NAME, ldapUseSSL);
+    }
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(LdapUserCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/gemfire1.keystore");
+      extraProps.setProperty(HandShake.PRIVATE_KEY_FILE_PROP, keyStoreFile);
+      extraProps.setProperty(HandShake.PRIVATE_KEY_ALIAS_PROP, "gemfire1");
+      extraProps.setProperty(HandShake.PRIVATE_KEY_PASSWD_PROP, "gemfire");
+    }
+    return extraProps;
+  }
+
+  @Override
+  public ClassCode classCode() {
+    return ClassCode.LDAP;
+  }
+
+  @Override
+  public String getAuthInit() {
+    return "templates.security.UserPasswordAuthInit.create";
+  }
+
+  @Override
+  public String getAuthenticator() {
+    return "templates.security.LdapUserAuthenticator.create";
+  }
+
+  @Override
+  public Properties getValidCredentials(int index) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, USER_PREFIX
+        + ((index % 10) + 1));
+    props.setProperty(UserPasswordAuthInit.PASSWORD, USER_PREFIX
+        + ((index % 10) + 1));
+    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
+        algos[prng.nextInt(algos.length)]);
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
+      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
+      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
+    }
+    return props;
+  }
+
+  @Override
+  public Properties getValidCredentials(Principal principal) {
+
+    Properties props = null;
+    String userName = principal.getName();
+    if (userName != null && userName.startsWith(USER_PREFIX)) {
+      boolean isValid;
+      try {
+        int suffix = Integer.parseInt(userName.substring(USER_PREFIX.length()));
+        isValid = (suffix >= 1 && suffix <= 10);
+      }
+      catch (Exception ex) {
+        isValid = false;
+      }
+      if (isValid) {
+        props = new Properties();
+        props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+        props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+      }
+    }
+    if (props == null) {
+      throw new IllegalArgumentException("LDAP: [" + userName
+          + "] not a valid user");
+    }
+    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
+        algos[prng.nextInt(algos.length)]);
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
+      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
+      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
+    }
+    return props;
+  }
+
+  @Override
+  public Properties getInvalidCredentials(int index) {
+
+    Properties props = new Properties();
+    props.setProperty(UserPasswordAuthInit.USER_NAME, "invalid" + index);
+    props.setProperty(UserPasswordAuthInit.PASSWORD, "none");
+    props.setProperty(DistributionConfig.SECURITY_CLIENT_DHALGO_NAME,
+        algos[prng.nextInt(algos.length)]);
+    if (serverAuthEnabled) {
+      String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, PKCSCredentialGenerator.keyStoreDir + "/publickeyfile");
+      props.setProperty(HandShake.PUBLIC_KEY_FILE_PROP, keyStoreFile);
+      props.setProperty(HandShake.PUBLIC_KEY_PASSWD_PROP, "gemfire");
+    }
+    return props;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java
new file mode 100644
index 0000000..fa4bf04
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/PKCSCredentialGenerator.java
@@ -0,0 +1,110 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.security.Provider;
+import java.security.Security;
+import java.util.Properties;
+
+import com.gemstone.gemfire.util.test.TestUtil;
+
+/**
+ * @author kneeraj
+ * 
+ */
+public class PKCSCredentialGenerator extends CredentialGenerator {
+
+  public static String keyStoreDir = getKeyStoreDir();
+
+  public static boolean usesIBMJSSE;
+
+  // Checks if the current JVM uses only IBM JSSE providers.
+  private static boolean usesIBMProviders() {
+    Provider[] providers = Security.getProviders();
+    for (int index = 0; index < providers.length; ++index) {
+      if (!providers[index].getName().toLowerCase().startsWith("ibm")) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  private static String getKeyStoreDir() {
+    usesIBMJSSE = usesIBMProviders();
+    if (usesIBMJSSE) {
+      return "/lib/keys/ibm";
+    }
+    else {
+      return "/lib/keys";
+    }
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.PKCS;
+  }
+
+  public String getAuthInit() {
+    return "templates.security.PKCSAuthInit.create";
+  }
+
+  public String getAuthenticator() {
+    return "templates.security.PKCSAuthenticator.create";
+  }
+
+  public Properties getInvalidCredentials(int index) {
+    Properties props = new Properties();
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/gemfire11.keystore");
+    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
+    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, "gemfire11");
+    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+  public Properties getValidCredentials(int index) {
+    Properties props = new Properties();
+    int aliasnum = (index % 10) + 1;
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/gemfire" + aliasnum + ".keystore");
+    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
+    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, "gemfire" + aliasnum);
+    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+  public Properties getValidCredentials(Principal principal) {
+    Properties props = new Properties();
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + principal.getName() + ".keystore");
+    props.setProperty(PKCSAuthInit.KEYSTORE_FILE_PATH, keyStoreFile);
+    props.setProperty(PKCSAuthInit.KEYSTORE_ALIAS, principal.getName());
+    props.setProperty(PKCSAuthInit.KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+  protected Properties initialize() throws IllegalArgumentException {
+    Properties props = new Properties();
+    String keyStoreFile = TestUtil.getResourcePath(PKCSCredentialGenerator.class, keyStoreDir + "/publickeyfile");
+    props.setProperty(PKCSAuthenticator.PUBLIC_KEY_FILE, keyStoreFile);
+    props.setProperty(PKCSAuthenticator.PUBLIC_KEYSTORE_PASSWORD, "gemfire");
+    return props;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java
new file mode 100644
index 0000000..09367a2
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/SSLCredentialGenerator.java
@@ -0,0 +1,116 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.io.File;
+import java.io.IOException;
+import java.security.Principal;
+import java.util.Properties;
+
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+
+public class SSLCredentialGenerator extends CredentialGenerator {
+
+  private File findTrustedJKS() {
+    File ssldir = new File(System.getProperty("JTESTS") + "/ssl");
+    return new File(ssldir, "trusted.keystore");
+  }
+
+  private File findUntrustedJKS() {
+    File ssldir = new File(System.getProperty("JTESTS") + "/ssl");
+    return new File(ssldir, "untrusted.keystore");
+  }
+
+  private Properties getValidJavaSSLProperties() {
+    File jks = findTrustedJKS();
+    try {
+      Properties props = new Properties();
+      props.setProperty("javax.net.ssl.trustStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.trustStorePassword", "password");
+      props.setProperty("javax.net.ssl.keyStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.keyStorePassword", "password");
+      return props;
+    }
+    catch (IOException ex) {
+      throw new AuthenticationFailedException(
+          "SSL: Exception while opening the key store: " + ex);
+    }
+  }
+
+  private Properties getInvalidJavaSSLProperties() {
+    File jks = findUntrustedJKS();
+    try {
+      Properties props = new Properties();
+      props.setProperty("javax.net.ssl.trustStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.trustStorePassword", "password");
+      props.setProperty("javax.net.ssl.keyStore", jks.getCanonicalPath());
+      props.setProperty("javax.net.ssl.keyStorePassword", "password");
+      return props;
+    }
+    catch (IOException ex) {
+      throw new AuthenticationFailedException(
+          "SSL: Exception while opening the key store: " + ex);
+    }
+  }
+
+  private Properties getSSLProperties() {
+    Properties props = new Properties();
+    props.setProperty("ssl-enabled", "true");
+    props.setProperty("ssl-require-authentication", "true");
+    props.setProperty("ssl-ciphers", "SSL_RSA_WITH_RC4_128_MD5");
+    props.setProperty("ssl-protocols", "TLSv1");
+    return props;
+  }
+
+  protected Properties initialize() throws IllegalArgumentException {
+    this.javaProps = getValidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.SSL;
+  }
+
+  public String getAuthInit() {
+    return null;
+  }
+
+  public String getAuthenticator() {
+    return null;
+  }
+
+  public Properties getValidCredentials(int index) {
+    this.javaProps = getValidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+  public Properties getValidCredentials(Principal principal) {
+    this.javaProps = getValidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+  public Properties getInvalidCredentials(int index) {
+    this.javaProps = getInvalidJavaSSLProperties();
+    return getSSLProperties();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java b/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java
new file mode 100644
index 0000000..56dbf7d
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/UserPasswordWithExtraPropsAuthInit.java
@@ -0,0 +1,76 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.util.Properties;
+import java.util.Iterator;
+
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.security.AuthInitialize;
+import com.gemstone.gemfire.security.AuthenticationFailedException;
+
+/**
+ * An {@link AuthInitialize} implementation that obtains the user name and
+ * password as the credentials from the given set of properties. If 
+ * keep-extra-props property exits, it will copy rest of the
+ * properties provided in getCredential props argument will also be 
+ * copied as new credentials.
+ * 
+ * @author Soubhik
+ * @since 5.5
+ */
+public class UserPasswordWithExtraPropsAuthInit extends UserPasswordAuthInit {
+
+  public static final String EXTRA_PROPS = "security-keep-extra-props";
+
+  public static final String SECURITY_PREFIX = "security-";
+  
+  public static AuthInitialize create() {
+    return new UserPasswordWithExtraPropsAuthInit();
+  }
+
+  public UserPasswordWithExtraPropsAuthInit() {
+    super();
+  }
+
+  public Properties getCredentials(Properties props, DistributedMember server,
+      boolean isPeer) throws AuthenticationFailedException {
+
+    Properties newProps = super.getCredentials(props, server, isPeer);
+    String extraProps = props.getProperty(EXTRA_PROPS);
+    if(extraProps != null) {
+    	for(Iterator it = props.keySet().iterator(); it.hasNext();) {
+    		String key = (String)it.next();
+    		if( key.startsWith(SECURITY_PREFIX) && 
+    		    key.equalsIgnoreCase(USER_NAME) == false &&
+    		    key.equalsIgnoreCase(PASSWORD) == false &&
+    		    key.equalsIgnoreCase(EXTRA_PROPS) == false) {
+    			newProps.setProperty(key, props.getProperty(key));
+    		}
+    	}
+    	this.securitylog.fine("got everything and now have: "
+          + newProps.keySet().toString());
+    }
+    return newProps;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java
new file mode 100644
index 0000000..6b3f171
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/XmlAuthzCredentialGenerator.java
@@ -0,0 +1,262 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Properties;
+import java.util.Set;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.util.test.TestUtil;
+
+public class XmlAuthzCredentialGenerator extends AuthzCredentialGenerator {
+
+  private static final String dummyXml = "authz-dummy.xml";
+
+  private static final String ldapXml = "authz-ldap.xml";
+
+  private static final String pkcsXml = "authz-pkcs.xml";
+
+  private static final String sslXml = "authz-ssl.xml";
+
+  private static final String[] QUERY_REGIONS = { "/Portfolios", "/Positions",
+      "/AuthRegion" };
+
+  public static OperationCode[] READER_OPS = { OperationCode.GET,
+      OperationCode.REGISTER_INTEREST, OperationCode.UNREGISTER_INTEREST,
+      OperationCode.KEY_SET, OperationCode.CONTAINS_KEY, OperationCode.EXECUTE_FUNCTION };
+
+  public static OperationCode[] WRITER_OPS = { OperationCode.PUT,
+      OperationCode.DESTROY, OperationCode.INVALIDATE, OperationCode.REGION_CLEAR };
+
+  public static OperationCode[] QUERY_OPS = { OperationCode.QUERY,
+      OperationCode.EXECUTE_CQ, OperationCode.STOP_CQ, OperationCode.CLOSE_CQ };
+
+  private static final byte READER_ROLE = 1;
+
+  private static final byte WRITER_ROLE = 2;
+
+  private static final byte QUERY_ROLE = 3;
+
+  private static final byte ADMIN_ROLE = 4;
+
+  private static Set readerOpsSet;
+
+  private static Set writerOpsSet;
+
+  private static Set queryOpsSet;
+
+  private static Set queryRegionSet;
+
+  static {
+
+    readerOpsSet = new HashSet();
+    for (int index = 0; index < READER_OPS.length; index++) {
+      readerOpsSet.add(READER_OPS[index]);
+    }
+    writerOpsSet = new HashSet();
+    for (int index = 0; index < WRITER_OPS.length; index++) {
+      writerOpsSet.add(WRITER_OPS[index]);
+    }
+    queryOpsSet = new HashSet();
+    for (int index = 0; index < QUERY_OPS.length; index++) {
+      queryOpsSet.add(QUERY_OPS[index]);
+    }
+    queryRegionSet = new HashSet();
+    for (int index = 0; index < QUERY_REGIONS.length; index++) {
+      queryRegionSet.add(QUERY_REGIONS[index]);
+    }
+  }
+
+  public XmlAuthzCredentialGenerator() {
+  }
+
+  protected Properties init() throws IllegalArgumentException {
+
+    Properties sysProps = new Properties();
+    String dirName = "/lib/";
+    if (this.cGen.classCode().isDummy()) {
+      String xmlFilename = TestUtil.getResourcePath(XmlAuthzCredentialGenerator.class, dirName + dummyXml);
+      sysProps.setProperty(XmlAuthorization.DOC_URI_PROP_NAME, xmlFilename);
+    }
+    else if (this.cGen.classCode().isLDAP()) {
+      String xmlFilename = TestUtil.getResourcePath(XmlAuthzCredentialGenerator.class, dirName + ldapXml);
+      sysProps.setProperty(XmlAuthorization.DOC_URI_PROP_NAME, xmlFilename);
+    }
+    // else if (this.cGen.classCode().isPKCS()) {
+    // sysProps
+    // .setProperty(XmlAuthorization.DOC_URI_PROP_NAME, dirName + pkcsXml);
+    // }
+    // else if (this.cGen.classCode().isSSL()) {
+    // sysProps
+    // .setProperty(XmlAuthorization.DOC_URI_PROP_NAME, dirName + sslXml);
+    // }
+    else {
+      throw new IllegalArgumentException(
+          "No XML defined for XmlAuthorization module to work with "
+              + this.cGen.getAuthenticator());
+    }
+    return sysProps;
+  }
+
+  public ClassCode classCode() {
+    return ClassCode.XML;
+  }
+
+  public String getAuthorizationCallback() {
+    return "templates.security.XmlAuthorization.create";
+  }
+
+  private Principal getDummyPrincipal(byte roleType, int index) {
+
+    String[] admins = new String[] { "root", "admin", "administrator" };
+    int numReaders = 3;
+    int numWriters = 3;
+
+    switch (roleType) {
+      case READER_ROLE:
+        return new UsernamePrincipal("reader" + (index % numReaders));
+      case WRITER_ROLE:
+        return new UsernamePrincipal("writer" + (index % numWriters));
+      case QUERY_ROLE:
+        return new UsernamePrincipal("reader" + ((index % 2) + 3));
+      default:
+        return new UsernamePrincipal(admins[index % admins.length]);
+    }
+  }
+
+  private Principal getLdapPrincipal(byte roleType, int index) {
+
+    final String userPrefix = "gemfire";
+    final int[] readerIndices = { 3, 4, 5 };
+    final int[] writerIndices = { 6, 7, 8 };
+    final int[] queryIndices = { 9, 10 };
+    final int[] adminIndices = { 1, 2 };
+
+    switch (roleType) {
+      case READER_ROLE:
+        int readerIndex = readerIndices[index % readerIndices.length];
+        return new UsernamePrincipal(userPrefix + readerIndex);
+      case WRITER_ROLE:
+        int writerIndex = writerIndices[index % writerIndices.length];
+        return new UsernamePrincipal(userPrefix + writerIndex);
+      case QUERY_ROLE:
+        int queryIndex = queryIndices[index % queryIndices.length];
+        return new UsernamePrincipal(userPrefix + queryIndex);
+      default:
+        int adminIndex = adminIndices[index % adminIndices.length];
+        return new UsernamePrincipal(userPrefix + adminIndex);
+    }
+  }
+
+  private byte getRequiredRole(OperationCode[] opCodes, String[] regionNames) {
+
+    byte roleType = ADMIN_ROLE;
+    boolean requiresReader = true;
+    boolean requiresWriter = true;
+    boolean requiresQuery = true;
+
+    for (int opNum = 0; opNum < opCodes.length; opNum++) {
+      OperationCode opCode = opCodes[opNum];
+      if (requiresReader && !readerOpsSet.contains(opCode)) {
+        requiresReader = false;
+      }
+      if (requiresWriter && !writerOpsSet.contains(opCode)) {
+        requiresWriter = false;
+      }
+      if (requiresQuery && !queryOpsSet.contains(opCode)) {
+        requiresQuery = false;
+      }
+    }
+    if (requiresReader) {
+      roleType = READER_ROLE;
+    }
+    else if (requiresWriter) {
+      roleType = WRITER_ROLE;
+    }
+    else if (requiresQuery) {
+      if (regionNames != null && regionNames.length > 0) {
+        for (int index = 0; index < regionNames.length; index++) {
+          String regionName = XmlAuthorization
+              .normalizeRegionName(regionNames[index]);
+          if (requiresQuery && !queryRegionSet.contains(regionName)) {
+            requiresQuery = false;
+            break;
+          }
+        }
+        if (requiresQuery) {
+          roleType = QUERY_ROLE;
+        }
+      }
+    }
+    return roleType;
+  }
+
+  protected Principal getAllowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    if (this.cGen.classCode().isDummy()) {
+      byte roleType = getRequiredRole(opCodes, regionNames);
+      return getDummyPrincipal(roleType, index);
+    }
+    else if (this.cGen.classCode().isLDAP()) {
+      byte roleType = getRequiredRole(opCodes, regionNames);
+      return getLdapPrincipal(roleType, index);
+    }
+    return null;
+  }
+
+  protected Principal getDisallowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    byte roleType = getRequiredRole(opCodes, regionNames);
+    byte disallowedRoleType = READER_ROLE;
+    switch (roleType) {
+      case READER_ROLE:
+        disallowedRoleType = WRITER_ROLE;
+        break;
+      case WRITER_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+      case QUERY_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+      case ADMIN_ROLE:
+        disallowedRoleType = READER_ROLE;
+        break;
+    }
+    if (this.cGen.classCode().isDummy()) {
+      return getDummyPrincipal(disallowedRoleType, index);
+    }
+    else if (this.cGen.classCode().isLDAP()) {
+      return getLdapPrincipal(disallowedRoleType, index);
+    }
+    return null;
+  }
+
+  protected int getNumPrincipalTries(OperationCode[] opCodes,
+      String[] regionNames) {
+    return 5;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/authz-dummy.xml
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/authz-dummy.xml b/gemfire-core/src/test/resources/lib/authz-dummy.xml
new file mode 100644
index 0000000..7f73808
--- /dev/null
+++ b/gemfire-core/src/test/resources/lib/authz-dummy.xml
@@ -0,0 +1,126 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<!DOCTYPE acl PUBLIC "-//GemStone Systems, Inc.//GemFire XML Authorization 1.0//EN"
+              "authz6_0.dtd" >
+<acl>
+
+  <role name="reader">
+    <user>reader0</user>
+    <user>reader1</user>
+    <user>reader2</user>
+    <user>root</user>
+    <user>admin</user>
+    <user>administrator</user>
+  </role>
+
+  <role name="writer">
+    <user>writer0</user>
+    <user>writer1</user>
+    <user>writer2</user>
+    <user>root</user>
+    <user>admin</user>
+    <user>administrator</user>
+  </role>
+
+  <role name="cacheOps">
+    <user>root</user>
+    <user>admin</user>
+    <user>administrator</user>
+  </role>
+
+  <role name="queryRegions">
+    <user>reader3</user>
+    <user>reader4</user>
+  </role>
+
+  <role name="registerInterest">
+    <user>reader5</user>
+    <user>reader6</user>
+  </role>
+
+  <role name="unregisterInterest">
+    <user>reader5</user>
+    <user>reader7</user>
+  </role>
+  
+  <role name="onRegionFunctionExecutor">
+    <user>reader8</user>
+  </role>
+  
+  <role name="onServerFunctionExecutor">
+    <user>reader9</user>
+  </role>
+
+  <permission role="cacheOps">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+    <operation>REGION_CREATE</operation>
+    <operation>REGION_DESTROY</operation>
+  </permission>
+
+  <permission role="reader">
+    <operation>GET</operation>
+    <operation>REGISTER_INTEREST</operation>
+    <operation>UNREGISTER_INTEREST</operation>
+    <operation>KEY_SET</operation>
+    <operation>CONTAINS_KEY</operation>
+    <operation>EXECUTE_FUNCTION</operation>
+  </permission>
+
+  <permission role="writer">
+    <operation>PUT</operation>
+    <operation>PUTALL</operation>
+    <operation>DESTROY</operation>
+    <operation>INVALIDATE</operation>
+    <operation>REGION_CLEAR</operation>
+  </permission>
+
+  <permission role="queryRegions" regions="//Portfolios,/Positions/,AuthRegion">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+  </permission>
+  
+  <permission role="onRegionFunctionExecutor" regions="secureRegion,Positions">
+    <operation>PUT</operation>
+    <operation functionIds="SecureFunction,OptimizationFunction" optimizeForWrite="false" keySet="KEY-0,KEY-1">EXECUTE_FUNCTION</operation>
+  </permission>
+  
+  <permission role="onServerFunctionExecutor" >
+    <operation>PUT</operation>
+    <operation functionIds="SecureFunction,OptimizationFunction">EXECUTE_FUNCTION</operation>
+  </permission>
+
+  <permission role="registerInterest">
+    <operation>REGISTER_INTEREST</operation>
+    <operation>GET</operation>
+  </permission>
+
+  <permission role="unregisterInterest">
+    <operation>UNREGISTER_INTEREST</operation>
+    <operation>GET</operation>
+  </permission>
+
+</acl>

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/authz-ldap.xml
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/authz-ldap.xml b/gemfire-core/src/test/resources/lib/authz-ldap.xml
new file mode 100644
index 0000000..e63c23b
--- /dev/null
+++ b/gemfire-core/src/test/resources/lib/authz-ldap.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<!DOCTYPE acl PUBLIC "-//GemStone Systems, Inc.//GemFire XML Authorization 1.0//EN"
+              "authz5_5.dtd" >
+<acl>
+
+  <role name="reader">
+    <user>gemfire1</user>
+    <user>gemfire2</user>
+    <user>gemfire3</user>
+    <user>gemfire4</user>
+    <user>gemfire5</user>
+  </role>
+
+  <role name="writer">
+    <user>gemfire1</user>
+    <user>gemfire2</user>
+    <user>gemfire6</user>
+    <user>gemfire7</user>
+    <user>gemfire8</user>
+  </role>
+
+  <role name="cacheOps">
+    <user>gemfire1</user>
+    <user>gemfire2</user>
+  </role>
+
+  <role name="queryRegions">
+    <user>gemfire9</user>
+    <user>gemfire10</user>
+  </role>
+
+  <permission role="cacheOps">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+    <operation>REGION_CREATE</operation>
+    <operation>REGION_DESTROY</operation>
+  </permission>
+
+  <permission role="reader">
+    <operation>GET</operation>
+    <operation>REGISTER_INTEREST</operation>
+    <operation>UNREGISTER_INTEREST</operation>
+    <operation>KEY_SET</operation>
+    <operation>CONTAINS_KEY</operation>
+    <operation>EXECUTE_FUNCTION</operation>
+  </permission>
+
+  <permission role="writer">
+    <operation>PUT</operation>
+    <operation>PUTALL</operation>
+    <operation>DESTROY</operation>
+    <operation>INVALIDATE</operation>
+    <operation>REGION_CLEAR</operation>
+  </permission>
+
+  <permission role="queryRegions" regions="Portfolios,/Positions//,/AuthRegion">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+  </permission>
+
+</acl>

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/authz-multiUser-dummy.xml
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/authz-multiUser-dummy.xml b/gemfire-core/src/test/resources/lib/authz-multiUser-dummy.xml
new file mode 100644
index 0000000..0f3bbab
--- /dev/null
+++ b/gemfire-core/src/test/resources/lib/authz-multiUser-dummy.xml
@@ -0,0 +1,106 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<!DOCTYPE acl PUBLIC "-//GemStone Systems, Inc.//GemFire XML Authorization 1.0//EN"
+              "authz6_0.dtd" >
+<acl>
+
+  <role name="reader">
+    <user>user1</user>
+    <user>user2</user>
+    <user>root</user>
+    <user>admin</user>
+    <user>administrator</user>
+  </role>
+
+  <role name="writer">
+    <user>user3</user>
+    <user>user4</user>
+    <user>root</user>
+    <user>admin</user>
+    <user>administrator</user>
+  </role>
+  
+  <role name="cacheOps">
+    <user>user1</user>
+    <user>user2</user>
+    <user>root</user>
+    <user>admin</user>
+    <user>administrator</user>
+  </role>
+
+  <role name="queryRegions">
+    <user>user5</user>
+    <user>user6</user>
+  </role>
+
+  <role name="registerInterest">
+    <user>user7</user>
+    <user>user8</user>
+  </role>
+
+  <role name="unregisterInterest">
+    <user>user5</user>
+    <user>user7</user>
+  </role>
+  
+  <permission role="cacheOps">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+  </permission>
+
+  <permission role="reader">
+    <operation>GET</operation>
+    <operation>REGISTER_INTEREST</operation>
+    <operation>UNREGISTER_INTEREST</operation>
+    <operation>KEY_SET</operation>
+    <operation>CONTAINS_KEY</operation>
+    <operation>EXECUTE_FUNCTION</operation>
+  </permission>
+
+  <permission role="writer">
+    <operation>PUT</operation>
+    <operation>PUTALL</operation>
+    <operation>DESTROY</operation>
+    <operation>INVALIDATE</operation>
+    <operation>REGION_CLEAR</operation>
+  </permission>
+
+  <permission role="queryRegions" regions="//Portfolios,/Positions/,AuthRegion">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+  </permission>
+  
+  <permission role="registerInterest">
+    <operation>REGISTER_INTEREST</operation>
+    <operation>GET</operation>
+  </permission>
+
+  <permission role="unregisterInterest">
+    <operation>UNREGISTER_INTEREST</operation>
+    <operation>GET</operation>
+  </permission>
+
+</acl>

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/authz-multiUser-ldap.xml
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/authz-multiUser-ldap.xml b/gemfire-core/src/test/resources/lib/authz-multiUser-ldap.xml
new file mode 100644
index 0000000..a8e5392
--- /dev/null
+++ b/gemfire-core/src/test/resources/lib/authz-multiUser-ldap.xml
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+<!DOCTYPE acl PUBLIC "-//GemStone Systems, Inc.//GemFire XML Authorization 1.0//EN"
+              "authz5_5.dtd" >
+<acl>
+
+  <role name="reader">
+    <user>gemfire1</user>
+    <user>gemfire2</user>
+    <user>gemfire3</user>
+    <user>gemfire4</user>
+    <user>gemfire5</user>
+  </role>
+
+  <role name="writer">
+    <user>gemfire1</user>
+    <user>gemfire2</user>
+    <user>gemfire6</user>
+    <user>gemfire7</user>
+    <user>gemfire8</user>
+  </role>
+
+  <role name="cacheOps">
+    <user>gemfire1</user>
+    <user>gemfire2</user>
+  </role>
+
+  <role name="queryRegions">
+    <user>gemfire9</user>
+    <user>gemfire10</user>
+  </role>
+
+  <permission role="cacheOps">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+  </permission>
+
+  <permission role="reader">
+    <operation>GET</operation>
+    <operation>REGISTER_INTEREST</operation>
+    <operation>UNREGISTER_INTEREST</operation>
+    <operation>KEY_SET</operation>
+    <operation>CONTAINS_KEY</operation>
+    <operation>EXECUTE_FUNCTION</operation>
+  </permission>
+
+  <permission role="writer">
+    <operation>PUT</operation>
+    <operation>PUTALL</operation>
+    <operation>DESTROY</operation>
+    <operation>INVALIDATE</operation>
+    <operation>REGION_CLEAR</operation>
+  </permission>
+
+  <permission role="queryRegions" regions="Portfolios,/Positions//,/AuthRegion">
+    <operation>QUERY</operation>
+    <operation>EXECUTE_CQ</operation>
+    <operation>STOP_CQ</operation>
+    <operation>CLOSE_CQ</operation>
+  </permission>
+
+</acl>

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire1.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire1.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire1.keystore
new file mode 100644
index 0000000..15270bb
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire1.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire10.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire10.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire10.keystore
new file mode 100644
index 0000000..bb6f827
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire10.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire11.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire11.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire11.keystore
new file mode 100644
index 0000000..6839c74
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire11.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire2.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire2.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire2.keystore
new file mode 100644
index 0000000..fcb7ab8
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire2.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire3.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire3.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire3.keystore
new file mode 100644
index 0000000..19afc4b
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire3.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire4.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire4.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire4.keystore
new file mode 100644
index 0000000..c65916a
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire4.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire5.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire5.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire5.keystore
new file mode 100644
index 0000000..d738cca
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire5.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire6.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire6.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire6.keystore
new file mode 100644
index 0000000..1fea2d3
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire6.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire7.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire7.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire7.keystore
new file mode 100644
index 0000000..7a3187c
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire7.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire8.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire8.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire8.keystore
new file mode 100644
index 0000000..a3bb886
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire8.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/gemfire9.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/gemfire9.keystore b/gemfire-core/src/test/resources/lib/keys/gemfire9.keystore
new file mode 100644
index 0000000..674b4e6
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/gemfire9.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire1.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire1.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire1.keystore
new file mode 100644
index 0000000..4f9120c
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire1.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire10.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire10.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire10.keystore
new file mode 100644
index 0000000..0bd97d7
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire10.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire11.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire11.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire11.keystore
new file mode 100644
index 0000000..62ae3c7
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire11.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire2.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire2.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire2.keystore
new file mode 100644
index 0000000..c65bc81
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire2.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire3.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire3.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire3.keystore
new file mode 100644
index 0000000..b0796e0
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire3.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire4.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire4.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire4.keystore
new file mode 100644
index 0000000..9c94018
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire4.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire5.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire5.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire5.keystore
new file mode 100644
index 0000000..33f6937
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire5.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire6.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire6.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire6.keystore
new file mode 100644
index 0000000..568f674
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire6.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire7.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire7.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire7.keystore
new file mode 100644
index 0000000..80e2d80
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire7.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire8.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire8.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire8.keystore
new file mode 100644
index 0000000..a15def5
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire8.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/gemfire9.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/gemfire9.keystore b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire9.keystore
new file mode 100644
index 0000000..72087f3
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/gemfire9.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/ibm/publickeyfile
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/ibm/publickeyfile b/gemfire-core/src/test/resources/lib/keys/ibm/publickeyfile
new file mode 100644
index 0000000..1b13872
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/ibm/publickeyfile differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/lib/keys/publickeyfile
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/lib/keys/publickeyfile b/gemfire-core/src/test/resources/lib/keys/publickeyfile
new file mode 100644
index 0000000..9c2daa3
Binary files /dev/null and b/gemfire-core/src/test/resources/lib/keys/publickeyfile differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/resources/ssl/untrusted.keystore
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/resources/ssl/untrusted.keystore b/gemfire-core/src/test/resources/ssl/untrusted.keystore
new file mode 100755
index 0000000..aa73eeb
Binary files /dev/null and b/gemfire-core/src/test/resources/ssl/untrusted.keystore differ

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gradle/rat.gradle
----------------------------------------------------------------------
diff --git a/gradle/rat.gradle b/gradle/rat.gradle
index 2068b88..cb6bdfb 100644
--- a/gradle/rat.gradle
+++ b/gradle/rat.gradle
@@ -40,7 +40,7 @@ rat {
     '**/.classpath',
     '**/.settings/**',
     '**/build-eclipse/**',
-    '*.iml',
+    '**/*.iml',
     '.idea/**',
     '**/tags',
 


[4/7] incubator-geode git commit: GEM-164: move the security tests in gemfire-test module inside the com.gemstone.gemfire.security packages to the open side.

Posted by je...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java b/gemfire-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java
new file mode 100644
index 0000000..6cb515a
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java
@@ -0,0 +1,1871 @@
+package com.gemstone.gemfire.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.net.ServerSocketFactory;
+import javax.net.SocketFactory;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLContextSpi;
+import javax.net.ssl.SSLServerSocketFactory;
+import javax.net.ssl.SSLSocketFactory;
+import javax.net.ssl.TrustManager;
+
+import com.gemstone.gemfire.LogWriter;
+import com.gemstone.gemfire.cache.AttributesFactory;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.cache.DataPolicy;
+import com.gemstone.gemfire.cache.DynamicRegionFactory;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.RegionAttributes;
+import com.gemstone.gemfire.cache.Scope;
+import com.gemstone.gemfire.cache.client.NoAvailableServersException;
+import com.gemstone.gemfire.cache.client.Pool;
+import com.gemstone.gemfire.cache.client.PoolFactory;
+import com.gemstone.gemfire.cache.client.PoolManager;
+import com.gemstone.gemfire.cache.client.ServerConnectivityException;
+import com.gemstone.gemfire.cache.client.ServerOperationException;
+import com.gemstone.gemfire.cache.client.ServerRefusedConnectionException;
+import com.gemstone.gemfire.cache.client.internal.PoolImpl;
+import com.gemstone.gemfire.cache.client.internal.ProxyCache;
+import com.gemstone.gemfire.cache.execute.Execution;
+import com.gemstone.gemfire.cache.execute.Function;
+import com.gemstone.gemfire.cache.execute.FunctionException;
+import com.gemstone.gemfire.cache.execute.FunctionService;
+import com.gemstone.gemfire.cache.query.Query;
+import com.gemstone.gemfire.cache.query.QueryInvocationTargetException;
+import com.gemstone.gemfire.cache.query.SelectResults;
+import com.gemstone.gemfire.cache.server.CacheServer;
+import com.gemstone.gemfire.cache30.ClientServerTestCase;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.Locator;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.internal.AvailablePort;
+import com.gemstone.gemfire.internal.logging.InternalLogWriter;
+import com.gemstone.gemfire.internal.logging.PureLogWriter;
+import com.gemstone.gemfire.internal.util.Callable;
+
+import dunit.DistributedTestCase;
+
+/**
+ * Contains utility methods for setting up servers/clients for authentication
+ * and authorization tests.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public class SecurityTestUtil extends DistributedTestCase {
+
+  public SecurityTestUtil(String name) {
+    super(name);
+  }
+
+  private static Locator locator = null;
+
+  private static Cache cache = null;
+
+  private static Properties currentJavaProps = null;
+
+  private static String locatorString = null;
+
+  private static Integer mcastPort = null;
+
+  public static final int NO_EXCEPTION = 0;
+
+  public static final int AUTHREQ_EXCEPTION = 1;
+
+  public static final int AUTHFAIL_EXCEPTION = 2;
+
+  public static final int CONNREFUSED_EXCEPTION = 3;
+
+  public static final int NOTAUTHZ_EXCEPTION = 4;
+
+  public static final int OTHER_EXCEPTION = 5;
+  
+  public static final int NO_AVAILABLE_SERVERS = 6;
+
+  // Indicates that AuthReqException may not necessarily be thrown
+  public static final int NOFORCE_AUTHREQ_EXCEPTION = 16;
+
+  protected static final String regionName = "AuthRegion";
+
+  protected static final String[] keys = { "key1", "key2", "key3", "key4",
+      "key5", "key6", "key7", "key8" };
+
+  protected static final String[] values = { "value1", "value2", "value3",
+      "value4", "value5", "value6", "value7", "value8" };
+
+  protected static final String[] nvalues = { "nvalue1", "nvalue2", "nvalue3",
+      "nvalue4", "nvalue5", "nvalue6", "nvalue7", "nvalue8" };
+
+  static String[] expectedExceptions = null;
+
+  private static Pool pool = null;
+
+  private static boolean multiUserAuthMode = false;
+
+  private static final int numberOfUsers = 1;
+
+  static ProxyCache[] proxyCaches = new ProxyCache[numberOfUsers];
+
+  private static Region regionRef = null;
+
+  public static void addExpectedExceptions(String[] expectedExceptions,
+      LogWriter logger) {
+    if (expectedExceptions != null) {
+      for (int index = 0; index < expectedExceptions.length; index++) {
+        logger.info("<ExpectedException action=add>"
+            + expectedExceptions[index] + "</ExpectedException>");
+      }
+    }
+  }
+
+  public static void removeExpectedExceptions(String[] expectedExceptions,
+      LogWriter logger) {
+    if (expectedExceptions != null) {
+      for (int index = 0; index < expectedExceptions.length; index++) {
+        logger.info("<ExpectedException action=remove>"
+            + expectedExceptions[index] + "</ExpectedException>");
+      }
+    }
+  }
+
+  public static void setJavaProps(Properties javaProps) {
+
+    removeJavaProperties(currentJavaProps);
+    addJavaProperties(javaProps);
+    currentJavaProps = javaProps;
+  }
+
+  public DistributedSystem createSystem(Properties sysProps, Properties javaProps) {
+
+    closeCache();
+    clearStaticSSLContext();
+    setJavaProps(javaProps);
+
+    DistributedSystem dsys = getSystem(sysProps);
+    assertNotNull(dsys);
+    addExpectedExceptions(SecurityTestUtil.expectedExceptions, system
+        .getLogWriter());
+    return dsys;
+  }
+
+  void openCache() {
+
+    assertNotNull(system);
+    assertTrue(system.isConnected());
+    cache = CacheFactory.create(system);
+    assertNotNull(cache);
+  }
+
+  private static void initClientDynamicRegionFactory(String poolName) {
+
+    DynamicRegionFactory.get().open(
+        new DynamicRegionFactory.Config(null, poolName, false,true));
+  }
+
+  public static void initDynamicRegionFactory() {
+
+    DynamicRegionFactory.get().open(
+        new DynamicRegionFactory.Config(null, null, false, true));
+  }
+
+  public static Integer getLocatorPort() {
+
+    Integer locatorPort = new Integer(AvailablePort
+        .getRandomAvailablePort(AvailablePort.SOCKET));
+    String addr = DistributedTestCase.getIPLiteral();
+    if (locatorString == null) {
+      locatorString = addr + "[" + locatorPort + ']';
+    }
+    else {
+      locatorString += "," + addr + "[" + locatorPort + ']';
+    }
+    return locatorPort;
+  }
+
+  /**
+   * Note that this clears the string after returning for convenience in reusing
+   * for other tests. Hence it should normally be invoked only once for a test.
+   */
+  public static String getLocatorString() {
+
+    String locString = locatorString;
+    locatorString = null;
+    return locString;
+  }
+
+  public static Properties concatProperties(Properties[] propsList) {
+
+    Properties props = new Properties();
+    for (int index = 0; index < propsList.length; ++index) {
+      if (propsList[index] != null) {
+        props.putAll(propsList[index]);
+      }
+    }
+    return props;
+  }
+
+  public static void registerExpectedExceptions(String[] expectedExceptions) {
+    SecurityTestUtil.expectedExceptions = expectedExceptions;
+  }
+
+  private static void addJavaProperties(Properties javaProps) {
+
+    if (javaProps != null) {
+      Iterator iter = javaProps.entrySet().iterator();
+      while (iter.hasNext()) {
+        Map.Entry entry = (Map.Entry)iter.next();
+        System.setProperty((String)entry.getKey(), (String)entry.getValue());
+      }
+    }
+  }
+
+  private static void removeJavaProperties(Properties javaProps) {
+
+    if (javaProps != null) {
+      Properties props = System.getProperties();
+      Iterator iter = javaProps.keySet().iterator();
+      while (iter.hasNext()) {
+        props.remove(iter.next());
+      }
+      System.setProperties(props);
+    }
+  }
+
+  public static Integer createCacheServer(Properties authProps,
+      Object javaProps, Integer dsPort, String locatorString,
+      Integer serverPort, Integer expectedResult) {
+
+    return createCacheServer(authProps, javaProps, dsPort, locatorString,
+        serverPort, Boolean.FALSE, expectedResult);
+  }
+
+  public static Integer createCacheServer(Properties authProps,
+      Object javaProps, Integer locatorPort, String locatorString,
+      Integer serverPort, Boolean setupDynamicRegionFactory,
+      Integer expectedResult) {
+
+    if (authProps == null) {
+      authProps = new Properties();
+    }
+    authProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    if (locatorString != null && locatorString.length() > 0) {
+      authProps.setProperty(DistributionConfig.LOCATORS_NAME, locatorString);
+      if (locatorPort != null) {
+        authProps.setProperty(DistributionConfig.START_LOCATOR_NAME,
+            DistributedTestCase.getIPLiteral() + "[" + locatorPort.toString() + ']');
+      }
+    } else {
+      authProps.setProperty("locators", "localhost["+getDUnitLocatorPort()+"]");
+    }
+    authProps.setProperty(DistributionConfig.SECURITY_LOG_LEVEL_NAME, "finest");
+    getLogWriter().info("Set the server properties to: " + authProps);
+    getLogWriter().info("Set the java properties to: " + javaProps);
+
+    SecurityTestUtil tmpInstance = new SecurityTestUtil("temp");
+    try {
+      tmpInstance.createSystem(authProps, (Properties)javaProps);
+      if (expectedResult.intValue() != NO_EXCEPTION) {
+        fail("Expected a security exception when starting peer");
+      }
+    }
+    catch (AuthenticationRequiredException ex) {
+      if (expectedResult.intValue() == AUTHREQ_EXCEPTION) {
+        getLogWriter().info("Got expected exception when starting peer: " + ex);
+        return new Integer(0);
+      }
+      else {
+        fail("Got unexpected exception when starting peer", ex);
+      }
+    }
+    catch (AuthenticationFailedException ex) {
+      if (expectedResult.intValue() == AUTHFAIL_EXCEPTION) {
+        getLogWriter().info("Got expected exception when starting peer: " + ex);
+        return new Integer(0);
+      }
+      else {
+        fail("Got unexpected exception when starting peer", ex);
+      }
+    }
+    catch (Exception ex) {
+      fail("Got unexpected exception when starting peer", ex);
+    }
+
+    if (setupDynamicRegionFactory.booleanValue()) {
+      initDynamicRegionFactory();
+    }
+    tmpInstance.openCache();
+    AttributesFactory factory = new AttributesFactory();
+    factory.setScope(Scope.DISTRIBUTED_ACK);
+    factory.setDataPolicy(DataPolicy.REPLICATE);
+    RegionAttributes attrs = factory.create();
+    cache.createRegion(regionName, attrs);
+    int port;
+    if (serverPort == null || serverPort.intValue() <= 0) {
+      port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+    }
+    else {
+      port = serverPort.intValue();
+    }
+    CacheServer server1 = cache.addCacheServer();
+    server1.setPort(port);
+    server1.setNotifyBySubscription(true);
+    try {
+      server1.start();
+    }
+    catch (Exception ex) {
+      fail("Got unexpected exception when starting CacheServer", ex);
+    }
+    return new Integer(server1.getPort());
+  }
+
+  public static void createCacheClient(String authInitModule,
+      Properties authProps, Properties javaProps, Integer[] ports,
+      Object numConnections, Integer expectedResult) {
+    createCacheClient(authInitModule, authProps, javaProps, ports,
+        numConnections, "false", expectedResult);
+  }
+
+  public static void createCacheClient(String authInitModule,
+      Properties authProps, Properties javaProps, Integer[] ports,
+      Object numConnections, String multiUserMode, Integer expectedResult) {
+    createCacheClient(authInitModule, authProps, javaProps, ports,
+        (Integer)numConnections, Boolean.FALSE, multiUserMode, expectedResult);
+  }
+
+  public static void createCacheClient(String authInitModule,
+      Properties authProps, Properties javaProps, Integer[] ports,
+      Integer numConnections, Boolean setupDynamicRegionFactory,
+      Integer expectedResult) {
+    createCacheClient(authInitModule, authProps, javaProps, ports,
+        numConnections, setupDynamicRegionFactory, "false", expectedResult);
+  }
+
+  public static void createCacheClient(String authInitModule,
+      Properties authProps, Properties javaProps, Integer[] ports,
+      Integer numConnections, Boolean setupDynamicRegionFactory,
+      String multiUserMode, Integer expectedResult) {
+    createCacheClient(authInitModule, authProps, javaProps, ports,
+        numConnections, setupDynamicRegionFactory, multiUserMode, Boolean.TRUE,
+        expectedResult);
+  }
+
+  public static void createCacheClient(String authInitModule,
+      Properties authProps, Properties javaProps, Integer[] ports,
+      Integer numConnections, Boolean setupDynamicRegionFactory,
+      String multiUserMode, Boolean subscriptionEnabled,
+      Integer expectedResult) {
+
+    multiUserAuthMode = Boolean.valueOf(multiUserMode);
+    if (authProps == null) {
+      authProps = new Properties();
+    }
+    authProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    authProps.setProperty(DistributionConfig.LOCATORS_NAME, "");
+    authProps.setProperty(DistributionConfig.SECURITY_LOG_LEVEL_NAME, "finest");
+    // TODO (ashetkar) Add " && (!multiUserAuthMode)" below.
+    if (authInitModule != null) {
+      authProps.setProperty(DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME,
+          authInitModule);
+    }
+
+    SecurityTestUtil tmpInstance = new SecurityTestUtil("temp");
+    tmpInstance.createSystem(authProps, javaProps);
+    AttributesFactory factory = new AttributesFactory();
+    int[] portsI = new int[ports.length];
+    for(int z=0;z<ports.length;z++) {
+      portsI[z] = ports[z].intValue();
+    }
+   
+    try {
+      PoolFactory poolFactory = PoolManager.createFactory();
+      poolFactory.setRetryAttempts(200);
+      if (multiUserAuthMode) {
+        poolFactory.setMultiuserAuthentication(multiUserAuthMode);
+        // [sumedh] Why is this false here only to be overridden in
+        // ClientServerTestCase.configureConnectionPoolWithNameAndFactory below?
+        // Actually setting it to false causes MultiuserAPIDUnitTest to fail.
+        //poolFactory.setSubscriptionEnabled(false);
+      }
+      pool = ClientServerTestCase.configureConnectionPoolWithNameAndFactory(factory,
+          DistributedTestCase.getIPLiteral(), portsI, subscriptionEnabled, 0,
+          numConnections == null ? -1 : numConnections.intValue(), null, null,
+          poolFactory);
+
+      if (setupDynamicRegionFactory.booleanValue()) {
+        initClientDynamicRegionFactory(pool.getName());
+      }
+      tmpInstance.openCache();
+      try {
+        getLogWriter().info("multi-user mode " + multiUserAuthMode);
+        proxyCaches[0] = (ProxyCache)((PoolImpl) pool).createAuthenticatedCacheView(authProps);
+        if (!multiUserAuthMode) {
+          fail("Expected a UnsupportedOperationException but got none in single-user mode");
+        }
+      } catch (UnsupportedOperationException uoe) {
+        if (!multiUserAuthMode) {
+          getLogWriter().info("Got expected UnsupportedOperationException in single-user mode");
+        }
+        else {
+          fail("Got unexpected exception in multi-user mode ", uoe);
+        }
+      }
+
+      factory.setScope(Scope.LOCAL);
+      if (multiUserAuthMode) {
+        factory.setDataPolicy(DataPolicy.EMPTY);
+      }
+      RegionAttributes attrs = factory.create();
+      cache.createRegion(regionName, attrs);
+
+      if (expectedResult.intValue() != NO_EXCEPTION
+          && expectedResult.intValue() != NOFORCE_AUTHREQ_EXCEPTION) {
+        if (!multiUserAuthMode) {
+          fail("Expected an exception when starting client");
+        }
+      }
+    }
+    catch (AuthenticationRequiredException ex) {
+      if (expectedResult.intValue() == AUTHREQ_EXCEPTION
+          || expectedResult.intValue() == NOFORCE_AUTHREQ_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when starting client: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when starting client", ex);
+      }
+    }
+    catch (AuthenticationFailedException ex) {
+      if (expectedResult.intValue() == AUTHFAIL_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when starting client: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when starting client", ex);
+      }
+    }
+    catch (ServerRefusedConnectionException ex) {
+      if (expectedResult.intValue() == CONNREFUSED_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when starting client: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when starting client", ex);
+      }
+    }
+    catch (Exception ex) {
+      fail("Got unexpected exception when starting client", ex);
+    }
+  }
+
+  public static void createCacheClientForMultiUserMode(Integer numOfUsers,
+      String authInitModule, Properties[] authProps, Properties javaProps,
+      Integer[] ports, Integer numConnections,
+      Boolean setupDynamicRegionFactory, Integer expectedResult) {
+    createCacheClientForMultiUserMode(numOfUsers, authInitModule, authProps,
+        javaProps, ports, numConnections, setupDynamicRegionFactory, null,
+        expectedResult);
+  }
+
+  public static void createCacheClientForMultiUserMode(Integer numOfUsers,
+      String authInitModule, Properties[] authProps, Properties javaProps,
+      Integer[] ports, Integer numConnections,
+      Boolean setupDynamicRegionFactory, String durableClientId,
+      Integer expectedResult) {
+
+    if (numOfUsers == null || numOfUsers < 1) {
+      fail("Number of users cannot be less than one");
+    }
+    multiUserAuthMode = true;
+    // Assert that number of users == length of arrays of the provided params
+//    if (numOfUsers != authInitModules.length) {
+//      fail("Number of authInitModules provided does not match with numOfUsers specified, "
+//          + authInitModules.length);
+//    }
+    if (numOfUsers != authProps.length) {
+      fail("Number of authProps provided does not match with numOfUsers specified, "
+          + authProps.length);
+    }
+//    if (numOfUsers != javaProps.length) {
+//      fail("Number of javaProps provided does not match with numOfUsers specified, "
+//          + javaProps.length);
+//    }
+//    if (numOfUsers != expectedResult.length) {
+//      fail("Number of expectedResult provided does not match with numOfUsers specified, "
+//          + expectedResult.length);
+//    }
+    if (authProps[0] == null) {
+      authProps[0] = new Properties();
+    }
+    authProps[0].setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+    authProps[0].setProperty(DistributionConfig.LOCATORS_NAME, "");
+    authProps[0].setProperty(DistributionConfig.SECURITY_LOG_LEVEL_NAME,
+        "finest");
+    Properties props = new Properties();
+    if (authInitModule != null) {
+      authProps[0].setProperty(
+          DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME, authInitModule);
+      props.setProperty(DistributionConfig.SECURITY_CLIENT_AUTH_INIT_NAME,
+          authInitModule);
+    }
+    if (durableClientId != null) {
+      props.setProperty(DistributionConfig.DURABLE_CLIENT_ID_NAME,
+          durableClientId);
+      props.setProperty(DistributionConfig.DURABLE_CLIENT_TIMEOUT_NAME, String
+          .valueOf(DistributionConfig.DEFAULT_DURABLE_CLIENT_TIMEOUT));
+    }
+
+    SecurityTestUtil tmpInstance = new SecurityTestUtil("temp");
+    tmpInstance.createSystem(props, javaProps);
+    AttributesFactory factory = new AttributesFactory();
+    int[] portsI = new int[ports.length];
+    for(int z=0;z<ports.length;z++) {
+      portsI[z] = ports[z].intValue();
+    }
+   
+    try {
+      tmpInstance.openCache();
+      PoolFactory poolFactory = PoolManager.createFactory();
+      poolFactory.setRetryAttempts(200);
+      poolFactory.setMultiuserAuthentication(multiUserAuthMode);
+      poolFactory.setSubscriptionEnabled(true);
+      pool = ClientServerTestCase.configureConnectionPoolWithNameAndFactory(factory,
+          DistributedTestCase.getIPLiteral(), portsI, true, 1,
+          numConnections == null ? -1 : numConnections.intValue(), null, null,
+          poolFactory);
+
+      if (setupDynamicRegionFactory.booleanValue()) {
+        initClientDynamicRegionFactory(pool.getName());
+      }
+      proxyCaches = new ProxyCache[numOfUsers];
+      for (int i=0; i<numOfUsers; i++) {
+        proxyCaches[i] = (ProxyCache)((PoolImpl) pool).createAuthenticatedCacheView(authProps[i]);
+      }
+
+      factory.setScope(Scope.LOCAL);
+      factory.setDataPolicy(DataPolicy.EMPTY);
+      RegionAttributes attrs = factory.create();
+      cache.createRegion(regionName, attrs);
+
+      if (expectedResult.intValue() != NO_EXCEPTION
+          && expectedResult.intValue() != NOFORCE_AUTHREQ_EXCEPTION) {
+        if (!multiUserAuthMode) {
+          fail("Expected an exception when starting client");
+        }
+      }
+    }
+    catch (AuthenticationRequiredException ex) {
+      if (expectedResult.intValue() == AUTHREQ_EXCEPTION
+          || expectedResult.intValue() == NOFORCE_AUTHREQ_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when starting client: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when starting client", ex);
+      }
+    }
+    catch (AuthenticationFailedException ex) {
+      if (expectedResult.intValue() == AUTHFAIL_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when starting client: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when starting client", ex);
+      }
+    }
+    catch (ServerRefusedConnectionException ex) {
+      if (expectedResult.intValue() == CONNREFUSED_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when starting client: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when starting client", ex);
+      }
+    }
+    catch (Exception ex) {
+      fail("Got unexpected exception when starting client", ex);
+    }
+  }
+
+  public static void createProxyCache(Integer[] userIndices, Properties[] props) {
+    int j = 0;
+    for (int i : userIndices) {
+      SecurityTestUtil.proxyCaches[i] = (ProxyCache)((PoolImpl) SecurityTestUtil.pool)
+          .createAuthenticatedCacheView(props[j]);
+      j++;
+    }
+  }
+
+  public static void stopCacheServers() {
+    Iterator iter = getCache().getCacheServers().iterator();
+    if (iter.hasNext()) {
+      CacheServer server = (CacheServer)iter.next();
+      server.stop();
+      assertFalse(server.isRunning());
+    }
+  }
+
+  public static void restartCacheServers() {
+    Iterator iter = getCache().getCacheServers().iterator();
+    if (iter.hasNext()) {
+      CacheServer server = (CacheServer)iter.next();
+      try {
+        server.start();
+      }
+      catch (Exception ex) {
+        fail("Unexpected exception when restarting cache servers", ex);
+      }
+      assertTrue(server.isRunning());
+    }
+  }
+
+  public static void startLocator(String name, Integer port, Object extraProps,
+      Object javaProps, String[] expectedExceptions) {
+
+    File logFile = new File(name + "-locator" + port.intValue() + ".log");
+    try {
+      Properties authProps = new Properties();
+      if (extraProps != null) {
+        authProps.putAll((Properties)extraProps);
+      }
+      authProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+      authProps.setProperty(DistributionConfig.LOCATORS_NAME, 
+                            DistributedTestCase.getIPLiteral() + "[" + port + "]");
+      authProps.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+      clearStaticSSLContext();
+      setJavaProps((Properties)javaProps);
+      FileOutputStream logOut = new FileOutputStream(logFile);
+      PrintStream logStream = new PrintStream(logOut);
+      LogWriter logger = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL,
+          logStream);
+      addExpectedExceptions(expectedExceptions, logger);
+      logStream.flush();
+      locator = Locator.startLocatorAndDS(port.intValue(), logFile, null,
+          authProps);
+    }
+    catch (IOException ex) {
+      fail("While starting locator on port " + port.intValue(), ex);
+    }
+  }
+
+  public static void stopLocator(Integer port, String[] expectedExceptions) {
+
+    try {
+      locator.stop();
+      removeExpectedExceptions(expectedExceptions, locator
+          .getDistributedSystem().getLogWriter());
+    }
+    catch (Exception ex) {
+      fail("While stopping locator on port " + port.intValue(), ex);
+    }
+  }
+
+  public static Cache getCache() {
+    return cache;
+  }
+
+  // Some useful region methods used by security tests
+
+  public static void waitForCondition(Callable cond) {
+    waitForCondition(cond, 100, 120);
+  }
+
+  public static void waitForCondition(final Callable cond, int sleepMillis,
+      int numTries) {
+    WaitCriterion ev = new WaitCriterion() {
+      public boolean done() {
+        try {
+          return ((Boolean)cond.call()).booleanValue();
+        }
+        catch (Exception e) {
+          fail("Unexpected exception", e);
+        }
+        return false; // NOTREACHED
+      }
+      public String description() {
+        return null;
+      }
+    };
+    DistributedTestCase.waitForCriterion(ev, sleepMillis * numTries, 200, true);
+  }
+
+  public static Object getLocalValue(Region region, Object key) {
+
+    Region.Entry entry = region.getEntry(key);
+    return (entry != null ? entry.getValue() : null);
+  }
+
+  public static void doProxyCacheClose() {
+    for (int i=0; i<proxyCaches.length; i++) {
+      proxyCaches[i].close();
+    }
+  }
+
+  private static void doPutsP(Integer num, Integer expectedResult,
+      boolean newVals) {
+    doPutsP(num, Integer.valueOf(0), expectedResult, newVals);
+  }
+
+  private static void doPutsP(Integer num, Integer multiUserIndex,
+      Integer expectedResult, boolean newVals) {
+
+    assertTrue(num.intValue() <= keys.length);
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+        regionRef = region;
+      }
+      else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing puts: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing puts", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      try {
+        if (newVals) {
+          region.put(keys[index], nvalues[index]);
+        }
+        else {
+          region.put(keys[index], values[index]);
+        }
+        if (expectedResult.intValue() != NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing puts");
+        }
+      }
+      catch(NoAvailableServersException ex) {
+        if(expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing puts: "
+              + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        if ((expectedResult.intValue() == AUTHREQ_EXCEPTION)
+            && (ex.getCause() instanceof AuthenticationRequiredException)) {
+          getLogWriter().info(
+              "Got expected AuthenticationRequiredException when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        if ((expectedResult.intValue() == AUTHFAIL_EXCEPTION)
+            && (ex.getCause() instanceof AuthenticationFailedException)) {
+          getLogWriter().info(
+              "Got expected AuthenticationFailedException when doing puts: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing puts: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing puts: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing puts", ex);
+        }
+      }
+    }
+  }
+
+  private static void doGetAllP(Integer multiUserIndex,
+      Integer expectedResult, boolean useTX) {
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      }
+      else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing getAll: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing getAll", ex);
+      }
+    }
+    try {
+      List keys = new ArrayList();
+      keys.add("key1");
+      keys.add("key2");
+      if (useTX) {
+        getCache().getCacheTransactionManager().begin();
+      }
+      Map entries = region.getAll(keys);
+      // Also check getEntry()
+      region.getEntry("key1");
+      if (useTX) {
+        getCache().getCacheTransactionManager().commit();
+      }
+      assertNotNull(entries);
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)) {
+        assertEquals(0, entries.size());
+      } else if ((expectedResult.intValue() == NO_EXCEPTION)) {
+        assertEquals(2, entries.size());
+        assertEquals("value1", entries.get("key1"));
+        assertEquals("value2", entries.get("key2"));
+      }
+    } catch (NoAvailableServersException ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+        getLogWriter().info(
+            "Got expected NoAvailableServers when doing getAll: "
+                + ex.getCause());
+      } else {
+        fail("Got unexpected exception when doing getAll", ex);
+      }
+    } catch (ServerConnectivityException ex) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && (ex.getCause() instanceof NotAuthorizedException)) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when doing getAll: "
+                + ex.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing getAll: " + ex);
+      } else {
+        fail("Got unexpected exception when doing getAll", ex);
+      }
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing getAll: " + ex);
+      } else {
+        fail("Got unexpected exception when doing getAll", ex);
+      }
+    }
+  }
+
+  private static void doGetsP(Integer num, Integer expectedResult,
+      boolean newVals) {
+    doGetsP(num, Integer.valueOf(0), expectedResult, newVals);
+  }
+
+  private static void doGetsP(Integer num, Integer multiUserIndex,
+      Integer expectedResult, boolean newVals) {
+
+    assertTrue(num.intValue() <= keys.length);
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      }
+      else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing gets: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing gets", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      Object value = null;
+      try {
+        try {
+          region.localInvalidate(keys[index]);
+        }
+        catch (Exception ex) {
+        }
+        value = region.get(keys[index]);
+        if (expectedResult.intValue() != NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing gets");
+        }
+      }
+      catch(NoAvailableServersException ex) {
+        if(expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing gets: "
+              + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing gets", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing gets: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing gets: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing gets", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing gets: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing gets", ex);
+        }
+      }
+      assertNotNull(value);
+      if (newVals) {
+        assertEquals(nvalues[index], value);
+      }
+      else {
+        assertEquals(values[index], value);
+      }
+    }
+  }
+
+  private static void doLocalGetsP(int num, boolean checkNVals) {
+
+    assertTrue(num <= keys.length);
+    String[] vals = values;
+    if (checkNVals) {
+      vals = nvalues;
+    }
+    final Region region = getCache().getRegion(regionName);
+    assertNotNull(region);
+    for (int index = 0; index < num; ++index) {
+      final String key = keys[index];
+      final String expectedVal = vals[index];
+      waitForCondition(new Callable() {
+        public Object call() throws Exception {
+          Object value = getLocalValue(region, key);
+          return Boolean.valueOf(expectedVal.equals(value));
+        }
+      }, 1000, 30 / num);
+    }
+    for (int index = 0; index < num; ++index) {
+      Region.Entry entry = region.getEntry(keys[index]);
+      assertNotNull(entry);
+      assertEquals(vals[index], entry.getValue());
+    }
+  }
+
+  private static void doRegionDestroysP(Integer multiuserIndex,
+      Integer expectedResult) {
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiuserIndex].getRegion(regionName);
+      } else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when doing region destroy: " + ex);
+      } else {
+        fail("Got unexpected exception when doing region destroy", ex);
+      }
+    }
+
+    try {
+      region.destroyRegion();
+      if (expectedResult.intValue() != NO_EXCEPTION) {
+        fail("Expected a NotAuthorizedException while doing region destroy");
+      }
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiuserIndex].getRegion(regionName);
+      } else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNull(region);
+    } catch (NoAvailableServersException ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+        getLogWriter().info(
+            "Got expected NoAvailableServers when doing region destroy: "
+                + ex.getCause());
+      } else {
+        fail("Got unexpected exception when doing region destroy", ex);
+      }
+    } catch (ServerConnectivityException ex) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && (ex.getCause() instanceof NotAuthorizedException)) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when doing region destroy: "
+                + ex.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when doing region destroy: " + ex);
+      } else {
+        fail("Got unexpected exception when doing region destroy", ex);
+      }
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when doing region destroy: " + ex);
+      } else {
+        fail("Got unexpected exception when doing region destroy", ex);
+      }
+    }
+  }
+  
+  private static void doDestroysP(Integer num, Integer multiUserIndex,
+      Integer expectedResult, boolean newVals) {
+
+    assertTrue(num.intValue() <= keys.length);
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      }
+      else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing destroys: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing destroys", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      try {
+        region.destroy(keys[index]);
+        if (expectedResult.intValue() != NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing destroys");
+        }
+      }
+      catch(NoAvailableServersException ex) {
+        if(expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing destroys: "
+              + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing destroys", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing destroys: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing destroys: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing destroys", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing destroys: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing destroys", ex);
+        }
+      }
+    }
+  }
+
+  private static void doInvalidatesP(Integer num, Integer multiUserIndex,
+      Integer expectedResult, boolean newVals) {
+
+    assertTrue(num.intValue() <= keys.length);
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      }
+      else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing invalidates: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing invalidates", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      try {
+        region.invalidate(keys[index]);
+        if (expectedResult.intValue() != NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing invalidates");
+        }
+      }
+      catch(NoAvailableServersException ex) {
+        if(expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing invalidates: "
+              + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing invalidates", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing invalidates: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing invalidates: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing invalidates", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing invalidates: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing invalidates", ex);
+        }
+      }
+    }
+  }
+
+  private static void doContainsKeysP(Integer num, Integer multiUserIndex,
+      Integer expectedResult, boolean newVals, boolean expectedValue) {
+
+    assertTrue(num.intValue() <= keys.length);
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      }
+      else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    }
+    catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing containsKey: " + ex);
+      }
+      else {
+        fail("Got unexpected exception when doing containsKey", ex);
+      }
+    }
+    for (int index = 0; index < num.intValue(); ++index) {
+      boolean result = false;
+      try {
+        result = region.containsKeyOnServer(keys[index]);
+        if (expectedResult.intValue() != NO_EXCEPTION) {
+          fail("Expected a NotAuthorizedException while doing containsKey");
+        }
+      }
+      catch(NoAvailableServersException ex) {
+        if(expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+          getLogWriter().info(
+              "Got expected NoAvailableServers when doing containsKey: "
+              + ex.getCause());
+          continue;
+        }
+        else {
+          fail("Got unexpected exception when doing containsKey", ex);
+        }
+      }
+      catch (ServerConnectivityException ex) {
+        if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+            && (ex.getCause() instanceof NotAuthorizedException)) {
+          getLogWriter().info(
+              "Got expected NotAuthorizedException when doing containsKey: "
+                  + ex.getCause());
+          continue;
+        }
+        else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing containsKey: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing containsKey", ex);
+        }
+      }
+      catch (Exception ex) {
+        if (expectedResult.intValue() == OTHER_EXCEPTION) {
+          getLogWriter().info("Got expected exception when doing containsKey: " + ex);
+        }
+        else {
+          fail("Got unexpected exception when doing containsKey", ex);
+        }
+      }
+      assertEquals(expectedValue, result);
+    }
+  }
+
+  private static void doQueriesP(Integer multiUserIndex,
+      Integer expectedResult, Integer expectedValue) {
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      } else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing queries: " + ex);
+      } else {
+        fail("Got unexpected exception when doing queries", ex);
+      }
+    }
+    String queryStr = "SELECT DISTINCT * FROM " + region.getFullPath();
+    try {
+      SelectResults queryResults = region.query(queryStr);
+      Set resultSet = queryResults.asSet();
+      assertEquals(expectedValue.intValue(), resultSet.size());
+      if (expectedResult.intValue() != NO_EXCEPTION) {
+        fail("Expected a NotAuthorizedException while doing queries");
+      }
+    } catch (NoAvailableServersException ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+        getLogWriter().info(
+            "Got expected NoAvailableServers when doing queries: "
+                + ex.getCause());
+      } else {
+        fail("Got unexpected exception when doing queries", ex);
+      }
+    } catch (ServerConnectivityException ex) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && (ex.getCause() instanceof NotAuthorizedException)) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when doing queries: "
+                + ex.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing queries: " + ex);
+      } else {
+        fail("Got unexpected exception when doing queries", ex);
+      }
+    } catch (QueryInvocationTargetException qite) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && (qite.getCause() instanceof NotAuthorizedException)) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when doing queries: "
+                + qite.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing queries: " + qite);
+      } else {
+        fail("Got unexpected exception when doing queries", qite);
+      }
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info("Got expected exception when doing queries: " + ex);
+      } else {
+        fail("Got unexpected exception when doing queries", ex);
+      }
+    }
+  }
+
+  private static void doFunctionExecuteP(Integer multiUserIndex,
+      Function function, Integer expectedResult, Object expectedValue,
+      String method) {
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      } else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing function: " + ex);
+      } else {
+        fail("Got unexpected exception when executing function", ex);
+      }
+    }
+    try {
+      FunctionService.registerFunction(function);
+      Execution execution = null;
+      if ("region".equals(method)) {
+        execution = FunctionService.onRegion(region);
+      } else if ("server".equals(method)) {
+        if (multiUserAuthMode) {
+          execution = FunctionService.onServer(proxyCaches[multiUserIndex]);
+        } else {
+          execution = FunctionService.onServer(pool);
+        }
+      } else { // if ("servers".equals(method)) {
+        if (multiUserAuthMode) {
+          execution = FunctionService.onServers(proxyCaches[multiUserIndex]);
+        } else {
+          execution = FunctionService.onServers(pool);
+        }
+      }
+      execution.execute(function.getId());
+      if (expectedResult.intValue() != NO_EXCEPTION) {
+        fail("Expected a NotAuthorizedException while executing function");
+      }
+    } catch (NoAvailableServersException ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+        getLogWriter().info(
+            "Got expected NoAvailableServers when executing function: "
+                + ex.getCause());
+      } else {
+        fail("Got unexpected exception when executing function", ex);
+      }
+    } catch (ServerConnectivityException ex) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && (ex.getCause() instanceof NotAuthorizedException)) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when executing function: "
+                + ex.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing function: " + ex);
+      } else {
+        fail("Got unexpected exception when executing function", ex);
+      }
+    } catch (FunctionException ex) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && ((ex.getCause() instanceof NotAuthorizedException) || ((ex
+              .getCause() instanceof ServerOperationException) && (((ServerOperationException)ex
+              .getCause()).getCause() instanceof NotAuthorizedException)))) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when executing function: "
+                + ex.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing function: " + ex);
+      } else {
+        fail("Got unexpected exception when executing function", ex);
+      }
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing function: " + ex);
+      } else {
+        fail("Got unexpected exception when executing function", ex);
+      }
+    }
+  }
+
+  private static void doQueryExecuteP(Integer multiUserIndex,
+      Integer expectedResult, Integer expectedValue) {
+    Region region = null;
+    try {
+      if (multiUserAuthMode) {
+        region = proxyCaches[multiUserIndex].getRegion(regionName);
+      } else {
+        region = getCache().getRegion(regionName);
+      }
+      assertNotNull(region);
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing query: " + ex);
+      } else {
+        fail("Got unexpected exception when executing query", ex);
+      }
+    }
+    try {
+      String queryString = "SELECT DISTINCT * FROM " + region.getFullPath();
+      Query query = null;
+      if (multiUserAuthMode) {
+        query = proxyCaches[multiUserIndex].getQueryService().newQuery(queryString);
+      }
+      else {
+        region.getCache().getQueryService().newQuery(queryString);
+      }
+      SelectResults result = (SelectResults)query.execute();
+      if (expectedResult.intValue() != NO_EXCEPTION) {
+        fail("Expected a NotAuthorizedException while executing function");
+      }
+      assertEquals(expectedValue.intValue(), result.asList().size());
+    } catch (NoAvailableServersException ex) {
+      if (expectedResult.intValue() == SecurityTestUtil.NO_AVAILABLE_SERVERS) {
+        getLogWriter().info(
+            "Got expected NoAvailableServers when executing query: "
+                + ex.getCause());
+      } else {
+        fail("Got unexpected exception when executing query", ex);
+      }
+    } catch (ServerConnectivityException ex) {
+      if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
+          && (ex.getCause() instanceof NotAuthorizedException)) {
+        getLogWriter().info(
+            "Got expected NotAuthorizedException when executing query: "
+                + ex.getCause());
+      } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing query: " + ex);
+      } else {
+        fail("Got unexpected exception when executing query", ex);
+      }
+    } catch (Exception ex) {
+      if (expectedResult.intValue() == OTHER_EXCEPTION) {
+        getLogWriter().info(
+            "Got expected exception when executing query: " + ex);
+      } else {
+        fail("Got unexpected exception when executing query", ex);
+      }
+    }
+  }
+
+  public static void doPuts(Integer num) {
+
+    doPutsP(num, new Integer(NO_EXCEPTION), false);
+  }
+
+  public static void doPuts(Integer num, Integer expectedResult) {
+
+    doPutsP(num, expectedResult, false);
+  }
+
+  public static void doMultiUserPuts(Integer num, Integer numOfUsers,
+      Integer[] expectedResults) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserPuts(): numOfUsers = " + numOfUsers
+          + ", but expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("PUT: MultiUser# " + i);
+      doPutsP(num, Integer.valueOf(i), expectedResults[i], false);
+    }
+  }
+
+  public static void doGets(Integer num) {
+
+    doGetsP(num, new Integer(NO_EXCEPTION), false);
+  }
+
+  public static void doGets(Integer num, Integer expectedResult) {
+
+    doGetsP(num, expectedResult, false);
+  }
+
+  public static void doMultiUserGetAll(Integer numOfUsers, Integer[] expectedResults) {
+    doMultiUserGetAll(numOfUsers, expectedResults, false);
+  }
+
+  public static void doMultiUserGetAll(Integer numOfUsers,
+      Integer[] expectedResults, boolean useTX) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserGetAll(): numOfUsers = " + numOfUsers
+          + ", but expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info(
+          "GET_ALL" + (useTX ? " in TX" : "") + ": MultiUser# " + i);
+      doGetAllP(Integer.valueOf(i), expectedResults[i], useTX);
+    }
+  }
+  
+  public static void doMultiUserGets(Integer num, Integer numOfUsers,
+      Integer[] expectedResults) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserGets(): numOfUsers = " + numOfUsers
+          + ", but expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("GET: MultiUser# " + i);
+      doGetsP(num, Integer.valueOf(i), expectedResults[i], false);
+    }
+  }
+
+  public static void doMultiUserRegionDestroys(Integer numOfUsers,
+      Integer[] expectedResults) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserRegionDestroys(): numOfUsers = " + numOfUsers
+          + ", but expected results " + expectedResults.length);
+    }
+    for (int i = numOfUsers-1; i >= 0; i--) {
+      getLogWriter().info("DESTROY: MultiUser# " + i);
+      doRegionDestroysP(Integer.valueOf(i), expectedResults[i]);
+    }
+  }
+
+  public static void doMultiUserDestroys(Integer num, Integer numOfUsers,
+      Integer[] expectedResults) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserDestroys(): numOfUsers = " + numOfUsers
+          + ", but expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("DESTROY: MultiUser# " + i);
+      doDestroysP(num, Integer.valueOf(i), expectedResults[i], false);
+    }
+  }
+
+  public static void doMultiUserInvalidates(Integer num, Integer numOfUsers,
+      Integer[] expectedResults) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserInvalidates(): numOfUsers = " + numOfUsers
+          + ", but expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("INVALIDATE: MultiUser# " + i);
+      doInvalidatesP(num, Integer.valueOf(i), expectedResults[i], false);
+    }
+  }
+
+  public static void doMultiUserContainsKeys(Integer num, Integer numOfUsers,
+      Integer[] expectedResults, Boolean[] results) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserContainsKeys(): numOfUsers = " + numOfUsers
+          + ", but #expected results " + expectedResults.length);
+    }
+    if (numOfUsers != results.length) {
+      fail("SecurityTestUtil.doMultiUserContainsKeys(): numOfUsers = " + numOfUsers
+          + ", but #expected output " + results.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("CONTAINS_KEY: MultiUser# " + i);
+      doContainsKeysP(num, Integer.valueOf(i), expectedResults[i], false, results[i]);
+    }
+  }
+
+  public static void doMultiUserQueries(Integer numOfUsers,
+      Integer[] expectedResults, Integer valueSize) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserQueries(): numOfUsers = " + numOfUsers
+          + ", but #expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("QUERY: MultiUser# " + i);
+      doQueriesP(Integer.valueOf(i), expectedResults[i], valueSize);
+    }
+  }
+
+  public static void doMultiUserFE(Integer numOfUsers, Function function,
+      Integer[] expectedResults, Object[] results, Boolean isFailoverCase) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserFE(): numOfUsers = " + numOfUsers
+          + ", but #expected results " + expectedResults.length);
+    }
+    if (numOfUsers != results.length) {
+      fail("SecurityTestUtil.doMultiUserFE(): numOfUsers = " + numOfUsers
+          + ", but #expected output " + results.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("FunctionExecute:onRegion MultiUser# " + i);
+      doFunctionExecuteP(Integer.valueOf(i), function, expectedResults[i], results[i], "region");
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("FunctionExecute:onServer MultiUser# " + i);
+      doFunctionExecuteP(Integer.valueOf(i), function, expectedResults[i], results[i], "server");
+    }
+    if (!isFailoverCase) {
+      for (int i = 0; i < numOfUsers; i++) {
+        getLogWriter().info("FunctionExecute:onServers MultiUser# " + i);
+        doFunctionExecuteP(Integer.valueOf(i), function, expectedResults[i],
+            results[i], "servers");
+      }
+    }
+  }
+
+  public static void doMultiUserQueryExecute(Integer numOfUsers,
+      Integer[] expectedResults, Integer result) {
+    if (numOfUsers != expectedResults.length) {
+      fail("SecurityTestUtil.doMultiUserFE(): numOfUsers = " + numOfUsers
+          + ", but #expected results " + expectedResults.length);
+    }
+    for (int i = 0; i < numOfUsers; i++) {
+      getLogWriter().info("QueryExecute: MultiUser# " + i);
+      doQueryExecuteP(Integer.valueOf(i), expectedResults[i], result);
+    }
+  }
+
+  public static void doLocalGets(Integer num) {
+
+    doLocalGetsP(num.intValue(), false);
+  }
+
+  public static void doNPuts(Integer num) {
+
+    doPutsP(num, new Integer(NO_EXCEPTION), true);
+  }
+
+  public static void doNPuts(Integer num, Integer expectedResult) {
+
+    doPutsP(num, expectedResult, true);
+  }
+
+  public static void doNGets(Integer num) {
+
+    doGetsP(num, new Integer(NO_EXCEPTION), true);
+  }
+
+  public static void doNGets(Integer num, Integer expectedResult) {
+
+    doGetsP(num, expectedResult, true);
+  }
+
+  public static void doNLocalGets(Integer num) {
+
+    doLocalGetsP(num.intValue(), true);
+  }
+
+  public static void doSimpleGet(String expectedResult) {
+    if (regionRef != null) {
+      try {
+        regionRef.get("KEY");
+        if (expectedResult != null && expectedResult.endsWith("Exception")) {
+          fail("Expected " + expectedResult + " but found none in doSimpleGet()");
+        }
+      } catch (Exception e) {
+        if (!e.getClass().getSimpleName().endsWith(expectedResult)) {
+          fail("Expected " + expectedResult + " but found "
+              + e.getClass().getSimpleName() + " in doSimpleGet()");
+        } else {
+          getLogWriter().fine(
+              "Got expected " + e.getClass().getSimpleName()
+                  + " in doSimpleGet()");
+        }
+      }
+    }
+  }
+
+  public static void doSimplePut(String expectedResult) {
+    if (regionRef != null) {
+      try {
+        regionRef.put("KEY", "VALUE");
+        if (expectedResult != null && expectedResult.endsWith("Exception")) {
+          fail("Expected " + expectedResult + " but found none in doSimplePut()");
+        }
+      } catch (Exception e) {
+        if (!e.getClass().getSimpleName().endsWith(expectedResult)) {
+          fail("Expected " + expectedResult + " but found "
+              + e.getClass().getSimpleName() + " in doSimplePut()", e);
+        } else {
+          getLogWriter().fine(
+              "Got expected " + e.getClass().getSimpleName()
+                  + " in doSimplePut()");
+        }
+      }
+    }
+  }
+  // Deal with javax SSL properties
+
+  private static void makeNullStaticField(Class cls) {
+
+    Field[] fields = cls.getDeclaredFields();
+    for (int index = 0; index < fields.length; ++index) {
+      Field field = fields[index];
+      try {
+        if (Modifier.isStatic(field.getModifiers())) {
+          field.setAccessible(true);
+          if (field.getClass().equals(boolean.class)) {
+            field.setBoolean(null, false);
+            assertFalse(field.getBoolean(null));
+          }
+          else if (cls.isInstance(field.get(null))) {
+            field.set(null, null);
+            assertNull(field.get(null));
+          }
+        }
+      }
+      catch (IllegalAccessException ex) {
+        getLogWriter()
+            .warning("Exception while clearing static SSL field.", ex);
+      }
+      catch (ClassCastException ex) {
+        getLogWriter()
+            .warning("Exception while clearing static SSL field.", ex);
+      }
+    }
+  }
+
+  private static void makeNullSSLFields(Object obj, Map fieldMap) {
+
+    Iterator fieldIter = fieldMap.entrySet().iterator();
+    while (fieldIter.hasNext()) {
+      Map.Entry entry = (Map.Entry)fieldIter.next();
+      Field field = (Field)entry.getKey();
+      Object fieldObj = entry.getValue();
+      try {
+        field.setAccessible(true);
+        makeNullStaticField(fieldObj.getClass());
+        field.set(obj, null);
+        assertNull(field.get(obj));
+      }
+      catch (IllegalAccessException ex) {
+        getLogWriter().warning("Exception while clearing SSL fields.", ex);
+      }
+    }
+  }
+
+  private static HashMap getSSLFields(Object obj, Class[] classes) {
+
+    HashMap resultFields = new HashMap();
+    Field[] fields = obj.getClass().getDeclaredFields();
+    for (int index = 0; index < fields.length; ++index) {
+      Field field = fields[index];
+      try {
+        field.setAccessible(true);
+        Object fieldObj = field.get(obj);
+        boolean isInstance = false;
+        for (int classIndex = 0; classIndex < classes.length; ++classIndex) {
+          if ((isInstance = classes[classIndex].isInstance(fieldObj)) == true) {
+            break;
+          }
+        }
+        if (isInstance) {
+          resultFields.put(field, fieldObj);
+        }
+      }
+      catch (IllegalAccessException ex) {
+        getLogWriter().warning("Exception while getting SSL fields.", ex);
+      }
+    }
+    return resultFields;
+  }
+
+  // This is a hack using reflection to clear the static objects in JSSE since
+  // otherwise changing the javax.* store related properties has no effect
+  // during the course of running dunit suite unless the VMs are restarted.
+  public static void clearStaticSSLContext() {
+
+    ServerSocketFactory defaultServerFact = SSLServerSocketFactory.getDefault();
+    // Get the class of this and use reflection to blank out any static
+    // SSLContext objects inside
+    Map contextMap = getSSLFields(defaultServerFact, new Class[] {
+        SSLContext.class, SSLContextSpi.class });
+    makeNullSSLFields(defaultServerFact, contextMap);
+    Iterator contextObjsIter = contextMap.values().iterator();
+    while (contextObjsIter.hasNext()) {
+      Object contextObj = contextObjsIter.next();
+      Map contextObjsMap = getSSLFields(contextObj, new Class[] {
+          TrustManager.class, KeyManager.class, TrustManager[].class,
+          KeyManager[].class });
+      makeNullSSLFields(contextObj, contextObjsMap);
+    }
+    makeNullStaticField(SSLServerSocketFactory.class);
+
+    // Do the same for normal SSL socket factory
+    SocketFactory defaultFact = SSLSocketFactory.getDefault();
+    contextMap = getSSLFields(defaultFact, new Class[] { SSLContext.class,
+        SSLContextSpi.class });
+    makeNullSSLFields(defaultFact, contextMap);
+    contextObjsIter = contextMap.values().iterator();
+    while (contextObjsIter.hasNext()) {
+      Object contextObj = contextObjsIter.next();
+      Map contextObjsMap = getSSLFields(contextObj, new Class[] {
+          TrustManager.class, KeyManager.class, TrustManager[].class,
+          KeyManager[].class });
+      makeNullSSLFields(contextObj, contextObjsMap);
+    }
+    makeNullStaticField(SSLSocketFactory.class);
+    makeNullStaticField(SSLContext.class);
+  }
+
+  private static LogWriter getLogger() {
+
+    LogWriter logger = null;
+    DistributedSystem dsys = system;
+    if (dsys == null || !dsys.isConnected()) {
+      while ((dsys = InternalDistributedSystem.getAnyInstance()) != null
+          && !dsys.isConnected()) {
+      }
+    }
+    if (dsys != null && dsys.isConnected()) {
+      logger = dsys.getLogWriter();
+    }
+    return logger;
+  }
+
+  public static void closeCache() {
+
+    LogWriter logger = getLogger();
+    if (logger != null) {
+      removeExpectedExceptions(SecurityTestUtil.expectedExceptions, logger);
+    }
+    if (cache != null && !cache.isClosed()) {
+      DistributedSystem sys = cache.getDistributedSystem();
+      cache.close();
+      sys.disconnect();
+      cache = null;
+    }
+    disconnectFromDS();
+  }
+
+  public static void closeCache(Boolean keepAlive) {
+    LogWriter logger = getLogger();
+    if (logger != null) {
+      removeExpectedExceptions(SecurityTestUtil.expectedExceptions, logger);
+    }
+    if (cache != null && !cache.isClosed()) {
+      DistributedSystem sys = cache.getDistributedSystem();
+      cache.close(keepAlive);
+      sys.disconnect();
+      cache = null;
+    }
+    disconnectFromDS();
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/a622d6ec/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java b/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java
new file mode 100644
index 0000000..0e1ccf6
--- /dev/null
+++ b/gemfire-core/src/test/java/templates/security/AuthzCredentialGenerator.java
@@ -0,0 +1,465 @@
+
+package templates.security;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
+import com.gemstone.gemfire.security.AccessControl;
+
+/**
+ * Encapsulates obtaining authorized and unauthorized credentials for a given
+ * operation in a region. Implementations will be for different kinds of
+ * authorization scheme and authentication scheme combos.
+ * 
+ * @author sumedh
+ * @since 5.5
+ */
+public abstract class AuthzCredentialGenerator {
+
+  /**
+   * Enumeration for various {@link AuthzCredentialGenerator} implementations.
+   * 
+   * The following schemes are supported as of now:
+   * <ul>
+   * <li><code>DummyAuthorization</code> with <code>DummyAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> with <code>DummyAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> with <code>LDAPAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> with <code>PKCSAuthenticator</code></li>
+   * <li><code>XMLAuthorization</code> when using SSL sockets</li>
+   * </ul>
+   * 
+   * To add a new authorization scheme the following needs to be done:
+   * <ul>
+   * <li>Add implementation for {@link AccessControl}.</li>
+   * <li>Choose the authentication schemes that it shall work with from
+   * {@link CredentialGenerator.ClassCode}</li>
+   * <li>Add a new enumeration value for the scheme in this class. Notice the
+   * size of <code>VALUES</code> array and increase that if it is getting
+   * overflowed. Note the methods and fields for existing schemes and add for
+   * the new one in a similar manner.</li>
+   * <li>Add an implementation for {@link AuthzCredentialGenerator}. Note the
+   * {@link AuthzCredentialGenerator#init} method where different authentication
+   * schemes can be passed and initialize differently for the authentication
+   * schemes that shall be handled.</li>
+   * <li>Modify the {@link AuthzCredentialGenerator#create} method to add
+   * creation of an instance of the new implementation for the
+   * <code>ClassCode</code> enumeration value.</li>
+   * </ul>
+   * All dunit tests will automagically start testing the new implementation
+   * after this.
+   * 
+   * @author sumedh
+   * @since 5.5
+   */
+  public static final class ClassCode {
+
+    private static final byte ID_DUMMY = 1;
+
+    private static final byte ID_XML = 2;
+
+    private static byte nextOrdinal = 0;
+
+    private static final ClassCode[] VALUES = new ClassCode[10];
+
+    private static final Map CodeNameMap = new HashMap();
+
+    public static final ClassCode DUMMY = new ClassCode(
+        "templates.security.DummyAuthorization.create", ID_DUMMY);
+
+    public static final ClassCode XML = new ClassCode(
+        "templates.security.XmlAuthorization.create", ID_XML);
+
+    /** The name of this class. */
+    private final String name;
+
+    /** byte used as ordinal to represent this class */
+    private final byte ordinal;
+
+    /**
+     * One of the following: ID_DUMMY, ID_LDAP, ID_PKI
+     */
+    private final byte classType;
+
+    /** Creates a new instance of class code. */
+    private ClassCode(String name, byte classType) {
+      this.name = name;
+      this.classType = classType;
+      this.ordinal = nextOrdinal++;
+      VALUES[this.ordinal] = this;
+      CodeNameMap.put(name, this);
+    }
+
+    public boolean isDummy() {
+      return (this.classType == ID_DUMMY);
+    }
+
+    public boolean isXml() {
+      return (this.classType == ID_XML);
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified ordinal.
+     */
+    public static ClassCode fromOrdinal(byte ordinal) {
+      return VALUES[ordinal];
+    }
+
+    /**
+     * Returns the <code>ClassCode</code> represented by specified string.
+     */
+    public static ClassCode parse(String operationName) {
+      return (ClassCode)CodeNameMap.get(operationName);
+    }
+
+    /**
+     * Returns all the possible values.
+     */
+    public static List getAll() {
+      List codes = new ArrayList();
+      Iterator iter = CodeNameMap.values().iterator();
+      while (iter.hasNext()) {
+        codes.add(iter.next());
+      }
+      return codes;
+    }
+
+    /**
+     * Returns the ordinal for this class code.
+     * 
+     * @return the ordinal of this class code.
+     */
+    public byte toOrdinal() {
+      return this.ordinal;
+    }
+
+    /**
+     * Returns a string representation for this class code.
+     * 
+     * @return the name of this class code.
+     */
+    final public String toString() {
+      return this.name;
+    }
+
+    /**
+     * Indicates whether other object is same as this one.
+     * 
+     * @return true if other object is same as this one.
+     */
+    @Override
+    final public boolean equals(final Object obj) {
+      if (obj == this) {
+        return true;
+      }
+      if (!(obj instanceof ClassCode)) {
+        return false;
+      }
+      final ClassCode other = (ClassCode)obj;
+      return (other.ordinal == this.ordinal);
+    }
+
+    /**
+     * Indicates whether other <code>ClassCode</code> is same as this one.
+     * 
+     * @return true if other <code>ClassCode</code> is same as this one.
+     */
+    final public boolean equals(final ClassCode opCode) {
+      return (opCode != null && opCode.ordinal == this.ordinal);
+    }
+
+    /**
+     * Returns a hash code value for this <code>ClassCode</code> which is the
+     * same as its ordinal.
+     * 
+     * @return the ordinal of this <code>ClassCode</code>.
+     */
+    @Override
+    final public int hashCode() {
+      return this.ordinal;
+    }
+
+  }
+
+  /**
+   * The {@link CredentialGenerator} being used.
+   */
+  protected CredentialGenerator cGen;
+
+  /**
+   * A set of system properties that should be added to the gemfire system
+   * properties before using the authorization module.
+   */
+  private Properties sysProps;
+
+  /**
+   * A factory method to create a new instance of an
+   * {@link AuthzCredentialGenerator} for the given {@link ClassCode}. Caller
+   * is supposed to invoke {@link AuthzCredentialGenerator#init} immediately
+   * after obtaining the instance.
+   * 
+   * @param classCode
+   *                the <code>ClassCode</code> of the
+   *                <code>AuthzCredentialGenerator</code> implementation
+   * 
+   * @return an instance of <code>AuthzCredentialGenerator</code> for the
+   *         given class code
+   */
+  public static AuthzCredentialGenerator create(ClassCode classCode) {
+    switch (classCode.classType) {
+      case ClassCode.ID_DUMMY:
+        return new DummyAuthzCredentialGenerator();
+      case ClassCode.ID_XML:
+        return new XmlAuthzCredentialGenerator();
+      default:
+        return null;
+    }
+  }
+
+  /**
+   * Initialize the authorized credential generator.
+   * 
+   * @param cGen
+   *                an instance of {@link CredentialGenerator} of the credential
+   *                implementation for which to obtain authorized/unauthorized
+   *                credentials.
+   * 
+   * @return false when the given {@link CredentialGenerator} is incompatible
+   *         with this authorization module.
+   */
+  public boolean init(CredentialGenerator cGen) {
+    this.cGen = cGen;
+    try {
+      this.sysProps = init();
+    }
+    catch (IllegalArgumentException ex) {
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   */
+  public Properties getSystemProperties() {
+    return this.sysProps;
+  }
+
+  /**
+   * Get the {@link CredentialGenerator} being used by this instance.
+   */
+  public CredentialGenerator getCredentialGenerator() {
+    return this.cGen;
+  }
+
+  /**
+   * The {@link ClassCode} of the particular implementation.
+   * 
+   * @return the <code>ClassCode</code>
+   */
+  public abstract ClassCode classCode();
+
+  /**
+   * The name of the {@link AccessControl} factory function that should be used
+   * as the authorization module on the server side.
+   * 
+   * @return name of the <code>AccessControl</code> factory function
+   */
+  public abstract String getAuthorizationCallback();
+
+  /**
+   * Get a set of credentials generated using the given index allowed to perform
+   * the given {@link OperationCode}s for the given regions.
+   * 
+   * @param opCodes
+   *                the list of {@link OperationCode}s of the operations
+   *                requiring authorization; should not be null
+   * @param regionNames
+   *                list of the region names requiring authorization; a value of
+   *                null indicates all regions
+   * @param index
+   *                used to generate multiple such credentials by passing
+   *                different values for this
+   * 
+   * @return the set of credentials authorized to perform the given operation in
+   *         the given regions
+   */
+  public Properties getAllowedCredentials(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    int numTries = getNumPrincipalTries(opCodes, regionNames);
+    if (numTries <= 0) {
+      numTries = 1;
+    }
+    for (int tries = 0; tries < numTries; tries++) {
+      Principal principal = getAllowedPrincipal(opCodes, regionNames,
+          (index + tries) % numTries);
+      try {
+        return this.cGen.getValidCredentials(principal);
+      }
+      catch (IllegalArgumentException ex) {
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Get a set of credentials generated using the given index not allowed to
+   * perform the given {@link OperationCode}s for the given regions. The
+   * credentials are required to be valid for authentication.
+   * 
+   * @param opCode
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization failure; should not be null
+   * @param regionNames
+   *                list of the region names requiring authorization failure; a
+   *                value of null indicates all regions
+   * @param index
+   *                used to generate multiple such credentials by passing
+   *                different values for this
+   * 
+   * @return the set of credentials that are not authorized to perform the given
+   *         operation in the given region
+   */
+  public Properties getDisallowedCredentials(OperationCode[] opCodes,
+      String[] regionNames, int index) {
+
+    // This may not be very correct since we use the value of
+    // getNumPrincipalTries() but is used to avoid adding another method.
+    // Also something like getNumDisallowedPrincipals() will be normally always
+    // infinite, and the number here is just to perform some number of tries
+    // before giving up.
+    int numTries = getNumPrincipalTries(opCodes, regionNames);
+    if (numTries <= 0) {
+      numTries = 1;
+    }
+    for (int tries = 0; tries < numTries; tries++) {
+      Principal principal = getDisallowedPrincipal(opCodes, regionNames,
+          (index + tries) % numTries);
+      try {
+        return this.cGen.getValidCredentials(principal);
+      }
+      catch (IllegalArgumentException ex) {
+      }
+    }
+    return null;
+  }
+
+  /**
+   * Initialize the authorized credential generator.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @return A set of extra properties that should be added to Gemfire system
+   *         properties when not null.
+   * 
+   * @throws IllegalArgumentException
+   *                 when the {@link CredentialGenerator} is incompatible with
+   *                 this authorization module.
+   */
+  protected abstract Properties init() throws IllegalArgumentException;
+
+  /**
+   * Get the number of tries to be done for obtaining valid credentials for the
+   * given operations in the given region. It is required that
+   * {@link #getAllowedPrincipal} method returns valid principals for values of
+   * <code>index</code> from 0 through (n-1) where <code>n</code> is the
+   * value returned by this method. It is recommended that the principals so
+   * returned be unique for efficiency.
+   * 
+   * This will be used by {@link #getAllowedCredentials} to step through
+   * different principals and obtain a set of valid credentials.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @param opCodes
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization
+   * @param regionNames
+   *                list of the region names requiring authorization; a value of
+   *                null indicates all regions
+   * @param index
+   *                used to generate multiple such credentials by passing
+   *                different values for this
+   * 
+   * @return the number of principals allowed to perform the given operation in
+   *         the given region
+   */
+  protected abstract int getNumPrincipalTries(OperationCode[] opCodes,
+      String[] regionNames);
+
+  /**
+   * Get a {@link Principal} generated using the given index allowed to perform
+   * the given {@link OperationCode}s for the given region.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @param opCodes
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization
+   * @param regionNames
+   *                list of the region names requiring authorization; a value of
+   *                null indicates all regions
+   * @param index
+   *                used to generate multiple such principals by passing
+   *                different values for this
+   * 
+   * @return the {@link Principal} authorized to perform the given operation in
+   *         the given region
+   */
+  protected abstract Principal getAllowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index);
+
+  /**
+   * Get a {@link Principal} generated using the given index not allowed to
+   * perform the given {@link OperationCode}s for the given region.
+   * 
+   * Required to be implemented by concrete classes that implement this abstract
+   * class.
+   * 
+   * @param opCodes
+   *                the {@link OperationCode}s of the operations requiring
+   *                authorization failure
+   * @param regionNames
+   *                list of the region names requiring authorization failure; a
+   *                value of null indicates all regions
+   * @param index
+   *                used to generate multiple such principals by passing
+   *                different values for this
+   * 
+   * @return a {@link Principal} not authorized to perform the given operation
+   *         in the given region
+   */
+  protected abstract Principal getDisallowedPrincipal(OperationCode[] opCodes,
+      String[] regionNames, int index);
+}