You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2016/03/31 00:25:59 UTC
[01/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Repository: incubator-geode
Updated Branches:
refs/heads/develop 48af841fc -> 22ca5ef82
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserDurableCQAuthzDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserDurableCQAuthzDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserDurableCQAuthzDUnitTest.java
deleted file mode 100644
index 965c436..0000000
--- a/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserDurableCQAuthzDUnitTest.java
+++ /dev/null
@@ -1,475 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.gemstone.gemfire.security;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Random;
-
-import com.gemstone.gemfire.cache.Region;
-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.CqListener;
-import com.gemstone.gemfire.cache.query.CqQuery;
-import com.gemstone.gemfire.cache.query.QueryService;
-import com.gemstone.gemfire.cache.query.SelectResults;
-import com.gemstone.gemfire.cache.query.cq.dunit.CqQueryTestListener;
-import com.gemstone.gemfire.cache.query.internal.cq.ClientCQImpl;
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.internal.AvailablePort;
-import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
-import com.gemstone.gemfire.internal.logging.InternalLogWriter;
-import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
-import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.Invoke;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
-import com.gemstone.gemfire.test.dunit.SerializableRunnable;
-
-/**
- *
- */
-public class MultiuserDurableCQAuthzDUnitTest extends
- ClientAuthorizationTestBase {
-
- public static final Map<String, String> cqNameToQueryStrings = new HashMap<String, String>();
-
- static {
- cqNameToQueryStrings.put("CQ_0", "SELECT * FROM ");
- cqNameToQueryStrings.put("CQ_1", "SELECT * FROM ");
- }
-
- public MultiuserDurableCQAuthzDUnitTest(String name) {
- super(name);
- }
-
- @Override
- public final void postSetUp() throws Exception {
- getSystem();
- Invoke.invokeInEveryVM(new SerializableRunnable("getSystem") {
- public void run() {
- getSystem();
- }
- });
-
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
- }
-
- public void testCQForDurableClientsWithDefaultClose() throws Exception {
- /*
- * 1. Start a server.
- * 2. Start a durable client in mulituser secure mode.
- * 3. Create two users registering unique durable CQs on server.
- * 4. Invoke GemFireCache.close() at client.
- * 5. Put some events on server satisfying both the CQs.
- * 6. Up the client and the two users.
- * 7. Confirm that the users receive the events which were enqueued at server while they were away.
- * 8. Same for ProxyCache.close()
- */
- Integer numOfUsers = 2;
- Integer numOfPuts = 5;
- Boolean[] postAuthzAllowed = new Boolean[] {Boolean.TRUE, Boolean.TRUE};
-
- doTest(numOfUsers, numOfPuts, postAuthzAllowed,
- getXmlAuthzGenerator(), null);
- }
-
- public void testCQForDurableClientsWithCloseKeepAliveTrue() throws Exception {
- /*
- * 1. Start a server.
- * 2. Start a durable client in mulituser secure mode.
- * 3. Create two users registering unique durable CQs on server.
- * 4. Invoke GemFireCache.close(false) at client.
- * 5. Put some events on server satisfying both the CQs.
- * 6. Up the client and the two users.
- * 7. Observer the behaviour.
- * 8. Same for ProxyCache.close(false)
- */
- Integer numOfUsers = 2;
- Integer numOfPuts = 5;
- Boolean[] postAuthzAllowed = new Boolean[] {Boolean.TRUE, Boolean.TRUE};
-
- doTest(numOfUsers, numOfPuts, postAuthzAllowed,
- getXmlAuthzGenerator(), Boolean.TRUE);
- }
-
- public void testCQForDurableClientsWithCloseKeepAliveFalse() throws Exception {
- /*
- * 1. Start a server.
- * 2. Start a durable client in mulituser secure mode.
- * 3. Create two users registering unique durable CQs on server.
- * 4. Invoke GemFireCache.close(true) at client.
- * 5. Put some events on server satisfying both the CQs.
- * 6. Up the client and the two users.
- * 7. Observer the behaviour.
- * 8. Same for ProxyCache.close(true)
- */
- Integer numOfUsers = 2;
- Integer numOfPuts = 5;
- Boolean[] postAuthzAllowed = new Boolean[] {Boolean.TRUE, Boolean.TRUE};
-
- doTest(numOfUsers, numOfPuts, postAuthzAllowed,
- getXmlAuthzGenerator(), Boolean.FALSE);
- }
-
- private void doTest(Integer numOfUsers, Integer numOfPuts,
- Boolean[] postAuthzAllowed, AuthzCredentialGenerator gen, Boolean keepAlive)
- throws Exception {
- CredentialGenerator cGen = gen.getCredentialGenerator();
- Properties extraAuthProps = cGen.getSystemProperties();
- Properties javaProps = cGen.getJavaProperties();
- Properties extraAuthzProps = gen.getSystemProperties();
- String authenticator = cGen.getAuthenticator();
- String accessor = gen.getAuthorizationCallback();
- String authInit = cGen.getAuthInit();
- TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(gen);
-
- Properties serverProps = buildProperties(authenticator, accessor, true,
- extraAuthProps, extraAuthzProps);
-
- Properties opCredentials;
- cGen = tgen.getCredentialGenerator();
- Properties javaProps2 = null;
- if (cGen != null) {
- javaProps2 = cGen.getJavaProperties();
- }
-
- int[] indices = new int[numOfPuts];
- for (int index = 0; index < numOfPuts; ++index) {
- indices[index] = index;
- }
-
- Random rnd = new Random();
- Properties[] authProps = new Properties[numOfUsers];
- String durableClientId = "multiuser_durable_client_1";
- Properties client2Credentials = null;
- for (int i = 0; i < numOfUsers; i++) {
- int rand = rnd.nextInt(100) + 1;
- if (postAuthzAllowed[i]) {
- opCredentials = tgen.getAllowedCredentials(new OperationCode[] {
- OperationCode.EXECUTE_CQ, OperationCode.GET}, // For callback, GET should be allowed
- new String[] {regionName}, indices, rand);
- } else {
- opCredentials = tgen.getDisallowedCredentials(new OperationCode[] {
- OperationCode.GET}, // For callback, GET should be disallowed
- new String[] {regionName}, indices, rand);
- }
- authProps[i] = SecurityTestUtil.concatProperties(new Properties[] {
- opCredentials, extraAuthProps, extraAuthzProps});
-
- if (client2Credentials == null) {
- client2Credentials = tgen.getAllowedCredentials(new OperationCode[] {
- OperationCode.PUT},
- new String[] {regionName}, indices, rand);
- }
- }
-
- // Get ports for the servers
- Integer port1 = new Integer(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- Integer port2 = new Integer(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- Integer locatorPort = new Integer(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- // Close down any running servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
-
- server1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.createServerCache(serverProps, javaProps, locatorPort, port1));
- client1.invoke(MultiuserDurableCQAuthzDUnitTest.class,
- "createClientCache", new Object[] {javaProps2, authInit, authProps,
- new Integer[] {port1, port2}, numOfUsers, durableClientId, postAuthzAllowed});
-
-// client2.invoke(SecurityTestUtil.class, "createCacheClient",
-// new Object[] {authInit, client2Credentials, javaProps2,
-// new Integer[] {port1, port2}, null, SecurityTestUtil.NO_EXCEPTION});
-
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.createCQ(numOfUsers, Boolean.TRUE));
- client1.invoke(MultiuserDurableCQAuthzDUnitTest.class, "executeCQ",
- new Object[] {numOfUsers, new Boolean[] {false, false}, numOfPuts,
- new String[numOfUsers]});
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.readyForEvents());
-
- if (keepAlive == null) {
- client1.invoke(() -> SecurityTestUtil.closeCache());
- } else {
- client1.invoke(() -> SecurityTestUtil.closeCache(keepAlive));
- }
-
- server1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.doPuts(numOfPuts, Boolean.TRUE/* put last key */));
-
- client1.invoke(MultiuserDurableCQAuthzDUnitTest.class,
- "createClientCache", new Object[] {javaProps2, authInit, authProps,
- new Integer[] {port1, port2}, numOfUsers, durableClientId, postAuthzAllowed});
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.createCQ(numOfUsers, Boolean.TRUE));
- client1.invoke(MultiuserDurableCQAuthzDUnitTest.class, "executeCQ",
- new Object[] {numOfUsers, new Boolean[] {false, false}, numOfPuts,
- new String[numOfUsers]});
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.readyForEvents());
-
- if (!postAuthzAllowed[0] || keepAlive == null || !keepAlive) {
- // Don't wait as no user is authorized to receive cq events.
- Thread.sleep(1000);
- } else {
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.waitForLastKey(Integer.valueOf(0), Boolean.TRUE));
- }
- Integer numOfCreates = (keepAlive == null) ? 0
- : (keepAlive) ? (numOfPuts + 1/* last key */) : 0;
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.checkCQListeners(numOfUsers, postAuthzAllowed, numOfCreates, 0));
-
- client1.invoke(MultiuserDurableCQAuthzDUnitTest.class, "proxyCacheClose",
- new Object[] {new Integer[] {0, 1}, keepAlive});
-
- client1.invoke(SecurityTestUtil.class, "createProxyCache",
- new Object[] {new Integer[] {0, 1}, authProps});
-
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.createCQ(numOfUsers, Boolean.TRUE));
- client1.invoke(MultiuserDurableCQAuthzDUnitTest.class, "executeCQ",
- new Object[] {numOfUsers, new Boolean[] {false, false}, numOfPuts,
- new String[numOfUsers]});
-
- server1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.doPuts(numOfPuts, Boolean.TRUE/* put last key */));
-
- if (!postAuthzAllowed[0] || keepAlive == null || !keepAlive) {
- // Don't wait as no user is authorized to receive cq events.
- Thread.sleep(1000);
- } else {
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.waitForLastKey(Integer.valueOf(0), Boolean.FALSE));
- }
- Integer numOfUpdates = numOfPuts + 1;
- client1.invoke(() -> MultiuserDurableCQAuthzDUnitTest.checkCQListeners(numOfUsers, postAuthzAllowed, 0, numOfUpdates));
- }
-
- public static void createServerCache(Properties serverProps,
- Properties javaProps, Integer locatorPort, Integer serverPort) {
- SecurityTestUtil.createCacheServer((Properties)serverProps, javaProps,
- locatorPort, null, serverPort, Boolean.TRUE, new Integer(
- SecurityTestUtil.NO_EXCEPTION));
- }
-
- public static void createClientCache(Properties javaProps,
- String authInit, Properties[] authProps, Integer ports[],
- Integer numOfUsers, Boolean[] postAuthzAllowed) {
- SecurityTestUtil.createCacheClientForMultiUserMode(numOfUsers, authInit,
- authProps, javaProps, ports, null, Boolean.FALSE,
- SecurityTestUtil.NO_EXCEPTION);
- }
-
- public static void readyForEvents() {
- GemFireCacheImpl.getInstance().readyForEvents();
- }
-
- public static void createClientCache(Properties javaProps,
- String authInit, Properties[] authProps, Integer ports[],
- Integer numOfUsers, String durableId, Boolean[] postAuthzAllowed) {
- SecurityTestUtil.createCacheClientForMultiUserMode(numOfUsers, authInit,
- authProps, javaProps, ports, null, Boolean.FALSE, durableId,
- SecurityTestUtil.NO_EXCEPTION);
- }
-
- public static void createCQ(Integer num) {
- createCQ(num, false);
- }
-
- public static void createCQ(Integer num, Boolean isDurable) {
- for (int i = 0; i < num; i++) {
- QueryService cqService = SecurityTestUtil.proxyCaches[i].getQueryService();
- String cqName = "CQ_" + i;
- String queryStr = cqNameToQueryStrings.get(cqName)
- + SecurityTestUtil.proxyCaches[i].getRegion(regionName).getFullPath();
- // Create CQ Attributes.
- CqAttributesFactory cqf = new CqAttributesFactory();
- CqListener[] cqListeners = {new CqQueryTestListener(LogWriterUtils.getLogWriter())};
- ((CqQueryTestListener)cqListeners[0]).cqName = cqName;
-
- cqf.initCqListeners(cqListeners);
- CqAttributes cqa = cqf.create();
-
- // Create CQ.
- try {
- CqQuery cq1 = cqService.newCq(cqName, queryStr, cqa, isDurable);
- assertTrue("newCq() state mismatch", cq1.getState().isStopped());
- } catch (Exception ex) {
- AssertionError err = new AssertionError("Failed to create CQ " + cqName
- + " . ");
- err.initCause(ex);
- LogWriterUtils.getLogWriter().info("CqService is :" + cqService, err);
- throw err;
- }
- }
- }
-
- public static void executeCQ(Integer num, Boolean[] initialResults,
- Integer expectedResultsSize, String[] expectedErr) {
- InternalLogWriter logWriter = InternalDistributedSystem.getStaticInternalLogWriter();
- for (int i = 0; i < num; i++) {
- try {
- if (expectedErr[i] != null) {
- logWriter.info(
- "<ExpectedException action=add>" + expectedErr[i]
- + "</ExpectedException>");
- }
- CqQuery cq1 = null;
- String cqName = "CQ_" + i;
- String queryStr = cqNameToQueryStrings.get(cqName)
- + SecurityTestUtil.proxyCaches[i].getRegion(regionName)
- .getFullPath();
- QueryService cqService = SecurityTestUtil.proxyCaches[i]
- .getQueryService();
-
- // Get CqQuery object.
- try {
- cq1 = cqService.getCq(cqName);
- if (cq1 == null) {
- LogWriterUtils.getLogWriter().info(
- "Failed to get CqQuery object for CQ name: " + cqName);
- fail("Failed to get CQ " + cqName);
- } else {
- LogWriterUtils.getLogWriter().info("Obtained CQ, CQ name: " + cq1.getName());
- assertTrue("newCq() state mismatch", cq1.getState().isStopped());
- }
- } catch (Exception ex) {
- LogWriterUtils.getLogWriter().info("CqService is :" + cqService);
- LogWriterUtils.getLogWriter().error(ex);
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ex);
- throw err;
- }
-
- if (initialResults[i]) {
- SelectResults cqResults = null;
-
- try {
- cqResults = cq1.executeWithInitialResults();
- } catch (Exception ex) {
- LogWriterUtils.getLogWriter().info("CqService is: " + cqService);
- ex.printStackTrace();
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ex);
- throw err;
- }
- LogWriterUtils.getLogWriter().info("initial result size = " + cqResults.size());
- assertTrue("executeWithInitialResults() state mismatch", cq1
- .getState().isRunning());
- if (expectedResultsSize >= 0) {
- assertEquals("unexpected results size", expectedResultsSize
- .intValue(), cqResults.size());
- }
- } else {
- try {
- cq1.execute();
- } catch (Exception ex) {
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ex);
- if (expectedErr == null) {
- LogWriterUtils.getLogWriter().info("CqService is: " + cqService, err);
- }
- throw err;
- }
- assertTrue("execute() state mismatch", cq1.getState().isRunning());
- }
- } finally {
- if (expectedErr[i] != null) {
- logWriter.info(
- "<ExpectedException action=remove>" + expectedErr[i]
- + "</ExpectedException>");
- }
- }
- }
- }
-
- public static void doPuts(Integer num, Boolean putLastKey) {
- Region region = GemFireCacheImpl.getInstance().getRegion(regionName);
- for (int i = 0; i < num; i++) {
- region.put("CQ_key"+i, "CQ_value"+i);
- }
- if (putLastKey) {
- region.put("LAST_KEY", "LAST_KEY");
- }
- }
-
- public static void putLastKey() {
- Region region = GemFireCacheImpl.getInstance().getRegion(regionName);
- region.put("LAST_KEY", "LAST_KEY");
- }
-
- public static void waitForLastKey(Integer cqIndex, Boolean isCreate) {
- String cqName = "CQ_" + cqIndex;
- QueryService qService = SecurityTestUtil.proxyCaches[cqIndex].getQueryService();
- ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
- if (isCreate) {
- ((CqQueryTestListener)cqQuery.getCqListeners()[cqIndex])
- .waitForCreated("LAST_KEY");
- } else {
- ((CqQueryTestListener)cqQuery.getCqListeners()[cqIndex])
- .waitForUpdated("LAST_KEY");
- }
- }
-
- public static void checkCQListeners(Integer numOfUsers,
- Boolean[] expectedListenerInvocation, Integer createEventsSize,
- Integer updateEventsSize) {
- for (int i = 0; i < numOfUsers; i++) {
- String cqName = "CQ_" + i;
- QueryService qService = SecurityTestUtil.proxyCaches[i].getQueryService();
- ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
- if (expectedListenerInvocation[i]) {
- for (CqListener listener : cqQuery.getCqListeners()) {
- assertEquals(createEventsSize.intValue(),
- ((CqQueryTestListener)listener).getCreateEventCount());
- assertEquals(updateEventsSize.intValue(),
- ((CqQueryTestListener)listener).getUpdateEventCount());
- }
- } else {
- for (CqListener listener : cqQuery.getCqListeners()) {
- assertEquals(0, ((CqQueryTestListener)listener).getTotalEventCount());
- }
- }
- }
- }
-
- public static void proxyCacheClose(Integer[] userIndices) {
- proxyCacheClose(userIndices, null);
- }
-
- public static void proxyCacheClose(Integer[] userIndices, Boolean keepAliveFlags) {
- if (keepAliveFlags != null) {
- for (int i : userIndices) {
- SecurityTestUtil.proxyCaches[i].close(keepAliveFlags);
- }
- } else {
- for (int i : userIndices) {
- SecurityTestUtil.proxyCaches[i].close();
- }
- }
- }
-
-}
[05/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java b/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java
deleted file mode 100644
index da530d4..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtil.java
+++ /dev/null
@@ -1,1918 +0,0 @@
-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.LinkedHashMap;
-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 com.gemstone.gemfire.pdx.PdxReader;
-import com.gemstone.gemfire.pdx.PdxSerializable;
-import com.gemstone.gemfire.pdx.PdxWriter;
-import com.gemstone.gemfire.test.dunit.Assert;
-import com.gemstone.gemfire.test.dunit.DistributedTestCase;
-import com.gemstone.gemfire.test.dunit.DistributedTestUtils;
-import com.gemstone.gemfire.test.dunit.NetworkUtils;
-import com.gemstone.gemfire.test.dunit.Wait;
-import com.gemstone.gemfire.test.dunit.WaitCriterion;
-
-/**
- * Contains utility methods for setting up servers/clients for authentication
- * and authorization tests.
- *
- * @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, dsys
- .getLogWriter());
- return dsys;
- }
-
- void openCache() {
-
- assertNotNull(basicGetSystem());
- assertTrue(basicGetSystem().isConnected());
- cache = CacheFactory.create(basicGetSystem());
- 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 = NetworkUtils.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,
- NetworkUtils.getIPLiteral() + "[" + locatorPort.toString() + ']');
- }
- } else {
- authProps.setProperty("locators", "localhost["+DistributedTestUtils.getDUnitLocatorPort()+"]");
- }
- authProps.setProperty(DistributionConfig.SECURITY_LOG_LEVEL_NAME, "finest");
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Set the server properties to: " + authProps);
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when starting peer: " + ex);
- return new Integer(0);
- }
- else {
- Assert.fail("Got unexpected exception when starting peer", ex);
- }
- }
- catch (AuthenticationFailedException ex) {
- if (expectedResult.intValue() == AUTHFAIL_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when starting peer: " + ex);
- return new Integer(0);
- }
- else {
- Assert.fail("Got unexpected exception when starting peer", ex);
- }
- }
- catch (Exception ex) {
- Assert.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 = 0;
- }
- else {
- port = serverPort.intValue();
- }
- CacheServer server1 = cache.addCacheServer();
- server1.setPort(port);
- server1.setNotifyBySubscription(true);
- try {
- server1.start();
- }
- catch (Exception ex) {
- Assert.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,
- NetworkUtils.getIPLiteral(), portsI, subscriptionEnabled, 0,
- numConnections == null ? -1 : numConnections.intValue(), null, null,
- poolFactory);
-
- if (setupDynamicRegionFactory.booleanValue()) {
- initClientDynamicRegionFactory(pool.getName());
- }
- tmpInstance.openCache();
- try {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected UnsupportedOperationException in single-user mode");
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when starting client: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when starting client", ex);
- }
- }
- catch (AuthenticationFailedException ex) {
- if (expectedResult.intValue() == AUTHFAIL_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when starting client: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when starting client", ex);
- }
- }
- catch (ServerRefusedConnectionException ex) {
- if (expectedResult.intValue() == CONNREFUSED_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when starting client: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when starting client", ex);
- }
- }
- catch (Exception ex) {
- Assert.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,
- NetworkUtils.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when starting client: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when starting client", ex);
- }
- }
- catch (AuthenticationFailedException ex) {
- if (expectedResult.intValue() == AUTHFAIL_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when starting client: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when starting client", ex);
- }
- }
- catch (ServerRefusedConnectionException ex) {
- if (expectedResult.intValue() == CONNREFUSED_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when starting client: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when starting client", ex);
- }
- }
- catch (Exception ex) {
- Assert.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) {
- Assert.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,
- NetworkUtils.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) {
- Assert.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) {
- Assert.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) {
- Assert.fail("Unexpected exception", e);
- }
- return false; // NOTREACHED
- }
- public String description() {
- return null;
- }
- };
- Wait.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing puts: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing puts: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing puts", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing puts: "
- + ex.getCause());
- continue;
- }
- if ((expectedResult.intValue() == AUTHREQ_EXCEPTION)
- && (ex.getCause() instanceof AuthenticationRequiredException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected AuthenticationRequiredException when doing puts: "
- + ex.getCause());
- continue;
- }
- if ((expectedResult.intValue() == AUTHFAIL_EXCEPTION)
- && (ex.getCause() instanceof AuthenticationFailedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected AuthenticationFailedException when doing puts: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing puts: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing puts", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing puts: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing puts", ex);
- }
- }
- }
- }
-
- public static class Employee implements PdxSerializable
- {
- private Long Id;
- private String fname;
- private String lname;
-
- public Employee() {}
-
- public Employee(Long id, String fn, String ln){
- this.Id = id;
- this.fname = fn;
- this.lname = ln;
- }
-
- /**
- * For test purpose, to make sure
- * the object is not deserialized
- */
- @Override
- public void fromData(PdxReader in) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void toData(PdxWriter out) {
- out.writeLong("Id", Id);
- out.writeString("fname", fname);
- out.writeString("lname", lname);
- }
-
- }
-
- public static void doPutAllP() throws Exception {
- Region region = getCache().getRegion(regionName);
- assertNotNull(region);
- Map map = new LinkedHashMap();
- map.put("1010L", new Employee(1010L, "John", "Doe"));
- region.putAll(map);
- }
-
- 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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing getAll: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing getAll: "
- + ex.getCause());
- } else {
- Assert.fail("Got unexpected exception when doing getAll", ex);
- }
- } catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing getAll: "
- + ex.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing getAll: " + ex);
- } else {
- Assert.fail("Got unexpected exception when doing getAll", ex);
- }
- } catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing getAll: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing gets: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing gets: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing gets", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing gets: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing gets: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing gets", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing gets: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when doing region destroy: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing region destroy: "
- + ex.getCause());
- } else {
- Assert.fail("Got unexpected exception when doing region destroy", ex);
- }
- } catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing region destroy: "
- + ex.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when doing region destroy: " + ex);
- } else {
- Assert.fail("Got unexpected exception when doing region destroy", ex);
- }
- } catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when doing region destroy: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing destroys: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing destroys: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing destroys", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing destroys: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing destroys: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing destroys", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing destroys: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing invalidates: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing invalidates: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing invalidates", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing invalidates: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing invalidates: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing invalidates", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing invalidates: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing containsKey: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing containsKey: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing containsKey", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing containsKey: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing containsKey: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing containsKey", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing containsKey: " + ex);
- }
- else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing queries: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing queries: "
- + ex.getCause());
- } else {
- Assert.fail("Got unexpected exception when doing queries", ex);
- }
- } catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing queries: "
- + ex.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing queries: " + ex);
- } else {
- Assert.fail("Got unexpected exception when doing queries", ex);
- }
- } catch (QueryInvocationTargetException qite) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (qite.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing queries: "
- + qite.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing queries: " + qite);
- } else {
- Assert.fail("Got unexpected exception when doing queries", qite);
- }
- } catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("Got expected exception when doing queries: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing function: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when executing function: "
- + ex.getCause());
- } else {
- Assert.fail("Got unexpected exception when executing function", ex);
- }
- } catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when executing function: "
- + ex.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing function: " + ex);
- } else {
- Assert.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)))) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when executing function: "
- + ex.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing function: " + ex);
- } else {
- Assert.fail("Got unexpected exception when executing function", ex);
- }
- } catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing function: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing query: " + ex);
- } else {
- Assert.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when executing query: "
- + ex.getCause());
- } else {
- Assert.fail("Got unexpected exception when executing query", ex);
- }
- } catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when executing query: "
- + ex.getCause());
- } else if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing query: " + ex);
- } else {
- Assert.fail("Got unexpected exception when executing query", ex);
- }
- } catch (Exception ex) {
- if (expectedResult.intValue() == OTHER_EXCEPTION) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info(
- "Got expected exception when executing query: " + ex);
- } else {
- Assert.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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--) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter().info("FunctionExecute:onRegion MultiUser# " + i);
- doFunctionExecuteP(Integer.valueOf(i), function, expectedResults[i], results[i], "region");
- }
- for (int i = 0; i < numOfUsers; i++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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++) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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 {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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)) {
- Assert.fail("Expected " + expectedResult + " but found "
- + e.getClass().getSimpleName() + " in doSimplePut()", e);
- } else {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.getLogWriter()
- .warning("Exception while clearing static SSL field.", ex);
- }
- catch (ClassCastException ex) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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) {
- com.gemstone.gemfire.test.dunit.LogWriterUtils.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 = getSystemStatic();
- 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();
- }
-
-}
[02/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientPostAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientPostAuthorizationDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientPostAuthorizationDUnitTest.java
index 4381510..ce03ac6 100644
--- a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientPostAuthorizationDUnitTest.java
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientPostAuthorizationDUnitTest.java
@@ -16,6 +16,10 @@
*/
package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -23,11 +27,14 @@ import java.util.Properties;
import java.util.Random;
import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
+import com.gemstone.gemfire.test.junit.Retry;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import com.gemstone.gemfire.test.junit.rules.RetryRule;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* Tests for authorization from client to server. This tests for authorization
@@ -36,83 +43,19 @@ import com.gemstone.gemfire.test.dunit.LogWriterUtils;
*
* @since 5.5
*/
-public class ClientPostAuthorizationDUnitTest extends
- ClientAuthorizationTestBase {
-
-
- /** constructor */
- public ClientPostAuthorizationDUnitTest(String name) {
- super(name);
- }
-
- @Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
- }
-
- // Region: Tests
-
- public void testAllPostOps() {
-
- OperationWithAction[] allOps = {
- // Test CREATE and verify with a GET
- new OperationWithAction(OperationCode.PUT),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY, 4),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_NOTAUTHZ, 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.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 4),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 4),
- new OperationWithAction(OperationCode.GET, 3,
- OpFlags.USE_OLDCONN | OpFlags.CHECK_NOKEY | OpFlags.USE_NEWVAL
- | OpFlags.CHECK_NOTAUTHZ, 4),
+@Category(DistributedTest.class)
+public class ClientPostAuthorizationDUnitTest extends ClientAuthorizationTestCase {
- OperationWithAction.OPBLOCK_END,
+ @Rule
+ public RetryRule retryRule = new RetryRule();
- // Test UPDATE and verify with a KEY_SET
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 6),
- new OperationWithAction(OperationCode.KEY_SET, 2, OpFlags.NONE, 6),
- new OperationWithAction(OperationCode.KEY_SET, 3,
- OpFlags.CHECK_NOTAUTHZ, 6),
+ @Test
+ @Retry(2)
+ public void testAllPostOps() throws Exception {
+ OperationWithAction[] allOps = allOpsForTestAllPostOps();
- OperationWithAction.OPBLOCK_END,
-
- // Test UPDATE and verify with a QUERY
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 7),
- new OperationWithAction(OperationCode.QUERY, 2, OpFlags.USE_NEWVAL, 7),
- new OperationWithAction(OperationCode.QUERY, 3, OpFlags.USE_NEWVAL
- | OpFlags.CHECK_NOTAUTHZ, 7),
-
- OperationWithAction.OPBLOCK_END,
-
- // Test UPDATE and verify with a EXECUTE_CQ initial results
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 8),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 2, OpFlags.NONE, 8),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 3,
- OpFlags.CHECK_NOTAUTHZ, 8),
-
- OperationWithAction.OPBLOCK_END };
-
- Iterator iter = getDummyGeneratorCombos().iterator();
- while (iter.hasNext()) {
- AuthzCredentialGenerator gen = (AuthzCredentialGenerator)iter.next();
+ for (Iterator<AuthzCredentialGenerator> iter = getDummyGeneratorCombos().iterator(); iter.hasNext();) {
+ AuthzCredentialGenerator gen = iter.next();
CredentialGenerator cGen = gen.getCredentialGenerator();
Properties extraAuthProps = cGen.getSystemProperties();
Properties javaProps = cGen.getJavaProperties();
@@ -122,56 +65,45 @@ public class ClientPostAuthorizationDUnitTest extends
String accessor = gen.getAuthorizationCallback();
TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(gen);
- LogWriterUtils.getLogWriter().info("testAllPostOps: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testAllPostOps: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testAllPostOps: Using accessor: " + accessor);
+ getLogWriter().info("testAllPostOps: Using authinit: " + authInit);
+ getLogWriter().info("testAllPostOps: Using authenticator: " + authenticator);
+ getLogWriter().info("testAllPostOps: Using accessor: " + accessor);
// Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, true,
- extraAuthProps, extraAuthzProps);
+ 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));
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 = getRandomAvailablePort(SOCKET);
// Close down any running servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ server1.invoke(() -> closeCache());
+ server2.invoke(() -> closeCache());
// 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
+ // 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 (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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.closeCache());
- executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
- extraAuthzProps, tgen, rnd);
+ server1.invoke(() -> createCacheServer(getLocatorPort(), port1, serverProps, javaProps ));
+ server2.invoke(() -> 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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port2, serverProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.closeCache());
- executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
- extraAuthzProps, tgen, rnd);
+ server2.invoke(() -> createCacheServer(getLocatorPort(), port2, serverProps, javaProps ));
+ server1.invoke(() -> closeCache());
+ executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, tgen, rnd);
}
opBlock.clear();
}
- }
- else {
+
+ } else {
currentOp.setOpNum(opNum);
opBlock.add(currentOp);
}
@@ -179,57 +111,134 @@ public class ClientPostAuthorizationDUnitTest extends
}
}
- public void testAllOpsNotifications() {
+ @Test
+ public void testAllOpsNotifications() throws Exception {
+ OperationWithAction[] allOps = allOpsForTestAllOpsNotifications();
+
+ AuthzCredentialGenerator authzGenerator = getXmlAuthzGenerator();
+
+ getLogWriter().info("Executing opblocks with credential generator " + authzGenerator);
+
+ CredentialGenerator credentialGenerator = authzGenerator.getCredentialGenerator();
+ Properties extraAuthProps = credentialGenerator.getSystemProperties();
+ Properties javaProps = credentialGenerator.getJavaProperties();
+ Properties extraAuthzProps = authzGenerator.getSystemProperties();
+ String authenticator = credentialGenerator.getAuthenticator();
+ String authInit = credentialGenerator.getAuthInit();
+ String accessor = authzGenerator.getAuthorizationCallback();
+ TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(authzGenerator);
+
+ 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
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 = getRandomAvailablePort(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(() -> createCacheServer(getLocatorPort(), port1, serverProps, javaProps ));
+ server2.invoke(() -> 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(() -> createCacheServer(getLocatorPort(), port2, serverProps, javaProps ));
+ server1.invoke(() -> closeCache());
+ executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, tgen, rnd);
+ }
+ opBlock.clear();
+ }
+
+ } else {
+ currentOp.setOpNum(opNum);
+ opBlock.add(currentOp);
+ }
+ }
+ }
+
+ private OperationWithAction[] allOpsForTestAllPostOps() {
+ return new OperationWithAction[] {
+ // Test CREATE and verify with a GET
+ new OperationWithAction(OperationCode.PUT),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY | OpFlags.CHECK_NOTAUTHZ, 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.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.CHECK_NOKEY | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOTAUTHZ, 4),
+
+ OperationWithAction.OPBLOCK_END,
+
+ // Test UPDATE and verify with a KEY_SET
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 6),
+ new OperationWithAction(OperationCode.KEY_SET, 2, OpFlags.NONE, 6),
+ new OperationWithAction(OperationCode.KEY_SET, 3, OpFlags.CHECK_NOTAUTHZ, 6),
+
+ OperationWithAction.OPBLOCK_END,
+
+ // Test UPDATE and verify with a QUERY
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 7),
+ new OperationWithAction(OperationCode.QUERY, 2, OpFlags.USE_NEWVAL, 7),
+ new OperationWithAction(OperationCode.QUERY, 3, OpFlags.USE_NEWVAL | OpFlags.CHECK_NOTAUTHZ, 7),
+
+ OperationWithAction.OPBLOCK_END,
+
+ // Test UPDATE and verify with a EXECUTE_CQ initial results
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 8),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 2, OpFlags.NONE, 8),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 3, OpFlags.CHECK_NOTAUTHZ, 8),
- OperationWithAction[] allOps = {
+ OperationWithAction.OPBLOCK_END
+ };
+ }
+
+ private OperationWithAction[] allOpsForTestAllOpsNotifications() {
+ return new OperationWithAction[]{
// 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.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),
+ 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
+ // 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),
+ 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,
- // Test DESTROY and verify with GET that keys should not exist
+ // Test DESTROY and verify with GET that KEYS should not exist
new OperationWithAction(OperationCode.PUT, 3, OpFlags.NONE, 8),
- new OperationWithAction(OperationCode.REGISTER_INTEREST,
- OperationCode.GET, 2, OpFlags.USE_REGEX, 8),
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 3,
- OpFlags.USE_REGEX | OpFlags.USE_OLDCONN | OpFlags.REGISTER_POLICY_NONE, 8),
- // registerInterest now clears the keys, so a dummy put to add
- // those keys back for the case when updates should not come
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 2, OpFlags.USE_REGEX, 8),
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 3, OpFlags.USE_REGEX | OpFlags.USE_OLDCONN | OpFlags.REGISTER_POLICY_NONE, 8),
+ // registerInterest now clears the KEYS, so a dummy put to add those KEYS back for the case when updates should not come
new OperationWithAction(OperationCode.PUT, 3, OpFlags.USE_OLDCONN, 8),
- new OperationWithAction(OperationCode.DESTROY, 1, OpFlags.USE_OLDCONN,
- 4),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.CHECK_FAIL, 4),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP, 4),
+ new OperationWithAction(OperationCode.DESTROY, 1, OpFlags.USE_OLDCONN, 4),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.CHECK_FAIL, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
// Repopulate the region
new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 8),
@@ -237,152 +246,46 @@ public class ClientPostAuthorizationDUnitTest extends
// Do REGION_CLEAR and check with GET
new OperationWithAction(OperationCode.PUT, 3, OpFlags.NONE, 8),
- new OperationWithAction(OperationCode.REGISTER_INTEREST,
- OperationCode.GET, 2, OpFlags.USE_ALL_KEYS, 1),
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 3,
- OpFlags.USE_ALL_KEYS | OpFlags.USE_OLDCONN | OpFlags.REGISTER_POLICY_NONE, 1),
- // registerInterest now clears the keys, so a dummy put to add
- // those keys back for the case when updates should not come
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 2, OpFlags.USE_ALL_KEYS, 1),
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 3, OpFlags.USE_ALL_KEYS | OpFlags.USE_OLDCONN | OpFlags.REGISTER_POLICY_NONE, 1),
+ // registerInterest now clears the KEYS, so a dummy put to add those KEYS back for the case when updates should not come
new OperationWithAction(OperationCode.PUT, 3, OpFlags.USE_OLDCONN, 8),
- new OperationWithAction(OperationCode.REGION_CLEAR, 1,
- OpFlags.USE_OLDCONN, 1),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.CHECK_FAIL, 8),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP, 8),
+ new OperationWithAction(OperationCode.REGION_CLEAR, 1, OpFlags.USE_OLDCONN, 1),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.CHECK_FAIL, 8),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 8),
// Repopulate the region
new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 8),
OperationWithAction.OPBLOCK_END,
// Do REGION_CREATE and check with CREATE/GET
- new OperationWithAction(OperationCode.REGISTER_INTEREST,
- OperationCode.GET, 2, OpFlags.USE_ALL_KEYS | OpFlags.ENABLE_DRF, 1),
- new OperationWithAction(OperationCode.REGISTER_INTEREST,
- OperationCode.GET, 3, OpFlags.USE_ALL_KEYS | OpFlags.ENABLE_DRF
- | OpFlags.USE_NOTAUTHZ | OpFlags.REGISTER_POLICY_NONE, 1),
- new OperationWithAction(OperationCode.REGION_CREATE, 1,
- OpFlags.ENABLE_DRF, 1),
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_SUBREGION, 4),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION
- | OpFlags.NO_CREATE_SUBREGION, 4),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION
- | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOREGION, 4),
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 2, OpFlags.USE_ALL_KEYS | OpFlags.ENABLE_DRF, 1),
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 3, OpFlags.USE_ALL_KEYS | OpFlags.ENABLE_DRF | OpFlags.USE_NOTAUTHZ | OpFlags.REGISTER_POLICY_NONE, 1),
+ new OperationWithAction(OperationCode.REGION_CREATE, 1, OpFlags.ENABLE_DRF, 1),
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION, 4),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION | OpFlags.NO_CREATE_SUBREGION, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOREGION, 4),
// Do REGION_DESTROY of the sub-region and check with GET
- new OperationWithAction(OperationCode.REGION_DESTROY, 1,
- OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION, 1),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION
- | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOREGION, 4),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_SUBREGION | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_EXCEPTION, 4),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION
- | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOREGION, 4),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.USE_SUBREGION | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_EXCEPTION, 4),
+ new OperationWithAction(OperationCode.REGION_DESTROY, 1, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION, 1),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOREGION, 4),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION | OpFlags.CHECK_NOKEY | OpFlags.CHECK_EXCEPTION, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.USE_SUBREGION | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOREGION, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION | OpFlags.CHECK_NOKEY | OpFlags.CHECK_EXCEPTION, 4),
OperationWithAction.OPBLOCK_END,
// Do REGION_DESTROY of the region and check with GET
new OperationWithAction(OperationCode.PUT, 3, OpFlags.NONE, 8),
- new OperationWithAction(OperationCode.REGISTER_INTEREST,
- OperationCode.GET, 2, OpFlags.USE_ALL_KEYS, 1),
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 3,
- OpFlags.USE_ALL_KEYS | OpFlags.USE_OLDCONN | OpFlags.REGISTER_POLICY_NONE, 1),
- // registerInterest now clears the keys, so a dummy put to add
- // those keys back for the case when updates should not come
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 2, OpFlags.USE_ALL_KEYS, 1),
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 3, OpFlags.USE_ALL_KEYS | OpFlags.USE_OLDCONN | OpFlags.REGISTER_POLICY_NONE, 1),
+ // registerInterest now clears the KEYS, so a dummy put to add those KEYS back for the case when updates should not come
new OperationWithAction(OperationCode.PUT, 3, OpFlags.USE_OLDCONN, 8),
- new OperationWithAction(OperationCode.REGION_DESTROY, 1, OpFlags.NONE,
- 1),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP | OpFlags.CHECK_NOREGION, 4),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP, 4),
-
- OperationWithAction.OPBLOCK_NO_FAILOVER };
-
- AuthzCredentialGenerator gen = getXmlAuthzGenerator();
- LogWriterUtils.getLogWriter().info("Executing opblocks with credential generator " + gen);
- 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);
-
- LogWriterUtils.getLogWriter().info(
- "testAllOpsNotifications: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testAllOpsNotifications: Using authenticator: " + authenticator);
- LogWriterUtils.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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port2, serverProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.closeCache());
- executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
- extraAuthzProps, tgen, rnd);
- }
- opBlock.clear();
- }
- }
- else {
- currentOp.setOpNum(opNum);
- opBlock.add(currentOp);
- }
- }
- }
+ new OperationWithAction(OperationCode.REGION_DESTROY, 1, OpFlags.NONE, 1),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.CHECK_NOREGION, 4),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
- // End Region: Tests
-
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- SecurityTestUtil.closeCache();
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ OperationWithAction.OPBLOCK_NO_FAILOVER
+ };
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserAPIDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserAPIDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserAPIDUnitTest.java
new file mode 100644
index 0000000..9e04f5f
--- /dev/null
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserAPIDUnitTest.java
@@ -0,0 +1,314 @@
+/*
+ * 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.
+ */
+package com.gemstone.gemfire.security;
+
+import static com.gemstone.gemfire.distributed.internal.DistributionConfig.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+
+import java.io.IOException;
+import java.util.Properties;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLHandshakeException;
+
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.client.Pool;
+import com.gemstone.gemfire.cache.execute.FunctionService;
+import com.gemstone.gemfire.cache.query.CqAttributesFactory;
+import com.gemstone.gemfire.cache.query.CqException;
+import com.gemstone.gemfire.cache.query.CqQuery;
+import com.gemstone.gemfire.cache.query.Query;
+import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.cache.PoolManagerImpl;
+import com.gemstone.gemfire.security.generator.CredentialGenerator;
+import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+@Category(DistributedTest.class)
+public class MultiUserAPIDUnitTest extends ClientAuthorizationTestCase {
+
+ private static final String[] serverIgnoredExceptions = {
+ 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[] clientIgnoredExceptions = {
+ AuthenticationRequiredException.class.getName(),
+ AuthenticationFailedException.class.getName(),
+ SSLHandshakeException.class.getName()};
+
+ @Test
+ public void testSingleUserUnsupportedAPIs() {
+ // Start servers
+ // Start clients with multiuser-authentication set to false
+ setUpVMs(new DummyCredentialGenerator(), false);
+ client1.invoke(() -> verifyDisallowedOps(false));
+ }
+
+ @Test
+ public void testMultiUserUnsupportedAPIs() {
+ // Start servers.
+ // Start clients with multiuser-authentication set to true.
+ setUpVMs(new DummyCredentialGenerator(), true);
+ client1.invoke(() -> verifyDisallowedOps(true));
+ }
+
+ private void verifyDisallowedOps(final boolean multiUserMode) throws Exception {
+ String op = "unknown";
+ boolean success = false;
+
+ if (!multiUserMode) {
+ success = false;
+
+ try {
+ // Attempt cache.createAuthenticatedCacheView() and expect an exception, fail otherwise
+ op = "Pool.createSecureUserCache()";
+ GemFireCacheImpl.getInstance().createAuthenticatedView(new Properties(), "testPool");
+ } catch (IllegalStateException uoe) {
+ getLogWriter().info(op + ": Got expected exception: " + uoe);
+ success = true;
+ }
+
+ if (!success) {
+ fail("Did not get exception while doing " + op);
+ }
+
+ } else { // multiuser mode
+ Region realRegion = GemFireCacheImpl.getInstance().getRegion(SecurityTestUtils.REGION_NAME);
+ Region proxyRegion = SecurityTestUtils.getProxyCaches(0).getRegion(SecurityTestUtils.REGION_NAME);
+ Pool pool = PoolManagerImpl.getPMI().find("testPool");
+
+ for (int i = 0; i <= 27; i++) {
+ success = false;
+ try {
+ switch (i) {
+ // Attempt (real) Region.create/put/get/containsKeyOnServer/destroy/
+ // destroyRegion/clear/remove/registerInterest/unregisterInterest()
+ // and expect an exception, fail otherwise.
+ case 0:
+ op = "Region.create()";
+ realRegion.create("key", "value");
+ break;
+ case 1:
+ op = "Region.put()";
+ realRegion.put("key", "value");
+ break;
+ case 2:
+ op = "Region.get()";
+ realRegion.get("key");
+ break;
+ case 3:
+ op = "Region.containsKeyOnServer()";
+ realRegion.containsKeyOnServer("key");
+ break;
+ case 4:
+ op = "Region.remove()";
+ realRegion.remove("key");
+ break;
+ case 5:
+ op = "Region.destroy()";
+ realRegion.destroy("key");
+ break;
+ case 6:
+ op = "Region.destroyRegion()";
+ realRegion.destroyRegion();
+ break;
+ case 7:
+ op = "Region.registerInterest()";
+ realRegion.registerInterest("key");
+ break;
+ // case 8:
+ // op = "Region.unregisterInterest()";
+ // realRegion.unregisterInterest("key");
+ // break;
+ case 8:
+ op = "Region.clear()";
+ realRegion.clear();
+ break;
+ // Attempt ProxyRegion.createSubregion/forceRolling/
+ // getAttributesMutator/registerInterest/loadSnapShot/saveSnapshot/
+ // setUserAttribute/unregisterInterest/writeToDisk
+ // and expect an exception, fail otherwise.
+ case 9:
+ op = "ProxyRegion.createSubregion()";
+ proxyRegion.createSubregion("subregion", null);
+ break;
+ case 10:
+ op = "ProxyRegion.forceRolling()";
+ proxyRegion.forceRolling();
+ break;
+ case 11:
+ op = "ProxyRegion.getAttributesMutator()";
+ proxyRegion.getAttributesMutator();
+ break;
+ case 12:
+ op = "ProxyRegion.registerInterest()";
+ proxyRegion.registerInterest("key");
+ break;
+ case 13:
+ op = "ProxyRegion.loadSnapshot()";
+ proxyRegion.loadSnapshot(null);
+ break;
+ case 14:
+ op = "ProxyRegion.saveSnapshot()";
+ proxyRegion.saveSnapshot(null);
+ break;
+ case 15:
+ op = "ProxyRegion.setUserAttribute()";
+ proxyRegion.setUserAttribute(null);
+ break;
+ case 16:
+ op = "ProxyRegion.unregisterInterestRegex()";
+ proxyRegion.unregisterInterestRegex("*");
+ break;
+ // Attempt FunctionService.onRegion/onServer/s(pool) and expect an
+ // exception, fail otherwise.
+ case 17:
+ op = "FunctionService.onRegion()";
+ FunctionService.onRegion(realRegion);
+ break;
+ case 18:
+ op = "FunctionService.onServer(pool)";
+ FunctionService.onServer(pool);
+ break;
+ case 19:
+ op = "FunctionService.onServers(pool)";
+ FunctionService.onServers(pool);
+ break;
+ // Attempt
+ // QueryService.newQuery().execute()/newCq().execute/executeWithInitialResults()
+ case 20:
+ op = "QueryService.newQuery.execute()";
+ Query query = pool.getQueryService().newQuery("SELECT * FROM /" + SecurityTestUtils.REGION_NAME);
+ query.execute();
+ break;
+ case 21:
+ op = "QueryService.newCq.execute()";
+ CqQuery cqQuery = pool.getQueryService().newCq("SELECT * FROM /" + SecurityTestUtils.REGION_NAME, new CqAttributesFactory().create());
+ try {
+ cqQuery.execute();
+ } catch (CqException ce) {
+ throw (Exception)ce.getCause();
+ }
+ break;
+ case 22:
+ op = "QueryService.newCq.executeWithInitialResults()";
+ cqQuery = pool.getQueryService().newCq("SELECT * FROM /" + SecurityTestUtils.REGION_NAME, new CqAttributesFactory().create());
+ try {
+ cqQuery.executeWithInitialResults();
+ } catch (CqException ce) {
+ throw (Exception)ce.getCause();
+ }
+ break;
+ // Attempt ProxyQueryService.getIndex/createIndex/removeIndex() and
+ // expect an exception, fail otherwise.
+ case 23:
+ op = "ProxyQueryService().getIndexes()";
+ SecurityTestUtils.getProxyCaches(0).getQueryService().getIndexes(null);
+ break;
+ case 24:
+ op = "ProxyQueryService().createIndex()";
+ SecurityTestUtils.getProxyCaches(0).getQueryService().createIndex(null, null, null );
+ break;
+ case 25:
+ op = "ProxyQueryService().removeIndexes()";
+ SecurityTestUtils.getProxyCaches(0).getQueryService().removeIndexes();
+ break;
+ case 26:
+ op = "ProxyRegion.localDestroy()";
+ proxyRegion.localDestroy("key");
+ break;
+ case 27:
+ op = "ProxyRegion.localInvalidate()";
+ proxyRegion.localInvalidate("key");
+ break;
+ default:
+ fail("Unknown op code: " + i);
+ break;
+ }
+
+ } catch (UnsupportedOperationException uoe) {
+ getLogWriter().info(op + ": Got expected exception: " + uoe);
+ success = true;
+ }
+ if (!success) {
+ fail("Did not get exception while doing " + op);
+ }
+ }
+ }
+ }
+
+ private void setUpVMs(final CredentialGenerator gen, final boolean multiUser) {
+ 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
+ int locPort1 = SecurityTestUtils.getLocatorPort();
+ int locPort2 = SecurityTestUtils.getLocatorPort();
+ String locString = SecurityTestUtils.getAndClearLocatorString();
+
+ int port1 = server1.invoke(() -> createCacheServer(locPort1, locString, authenticator, extraProps, javaProps));
+ int port2 = server2.invoke(() -> createCacheServer(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(() -> createCacheClient(authInit, credentials1, javaProps1, port1, port2, 0, multiUser, NO_EXCEPTION));
+ }
+
+ private int createCacheServer(final int dsPort, final String locatorString, final String authenticator, final Properties extraProps, final Properties javaProps) {
+ Properties authProps = new Properties();
+ if (extraProps != null) {
+ authProps.putAll(extraProps);
+ }
+
+ if (authenticator != null) {
+ authProps.setProperty(SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
+ }
+
+ return SecurityTestUtils.createCacheServer(authProps, javaProps, dsPort, locatorString, 0, NO_EXCEPTION);
+ }
+
+ // a
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean multiUserMode, final int expectedResult) {
+ SecurityTestUtils.createCacheClient(authInit, authProps, javaProps, ports, numConnections, multiUserMode, expectedResult); // invokes SecurityTestUtils 2
+ }
+
+ // b
+ private void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int port1, final int port2, final int numConnections, final boolean multiUserMode, final int expectedResult) {
+ createCacheClient(authInit, authProps, javaProps, new int[] {port1, port2}, numConnections, multiUserMode, expectedResult); // invokes a
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserDurableCQAuthzDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserDurableCQAuthzDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserDurableCQAuthzDUnitTest.java
new file mode 100644
index 0000000..632a997
--- /dev/null
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiUserDurableCQAuthzDUnitTest.java
@@ -0,0 +1,387 @@
+/*
+ * 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.
+ */
+package com.gemstone.gemfire.security;
+
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.Invoke.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Random;
+
+import com.gemstone.gemfire.cache.Region;
+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.CqException;
+import com.gemstone.gemfire.cache.query.CqExistsException;
+import com.gemstone.gemfire.cache.query.CqListener;
+import com.gemstone.gemfire.cache.query.CqQuery;
+import com.gemstone.gemfire.cache.query.QueryService;
+import com.gemstone.gemfire.cache.query.RegionNotFoundException;
+import com.gemstone.gemfire.cache.query.SelectResults;
+import com.gemstone.gemfire.cache.query.cq.dunit.CqQueryTestListener;
+import com.gemstone.gemfire.cache.query.internal.cq.ClientCQImpl;
+import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
+import com.gemstone.gemfire.security.generator.CredentialGenerator;
+import com.gemstone.gemfire.test.dunit.SerializableRunnable;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+@Category(DistributedTest.class)
+public class MultiUserDurableCQAuthzDUnitTest extends ClientAuthorizationTestCase {
+
+ private final Map<String, String> cqNameToQueryStrings = new HashMap<>();
+
+ @Override
+ public final void preSetUpClientAuthorizationTestBase() throws Exception {
+ getSystem();
+ invokeInEveryVM(new SerializableRunnable("getSystem") {
+ public void run() {
+ getSystem();
+ }
+ });
+ }
+
+ @Override
+ public final void postSetUpClientAuthorizationTestBase() throws Exception {
+ cqNameToQueryStrings.put("CQ_0", "SELECT * FROM ");
+ cqNameToQueryStrings.put("CQ_1", "SELECT * FROM ");
+ }
+
+ @Override
+ public final void postTearDownClientAuthorizationTestBase() throws Exception {
+ cqNameToQueryStrings.clear();
+ }
+
+ @Test
+ public void testCQForDurableClientsWithDefaultClose() throws Exception {
+ /*
+ * 1. Start a server.
+ * 2. Start a durable client in mulituser secure mode.
+ * 3. Create two users registering unique durable CQs on server.
+ * 4. Invoke GemFireCache.close() at client.
+ * 5. Put some events on server satisfying both the CQs.
+ * 6. Up the client and the two users.
+ * 7. Confirm that the users receive the events which were enqueued at server while they were away.
+ * 8. Same for ProxyCache.close()
+ */
+ int numOfUsers = 2;
+ int numOfPuts = 5;
+ boolean[] postAuthzAllowed = new boolean[] {true, true};
+
+ doTest(numOfUsers, numOfPuts, postAuthzAllowed, getXmlAuthzGenerator(), null);
+ }
+
+ @Test
+ public void testCQForDurableClientsWithCloseKeepAliveTrue() throws Exception {
+ /*
+ * 1. Start a server.
+ * 2. Start a durable client in mulituser secure mode.
+ * 3. Create two users registering unique durable CQs on server.
+ * 4. Invoke GemFireCache.close(false) at client.
+ * 5. Put some events on server satisfying both the CQs.
+ * 6. Up the client and the two users.
+ * 7. Observer the behaviour.
+ * 8. Same for ProxyCache.close(false)
+ */
+ int numOfUsers = 2;
+ int numOfPuts = 5;
+ boolean[] postAuthzAllowed = new boolean[] {true, true};
+
+ doTest(numOfUsers, numOfPuts, postAuthzAllowed, getXmlAuthzGenerator(), true);
+ }
+
+ @Test
+ public void testCQForDurableClientsWithCloseKeepAliveFalse() throws Exception {
+ /*
+ * 1. Start a server.
+ * 2. Start a durable client in mulituser secure mode.
+ * 3. Create two users registering unique durable CQs on server.
+ * 4. Invoke GemFireCache.close(true) at client.
+ * 5. Put some events on server satisfying both the CQs.
+ * 6. Up the client and the two users.
+ * 7. Observer the behaviour.
+ * 8. Same for ProxyCache.close(true)
+ */
+ int numOfUsers = 2;
+ int numOfPuts = 5;
+ boolean[] postAuthzAllowed = new boolean[] {true, true};
+
+ doTest(numOfUsers, numOfPuts, postAuthzAllowed, getXmlAuthzGenerator(), false);
+ }
+
+ /**
+ * WARNING: "final Boolean keepAlive" is treated as a ternary value: null, true, false
+ */
+ private void doTest(int numOfUsers, int numOfPuts, boolean[] postAuthzAllowed, final AuthzCredentialGenerator authzGenerator, final Boolean keepAlive) throws Exception {
+ CredentialGenerator credentialGenerator = authzGenerator.getCredentialGenerator();
+ Properties extraAuthProps = credentialGenerator.getSystemProperties();
+ Properties javaProps = credentialGenerator.getJavaProperties();
+ Properties extraAuthzProps = authzGenerator.getSystemProperties();
+ String authenticator = credentialGenerator.getAuthenticator();
+ String accessor = authzGenerator.getAuthorizationCallback();
+ String authInit = credentialGenerator.getAuthInit();
+ TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(authzGenerator);
+
+ Properties serverProps = buildProperties(authenticator, accessor, true, extraAuthProps, extraAuthzProps);
+
+ Properties opCredentials;
+ credentialGenerator = tgen.getCredentialGenerator();
+ final Properties javaProps2 = credentialGenerator != null ? credentialGenerator.getJavaProperties() : null;
+
+ int[] indices = new int[numOfPuts];
+ for (int index = 0; index < numOfPuts; ++index) {
+ indices[index] = index;
+ }
+
+ Random random = new Random();
+ Properties[] authProps = new Properties[numOfUsers];
+ String durableClientId = "multiuser_durable_client_1";
+
+ Properties client2Credentials = null;
+
+ for (int i = 0; i < numOfUsers; i++) {
+ int rand = random.nextInt(100) + 1;
+ if (postAuthzAllowed[i]) {
+ opCredentials = tgen.getAllowedCredentials(
+ new OperationCode[] {OperationCode.EXECUTE_CQ, OperationCode.GET}, // For callback, GET should be allowed
+ new String[] {regionName},
+ indices,
+ rand);
+
+ } else {
+ opCredentials = tgen.getDisallowedCredentials(
+ new OperationCode[] {OperationCode.GET}, // For callback, GET should be disallowed
+ new String[] {regionName},
+ indices,
+ rand);
+ }
+
+ authProps[i] = concatProperties(new Properties[] {opCredentials, extraAuthProps, extraAuthzProps});
+
+ if (client2Credentials == null) {
+ client2Credentials = tgen.getAllowedCredentials(
+ new OperationCode[] {OperationCode.PUT},
+ new String[] {regionName},
+ indices,
+ rand);
+ }
+ }
+
+ // Get ports for the servers
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 = getRandomAvailablePort(SOCKET);
+ int locatorPort = getRandomAvailablePort(SOCKET);
+
+ // Close down any running servers
+ server1.invoke(() -> closeCache());
+ server2.invoke(() -> closeCache());
+
+ server1.invoke(() -> createServerCache(serverProps, javaProps, locatorPort, port1));
+ client1.invoke(() -> createClientCache(javaProps2, authInit, authProps, new int[] {port1, port2}, numOfUsers, durableClientId, postAuthzAllowed));
+
+ client1.invoke(() -> createCQ(numOfUsers, true));
+ client1.invoke(() -> executeCQ(numOfUsers, new boolean[] {false, false}, numOfPuts, new String[numOfUsers]));
+ client1.invoke(() -> readyForEvents());
+
+ if (keepAlive == null) {
+ client1.invoke(() -> closeCache());
+ } else {
+ client1.invoke(() -> closeCache(keepAlive));
+ }
+
+ server1.invoke(() -> doPuts(numOfPuts, true/* put last key */));
+
+ client1.invoke(() -> createClientCache(javaProps2, authInit, authProps, new int[] {port1, port2}, numOfUsers, durableClientId, postAuthzAllowed));
+ client1.invoke(() -> createCQ(numOfUsers, true));
+ client1.invoke(() ->executeCQ(numOfUsers, new boolean[] {false, false}, numOfPuts, new String[numOfUsers]));
+ client1.invoke(() -> readyForEvents());
+
+ if (!postAuthzAllowed[0] || keepAlive == null || !keepAlive) {
+ // Don't wait as no user is authorized to receive cq events.
+ Thread.sleep(1000); // TODO: use Awaitility
+ } else {
+ client1.invoke(() -> waitForLastKey(0, true));
+ }
+
+ int numOfCreates = keepAlive == null ? 0 : (keepAlive ? numOfPuts + 1/* last key */ : 0);
+ client1.invoke(() -> checkCQListeners(numOfUsers, postAuthzAllowed, numOfCreates, 0));
+ client1.invoke(() -> proxyCacheClose(new int[] {0, 1}, keepAlive));
+ client1.invoke(() -> createProxyCache(new int[] {0, 1}, authProps));
+ client1.invoke(() -> createCQ(numOfUsers, true));
+ client1.invoke(() -> executeCQ(numOfUsers, new boolean[] {false, false}, numOfPuts, new String[numOfUsers]));
+
+ server1.invoke(() -> doPuts(numOfPuts, true/* put last key */));
+
+ if (!postAuthzAllowed[0] || keepAlive == null || !keepAlive) {
+ // Don't wait as no user is authorized to receive cq events.
+ Thread.sleep(1000); // TODO: use Awaitility
+ } else {
+ client1.invoke(() -> waitForLastKey(0, false));
+ }
+
+ int numOfUpdates = numOfPuts + 1;
+ client1.invoke(() -> checkCQListeners(numOfUsers, postAuthzAllowed, 0, numOfUpdates));
+ }
+
+ private void createServerCache(final Properties serverProps, final Properties javaProps, final int locatorPort, final int serverPort) {
+ SecurityTestUtils.createCacheServer(serverProps, javaProps, locatorPort, null, serverPort, true, NO_EXCEPTION);
+ }
+
+ private void readyForEvents() {
+ GemFireCacheImpl.getInstance().readyForEvents();
+ }
+
+ /**
+ * NOTE: "final boolean[] postAuthzAllowed" is never used
+ */
+ private void createClientCache(final Properties javaProps, final String authInit, final Properties[] authProps, final int ports[], final int numOfUsers, final String durableId, final boolean[] postAuthzAllowed) {
+ createCacheClientForMultiUserMode(numOfUsers, authInit, authProps, javaProps, ports, 0, false, durableId, NO_EXCEPTION);
+ }
+
+ private void createCQ(final int num, final boolean isDurable) throws CqException, CqExistsException {
+ for (int i = 0; i < num; i++) {
+ QueryService cqService = getProxyCaches(i).getQueryService();
+ String cqName = "CQ_" + i;
+ String queryStr = cqNameToQueryStrings.get(cqName) + getProxyCaches(i).getRegion(regionName).getFullPath();
+
+ // Create CQ Attributes.
+ CqAttributesFactory cqf = new CqAttributesFactory();
+ CqListener[] cqListeners = {new CqQueryTestListener(getLogWriter())};
+ ((CqQueryTestListener)cqListeners[0]).cqName = cqName;
+
+ cqf.initCqListeners(cqListeners);
+ CqAttributes cqa = cqf.create();
+
+ // Create CQ.
+ CqQuery cq1 = cqService.newCq(cqName, queryStr, cqa, isDurable);
+ assertTrue("newCq() state mismatch", cq1.getState().isStopped());
+ }
+ }
+
+ private void executeCQ(final int num, final boolean[] initialResults, final int expectedResultsSize, final String[] expectedErr) throws CqException, RegionNotFoundException {
+ for (int i = 0; i < num; i++) {
+ try {
+ if (expectedErr[i] != null) {
+ getLogWriter().info("<ExpectedException action=add>" + expectedErr[i]+ "</ExpectedException>");
+ }
+
+ CqQuery cq1 = null;
+ String cqName = "CQ_" + i;
+ String queryStr = cqNameToQueryStrings.get(cqName) + getProxyCaches(i).getRegion(regionName).getFullPath();
+ QueryService cqService = getProxyCaches(i).getQueryService();
+
+ // Get CqQuery object.
+ cq1 = cqService.getCq(cqName);
+ if (cq1 == null) {
+ getLogWriter().info("Failed to get CqQuery object for CQ name: " + cqName);
+ fail("Failed to get CQ " + cqName);
+
+ } else {
+ getLogWriter().info("Obtained CQ, CQ name: " + cq1.getName());
+ assertTrue("newCq() state mismatch", cq1.getState().isStopped());
+ }
+
+ if (initialResults[i]) {
+ SelectResults cqResults = null;
+
+ cqResults = cq1.executeWithInitialResults();
+
+ getLogWriter().info("initial result size = " + cqResults.size());
+ assertTrue("executeWithInitialResults() state mismatch", cq1
+ .getState().isRunning());
+ if (expectedResultsSize >= 0) {
+ assertEquals("unexpected results size", expectedResultsSize, cqResults.size());
+ }
+
+ } else {
+ cq1.execute();
+ assertTrue("execute() state mismatch", cq1.getState().isRunning());
+ }
+
+ } finally {
+ if (expectedErr[i] != null) {
+ getLogWriter().info("<ExpectedException action=remove>" + expectedErr[i]+ "</ExpectedException>");
+ }
+ }
+ }
+ }
+
+ private void doPuts(final int num, final boolean putLastKey) {
+ Region region = GemFireCacheImpl.getInstance().getRegion(regionName);
+ for (int i = 0; i < num; i++) {
+ region.put("CQ_key"+i, "CQ_value"+i);
+ }
+ if (putLastKey) {
+ region.put("LAST_KEY", "LAST_KEY");
+ }
+ }
+
+ private void waitForLastKey(final int cqIndex, final boolean isCreate) {
+ String cqName = "CQ_" + cqIndex;
+ QueryService qService = getProxyCaches(cqIndex).getQueryService();
+ ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
+ if (isCreate) {
+ ((CqQueryTestListener)cqQuery.getCqListeners()[cqIndex]).waitForCreated("LAST_KEY");
+ } else {
+ ((CqQueryTestListener)cqQuery.getCqListeners()[cqIndex]).waitForUpdated("LAST_KEY");
+ }
+ }
+
+ private void checkCQListeners(final int numOfUsers, final boolean[] expectedListenerInvocation, final int createEventsSize, final int updateEventsSize) {
+ for (int i = 0; i < numOfUsers; i++) {
+ String cqName = "CQ_" + i;
+ QueryService qService = getProxyCaches(i).getQueryService();
+ ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
+
+ if (expectedListenerInvocation[i]) {
+ for (CqListener listener : cqQuery.getCqListeners()) {
+ assertEquals(createEventsSize, ((CqQueryTestListener)listener).getCreateEventCount());
+ assertEquals(updateEventsSize, ((CqQueryTestListener)listener).getUpdateEventCount());
+ }
+
+ } else {
+ for (CqListener listener : cqQuery.getCqListeners()) {
+ assertEquals(0, ((CqQueryTestListener)listener).getTotalEventCount());
+ }
+ }
+ }
+ }
+
+ /**
+ * WARNING: "final Boolean keepAliveFlags" is treated as a ternary: null, true, false
+ */
+ private void proxyCacheClose(final int[] userIndices, final Boolean keepAliveFlags) {
+ if (keepAliveFlags != null) {
+ for (int i : userIndices) {
+ getProxyCaches(i).close(keepAliveFlags);
+ }
+
+ } else {
+ for (int i : userIndices) {
+ getProxyCaches(i).close();
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserAPIDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserAPIDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserAPIDUnitTest.java
deleted file mode 100644
index c5a1afe..0000000
--- a/geode-cq/src/test/java/com/gemstone/gemfire/security/MultiuserAPIDUnitTest.java
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.gemstone.gemfire.security;
-
-import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
-import hydra.Log;
-
-import java.io.IOException;
-import java.util.Properties;
-
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
-import com.gemstone.gemfire.cache.Region;
-import com.gemstone.gemfire.cache.client.Pool;
-import com.gemstone.gemfire.cache.execute.FunctionService;
-import com.gemstone.gemfire.cache.query.CqAttributesFactory;
-import com.gemstone.gemfire.cache.query.CqException;
-import com.gemstone.gemfire.cache.query.CqQuery;
-import com.gemstone.gemfire.cache.query.Query;
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
-import com.gemstone.gemfire.internal.cache.PoolManagerImpl;
-import com.gemstone.gemfire.test.dunit.Assert;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
-import com.gemstone.gemfire.test.dunit.VM;
-
-public class MultiuserAPIDUnitTest extends ClientAuthorizationTestBase {
-
- /** constructor */
- public MultiuserAPIDUnitTest(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 final void postSetUp() throws Exception {
- 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.registerExpectedExceptions(serverExpectedExceptions));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions(serverExpectedExceptions));
- client1.invoke(() -> SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions));
- }
-
- 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));
- }
-
- private static void createCacheClient(Object authInit, Properties authProps,
- Properties javaProps, Integer[] ports, Object numConnections,
- Boolean multiUserMode, Integer expectedResult) {
-
- String authInitStr = (authInit == null ? null : authInit.toString());
- SecurityTestUtil.createCacheClient(authInitStr, authProps, javaProps,
- ports, numConnections, multiUserMode.toString(), expectedResult);
- }
-
- public static void createCacheClient(Object authInit, Object authProps,
- Object javaProps, Integer port1, Integer port2, Object numConnections,
- Boolean multiUserMode, Integer expectedResult) {
-
- createCacheClient(authInit, (Properties)authProps, (Properties)javaProps,
- new Integer[] {port1, port2}, numConnections, multiUserMode,
- expectedResult);
- }
-
- public static void registerAllInterest() {
- Region region = SecurityTestUtil.getCache().getRegion(
- SecurityTestUtil.regionName);
- assertNotNull(region);
- region.registerInterestRegex(".*");
- }
-
- private void setUpVMs(CredentialGenerator gen, Boolean multiUser) {
- Properties extraProps = gen.getSystemProperties();
- Properties javaProps = gen.getJavaProperties();
- String authenticator = gen.getAuthenticator();
- String authInit = gen.getAuthInit();
-
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: Using authenticator: " + authenticator);
- LogWriterUtils.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(() -> MultiuserAPIDUnitTest.createCacheServer(locPort1, locString, authenticator,
- extraProps, javaProps));
- Integer port2 = (Integer)server2.invoke(() -> MultiuserAPIDUnitTest.createCacheServer(locPort2, locString, authenticator,
- extraProps, javaProps));
-
- // Start the clients with valid credentials
- Properties credentials1 = gen.getValidCredentials(1);
- Properties javaProps1 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: For first client credentials: " + credentials1
- + " : " + javaProps1);
- Properties credentials2 = gen.getValidCredentials(2);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: For second client credentials: " + credentials2
- + " : " + javaProps2);
- client1.invoke(() -> MultiuserAPIDUnitTest.createCacheClient(authInit, credentials1, javaProps1, port1, port2, null,
- multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION)));
- }
-
- public void testSingleUserUnsupportedAPIs() {
- // Start servers
- // Start clients with multiuser-authentication set to false
- setUpVMs(new DummyCredentialGenerator(), Boolean.FALSE);
- client1.invoke(() -> MultiuserAPIDUnitTest.verifyDisallowedOps(Boolean.FALSE));
- }
-
- public void testMultiUserUnsupportedAPIs() {
- // Start servers.
- // Start clients with multiuser-authentication set to true.
- setUpVMs(new DummyCredentialGenerator(), Boolean.TRUE);
- client1.invoke(() -> MultiuserAPIDUnitTest.verifyDisallowedOps(Boolean.TRUE));
- }
-
- public static void verifyDisallowedOps(Boolean multiuserMode) {
- String op = "unknown";
- boolean success = false;
- if (!multiuserMode) {
- success = false;
- try {
- // Attempt cache.createAuthenticatedCacheView() and expect an exception, fail otherwise
- op = "Pool.createSecureUserCache()";
- GemFireCacheImpl.getInstance().createAuthenticatedView(new Properties(), "testPool");
- } catch (IllegalStateException uoe) {
- Log.getLogWriter().info(op + ": Got expected exception: " + uoe);
- success = true;
- } catch (Exception e) {
- Assert.fail("Got unexpected exception while doing " + op, e);
- }
- if (!success) {
- fail("Did not get exception while doing " + op);
- }
- } else { // multiuser mode
- Region realRegion = GemFireCacheImpl.getInstance().getRegion(
- SecurityTestUtil.regionName);
- Region proxyRegion = SecurityTestUtil.proxyCaches[0]
- .getRegion(SecurityTestUtil.regionName);
- Pool pool = PoolManagerImpl.getPMI().find("testPool");
- for (int i = 0; i <= 27; i++) {
- success = false;
- try {
- switch (i) {
- // Attempt (real) Region.create/put/get/containsKeyOnServer/destroy/
- // destroyRegion/clear/remove/registerInterest/unregisterInterest()
- // and expect an exception, fail otherwise.
- case 0:
- op = "Region.create()";
- realRegion.create("key", "value");
- break;
- case 1:
- op = "Region.put()";
- realRegion.put("key", "value");
- break;
- case 2:
- op = "Region.get()";
- realRegion.get("key");
- break;
- case 3:
- op = "Region.containsKeyOnServer()";
- realRegion.containsKeyOnServer("key");
- break;
- case 4:
- op = "Region.remove()";
- realRegion.remove("key");
- break;
- case 5:
- op = "Region.destroy()";
- realRegion.destroy("key");
- break;
- case 6:
- op = "Region.destroyRegion()";
- realRegion.destroyRegion();
- break;
- case 7:
- op = "Region.registerInterest()";
- realRegion.registerInterest("key");
- break;
- // case 8:
- // op = "Region.unregisterInterest()";
- // realRegion.unregisterInterest("key");
- // break;
- case 8:
- op = "Region.clear()";
- realRegion.clear();
- break;
- // Attempt ProxyRegion.createSubregion/forceRolling/
- // getAttributesMutator/registerInterest/loadSnapShot/saveSnapshot/
- // setUserAttribute/unregisterInterest/writeToDisk
- // and expect an exception, fail otherwise.
- case 9:
- op = "ProxyRegion.createSubregion()";
- proxyRegion.createSubregion("subregion",
- null);
- break;
- case 10:
- op = "ProxyRegion.forceRolling()";
- proxyRegion.forceRolling();
- break;
- case 11:
- op = "ProxyRegion.getAttributesMutator()";
- proxyRegion.getAttributesMutator();
- break;
- case 12:
- op = "ProxyRegion.registerInterest()";
- proxyRegion.registerInterest("key");
- break;
- case 13:
- op = "ProxyRegion.loadSnapshot()";
- proxyRegion.loadSnapshot(null);
- break;
- case 14:
- op = "ProxyRegion.saveSnapshot()";
- proxyRegion.saveSnapshot(null);
- break;
- case 15:
- op = "ProxyRegion.setUserAttribute()";
- proxyRegion.setUserAttribute(null);
- break;
- case 16:
- op = "ProxyRegion.unregisterInterestRegex()";
- proxyRegion.unregisterInterestRegex("*");
- break;
- // Attempt FunctionService.onRegion/onServer/s(pool) and expect an
- // exception, fail otherwise.
- case 17:
- op = "FunctionService.onRegion()";
- FunctionService.onRegion(realRegion);
- break;
- case 18:
- op = "FunctionService.onServer(pool)";
- FunctionService.onServer(pool);
- break;
- case 19:
- op = "FunctionService.onServers(pool)";
- FunctionService.onServers(pool);
- break;
- // Attempt
- // QueryService.newQuery().execute()/newCq().execute/executeWithInitialResults()
- case 20:
- op = "QueryService.newQuery.execute()";
- Query query = pool.getQueryService().newQuery(
- "SELECT * FROM /" + SecurityTestUtil.regionName);
- query.execute();
- break;
- case 21:
- op = "QueryService.newCq.execute()";
- CqQuery cqQuery = pool.getQueryService().newCq(
- "SELECT * FROM /" + SecurityTestUtil.regionName,
- new CqAttributesFactory().create());
- try {
- cqQuery.execute();
- } catch (CqException ce) {
- throw (Exception)ce.getCause();
- }
- break;
- case 22:
- op = "QueryService.newCq.executeWithInitialResults()";
- cqQuery = pool.getQueryService().newCq(
- "SELECT * FROM /" + SecurityTestUtil.regionName,
- new CqAttributesFactory().create());
- try {
- cqQuery.executeWithInitialResults();
- } catch (CqException ce) {
- throw (Exception)ce.getCause();
- }
- break;
- // Attempt ProxyQueryService.getIndex/createIndex/removeIndex() and
- // expect an exception, fail otherwise.
- case 23:
- op = "ProxyQueryService().getIndexes()";
- SecurityTestUtil.proxyCaches[0].getQueryService()
- .getIndexes(null);
- break;
- case 24:
- op = "ProxyQueryService().createIndex()";
- SecurityTestUtil.proxyCaches[0].getQueryService().createIndex(
- null, null, null );
- break;
- case 25:
- op = "ProxyQueryService().removeIndexes()";
- SecurityTestUtil.proxyCaches[0].getQueryService().removeIndexes();
- break;
- case 26:
- op = "ProxyRegion.localDestroy()";
- proxyRegion.localDestroy("key");
- break;
- case 27:
- op = "ProxyRegion.localInvalidate()";
- proxyRegion.localInvalidate("key");
- break;
- default:
- fail("Unknown op code: " + i);
- break;
- }
- } catch (UnsupportedOperationException uoe) {
- Log.getLogWriter().info(op + ": Got expected exception: " + uoe);
- success = true;
- } catch (Exception e) {
- Assert.fail("Got unexpected exception while doing " + op, e);
- }
- if (!success) {
- fail("Did not get exception while doing " + op);
- }
- }
- }
- }
-
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
- }
-}
[04/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtils.java b/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtils.java
new file mode 100644
index 0000000..663a17d
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/SecurityTestUtils.java
@@ -0,0 +1,1683 @@
+/*
+ * 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.
+ */
+package com.gemstone.gemfire.security;
+
+import static com.gemstone.gemfire.distributed.internal.DistributionConfig.*;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.DistributedTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+import static com.gemstone.gemfire.test.dunit.NetworkUtils.*;
+import static com.gemstone.gemfire.test.dunit.Wait.*;
+
+import static com.gemstone.gemfire.cache30.ClientServerTestCase.configureConnectionPoolWithNameAndFactory;
+
+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.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.Callable;
+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.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.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.Locator;
+import com.gemstone.gemfire.pdx.PdxReader;
+import com.gemstone.gemfire.pdx.PdxSerializable;
+import com.gemstone.gemfire.pdx.PdxWriter;
+import com.gemstone.gemfire.test.dunit.DistributedTestCase;
+import com.gemstone.gemfire.test.dunit.WaitCriterion;
+
+/**
+ * Contains utility methods for setting up servers/clients for authentication
+ * and authorization tests.
+ *
+ * @since 5.5
+ */
+public final class SecurityTestUtils {
+
+ private final DistributedTestCase distributedTestCase = new DistributedTestCase(getClass().getSimpleName()) {}; // TODO: delete
+
+ protected static final int NO_EXCEPTION = 0;
+ protected static final int AUTHREQ_EXCEPTION = 1;
+ protected static final int AUTHFAIL_EXCEPTION = 2;
+ protected static final int CONNREFUSED_EXCEPTION = 3;
+ protected static final int NOTAUTHZ_EXCEPTION = 4;
+ protected static final int OTHER_EXCEPTION = 5;
+ protected static final int NO_AVAILABLE_SERVERS = 6;
+ // Indicates that AuthReqException may not necessarily be thrown
+ protected static final int NOFORCE_AUTHREQ_EXCEPTION = 16;
+
+ protected static final String REGION_NAME = "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" };
+
+ private static final int NUMBER_OF_USERS = 1;
+
+ private static String[] ignoredExceptions = null;
+
+ private static Locator locator = null;
+ private static Cache cache = null;
+ private static Properties currentJavaProps = null;
+ private static String locatorString = null;
+
+ private static Pool pool = null;
+ private static boolean multiUserAuthMode = false;
+
+ private static ProxyCache[] proxyCaches = new ProxyCache[NUMBER_OF_USERS];
+
+ private static Region regionRef = null;
+
+ public SecurityTestUtils(String name) { // TODO: delete
+ }
+
+ /**
+ * @deprecated Please use {@link com.gemstone.gemfire.test.dunit.IgnoredException} instead
+ */
+ private static void addIgnoredExceptions(final String[] expectedExceptions) { // TODO: delete
+ if (expectedExceptions != null) {
+ for (int index = 0; index < expectedExceptions.length; index++) {
+ getLogWriter().info("<ExpectedException action=add>" + expectedExceptions[index] + "</ExpectedException>");
+ }
+ }
+ }
+
+ /**
+ * @deprecated Please use {@link com.gemstone.gemfire.test.dunit.IgnoredException} instead
+ */
+ private static void removeExpectedExceptions(final String[] expectedExceptions) { // TODO: delete
+ if (expectedExceptions != null) {
+ for (int index = 0; index < expectedExceptions.length; index++) {
+ getLogWriter().info("<ExpectedException action=remove>" + expectedExceptions[index] + "</ExpectedException>");
+ }
+ }
+ }
+
+ protected static void setJavaProps(final Properties javaProps) {
+ removeJavaProperties(currentJavaProps);
+ addJavaProperties(javaProps);
+ currentJavaProps = javaProps;
+ }
+
+ protected static ProxyCache getProxyCaches(final int index) {
+ return proxyCaches[index];
+ }
+
+ protected static void initDynamicRegionFactory() {
+ DynamicRegionFactory.get().open(new DynamicRegionFactory.Config(null, null, false, true));
+ }
+
+ protected static int getLocatorPort() {
+ int locatorPort = getRandomAvailablePort(SOCKET);
+ String addr = 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.
+ */
+ protected static String getAndClearLocatorString() {
+ String locString = locatorString;
+ locatorString = null;
+ return locString;
+ }
+
+ protected static Properties concatProperties(final Properties[] propsList) {
+ Properties props = new Properties();
+ for (int index = 0; index < propsList.length; ++index) {
+ if (propsList[index] != null) {
+ props.putAll(propsList[index]);
+ }
+ }
+ return props;
+ }
+
+ protected static void registerExpectedExceptions(final String[] expectedExceptions) { // TODO: delete
+ SecurityTestUtils.ignoredExceptions = expectedExceptions;
+ }
+
+ protected static int createCacheServer(final Properties authProps, final Properties javaProps, final int locatorPort, final String locatorString, final int serverPort, final int expectedResult) {
+ return createCacheServer(authProps, javaProps, locatorPort, locatorString, serverPort, false, expectedResult);
+ }
+
+ protected static int createCacheServer(Properties authProps, final Properties javaProps, final int locatorPort, final String locatorString, final int serverPort, final boolean setupDynamicRegionFactory, final int expectedResult) {
+ if (authProps == null) {
+ authProps = new Properties();
+ }
+ authProps.setProperty(MCAST_PORT_NAME, "0");
+ if (locatorString != null && locatorString.length() > 0) {
+ authProps.setProperty(LOCATORS_NAME, locatorString);
+ authProps.setProperty(START_LOCATOR_NAME, getIPLiteral() + "[" + locatorPort + ']');
+ } else {
+ authProps.setProperty("locators", "localhost["+getDUnitLocatorPort()+"]");
+ }
+ authProps.setProperty(SECURITY_LOG_LEVEL_NAME, "finest");
+
+ getLogWriter().info("Set the server properties to: " + authProps);
+ getLogWriter().info("Set the java properties to: " + javaProps);
+
+ SecurityTestUtils tmpInstance = new SecurityTestUtils("temp");
+ try {
+ tmpInstance.createSystem(authProps, javaProps);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a security exception when starting peer");
+ }
+
+ } catch (AuthenticationRequiredException ex) {
+ if (expectedResult == AUTHREQ_EXCEPTION) {
+ getLogWriter().info("Got expected exception when starting peer: " + ex);
+ return 0;
+ } else {
+ fail("Got unexpected exception when starting peer", ex);
+ }
+
+ } catch (AuthenticationFailedException ex) {
+ if (expectedResult == AUTHFAIL_EXCEPTION) {
+ getLogWriter().info("Got expected exception when starting peer: " + ex);
+ return 0;
+ } else {
+ fail("Got unexpected exception when starting peer", ex);
+ }
+
+ } catch (Exception ex) {
+ fail("Got unexpected exception when starting peer", ex);
+ }
+
+ if (setupDynamicRegionFactory) {
+ initDynamicRegionFactory();
+ }
+
+ tmpInstance.openCache();
+
+ AttributesFactory factory = new AttributesFactory();
+ factory.setScope(Scope.DISTRIBUTED_ACK);
+ factory.setDataPolicy(DataPolicy.REPLICATE);
+
+ RegionAttributes attrs = factory.create();
+
+ cache.createRegion(REGION_NAME, attrs);
+
+ int port = serverPort <= 0 ? 0 : serverPort;
+
+ 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 server1.getPort();
+ }
+
+ // 1
+ protected static void createCacheClient(final String authInitModule, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final int expectedResult) {
+ createCacheClient(authInitModule, authProps, javaProps, ports, numConnections, false, expectedResult);
+ }
+
+ // 2 a
+ protected static void createCacheClient(final String authInitModule, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean multiUserMode, final int expectedResult) {
+ createCacheClient(authInitModule, authProps, javaProps, ports, numConnections, false, multiUserMode, expectedResult);
+ }
+
+ // 3
+ protected static void createCacheClientWithDynamicRegion(final String authInitModule, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean setupDynamicRegionFactory, final int expectedResult) {
+ createCacheClient(authInitModule, authProps, javaProps, ports, numConnections, setupDynamicRegionFactory, false, expectedResult);
+ }
+
+ // 4
+ protected static void createCacheClient(final String authInitModule, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean setupDynamicRegionFactory, final boolean multiUserMode, final int expectedResult) {
+ createCacheClient(authInitModule, authProps, javaProps, ports, numConnections, setupDynamicRegionFactory, multiUserMode, true, expectedResult);
+ }
+
+ // 5
+ protected static void createCacheClient(final String authInitModule, Properties authProps, final Properties javaProps, int[] ports, final int numConnections, final boolean setupDynamicRegionFactory, final boolean multiUserMode, final boolean subscriptionEnabled, final int expectedResult) {
+ multiUserAuthMode = multiUserMode;
+
+ if (authProps == null) {
+ authProps = new Properties();
+ }
+ authProps.setProperty(MCAST_PORT_NAME, "0");
+ authProps.setProperty(LOCATORS_NAME, "");
+ authProps.setProperty(SECURITY_LOG_LEVEL_NAME, "finest");
+ // TODO (ashetkar) Add " && (!multiUserAuthMode)" below.
+ if (authInitModule != null) {
+ authProps.setProperty(SECURITY_CLIENT_AUTH_INIT_NAME, authInitModule);
+ }
+
+ SecurityTestUtils tmpInstance = new SecurityTestUtils("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];
+ }
+
+ 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 = configureConnectionPoolWithNameAndFactory(factory, getIPLiteral(), portsI, subscriptionEnabled, 0, numConnections, null, null, poolFactory);
+
+ if (setupDynamicRegionFactory) {
+ 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(REGION_NAME, attrs);
+
+ if (expectedResult != NO_EXCEPTION && expectedResult != NOFORCE_AUTHREQ_EXCEPTION) {
+ if (!multiUserAuthMode) {
+ fail("Expected an exception when starting client");
+ }
+ }
+
+ } catch (AuthenticationRequiredException ex) {
+ if (expectedResult == AUTHREQ_EXCEPTION || expectedResult == 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 == 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 == 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);
+ }
+ }
+
+ protected static void createCacheClientForMultiUserMode(final int numOfUsers, final String authInitModule, final Properties[] authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean setupDynamicRegionFactory, final int expectedResult) {
+ createCacheClientForMultiUserMode(numOfUsers, authInitModule, authProps, javaProps, ports, numConnections, setupDynamicRegionFactory, null, expectedResult);
+ }
+
+ protected static void createCacheClientForMultiUserMode(final int numOfUsers, final String authInitModule, final Properties[] authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean setupDynamicRegionFactory, final String durableClientId, final int expectedResult) {
+ if (numOfUsers < 1) {
+ fail("Number of users cannot be less than one");
+ }
+
+ multiUserAuthMode = true;
+
+ if (numOfUsers != authProps.length) {
+ fail("Number of authProps provided does not match with numOfUsers specified, " + authProps.length);
+ }
+
+ if (authProps[0] == null) {
+ authProps[0] = new Properties();
+ }
+ authProps[0].setProperty(MCAST_PORT_NAME, "0");
+ authProps[0].setProperty(LOCATORS_NAME, "");
+ authProps[0].setProperty(SECURITY_LOG_LEVEL_NAME, "finest");
+
+ Properties props = new Properties();
+
+ if (authInitModule != null) {
+ authProps[0].setProperty(SECURITY_CLIENT_AUTH_INIT_NAME, authInitModule);
+ props.setProperty(SECURITY_CLIENT_AUTH_INIT_NAME, authInitModule);
+ }
+
+ if (durableClientId != null) {
+ props.setProperty(DURABLE_CLIENT_ID_NAME, durableClientId);
+ props.setProperty(DURABLE_CLIENT_TIMEOUT_NAME, String.valueOf(DEFAULT_DURABLE_CLIENT_TIMEOUT));
+ }
+
+ SecurityTestUtils tmpInstance = new SecurityTestUtils("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];
+ }
+
+ try {
+ tmpInstance.openCache();
+
+ PoolFactory poolFactory = PoolManager.createFactory();
+ poolFactory.setRetryAttempts(200);
+ poolFactory.setMultiuserAuthentication(multiUserAuthMode);
+ poolFactory.setSubscriptionEnabled(true);
+
+ pool = configureConnectionPoolWithNameAndFactory(factory, getIPLiteral(), portsI, true, 1, numConnections, null, null, poolFactory);
+
+ if (setupDynamicRegionFactory) {
+ 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(REGION_NAME, attrs);
+
+ if (expectedResult != NO_EXCEPTION && expectedResult != NOFORCE_AUTHREQ_EXCEPTION) {
+ if (!multiUserAuthMode) {
+ fail("Expected an exception when starting client");
+ }
+ }
+
+ } catch (AuthenticationRequiredException ex) {
+ if (expectedResult == AUTHREQ_EXCEPTION || expectedResult == 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 == 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 == 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);
+ }
+ }
+
+ protected static void createProxyCache(final int[] userIndices, final Properties[] props) {
+ int j = 0;
+ for (int i : userIndices) {
+ proxyCaches[i] = (ProxyCache)((PoolImpl) pool).createAuthenticatedCacheView(props[j]);
+ j++;
+ }
+ }
+
+ protected static void startLocator(final String name, int port, final Properties extraProps, final Properties javaProps, final String[] expectedExceptions) {
+ try {
+ Properties authProps = new Properties();
+
+ if (extraProps != null) {
+ authProps.putAll(extraProps);
+ }
+ authProps.setProperty(MCAST_PORT_NAME, "0");
+ authProps.setProperty(LOCATORS_NAME, getIPLiteral() + "[" + port + "]");
+ authProps.setProperty(ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+
+ clearStaticSSLContext();
+
+ setJavaProps(javaProps);
+
+ File logFile = new File(name + "-locator" + port + ".log");
+ FileOutputStream logOut = new FileOutputStream(logFile);
+ PrintStream logStream = new PrintStream(logOut);
+ addIgnoredExceptions(expectedExceptions);
+ logStream.flush();
+
+ locator = Locator.startLocatorAndDS(port, logFile, null, authProps);
+
+ } catch (IOException ex) {
+ fail("While starting locator on port " + port, ex);
+ }
+ }
+
+ protected static void stopLocator(final int port, final String[] expectedExceptions) {
+ try {
+ locator.stop();
+ removeExpectedExceptions(expectedExceptions);
+
+ } catch (Exception ex) {
+ fail("While stopping locator on port " + port, ex);
+ }
+ }
+
+ protected static Cache getCache() {
+ return cache;
+ }
+
+ protected static void waitForCondition(final Callable<Boolean> condition) {
+ waitForCondition(condition, 100, 120);
+ }
+
+ protected static void waitForCondition(final Callable<Boolean> condition, final int sleepMillis, final int numTries) {
+ WaitCriterion ev = new WaitCriterion() {
+ @Override
+ public boolean done() {
+ try {
+ return condition.call();
+ } catch (Exception e) {
+ fail("Unexpected exception", e);
+ }
+ return false; // NOTREACHED
+ }
+ @Override
+ public String description() {
+ return null;
+ }
+ };
+ waitForCriterion(ev, sleepMillis * numTries, 200, true);
+ }
+
+ protected static Object getLocalValue(final Region region, final Object key) {
+ Region.Entry entry = region.getEntry(key);
+ return (entry != null ? entry.getValue() : null);
+ }
+
+ protected static void doProxyCacheClose() {
+ for (int i = 0; i< proxyCaches.length; i++) {
+ proxyCaches[i].close();
+ }
+ }
+
+ protected static void doPutAllP() throws Exception {
+ Region region = getCache().getRegion(REGION_NAME);
+ assertNotNull(region);
+
+ Map<String, Employee> map = new LinkedHashMap<>();
+ map.put("1010L", new Employee(1010L, "John", "Doe"));
+
+ region.putAll(map);
+ }
+
+ protected static void doPuts(final int num) {
+ doPutsP(num, NO_EXCEPTION, false);
+ }
+
+ protected static void doPuts(final int num, final int expectedResult) {
+ doPutsP(num, expectedResult, false);
+ }
+
+ protected static void doMultiUserPuts(final int num, final int numOfUsers, final int[] expectedResults) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserPuts(): numOfUsers = " + numOfUsers + ", but expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("PUT: MultiUser# " + i);
+ doPutsP(num, i, expectedResults[i], false);
+ }
+ }
+
+ protected static void doGets(final int num) {
+ doGetsP(num, NO_EXCEPTION, false);
+ }
+
+ protected static void doGets(final int num, final int expectedResult) {
+ doGetsP(num, expectedResult, false);
+ }
+
+ protected static void doMultiUserGetAll(final int numOfUsers, final int[] expectedResults) {
+ doMultiUserGetAll(numOfUsers, expectedResults, false);
+ }
+
+ protected static void doMultiUserGetAll(final int numOfUsers, final int[] expectedResults, final boolean useTX) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.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(i, expectedResults[i], useTX);
+ }
+ }
+
+ protected static void doMultiUserGets(final int num, final int numOfUsers, final int[] expectedResults) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserGets(): numOfUsers = " + numOfUsers + ", but expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("GET: MultiUser# " + i);
+ doGetsP(num, i, expectedResults[i], false);
+ }
+ }
+
+ protected static void doMultiUserRegionDestroys(final int numOfUsers, final int[] expectedResults) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserRegionDestroys(): numOfUsers = " + numOfUsers + ", but expected results " + expectedResults.length);
+ }
+
+ for (int i = numOfUsers-1; i >= 0; i--) {
+ getLogWriter().info("DESTROY: MultiUser# " + i);
+ doRegionDestroysP(i, expectedResults[i]);
+ }
+ }
+
+ protected static void doMultiUserDestroys(final int num, final int numOfUsers, final int[] expectedResults) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserDestroys(): numOfUsers = " + numOfUsers + ", but expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("DESTROY: MultiUser# " + i);
+ doDestroysP(num, i, expectedResults[i]);
+ }
+ }
+
+ protected static void doMultiUserInvalidates(final int num, final int numOfUsers, final int[] expectedResults) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserInvalidates(): numOfUsers = " + numOfUsers + ", but expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("INVALIDATE: MultiUser# " + i);
+ doInvalidatesP(num, i, expectedResults[i]);
+ }
+ }
+
+ protected static void doMultiUserContainsKeys(final int num, final int numOfUsers, final int[] expectedResults, final boolean[] results) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserContainsKeys(): numOfUsers = " + numOfUsers + ", but #expected results " + expectedResults.length);
+ }
+
+ if (numOfUsers != results.length) {
+ fail("SecurityTestUtils.doMultiUserContainsKeys(): numOfUsers = " + numOfUsers + ", but #expected output " + results.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("CONTAINS_KEY: MultiUser# " + i);
+ doContainsKeysP(num, i, expectedResults[i], results[i]);
+ }
+ }
+
+ protected static void doMultiUserQueries(final int numOfUsers, final int[] expectedResults, final int valueSize) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserQueries(): numOfUsers = " + numOfUsers + ", but #expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("QUERY: MultiUser# " + i);
+ doQueriesP(i, expectedResults[i], valueSize);
+ }
+ }
+
+ protected static void doMultiUserFE(final int numOfUsers, final Function function, final int[] expectedResults, final boolean isFailOverCase) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserFE(): numOfUsers = " + numOfUsers + ", but #expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("FunctionExecute:onRegion MultiUser# " + i);
+ doFunctionExecuteP(i, function, expectedResults[i], "region");
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("FunctionExecute:onServer MultiUser# " + i);
+ doFunctionExecuteP(i, function, expectedResults[i], "server");
+ }
+
+ if (!isFailOverCase) {
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("FunctionExecute:onServers MultiUser# " + i);
+ doFunctionExecuteP(i, function, expectedResults[i], "servers");
+ }
+ }
+ }
+
+ protected static void doMultiUserQueryExecute(final int numOfUsers, final int[] expectedResults, final int result) {
+ if (numOfUsers != expectedResults.length) {
+ fail("SecurityTestUtils.doMultiUserFE(): numOfUsers = " + numOfUsers + ", but #expected results " + expectedResults.length);
+ }
+
+ for (int i = 0; i < numOfUsers; i++) {
+ getLogWriter().info("QueryExecute: MultiUser# " + i);
+ doQueryExecuteP(i, expectedResults[i], result);
+ }
+ }
+
+ protected static void doLocalGets(final int num) {
+ doLocalGetsP(num, false);
+ }
+
+ protected static void doNPuts(final int num) {
+ doPutsP(num, NO_EXCEPTION, true);
+ }
+
+ protected static void doNPuts(final int num, final int expectedResult) {
+ doPutsP(num, expectedResult, true);
+ }
+
+ protected static void doNGets(final int num) {
+ doGetsP(num, NO_EXCEPTION, true);
+ }
+
+ protected static void doNGets(final int num, final int expectedResult) {
+ doGetsP(num, expectedResult, true);
+ }
+
+ protected static void doNLocalGets(final int num) {
+ doLocalGetsP(num, true);
+ }
+
+ protected static void doSimpleGet(final 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()");
+ }
+ }
+ }
+ }
+
+ protected static void doSimplePut(final 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()");
+ }
+ }
+ }
+ }
+
+ /**
+ * 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.
+ */
+ protected static void clearStaticSSLContext() {
+ ServerSocketFactory defaultServerFact = SSLServerSocketFactory.getDefault();
+
+ // Get the class of this and use reflection to blank out any static SSLContext objects inside
+ Map<Field, Object> contextMap = getSSLFields(defaultServerFact, new Class[] { SSLContext.class, SSLContextSpi.class });
+ makeNullSSLFields(defaultServerFact, contextMap);
+
+ for (Iterator contextObjsIter = contextMap.values().iterator(); contextObjsIter.hasNext();) {
+ Object contextObj = contextObjsIter.next();
+ Map<Field, Object> 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);
+
+ for (Iterator contextObjsIter = contextMap.values().iterator(); contextObjsIter.hasNext();) {
+ Object contextObj = contextObjsIter.next();
+ Map<Field, Object> contextObjsMap = getSSLFields(contextObj, new Class[] { TrustManager.class, KeyManager.class, TrustManager[].class, KeyManager[].class });
+ makeNullSSLFields(contextObj, contextObjsMap);
+ }
+
+ makeNullStaticField(SSLSocketFactory.class);
+ makeNullStaticField(SSLContext.class);
+ }
+
+ protected static void closeCache() {
+ removeExpectedExceptions(ignoredExceptions);
+
+ if (cache != null && !cache.isClosed()) {
+ DistributedSystem sys = cache.getDistributedSystem();
+ cache.close();
+ sys.disconnect();
+ cache = null;
+ }
+
+ DistributedTestCase.disconnectFromDS();
+ }
+
+ protected static void closeCache(final Boolean keepAlive) {
+ removeExpectedExceptions(ignoredExceptions);
+
+ if (cache != null && !cache.isClosed()) {
+ DistributedSystem sys = cache.getDistributedSystem();
+ cache.close(keepAlive);
+ sys.disconnect();
+ cache = null;
+ }
+
+ DistributedTestCase.disconnectFromDS();
+ }
+
+ // ------------------------- private static methods -------------------------
+
+ private static void initClientDynamicRegionFactory(final String poolName) {
+ DynamicRegionFactory.get().open(new DynamicRegionFactory.Config(null, poolName, false, true));
+ }
+
+ private static void addJavaProperties(final Properties javaProps) {
+ if (javaProps != null) {
+ for (Iterator iter = javaProps.entrySet().iterator(); iter.hasNext();) {
+ Map.Entry entry = (Map.Entry)iter.next();
+ System.setProperty((String)entry.getKey(), (String)entry.getValue());
+ }
+ }
+ }
+
+ private static void removeJavaProperties(final Properties javaProps) {
+ if (javaProps != null) {
+ Properties props = System.getProperties();
+
+ for (Iterator iter = javaProps.keySet().iterator(); iter.hasNext();) {
+ props.remove(iter.next());
+ }
+
+ System.setProperties(props);
+ }
+ }
+
+ private static void doPutsP(final int num, final int expectedResult, final boolean newVals) {
+ doPutsP(num, 0, expectedResult, newVals);
+ }
+
+ private static void doPutsP(final int num, final int multiUserIndex, final int expectedResult, final boolean newVals) {
+ assertTrue(num <= KEYS.length);
+ Region region = null;
+
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ regionRef = region;
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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; ++index) {
+ try {
+ if (newVals) {
+ region.put(KEYS[index], NVALUES[index]);
+ } else {
+ region.put(KEYS[index], VALUES[index]);
+ }
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing puts");
+ }
+
+ } catch(NoAvailableServersException ex) {
+ if(expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing puts: " + ex.getCause());
+ continue;
+ }
+
+ if ((expectedResult == AUTHREQ_EXCEPTION) && (ex.getCause() instanceof AuthenticationRequiredException)) {
+ getLogWriter().info("Got expected AuthenticationRequiredException when doing puts: " + ex.getCause());
+ continue;
+ }
+
+ if ((expectedResult == AUTHFAIL_EXCEPTION) && (ex.getCause() instanceof AuthenticationFailedException)) {
+ getLogWriter().info("Got expected AuthenticationFailedException when doing puts: " + ex.getCause());
+ continue;
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when doing puts: " + ex);
+ } else {
+ fail("Got unexpected exception when doing puts", ex);
+ }
+ }
+ }
+ }
+
+ private static Map<Field, Object> getSSLFields(final Object obj, final Class[] classes) {
+ Map<Field, Object> 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;
+ }
+
+ private static void makeNullSSLFields(final Object obj, final Map<Field, Object> fieldMap) {
+ for (Iterator<Map.Entry<Field, Object>> fieldIter = fieldMap.entrySet().iterator(); fieldIter.hasNext();) {
+ Map.Entry<Field, Object> entry = fieldIter.next();
+ 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);
+ }
+ }
+ }
+
+ /**
+ * Deal with javax SSL properties
+ */
+ private static void makeNullStaticField(final Class sslClass) {
+ Field[] fields = sslClass.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 (sslClass.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 doQueryExecuteP(final int multiUserIndex, final int expectedResult, final int expectedValue) {
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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 != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while executing function");
+ }
+ assertEquals(expectedValue, result.asList().size());
+
+ } catch (NoAvailableServersException ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when executing query: " + ex.getCause());
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when executing query: " + ex);
+ } else {
+ fail("Got unexpected exception when executing query", ex);
+ }
+ }
+ }
+
+ private static void doFunctionExecuteP(final int multiUserIndex, final Function function, int expectedResult, final String method) {
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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 != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while executing function");
+ }
+
+ } catch (NoAvailableServersException ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when executing function: " + ex.getCause());
+ } else if (expectedResult == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when executing function: " + ex);
+ } else {
+ fail("Got unexpected exception when executing function", ex);
+ }
+
+ } catch (FunctionException ex) {
+ // if NOTAUTHZ_EXCEPTION AND (cause is NotAuthorizedException OR (cause is ServerOperationException AND cause.cause is NotAuthorizedException))
+ if (expectedResult == NOTAUTHZ_EXCEPTION && (ex.getCause() instanceof NotAuthorizedException || (ex.getCause() instanceof ServerOperationException && ex.getCause().getCause() instanceof NotAuthorizedException)) ) {
+ getLogWriter().info("Got expected NotAuthorizedException when executing function: " + ex.getCause());
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when executing function: " + ex);
+ } else {
+ fail("Got unexpected exception when executing function", ex);
+ }
+ }
+ }
+
+ private static void doQueriesP(final int multiUserIndex, final int expectedResult, final int expectedValue) {
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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, resultSet.size());
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing queries");
+ }
+
+ } catch (NoAvailableServersException ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing queries: " + ex.getCause());
+ } else if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (qite.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing queries: " + qite.getCause());
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when doing queries: " + ex);
+ } else {
+ fail("Got unexpected exception when doing queries", ex);
+ }
+ }
+ }
+
+ private static void doContainsKeysP(final int num, final int multiUserIndex, final int expectedResult, final boolean expectedValue) {
+ assertTrue(num <= KEYS.length);
+
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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; ++index) {
+ boolean result = false;
+
+ try {
+ result = region.containsKeyOnServer(KEYS[index]);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing containsKey");
+ }
+
+ } catch(NoAvailableServersException ex) {
+ if(expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing containsKey: " + ex.getCause());
+ continue;
+ } else if (expectedResult == 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 == 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 doInvalidatesP(final int num, final int multiUserIndex, final int expectedResult) {
+ assertTrue(num <= KEYS.length);
+
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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; ++index) {
+ try {
+ region.invalidate(KEYS[index]);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing invalidates");
+ }
+
+ } catch(NoAvailableServersException ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing invalidates: " + ex.getCause());
+ continue;
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when doing invalidates: " + ex);
+ } else {
+ fail("Got unexpected exception when doing invalidates", ex);
+ }
+ }
+ }
+ }
+
+ private static void doDestroysP(final int num, final int multiUserIndex, final int expectedResult) {
+ assertTrue(num <= KEYS.length);
+
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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; ++index) {
+ try {
+ region.destroy(KEYS[index]);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing destroys");
+ }
+
+ } catch(NoAvailableServersException ex) {
+ if(expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing destroys: " + ex.getCause());
+ continue;
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when doing destroys: " + ex);
+ } else {
+ fail("Got unexpected exception when doing destroys", ex);
+ }
+ }
+ }
+ }
+
+ private static void doRegionDestroysP(final int multiUserIndex, final int expectedResult) {
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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 != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing region destroy");
+ }
+
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNull(region);
+
+ } catch (NoAvailableServersException ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing region destroy: " + ex.getCause());
+ } else if (expectedResult == 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 == 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 doLocalGetsP(final int num, final boolean checkNVals) {
+ assertTrue(num <= KEYS.length);
+
+ String[] vals = VALUES;
+ if (checkNVals) {
+ vals = NVALUES;
+ }
+
+ final Region region = getCache().getRegion(REGION_NAME);
+ assertNotNull(region);
+
+ for (int index = 0; index < num; ++index) {
+ final String key = KEYS[index];
+ final String expectedVal = vals[index];
+ waitForCondition(() -> expectedVal.equals(getLocalValue(region, key)), 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 doGetAllP(final int multiUserIndex, final int expectedResult, final boolean useTX) {
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION)) {
+ assertEquals(0, entries.size());
+ } else if ((expectedResult == NO_EXCEPTION)) {
+ assertEquals(2, entries.size());
+ assertEquals("value1", entries.get("key1"));
+ assertEquals("value2", entries.get("key2"));
+ }
+
+ } catch (NoAvailableServersException ex) {
+ if (expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing getAll: " + ex.getCause());
+ } else if (expectedResult == 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 == OTHER_EXCEPTION) {
+ getLogWriter().info("Got expected exception when doing getAll: " + ex);
+ } else {
+ fail("Got unexpected exception when doing getAll", ex);
+ }
+ }
+ }
+
+ private static void doGetsP(final int num, final int expectedResult, final boolean newVals) {
+ doGetsP(num, 0, expectedResult, newVals);
+ }
+
+ private static void doGetsP(final int num, final int multiUserIndex, final int expectedResult, final boolean newVals) {
+ assertTrue(num <= KEYS.length);
+
+ Region region = null;
+ try {
+ if (multiUserAuthMode) {
+ region = proxyCaches[multiUserIndex].getRegion(REGION_NAME);
+ } else {
+ region = getCache().getRegion(REGION_NAME);
+ }
+ assertNotNull(region);
+
+ } catch (Exception ex) {
+ if (expectedResult == 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; ++index) {
+ Object value = null;
+ try {
+
+ try {
+ region.localInvalidate(KEYS[index]);
+ } catch (Exception ex) {
+ }
+
+ value = region.get(KEYS[index]);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing gets");
+ }
+
+ } catch(NoAvailableServersException ex) {
+ if(expectedResult == 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ getLogWriter().info("Got expected NotAuthorizedException when doing gets: " + ex.getCause());
+ continue;
+ } else if (expectedResult == 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 == 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);
+ }
+ }
+ }
+
+ // ----------------------------- member methods -----------------------------
+
+ public DistributedSystem createSystem(final Properties sysProps, final Properties javaProps) {
+ closeCache();
+ clearStaticSSLContext();
+ setJavaProps(javaProps);
+
+ DistributedSystem dsys = distributedTestCase.getSystem(sysProps);
+ assertNotNull(dsys);
+ addIgnoredExceptions(ignoredExceptions);
+ return dsys;
+ }
+
+ private void openCache() {
+ assertNotNull(distributedTestCase.basicGetSystem());
+ assertTrue(distributedTestCase.basicGetSystem().isConnected());
+ cache = CacheFactory.create(distributedTestCase.basicGetSystem());
+ assertNotNull(cache);
+ }
+
+ // ------------------------------- inner classes ----------------------------
+
+ private static class Employee implements PdxSerializable {
+
+ private Long Id;
+ private String fname;
+ private String lname;
+
+ public Employee() {}
+
+ public Employee(Long id, String fn, String ln){
+ this.Id = id;
+ this.fname = fn;
+ this.lname = ln;
+ }
+
+ /**
+ * For test purpose, to make sure
+ * the object is not deserialized
+ */
+ @Override
+ public void fromData(PdxReader in) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void toData(PdxWriter out) {
+ out.writeLong("Id", Id);
+ out.writeString("fname", fname);
+ out.writeString("lname", lname);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTwoDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTwoDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTwoDUnitTest.java
index 336898e..e2950c2 100644
--- a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTwoDUnitTest.java
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTwoDUnitTest.java
@@ -16,9 +16,13 @@
*/
package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.IgnoredException.*;
+
import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.IgnoredException;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* Tests for authorization from client to server. This tests for authorization
@@ -31,206 +35,133 @@ import com.gemstone.gemfire.test.dunit.IgnoredException;
*
* @since 5.5
*/
-public class ClientAuthorizationTwoDUnitTest extends
- ClientAuthorizationTestBase {
+@Category(DistributedTest.class)
+public class ClientAuthorizationTwoDUnitTest extends ClientAuthorizationTestCase {
-
- /** constructor */
- public ClientAuthorizationTwoDUnitTest(String name) {
- super(name);
+ @Override
+ public final void postSetUpClientAuthorizationTestBase() throws Exception {
+ addIgnoredException("Read timed out");
+ addIgnoredException("Connection reset");
+ addIgnoredException("SocketTimeoutException");
+ addIgnoredException("ServerConnectivityException");
+ addIgnoredException("Socket Closed");
}
@Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client1.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+ public final void preTearDownClientAuthorizationTestBase() throws Exception {
+ closeCache();
}
- // Region: Tests
-
- public void testAllOpsWithFailover2() {
- IgnoredException.addIgnoredException("Read timed out");
- IgnoredException.addIgnoredException("Connection reset");
- IgnoredException.addIgnoredException("SocketTimeoutException");
- IgnoredException.addIgnoredException("ServerConnectivityException");
- IgnoredException.addIgnoredException("Socket Closed");
-
- OperationWithAction[] allOps = {
- // Register interest in all keys using list
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 3,
- OpFlags.USE_LIST | OpFlags.CHECK_NOTAUTHZ, 4),
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 1,
- OpFlags.USE_LIST, 4),
+ @Test
+ public void testAllOpsWithFailover2() throws Exception {
+ runOpsWithFailOver(allOps(), "testAllOpsWithFailover2");
+ }
+
+ private OperationWithAction[] allOps() {
+ return new OperationWithAction[] {
+ // Register interest in all KEYS using list
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 3, OpFlags.USE_LIST | OpFlags.CHECK_NOTAUTHZ, 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),
+ new OperationWithAction(OperationCode.GET, 1, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
- // Unregister interest in all keys using list
- new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 1,
- OpFlags.USE_OLDCONN | OpFlags.USE_LIST, 4),
+ // Unregister interest in all KEYS using list
+ 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),
+ 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, 3,
- OpFlags.USE_REGEX | OpFlags.CHECK_NOTAUTHZ, 4),
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 2,
- OpFlags.USE_REGEX, 4),
+ // Register interest in all KEYS using regular expression
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 3, OpFlags.USE_REGEX | OpFlags.CHECK_NOTAUTHZ, 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),
+ 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, 2,
- OpFlags.USE_OLDCONN | OpFlags.USE_REGEX, 4),
+ // Unregister interest in all KEYS using regular expression
+ 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),
+ 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 ALL_KEYS
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 3,
- OpFlags.USE_ALL_KEYS | OpFlags.CHECK_NOTAUTHZ, 4),
- new OperationWithAction(OperationCode.REGISTER_INTEREST, 2,
- OpFlags.USE_ALL_KEYS, 4),
+ // Register interest in all KEYS using ALL_KEYS
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 3, OpFlags.USE_ALL_KEYS | OpFlags.CHECK_NOTAUTHZ, 4),
+ new OperationWithAction(OperationCode.REGISTER_INTEREST, 2, OpFlags.USE_ALL_KEYS, 4),
// UPDATE and test with GET
new OperationWithAction(OperationCode.PUT),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP, 4),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
- // Unregister interest in all keys using ALL_KEYS
- new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 2,
- OpFlags.USE_OLDCONN | OpFlags.USE_ALL_KEYS, 4),
+ // Unregister interest in all KEYS using ALL_KEYS
+ new OperationWithAction(OperationCode.UNREGISTER_INTEREST, 2, OpFlags.USE_OLDCONN | OpFlags.USE_ALL_KEYS, 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),
+ 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 CQ
new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_NEWVAL, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 3,
- OpFlags.CHECK_NOTAUTHZ, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 1,
- OpFlags.USE_NEWVAL, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 3, OpFlags.CHECK_NOTAUTHZ, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 1, OpFlags.USE_NEWVAL, 4),
// UPDATE and test with GET
new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 1,
- OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 1, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
// Stop CQ
- new OperationWithAction(OperationCode.STOP_CQ, 3, OpFlags.USE_OLDCONN
- | OpFlags.CHECK_EXCEPTION, 4),
- new OperationWithAction(OperationCode.STOP_CQ, 1, OpFlags.USE_OLDCONN,
- 4),
+ new OperationWithAction(OperationCode.STOP_CQ, 3, OpFlags.USE_OLDCONN | OpFlags.CHECK_EXCEPTION, 4),
+ new OperationWithAction(OperationCode.STOP_CQ, 1, OpFlags.USE_OLDCONN, 4),
// UPDATE and test with GET for no updates
- new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 1,
- OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL | OpFlags.LOCAL_OP, 4),
+ new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 1, OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL | OpFlags.LOCAL_OP, 4),
// Restart the CQ
- new OperationWithAction(OperationCode.EXECUTE_CQ, 3, OpFlags.USE_NEWVAL
- | OpFlags.CHECK_NOTAUTHZ, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 1,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 3, OpFlags.USE_NEWVAL | OpFlags.CHECK_NOTAUTHZ, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
// UPDATE and test with GET
new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 1,
- OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 1, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
// Close CQ
- new OperationWithAction(OperationCode.CLOSE_CQ, 3, OpFlags.USE_OLDCONN,
- 4),
- new OperationWithAction(OperationCode.CLOSE_CQ, 1, OpFlags.USE_OLDCONN,
- 4),
+ new OperationWithAction(OperationCode.CLOSE_CQ, 3, OpFlags.USE_OLDCONN, 4),
+ new OperationWithAction(OperationCode.CLOSE_CQ, 1, OpFlags.USE_OLDCONN, 4),
// UPDATE and test with GET for no updates
- new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 4),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 1,
- OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL | OpFlags.LOCAL_OP, 4),
+ new OperationWithAction(OperationCode.PUT, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 1, OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL | OpFlags.LOCAL_OP, 4),
OperationWithAction.OPBLOCK_END,
// Do REGION_CLEAR and check with GET
- new OperationWithAction(OperationCode.REGION_CLEAR, 3,
- OpFlags.CHECK_NOTAUTHZ, 1),
+ new OperationWithAction(OperationCode.REGION_CLEAR, 3, OpFlags.CHECK_NOTAUTHZ, 1),
new OperationWithAction(OperationCode.REGION_CLEAR, 1, OpFlags.NONE, 1),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_FAIL, 8),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY | OpFlags.CHECK_FAIL, 8),
// Repopulate the region
new OperationWithAction(OperationCode.PUT),
OperationWithAction.OPBLOCK_END,
// Do REGION_CREATE and check with CREATE/GET
- new OperationWithAction(OperationCode.REGION_CREATE, 3,
- OpFlags.ENABLE_DRF | OpFlags.CHECK_NOTAUTHZ, 1),
- new OperationWithAction(OperationCode.REGION_CREATE, 1,
- OpFlags.ENABLE_DRF, 1),
- new OperationWithAction(OperationCode.PUT, 3, OpFlags.USE_OLDCONN
- | OpFlags.USE_SUBREGION | OpFlags.CHECK_NOTAUTHZ, 4),
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_SUBREGION, 4),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY
- | OpFlags.USE_SUBREGION, 4),
+ new OperationWithAction(OperationCode.REGION_CREATE, 3, OpFlags.ENABLE_DRF | OpFlags.CHECK_NOTAUTHZ, 1),
+ new OperationWithAction(OperationCode.REGION_CREATE, 1, OpFlags.ENABLE_DRF, 1),
+ new OperationWithAction(OperationCode.PUT, 3, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION | OpFlags.CHECK_NOTAUTHZ, 4),
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION, 4),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY | OpFlags.USE_SUBREGION, 4),
// Do REGION_DESTROY of the sub-region and check with GET
- new OperationWithAction(OperationCode.REGION_DESTROY, 3,
- OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION
- | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOTAUTHZ, 1),
- new OperationWithAction(OperationCode.REGION_DESTROY, 1,
- OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION
- | OpFlags.NO_CREATE_SUBREGION, 1),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_SUBREGION | OpFlags.CHECK_EXCEPTION, 4),
+ new OperationWithAction(OperationCode.REGION_DESTROY, 3, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION | OpFlags.NO_CREATE_SUBREGION | OpFlags.CHECK_NOTAUTHZ, 1),
+ new OperationWithAction(OperationCode.REGION_DESTROY, 1, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION | OpFlags.NO_CREATE_SUBREGION, 1),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_SUBREGION | OpFlags.CHECK_EXCEPTION, 4),
// Do REGION_DESTROY of the region and check with GET
- new OperationWithAction(OperationCode.REGION_DESTROY, 3,
- OpFlags.CHECK_NOTAUTHZ, 1),
- new OperationWithAction(OperationCode.REGION_DESTROY, 1, OpFlags.NONE,
- 1),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_EXCEPTION, 4),
-
- // Skip failover for region destroy since it shall fail
- // without restarting the server
- OperationWithAction.OPBLOCK_NO_FAILOVER };
+ new OperationWithAction(OperationCode.REGION_DESTROY, 3, OpFlags.CHECK_NOTAUTHZ, 1),
+ new OperationWithAction(OperationCode.REGION_DESTROY, 1, OpFlags.NONE, 1),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY | OpFlags.CHECK_EXCEPTION, 4),
- runOpsWithFailover(allOps, "testAllOpsWithFailover2");
- }
-
- // End Region: Tests
-
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- SecurityTestUtil.closeCache();
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ // Skip failover for region destroy since it shall fail without restarting the server
+ OperationWithAction.OPBLOCK_NO_FAILOVER };
}
}
[03/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthzObjectModDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthzObjectModDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthzObjectModDUnitTest.java
index 346dff8..0e8e57f 100644
--- a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthzObjectModDUnitTest.java
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientAuthzObjectModDUnitTest.java
@@ -16,28 +16,30 @@
*/
package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.distributed.internal.DistributionConfig.*;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
+import com.gemstone.gemfire.DataSerializable;
+import com.gemstone.gemfire.Instantiator;
+import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
import com.gemstone.gemfire.internal.security.FilterPostAuthorization;
import com.gemstone.gemfire.internal.security.FilterPreAuthorization;
+import com.gemstone.gemfire.internal.security.ObjectWithAuthz;
import com.gemstone.gemfire.security.generator.CredentialGenerator;
import com.gemstone.gemfire.security.generator.DummyAuthzCredentialGenerator;
import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
import com.gemstone.gemfire.security.templates.UserPasswordAuthInit;
-
-import com.gemstone.gemfire.DataSerializable;
-import com.gemstone.gemfire.Instantiator;
-import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.AvailablePort;
-import com.gemstone.gemfire.internal.security.ObjectWithAuthz;
-import com.gemstone.gemfire.test.dunit.DistributedTestCase;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
import com.gemstone.gemfire.test.dunit.SerializableRunnable;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* Tests for authorization callback that modify objects and callbacks from
@@ -55,73 +57,14 @@ import com.gemstone.gemfire.test.dunit.SerializableRunnable;
*
* @since 5.5
*/
-public class ClientAuthzObjectModDUnitTest extends ClientAuthorizationTestBase {
-
-
- /** constructor */
- public ClientAuthzObjectModDUnitTest(String name) {
- super(name);
- }
+@Category(DistributedTest.class)
+public class ClientAuthzObjectModDUnitTest extends ClientAuthorizationTestCase {
private static final String preAccessor = FilterPreAuthorization.class.getName() + ".create";
-
private static final String postAccessor = FilterPostAuthorization.class.getName() + ".create";
- private static class TestPostCredentialGenerator implements
- TestCredentialGenerator {
-
- public TestPostCredentialGenerator() {
- }
-
- public Properties getAllowedCredentials(OperationCode[] opCodes,
- String[] regionNames, int[] keyIndices, int num) {
-
- int userIndex = 1;
- byte role = DummyAuthzCredentialGenerator.getRequiredRole(opCodes);
- if (role == DummyAuthzCredentialGenerator.READER_ROLE) {
- userIndex = keyIndices[0] + 1;
- }
- Properties props = new Properties();
- props.setProperty(UserPasswordAuthInit.USER_NAME, "user" + userIndex);
- props.setProperty(UserPasswordAuthInit.PASSWORD, "user" + userIndex);
- return props;
- }
-
- public Properties getDisallowedCredentials(OperationCode[] opCodes,
- String[] regionNames, int[] keyIndices, int num) {
-
- int userIndex = 0;
- for (int index = 0; index < keyIndices.length; ++index) {
- if (keyIndices[index] != index) {
- userIndex = index + 1;
- break;
- }
- }
- Properties props = new Properties();
- props.setProperty(UserPasswordAuthInit.USER_NAME, "gemfire" + userIndex);
- props.setProperty(UserPasswordAuthInit.PASSWORD, "gemfire" + userIndex);
- return props;
- }
-
- public CredentialGenerator getCredentialGenerator() {
-
- return null;
- }
- }
-
@Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
-
+ protected final void postSetUpClientAuthorizationTestBase() throws Exception {
//required by FilterPreAuthorization and FilterPostAuthorization. Normally,
//this would be automatically registered in the static initializer, but with dunit
//a previous test may have already loaded these classes. We clear the instantiators
@@ -135,271 +78,208 @@ public class ClientAuthzObjectModDUnitTest extends ClientAuthorizationTestBase {
server2.invoke(registerInstantiator);
}
- // Region: Utility and static functions invoked by the tests
-
- private static Properties buildProperties(String authenticator,
- Properties extraProps, String preAccessor, String postAccessor) {
+ @Test
+ public void testAllOpsObjectModWithFailover() throws Exception {
+ OperationWithAction[] allOps = allOps();
- Properties authProps = new Properties();
- if (authenticator != null) {
- authProps.setProperty(
- DistributionConfig.SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
- }
- if (preAccessor != null) {
- authProps.setProperty(DistributionConfig.SECURITY_CLIENT_ACCESSOR_NAME,
- preAccessor);
- }
- if (postAccessor != null) {
- authProps.setProperty(
- DistributionConfig.SECURITY_CLIENT_ACCESSOR_PP_NAME, postAccessor);
- }
- if (extraProps != null) {
- authProps.putAll(extraProps);
- }
- return authProps;
- }
+ TestPostCredentialGenerator tgen = new TestPostCredentialGenerator();
- public static Integer createCacheServer(Integer mcastPort,
- Properties authProps) {
+ CredentialGenerator credentialGenerator = new DummyCredentialGenerator();
+ credentialGenerator.init();
+ Properties extraProps = credentialGenerator.getSystemProperties();
+ Properties javaProps = credentialGenerator.getJavaProperties();
+ String authInit = credentialGenerator.getAuthInit();
+ String authenticator = credentialGenerator.getAuthenticator();
- if (mcastPort == null) {
- mcastPort = new Integer(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- }
- return SecurityTestUtil.createCacheServer(authProps, null, mcastPort, null,
- null, Boolean.FALSE, new Integer(SecurityTestUtil.NO_EXCEPTION));
- }
+ getLogWriter().info("testPutsGetsObjectModWithFailover: Using authinit: " + authInit);
+ getLogWriter().info("testPutsGetsObjectModWithFailover: Using authenticator: " + authenticator);
+ getLogWriter().info("testPutsGetsObjectModWithFailover: Using pre-operation accessor: " + preAccessor);
+ getLogWriter().info("testPutsGetsObjectModWithFailover: Using post-operation accessor: " + postAccessor);
- public static void createCacheServer(Integer loctorPort, Integer serverPort,
- Properties authProps) {
+ // Start servers with all required properties
+ Properties serverProps = buildProperties(authenticator, extraProps, preAccessor, postAccessor);
- if (loctorPort == null) {
- loctorPort = new Integer(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- }
- SecurityTestUtil.createCacheServer(authProps, null, loctorPort, null,
- serverPort, Boolean.FALSE, new Integer(SecurityTestUtil.NO_EXCEPTION));
- }
+ // Get ports for the servers
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 =getRandomAvailablePort(SOCKET);
- // End Region: Utility and static functions invoked by the tests
+ // Perform all the ops on the clients
+ List opBlock = new ArrayList();
+ Random rnd = new Random();
- // Region: Tests
+ 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(() -> createCacheServer(getLocatorPort(), port1, serverProps, javaProps ));
+ server2.invoke(() -> closeCache());
+ executeOpBlock(opBlock, port1, port2, authInit, extraProps, null, tgen, rnd);
+ if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
+ // Failover to the second server and run the block again
+ server2.invoke(() -> createCacheServer(getLocatorPort(), port2, serverProps, javaProps ));
+ server1.invoke(() -> closeCache());
+ executeOpBlock(opBlock, port1, port2, authInit, extraProps, null, tgen, rnd);
+ }
+ opBlock.clear();
+ }
- public void testAllOpsObjectModWithFailover() {
+ } else {
+ currentOp.setOpNum(opNum);
+ opBlock.add(currentOp);
+ }
+ }
+ }
- OperationWithAction[] allOps = {
+ private OperationWithAction[] allOps() {
+ return new OperationWithAction[] {
// Perform CREATE and verify with GET
new OperationWithAction(OperationCode.PUT, 1, OpFlags.NONE, 8),
- // For second client connect with valid credentials for key2, key4,
- // key6, key8 and check that other keys are not accessible
- new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY,
- new int[] { 1, 3, 5, 7 }),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY
- | OpFlags.USE_OLDCONN | OpFlags.CHECK_NOTAUTHZ, new int[] { 0, 2,
- 4, 6 }),
- // For third client check that key3, key6 are accessible but others are
- // not
- new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY,
- new int[] { 2, 5 }),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY
- | OpFlags.USE_OLDCONN | OpFlags.CHECK_NOTAUTHZ, new int[] { 0, 1,
- 3, 4, 6, 7 }),
-
- // OPBLOCK_END indicates end of an operation block that needs to
- // be executed on each server when doing failover
+ // For second client connect with valid credentials for key2, key4, key6, key8 and check that other KEYS are not accessible
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY, new int[]{1, 3, 5, 7}),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.CHECK_NOKEY | OpFlags.USE_OLDCONN | OpFlags.CHECK_NOTAUTHZ, new int[]{0, 2, 4, 6}),
+ // For third client check that key3, key6 are accessible but others are not
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY, new int[]{2, 5}),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.CHECK_NOKEY | OpFlags.USE_OLDCONN | OpFlags.CHECK_NOTAUTHZ, new int[]{0, 1, 3, 4, 6, 7}),
+
+ // OPBLOCK_END indicates end of an operation block that needs to be executed on each server when doing failover
OperationWithAction.OPBLOCK_END,
// Perform UPDATE and verify with GET
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 8),
- // For second client check that key2, key4, key6, key8 are accessible
- // but others are not
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, new int[] { 1, 3, 5, 7 }),
- new OperationWithAction(OperationCode.GET, 2,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_NOTAUTHZ, new int[] { 0, 2, 4, 6 }),
- // For third client check that key3, key6 are accessible but others are
- // not
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, new int[] { 2, 5 }),
- new OperationWithAction(OperationCode.GET, 3,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_NOTAUTHZ, new int[] { 0, 1, 3, 4, 6, 7 }),
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 8),
+ // For second client check that key2, key4, key6, key8 are accessible but others are not
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[]{1, 3, 5, 7}),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY | OpFlags.CHECK_NOTAUTHZ, new int[]{0, 2, 4, 6}),
+ // For third client check that key3, key6 are accessible but others are not
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[]{2, 5}),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY | OpFlags.CHECK_NOTAUTHZ, new int[]{0, 1, 3, 4, 6, 7}),
OperationWithAction.OPBLOCK_END,
// Perform UPDATE and verify with GET_ALL
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 8),
- // For second client check that key2, key4, key6, key8 are accessible
- // but others are not; getAll test in doOp uses a combination of local
- // entries and remote fetches
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS,
- new int[] { 1, 3, 5, 7 }),
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_FAIL, new int[] { 0, 2, 4, 6 }),
- // For third client check that key3, key6 are accessible but others are
- // not
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS, new int[] { 2, 5 }),
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_FAIL, new int[] { 0, 1, 3, 4, 6, 7 }),
-
- // locally destroy the keys to also test create after failover
- new OperationWithAction(OperationCode.DESTROY, 1, OpFlags.USE_OLDCONN
- | OpFlags.LOCAL_OP, 8),
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 8),
+ // For second client check that key2, key4, key6, key8 are accessible but others are not; getAll test in doOp uses a combination of local entries and remote fetches
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS, new int[]{1, 3, 5, 7}),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS | OpFlags.CHECK_NOKEY | OpFlags.CHECK_FAIL, new int[]{0, 2, 4, 6}),
+ // For third client check that key3, key6 are accessible but others are not
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS, new int[]{2, 5}),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.USE_ALL_KEYS | OpFlags.CHECK_NOKEY | OpFlags.CHECK_FAIL, new int[]{0, 1, 3, 4, 6, 7}),
+
+ // locally destroy the KEYS to also test create after failover
+ new OperationWithAction(OperationCode.DESTROY, 1, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 8),
OperationWithAction.OPBLOCK_END,
// Perform PUTALL and verify with GET
- new OperationWithAction(OperationCode.PUTALL, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 8),
- // For second client check that key2, key4, key6, key8 are accessible
- // but others are not
- new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, new int[] { 1, 3, 5, 7 }),
- new OperationWithAction(OperationCode.GET, 2,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_NOTAUTHZ, new int[] { 0, 2, 4, 6 }),
- // For third client check that key3, key6 are accessible but others are
- // not
- new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, new int[] { 2, 5 }),
- new OperationWithAction(OperationCode.GET, 3,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY
- | OpFlags.CHECK_NOTAUTHZ, new int[] { 0, 1, 3, 4, 6, 7 }),
+ new OperationWithAction(OperationCode.PUTALL, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 8),
+ // For second client check that key2, key4, key6, key8 are accessible but others are not
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[]{1, 3, 5, 7}),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY | OpFlags.CHECK_NOTAUTHZ, new int[]{0, 2, 4, 6}),
+ // For third client check that key3, key6 are accessible but others are not
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[]{2, 5}),
+ new OperationWithAction(OperationCode.GET, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_NOKEY | OpFlags.CHECK_NOTAUTHZ, new int[]{0, 1, 3, 4, 6, 7}),
OperationWithAction.OPBLOCK_END,
-
+
// Test UPDATE and verify with a QUERY
new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN, 8),
- // For second client check that key2, key4, key6, key8 are accessible
- // but others are not
- new OperationWithAction(OperationCode.QUERY, 2, OpFlags.USE_OLDCONN,
- new int[] { 1, 3, 5, 7 }),
- new OperationWithAction(OperationCode.QUERY, 2, OpFlags.USE_OLDCONN
- | OpFlags.CHECK_FAIL, new int[] { 0, 2, 4, 6 }),
- // For third client check that key3, key6 are accessible but others are
- // not
- new OperationWithAction(OperationCode.QUERY, 3, OpFlags.USE_OLDCONN,
- new int[] { 2, 5 }),
- new OperationWithAction(OperationCode.QUERY, 3, OpFlags.USE_OLDCONN
- | OpFlags.CHECK_FAIL, new int[] { 0, 1, 3, 4, 6, 7 }),
+ // For second client check that key2, key4, key6, key8 are accessible but others are not
+ new OperationWithAction(OperationCode.QUERY, 2, OpFlags.USE_OLDCONN, new int[]{1, 3, 5, 7}),
+ new OperationWithAction(OperationCode.QUERY, 2, OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL, new int[]{0, 2, 4, 6}),
+ // For third client check that key3, key6 are accessible but others are not
+ new OperationWithAction(OperationCode.QUERY, 3, OpFlags.USE_OLDCONN, new int[]{2, 5}),
+ new OperationWithAction(OperationCode.QUERY, 3, OpFlags.USE_OLDCONN | OpFlags.CHECK_FAIL, new int[]{0, 1, 3, 4, 6, 7}),
OperationWithAction.OPBLOCK_END,
// Test UPDATE and verify with a EXECUTE_CQ initial results
- new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN
- | OpFlags.USE_NEWVAL, 8),
- // For second client check that key2, key4, key6, key8 are accessible
- // but others are not
- new OperationWithAction(OperationCode.EXECUTE_CQ, 2,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[] { 1, 3, 5, 7 }),
- new OperationWithAction(OperationCode.CLOSE_CQ, 2, OpFlags.USE_OLDCONN,
- 1),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 2,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_FAIL,
- new int[] { 0, 2, 4, 6 }),
- new OperationWithAction(OperationCode.CLOSE_CQ, 2, OpFlags.USE_OLDCONN,
- 1),
- // For third client check that key3, key6 are accessible but others are
- // not
- new OperationWithAction(OperationCode.EXECUTE_CQ, 3,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[] { 2, 5 }),
- new OperationWithAction(OperationCode.CLOSE_CQ, 3, OpFlags.USE_OLDCONN,
- 1),
- new OperationWithAction(OperationCode.EXECUTE_CQ, 3,
- OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_FAIL,
- new int[] { 0, 1, 3, 4, 6, 7 }),
- new OperationWithAction(OperationCode.CLOSE_CQ, 3, OpFlags.USE_OLDCONN,
- 1),
-
- OperationWithAction.OPBLOCK_END };
-
- TestPostCredentialGenerator tgen = new TestPostCredentialGenerator();
-
- CredentialGenerator gen = new DummyCredentialGenerator();
- gen.init();
- Properties extraProps = gen.getSystemProperties();
- Properties javaProps = gen.getJavaProperties();
- String authInit = gen.getAuthInit();
- String authenticator = gen.getAuthenticator();
-
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsObjectModWithFailover: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsObjectModWithFailover: Using authenticator: "
- + authenticator);
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsObjectModWithFailover: Using pre-operation accessor: "
- + preAccessor);
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsObjectModWithFailover: Using post-operation accessor: "
- + postAccessor);
+ new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 8),
+ // For second client check that key2, key4, key6, key8 are accessible but others are not
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[]{1, 3, 5, 7}),
+ new OperationWithAction(OperationCode.CLOSE_CQ, 2, OpFlags.USE_OLDCONN, 1),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 2, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_FAIL, new int[]{0, 2, 4, 6}),
+ new OperationWithAction(OperationCode.CLOSE_CQ, 2, OpFlags.USE_OLDCONN, 1),
+ // For third client check that key3, key6 are accessible but others are not
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, new int[]{2, 5}),
+ new OperationWithAction(OperationCode.CLOSE_CQ, 3, OpFlags.USE_OLDCONN, 1),
+ new OperationWithAction(OperationCode.EXECUTE_CQ, 3, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL | OpFlags.CHECK_FAIL, new int[]{0, 1, 3, 4, 6, 7}),
+ new OperationWithAction(OperationCode.CLOSE_CQ, 3, OpFlags.USE_OLDCONN, 1),
+
+ OperationWithAction.OPBLOCK_END};
+ }
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, extraProps,
- preAccessor, postAccessor);
- // 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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.closeCache());
- executeOpBlock(opBlock, port1, port2, authInit, extraProps, null,
- tgen, rnd);
- if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
- // Failover to the second server and run the block again
- server2.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port2, serverProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.closeCache());
- executeOpBlock(opBlock, port1, port2, authInit, extraProps, null,
- tgen, rnd);
- }
- opBlock.clear();
- }
- }
- else {
- currentOp.setOpNum(opNum);
- opBlock.add(currentOp);
- }
+ private Properties buildProperties(final String authenticator, final Properties extraProps, final String preAccessor, final String postAccessor) {
+ Properties authProps = new Properties();
+ if (authenticator != null) {
+ authProps.setProperty(SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
+ }
+ if (preAccessor != null) {
+ authProps.setProperty(SECURITY_CLIENT_ACCESSOR_NAME, preAccessor);
+ }
+ if (postAccessor != null) {
+ authProps.setProperty(SECURITY_CLIENT_ACCESSOR_PP_NAME, postAccessor);
}
+ if (extraProps != null) {
+ authProps.putAll(extraProps);
+ }
+ return authProps;
}
private static class MyInstantiator extends Instantiator {
- public MyInstantiator(Class clazz, int classId) {
- super(clazz, classId);
- }
public MyInstantiator() {
this(ObjectWithAuthz.class, ObjectWithAuthz.CLASSID);
}
+ public MyInstantiator(final Class clazz, final int classId) {
+ super(clazz, classId);
+ }
+
+ @Override
public DataSerializable newInstance() {
return new ObjectWithAuthz();
}
}
+ private static class TestPostCredentialGenerator implements TestCredentialGenerator {
+
+ public TestPostCredentialGenerator() {
+ }
+
+ @Override
+ public Properties getAllowedCredentials(final OperationCode[] opCodes, final String[] regionNames, final int[] keyIndices, final int num) {
+ int userIndex = 1;
+ byte role = DummyAuthzCredentialGenerator.getRequiredRole(opCodes);
+ if (role == DummyAuthzCredentialGenerator.READER_ROLE) {
+ userIndex = keyIndices[0] + 1;
+ }
+ Properties props = new Properties();
+ props.setProperty(UserPasswordAuthInit.USER_NAME, "user" + userIndex);
+ props.setProperty(UserPasswordAuthInit.PASSWORD, "user" + userIndex);
+ return props;
+ }
+
+ @Override
+ public Properties getDisallowedCredentials(final OperationCode[] opCodes, final String[] regionNames, final int[] keyIndices, final int num) {
+ int userIndex = 0;
+ for (int index = 0; index < keyIndices.length; ++index) {
+ if (keyIndices[index] != index) {
+ userIndex = index + 1;
+ break;
+ }
+ }
+ Properties props = new Properties();
+ props.setProperty(UserPasswordAuthInit.USER_NAME, "gemfire" + userIndex);
+ props.setProperty(UserPasswordAuthInit.PASSWORD, "gemfire" + userIndex);
+ return props;
+ }
+
+ @Override
+ public CredentialGenerator getCredentialGenerator() {
+ return null;
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientCQPostAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientCQPostAuthorizationDUnitTest.java b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientCQPostAuthorizationDUnitTest.java
index e130601..dfa89f9 100644
--- a/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientCQPostAuthorizationDUnitTest.java
+++ b/geode-cq/src/test/java/com/gemstone/gemfire/security/ClientCQPostAuthorizationDUnitTest.java
@@ -16,6 +16,13 @@
*/
package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.Invoke.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+import static com.gemstone.gemfire.test.dunit.Wait.*;
+
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@@ -27,76 +34,51 @@ 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.CqException;
+import com.gemstone.gemfire.cache.query.CqExistsException;
import com.gemstone.gemfire.cache.query.CqListener;
import com.gemstone.gemfire.cache.query.CqQuery;
import com.gemstone.gemfire.cache.query.QueryService;
+import com.gemstone.gemfire.cache.query.RegionNotFoundException;
import com.gemstone.gemfire.cache.query.SelectResults;
import com.gemstone.gemfire.cache.query.cq.dunit.CqQueryTestListener;
import com.gemstone.gemfire.cache.query.internal.cq.ClientCQImpl;
import com.gemstone.gemfire.cache.query.internal.cq.CqService;
import com.gemstone.gemfire.cache.query.internal.cq.InternalCqQuery;
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
-import com.gemstone.gemfire.internal.logging.InternalLogWriter;
import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.Invoke;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
import com.gemstone.gemfire.test.dunit.SerializableRunnable;
-import com.gemstone.gemfire.test.dunit.Wait;
import com.gemstone.gemfire.test.dunit.WaitCriterion;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
/**
* This is for multiuser-authentication
- *
- *
*/
-public class ClientCQPostAuthorizationDUnitTest extends
- ClientAuthorizationTestBase {
-
-// public static final String regionName = "ClientCQPostAuthorizationDUnitTest_region";
-
- public static final Map<String, String> cqNameToQueryStrings = new HashMap<String, String>();
-
- static {
- cqNameToQueryStrings.put("CQ_0", "SELECT * FROM ");
- cqNameToQueryStrings.put("CQ_1", "SELECT * FROM ");
- }
+@Category(DistributedTest.class)
+public class ClientCQPostAuthorizationDUnitTest extends ClientAuthorizationTestCase {
- public ClientCQPostAuthorizationDUnitTest(String name) {
- super(name);
- }
+ private Map<String, String> cqNameToQueryStrings = new HashMap<>();
@Override
- public final void postSetUp() throws Exception {
+ protected final void preSetUpClientAuthorizationTestBase() throws Exception {
getSystem();
- Invoke.invokeInEveryVM(new SerializableRunnable("getSystem") {
+ invokeInEveryVM(new SerializableRunnable("getSystem") {
public void run() {
getSystem();
}
});
-
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+ this.cqNameToQueryStrings.put("CQ_0", "SELECT * FROM ");
+ this.cqNameToQueryStrings.put("CQ_1", "SELECT * FROM ");
}
@Override
- public final void preTearDown() throws Exception {
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ public final void postTearDownClientAuthorizationTestBase() throws Exception {
+ this.cqNameToQueryStrings.clear();
}
+ @Test
public void testAllowCQForAllMultiusers() throws Exception {
/*
* Start a server
@@ -105,10 +87,10 @@ public class ClientCQPostAuthorizationDUnitTest extends
* Client2 does some operations on the region which satisfies both the CQs
* Validate that listeners for both the CQs are invoked.
*/
- doStartUp(Integer.valueOf(2), Integer.valueOf(5), new Boolean[] {true,
- true});
+ doStartUp(2, 5, new boolean[] {true, true}, false);
}
+ @Test
public void testDisallowCQForAllMultiusers() throws Exception {
/*
* Start a server
@@ -117,10 +99,10 @@ public class ClientCQPostAuthorizationDUnitTest extends
* Client2 does some operations on the region which satisfies both the CQs
* Validate that listeners for none of the CQs are invoked.
*/
- doStartUp(Integer.valueOf(2), Integer.valueOf(5), new Boolean[] {false,
- false});
+ doStartUp(2, 5, new boolean[] {false, false}, false);
}
+ @Test
public void testDisallowCQForSomeMultiusers() throws Exception {
/*
* Start a server
@@ -130,10 +112,10 @@ public class ClientCQPostAuthorizationDUnitTest extends
* Client2 does some operations on the region which satisfies both the CQs
* Validate that listener for User1's CQ is invoked but that for User2's CQ is not invoked.
*/
- doStartUp(Integer.valueOf(2), Integer.valueOf(5), new Boolean[] {true,
- false});
+ doStartUp(2, 5, new boolean[] {true, false}, false);
}
+ @Test
public void testAllowCQForAllMultiusersWithFailover() throws Exception {
/*
* Start a server1
@@ -145,204 +127,137 @@ public class ClientCQPostAuthorizationDUnitTest extends
* Client2 does some operations on the region which satisfies both the CQs
* Validate that listeners for both the CQs are get updates.
*/
- doStartUp(Integer.valueOf(2), Integer.valueOf(5), new Boolean[] {true,
- true}, Boolean.TRUE);
+ doStartUp(2, 5, new boolean[] {true, true}, true);
}
- public void doStartUp(Integer numOfUsers, Integer numOfPuts,
- Boolean[] postAuthzAllowed) throws Exception {
- doStartUp(numOfUsers, numOfPuts, postAuthzAllowed, Boolean.FALSE /* failover */);
- }
+ private void doStartUp(final int numOfUsers, final int numOfPuts, final boolean[] postAuthzAllowed, final boolean failover) throws Exception {
+ AuthzCredentialGenerator authzGenerator = getXmlAuthzGenerator();
+ CredentialGenerator credentialGenerator = authzGenerator.getCredentialGenerator();
+ Properties extraAuthProps = credentialGenerator.getSystemProperties();
+ Properties javaProps = credentialGenerator.getJavaProperties();
+ Properties extraAuthzProps = authzGenerator.getSystemProperties();
+ String authenticator = credentialGenerator.getAuthenticator();
+ String accessor = authzGenerator.getAuthorizationCallback();
+ String authInit = credentialGenerator.getAuthInit();
+ TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(authzGenerator);
+
+ Properties serverProps = buildProperties(authenticator, accessor, true, extraAuthProps, extraAuthzProps);
+
+ Properties opCredentials;
+ credentialGenerator = tgen.getCredentialGenerator();
+ final Properties javaProps2 = credentialGenerator == null ? null : credentialGenerator.getJavaProperties();
+
+ int[] indices = new int[numOfPuts];
+ for (int index = 0; index < numOfPuts; ++index) {
+ indices[index] = index;
+ }
- public void doStartUp(Integer numOfUsers, Integer numOfPuts,
- Boolean[] postAuthzAllowed, Boolean failover) 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 accessor = gen.getAuthorizationCallback();
- String authInit = cGen.getAuthInit();
- TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(gen);
-
- Properties serverProps = buildProperties(authenticator, accessor, true,
- extraAuthProps, extraAuthzProps);
-
- Properties opCredentials;
- cGen = tgen.getCredentialGenerator();
- Properties javaProps2 = null;
- if (cGen != null) {
- javaProps2 = cGen.getJavaProperties();
- }
+ Random rnd = new Random();
+ Properties[] authProps = new Properties[numOfUsers];
+ for (int i = 0; i < numOfUsers; i++) {
+ int rand = rnd.nextInt(100) + 1;
- int[] indices = new int[numOfPuts];
- for (int index = 0; index < numOfPuts; ++index) {
- indices[index] = index;
+ if (postAuthzAllowed[i]) {
+ // For callback, GET should be allowed
+ opCredentials = tgen.getAllowedCredentials(new OperationCode[] {OperationCode.EXECUTE_CQ, OperationCode.GET}, new String[] {REGION_NAME}, indices, rand);
+ } else {
+ // For callback, GET should be disallowed
+ opCredentials = tgen.getDisallowedCredentials(new OperationCode[] { OperationCode.GET}, new String[] {REGION_NAME}, indices, rand);
}
- Random rnd = new Random();
- Properties[] authProps = new Properties[numOfUsers];
- for (int i = 0; i < numOfUsers; i++) {
- int rand = rnd.nextInt(100) + 1;
- if (postAuthzAllowed[i]) {
- opCredentials = tgen.getAllowedCredentials(new OperationCode[] {
- OperationCode.EXECUTE_CQ, OperationCode.GET}, // For callback, GET should be allowed
- new String[] {regionName}, indices, rand);
-// authProps[i] = gen.getAllowedCredentials(
-// new OperationCode[] {OperationCode.EXECUTE_CQ},
-// new String[] {regionName}, rnd.nextInt(100) + 1);
- } else {
- opCredentials = tgen.getDisallowedCredentials(new OperationCode[] {
- OperationCode.GET}, // For callback, GET should be disallowed
- new String[] {regionName}, indices, rand);
-// authProps[i] = gen.getDisallowedCredentials(
-// new OperationCode[] {OperationCode.EXECUTE_CQ},
-// new String[] {regionName}, rnd.nextInt(100) + 1);
- }
- authProps[i] = SecurityTestUtil.concatProperties(new Properties[] {
- opCredentials, extraAuthProps, extraAuthzProps});
- }
+ authProps[i] = concatProperties(new Properties[] {opCredentials, extraAuthProps, extraAuthzProps});
+ }
- // Get ports for the servers
- Integer port1 = Integer.valueOf(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- Integer port2 = Integer.valueOf(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- Integer locatorPort = Integer.valueOf(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- // Close down any running servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
-
- server1.invoke(() -> ClientCQPostAuthorizationDUnitTest.createServerCache(serverProps, javaProps, locatorPort, port1));
- client1.invoke(ClientCQPostAuthorizationDUnitTest.class,
- "createClientCache", new Object[] {javaProps2, authInit, authProps,
- new Integer[] {port1, port2}, numOfUsers, postAuthzAllowed});
- client2.invoke(ClientCQPostAuthorizationDUnitTest.class,
- "createClientCache", new Object[] {javaProps2, authInit, authProps,
- new Integer[] {port1, port2}, numOfUsers, postAuthzAllowed});
-
- client1.invoke(() -> ClientCQPostAuthorizationDUnitTest.createCQ(numOfUsers));
- client1.invoke(ClientCQPostAuthorizationDUnitTest.class, "executeCQ",
- new Object[] {numOfUsers, new Boolean[] {false, false}, numOfPuts,
- new String[numOfUsers], postAuthzAllowed});
-
- client2.invoke(() -> ClientCQPostAuthorizationDUnitTest.doPuts(numOfPuts, Boolean.TRUE/* put last key */));
- if (!postAuthzAllowed[0]) {
- // There is no point waiting as no user is authorized to receive cq events.
- try {Thread.sleep(1000);} catch (InterruptedException ie) {}
- } else {
- client1.invoke(() -> ClientCQPostAuthorizationDUnitTest.waitForLastKey(Integer.valueOf(0)));
- if (postAuthzAllowed[1]) {
- client1.invoke(() -> ClientCQPostAuthorizationDUnitTest.waitForLastKey(Integer.valueOf(1)));
- }
- }
- client1.invoke(() -> ClientCQPostAuthorizationDUnitTest.checkCQListeners(numOfUsers, postAuthzAllowed,
- numOfPuts + 1/* last key */, 0, !failover));
- if (failover) {
- server2.invoke(() -> ClientCQPostAuthorizationDUnitTest.createServerCache(serverProps, javaProps, locatorPort, port2));
- server1.invoke(() -> SecurityTestUtil.closeCache());
-
- // Allow time for client1 to register its CQs on server2
- server2.invoke(() -> ClientCQPostAuthorizationDUnitTest.allowCQsToRegister(Integer.valueOf(2)));
-
- client2.invoke(() -> ClientCQPostAuthorizationDUnitTest.doPuts(numOfPuts, Boolean.TRUE/* put last key */));
- client1.invoke(() -> ClientCQPostAuthorizationDUnitTest.waitForLastKeyUpdate(Integer.valueOf(0)));
- client1.invoke(() -> ClientCQPostAuthorizationDUnitTest.checkCQListeners(numOfUsers, postAuthzAllowed,
- numOfPuts + 1/* last key */, numOfPuts + 1/* last key */,
- Boolean.TRUE));
+ // Get ports for the servers
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 = getRandomAvailablePort(SOCKET);
+ int locatorPort = getRandomAvailablePort(SOCKET);
+
+ // Close down any running servers
+ server1.invoke(() -> closeCache());
+ server2.invoke(() -> closeCache());
+
+ server1.invoke(() -> createTheServerCache(serverProps, javaProps, locatorPort, port1));
+ client1.invoke(() -> createClientCache(javaProps2, authInit, authProps, new int[] {port1, port2}, numOfUsers, postAuthzAllowed));
+ client2.invoke(() -> createClientCache(javaProps2, authInit, authProps, new int[] {port1, port2}, numOfUsers, postAuthzAllowed));
+
+ client1.invoke(() -> createCQ(numOfUsers));
+ client1.invoke(() -> executeCQ(numOfUsers, new boolean[] {false, false}, numOfPuts, new String[numOfUsers], postAuthzAllowed));
+
+ client2.invoke(() -> doPuts(numOfPuts, true/* put last key */));
+
+ if (!postAuthzAllowed[0]) {
+ // There is no point waiting as no user is authorized to receive cq events.
+ try {Thread.sleep(1000);} catch (InterruptedException ie) {} // TODO: replace with Awaitility
+ } else {
+ client1.invoke(() -> waitForLastKey(0));
+ if (postAuthzAllowed[1]) {
+ client1.invoke(() -> waitForLastKey(1));
}
- }
+ }
+
+ client1.invoke(() -> checkCQListeners(numOfUsers, postAuthzAllowed, numOfPuts + 1/* last key */, 0, !failover));
- public static void createServerCache(Properties serverProps,
- Properties javaProps, Integer serverPort) {
- Integer locatorPort = Integer.valueOf(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- SecurityTestUtil.createCacheServer((Properties)serverProps, javaProps,
- locatorPort, null, serverPort, Boolean.TRUE, Integer.valueOf(
- SecurityTestUtil.NO_EXCEPTION));
+ if (failover) {
+ server2.invoke(() -> createTheServerCache(serverProps, javaProps, locatorPort, port2));
+ server1.invoke(() -> closeCache());
+
+ // Allow time for client1 to register its CQs on server2
+ server2.invoke(() -> allowCQsToRegister(2));
+
+ client2.invoke(() -> doPuts(numOfPuts, true/* put last key */));
+ client1.invoke(() -> waitForLastKeyUpdate(0));
+ client1.invoke(() -> checkCQListeners(numOfUsers, postAuthzAllowed, numOfPuts + 1/* last key */, numOfPuts + 1/* last key */, true));
+ }
}
- public static void createServerCache(Properties serverProps,
- Properties javaProps, Integer locatorPort, Integer serverPort) {
- SecurityTestUtil.createCacheServer((Properties)serverProps, javaProps,
- locatorPort, null, serverPort, Boolean.TRUE, Integer.valueOf(
- SecurityTestUtil.NO_EXCEPTION));
+ private void createTheServerCache(final Properties serverProps, final Properties javaProps, final int locatorPort, final int serverPort) {
+ SecurityTestUtils.createCacheServer(serverProps, javaProps, locatorPort, (String)null, serverPort, true, NO_EXCEPTION);
}
- public static void createClientCache(Properties javaProps, String authInit,
- Properties[] authProps, Integer ports[], Integer numOfUsers,
- Boolean[] postAuthzAllowed) {
- SecurityTestUtil.createCacheClientForMultiUserMode(numOfUsers, authInit,
- authProps, javaProps, ports, null, Boolean.FALSE,
- SecurityTestUtil.NO_EXCEPTION);
+ private void createClientCache(final Properties javaProps, final String authInit, final Properties[] authProps, final int ports[], final int numOfUsers, final boolean[] postAuthzAllowed) {
+ createCacheClientForMultiUserMode(numOfUsers, authInit, authProps, javaProps, ports, 0, false, NO_EXCEPTION);
}
- public static void createCQ(Integer num) {
+ private void createCQ(final int num) throws CqException, CqExistsException {
for (int i = 0; i < num; i++) {
- QueryService cqService = SecurityTestUtil.proxyCaches[i].getQueryService();
+ QueryService cqService = getProxyCaches(i).getQueryService();
String cqName = "CQ_" + i;
- String queryStr = cqNameToQueryStrings.get(cqName)
- + SecurityTestUtil.proxyCaches[i].getRegion(regionName).getFullPath();
+ String queryStr = cqNameToQueryStrings.get(cqName) + getProxyCaches(i).getRegion(REGION_NAME).getFullPath();
+
// Create CQ Attributes.
CqAttributesFactory cqf = new CqAttributesFactory();
- CqListener[] cqListeners = {new CqQueryTestListener(LogWriterUtils.getLogWriter())};
+ CqListener[] cqListeners = {new CqQueryTestListener(getLogWriter())};
((CqQueryTestListener)cqListeners[0]).cqName = cqName;
cqf.initCqListeners(cqListeners);
CqAttributes cqa = cqf.create();
// Create CQ.
- try {
- CqQuery cq1 = cqService.newCq(cqName, queryStr, cqa);
- assertTrue("newCq() state mismatch", cq1.getState().isStopped());
- } catch (Exception ex) {
- AssertionError err = new AssertionError("Failed to create CQ " + cqName
- + " . ");
- err.initCause(ex);
- LogWriterUtils.getLogWriter().info("CqService is :" + cqService, err);
- throw err;
- }
+ CqQuery cq1 = cqService.newCq(cqName, queryStr, cqa);
+ assertTrue("newCq() state mismatch", cq1.getState().isStopped());
}
}
- public static void executeCQ(Integer num, Boolean[] initialResults,
- Integer expectedResultsSize, String[] expectedErr, Boolean[] postAuthzAllowed) {
- InternalLogWriter logWriter = InternalDistributedSystem.getStaticInternalLogWriter();
+ private void executeCQ(final int num, final boolean[] initialResults, final int expectedResultsSize, final String[] expectedErr, final boolean[] postAuthzAllowed) throws RegionNotFoundException, CqException {
for (int i = 0; i < num; i++) {
try {
if (expectedErr[i] != null) {
- logWriter.info(
- "<ExpectedException action=add>" + expectedErr[i]
- + "</ExpectedException>");
+ getLogWriter().info("<ExpectedException action=add>" + expectedErr[i] + "</ExpectedException>");
}
CqQuery cq1 = null;
String cqName = "CQ_" + i;
- String queryStr = cqNameToQueryStrings.get(cqName)
- + SecurityTestUtil.proxyCaches[i].getRegion(regionName)
- .getFullPath();
- QueryService cqService = SecurityTestUtil.proxyCaches[i]
- .getQueryService();
+ //String queryStr = cqNameToQueryStrings.get(cqName) + getProxyCaches(i).getRegion(REGION_NAME).getFullPath();
+ QueryService cqService = getProxyCaches(i).getQueryService();
// Get CqQuery object.
- try {
- cq1 = cqService.getCq(cqName);
- if (cq1 == null) {
- LogWriterUtils.getLogWriter().info(
- "Failed to get CqQuery object for CQ name: " + cqName);
- fail("Failed to get CQ " + cqName);
- } else {
- LogWriterUtils.getLogWriter().info("Obtained CQ, CQ name: " + cq1.getName());
- assertTrue("newCq() state mismatch", cq1.getState().isStopped());
- }
- } catch (Exception ex) {
- LogWriterUtils.getLogWriter().info("CqService is :" + cqService);
- LogWriterUtils.getLogWriter().error(ex);
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ex);
- throw err;
+ cq1 = cqService.getCq(cqName);
+ if (cq1 == null) {
+ getLogWriter().info("Failed to get CqQuery object for CQ name: " + cqName);
+ fail("Failed to get CQ " + cqName);
+ } else {
+ getLogWriter().info("Obtained CQ, CQ name: " + cq1.getName());
+ assertTrue("newCq() state mismatch", cq1.getState().isStopped());
}
if (initialResults[i]) {
@@ -352,68 +267,43 @@ public class ClientCQPostAuthorizationDUnitTest extends
cqResults = cq1.executeWithInitialResults();
} catch (CqException ce) {
if (ce.getCause() instanceof NotAuthorizedException && !postAuthzAllowed[i]) {
- LogWriterUtils.getLogWriter().info("Got expected exception for CQ " + cqName);
+ getLogWriter().info("Got expected exception for CQ " + cqName);
} else {
- LogWriterUtils.getLogWriter().info("CqService is: " + cqService);
- ce.printStackTrace();
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ce);
- throw err;
+ getLogWriter().info("CqService is: " + cqService);
+ throw new AssertionError("Failed to execute CQ " + cqName, ce);
}
- } catch (Exception ex) {
- LogWriterUtils.getLogWriter().info("CqService is: " + cqService);
- ex.printStackTrace();
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ex);
- throw err;
}
- LogWriterUtils.getLogWriter().info("initial result size = " + cqResults.size());
- assertTrue("executeWithInitialResults() state mismatch", cq1
- .getState().isRunning());
+
+ getLogWriter().info("initial result size = " + cqResults.size());
+ assertTrue("executeWithInitialResults() state mismatch", cq1.getState().isRunning());
if (expectedResultsSize >= 0) {
- assertEquals("unexpected results size", expectedResultsSize
- .intValue(), cqResults.size());
+ assertEquals("unexpected results size", expectedResultsSize, cqResults.size());
}
+
} else {
+
try {
cq1.execute();
} catch (CqException ce) {
if (ce.getCause() instanceof NotAuthorizedException && !postAuthzAllowed[i]) {
- LogWriterUtils.getLogWriter().info("Got expected exception for CQ " + cqName);
+ getLogWriter().info("Got expected exception for CQ " + cqName);
} else {
- LogWriterUtils.getLogWriter().info("CqService is: " + cqService);
- ce.printStackTrace();
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ce);
- throw err;
- }
- } catch (Exception ex) {
- AssertionError err = new AssertionError("Failed to execute CQ "
- + cqName);
- err.initCause(ex);
- if (expectedErr == null) {
- LogWriterUtils.getLogWriter().info("CqService is: " + cqService, err);
+ throw ce;
}
- throw err;
}
+
assertTrue("execute() state mismatch", cq1.getState().isRunning() == postAuthzAllowed[i]);
}
} finally {
if (expectedErr[i] != null) {
- logWriter.info(
- "<ExpectedException action=remove>" + expectedErr[i]
- + "</ExpectedException>");
+ getLogWriter().info("<ExpectedException action=remove>" + expectedErr[i] + "</ExpectedException>");
}
}
}
}
- public static void doPuts(Integer num, Boolean putLastKey) {
-// Region region = GemFireCache.getInstance().getRegion(regionName);
- Region region = SecurityTestUtil.proxyCaches[0].getRegion(regionName);
+ private void doPuts(final int num, final boolean putLastKey) {
+ Region region = getProxyCaches(0).getRegion(REGION_NAME);
for (int i = 0; i < num; i++) {
region.put("CQ_key"+i, "CQ_value"+i);
}
@@ -422,46 +312,24 @@ public class ClientCQPostAuthorizationDUnitTest extends
}
}
- public static void putLastKey() {
- Region region = GemFireCacheImpl.getInstance().getRegion(regionName);
- region.put("LAST_KEY", "LAST_KEY");
- }
-
- public static void waitForLastKey(Integer cqIndex) {
+ private void waitForLastKey(final int cqIndex) {
String cqName = "CQ_" + cqIndex;
- QueryService qService = SecurityTestUtil.proxyCaches[cqIndex].getQueryService();
+ QueryService qService = getProxyCaches(cqIndex).getQueryService();
ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
- ((CqQueryTestListener)cqQuery.getCqListeners()[0])
- .waitForCreated("LAST_KEY");
-// WaitCriterion wc = new WaitCriterion() {
-// public boolean done() {
-// Region region = GemFireCache.getInstance().getRegion(regionName);
-// Region.Entry entry = region.getEntry("LAST_KEY");
-// if (entry != null && entry.getValue() != null) {
-// return false;
-// } else if (entry.getValue() != null) {
-// return true;
-// }
-// return false;
-// }
-// public String description() {
-// return "Last key not received.";
-// }
-// };
-// DistributedTestCase.waitForCriterion(wc, 60 * 1000, 100, false);
+ ((CqQueryTestListener)cqQuery.getCqListeners()[0]).waitForCreated("LAST_KEY");
}
- public static void waitForLastKeyUpdate(Integer cqIndex) {
+ private void waitForLastKeyUpdate(final int cqIndex) {
String cqName = "CQ_" + cqIndex;
- QueryService qService = SecurityTestUtil.proxyCaches[cqIndex].getQueryService();
+ QueryService qService = getProxyCaches(cqIndex).getQueryService();
ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
- ((CqQueryTestListener)cqQuery.getCqListeners()[0])
- .waitForUpdated("LAST_KEY");
+ ((CqQueryTestListener)cqQuery.getCqListeners()[0]).waitForUpdated("LAST_KEY");
}
- public static void allowCQsToRegister(Integer number) {
+ private void allowCQsToRegister(final int number) {
final int num = number;
WaitCriterion wc = new WaitCriterion() {
+ @Override
public boolean done() {
CqService cqService = GemFireCacheImpl.getInstance().getCqService();
cqService.start();
@@ -472,28 +340,24 @@ public class ClientCQPostAuthorizationDUnitTest extends
return false;
}
}
-
+ @Override
public String description() {
- return num + "Waited for " + num
- + " CQs to be registered on this server.";
+ return num + "Waited for " + num + " CQs to be registered on this server.";
}
};
- Wait.waitForCriterion(wc, 60 * 1000, 100, false);
+ waitForCriterion(wc, 60 * 1000, 100, false);
}
- public static void checkCQListeners(Integer numOfUsers,
- Boolean[] expectedListenerInvocation, Integer createEventsSize,
- Integer updateEventsSize, Boolean closeCache) {
+ private boolean checkCQListeners(final int numOfUsers, final boolean[] expectedListenerInvocation, final int createEventsSize, final int updateEventsSize, final boolean closeCache) {
for (int i = 0; i < numOfUsers; i++) {
String cqName = "CQ_" + i;
- QueryService qService = SecurityTestUtil.proxyCaches[i].getQueryService();
+ QueryService qService = getProxyCaches(i).getQueryService();
ClientCQImpl cqQuery = (ClientCQImpl)qService.getCq(cqName);
+
if (expectedListenerInvocation[i]) {
for (CqListener listener : cqQuery.getCqListeners()) {
- assertEquals(createEventsSize.intValue(),
- ((CqQueryTestListener)listener).getCreateEventCount());
- assertEquals(updateEventsSize.intValue(),
- ((CqQueryTestListener)listener).getUpdateEventCount());
+ assertEquals(createEventsSize, ((CqQueryTestListener)listener).getCreateEventCount());
+ assertEquals(updateEventsSize, ((CqQueryTestListener)listener).getUpdateEventCount());
}
} else {
for (CqListener listener : cqQuery.getCqListeners()) {
@@ -501,8 +365,9 @@ public class ClientCQPostAuthorizationDUnitTest extends
}
}
if (closeCache) {
- SecurityTestUtil.proxyCaches[i].close();
+ getProxyCaches(i).close();
}
}
+ return true;
}
}
[08/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
deleted file mode 100644
index 41797ed..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestBase.java
+++ /dev/null
@@ -1,1381 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package com.gemstone.gemfire.security;
-
-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 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 com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
-import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator.ClassCode;
-import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
-import com.gemstone.gemfire.security.generator.XmlAuthzCredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Assert;
-import com.gemstone.gemfire.test.dunit.DistributedTestCase;
-import com.gemstone.gemfire.test.dunit.VM;
-import com.gemstone.gemfire.test.dunit.Wait;
-import com.gemstone.gemfire.test.dunit.WaitCriterion;
-
-/**
- * Base class for tests for authorization from client to server. It contains
- * utility functions for the authorization tests from client to server.
- *
- * @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 Integer createCacheServer(Integer locatorPort, Integer serverPort,
- Object authProps, Object javaProps) {
- if (locatorPort == null) {
- locatorPort = new Integer(AvailablePort
- .getRandomAvailablePort(AvailablePort.SOCKET));
- }
- return 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;
- System.out.println(
- "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);
- System.out.println(""+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;
- }
- };
- Wait.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
- System.out.println(
- "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)) {
- System.out.println(
- "doOp: Got expected NotAuthorizedException when doing operation ["
- + op + "] with flags " + OpFlags.description(flags)
- + ": " + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
- System.out.println(
- "doOp: Got expected exception when doing operation: "
- + ex.toString());
- continue;
- }
- else {
- Assert.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;
- }
- System.out.println(
- "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
- System.out.println(
- "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 {
- byte ordinal = opCode.toOrdinal();
- int[] indices = currentOp.getIndices();
- clientVM.invoke(() -> ClientAuthorizationTestBase.doOp( new Byte(ordinal),
- indices, 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);
-
- System.out.println(testName + ": Using authinit: " + authInit);
- System.out.println(testName + ": Using authenticator: " + authenticator);
- System.out.println(testName + ": Using accessor: " + accessor);
-
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- // Get ports for the servers
- Keeper locator1PortKeeper = AvailablePort.getRandomAvailablePortKeeper(AvailablePort.SOCKET);
- Keeper locator2PortKeeper = AvailablePort.getRandomAvailablePortKeeper(AvailablePort.SOCKET);
- Keeper port1Keeper = AvailablePort.getRandomAvailablePortKeeper(AvailablePort.SOCKET);
- Keeper port2Keeper = AvailablePort.getRandomAvailablePortKeeper(AvailablePort.SOCKET);
- int locator1Port = locator1PortKeeper.getPort();
- int locator2Port = locator2PortKeeper.getPort();
- 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) {
- locator1PortKeeper.release();
- port1Keeper.release();
- // Start the first server and execute the operation block
- server1.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- locator1Port, port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.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
- locator2PortKeeper.release();
- port2Keeper.release();
- server2.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- locator2Port, port2, serverProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.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.
- *
- * @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.
- *
- * @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.
- *
- * @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.
- *
- * @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.
- *
- * @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();
- }
- }
-
-}
[09/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
index df7a473..eeb2c39 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationDUnitTest.java
@@ -1,6 +1,3 @@
-
-package com.gemstone.gemfire.security;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,9 +6,9 @@ package com.gemstone.gemfire.security;
* 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
@@ -19,7 +16,15 @@ package com.gemstone.gemfire.security;
* specific language governing permissions and limitations
* under the License.
*/
+package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+//import static com.gemstone.gemfire.security.ClientAuthenticationTestUtils.*;
+//import static com.gemstone.gemfire.security.ClientAuthorizationTestCase.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.IgnoredException.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
import java.util.ArrayList;
import java.util.Iterator;
@@ -27,17 +32,15 @@ import java.util.List;
import java.util.Properties;
import com.gemstone.gemfire.cache.operations.OperationContext.OperationCode;
-import com.gemstone.gemfire.internal.AvailablePort;
import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
import com.gemstone.gemfire.security.generator.CredentialGenerator;
import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
import com.gemstone.gemfire.security.generator.XmlAuthzCredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.IgnoredException;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
-import com.gemstone.gemfire.test.dunit.VM;
-
import com.gemstone.gemfire.security.templates.UserPasswordAuthInit;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* Tests for authorization from client to server. This tests for authorization
@@ -47,209 +50,59 @@ import com.gemstone.gemfire.security.templates.UserPasswordAuthInit;
*
* @since 5.5
*/
-public class ClientAuthorizationDUnitTest extends ClientAuthorizationTestBase {
-
- /** constructor */
- public ClientAuthorizationDUnitTest(String name) {
- super(name);
- }
+@Category(DistributedTest.class)
+public class ClientAuthorizationDUnitTest extends ClientAuthorizationTestCase {
@Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client1.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+ public final void preTearDownClientAuthorizationTestBase() throws Exception {
+ closeCache();
}
- private Properties getUserPassword(String userName) {
+ @Test
+ 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();
- Properties props = new Properties();
- props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
- props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
- return props;
- }
+ getLogWriter().info("testAllowPutsGets: Using authinit: " + authInit);
+ getLogWriter().info("testAllowPutsGets: Using authenticator: " + authenticator);
+ getLogWriter().info("testAllowPutsGets: Using accessor: " + accessor);
- private void executeRIOpBlock(List opBlock, Integer port1, Integer port2,
- String authInit, Properties extraAuthProps, Properties extraAuthzProps,
- Properties javaProps) {
+ // Start servers with all required properties
+ Properties serverProps = buildProperties(authenticator, accessor, false, extraAuthProps, extraAuthzProps);
- 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;
- }
- LogWriterUtils.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
- LogWriterUtils.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;
- }
+ int port1 = createServer1(javaProps, serverProps);
+ int port2 = createServer2(javaProps, serverProps);
- // Perform the operation from selected client
- if (useThisVM) {
- doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), new Integer(
- opFlags), new Integer(expectedResult));
- }
- else {
- byte ordinal = opCode.toOrdinal();
- int[] indices = currentOp.getIndices();
- clientVM.invoke(() -> ClientAuthorizationTestBase.doOp( new Byte(ordinal),
- indices, new Integer(opFlags),
- new Integer(expectedResult) ));
- }
- }
- }
+ // Start client1 with valid CREATE credentials
+ Properties createCredentials = gen.getAllowedCredentials(new OperationCode[] { OperationCode.PUT }, new String[] { regionName }, 1);
+ javaProps = cGen.getJavaProperties();
- // Region: Tests
+ getLogWriter().info("testAllowPutsGets: For first client credentials: " + createCredentials);
- 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();
-
- LogWriterUtils.getLogWriter().info("testAllowPutsGets: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testAllowPutsGets: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testAllowPutsGets: Using accessor: " + accessor);
-
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- Integer port1 = createServer1(javaProps, serverProps);
- Integer port2 = createServer2(javaProps, serverProps);
-
- // Start client1 with valid CREATE credentials
- Properties createCredentials = gen.getAllowedCredentials(
- new OperationCode[] { OperationCode.PUT },
- new String[] { regionName }, 1);
- javaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testAllowPutsGets: For first client credentials: "
- + createCredentials);
- createClient1NoException(javaProps, authInit, port1, port2,
- createCredentials);
-
- // Start client2 with valid GET credentials
- Properties getCredentials = gen.getAllowedCredentials(
- new OperationCode[] { OperationCode.GET },
- new String[] { regionName }, 2);
- javaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter()
- .info(
- "testAllowPutsGets: For second client credentials: "
- + getCredentials);
- createClient2NoException(javaProps, authInit, port1, port2,
- getCredentials);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
-
- // Verify that the gets succeed
- client2.invoke(() -> SecurityTestUtil.doGets(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
+ createClient1NoException(javaProps, authInit, port1, port2, createCredentials);
+
+ // 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);
+
+ createClient2NoException(javaProps, authInit, port1, port2, getCredentials);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2, NO_EXCEPTION));
+
+ // Verify that the gets succeed
+ client2.invoke(() -> doGets(2, NO_EXCEPTION));
}
+ @Test
public void testPutAllWithSecurity() {
AuthzCredentialGenerator gen = getXmlAuthzGenerator();
CredentialGenerator cGen = gen.getCredentialGenerator();
@@ -260,378 +113,228 @@ public class ClientAuthorizationDUnitTest extends ClientAuthorizationTestBase {
String authInit = cGen.getAuthInit();
String accessor = gen.getAuthorizationCallback();
- LogWriterUtils.getLogWriter().info("testPutAllWithSecurity: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info("testPutAllWithSecurity: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testPutAllWithSecurity: Using accessor: " + accessor);
+ getLogWriter().info("testPutAllWithSecurity: Using authinit: " + authInit);
+ getLogWriter().info("testPutAllWithSecurity: Using authenticator: " + authenticator);
+ getLogWriter().info("testPutAllWithSecurity: Using accessor: " + accessor);
// Start servers with all required properties
Properties serverProps = buildProperties(authenticator, accessor, false, extraAuthProps, extraAuthzProps);
- Integer port1 = createServer1(javaProps, serverProps);
- Integer port2 = createServer2(javaProps, serverProps);
+
+ int port1 = createServer1(javaProps, serverProps);
+ int port2 = createServer2(javaProps, serverProps);
// Start client1 with valid CREATE credentials
Properties createCredentials = gen.getAllowedCredentials(new OperationCode[] { OperationCode.PUTALL }, new String[] { regionName }, 1);
javaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter().info("testPutAllWithSecurity: For first client credentials: " + createCredentials);
+
+ getLogWriter().info("testPutAllWithSecurity: For first client credentials: " + createCredentials);
+
createClient1NoException(javaProps, authInit, port1, port2, createCredentials);
// Perform some put all operations from client1
- client1.invoke(() -> SecurityTestUtil.doPutAllP());
- }
-
- protected void createClient2NoException(Properties javaProps, String authInit,
- Integer port1, Integer port2, Properties getCredentials) {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, getCredentials, javaProps, port1, port2,
- null, new Integer(SecurityTestUtil.NO_EXCEPTION) ));
+ client1.invoke(() -> doPutAllP());
}
- protected void createClient1NoException(Properties javaProps, String authInit,
- Integer port1, Integer port2, Properties createCredentials) {
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, createCredentials, javaProps, port1, port2,
- null, new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- }
+ @Test
+ 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();
- protected Integer createServer2(Properties javaProps,
- Properties serverProps) {
- Integer port2 = ((Integer)server2.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- SecurityTestUtil.getLocatorPort(), serverProps, javaProps )));
- return port2;
- }
+ getLogWriter().info("testDisallowPutsGets: Using authinit: " + authInit);
+ getLogWriter().info("testDisallowPutsGets: Using authenticator: " + authenticator);
+ getLogWriter().info("testDisallowPutsGets: Using accessor: " + accessor);
- protected Integer createServer1(Properties javaProps,
- Properties serverProps) {
- Integer port1 = ((Integer)server1.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- SecurityTestUtil.getLocatorPort(), serverProps, javaProps )));
- return port1;
- }
+ // 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();
- public void testDisallowPutsGets() {
+ 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);
+
+ int port1 = createServer1(javaProps, serverProps);
+ int port2 = createServer2(javaProps, serverProps);
+
+ createClient1NoException(createJavaProps, authInit, port1, port2, createCredentials);
+
+ createClient2NoException(getJavaProps, authInit, port1, port2, getCredentials);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2, NO_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();
-
- LogWriterUtils.getLogWriter().info("testDisallowPutsGets: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testDisallowPutsGets: Using authenticator: " + authenticator);
- LogWriterUtils.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();
- LogWriterUtils.getLogWriter().info(
- "testDisallowPutsGets: For first client credentials: "
- + createCredentials);
- Properties getCredentials = gen.getDisallowedCredentials(
- new OperationCode[] { OperationCode.GET },
- new String[] { regionName }, 2);
- Properties getJavaProps = cGen.getJavaProperties();
-
- LogWriterUtils.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 = createServer1(javaProps, serverProps);
- Integer port2 = createServer2(javaProps, serverProps);
-
- createClient1NoException(createJavaProps, authInit, port1, port2,
- createCredentials);
-
- createClient2NoException(getJavaProps, authInit, port1, port2,
- getCredentials);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
-
- // Gets as normal user should throw exception
- client2.invoke(() -> SecurityTestUtil.doGets(
- 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();
- LogWriterUtils.getLogWriter().info(
- "testDisallowPutsGets: For second client with GET credentials: "
- + getCredentials);
- createClient2NoException(getJavaProps, authInit, port1, port2,
- getCredentials);
-
- // Verify that the gets succeed
- client2.invoke(() -> SecurityTestUtil.doGets(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
-
- // Verify that the puts throw exception
- client2.invoke(() -> SecurityTestUtil.doNPuts(
- new Integer(2), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) ));
+ // Gets as normal user should throw exception
+ client2.invoke(() -> doGets(2, 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);
+
+ createClient2NoException(getJavaProps, authInit, port1, port2, getCredentials);
+
+ // Verify that the gets succeed
+ client2.invoke(() -> doGets(2, NO_EXCEPTION));
+
+ // Verify that the puts throw exception
+ client2.invoke(() -> doNPuts(2, NOTAUTHZ_EXCEPTION));
}
+ @Test
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();
-
- LogWriterUtils.getLogWriter().info("testInvalidAccessor: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testInvalidAccessor: Using authenticator: " + authenticator);
-
- // Start server1 with invalid accessor
- Properties serverProps = buildProperties(authenticator,
- "com.gemstone.none", false, extraAuthProps, extraAuthzProps);
- Integer port1 = createServer1(javaProps, serverProps);
- 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();
- LogWriterUtils.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();
- LogWriterUtils.getLogWriter().info(
- "testInvalidAccessor: For second client GET credentials: "
- + getCredentials);
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, createCredentials, createJavaProps, port1,
- port2, null, Boolean.FALSE, Boolean.FALSE,
- Integer.valueOf(SecurityTestUtil.NO_EXCEPTION) ));
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(1), new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) ));
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, getCredentials, getJavaProps, port1, port2,
- null, Boolean.FALSE, Boolean.FALSE,
- Integer.valueOf(SecurityTestUtil.NO_EXCEPTION) ));
- client2.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(1), new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) ));
-
- // Now start server2 that has valid accessor
- LogWriterUtils.getLogWriter().info("testInvalidAccessor: Using accessor: " + accessor);
- serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- createServer2(javaProps, serverProps, port2);
- server1.invoke(() -> SecurityTestUtil.closeCache());
-
- createClient1NoException(createJavaProps, authInit, port1, port2,
- createCredentials);
- createClient2NoException(getJavaProps, authInit, port1, port2,
- getCredentials);
-
- // Now perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
-
- // Verify that the gets succeed
- client2.invoke(() -> SecurityTestUtil.doGets(
- new Integer(4), new Integer(SecurityTestUtil.NO_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("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);
+
+ int port1 = createServer1(javaProps, serverProps);
+ int port2 = getRandomAvailablePort(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);
- protected void createServer2(Properties javaProps, Properties serverProps,
- Integer port2) {
- server2.invoke(() -> ClientAuthorizationTestBase.createCacheServer( SecurityTestUtil.getLocatorPort(), port2, serverProps,
- javaProps ));
+ 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(() -> ClientAuthenticationTestUtils.createCacheClient( authInit, createCredentials, createJavaProps, port1, port2, 0, false, false, NO_EXCEPTION));
+ client1.invoke(() -> doPuts(1, AUTHFAIL_EXCEPTION));
+
+ client2.invoke(() -> ClientAuthenticationTestUtils.createCacheClient( authInit, getCredentials, getJavaProps, port1, port2, 0, false, false, NO_EXCEPTION));
+ client2.invoke(() -> doPuts(1, AUTHFAIL_EXCEPTION));
+
+ // Now start server2 that has valid accessor
+ getLogWriter().info("testInvalidAccessor: Using accessor: " + accessor);
+ serverProps = buildProperties(authenticator, accessor, false, extraAuthProps, extraAuthzProps);
+ createServer2(javaProps, serverProps, port2);
+ server1.invoke(() -> closeCache());
+
+ createClient1NoException(createJavaProps, authInit, port1, port2, createCredentials);
+ createClient2NoException(getJavaProps, authInit, port1, port2, getCredentials);
+
+ // Now perform some put operations from client1
+ client1.invoke(() -> doPuts(4, NO_EXCEPTION));
+
+ // Verify that the gets succeed
+ client2.invoke(() -> doGets(4, NO_EXCEPTION));
}
+ @Test
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();
-
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsWithFailover: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsWithFailover: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsWithFailover: Using accessor: " + accessor);
-
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- Integer port1 = createServer1(javaProps, serverProps);
- // 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();
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsWithFailover: For first client credentials: "
- + createCredentials);
- createClient1NoException(createJavaProps, authInit, port1, port2,
- createCredentials);
-
- // Start client2 with valid GET credentials
- Properties getCredentials = gen.getAllowedCredentials(
- new OperationCode[] { OperationCode.GET },
- new String[] { regionName }, 5);
- Properties getJavaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsWithFailover: For second client credentials: "
- + getCredentials);
- createClient2NoException(getJavaProps, authInit, port1, port2,
- getCredentials);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doGets(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
-
- createServer2(javaProps, serverProps, port2);
- server1.invoke(() -> SecurityTestUtil.closeCache());
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doNPuts(
- new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doNGets(
- 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();
-
- LogWriterUtils.getLogWriter().info(
- "testPutsGetsWithFailover: For second client disallowed GET credentials: "
- + noGetCredentials);
-
- createClient2NoException(getJavaProps, authInit, port1, port2,
- noGetCredentials);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- // Gets as normal user should throw exception
- client2.invoke(() -> SecurityTestUtil.doGets(
- new Integer(4), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) ));
-
- // force a failover and do the drill again
- server1.invoke(() -> ClientAuthorizationTestBase.createCacheServer( SecurityTestUtil.getLocatorPort(), port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.closeCache());
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doNPuts(
- new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- // Gets as normal user should throw exception
- client2.invoke(() -> SecurityTestUtil.doNGets(
- new Integer(4), new Integer(SecurityTestUtil.NOTAUTHZ_EXCEPTION) ));
-
- createClient2NoException(getJavaProps, authInit, port1, port2,
- getCredentials);
-
- // Verify that the gets succeed
- client2.invoke(() -> SecurityTestUtil.doNGets(
- new Integer(4), new Integer(SecurityTestUtil.NO_EXCEPTION) ));
-
- // Verify that the puts throw exception
- client2.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(4), new Integer(SecurityTestUtil.NOTAUTHZ_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();
- public void testUnregisterInterestWithFailover() {
+ getLogWriter().info("testPutsGetsWithFailover: Using authinit: " + authInit);
+ getLogWriter().info("testPutsGetsWithFailover: Using authenticator: " + authenticator);
+ getLogWriter().info("testPutsGetsWithFailover: Using accessor: " + accessor);
- 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),
+ // Start servers with all required properties
+ Properties serverProps = buildProperties(authenticator, accessor, false, extraAuthProps, extraAuthzProps);
- OperationWithAction.OPBLOCK_END,
+ int port1 = createServer1(javaProps, serverProps);
- // 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),
+ // Get a port for second server but do not start it. This forces the clients to connect to the first server
+ int port2 = getRandomAvailablePort(SOCKET);
- OperationWithAction.OPBLOCK_END,
+ // Start client1 with valid CREATE credentials
+ Properties createCredentials = gen.getAllowedCredentials(new OperationCode[] { OperationCode.PUT }, new String[] { regionName }, 1);
+ Properties createJavaProps = cGen.getJavaProperties();
- // 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),
+ getLogWriter().info("testPutsGetsWithFailover: For first client credentials: " + createCredentials);
- OperationWithAction.OPBLOCK_END };
+ createClient1NoException(createJavaProps, authInit, port1, port2, createCredentials);
+
+ // 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);
+
+ createClient2NoException(getJavaProps, authInit, port1, port2, getCredentials);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2, NO_EXCEPTION));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doGets(2, NO_EXCEPTION));
+
+ createServer2(javaProps, serverProps, port2);
+ server1.invoke(() -> closeCache());
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doNPuts(4, NO_EXCEPTION));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doNGets(4, 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);
+
+ createClient2NoException(getJavaProps, authInit, port1, port2, noGetCredentials);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(4, NO_EXCEPTION));
+
+ // Gets as normal user should throw exception
+ client2.invoke(() -> doGets(4, NOTAUTHZ_EXCEPTION));
+
+ // force a failover and do the drill again
+ server1.invoke(() -> ClientAuthorizationTestCase.createCacheServer( getLocatorPort(), port1, serverProps, javaProps ));
+ server2.invoke(() -> closeCache());
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doNPuts(4, NO_EXCEPTION));
+
+ // Gets as normal user should throw exception
+ client2.invoke(() -> doNGets(4, NOTAUTHZ_EXCEPTION));
+
+ createClient2NoException(getJavaProps, authInit, port1, port2, getCredentials);
+
+ // Verify that the gets succeed
+ client2.invoke(() -> doNGets(4, NO_EXCEPTION));
+
+ // Verify that the puts throw exception
+ client2.invoke(() -> doPuts(4, NOTAUTHZ_EXCEPTION));
+ }
+
+ @Test
+ public void testUnregisterInterestWithFailover() throws InterruptedException {
+ OperationWithAction[] unregisterOps = unregisterOpsForTestUnregisterInterestWithFailover();
AuthzCredentialGenerator gen = new XmlAuthzCredentialGenerator();
CredentialGenerator cGen = new DummyCredentialGenerator();
@@ -644,167 +347,300 @@ public class ClientAuthorizationDUnitTest extends ClientAuthorizationTestBase {
String authInit = cGen.getAuthInit();
String accessor = gen.getAuthorizationCallback();
- LogWriterUtils.getLogWriter().info("testAllOpsWithFailover: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testAllOpsWithFailover: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testAllOpsWithFailover: Using accessor: " + accessor);
+ 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);
+ 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));
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 = getRandomAvailablePort(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
+
+ // 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 (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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.closeCache());
- executeRIOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
- extraAuthzProps, javaProps);
+ server1.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), port1, serverProps, javaProps));
+ server2.invoke(() -> closeCache());
+
+ executeRIOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, javaProps);
+
if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
createServer2(javaProps, serverProps, port2);
- server1.invoke(() -> SecurityTestUtil.closeCache());
- executeRIOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
- extraAuthzProps, javaProps);
+ server1.invoke(() -> closeCache());
+
+ executeRIOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, javaProps);
}
opBlock.clear();
}
- }
- else {
+
+ } else {
currentOp.setOpNum(opNum);
opBlock.add(currentOp);
}
}
}
-
- public void testAllOpsWithFailover() {
- IgnoredException.addIgnoredException("Read timed out");
+ @Test
+ public void testAllOpsWithFailover() throws InterruptedException {
+ addIgnoredException("Read timed out");
+ runOpsWithFailOver(allOpsForAllOpsWithFailover(), "testAllOpsWithFailover");
+ }
+
+ private OperationWithAction[] unregisterOpsForTestUnregisterInterestWithFailover() {
+ return new OperationWithAction[] {
+ // 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
+ };
+ }
- OperationWithAction[] allOps = {
+ private OperationWithAction[] allOpsForAllOpsWithFailover() {
+ return new OperationWithAction[] {
// 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, 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
+ // 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, 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),
+ 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, 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),
+ 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, 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
+ 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, 3, OpFlags.CHECK_NOTAUTHZ, 4),
new OperationWithAction(OperationCode.CONTAINS_KEY),
- // Destroy the keys and check for failure in 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),
+ 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, 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, 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),
+ // 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),
+ 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),
+ // 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),
+ 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),
+ new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_GET_ENTRY_IN_TX | OpFlags.CHECK_FAIL, 4),
OperationWithAction.OPBLOCK_END };
+ }
- runOpsWithFailover(allOps, "testAllOpsWithFailover");
+ private Properties getUserPassword(final String userName) {
+ Properties props = new Properties();
+ props.setProperty(UserPasswordAuthInit.USER_NAME, userName);
+ props.setProperty(UserPasswordAuthInit.PASSWORD, userName);
+ return props;
}
- // End Region: Tests
+ private void executeRIOpBlock(final List<OperationWithAction> opBlock, final int port1, final int port2, final String authInit, final Properties extraAuthProps, final Properties extraAuthzProps, final Properties javaProps) throws InterruptedException {
+ for (Iterator opIter = opBlock.iterator(); 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;
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- SecurityTestUtil.closeCache();
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ 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 += ('/' + SUBREGION_NAME);
+ }
+ 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 = 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) {
+ createCacheClientWithDynamicRegion(authInit, clientProps, javaProps, new int[] { port1, port2 }, 0, false, NO_EXCEPTION);
+ } else {
+ clientVM.invoke(() -> createCacheClient(authInit, clientProps, javaProps, new int[] { port1, port2 }, 0, false, NO_EXCEPTION));
+ }
+
+ }
+
+ int expectedResult;
+ if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0) {
+ expectedResult = NOTAUTHZ_EXCEPTION;
+ } else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
+ expectedResult = OTHER_EXCEPTION;
+ } else {
+ expectedResult = NO_EXCEPTION;
+ }
+
+ // Perform the operation from selected client
+ if (useThisVM) {
+ doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), opFlags, expectedResult);
+
+ } else {
+ byte ordinal = opCode.toOrdinal();
+ int[] indices = currentOp.getIndices();
+ clientVM.invoke(() -> ClientAuthorizationTestCase.doOp(ordinal, indices, opFlags, expectedResult));
+ }
+ }
+ }
+
+ private void createClient2NoException(final Properties javaProps, final String authInit, final int port1, final int port2, final Properties getCredentials) {
+ client2.invoke(() -> ClientAuthenticationTestUtils.createCacheClient(authInit, getCredentials, javaProps, port1, port2, 0, NO_EXCEPTION));
+ }
+
+ private void createClient1NoException(final Properties javaProps, final String authInit, final int port1, final int port2, final Properties createCredentials) {
+ client1.invoke(() -> ClientAuthenticationTestUtils.createCacheClient(authInit, createCredentials, javaProps, port1, port2, 0, NO_EXCEPTION));
+ }
+
+ private int createServer2(final Properties javaProps, final Properties serverProps) {
+ return server2.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), serverProps, javaProps));
+ }
+
+ private int createServer1(final Properties javaProps, final Properties serverProps) {
+ return server1.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), serverProps, javaProps));
+ }
+
+ private void createServer2(Properties javaProps, Properties serverProps, int port2) {
+ server2.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), port2, serverProps, javaProps));
}
}
[07/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestCase.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestCase.java
new file mode 100644
index 0000000..088dec4
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthorizationTestCase.java
@@ -0,0 +1,1323 @@
+/*
+ * 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.
+ */
+package com.gemstone.gemfire.security;
+
+import static com.gemstone.gemfire.distributed.internal.DistributionConfig.*;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.Host.*;
+import static com.gemstone.gemfire.test.dunit.Wait.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+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 java.util.concurrent.Callable;
+
+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.internal.AvailablePort.Keeper;
+import com.gemstone.gemfire.internal.cache.AbstractRegionEntry;
+import com.gemstone.gemfire.internal.cache.LocalRegion;
+import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
+import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator.ClassCode;
+import com.gemstone.gemfire.security.generator.CredentialGenerator;
+import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
+import com.gemstone.gemfire.security.generator.XmlAuthzCredentialGenerator;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.dunit.WaitCriterion;
+import com.gemstone.gemfire.test.dunit.internal.JUnit4DistributedTestCase;
+
+/**
+ * Base class for tests for authorization from client to server. It contains
+ * utility functions for the authorization tests from client to server.
+ *
+ * @since 5.5
+ */
+public abstract class ClientAuthorizationTestCase extends JUnit4DistributedTestCase {
+
+ private static final int PAUSE = 5 * 1000;
+
+ 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 = REGION_NAME; // TODO: remove
+ protected static final String SUBREGION_NAME = "AuthSubregion";
+
+ private static final String[] serverIgnoredExceptions = {
+ "Connection refused",
+ AuthenticationRequiredException.class.getName(),
+ AuthenticationFailedException.class.getName(),
+ NotAuthorizedException.class.getName(),
+ GemFireSecurityException.class.getName(),
+ RegionDestroyedException.class.getName(),
+ ClassNotFoundException.class.getName()
+ };
+
+ private static final String[] clientIgnoredExceptions = {
+ AuthenticationFailedException.class.getName(),
+ NotAuthorizedException.class.getName(),
+ RegionDestroyedException.class.getName()
+ };
+
+ @Override
+ public final void preSetUp() throws Exception {
+ }
+
+ @Override
+ public final void postSetUp() throws Exception {
+ preSetUpClientAuthorizationTestBase();
+ setUpClientAuthorizationTestBase();
+ postSetUpClientAuthorizationTestBase();
+ }
+
+ private final void setUpClientAuthorizationTestBase() throws Exception {
+ server1 = getHost(0).getVM(0);
+ server2 = getHost(0).getVM(1);
+ client1 = getHost(0).getVM(2);
+ client2 = getHost(0).getVM(3);
+ setUpIgnoredExceptions();
+ }
+
+ private final void setUpIgnoredExceptions() {
+ Set<String> serverExceptions = new HashSet<>();
+ serverExceptions.addAll(Arrays.asList(serverIgnoredExceptions()));
+ if (serverExceptions.isEmpty()) {
+ serverExceptions.addAll(Arrays.asList(serverIgnoredExceptions));
+ }
+
+ String[] serverExceptionsArray = serverExceptions.toArray(new String[serverExceptions.size()]);
+ server1.invoke(() -> registerExpectedExceptions(serverExceptionsArray));
+ server2.invoke(() -> registerExpectedExceptions(serverExceptionsArray));
+
+ Set<String> clientExceptions = new HashSet<>();
+ clientExceptions.addAll(Arrays.asList(clientIgnoredExceptions()));
+ if (clientExceptions.isEmpty()) {
+ clientExceptions.addAll(Arrays.asList(clientIgnoredExceptions));
+ }
+
+ String[] clientExceptionsArray = serverExceptions.toArray(new String[clientExceptions.size()]);
+ client2.invoke(() -> registerExpectedExceptions(clientExceptionsArray));
+ registerExpectedExceptions(clientExceptionsArray);
+ }
+
+ protected String[] serverIgnoredExceptions() {
+ return new String[]{};
+ }
+
+ protected String[] clientIgnoredExceptions() {
+ return new String[]{};
+ }
+
+ protected void preSetUpClientAuthorizationTestBase() throws Exception {
+ }
+
+ protected void postSetUpClientAuthorizationTestBase() throws Exception {
+ }
+
+ @Override
+ public final void preTearDown() throws Exception {
+ preTearDownClientAuthorizationTestBase();
+ tearDownClientAuthorizationTestBase();
+ postTearDownClientAuthorizationTestBase();
+ }
+
+ @Override
+ public final void postTearDown() throws Exception {
+ }
+
+ private final void tearDownClientAuthorizationTestBase() throws Exception {
+ // close the clients first
+ client1.invoke(() -> closeCache());
+ client2.invoke(() -> closeCache());
+ // then close the servers
+ server1.invoke(() -> closeCache());
+ server2.invoke(() -> closeCache());
+ }
+
+ protected void preTearDownClientAuthorizationTestBase() throws Exception {
+ }
+
+ protected void postTearDownClientAuthorizationTestBase() throws Exception {
+ }
+
+ protected static Properties buildProperties(final String authenticator, final String accessor, final boolean isAccessorPP, final Properties extraAuthProps, final Properties extraAuthzProps) {
+ Properties authProps = new Properties();
+ if (authenticator != null) {
+ authProps.setProperty(SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
+ }
+ if (accessor != null) {
+ if (isAccessorPP) {
+ authProps.setProperty(SECURITY_CLIENT_ACCESSOR_PP_NAME, accessor);
+ } else {
+ authProps.setProperty(SECURITY_CLIENT_ACCESSOR_NAME, accessor);
+ }
+ }
+ return concatProperties(new Properties[] { authProps, extraAuthProps, extraAuthzProps });
+ }
+
+ protected static Integer createCacheServer(int locatorPort, final Properties authProps, final Properties javaProps) {
+ if (locatorPort == 0) {
+ locatorPort = getRandomAvailablePort(SOCKET);
+ }
+ return SecurityTestUtils.createCacheServer(authProps, javaProps, locatorPort, null, 0, true, NO_EXCEPTION);
+ }
+
+ protected static int createCacheServer(int locatorPort, final int serverPort, final Properties authProps, final Properties javaProps) {
+ if (locatorPort == 0) {
+ locatorPort = getRandomAvailablePort(SOCKET);
+ }
+ return SecurityTestUtils.createCacheServer(authProps, javaProps, locatorPort, null, serverPort, true, NO_EXCEPTION);
+ }
+
+ protected static Region getRegion() {
+ return getCache().getRegion(regionName);
+ }
+
+ protected static Region getSubregion() {
+ return getCache().getRegion(regionName + '/' + SUBREGION_NAME);
+ }
+
+ private static Region createSubregion(final Region region) {
+ Region subregion = getSubregion();
+ if (subregion == null) {
+ subregion = region.createSubregion(SUBREGION_NAME, region.getAttributes());
+ }
+ return subregion;
+ }
+
+ protected static String indicesToString(final 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;
+ }
+
+ protected static void doOp(final byte opCode, final int[] indices, final int flagsI, final int expectedResult) throws InterruptedException {
+ OperationCode op = OperationCode.fromOrdinal(opCode);
+ boolean operationOmitted = false;
+ final int flags = flagsI;
+ 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
+ waitForCondition(() -> getSubregion() == null);
+ subregion = getSubregion();
+ assertNull(subregion);
+ return;
+
+ } else {
+ // Wait for some time for DRF update to come
+ waitForCondition(() -> 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
+ waitForCondition(() -> getRegion() == null);
+ region = getRegion();
+ assertNull(region);
+ return;
+
+ } else {
+ assertNotNull(region);
+ }
+
+ final String[] keys = KEYS;
+ final String[] vals;
+ if ((flags & OpFlags.USE_NEWVAL) > 0) {
+ vals = NVALUES;
+ }
+ else {
+ vals = VALUES;
+ }
+
+ InterestResultPolicy policy = InterestResultPolicy.KEYS_VALUES;
+ if ((flags & OpFlags.REGISTER_POLICY_NONE) > 0) {
+ policy = InterestResultPolicy.NONE;
+ }
+
+ final int numOps = indices.length;
+ System.out.println("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()) {
+ Thread.sleep(PAUSE);
+ }
+
+ 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);
+ System.out.println(""+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<Boolean> condition = new Callable<Boolean>() {
+ private Region region;
+
+ @Override
+ public Boolean call() throws Exception {
+ Object value = getLocalValue(region, key);
+ return (flags & OpFlags.CHECK_FAIL) > 0 ? !expectedVal.equals(value) : expectedVal.equals(value);
+ }
+
+ public Callable<Boolean> init(Region region) {
+ this.region = region;
+ return this;
+ }
+ }.init(region);
+ waitForCondition(condition);
+
+ value = getLocalValue(region, key);
+
+ } else if ((flags & OpFlags.USE_GET_ENTRY_IN_TX) > 0) {
+ getCache().getCacheTransactionManager().begin();
+ Entry e = region.getEntry(key);
+
+ // Also, check getAll()
+ ArrayList a = new ArrayList();
+ a.addAll(a);
+ region.getAll(a);
+
+ 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 = 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() {
+ @Override
+ public boolean done() {
+ if ((flags & OpFlags.CHECK_FAIL) > 0) {
+ return 0 == listener.getNumUpdates();
+ } else {
+ return numOps == listener.getNumUpdates();
+ }
+ }
+ @Override
+ public String description() {
+ return null;
+ }
+ };
+ 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 = getCache().getQueryService().getCq("cq1");
+ ((AuthzCqListener)cqQuery.getCqAttributes().getCqListener()).reset();
+ cqQuery.stop();
+
+ } else if (op.isCloseCQ()) {
+ breakLoop = true;
+ CqQuery cqQuery = 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, SUBREGION_NAME);
+ assertEquals('/' + regionName + '/' + SUBREGION_NAME, 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
+ System.out.println("doOp: sub-region " + region.getFullPath() + " already destroyed");
+ operationOmitted = true;
+ }
+ } else {
+ region.destroyRegion();
+ }
+ }
+
+ } else {
+ fail("doOp: Unhandled operation " + op);
+ }
+
+ if (expectedResult != 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 == NOTAUTHZ_EXCEPTION) && (ex.getCause() instanceof NotAuthorizedException)) {
+ System.out.println("doOp: Got expected NotAuthorizedException when doing operation [" + op + "] with flags " + OpFlags.description(flags) + ": " + ex.getCause());
+ continue;
+ } else if (expectedResult == OTHER_EXCEPTION) {
+ System.out.println("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 != NO_EXCEPTION) {
+ fail("Expected an exception while performing operation: " + op + " flags = " + OpFlags.description(flags));
+ }
+ }
+
+ protected void executeOpBlock(final List<OperationWithAction> opBlock, final int port1, final int port2, final String authInit, final Properties extraAuthProps, final Properties extraAuthzProps, final TestCredentialGenerator credentialGenerator, final Random random) throws InterruptedException {
+ for (Iterator<OperationWithAction> opIter = opBlock.iterator(); opIter.hasNext();) {
+ // Start client with valid credentials as specified in OperationWithAction
+ OperationWithAction currentOp = 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;
+ }
+
+ System.out.println("executeOpBlock: performing operation number [" + currentOp.getOpNum() + "]: " + currentOp);
+ if ((opFlags & OpFlags.USE_OLDCONN) == 0) {
+ Properties opCredentials;
+ int newRnd = random.nextInt(100) + 1;
+ String currentRegionName = '/' + regionName;
+ if ((opFlags & OpFlags.USE_SUBREGION) > 0) {
+ currentRegionName += ('/' + SUBREGION_NAME);
+ }
+
+ String credentialsTypeStr;
+ OperationCode authOpCode = currentOp.getAuthzOperationCode();
+ int[] indices = currentOp.getIndices();
+ CredentialGenerator cGen = credentialGenerator.getCredentialGenerator();
+ final Properties javaProps = cGen == null ? null : cGen.getJavaProperties();
+
+ if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0 || (opFlags & OpFlags.USE_NOTAUTHZ) > 0) {
+ opCredentials = credentialGenerator.getDisallowedCredentials(new OperationCode[] { authOpCode }, new String[] { currentRegionName }, indices, newRnd);
+ credentialsTypeStr = " unauthorized " + authOpCode;
+ } else {
+ opCredentials = credentialGenerator.getAllowedCredentials(new OperationCode[] { opCode, authOpCode }, new String[] { currentRegionName }, indices, newRnd);
+ credentialsTypeStr = " authorized " + authOpCode;
+ }
+
+ Properties clientProps = concatProperties(new Properties[] { opCredentials, extraAuthProps, extraAuthzProps });
+ // Start the client with valid credentials but allowed or disallowed to perform an operation
+ System.out.println("executeOpBlock: For client" + clientNum + credentialsTypeStr + " credentials: " + opCredentials);
+ boolean setupDynamicRegionFactory = (opFlags & OpFlags.ENABLE_DRF) > 0;
+
+ if (useThisVM) {
+ SecurityTestUtils.createCacheClientWithDynamicRegion(authInit, clientProps, javaProps, new int[] { port1, port2 }, 0, setupDynamicRegionFactory, NO_EXCEPTION);
+ } else {
+ clientVM.invoke(() -> SecurityTestUtils.createCacheClientWithDynamicRegion(authInit, clientProps, javaProps, new int[] { port1, port2 }, 0, setupDynamicRegionFactory, NO_EXCEPTION));
+ }
+ }
+
+ int expectedResult;
+ if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0) {
+ expectedResult = NOTAUTHZ_EXCEPTION;
+ } else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
+ expectedResult = OTHER_EXCEPTION;
+ } else {
+ expectedResult = NO_EXCEPTION;
+ }
+
+ // Perform the operation from selected client
+ if (useThisVM) {
+ doOp(opCode.toOrdinal(), currentOp.getIndices(), new Integer(opFlags), new Integer(expectedResult));
+ } else {
+ byte ordinal = opCode.toOrdinal();
+ int[] indices = currentOp.getIndices();
+ clientVM.invoke(() -> ClientAuthorizationTestCase.doOp( new Byte(ordinal), indices, 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<AuthzCredentialGenerator> getDummyGeneratorCombos() {
+ List<AuthzCredentialGenerator> 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(final OperationWithAction[] opCodes, final String testName) throws InterruptedException {
+ 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);
+
+ System.out.println(testName + ": Using authinit: " + authInit);
+ System.out.println(testName + ": Using authenticator: " + authenticator);
+ System.out.println(testName + ": Using accessor: " + accessor);
+
+ // Start servers with all required properties
+ Properties serverProps = buildProperties(authenticator, accessor, false, extraAuthProps, extraAuthzProps);
+
+ // Get ports for the servers
+ Keeper locator1PortKeeper = getRandomAvailablePortKeeper(SOCKET);
+ Keeper locator2PortKeeper = getRandomAvailablePortKeeper(SOCKET);
+ Keeper port1Keeper = getRandomAvailablePortKeeper(SOCKET);
+ Keeper port2Keeper = getRandomAvailablePortKeeper(SOCKET);
+ int locator1Port = locator1PortKeeper.getPort();
+ int locator2Port = locator2PortKeeper.getPort();
+ 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) {
+ locator1PortKeeper.release();
+ port1Keeper.release();
+
+ // Start the first server and execute the operation block
+ server1.invoke(() -> ClientAuthorizationTestCase.createCacheServer(locator1Port, port1, serverProps, javaProps ));
+ server2.invoke(() -> 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
+ locator2PortKeeper.release();
+ port2Keeper.release();
+
+ server2.invoke(() -> ClientAuthorizationTestCase.createCacheServer(locator2Port, port2, serverProps, javaProps ));
+ server1.invoke(() -> 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.
+ *
+ * @since 5.5
+ */
+ private static class AuthzCqListener implements CqListener {
+
+ private List<CqEvent> 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(final 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(final 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(final String[] vals, final int[] indices) {
+ for (int indexIndex = 0; indexIndex < indices.length; ++indexIndex) {
+ int index = indices[indexIndex];
+ boolean foundKey = false;
+
+ for (Iterator<CqEvent> eventIter = this.eventList.iterator(); eventIter.hasNext();) {
+ CqEvent event = (CqEvent)eventIter.next();
+ if (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.
+ *
+ * @since 5.5
+ */
+ protected 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;
+
+ public static 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.
+ *
+ * @since 5.5
+ */
+ protected 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(final OperationCode opCode) {
+ this.opCode = opCode;
+ this.authzOpCode = opCode;
+ this.clientNum = 1;
+ this.flags = OpFlags.NONE;
+ setIndices(4);
+ this.opNum = 0;
+ }
+
+ public OperationWithAction(final OperationCode opCode, final int clientNum) {
+ this.opCode = opCode;
+ this.authzOpCode = opCode;
+ this.clientNum = clientNum;
+ this.flags = OpFlags.NONE;
+ setIndices(4);
+ this.opNum = 0;
+ }
+
+ public OperationWithAction(final OperationCode opCode, final int clientNum, final int flags, final int numOps) {
+ this.opCode = opCode;
+ this.authzOpCode = opCode;
+ this.clientNum = clientNum;
+ this.flags = flags;
+ setIndices(numOps);
+ this.opNum = 0;
+ }
+
+ public OperationWithAction(final OperationCode opCode, final OperationCode deniedOpCode, final int clientNum, final int flags, final int numOps) {
+ this.opCode = opCode;
+ this.authzOpCode = deniedOpCode;
+ this.clientNum = clientNum;
+ this.flags = flags;
+ setIndices(numOps);
+ this.opNum = 0;
+ }
+
+ public OperationWithAction(final OperationCode opCode, final int clientNum, final int flags, final int[] indices) {
+ this.opCode = opCode;
+ this.authzOpCode = opCode;
+ this.clientNum = clientNum;
+ this.flags = flags;
+ this.indices = indices;
+ this.opNum = 0;
+ }
+
+ public OperationWithAction(final OperationCode opCode, final OperationCode deniedOpCode, final int clientNum, final int flags, final 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;
+ }
+
+ @Override
+ 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.
+ *
+ * @since 5.5
+ */
+ protected 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.
+ *
+ * @since 5.5
+ */
+ protected static class TestAuthzCredentialGenerator implements TestCredentialGenerator {
+
+ private AuthzCredentialGenerator authzGen;
+
+ public TestAuthzCredentialGenerator(final AuthzCredentialGenerator authzGen) {
+ this.authzGen = authzGen;
+ }
+
+ public Properties getAllowedCredentials(final OperationCode[] opCodes, final String[] regionNames, final int[] keyIndices, final int num) {
+ return this.authzGen.getAllowedCredentials(opCodes, regionNames, num);
+ }
+
+ public Properties getDisallowedCredentials(final OperationCode[] opCodes, final String[] regionNames, final int[] keyIndices, final int num) {
+ return this.authzGen.getDisallowedCredentials(opCodes, regionNames, num);
+ }
+
+ public CredentialGenerator getCredentialGenerator() {
+ return authzGen.getCredentialGenerator();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
index 496c3a2..441d52c 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientMultiUserAuthzDUnitTest.java
@@ -1,6 +1,3 @@
-
-package com.gemstone.gemfire.security;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,9 +6,9 @@ package com.gemstone.gemfire.security;
* 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
@@ -19,51 +16,45 @@ package com.gemstone.gemfire.security;
* specific language governing permissions and limitations
* under the License.
*/
+package com.gemstone.gemfire.security;
+//import static com.gemstone.gemfire.security.ClientAuthenticationTestUtils.*;
+//import static com.gemstone.gemfire.security.ClientAuthorizationTestCase.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
import java.util.Iterator;
import java.util.Properties;
-import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
-import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.test.dunit.VM;
-
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.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.execute.PRClientServerTestBase;
import com.gemstone.gemfire.internal.cache.functions.TestFunction;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
-
-public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestBase {
+import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
+import com.gemstone.gemfire.security.generator.CredentialGenerator;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
- /** constructor */
- public ClientMultiUserAuthzDUnitTest(String name) {
- super(name);
- }
+@Category(DistributedTest.class)
+public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestCase {
@Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+ public final void preTearDownClientAuthorizationTestBase() throws Exception {
+ closeCache();
}
- // Tests with one user authorized to do puts/gets/containsKey/destroys and
- // another not authorized for the same.
+ /**
+ * Tests with one user authorized to do puts/gets/containsKey/destroys and
+ * another not authorized for the same.
+ */
+ @Test
public void testOps1() throws Exception {
- Iterator iter = getDummyGeneratorCombos().iterator();
- while (iter.hasNext()) {
- AuthzCredentialGenerator gen = (AuthzCredentialGenerator)iter.next();
+ for (Iterator<AuthzCredentialGenerator> iter = getDummyGeneratorCombos().iterator(); iter.hasNext();) {
+ AuthzCredentialGenerator gen = iter.next();
CredentialGenerator cGen = gen.getCredentialGenerator();
Properties extraAuthProps = cGen.getSystemProperties();
Properties javaProps = cGen.getJavaProperties();
@@ -72,134 +63,204 @@ public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestBase {
String authInit = cGen.getAuthInit();
String accessor = gen.getAuthorizationCallback();
- LogWriterUtils.getLogWriter().info("testOps1: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testOps1: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testOps1: Using accessor: " + accessor);
+ 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);
+ Properties serverProps = buildProperties(authenticator, accessor, false, extraAuthProps, extraAuthzProps);
- Integer port1 = createCacheServerOnVM(server1, javaProps, serverProps);
- Integer port2 = createCacheServerOnVM(server2, javaProps, serverProps);
+ int port1 = createCacheServerOnVM(server1, javaProps, serverProps);
+ int port2 = createCacheServerOnVM(server2, javaProps, serverProps);
- if (!prepareClientsForOps(gen, cGen, new OperationCode[] {
- OperationCode.PUT, OperationCode.PUT}, new OperationCode[] {
- OperationCode.GET, OperationCode.GET}, javaProps, authInit, port1,
- port2)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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 */);
+ /**
+ * Test query/function execute
+ */
+ @Test
+ 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);
+
+ int port1 = createCacheServerOnVM(server1, javaProps, serverProps);
+ int port2 = createCacheServerOnVM(server2, javaProps, serverProps);
+
+ // 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]);
+
+ final Properties finalJavaProps = javaProps;
+ client1.invoke(() -> createCacheClientForMultiUserMode(2, authInit, client1Credentials, finalJavaProps, new int[] {port1, port2}, -1, false, 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]);
+
+ final Properties finalJavaProps2 = javaProps;
+ client2.invoke(() -> createCacheClientForMultiUserMode(2, authInit, client2Credentials, finalJavaProps2, new int[] {port1, port2}, -1, false, NO_EXCEPTION));
+
+ Function function = new TestFunction(true,TestFunction.TEST_FUNCTION1);
+
+ server1.invoke(() -> PRClientServerTestBase.registerFunction(function));
+
+ server2.invoke(() -> PRClientServerTestBase.registerFunction(function));
+
+ // Perform some put operations before verifying queries
+ client1.invoke(() -> doMultiUserPuts(4, 2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}));
+ client1.invoke(() -> doMultiUserQueries(2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, 4));
+ client1.invoke(() -> doMultiUserQueryExecute(2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, 4));
+
+ // Verify that the FE succeeds/fails
+ client2.invoke(() ->doMultiUserFE(2, function, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, false));
+
+ // Failover
+ server1.invoke(() -> closeCache());
+ Thread.sleep(2000);
+
+ client1.invoke(() -> doMultiUserPuts(4, 2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}));
+
+ client1.invoke(() -> doMultiUserQueries(2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, 4));
+ client1.invoke(() -> doMultiUserQueryExecute(2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, 4));
+
+ // Verify that the FE succeeds/fails
+ client2.invoke(() -> doMultiUserFE(2, function, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, true));
+ }
+
+ @Test
+ public void testOpsWithClientsInDifferentModes() throws Exception {
+ for (Iterator<AuthzCredentialGenerator> iter = getDummyGeneratorCombos().iterator(); iter.hasNext();) {
+ AuthzCredentialGenerator gen = 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);
+
+ int port1 = createCacheServerOnVM(server1, javaProps, serverProps);
+ int port2 = createCacheServerOnVM(server2, javaProps, serverProps);
+
+ if (!prepareClientsForOps(gen, cGen, new OperationCode[] { OperationCode.PUT, OperationCode.PUT}, new OperationCode[] { OperationCode.GET, OperationCode.GET}, javaProps, authInit, port1, port2, false, 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, false, false)) {
+ continue;
+ }
+
+ verifyContainsKeyDestroys(false, false);
+ }
}
- private boolean prepareClientsForOps(AuthzCredentialGenerator gen,
- CredentialGenerator cGen, OperationCode[] client1OpCodes,
- OperationCode[] client2OpCodes, Properties javaProps, String authInit,
- Integer port1, Integer port2, Boolean bothClientsInMultiuserMode,
- Boolean allowOp) {
+ private boolean prepareClientsForOps(final AuthzCredentialGenerator gen, final CredentialGenerator cGen, final OperationCode[] client1OpCodes, final OperationCode[] client2OpCodes, final Properties javaProps, final String authInit, final int port1, final int port2) {
+ return prepareClientsForOps(gen, cGen, client1OpCodes, client2OpCodes, javaProps, authInit, port1, port2, true /* both clients in multiuser mode */, false /* unused */);
+ }
+
+ private boolean prepareClientsForOps(final AuthzCredentialGenerator gen, final CredentialGenerator cGen, final OperationCode[] client1OpCodes, final OperationCode[] client2OpCodes, Properties javaProps, final String authInit, final int port1, final int port2, final boolean bothClientsInMultiuserMode, final 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)};
+ 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) {
- LogWriterUtils.getLogWriter().info(
- "testOps1: Unable to obtain valid credentials with "
- + client1OpCodes[0].toString()
- + " permission; skipping this combination.");
+ 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) {
- LogWriterUtils.getLogWriter().info(
- "testOps1: Unable to obtain valid credentials with no "
- + client1OpCodes[0].toString()
- + " permission; skipping this combination.");
+ getLogWriter().info("testOps1: Unable to obtain valid credentials with no " + client1OpCodes[0].toString() + " permission; skipping this combination.");
return false;
}
+
javaProps = cGen.getJavaProperties();
- LogWriterUtils.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});
+ getLogWriter().info("testOps1: For first client credentials: " + client1Credentials[0] + "\n" + client1Credentials[1]);
+ final Properties finalJavaProps = javaProps;
+
+ client1.invoke(() -> createCacheClientForMultiUserMode(2, authInit, client1Credentials, finalJavaProps, new int[] {port1, port2}, -1, false, 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)};
+ 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) {
- LogWriterUtils.getLogWriter().info(
- "testOps1: Unable to obtain valid credentials with "
- + client2OpCodes[0].toString()
- + " permission; skipping this combination.");
+ 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) {
- LogWriterUtils.getLogWriter().info(
- "testOps1: Unable to obtain valid credentials with no "
- + client2OpCodes[0].toString()
- + " permission; skipping this combination.");
+ getLogWriter().info("testOps1: Unable to obtain valid credentials with no " + client2OpCodes[0].toString() + " permission; skipping this combination.");
return false;
}
+
javaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testOps1: For second client credentials: " + client2Credentials[0]
- + "\n" + client2Credentials[1]);
+ 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});
+ final Properties finalJavaProps2 = javaProps;
+ client2.invoke(() -> createCacheClientForMultiUserMode(2, authInit, client2Credentials, finalJavaProps2, new int[] {port1, port2}, -1, false, 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});
+ final Properties finalJavaProps2 = javaProps;
+ client2.invoke(() -> createCacheClient(authInit, client2Credentials[credentialsIndex], finalJavaProps2, new int[] {port1, port2}, -1, false, false, NO_EXCEPTION));
}
+
return true;
}
@@ -207,28 +268,17 @@ public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestBase {
verifyPutsGets(true, false /*unused */);
}
- private void verifyPutsGets(Boolean isMultiuser, Boolean opAllowed)
- throws Exception {
+ private void verifyPutsGets(final boolean isMultiuser, final 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}});
+ client1.invoke(() -> doMultiUserPuts(2, 2, new int[] { NO_EXCEPTION, 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}});
+ client2.invoke(() -> doMultiUserGets(2, 2, new int[] {NO_EXCEPTION, 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}});
+ int expectedResult = (opAllowed) ? NO_EXCEPTION : NOTAUTHZ_EXCEPTION;
+ client2.invoke(() -> doMultiUserGets(1, 1, new int[] {expectedResult}));
}
}
@@ -236,36 +286,18 @@ public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestBase {
verifyContainsKeyDestroys(true, false /* unused */);
}
- private void verifyContainsKeyDestroys(Boolean isMultiuser, Boolean opAllowed)
- throws Exception {
+ private void verifyContainsKeyDestroys(final boolean isMultiUser, final 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}});
+ client1.invoke(() -> doMultiUserPuts(2, 2, new int[] {NO_EXCEPTION, NO_EXCEPTION}));
+ client1.invoke(() -> doMultiUserContainsKeys(1, 2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, new boolean[] {true, 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}});
+ if (isMultiUser) {
+ client2.invoke(() -> doMultiUserDestroys(2, 2, new int[] {NO_EXCEPTION, 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}});
+ int expectedResult = (opAllowed) ? NO_EXCEPTION : NOTAUTHZ_EXCEPTION;
+ client2.invoke(() -> doMultiUserDestroys(1, 1, new int[] {expectedResult}));
}
}
@@ -273,249 +305,41 @@ public class ClientMultiUserAuthzDUnitTest extends ClientAuthorizationTestBase {
verifyContainsKeyInvalidates(true, false /* unused */);
}
- private void verifyContainsKeyInvalidates(Boolean isMultiuser, Boolean opAllowed)
- throws Exception {
+ private void verifyContainsKeyInvalidates(final boolean isMultiUser, final 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}});
+ client1.invoke(() -> doMultiUserPuts(2, 2, new int[] {NO_EXCEPTION, NO_EXCEPTION}));
+ client1.invoke(() -> doMultiUserContainsKeys(1, 2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, new boolean[] {true, 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}});
+ if (isMultiUser) {
+ client2.invoke(() -> doMultiUserInvalidates(2, 2, new int[] {NO_EXCEPTION, 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}});
+ int expectedResult = (opAllowed) ? NO_EXCEPTION : NOTAUTHZ_EXCEPTION;
+ client2.invoke(() -> doMultiUserInvalidates(1, 1, new int[] {expectedResult}));
}
}
private void verifyGetAllInTX() {
- server1.invoke(() -> ClientMultiUserAuthzDUnitTest.doPuts());
- client1.invoke(SecurityTestUtil.class, "doMultiUserGetAll", new Object[] {
- Integer.valueOf(2),
- new Integer[] {SecurityTestUtil.NO_EXCEPTION,
- SecurityTestUtil.NOTAUTHZ_EXCEPTION}, Boolean.TRUE/*use TX*/});
+ server1.invoke(() -> doPuts());
+ client1.invoke(() -> doMultiUserGetAll(2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}, true/*use TX*/));
}
private void verifyGetAllRegionDestroys() {
- server1.invoke(() -> ClientMultiUserAuthzDUnitTest.doPuts());
- client1.invoke(SecurityTestUtil.class, "doMultiUserGetAll", new Object[] {
- Integer.valueOf(2),
- new Integer[] {SecurityTestUtil.NO_EXCEPTION,
- SecurityTestUtil.NOTAUTHZ_EXCEPTION}});
+ server1.invoke(() -> doPuts());
+ client1.invoke(() -> doMultiUserGetAll(2, new int[] {NO_EXCEPTION, 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}});
+ client2.invoke(() -> doMultiUserRegionDestroys(2, new int[] {NO_EXCEPTION, NOTAUTHZ_EXCEPTION}));
}
- public static void doPuts() {
- Region region = GemFireCacheImpl.getInstance().getRegion(SecurityTestUtil.regionName);
+ private void doPuts() {
+ Region region = GemFireCacheImpl.getInstance().getRegion(REGION_NAME);
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();
-
- LogWriterUtils.getLogWriter().info("testOps2: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info("testOps2: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testOps2: Using accessor: " + accessor);
-
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- Integer port1 = createCacheServerOnVM(server1, javaProps, serverProps);
- Integer port2 = createCacheServerOnVM(server2, javaProps, serverProps);
-
- // 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();
- LogWriterUtils.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();
- LogWriterUtils.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.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});
-
-
- }
-
-
- protected Integer createCacheServerOnVM(VM server, Properties javaProps, Properties serverProps) {
- return (Integer)server.invoke(() -> ClientAuthorizationTestBase.createCacheServer(SecurityTestUtil.getLocatorPort(), serverProps,
- javaProps));
-
- }
-
- 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();
-
- LogWriterUtils.getLogWriter().info("testOpsWithClientsInDifferentModes: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testOpsWithClientsInDifferentModes: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testOpsWithClientsInDifferentModes: Using accessor: " + accessor);
-
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- Integer port1 = createCacheServerOnVM(server1, javaProps, serverProps);
- Integer port2 = createCacheServerOnVM(server2, javaProps, serverProps);
-
- 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
-
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- SecurityTestUtil.closeCache();
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ private int createCacheServerOnVM(final VM server, final Properties javaProps, final Properties serverProps) {
+ return server.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), serverProps, javaProps));
}
}
[11/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
GEODE-693: refactor security dunit tests
* GEODE-1114: remove com.gemstone.gemfire.internal.util.Callable
* convert security dunit tests to JUnit 4
* use RetryRule on ClientPostAuthorizationDUnitTest.testAllPostOps
* convert public variables and methods to private and/or protected
* convert many static variables and methods to instance
Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/22ca5ef8
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/22ca5ef8
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/22ca5ef8
Branch: refs/heads/develop
Commit: 22ca5ef829fee20024d44264b3839ee745916975
Parents: 48af841
Author: Kirk Lund <kl...@pivotal.io>
Authored: Wed Mar 30 15:13:17 2016 -0700
Committer: Kirk Lund <kl...@pivotal.io>
Committed: Wed Mar 30 15:25:52 2016 -0700
----------------------------------------------------------------------
.../gemfire/internal/cache/EntriesMap.java | 5 +-
.../gemfire/internal/util/Callable.java | 47 -
.../cli/ClasspathScanLoadHelperJUnitTest.java | 85 +-
.../security/ClientAuthenticationDUnitTest.java | 889 +-------
.../ClientAuthenticationPart2DUnitTest.java | 96 +-
.../security/ClientAuthenticationTestCase.java | 590 ++++++
.../security/ClientAuthenticationTestUtils.java | 93 +
.../security/ClientAuthorizationDUnitTest.java | 1094 +++++-----
.../security/ClientAuthorizationTestBase.java | 1381 -------------
.../security/ClientAuthorizationTestCase.java | 1323 ++++++++++++
.../security/ClientMultiUserAuthzDUnitTest.java | 590 ++----
.../DeltaClientAuthorizationDUnitTest.java | 396 ++--
.../DeltaClientPostAuthorizationDUnitTest.java | 614 ++----
.../security/P2PAuthenticationDUnitTest.java | 667 +++---
.../gemfire/security/SecurityTestUtil.java | 1918 ------------------
.../gemfire/security/SecurityTestUtils.java | 1683 +++++++++++++++
.../ClientAuthorizationTwoDUnitTest.java | 223 +-
.../security/ClientAuthzObjectModDUnitTest.java | 466 ++---
.../ClientCQPostAuthorizationDUnitTest.java | 449 ++--
.../ClientPostAuthorizationDUnitTest.java | 461 ++---
.../gemfire/security/MultiUserAPIDUnitTest.java | 314 +++
.../MultiUserDurableCQAuthzDUnitTest.java | 387 ++++
.../gemfire/security/MultiuserAPIDUnitTest.java | 381 ----
.../MultiuserDurableCQAuthzDUnitTest.java | 475 -----
24 files changed, 6371 insertions(+), 8256 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/EntriesMap.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/EntriesMap.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/EntriesMap.java
index 74697ea..257458f 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/EntriesMap.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/EntriesMap.java
@@ -20,10 +20,9 @@ package com.gemstone.gemfire.internal.cache;
import java.util.*;
import com.gemstone.gemfire.cache.*;
import com.gemstone.gemfire.internal.InternalStatisticsDisabledException;
-import com.gemstone.gemfire.internal.util.Callable;
-//import com.gemstone.gemfire.util.concurrent.ConcurrentMap;
+
+import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
-//import com.gemstone.gemfire.util.concurrent.locks.*;
import com.gemstone.gemfire.distributed.internal.DM;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/main/java/com/gemstone/gemfire/internal/util/Callable.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/util/Callable.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/util/Callable.java
deleted file mode 100755
index 7799224..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/util/Callable.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain. Use, modify, and
- * redistribute this code in any way without acknowledgement.
- */
-
-package com.gemstone.gemfire.internal.util;
-
-/**
- * A task that returns a result and may throw an exception.
- * Implementors define a single method with no arguments called
- * <tt>call</tt>.
- *
- * <p>The <tt>Callable</tt> interface is similar to {@link
- * java.lang.Runnable}, in that both are designed for classes whose
- * instances are potentially executed by another thread. A
- * <tt>Runnable</tt>, however, does not return a result and cannot
- * throw a checked exception.
- *
- *
- * @version based on JSR166 Callable version 1.6.
- */
-public interface Callable {
- /**
- * Computes a result, or throws an exception if unable to do so.
- *
- * @return computed result
- * @throws Exception if unable to compute a result
- */
- Object call() throws Exception;
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/management/internal/cli/ClasspathScanLoadHelperJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/management/internal/cli/ClasspathScanLoadHelperJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/management/internal/cli/ClasspathScanLoadHelperJUnitTest.java
index 4476cd6..79a0f09 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/management/internal/cli/ClasspathScanLoadHelperJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/management/internal/cli/ClasspathScanLoadHelperJUnitTest.java
@@ -16,14 +16,12 @@
*/
package com.gemstone.gemfire.management.internal.cli;
+import static org.junit.Assert.*;
+
import java.io.IOException;
import java.util.Set;
-import org.junit.experimental.categories.Category;
-
-import junit.framework.TestCase;
-
-import com.gemstone.gemfire.internal.util.Callable;
+import com.gemstone.gemfire.internal.util.Versionable;
import com.gemstone.gemfire.management.internal.cli.domain.AbstractImpl;
import com.gemstone.gemfire.management.internal.cli.domain.Impl1;
import com.gemstone.gemfire.management.internal.cli.domain.Impl12;
@@ -31,61 +29,52 @@ import com.gemstone.gemfire.management.internal.cli.domain.Interface1;
import com.gemstone.gemfire.management.internal.cli.domain.Interface2;
import com.gemstone.gemfire.management.internal.cli.util.ClasspathScanLoadHelper;
import com.gemstone.gemfire.test.junit.categories.UnitTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
-/**
- */
@Category(UnitTest.class)
-public class ClasspathScanLoadHelperJUnitTest extends TestCase{
+public class ClasspathScanLoadHelperJUnitTest {
private static final String PACKAGE_NAME = "com.gemstone.gemfire.management.internal.cli.domain";
private static final String WRONG_PACKAGE_NAME = "com.gemstone.gemfire.management.internal.cli.domain1";
private static final Class<?> INTERFACE1 = Interface1.class;
- private static final Class<?> NO_IMPL_INTERFACE = Callable.class;
+ private static final Class<?> NO_IMPL_INTERFACE = Versionable.class;
private static final Class<?> INTERFACE2 = Interface2.class;
private static final Class<?> IMPL1 = Impl1.class;
private static final Class<?> IMPL2 = Impl12.class;
private static final Class<?> ABSTRACT_IMPL = AbstractImpl.class;
+ @Test
+ public void testLoadAndGet() throws Exception {
+ Set<Class<?>> classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE1, true);
+ assertEquals(2, classLoaded.size());
+ assertTrue(classLoaded.contains(IMPL1));
+ assertTrue(classLoaded.contains(IMPL2));
+ //impl1 and impl12
+
+ classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE1, false);
+ assertEquals(4, classLoaded.size());
+ assertTrue(classLoaded.contains(IMPL1));
+ assertTrue(classLoaded.contains(IMPL2));
+ assertTrue(classLoaded.contains(ABSTRACT_IMPL));
+ assertTrue(classLoaded.contains(INTERFACE1));
+
+ classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE2, false);
+ assertEquals(2, classLoaded.size());
+ assertTrue(classLoaded.contains(IMPL2));
+ assertTrue(classLoaded.contains(INTERFACE2));
+
+ classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE2, true);
+ assertEquals(1, classLoaded.size());
+ assertTrue(classLoaded.contains(IMPL2));
+
+ classLoaded = ClasspathScanLoadHelper.loadAndGet(WRONG_PACKAGE_NAME, INTERFACE2, true);
+ assertEquals(0, classLoaded.size());
- public void testloadAndGet(){
+ classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, NO_IMPL_INTERFACE, true);
+ assertEquals(0, classLoaded.size());
- try {
- Set<Class<?>> classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE1, true);
- assertEquals(2, classLoaded.size());
- assertTrue(classLoaded.contains(IMPL1));
- assertTrue(classLoaded.contains(IMPL2));
- //impl1 and impl12
-
- classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE1, false);
- assertEquals(4, classLoaded.size());
- assertTrue(classLoaded.contains(IMPL1));
- assertTrue(classLoaded.contains(IMPL2));
- assertTrue(classLoaded.contains(ABSTRACT_IMPL));
- assertTrue(classLoaded.contains(INTERFACE1));
-
- classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE2, false);
- assertEquals(2, classLoaded.size());
- assertTrue(classLoaded.contains(IMPL2));
- assertTrue(classLoaded.contains(INTERFACE2));
-
- classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, INTERFACE2, true);
- assertEquals(1, classLoaded.size());
- assertTrue(classLoaded.contains(IMPL2));
-
- classLoaded = ClasspathScanLoadHelper.loadAndGet(WRONG_PACKAGE_NAME, INTERFACE2, true);
- assertEquals(0, classLoaded.size());
-
- classLoaded = ClasspathScanLoadHelper.loadAndGet(PACKAGE_NAME, NO_IMPL_INTERFACE, true);
- assertEquals(0, classLoaded.size());
-
- classLoaded = ClasspathScanLoadHelper.loadAndGet(WRONG_PACKAGE_NAME, NO_IMPL_INTERFACE, true);
- assertEquals(0, classLoaded.size());
-
-
- } catch (ClassNotFoundException e) {
- fail("Error loading class" + e);
- } catch (IOException e) {
- fail("Error loading class" + e);
- }
+ classLoaded = ClasspathScanLoadHelper.loadAndGet(WRONG_PACKAGE_NAME, NO_IMPL_INTERFACE, true);
+ assertEquals(0, classLoaded.size());
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
index 8741f58..ea83a66 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationDUnitTest.java
@@ -18,25 +18,10 @@
*/
package com.gemstone.gemfire.security;
-import java.io.IOException;
-import java.util.Properties;
-
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
-import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.security.generator.CredentialGenerator.ClassCode;
-
-import com.gemstone.gemfire.cache.Region;
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.AvailablePort;
-import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
-import com.gemstone.gemfire.test.dunit.DistributedTestCase;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.IgnoredException;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
-import com.gemstone.gemfire.test.dunit.VM;
-import com.gemstone.gemfire.test.dunit.Wait;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* Test for authentication from client to server. This tests for both valid and
@@ -45,857 +30,57 @@ import com.gemstone.gemfire.test.dunit.Wait;
*
* @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 final void postSetUp() throws Exception {
- final Host host = Host.getHost(0);
- server1 = host.getVM(0);
- server2 = host.getVM(1);
- client1 = host.getVM(2);
- client2 = host.getVM(3);
-
- IgnoredException.addIgnoredException("Connection refused: connect");
-
- server1.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client1.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( 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) {
+@Category(DistributedTest.class)
+public class ClientAuthenticationDUnitTest extends ClientAuthenticationTestCase {
- 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));
+ @Test
+ public void testValidCredentials() throws Exception {
+ doTestValidCredentials(false);
}
- 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);
+ @Test
+ public void testNoCredentials() throws Exception {
+ doTestNoCredentials(false);
}
- 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);
+ @Test
+ public void testInvalidCredentials() throws Exception {
+ doTestInvalidCredentials(false);
}
- 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);
+ @Test
+ public void testInvalidAuthInit() throws Exception {
+ doTestInvalidAuthInit(false);
}
- 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);
+ @Test
+ public void testNoAuthInitWithCredentials() throws Exception {
+ doTestNoAuthInitWithCredentials(false);
}
- public static void registerAllInterest() {
-
- Region region = SecurityTestUtil.getCache().getRegion(
- SecurityTestUtil.regionName);
- assertNotNull(region);
- region.registerInterestRegex(".*");
+ @Test
+ public void testInvalidAuthenticator() throws Exception {
+ doTestInvalidAuthenticator(false);
}
- // 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();
-
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: Using authenticator: " + authenticator);
- LogWriterUtils.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.createCacheServer( locPort1, locString, authenticator, extraProps,
- javaProps ));
- Integer port2 = (Integer)server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, authenticator, extraProps,
- javaProps ));
-
- // Start the clients with valid credentials
- Properties credentials1 = gen.getValidCredentials(1);
- Properties javaProps1 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: For first client credentials: " + credentials1
- + " : " + javaProps1);
- Properties credentials2 = gen.getValidCredentials(2);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testValidCredentials: For second client credentials: "
- + credentials2 + " : " + javaProps2);
- createClientsNoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1, credentials2, javaProps2);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( new Integer(2) ));
-
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doGets( new Integer(2) ));
-
- if (multiUser) {
- client1.invoke(() -> SecurityTestUtil.doProxyCacheClose());
- client2.invoke(() -> SecurityTestUtil.doProxyCacheClose());
- client1.invoke(() -> SecurityTestUtil.doSimplePut("CacheClosedException"));
- client2.invoke(() -> SecurityTestUtil.doSimpleGet("CacheClosedException"));
- }
+ @Test
+ public void testNoAuthenticatorWithCredentials() throws Exception {
+ doTestNoAuthenticatorWithCredentials(false);
}
- public void testNoCredentials() {
- itestNoCredentials(Boolean.FALSE);
+ @Test
+ public void testCredentialsWithFailover() throws Exception {
+ doTestCredentialsWithFailover(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();
-
- LogWriterUtils.getLogWriter()
- .info("testNoCredentials: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testNoCredentials: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testNoCredentials: Using authinit: " + authInit);
-
- // Start the servers
- Integer locPort1 = SecurityTestUtil.getLocatorPort();
- Integer locPort2 = SecurityTestUtil.getLocatorPort();
- String locString = SecurityTestUtil.getLocatorString();
- Integer port1 = createServer1(extraProps, javaProps, authenticator,
- locPort1, locString);
- Integer port2 = ((Integer)server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, authenticator, extraProps,
- javaProps )));
-
- // Start first client with valid credentials
- Properties credentials1 = gen.getValidCredentials(1);
- Properties javaProps1 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testNoCredentials: For first client credentials: " + credentials1
- + " : " + javaProps1);
- createClient1NoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( 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.createCacheClient( null, null, null, port1, port2, null, multiUser,
- new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- client2.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.OTHER_EXCEPTION) ));
- }
- else {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( 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();
-
- LogWriterUtils.getLogWriter().info(
- "testInvalidCredentials: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testInvalidCredentials: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter()
- .info("testInvalidCredentials: Using authinit: " + authInit);
-
- // Start the servers
- Integer locPort1 = SecurityTestUtil.getLocatorPort();
- Integer locPort2 = SecurityTestUtil.getLocatorPort();
- String locString = SecurityTestUtil.getLocatorString();
- Integer port1 = createServer1(extraProps, javaProps, authenticator,
- locPort1, locString);
- Integer port2 = ((Integer)server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, authenticator, extraProps,
- javaProps )));
-
- // Start first client with valid credentials
- Properties credentials1 = gen.getValidCredentials(1);
- Properties javaProps1 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testInvalidCredentials: For first client credentials: "
- + credentials1 + " : " + javaProps1);
- createClient1NoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( 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();
- LogWriterUtils.getLogWriter().info(
- "testInvalidCredentials: For second client credentials: "
- + credentials2 + " : " + javaProps2);
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( 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();
-
- LogWriterUtils.getLogWriter().info(
- "testInvalidAuthInit: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testInvalidAuthInit: Using authenticator: " + authenticator);
-
- // Start the server
- Integer locPort1 = SecurityTestUtil.getLocatorPort();
- String locString = SecurityTestUtil.getLocatorString();
- Integer port1 = createServer1(extraProps, javaProps, authenticator,
- locPort1, locString);
-
- Properties credentials = gen.getValidCredentials(1);
- javaProps = gen.getJavaProperties();
- LogWriterUtils.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) });
- }
-
- protected Integer createServer1(Properties extraProps, Properties javaProps,
- String authenticator, Integer locPort1, String locString) {
- Integer port1 = ((Integer)server1.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort1, locString, authenticator, extraProps,
- javaProps )));
- return port1;
- }
-
- 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();
-
-
- LogWriterUtils.getLogWriter().info(
- "testNoAuthInitWithCredentials: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testNoAuthInitWithCredentials: Using authenticator: "
- + authenticator);
-
- // Start the servers
- Integer locPort1 = SecurityTestUtil.getLocatorPort();
- Integer locPort2 = SecurityTestUtil.getLocatorPort();
- String locString = SecurityTestUtil.getLocatorString();
- Integer port1 = createServer1(extraProps, javaProps, authenticator,
- locPort1, locString);
- Integer port2 = ((Integer)server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, authenticator, extraProps,
- javaProps )));
-
- // Start the clients with valid credentials
- Properties credentials1 = gen.getValidCredentials(1);
- Properties javaProps1 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testNoAuthInitWithCredentials: For first client credentials: "
- + credentials1 + " : " + javaProps1);
- Properties credentials2 = gen.getValidCredentials(2);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testNoAuthInitWithCredentials: For second client credentials: "
- + credentials2 + " : " + javaProps2);
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( null, credentials1, javaProps1, port1, port2, null,
- multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) ));
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( null, credentials2, javaProps2, port1, port2, null,
- multiUser, new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) ));
- client2.invoke(() -> SecurityTestUtil.closeCache());
-
-
- // Now also try with invalid credentials
- Properties credentials3 = gen.getInvalidCredentials(5);
- Properties javaProps3 = gen.getJavaProperties();
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( null, credentials3, javaProps3, 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();
-
- LogWriterUtils.getLogWriter().info(
- "testInvalidAuthenticator: Using scheme: " + gen.classCode());
- LogWriterUtils.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.createCacheServer( locPort1, locString, "com.gemstone.gemfire.none",
- extraProps, javaProps ));
-
- // Trying to create the region on client should throw a security exception
- Properties credentials2 = gen.getValidCredentials(1);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testInvalidAuthenticator: For first client credentials: "
- + credentials2 + " : " + javaProps2);
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials2, javaProps2, port1, null,
- new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) ));
- client1.invoke(() -> SecurityTestUtil.closeCache());
-
-
- // Also test with invalid credentials
- Properties credentials3 = gen.getInvalidCredentials(1);
- Properties javaProps3 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testInvalidAuthenticator: For first client credentials: "
- + credentials3 + " : " + javaProps3);
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials3, javaProps3, 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();
-
- LogWriterUtils.getLogWriter().info(
- "testNoAuthenticatorWithCredentials: Using scheme: "
- + gen.classCode());
- LogWriterUtils.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.createCacheServer( locPort1, locString, null, extraProps, javaProps ));
- Integer port2 = (Integer)server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( 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();
- LogWriterUtils.getLogWriter().info(
- "testNoAuthenticatorWithCredentials: For first client credentials: "
- + credentials1 + " : " + javaProps1);
- Properties credentials2 = gen.getInvalidCredentials(5);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testNoAuthenticatorWithCredentials: For second client credentials: "
- + credentials2 + " : " + javaProps2);
- createClientsNoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1, credentials2, javaProps2);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( new Integer(2) ));
-
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doGets( 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();
-
- LogWriterUtils.getLogWriter().info(
- "testCredentialsWithFailover: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testCredentialsWithFailover: Using authenticator: " + authenticator);
- LogWriterUtils.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.createCacheServer( 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();
- LogWriterUtils.getLogWriter().info(
- "testCredentialsWithFailover: For first client credentials: "
- + credentials1 + " : " + javaProps1);
- Properties credentials2 = gen.getValidCredentials(6);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testCredentialsWithFailover: For second client credentials: "
- + credentials2 + " : " + javaProps2);
- createClientsNoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1, credentials2, javaProps2);
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( new Integer(2) ));
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doGets( new Integer(2) ));
-
- // start the second one and stop the first server to force a failover
- server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, port2, authenticator, extraProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.closeCache());
-
- // Perform some create/update operations from client1
- client1.invoke(() -> SecurityTestUtil.doNPuts( new Integer(4) ));
- // Verify that the creates/updates succeeded
- client2.invoke(() -> SecurityTestUtil.doNGets( 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.createCacheClient( null, null, null, port1, port2, null, multiUser,
- new Integer(SecurityTestUtil.NOFORCE_AUTHREQ_EXCEPTION) ));
- client2.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.OTHER_EXCEPTION) ));
- }
- else {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( 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
- Properties credentials3 = gen.getInvalidCredentials(7);
- Properties javaProps3 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testCredentialsWithFailover: For first client invalid credentials: "
- + credentials3 + " : " + javaProps3);
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials3, javaProps3, port1, port2,
- null, multiUser, new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) ));
-
- if (multiUser) {
- client1.invoke(() -> SecurityTestUtil.doProxyCacheClose());
- client2.invoke(() -> SecurityTestUtil.doProxyCacheClose());
- client1.invoke(() -> SecurityTestUtil.doSimplePut("CacheClosedException"));
- client2.invoke(() -> SecurityTestUtil.doSimpleGet("CacheClosedException"));
- }
- }
-
- protected void createClientsNoException(Boolean multiUser, String authInit,
- Integer port1, Integer port2, Properties credentials1,
- Properties javaProps1, Properties credentials2, Properties javaProps2) {
- createClient1NoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1);
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials2, javaProps2, port1, port2,
- null, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- }
-
- 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();
-
- LogWriterUtils.getLogWriter().info(
- "testCredentialsForNotifications: Using scheme: " + gen.classCode());
- LogWriterUtils.getLogWriter().info(
- "testCredentialsForNotifications: Using authenticator: "
- + authenticator);
- LogWriterUtils.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.createCacheServer( 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();
- LogWriterUtils.getLogWriter().info(
- "testCredentialsForNotifications: For first client credentials: "
- + credentials1 + " : " + javaProps1);
- Properties credentials2 = gen.getValidCredentials(4);
- Properties javaProps2 = gen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testCredentialsForNotifications: For second client credentials: "
- + credentials2 + " : " + javaProps2);
- createClient1NoException(multiUser, authInit, port1, port2, credentials1,
- javaProps1);
- // Set up zero forward connections to check notification handshake only
- Object zeroConns = new Integer(0);
- createClient2NoException(multiUser, authInit, port1, port2, credentials2,
- javaProps2, zeroConns);
-
- // Register interest on all keys on second client
- client2
- .invoke(() -> ClientAuthenticationDUnitTest.registerAllInterest());
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( new Integer(2) ));
-
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doLocalGets( new Integer(2) ));
-
- // start the second one and stop the first server to force a failover
- server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, port2, authenticator, extraProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.closeCache());
-
- // Wait for failover to complete
- Wait.pause(500);
-
- // Perform some create/update operations from client1
- client1.invoke(() -> SecurityTestUtil.doNPuts( new Integer(4) ));
- // Verify that the creates/updates succeeded
- client2.invoke(() -> SecurityTestUtil.doNLocalGets( new Integer(4) ));
-
- // Try to connect client1 with no credentials
- // Verify that the creation of region throws security exception
- server1.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( 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.createCacheClient( null, null, null, port1, port2,
- zeroConns, multiUser,
- new Integer(SecurityTestUtil.NOFORCE_AUTHREQ_EXCEPTION) ));
- client1.invoke(() -> SecurityTestUtil.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.OTHER_EXCEPTION) ));
- }
- else {
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( 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();
- LogWriterUtils.getLogWriter().info(
- "testCredentialsForNotifications: For second client invalid credentials: "
- + credentials2 + " : " + javaProps2);
- createClient2WithException(multiUser, authInit, port1, port2,
- credentials2, javaProps2, zeroConns);
-
- // 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.createCacheClient( "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.createCacheServer( locPort1, locString, port1,
- "com.gemstone.gemfire.none", extraProps, javaProps ));
- server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, port2,
- "com.gemstone.gemfire.none", extraProps, javaProps ));
-
- createClient2WithException(multiUser, authInit, port1, port2,
- credentials1, javaProps1, zeroConns);
- createClient1WithException(multiUser, authInit, port1, port2,
- credentials2, javaProps2, zeroConns);
- }
- else {
- LogWriterUtils.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.createCacheServer( locPort1, locString, port1,
- authenticator, extraProps, javaProps ));
- server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, port2,
- authenticator, extraProps, javaProps ));
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( null, credentials1, javaProps1,
- port1, port2, null, multiUser,
- new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) ));
- createClient2AuthReqException(multiUser, port1, port2, credentials2,
- javaProps2, zeroConns);
-
- createClient2AuthReqException(multiUser, port1, port2, credentials2,
- javaProps2, zeroConns);
- }
- else {
- LogWriterUtils.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.createCacheServer( locPort1, locString, port1,
- null, extraProps, javaProps ));
- server2.invoke(() -> ClientAuthenticationDUnitTest.createCacheServer( locPort2, locString, port2,
- null, extraProps, javaProps ));
- createClient1NoException(multiUser, authInit, port1, port2,
- credentials1, javaProps1);
- createClient2NoException(multiUser, authInit, port1, port2,
- credentials2, javaProps2, zeroConns);
-
- // Register interest on all keys on second client
- client2.invoke(() -> ClientAuthenticationDUnitTest.registerAllInterest());
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doPuts( new Integer(4) ));
-
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doLocalGets( new Integer(4) ));
-
- // Now also try with valid credentials on client2
- createClient1NoException(multiUser, authInit, port1, port2,
- credentials2, javaProps2);
- createClient2NoException(multiUser, authInit, port1, port2,
- credentials1, javaProps1, zeroConns);
-
- // Register interest on all keys on second client
- client2.invoke(() -> ClientAuthenticationDUnitTest.registerAllInterest());
-
- // Perform some put operations from client1
- client1.invoke(() -> SecurityTestUtil.doNPuts( new Integer(4) ));
-
- // Verify that the puts succeeded
- client2.invoke(() -> SecurityTestUtil.doNLocalGets( new Integer(4) ));
- }
- else {
- LogWriterUtils.getLogWriter().info(
- "testCredentialsForNotifications: Skipping scheme ["
- + gen.classCode() + "] which has no authenticator");
- }
- }
-
- protected void createClient1NoException(Boolean multiUser, String authInit,
- Integer port1, Integer port2, Properties credentials2,
- Properties javaProps2) {
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials2,
- javaProps2, port1, port2, null, multiUser,
- new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- }
-
- protected void createClient2AuthReqException(Boolean multiUser, Integer port1,
- Integer port2, Properties credentials2, Properties javaProps2,
- Object zeroConns) {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( null, credentials2, javaProps2,
- port1, port2, zeroConns, multiUser,
- new Integer(SecurityTestUtil.AUTHREQ_EXCEPTION) ));
- }
-
- protected void createClient1WithException(Boolean multiUser, String authInit,
- Integer port1, Integer port2, Properties credentials2,
- Properties javaProps2, Object zeroConns) {
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials2,
- javaProps2, port1, port2, zeroConns, multiUser,
- new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) ));
- }
-
- protected void createClient2WithException(Boolean multiUser, String authInit,
- Integer port1, Integer port2, Properties credentials2,
- Properties javaProps2, Object zeroConns) {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials2, javaProps2, port1, port2,
- zeroConns, multiUser, new Integer(SecurityTestUtil.AUTHFAIL_EXCEPTION) ));
- }
-
- protected void createClient2NoException(Boolean multiUser, String authInit,
- Integer port1, Integer port2, Properties credentials2,
- Properties javaProps2, Object zeroConns) {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, credentials2, javaProps2, port1, port2,
- zeroConns, multiUser, new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- }
-
- //////////////////////////////////////////////////////////////////////////////
- // Tests for MULTI_USER_MODE start here
- //////////////////////////////////////////////////////////////////////////////
-
- public void xtestValidCredentialsForMultipleUsers() {
- itestValidCredentials(Boolean.TRUE);
+ @Test
+ public void testCredentialsForNotifications() throws Exception {
+ doTestCredentialsForNotifications(false);
}
- //////////////////////////////////////////////////////////////////////////////
- // Tests for MULTI_USER_MODE end here
- //////////////////////////////////////////////////////////////////////////////
-
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ @Ignore("Disabled for unknown reason")
+ @Test
+ public void testValidCredentialsForMultipleUsers() throws Exception {
+ doTestValidCredentials(true);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
index 138114a..b633865 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationPart2DUnitTest.java
@@ -1,6 +1,3 @@
-
-package com.gemstone.gemfire.security;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,9 +6,9 @@ package com.gemstone.gemfire.security;
* 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
@@ -19,70 +16,59 @@ package com.gemstone.gemfire.security;
* specific language governing permissions and limitations
* under the License.
*/
+package com.gemstone.gemfire.security;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* 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 {
+@Category(DistributedTest.class)
+public class ClientAuthenticationPart2DUnitTest extends ClientAuthenticationTestCase {
- /** constructor */
- public ClientAuthenticationPart2DUnitTest(String name) {
- super(name);
+ @Test
+ public void testNoCredentialsForMultipleUsers() throws Exception {
+ doTestNoCredentials(true);
}
- // 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);
+ @Test
+ public void testInvalidCredentialsForMultipleUsers() throws Exception {
+ doTestInvalidCredentials(true);
}
- public void testInvalidAuthInitForMultipleUsers() {
- itestInvalidAuthInit(Boolean.TRUE);
- }
- public void testNoAuthInitWithCredentialsForMultipleUsers() {
- itestNoAuthInitWithCredentials(Boolean.TRUE);
+
+ @Test
+ public void testInvalidAuthInitForMultipleUsers() throws Exception {
+ doTestInvalidAuthInit(true);
}
- public void testInvalidAuthenitcatorForMultipleUsers() {
- itestInvalidAuthenticator(Boolean.TRUE);
+
+ @Test
+ public void testNoAuthInitWithCredentialsForMultipleUsers() throws Exception {
+ doTestNoAuthInitWithCredentials(true);
}
- public void testNoAuthenticatorWithCredentialsForMultipleUsers() {
- itestNoAuthenticatorWithCredentials(Boolean.TRUE);
+
+ @Test
+ public void testInvalidAuthenitcatorForMultipleUsers() throws Exception {
+ doTestInvalidAuthenticator(true);
}
- public void disabled_testCredentialsWithFailoverForMultipleUsers() {
- itestCredentialsWithFailover(Boolean.TRUE);
+
+ @Test
+ public void testNoAuthenticatorWithCredentialsForMultipleUsers() throws Exception {
+ doTestNoAuthenticatorWithCredentials(true);
}
- public void __testCredentialsForNotificationsForMultipleUsers() {
- itestCredentialsForNotifications(Boolean.TRUE);
+
+ @Ignore("Disabled for unknown reason")
+ @Test
+ public void testCredentialsWithFailoverForMultipleUsers() throws Exception {
+ doTestCredentialsWithFailover(true);
}
+ @Ignore("Disabled for unknown reason")
+ @Test
+ public void testCredentialsForNotificationsForMultipleUsers() throws Exception {
+ doTestCredentialsForNotifications(true);
+ }
}
[10/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestCase.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestCase.java
new file mode 100644
index 0000000..191ea3e
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestCase.java
@@ -0,0 +1,590 @@
+/*
+ * 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.
+ */
+package com.gemstone.gemfire.security;
+
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.ClientAuthenticationTestUtils.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.IgnoredException.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
+import static com.gemstone.gemfire.test.dunit.Wait.*;
+
+import java.io.IOException;
+import java.util.Properties;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.SSLHandshakeException;
+
+import com.gemstone.gemfire.security.generator.CredentialGenerator;
+import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
+import com.gemstone.gemfire.test.dunit.Host;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.dunit.internal.JUnit4DistributedTestCase;
+
+public abstract class ClientAuthenticationTestCase extends JUnit4DistributedTestCase {
+
+ private VM server1 = null;
+ private VM server2 = null;
+ private VM client1 = null;
+ private VM client2 = null;
+
+ private static final String[] serverIgnoredExceptions = {
+ 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[] clientIgnoredExceptions = {
+ AuthenticationRequiredException.class.getName(),
+ AuthenticationFailedException.class.getName(),
+ SSLHandshakeException.class.getName()
+ };
+
+ @Override
+ public final void postSetUp() throws Exception {
+ final Host host = Host.getHost(0);
+ server1 = host.getVM(0);
+ server2 = host.getVM(1);
+ client1 = host.getVM(2);
+ client2 = host.getVM(3);
+
+ addIgnoredException("Connection refused: connect");
+
+ server1.invoke(() -> registerExpectedExceptions(serverIgnoredExceptions));
+ server2.invoke(() -> registerExpectedExceptions(serverIgnoredExceptions));
+ client1.invoke(() -> registerExpectedExceptions(clientIgnoredExceptions));
+ client2.invoke(() -> registerExpectedExceptions(clientIgnoredExceptions));
+ }
+
+ protected void doTestValidCredentials(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = server1.invoke(() -> createCacheServer(locPort1, locString, authenticator, extraProps, javaProps));
+ int port2 = server2.invoke(() -> createCacheServer(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);
+
+ createClientsNoException(multiUser, authInit, port1, port2, credentials1, javaProps1, credentials2, javaProps2);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doGets(2));
+
+ if (multiUser) {
+ client1.invoke(() -> doProxyCacheClose());
+ client2.invoke(() -> doProxyCacheClose());
+ client1.invoke(() -> doSimplePut("CacheClosedException"));
+ client2.invoke(() -> doSimpleGet("CacheClosedException"));
+ }
+ }
+
+ protected void doTestNoCredentials(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = createServer1(extraProps, javaProps, authenticator, locPort1, locString);
+ int port2 = server2.invoke(() -> createCacheServer(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);
+
+ createClient1NoException(multiUser, authInit, port1, port2, credentials1, javaProps1);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2));
+
+ // Trying to create the region on client2
+ if (gen.classCode().equals(CredentialGenerator.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(() -> createCacheClient(null, null, null, port1, port2, 0, multiUser, NO_EXCEPTION));
+ client2.invoke(() -> doPuts(2, OTHER_EXCEPTION));
+
+ } else {
+ client2.invoke(() -> createCacheClient(null, null, null, port1, port2, 0, multiUser, AUTHREQ_EXCEPTION));
+ }
+ }
+
+ protected void doTestInvalidCredentials(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = createServer1(extraProps, javaProps, authenticator, locPort1, locString);
+ int port2 = server2.invoke(() -> createCacheServer(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);
+
+ createClient1NoException(multiUser, authInit, port1, port2, credentials1, javaProps1);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(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(() -> createCacheClient(authInit, credentials2, javaProps2, port1, port2, 0, multiUser, AUTHFAIL_EXCEPTION));
+ }
+
+ protected void doTestInvalidAuthInit(final boolean multiUser) throws Exception {
+ CredentialGenerator gen = new DummyCredentialGenerator();
+ Properties extraProps = gen.getSystemProperties();
+ final Properties javaProps = gen.getJavaProperties();
+ String authenticator = gen.getAuthenticator();
+
+ getLogWriter().info("testInvalidAuthInit: Using scheme: " + gen.classCode());
+ getLogWriter().info("testInvalidAuthInit: Using authenticator: " + authenticator);
+
+ // Start the server
+ int locPort1 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = createServer1(extraProps, javaProps, authenticator, locPort1, locString);
+ Properties credentials = gen.getValidCredentials(1);
+ getLogWriter().info("testInvalidAuthInit: For first client credentials: " + credentials + " : " + javaProps);
+
+ client1.invoke(() -> createCacheClient("com.gemstone.none", credentials, javaProps, new int[] { port1 }, 0, false, multiUser, true, AUTHREQ_EXCEPTION));
+ }
+
+ protected void doTestNoAuthInitWithCredentials(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = createServer1(extraProps, javaProps, authenticator, locPort1, locString);
+ int port2 = server2.invoke(() -> createCacheServer(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(() -> createCacheClient(null, credentials1, javaProps1, port1, port2, 0, multiUser, AUTHREQ_EXCEPTION));
+ client2.invoke(() -> createCacheClient(null, credentials2, javaProps2, port1, port2, 0, multiUser, AUTHREQ_EXCEPTION));
+ client2.invoke(() -> closeCache());
+
+ // Now also try with invalid credentials
+ Properties credentials3 = gen.getInvalidCredentials(5);
+ Properties javaProps3 = gen.getJavaProperties();
+
+ client2.invoke(() -> createCacheClient(null, credentials3, javaProps3, port1, port2, 0, multiUser, AUTHREQ_EXCEPTION));
+ }
+
+ /**
+ * NOTE: "final boolean multiUser" is unused
+ */
+ protected void doTestInvalidAuthenticator(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = server1.invoke(() -> createCacheServer(locPort1, locString, "com.gemstone.gemfire.none", extraProps, javaProps));
+
+ // Trying to create the region on client should throw a security exception
+ Properties credentials2 = gen.getValidCredentials(1);
+ Properties javaProps2 = gen.getJavaProperties();
+ getLogWriter().info("testInvalidAuthenticator: For first client credentials: " + credentials2 + " : " + javaProps2);
+
+ client1.invoke(() -> createCacheClient(authInit, credentials2, javaProps2, port1, 0, AUTHFAIL_EXCEPTION));
+ client1.invoke(() -> closeCache());
+
+ // Also test with invalid credentials
+ Properties credentials3 = gen.getInvalidCredentials(1);
+ Properties javaProps3 = gen.getJavaProperties();
+ getLogWriter().info("testInvalidAuthenticator: For first client credentials: " + credentials3 + " : " + javaProps3);
+
+ client1.invoke(() -> createCacheClient(authInit, credentials3, javaProps3, port1, 0, AUTHFAIL_EXCEPTION));
+ }
+
+ protected void doTestNoAuthenticatorWithCredentials(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = server1.invoke(() -> createCacheServer(locPort1, locString, null, extraProps, javaProps));
+ int port2 = server2.invoke(() -> createCacheServer(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);
+
+ createClientsNoException(multiUser, authInit, port1, port2, credentials1, javaProps1, credentials2, javaProps2);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doGets(2));
+ }
+
+ protected void doTestCredentialsWithFailover(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = server1.invoke(() -> createCacheServer(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
+ int port2 = getRandomAvailablePort(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);
+
+ createClientsNoException(multiUser, authInit, port1, port2, credentials1, javaProps1, credentials2, javaProps2);
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2));
+ // Verify that the puts succeeded
+ client2.invoke(() -> doGets(2));
+
+ // start the second one and stop the first server to force a failover
+ server2.invoke(() -> createCacheServer(locPort2, locString, port2, authenticator, extraProps, javaProps));
+ server1.invoke(() -> closeCache());
+
+ // Perform some create/update operations from client1
+ client1.invoke(() -> doNPuts(4));
+ // Verify that the creates/updates succeeded
+ client2.invoke(() -> doNGets(4));
+
+ // Try to connect client2 with no credentials
+ // Verify that the creation of region throws security exception
+ if (gen.classCode().equals(CredentialGenerator.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(() -> createCacheClient(null, null, null, port1, port2, 0, multiUser, NOFORCE_AUTHREQ_EXCEPTION));
+ client2.invoke(() -> doPuts(2, OTHER_EXCEPTION));
+
+ } else {
+ client2.invoke(() -> createCacheClient(null, null, null, port1, port2, 0, multiUser, AUTHREQ_EXCEPTION));
+ }
+
+ // Now try to connect client1 with invalid credentials
+ // Verify that the creation of region throws security exception
+ Properties credentials3 = gen.getInvalidCredentials(7);
+ Properties javaProps3 = gen.getJavaProperties();
+ getLogWriter().info("testCredentialsWithFailover: For first client invalid credentials: " + credentials3 + " : " + javaProps3);
+
+ client1.invoke(() -> createCacheClient(authInit, credentials3, javaProps3, port1, port2, 0, multiUser, AUTHFAIL_EXCEPTION));
+
+ if (multiUser) {
+ client1.invoke(() -> doProxyCacheClose());
+ client2.invoke(() -> doProxyCacheClose());
+ client1.invoke(() -> doSimplePut("CacheClosedException"));
+ client2.invoke(() -> doSimpleGet("CacheClosedException"));
+ }
+ }
+
+ protected void doTestCredentialsForNotifications(final boolean multiUser) throws Exception {
+ 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
+ int locPort1 = getLocatorPort();
+ int locPort2 = getLocatorPort();
+ String locString = getAndClearLocatorString();
+
+ int port1 = server1.invoke(() -> createCacheServer(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
+ int port2 = getRandomAvailablePort(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);
+
+ createClient1NoException(multiUser, authInit, port1, port2, credentials1, javaProps1);
+
+ // Set up zero forward connections to check notification handshake only
+ int zeroConns = 0;
+ createClient2NoException(multiUser, authInit, port1, port2, credentials2, javaProps2, zeroConns);
+
+ // Register interest on all keys on second client
+ client2.invoke(() -> registerAllInterest());
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doLocalGets(2));
+
+ // start the second one and stop the first server to force a failover
+ server2.invoke(() -> createCacheServer(locPort2, locString, port2, authenticator, extraProps, javaProps));
+ server1.invoke(() -> closeCache());
+
+ // Wait for failover to complete
+ pause(500);
+
+ // Perform some create/update operations from client1
+ client1.invoke(() -> doNPuts(4));
+ // Verify that the creates/updates succeeded
+ client2.invoke(() -> doNLocalGets(4));
+
+ // Try to connect client1 with no credentials
+ // Verify that the creation of region throws security exception
+ server1.invoke(() -> createCacheServer(locPort1, locString, port1, authenticator, extraProps, javaProps));
+
+ if (gen.classCode().equals(CredentialGenerator.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(() -> createCacheClient(null, null, null, port1, port2, zeroConns, multiUser, NOFORCE_AUTHREQ_EXCEPTION));
+ client1.invoke(() -> doPuts(2, OTHER_EXCEPTION));
+
+ } else {
+ client1.invoke(() -> createCacheClient(null, null, null, port1, port2, zeroConns, multiUser, 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);
+
+ createClient2WithException(multiUser, authInit, port1, port2, credentials2, javaProps2, zeroConns);
+
+ // 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(() -> createCacheClient("com.gemstone.none", credentials1, javaProps1, port1, port2, zeroConns, multiUser, 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(() -> createCacheServer(locPort1, locString, port1, "com.gemstone.gemfire.none", extraProps, javaProps));
+ server2.invoke(() -> createCacheServer(locPort2, locString, port2, "com.gemstone.gemfire.none", extraProps, javaProps));
+
+ createClient2WithException(multiUser, authInit, port1, port2, credentials1, javaProps1, zeroConns);
+ createClient1WithException(multiUser, authInit, port1, port2, credentials2, javaProps2, zeroConns);
+
+ } 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(() -> createCacheServer(locPort1, locString, port1, authenticator, extraProps, javaProps));
+ server2.invoke(() -> createCacheServer(locPort2, locString, port2, authenticator, extraProps, javaProps));
+ client1.invoke(() -> createCacheClient(null, credentials1, javaProps1, port1, port2, 0, multiUser, AUTHREQ_EXCEPTION));
+
+ createClient2AuthReqException(multiUser, port1, port2, credentials2, javaProps2, zeroConns);
+ createClient2AuthReqException(multiUser, port1, port2, credentials2, javaProps2, zeroConns);
+
+ } 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(() -> createCacheServer(locPort1, locString, port1, null, extraProps, javaProps));
+ server2.invoke(() -> createCacheServer(locPort2, locString, port2, null, extraProps, javaProps));
+
+ createClient1NoException(multiUser, authInit, port1, port2, credentials1, javaProps1);
+ createClient2NoException(multiUser, authInit, port1, port2, credentials2, javaProps2, zeroConns);
+
+ // Register interest on all keys on second client
+ client2.invoke(() -> registerAllInterest());
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(4));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doLocalGets(4));
+
+ // Now also try with valid credentials on client2
+ createClient1NoException(multiUser, authInit, port1, port2, credentials2, javaProps2);
+ createClient2NoException(multiUser, authInit, port1, port2, credentials1, javaProps1, zeroConns);
+
+ // Register interest on all keys on second client
+ client2.invoke(() -> registerAllInterest());
+
+ // Perform some put operations from client1
+ client1.invoke(() -> doNPuts(4));
+
+ // Verify that the puts succeeded
+ client2.invoke(() -> doNLocalGets(4));
+
+ } else {
+ getLogWriter().info("testCredentialsForNotifications: Skipping scheme [" + gen.classCode() + "] which has no authenticator");
+ }
+ }
+
+ private int createServer1(final Properties extraProps, final Properties javaProps, final String authenticator, final int locPort1, final String locString) {
+ return server1.invoke(() -> createCacheServer(locPort1, locString, authenticator, extraProps, javaProps));
+ }
+
+ private void createClient1NoException(final boolean multiUser, final String authInit, final int port1, final int port2, final Properties credentials2, final Properties javaProps2) {
+ client1.invoke(() -> createCacheClient(authInit, credentials2, javaProps2, port1, port2, 0, multiUser, NO_EXCEPTION));
+ }
+
+ private void createClient2AuthReqException(final boolean multiUser, final int port1, final int port2, final Properties credentials2, final Properties javaProps2, final int zeroConns) {
+ client2.invoke(() -> createCacheClient(null, credentials2, javaProps2, port1, port2, zeroConns, multiUser, AUTHREQ_EXCEPTION));
+ }
+
+ private void createClient1WithException(final boolean multiUser, final String authInit, final int port1, final int port2, final Properties credentials2, final Properties javaProps2, final int zeroConns) {
+ client1.invoke(() -> createCacheClient(authInit, credentials2, javaProps2, port1, port2, zeroConns, multiUser, AUTHFAIL_EXCEPTION));
+ }
+
+ private void createClient2WithException(final boolean multiUser, final String authInit, final int port1, final int port2, final Properties credentials2, final Properties javaProps2, final int zeroConns) {
+ client2.invoke(() -> createCacheClient(authInit, credentials2, javaProps2, port1, port2, zeroConns, multiUser, AUTHFAIL_EXCEPTION));
+ }
+
+ private void createClient2NoException(final boolean multiUser, final String authInit, final int port1, final int port2, final Properties credentials2, final Properties javaProps2, final int zeroConns) {
+ client2.invoke(() -> createCacheClient(authInit, credentials2, javaProps2, port1, port2, zeroConns, multiUser, NO_EXCEPTION));
+ }
+
+ private void createClientsNoException(final boolean multiUser, final String authInit, final int port1, final int port2, final Properties credentials1, final Properties javaProps1, final Properties credentials2, final Properties javaProps2) {
+ createClient1NoException(multiUser, authInit, port1, port2, credentials1, javaProps1);
+ client2.invoke(() -> createCacheClient(authInit, credentials2, javaProps2, port1, port2, 0, multiUser, NO_EXCEPTION));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestUtils.java b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestUtils.java
new file mode 100644
index 0000000..89a0a15
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/ClientAuthenticationTestUtils.java
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+package com.gemstone.gemfire.security;
+
+import static com.gemstone.gemfire.distributed.internal.DistributionConfig.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.Properties;
+
+import com.gemstone.gemfire.cache.Region;
+
+/**
+ * Extracted from ClientAuthenticationDUnitTest
+ */
+public abstract class ClientAuthenticationTestUtils {
+
+ protected ClientAuthenticationTestUtils() {
+ }
+
+ protected static Integer createCacheServer(final int locatorPort, final String locatorString, final String authenticator, final Properties extraProps, final Properties javaProps) {
+ Properties authProps;
+ if (extraProps == null) {
+ authProps = new Properties();
+ } else {
+ authProps = extraProps;
+ }
+
+ if (authenticator != null) {
+ authProps.setProperty(SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
+ }
+
+ return SecurityTestUtils.createCacheServer(authProps, javaProps, locatorPort, locatorString, 0, NO_EXCEPTION);
+ }
+
+ protected static void createCacheServer(final int locatorPort, final String locatorString, final int serverPort, final String authenticator, final Properties extraProps, final Properties javaProps) {
+ Properties authProps;
+ if (extraProps == null) {
+ authProps = new Properties();
+ } else {
+ authProps = extraProps;
+ }
+
+ if (authenticator != null) {
+ authProps.setProperty(SECURITY_CLIENT_AUTHENTICATOR_NAME, authenticator);
+ }
+ SecurityTestUtils.createCacheServer(authProps, javaProps, locatorPort, locatorString, serverPort, NO_EXCEPTION);
+ }
+
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean multiUserMode, final boolean subscriptionEnabled, final int expectedResult) {
+ SecurityTestUtils.createCacheClient(authInit, authProps, javaProps, ports, numConnections, false, multiUserMode, subscriptionEnabled, expectedResult);
+ }
+
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int[] ports, final int numConnections, final boolean multiUserMode, final int expectedResult) {
+ createCacheClient(authInit, authProps, javaProps, ports, numConnections, multiUserMode, true, expectedResult);
+ }
+
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int port1, final int numConnections, final int expectedResult) {
+ createCacheClient(authInit, authProps, javaProps, new int[] { port1 }, numConnections, false, true, expectedResult);
+ }
+
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int port1, final int port2, final int numConnections, final int expectedResult) {
+ createCacheClient(authInit, authProps, javaProps, port1, port2, numConnections, false, expectedResult);
+ }
+
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int port1, final int port2, final int numConnections, final boolean multiUserMode, final int expectedResult) {
+ createCacheClient(authInit, authProps, javaProps, port1, port2, numConnections, multiUserMode, true, expectedResult);
+ }
+
+ protected static void createCacheClient(final String authInit, final Properties authProps, final Properties javaProps, final int port1, final int port2, final int numConnections, final boolean multiUserMode, final boolean subscriptionEnabled, final int expectedResult) {
+ createCacheClient(authInit, authProps, javaProps, new int[] { port1, port2 }, numConnections, multiUserMode, subscriptionEnabled, expectedResult);
+ }
+
+ protected static void registerAllInterest() {
+ Region region = getCache().getRegion(REGION_NAME);
+ assertNotNull(region);
+ region.registerInterestRegex(".*");
+ }
+}
[06/11] incubator-geode git commit: GEODE-693: refactor security
dunit tests
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
index 8a78378..904a53c 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientAuthorizationDUnitTest.java
@@ -1,6 +1,3 @@
-
-package com.gemstone.gemfire.security;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,9 +6,9 @@ package com.gemstone.gemfire.security;
* 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
@@ -19,34 +16,143 @@ package com.gemstone.gemfire.security;
* specific language governing permissions and limitations
* under the License.
*/
+package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.security.ClientAuthenticationTestUtils.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
import java.util.Properties;
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 com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Assert;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* @since 6.1
*/
-public class DeltaClientAuthorizationDUnitTest extends
- ClientAuthorizationTestBase {
+@Category(DistributedTest.class)
+public final class DeltaClientAuthorizationDUnitTest extends ClientAuthorizationTestCase {
+
+ private DeltaTestImpl[] deltas = new DeltaTestImpl[8];
+
+ @Override
+ protected final void preSetUpClientAuthorizationTestBase() throws Exception {
+ setUpDeltas();
+ }
+
+ @Override
+ public final void preTearDownClientAuthorizationTestBase() throws Exception {
+ closeCache();
+ }
+
+ @Test
+ 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);
+
+ int port1 = createServer1(javaProps, serverProps);
+ int port2 = createServer2(javaProps, serverProps);
+
+ // Start client1 with valid CREATE credentials
+ Properties createCredentials = gen.getAllowedCredentials(new OperationCode[] { OperationCode.PUT }, new String[] { REGION_NAME }, 1);
+ javaProps = cGen.getJavaProperties();
+
+ getLogWriter().info("testAllowPutsGets: For first client credentials: " + createCredentials);
+
+ createClient1(javaProps, authInit, port1, port2, createCredentials);
+
+ // Start client2 with valid GET credentials
+ Properties getCredentials = gen.getAllowedCredentials(new OperationCode[] { OperationCode.GET }, new String[] { REGION_NAME }, 2);
+ javaProps = cGen.getJavaProperties();
+
+ getLogWriter().info("testAllowPutsGets: For second client credentials: " + getCredentials);
+
+ createClient2(javaProps, authInit, port1, port2, getCredentials);
- protected static final DeltaTestImpl[] deltas = new DeltaTestImpl[8];
+ // Perform some put operations from client1
+ client1.invoke(() -> doPuts(2, NO_EXCEPTION));
+
+ Thread.sleep(5000);
+ assertTrue("Delta feature NOT used", client1.invoke(() -> DeltaTestImpl.toDeltaFeatureUsed()));
+
+ // Verify that the gets succeed
+ client2.invoke(() -> doGets(2, NO_EXCEPTION));
+ }
+
+ private void createClient2(final Properties javaProps, final String authInit, final int port1, final int port2, final Properties getCredentials) {
+ client2.invoke(() -> createCacheClient(authInit, getCredentials, javaProps, port1, port2, 0, NO_EXCEPTION));
+ }
+
+ private void createClient1(final Properties javaProps, final String authInit, final int port1, final int port2, final Properties createCredentials) {
+ client1.invoke(() -> createCacheClient(authInit, createCredentials, javaProps, port1, port2, 0, NO_EXCEPTION));
+ }
+
+ private int createServer2(final Properties javaProps, final Properties serverProps) {
+ return server2.invoke(() -> createCacheServer(getLocatorPort(), serverProps, javaProps));
+ }
+
+ private int createServer1(final Properties javaProps, final Properties serverProps) {
+ return server1.invoke(() -> createCacheServer(getLocatorPort(), serverProps, javaProps));
+ }
+
+ private void doPuts(final int num, final int expectedResult) {
+ assertTrue(num <= KEYS.length);
+ Region region = getCache().getRegion(REGION_NAME);
+ assertNotNull(region);
+ for (int index = 0; index < num; ++index) {
+ region.put(KEYS[index], deltas[0]);
+ }
+ for (int index = 0; index < num; ++index) {
+ region.put(KEYS[index], deltas[index]);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing puts");
+ }
+ }
+ }
+
+ private void doGets(final int num, final int expectedResult) {
+ assertTrue(num <= KEYS.length);
+
+ Region region = getCache().getRegion(REGION_NAME);
+ assertNotNull(region);
+
+ for (int index = 0; index < num; ++index) {
+ region.localInvalidate(KEYS[index]);
+ Object value = region.get(KEYS[index]);
+ if (expectedResult != NO_EXCEPTION) {
+ fail("Expected a NotAuthorizedException while doing gets");
+ }
+ assertNotNull(value);
+ assertEquals(deltas[index], value);
+ }
+ }
- static {
+ private final void setUpDeltas() {
for (int i = 0; i < 8; i++) {
- deltas[i] = new DeltaTestImpl(0, "0", new Double(0), new byte[0],
- new TestObject1("0", 0));
+ deltas[i] = new DeltaTestImpl(0, "0", new Double(0), new byte[0], new TestObject1("0", 0));
}
deltas[1].setIntVar(5);
deltas[2].setIntVar(5);
@@ -89,263 +195,5 @@ public class DeltaClientAuthorizationDUnitTest extends
deltas[7].resetDeltaStatus();
deltas[7].setStr("delta string");
-
}
-
- /** constructor */
- public DeltaClientAuthorizationDUnitTest(String name) {
- super(name);
- }
-
- @Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
- }
-
- @Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- SecurityTestUtil.closeCache();
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.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();
-
- LogWriterUtils.getLogWriter().info("testAllowPutsGets: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testAllowPutsGets: Using authenticator: " + authenticator);
- LogWriterUtils.getLogWriter().info("testAllowPutsGets: Using accessor: " + accessor);
-
- // Start servers with all required properties
- Properties serverProps = buildProperties(authenticator, accessor, false,
- extraAuthProps, extraAuthzProps);
- Integer port1 = createServer1(javaProps, serverProps);
- Integer port2 = createServer2(javaProps, serverProps);
-
- // Start client1 with valid CREATE credentials
- Properties createCredentials = gen.getAllowedCredentials(
- new OperationCode[] { OperationCode.PUT },
- new String[] { regionName }, 1);
- javaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter().info(
- "testAllowPutsGets: For first client credentials: "
- + createCredentials);
- createClient1(javaProps, authInit, port1, port2, createCredentials);
-
- // Start client2 with valid GET credentials
- Properties getCredentials = gen.getAllowedCredentials(
- new OperationCode[] { OperationCode.GET },
- new String[] { regionName }, 2);
- javaProps = cGen.getJavaProperties();
- LogWriterUtils.getLogWriter()
- .info(
- "testAllowPutsGets: For second client credentials: "
- + getCredentials);
- createClient2(javaProps, authInit, port1, port2, getCredentials);
-
- // Perform some put operations from client1
- client1.invoke(() -> DeltaClientAuthorizationDUnitTest.doPuts(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION), Boolean.FALSE ));
- Thread.sleep(5000);
- assertTrue("Delta feature NOT used", (Boolean)client1.invoke(() -> DeltaTestImpl.toDeltaFeatureUsed()));
-
- // Verify that the gets succeed
- client2.invoke(() -> DeltaClientAuthorizationDUnitTest.doGets(
- new Integer(2), new Integer(SecurityTestUtil.NO_EXCEPTION), Boolean.FALSE ));
- }
-
- protected void createClient2(Properties javaProps, String authInit,
- Integer port1, Integer port2, Properties getCredentials) {
- client2.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, getCredentials, javaProps, port1, port2,
- null, new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- }
-
- protected void createClient1(Properties javaProps, String authInit,
- Integer port1, Integer port2, Properties createCredentials) {
- client1.invoke(() -> ClientAuthenticationDUnitTest.createCacheClient( authInit, createCredentials, javaProps, port1, port2,
- null, new Integer(SecurityTestUtil.NO_EXCEPTION) ));
- }
-
- protected Integer createServer2(Properties javaProps,
- Properties serverProps) {
- Integer port2 = ((Integer)server2.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- SecurityTestUtil.getLocatorPort(), serverProps, javaProps )));
- return port2;
- }
-
- protected Integer createServer1(Properties javaProps,
- Properties serverProps) {
- Integer port1 = ((Integer)server1.invoke(() -> ClientAuthorizationTestBase.createCacheServer(
- SecurityTestUtil.getLocatorPort(), serverProps, javaProps )));
- return port1;
- }
-
- 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) {
- LogWriterUtils.getLogWriter().info("Got expected exception when doing puts: " + ex);
- }
- else {
- Assert.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) {
- LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing puts: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing puts", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == SecurityTestUtil.NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing puts: "
- + ex.getCause());
- continue;
- }
- if ((expectedResult.intValue() == SecurityTestUtil.AUTHREQ_EXCEPTION)
- && (ex.getCause() instanceof AuthenticationRequiredException)) {
- LogWriterUtils.getLogWriter().info(
- "Got expected AuthenticationRequiredException when doing puts: "
- + ex.getCause());
- continue;
- }
- if ((expectedResult.intValue() == SecurityTestUtil.AUTHFAIL_EXCEPTION)
- && (ex.getCause() instanceof AuthenticationFailedException)) {
- LogWriterUtils.getLogWriter().info(
- "Got expected AuthenticationFailedException when doing puts: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
- LogWriterUtils.getLogWriter().info("Got expected exception when doing puts: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing puts", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
- LogWriterUtils.getLogWriter().info("Got expected exception when doing puts: " + ex);
- }
- else {
- Assert.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) {
- LogWriterUtils.getLogWriter().info("Got expected exception when doing gets: " + ex);
- }
- else {
- Assert.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) {
- LogWriterUtils.getLogWriter().info(
- "Got expected NoAvailableServers when doing puts: "
- + ex.getCause());
- continue;
- }
- else {
- Assert.fail("Got unexpected exception when doing puts", ex);
- }
- }
- catch (ServerConnectivityException ex) {
- if ((expectedResult.intValue() == SecurityTestUtil.NOTAUTHZ_EXCEPTION)
- && (ex.getCause() instanceof NotAuthorizedException)) {
- LogWriterUtils.getLogWriter().info(
- "Got expected NotAuthorizedException when doing gets: "
- + ex.getCause());
- continue;
- }
- else if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
- LogWriterUtils.getLogWriter().info("Got expected exception when doing gets: " + ex);
- }
- else {
- Assert.fail("Got unexpected exception when doing gets", ex);
- }
- }
- catch (Exception ex) {
- if (expectedResult.intValue() == SecurityTestUtil.OTHER_EXCEPTION) {
- LogWriterUtils.getLogWriter().info("Got expected exception when doing gets: " + ex);
- }
- else {
- Assert.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/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
index e0502a2..222ea00 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/DeltaClientPostAuthorizationDUnitTest.java
@@ -1,6 +1,3 @@
-
-package com.gemstone.gemfire.security;
-
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
@@ -9,9 +6,9 @@ package com.gemstone.gemfire.security;
* 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
@@ -19,185 +16,123 @@ package com.gemstone.gemfire.security;
* specific language governing permissions and limitations
* under the License.
*/
+package com.gemstone.gemfire.security;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.IgnoredException.*;
+import static com.gemstone.gemfire.test.dunit.LogWriterUtils.*;
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 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 com.gemstone.gemfire.internal.cache.PartitionedRegionLocalMaxMemoryDUnitTest;
import com.gemstone.gemfire.security.generator.AuthzCredentialGenerator;
import com.gemstone.gemfire.security.generator.CredentialGenerator;
-import com.gemstone.gemfire.test.dunit.Assert;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.IgnoredException;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* @since 6.1
- *
*/
-public class DeltaClientPostAuthorizationDUnitTest extends
- ClientAuthorizationTestBase {
- private static final int PAUSE = 5 * 1000;
+@Category(DistributedTest.class)
+public class DeltaClientPostAuthorizationDUnitTest extends ClientAuthorizationTestCase {
- /** constructor */
- public DeltaClientPostAuthorizationDUnitTest(String name) {
- super(name);
- }
+ private static final int PAUSE = 5 * 1000; // TODO: replace with Awaitility
+
+ private DeltaTestImpl[] deltas = new DeltaTestImpl[8];
@Override
- public final void postSetUp() throws Exception {
- 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.registerExpectedExceptions( serverExpectedExceptions ));
- server2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( serverExpectedExceptions ));
- client2.invoke(() -> SecurityTestUtil.registerExpectedExceptions( clientExpectedExceptions ));
- SecurityTestUtil.registerExpectedExceptions(clientExpectedExceptions);
+ public final void preSetUpClientAuthorizationTestBase() throws Exception {
+ setUpDeltas();
+ addIgnoredException("Unexpected IOException");
+ addIgnoredException("SocketException");
}
@Override
- public final void preTearDown() throws Exception {
- // close the clients first
- client1.invoke(() -> SecurityTestUtil.closeCache());
- client2.invoke(() -> SecurityTestUtil.closeCache());
- SecurityTestUtil.closeCache();
- // then close the servers
- server1.invoke(() -> SecurityTestUtil.closeCache());
- server2.invoke(() -> SecurityTestUtil.closeCache());
+ public final void preTearDownClientAuthorizationTestBase() throws Exception {
+ closeCache();
}
+ @Test
public void testPutPostOpNotifications() throws Exception {
- IgnoredException.addIgnoredException("Unexpected IOException");
- IgnoredException.addIgnoredException("SocketException");
+ OperationWithAction[] allOps = allOps();
- 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),
+ 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);
- // OPBLOCK_END indicates end of an operation block that needs to
- // be executed on each server when doing failover
- OperationWithAction.OPBLOCK_END,
+ getLogWriter().info("testAllOpsNotifications: Using authinit: " + authInit);
+ getLogWriter().info("testAllOpsNotifications: Using authenticator: " + authenticator);
+ getLogWriter().info("testAllOpsNotifications: Using accessor: " + accessor);
- // 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);
-
- LogWriterUtils.getLogWriter().info(
- "testAllOpsNotifications: Using authinit: " + authInit);
- LogWriterUtils.getLogWriter().info(
- "testAllOpsNotifications: Using authenticator: " + authenticator);
- LogWriterUtils.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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port1, serverProps,
- javaProps ));
- server2.invoke(() -> SecurityTestUtil.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.createCacheServer(
- SecurityTestUtil.getLocatorPort(), port2, serverProps,
- javaProps ));
- server1.invoke(() -> SecurityTestUtil.closeCache());
- executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps,
- extraAuthzProps, tgen, rnd);
- }
- opBlock.clear();
+ // Start servers with all required properties
+ Properties serverProps = buildProperties(authenticator, accessor, true, extraAuthProps, extraAuthzProps);
+
+ // Get ports for the servers
+ int port1 = getRandomAvailablePort(SOCKET);
+ int port2 = getRandomAvailablePort(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(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), port1, serverProps, javaProps ));
+ server2.invoke(() -> 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(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(), port2, serverProps, javaProps ));
+ server1.invoke(() -> closeCache());
+
+ executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, tgen, rnd);
}
+
+ opBlock.clear();
}
- else {
- currentOp.setOpNum(opNum);
- opBlock.add(currentOp);
- }
+
+ } 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();
+ @Override
+ protected final void executeOpBlock(final List<OperationWithAction> opBlock, final int port1, final int port2, final String authInit, final Properties extraAuthProps, final Properties extraAuthzProps, final TestCredentialGenerator credentialGenerator, final Random random) throws InterruptedException {
+ for (Iterator<OperationWithAction> opIter = opBlock.iterator(); opIter.hasNext();) {
+ // Start client with valid credentials as specified in OperationWithAction
+ OperationWithAction currentOp = 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;
@@ -212,325 +147,132 @@ public class DeltaClientPostAuthorizationDUnitTest extends
fail("executeOpBlock: Unknown client number " + clientNum);
break;
}
- LogWriterUtils.getLogWriter().info(
- "executeOpBlock: performing operation number ["
- + currentOp.getOpNum() + "]: " + currentOp);
+
+ getLogWriter().info("executeOpBlock: performing operation number [" + currentOp.getOpNum() + "]: " + currentOp);
+
if ((opFlags & OpFlags.USE_OLDCONN) == 0) {
Properties opCredentials;
- int newRnd = rnd.nextInt(100) + 1;
+ int newRnd = random.nextInt(100) + 1;
String currentRegionName = '/' + regionName;
if ((opFlags & OpFlags.USE_SUBREGION) > 0) {
- currentRegionName += ('/' + subregionName);
+ currentRegionName += ('/' + SUBREGION_NAME);
}
+
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);
+ CredentialGenerator cGen = credentialGenerator.getCredentialGenerator();
+ final Properties javaProps = cGen == null ? null : cGen.getJavaProperties();
+
+ if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0 || (opFlags & OpFlags.USE_NOTAUTHZ) > 0) {
+ opCredentials = credentialGenerator.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);
+
+ } else {
+ opCredentials = credentialGenerator.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
- LogWriterUtils.getLogWriter().info(
- "executeOpBlock: For client" + clientNum + credentialsTypeStr
- + " credentials: " + opCredentials);
+
+ Properties clientProps = 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) });
+ createCacheClient(authInit, clientProps, javaProps, new int[] { port1, port2 }, 0, setupDynamicRegionFactory, NO_EXCEPTION);
+
+ } else {
+ clientVM.invoke(() -> createCacheClient(authInit, clientProps, javaProps, new int[] { port1, port2 }, 0, setupDynamicRegionFactory, 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;
+ expectedResult = NOTAUTHZ_EXCEPTION;
+ } else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
+ expectedResult = OTHER_EXCEPTION;
+ } else {
+ expectedResult = NO_EXCEPTION;
}
// Perform the operation from selected client
if (useThisVM) {
- doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), new Integer(
- opFlags), new Integer(expectedResult));
- }
- else {
+ doOp(new Byte(opCode.toOrdinal()), currentOp.getIndices(), new Integer(opFlags), new Integer(expectedResult));
+ } else {
byte ordinal = opCode.toOrdinal();
int[] indices = currentOp.getIndices();
- clientVM.invoke(() -> DeltaClientPostAuthorizationDUnitTest.doOp( new Byte(ordinal),
- indices, new Integer(opFlags),
- new Integer(expectedResult) ));
+ clientVM.invoke(() -> doOp(new Byte(ordinal), indices, new Integer(opFlags), new Integer(expectedResult) ));
}
}
}
- private static Region createSubregion(Region region) {
-
- Region subregion = getSubregion();
- if (subregion == null) {
- subregion = region.createSubregion(subregionName, region.getAttributes());
+ private void setUpDeltas() {
+ for (int i = 0; i < 8; i++) {
+ deltas[i] = new DeltaTestImpl(0, "0", new Double(0), new byte[0], new PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("0", 0));
}
- return subregion;
- }
+ 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);
- 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;
- LogWriterUtils.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)) {
- LogWriterUtils.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) {
- LogWriterUtils.getLogWriter().info(
- "doOp: Got expected exception when doing operation: "
- + ex.toString());
- continue;
- }
- else {
- Assert.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));
- }
- }
+ 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 PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("CHANGED", 100));
+ deltas[6].setTestObj(new PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("CHANGED", 100));
+ deltas[7].setTestObj(new PartitionedRegionLocalMaxMemoryDUnitTest.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");
+ }
+
+ private OperationWithAction[] allOps() {
+ return new OperationWithAction[] {
+ // 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
+ };
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/22ca5ef8/geode-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
index a8f5f95..1db599f 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/security/P2PAuthenticationDUnitTest.java
@@ -18,69 +18,62 @@
*/
package com.gemstone.gemfire.security;
-import java.io.File;
-import java.util.Properties;
+import static com.gemstone.gemfire.distributed.internal.DistributionConfig.*;
+import static com.gemstone.gemfire.internal.AvailablePort.*;
+import static com.gemstone.gemfire.security.SecurityTestUtils.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.IgnoredException.*;
+import static com.gemstone.gemfire.test.dunit.NetworkUtils.*;
+import static com.gemstone.gemfire.test.dunit.Wait.*;
+import java.util.Properties;
import javax.net.ssl.SSLHandshakeException;
-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 com.gemstone.gemfire.security.generator.CredentialGenerator;
import com.gemstone.gemfire.security.generator.DummyCredentialGenerator;
import com.gemstone.gemfire.security.generator.LdapUserCredentialGenerator;
import com.gemstone.gemfire.security.generator.UserPasswordWithExtraPropsAuthInit;
import com.gemstone.gemfire.security.templates.LdapUserAuthenticator;
import com.gemstone.gemfire.security.templates.UserPasswordAuthInit;
-import com.gemstone.gemfire.test.dunit.DistributedTestCase;
import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.IgnoredException;
-import com.gemstone.gemfire.test.dunit.LogWriterUtils;
-import com.gemstone.gemfire.test.dunit.NetworkUtils;
import com.gemstone.gemfire.test.dunit.VM;
-import com.gemstone.gemfire.test.dunit.Wait;
+import com.gemstone.gemfire.test.dunit.internal.JUnit4DistributedTestCase;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
/**
* Tests peer to peer authentication in Gemfire
*
* @since 5.5
*/
-public class P2PAuthenticationDUnitTest extends DistributedTestCase {
+@Category(DistributedTest.class)
+public class P2PAuthenticationDUnitTest extends JUnit4DistributedTestCase {
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 = {
+ private static final String[] ignoredExceptions = {
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);
- }
+ "Failed to obtain credentials"
+ };
@Override
public final void postSetUp() throws Exception {
- 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);
+ disconnectAllFromDS();
+ locatorVM = Host.getHost(0).getVM(0);
+ for (String exceptionString : ignoredExceptions) {
+ addIgnoredException(exceptionString);
}
}
@@ -88,271 +81,231 @@ public class P2PAuthenticationDUnitTest extends DistributedTestCase {
* Check that mcast-port setting for discovery or with locator are
* incompatible with security
*/
+ @Test
public void testIllegalPropertyCombos() throws Exception {
+ int port = getRandomAvailablePort(SOCKET);
- 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,
- NetworkUtils.getIPLiteral() + "[" + port + "]");
- props.setProperty(DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME, UserPasswordAuthInit.class.getName() + ".create");
- props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+ props.setProperty(MCAST_PORT_NAME, "26753");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() + "[" + port + "]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, UserPasswordAuthInit.class.getName() + ".create");
+ props.setProperty(ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
try {
- Locator.startLocatorAndDS(port, logFile, null, props);
+ Locator.startLocatorAndDS(port, null, null, props);
fail("Expected an IllegalArgumentException while starting locator");
- }
- catch (IllegalArgumentException ex) {
+
+ } catch (IllegalArgumentException ex) {
// success
}
// Also try setting the authenticator
props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
- props.setProperty(DistributionConfig.LOCATORS_NAME,
- NetworkUtils.getIPLiteral() +"[" + port + "]");
- props.setProperty(DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME, LdapUserAuthenticator.class.getName() + ".create");
- props.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+ props.setProperty(MCAST_PORT_NAME, "26753");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"[" + port + "]");
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, LdapUserAuthenticator.class.getName() + ".create");
+ props.setProperty(ENABLE_CLUSTER_CONFIGURATION_NAME, "false");
+
try {
- Locator.startLocatorAndDS(port, logFile, null, props);
+ Locator.startLocatorAndDS(port, null, null, props);
fail("Expected an IllegalArgumentException while starting locator");
- }
- catch (IllegalArgumentException ex) {
+
+ } catch (IllegalArgumentException expected) {
// success
}
props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
- props.setProperty(DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME, UserPasswordAuthInit.class.getName() + ".create");
+ props.setProperty(MCAST_PORT_NAME, "26753");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, UserPasswordAuthInit.class.getName() + ".create");
+
try {
getSystem(props);
fail("Expected an IllegalArgumentException while connection to DS");
- }
- catch (IllegalArgumentException ex) {
+
+ } catch (IllegalArgumentException expected) {
// success
}
// Also try setting the authenticator
props = new Properties();
- props.setProperty(DistributionConfig.MCAST_PORT_NAME, "26753");
- props.setProperty(DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME, LdapUserAuthenticator.class.getName() + ".create");
+ props.setProperty(MCAST_PORT_NAME, "26753");
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, LdapUserAuthenticator.class.getName() + ".create");
+
try {
getSystem(props);
fail("Expected an IllegalArgumentException while connection to DS");
- }
- catch (IllegalArgumentException ex) {
+
+ } catch (IllegalArgumentException expected) {
// success
}
}
- // AuthInitialize is incorrect
+ /**
+ * AuthInitialize is incorrect
+ */
+ @Test
public void testP2PAuthenticationWithInvalidAuthInitialize() throws Exception {
+ int locatorPort = getRandomAvailablePort(SOCKET);
- 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 = NetworkUtils.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);
- startLocator(props, javaProps, port);
-
- LogWriter dsLogger = LogWriterUtils.createLogWriter(props);
- SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+ assertNotNull(gen.getAuthenticator());
+ assertNull(gen.getJavaProperties());
+
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() + "[" + locatorPort + "]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, "Incorrect_AuthInitialize");
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
+
+ startTheLocator(props, gen.getJavaProperties(), locatorPort);
+
try {
- new SecurityTestUtil("tmp").createSystem(props, null);
+ new SecurityTestUtils("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.stopLocator(
- new Integer(port), expectedExceptions));
+ locatorVM.invoke(() -> stopLocator(locatorPort, ignoredExceptions));
}
-
}
- protected void startLocator(Properties props, Properties javaProps,
- int port) {
- locatorVM.invoke(() -> SecurityTestUtil.startLocator(
- getUniqueName(), new Integer(port), props, javaProps,
- expectedExceptions));
- }
-
- // Authenticator is incorrect
+ /**
+ * Authenticator is incorrect
+ */
+ @Test
public void testP2PAuthenticationWithInvalidAuthenticator() throws Exception {
- disconnectAllFromDS();
+ int locatorPort = getRandomAvailablePort(SOCKET);
+
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 = NetworkUtils.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);
- startLocator(props, javaProps, port);
-
- LogWriter dsLogger = LogWriterUtils.createLogWriter(props);
- SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+ assertNotNull(gen.getAuthInit());
+ assertNull(gen.getJavaProperties());
+
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"["+locatorPort+"]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, gen.getAuthInit());
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, "xyz");
+
+ startTheLocator(props, null, locatorPort);
+
try {
- new SecurityTestUtil("tmp").createSystem(props, javaProps);
+ new SecurityTestUtils("tmp").createSystem(props, null);
fail("AuthenticationFailedException was expected as the Authenticator object passed is incorrect");
- }
- catch (AuthenticationFailedException expected) {
+
+ } catch (AuthenticationFailedException expected) {
// success
- }
- finally {
- SecurityTestUtil.removeExpectedExceptions(expectedExceptions, dsLogger);
- locatorVM.invoke(() -> SecurityTestUtil.stopLocator(
- new Integer(port), expectedExceptions ));
+
+ } finally {
+ locatorVM.invoke(() -> stopLocator(locatorPort, ignoredExceptions));
}
}
+ @Test
public void testP2PAuthenticationWithNoCredentials() throws Exception {
-
- disconnectAllFromDS();
+ int locatorPort = getRandomAvailablePort(SOCKET);
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 = NetworkUtils.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);
- startLocator(props, javaProps, port);
-
- LogWriter dsLogger = LogWriterUtils.createLogWriter(props);
- SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
+ assertNotNull(gen.getAuthenticator());
+ assertNotNull(gen.getAuthInit());
+ assertNull(gen.getJavaProperties());
+ assertNull(gen.getSystemProperties());
+
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"["+locatorPort+"]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, gen.getAuthInit());
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
+
+ startTheLocator(props, null, locatorPort);
+
try {
- new SecurityTestUtil("tmp").createSystem(props, null);
+ new SecurityTestUtils("tmp").createSystem(props, null);
fail("AuthenticationFailedException was expected as no credentials are set");
- }
- catch (AuthenticationFailedException expected) {
+
+ } catch (AuthenticationFailedException expected) {
// success
- }
- finally {
- SecurityTestUtil.removeExpectedExceptions(expectedExceptions, dsLogger);
- locatorVM.invoke(() -> SecurityTestUtil.stopLocator(
- new Integer(port), expectedExceptions ));
+
+ } finally {
+ locatorVM.invoke(() -> stopLocator(locatorPort, ignoredExceptions));
}
}
+ @Test
public void testP2PAuthenticationWithValidCredentials() throws Exception {
+ int locatorPort = getRandomAvailablePort(SOCKET);
- 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 = NetworkUtils.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);
- startLocator(props, javaProps, port);
+ assertNotNull(gen.getAuthenticator());
+ assertNotNull(gen.getAuthInit());
+ assertNull(gen.getJavaProperties());
+ assertNull(gen.getSystemProperties());
+ assertNotNull(gen.getValidCredentials(1));
+
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"["+locatorPort+"]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, gen.getAuthInit());
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
+ props.putAll(gen.getValidCredentials(1));
+
+ startTheLocator(props, gen.getJavaProperties(), locatorPort);
+
try {
- createDS(props, javaProps);
- verifyMembers(new Integer(2));
+ createDS(props, gen.getJavaProperties());
+ verifyMembers(2);
disconnectFromDS();
} finally {
- locatorVM.invoke(() -> SecurityTestUtil.stopLocator(
- new Integer(port), expectedExceptions ));
+ locatorVM.invoke(() -> stopLocator(locatorPort, ignoredExceptions));
}
}
- public void testP2PAuthenticationWithBothValidAndInValidCredentials()
- throws Exception {
+ @Test
+ public void testP2PAuthenticationWithBothValidAndInValidCredentials() throws Exception {
+ addIgnoredException("Authentication failed");
- disconnectAllFromDS();
- IgnoredException.addIgnoredException("Authentication failed");
+ int locatorPort = getRandomAvailablePort(SOCKET);
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 = NetworkUtils.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);
- startLocator(props, javaProps, port);
+ assertNotNull(gen.getAuthenticator());
+ assertNotNull(gen.getAuthInit());
+ assertNotNull(gen.getInvalidCredentials(1));
+ assertNull(gen.getJavaProperties());
+ assertNull(gen.getSystemProperties());
+ assertNotNull(gen.getValidCredentials(1));
+ assertNotNull(gen.getValidCredentials(3));
+
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"["+locatorPort+"]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, gen.getAuthInit());
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
+ props.putAll(gen.getValidCredentials(1));
+
+ startTheLocator(props, null, locatorPort);
+
try {
// invalid credentials for the peer
- credentials = gen.getInvalidCredentials(1);
- javaProps = gen.getJavaProperties();
- props.putAll(credentials);
+ props.putAll(gen.getInvalidCredentials(1));
- LogWriter dsLogger = LogWriterUtils.createLogWriter(props);
- SecurityTestUtil.addExpectedExceptions(expectedExceptions, dsLogger);
try {
- new SecurityTestUtil("tmp").createSystem(props, javaProps);
+ new SecurityTestUtils("tmp").createSystem(props, null);
fail("AuthenticationFailedException was expected as wrong credentials were passed");
- }
- catch (AuthenticationFailedException expected) {
+
+ } 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));
+ props.putAll(gen.getValidCredentials(3));
+
+ createDS(props, null);
+ verifyMembers(2);
disconnectFromDS();
} finally {
- locatorVM.invoke(() -> SecurityTestUtil.stopLocator(
- new Integer(port), expectedExceptions ));
+ locatorVM.invoke(() -> stopLocator(locatorPort, ignoredExceptions));
}
}
@@ -365,9 +318,11 @@ public class P2PAuthenticationDUnitTest extends DistributedTestCase {
* reported by the first peer should be only two while others will report as
* three.
*/
- public void disabled_testP2PViewChangeReject() throws Exception {
+ @Ignore("disabled for some reason?")
+ @Test
+ public void testP2PViewChangeReject() throws Exception {
+ int locatorPort = getRandomAvailablePort(SOCKET);
- disconnectAllFromDS();
final Host host = Host.getHost(0);
final VM peer2 = host.getVM(1);
final VM peer3 = host.getVM(2);
@@ -377,6 +332,7 @@ public class P2PAuthenticationDUnitTest extends DistributedTestCase {
Properties extraProps = gen.getSystemProperties();
String authenticator = gen.getAuthenticator();
String authInit = gen.getAuthInit();
+
if (extraProps == null) {
extraProps = new Properties();
}
@@ -385,93 +341,92 @@ public class P2PAuthenticationDUnitTest extends DistributedTestCase {
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 = NetworkUtils.getIPLiteral() +"["+port+"]";
- setProperty(props, DistributionConfig.SECURITY_PEER_AUTH_INIT_NAME,
- authInit);
- setProperty(props, DistributionConfig.SECURITY_PEER_AUTHENTICATOR_NAME,
- authenticator);
+ int port = getRandomAvailablePort(SOCKET);
+ final String locators = getIPLiteral() +"["+port+"]";
+
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, authInit);
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, authenticator);
Properties credentials = gen.getValidCredentials(1);
Properties javaProps = gen.getJavaProperties();
props.putAll(credentials);
props.putAll(extraProps);
- startLocator(props, javaProps, port);
+
+ startTheLocator(props, javaProps, port);
+
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 first peer with different authenticator
+ props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, locators);
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, authInit);
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, authenticator2);
- // 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);
- createDS(peer2, props, javaProps);
-
- createDS(peer3, props, javaProps);
-
- // wait for view propagation
- Wait.pause(2000);
- // Verify the number of members on all peers and locator
- locatorVM.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(4) ));
- verifyMembers(new Integer(2));
- peer2.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(4) ));
- peer3.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(4) ));
-
- // Disconnect the first peer and check again
- disconnectFromDS();
- Wait.pause(2000);
- locatorVM.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(3) ));
- peer2.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(3) ));
- peer3.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(3) ));
-
- // Disconnect the second peer and check again
- peer2.invoke(() -> DistributedTestCase.disconnectFromDS());
- Wait.pause(2000);
- locatorVM.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(2) ));
- peer3.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(2) ));
-
- // Same for last peer
- peer3.invoke(() -> DistributedTestCase.disconnectFromDS());
- Wait.pause(2000);
- locatorVM.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(1) ));
+ 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(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, locators);
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, authInit);
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, authenticator);
+
+ credentials = gen.getValidCredentials(7);
+ javaProps = gen.getJavaProperties();
+ props.putAll(credentials);
+ props.putAll(extraProps);
+
+ createDS(peer2, props, javaProps);
+
+ createDS(peer3, props, javaProps);
+
+ // wait for view propagation
+ pause(2000);
+
+ // Verify the number of members on all peers and locator
+ locatorVM.invoke(() -> verifyMembers(4));
+ verifyMembers(2);
+ peer2.invoke(() -> verifyMembers(4));
+ peer3.invoke(() -> verifyMembers(4));
+
+ // Disconnect the first peer and check again
+ disconnectFromDS();
+ pause(2000);
+
+ locatorVM.invoke(() -> verifyMembers(3));
+ peer2.invoke(() -> verifyMembers(3));
+ peer3.invoke(() -> verifyMembers(3));
+
+ // Disconnect the second peer and check again
+ peer2.invoke(() -> disconnectFromDS());
+ pause(2000);
+
+ locatorVM.invoke(() -> verifyMembers(2));
+ peer3.invoke(() -> verifyMembers(2));
+
+ // Same for last peer
+ peer3.invoke(() -> disconnectFromDS());
+ pause(2000);
+
+ locatorVM.invoke(() -> verifyMembers(1));
} finally {
- locatorVM.invoke(() -> SecurityTestUtil.stopLocator(
- new Integer(port), expectedExceptions ));
+ locatorVM.invoke(() -> stopLocator(port, ignoredExceptions));
}
}
- protected void createDS(final VM peer2, Properties props,
- Properties javaProps) {
- peer2.invoke(() -> P2PAuthenticationDUnitTest.createDS(
- props, javaProps ));
- }
-
/**
* The strategy is to test credential size greater than UDP datagram size.
*
@@ -479,119 +434,103 @@ public class P2PAuthenticationDUnitTest extends DistributedTestCase {
* from the first peer. Number of members in the DS
* should be four
*/
+ @Test
public void testP2PLargeCredentialSucceeds() throws Exception {
+ int locatorPort = getRandomAvailablePort(SOCKET);
- 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();
+
+ assertNotNull(gen.getAuthenticator());
+ assertNull(gen.getJavaProperties());
+ assertNull(gen.getSystemProperties());
+ assertNotNull(gen.getValidCredentials(1));
+
String authInit = UserPasswordWithExtraPropsAuthInit.class.getName() + ".create";
- if (extraProps == null) {
- extraProps = new Properties();
- }
+ Properties credentials = gen.getValidCredentials(1);
- // Start the locator with the Dummy authenticator
Properties props = new Properties();
- int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- final String locators = NetworkUtils.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.setProperty(SECURITY_PEER_AUTH_INIT_NAME, authInit);
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
props.putAll(credentials);
- props.putAll(extraProps);
- startLocator(props, javaProps, port);
+
+ startTheLocator(props, null, locatorPort);
+
try {
+ // Start the first peer with huge credentials
+ props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"["+locatorPort+"]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, authInit);
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
+
+ String hugeStr = "20KString";
+ for (int i = 0; i <= 20000; i++) {
+ hugeStr += "A";
+ }
- // 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);
+ credentials = gen.getValidCredentials(3);
+ 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);
+ props.putAll(credentials);
- LogWriter dsLogger = LogWriterUtils.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);
- }
+ createDS(props, null);
+ // fail("AuthenticationFailedException was expected as credentials were passed beyond 50k"); --?
- // 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);
- createDS(peer2, props, javaProps);
+ // Start the second peer with the same authenticator as locator
+ props = new Properties();
+ props.setProperty(MCAST_PORT_NAME, "0");
+ props.setProperty(LOCATORS_NAME, getIPLiteral() +"["+locatorPort+"]");
+ props.setProperty(SECURITY_PEER_AUTH_INIT_NAME, authInit);
+ props.setProperty(SECURITY_PEER_AUTHENTICATOR_NAME, gen.getAuthenticator());
+
+ credentials = gen.getValidCredentials(7);
+ props.putAll(credentials);
- createDS(peer3, props, javaProps);
+ createDS(peer2, props, null);
+ createDS(peer3, props, null);
- // wait for view propagation
- Wait.pause(2000);
- // Verify the number of members on all peers and locator
- locatorVM.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(4) ));
- peer2.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(4) ));
- peer3.invoke(() -> P2PAuthenticationDUnitTest.verifyMembers( new Integer(4) ));
+ // wait for view propagation
+ pause(2000);
+ // Verify the number of members on all peers and locator
+ locatorVM.invoke(() -> verifyMembers(4));
+ peer2.invoke(() -> verifyMembers(4));
+ peer3.invoke(() -> verifyMembers(4));
- // Disconnect the peers
- disconnectFromDS();
- peer2.invoke(() -> DistributedTestCase.disconnectFromDS());
- peer3.invoke(() -> DistributedTestCase.disconnectFromDS());
+ // Disconnect the peers
+ disconnectFromDS();
+ peer2.invoke(() -> disconnectFromDS());
+ peer3.invoke(() -> disconnectFromDS());
} finally {
- // Stopping the locator
- locatorVM.invoke(() -> SecurityTestUtil.stopLocator(
- new Integer(port), expectedExceptions ));
+ locatorVM.invoke(() -> stopLocator(locatorPort, ignoredExceptions));
}
}
- public static void createDS(Properties props, Object javaProps) {
+ private void createDS(final VM peer2, final Properties props, final Properties javaProps) {
+ peer2.invoke(() -> createDS(props, javaProps));
+ }
- SecurityTestUtil tmpUtil = new SecurityTestUtil("tmp");
- tmpUtil.createSystem(props, (Properties)javaProps);
+ private void startTheLocator(final Properties props, final Properties javaProps, final int port) {
+ locatorVM.invoke(() -> startLocator(getUniqueName(), port, props, javaProps, ignoredExceptions));
}
- public static void verifyMembers(Integer numExpectedMembers) {
+ private static void createDS(final Properties props, final Properties javaProps) {
+ SecurityTestUtils tmpUtil = new SecurityTestUtils("tmp");
+ tmpUtil.createSystem(props, javaProps);
+ }
+ private static void verifyMembers(final int numExpectedMembers) {
DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
- MembershipManager mgr = MembershipManagerHelper
- .getMembershipManager(ds);
- assertEquals(numExpectedMembers.intValue(), mgr.getView().size());
+ MembershipManager mgr = MembershipManagerHelper.getMembershipManager(ds);
+ assertEquals(numExpectedMembers, mgr.getView().size());
}
-
}