You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by nn...@apache.org on 2018/08/28 08:12:03 UTC

[geode] branch develop updated: GEODE-5618: Auth Attributes in FunctionService (#2360)

This is an automated email from the ASF dual-hosted git repository.

nnag pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git


The following commit(s) were added to refs/heads/develop by this push:
     new 60ea939  GEODE-5618: Auth Attributes in FunctionService (#2360)
60ea939 is described below

commit 60ea939e85e7d94da9d8eb64d5b88dd62edb2618
Author: Juan José Ramos <ju...@users.noreply.github.com>
AuthorDate: Tue Aug 28 09:11:50 2018 +0100

    GEODE-5618: Auth Attributes in FunctionService (#2360)
    
       * When a client executes a function using the id instead of the actual instance, an internal invocation to the `GetFunctionAttributeOp` function is executed to get the metadata about the original function itself. This invocation doesn't set the user attributes requried by the authentication mechanism, so the entire invocation fails.
       * Added distributed tests.
       * Classes `ServerFunctionExecutor` and `ServerRegionFunctionExecutor` now set the `userAttributes` in the local thread before getting the metadata when the function is executed by id.
---
 ...UserAuthenticationFunctionServiceDUnitTest.java | 183 +++++++++++++++++++++
 .../cache/execute/ServerFunctionExecutor.java      |  43 +++--
 .../execute/ServerRegionFunctionExecutor.java      |  42 +++--
 3 files changed, 234 insertions(+), 34 deletions(-)

diff --git a/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/execute/MultiUserAuthenticationFunctionServiceDUnitTest.java b/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/execute/MultiUserAuthenticationFunctionServiceDUnitTest.java
new file mode 100644
index 0000000..e45dbe5
--- /dev/null
+++ b/geode-core/src/distributedTest/java/org/apache/geode/internal/cache/execute/MultiUserAuthenticationFunctionServiceDUnitTest.java
@@ -0,0 +1,183 @@
+/*
+ * 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 org.apache.geode.internal.cache.execute;
+
+import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_CLIENT_AUTH_INIT;
+import static org.apache.geode.distributed.ConfigurationProperties.SECURITY_MANAGER;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.Properties;
+
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.DataSerializable;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionService;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
+import org.apache.geode.cache.client.ServerOperationException;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.examples.SimpleSecurityManager;
+import org.apache.geode.security.NotAuthorizedException;
+import org.apache.geode.security.templates.UserPasswordAuthInit;
+import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
+import org.apache.geode.test.junit.categories.FunctionServiceTest;
+import org.apache.geode.test.junit.categories.SecurityTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
+
+@Category({SecurityTest.class, FunctionServiceTest.class})
+public class MultiUserAuthenticationFunctionServiceDUnitTest {
+  private static MemberVM locator, server;
+  private static Properties clientProperties;
+
+  @ClassRule
+  public static GfshCommandRule gfsh = new GfshCommandRule();
+
+  @ClassRule
+  public static ClusterStartupRule lsRule = new ClusterStartupRule();
+
+  @BeforeClass
+  public static void beforeClass() throws Exception {
+    IgnoredException.addIgnoredException("org.apache.geode.security.AuthenticationFailedException");
+
+    // Start Cluster
+    Properties locatorProps = new Properties();
+    locatorProps.setProperty(SECURITY_MANAGER, SimpleSecurityManager.class.getCanonicalName());
+    locator = lsRule.startLocatorVM(0, locatorProps);
+    Properties serverProps = new Properties();
+    serverProps.setProperty("security-username", "cluster");
+    serverProps.setProperty("security-password", "cluster");
+    server = lsRule.startServerVM(1, serverProps, locator.getPort());
+
+    // Create region and deploy function
+    gfsh.connectAndVerify(locator);
+    server.invoke(() -> FunctionService.registerFunction(new TestFunction()));
+    locator.invoke(() -> FunctionService.registerFunction(new TestFunction()));
+    gfsh.executeAndAssertThat("create region --name=testRegion --type=REPLICATE").statusIsSuccess();
+    gfsh.executeAndAssertThat("execute function --id=TestFunction").statusIsSuccess()
+        .containsOutput("TestFunction Executed!");
+
+    // Default Client Properties
+    clientProperties = new Properties();
+    clientProperties.setProperty(UserPasswordAuthInit.USER_NAME, "stranger");
+    clientProperties.setProperty(UserPasswordAuthInit.PASSWORD, "stranger");
+    clientProperties.setProperty(SECURITY_CLIENT_AUTH_INIT, UserPasswordAuthInit.class.getName());
+    clientProperties.setProperty(LOCATORS, "");
+    clientProperties.setProperty(MCAST_PORT, "0");
+  }
+
+  static Properties getClientSecurityProperties(String username, String password) {
+    Properties properties = new Properties(clientProperties);
+    properties.setProperty(UserPasswordAuthInit.USER_NAME, username);
+    properties.setProperty(UserPasswordAuthInit.PASSWORD, password);
+
+    return properties;
+  }
+
+  @Test
+  public void multiUserAuthenticatedFunctionExecutionsOnServerShouldBeAuthorizedByServers() {
+    int locatorPort = locator.getPort();
+    ClientCache clientCache = new ClientCacheFactory(clientProperties)
+        .setPoolMultiuserAuthentication(true).addPoolLocator("localhost", locatorPort).create();
+    RegionService authorizedRegionService =
+        clientCache.createAuthenticatedView(getClientSecurityProperties("data", "data"));
+    RegionService unauthorizedRegionService =
+        clientCache.createAuthenticatedView(getClientSecurityProperties("cluster", "cluster"));
+
+    assertThat(FunctionService.onServer(authorizedRegionService).execute(new TestFunction())
+        .getResult().toString()).isEqualTo("[TestFunction Executed!]");
+    assertThat(FunctionService.onServer(authorizedRegionService).execute("TestFunction").getResult()
+        .toString()).isEqualTo("[TestFunction Executed!]");
+
+    assertThatThrownBy(
+        () -> FunctionService.onServer(unauthorizedRegionService).execute(new TestFunction()))
+            .isInstanceOf(ServerOperationException.class)
+            .hasCauseExactlyInstanceOf(NotAuthorizedException.class);
+    assertThatThrownBy(
+        () -> FunctionService.onServer(unauthorizedRegionService).execute("TestFunction"))
+            .isInstanceOf(ServerOperationException.class)
+            .hasCauseExactlyInstanceOf(NotAuthorizedException.class);
+
+    authorizedRegionService.close();
+    unauthorizedRegionService.close();
+    clientCache.close();
+  }
+
+  @Test
+  public void multiUserAuthenticatedFunctionExecutionsOnRegionShouldBeAuthorizedByServers() {
+    int locatorPort = locator.getPort();
+    ClientCache clientCache = new ClientCacheFactory(clientProperties)
+        .setPoolMultiuserAuthentication(true).addPoolLocator("localhost", locatorPort).create();
+    clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).create("testRegion");
+    RegionService authorizedRegionService =
+        clientCache.createAuthenticatedView(getClientSecurityProperties("data", "data"));
+    RegionService unauthorizedRegionService =
+        clientCache.createAuthenticatedView(getClientSecurityProperties("cluster", "cluster"));
+    Region authorizedRegion = authorizedRegionService.getRegion("testRegion");
+    Region unauthorizedRegion = unauthorizedRegionService.getRegion("testRegion");
+
+    assertThat(FunctionService.onRegion(authorizedRegion).execute(new TestFunction()).getResult()
+        .toString()).isEqualTo("[TestFunction Executed!]");
+    assertThat(
+        FunctionService.onRegion(authorizedRegion).execute("TestFunction").getResult().toString())
+            .isEqualTo("[TestFunction Executed!]");
+    assertThatThrownBy(
+        () -> FunctionService.onRegion(unauthorizedRegion).execute(new TestFunction()))
+            .isInstanceOf(FunctionException.class)
+            .hasCauseExactlyInstanceOf(ServerOperationException.class)
+            .hasMessageContaining("NotAuthorizedException");
+    assertThatThrownBy(() -> FunctionService.onRegion(unauthorizedRegion).execute("TestFunction"))
+        .isInstanceOf(FunctionException.class)
+        .hasCauseExactlyInstanceOf(ServerOperationException.class)
+        .hasMessageContaining("NotAuthorizedException");
+
+    authorizedRegionService.close();
+    unauthorizedRegionService.close();
+    clientCache.close();
+  }
+
+  public static class TestFunction implements Function, DataSerializable {
+    @SuppressWarnings("unchecked")
+    public void execute(FunctionContext context) {
+      context.getResultSender().lastResult("TestFunction Executed!");
+    }
+
+    @Override
+    public String getId() {
+      return getClass().getSimpleName();
+    }
+
+    @Override
+    public void toData(DataOutput out) throws IOException {}
+
+    @Override
+    public void fromData(DataInput in) throws IOException, ClassNotFoundException {}
+  }
+}
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerFunctionExecutor.java b/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerFunctionExecutor.java
index b08e11e..5e4d930 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerFunctionExecutor.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerFunctionExecutor.java
@@ -228,10 +228,7 @@ public class ServerFunctionExecutor extends AbstractExecution {
     return this.pool;
   }
 
-  public boolean getAllServers() {
-    return this.allServers;
-  }
-
+  @Override
   public Execution withFilter(Set filter) {
     throw new FunctionException(
         LocalizedStrings.ExecuteFunction_CANNOT_SPECIFY_0_FOR_DATA_INDEPENDENT_FUNCTIONS
@@ -255,10 +252,12 @@ public class ServerFunctionExecutor extends AbstractExecution {
     return new ServerFunctionExecutor(this, args);
   }
 
+  @Override
   public Execution withArgs(Object args) {
     return setArguments(args);
   }
 
+  @Override
   public Execution withCollector(ResultCollector rs) {
     if (rs == null) {
       throw new FunctionException(
@@ -268,6 +267,7 @@ public class ServerFunctionExecutor extends AbstractExecution {
     return new ServerFunctionExecutor(this, rs);
   }
 
+  @Override
   public InternalExecution withMemberMappedArgument(MemberMappedArgument argument) {
     if (argument == null) {
       throw new FunctionException(
@@ -277,13 +277,6 @@ public class ServerFunctionExecutor extends AbstractExecution {
     return new ServerFunctionExecutor(this, argument);
   }
 
-  /*
-   * (non-Javadoc)
-   *
-   * @see
-   * org.apache.geode.internal.cache.execute.AbstractExecution#validateExecution(org.apache.geode.
-   * cache.execute.Function, java.util.Set)
-   */
   @Override
   public void validateExecution(Function function, Set targetMembers) {
     if (TXManagerImpl.getCurrentTXUniqueId() != TXManagerImpl.NOTX) {
@@ -291,6 +284,7 @@ public class ServerFunctionExecutor extends AbstractExecution {
     }
   }
 
+  @Override
   public ResultCollector execute(final String functionName) {
     if (functionName == null) {
       throw new FunctionException(
@@ -301,18 +295,31 @@ public class ServerFunctionExecutor extends AbstractExecution {
     Function functionObject = FunctionService.getFunction(functionName);
     if (functionObject == null) {
       byte[] functionAttributes = getFunctionAttributes(functionName);
+
       if (functionAttributes == null) {
-        Object obj = GetFunctionAttributeOp.execute(this.pool, functionName);
-        functionAttributes = (byte[]) obj;
-        addFunctionAttributes(functionName, functionAttributes);
+        // GEODE-5618: Set authentication properties before executing the internal function.
+        try {
+          if (proxyCache != null) {
+            if (this.proxyCache.isClosed()) {
+              throw proxyCache.getCacheClosedException("Cache is closed for this user.");
+            }
+            UserAttributes.userAttributes.set(this.proxyCache.getUserAttributes());
+          }
+
+          Object obj = GetFunctionAttributeOp.execute(this.pool, functionName);
+          functionAttributes = (byte[]) obj;
+          addFunctionAttributes(functionName, functionAttributes);
+        } finally {
+          UserAttributes.userAttributes.set(null);
+        }
       }
-      boolean hasResult = ((functionAttributes[0] == 1) ? true : false);
-      boolean isHA = ((functionAttributes[1] == 1) ? true : false);
-      boolean optimizeForWrite = ((functionAttributes[2] == 1) ? true : false);
+
+      boolean isHA = functionAttributes[1] == 1;
+      boolean hasResult = functionAttributes[0] == 1;
+      boolean optimizeForWrite = functionAttributes[2] == 1;
       return executeFunction(functionName, hasResult, isHA, optimizeForWrite);
     } else {
       return executeFunction(functionObject);
     }
   }
-
 }
diff --git a/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerRegionFunctionExecutor.java b/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerRegionFunctionExecutor.java
index d5a17eb..cf1d4c8 100755
--- a/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerRegionFunctionExecutor.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/cache/execute/ServerRegionFunctionExecutor.java
@@ -57,15 +57,6 @@ public class ServerRegionFunctionExecutor extends AbstractExecution {
     this.proxyCache = proxyCache;
   }
 
-  // private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor sre) {
-  // super(sre);
-  // this.region = sre.region;
-  // if (sre.filter != null) {
-  // this.filter.clear();
-  // this.filter.addAll(sre.filter);
-  // }
-  // }
-
   private ServerRegionFunctionExecutor(ServerRegionFunctionExecutor serverRegionFunctionExecutor,
       Object args) {
     super(serverRegionFunctionExecutor);
@@ -122,6 +113,7 @@ public class ServerRegionFunctionExecutor extends AbstractExecution {
     this.executeOnBucketSet = executeOnBucketSet;
   }
 
+  @Override
   public Execution withFilter(Set fltr) {
     if (fltr == null) {
       throw new FunctionException(
@@ -132,6 +124,7 @@ public class ServerRegionFunctionExecutor extends AbstractExecution {
     return new ServerRegionFunctionExecutor(this, fltr);
   }
 
+  @Override
   public InternalExecution withBucketFilter(Set<Integer> bucketIDs) {
     if (bucketIDs == null) {
       throw new FunctionException(
@@ -316,10 +309,12 @@ public class ServerRegionFunctionExecutor extends AbstractExecution {
     return new ServerRegionFunctionExecutor(this, args);
   }
 
+  @Override
   public Execution withArgs(Object args) {
     return setArguments(args);
   }
 
+  @Override
   public Execution withCollector(ResultCollector rs) {
     if (rs == null) {
       throw new FunctionException(
@@ -329,6 +324,7 @@ public class ServerRegionFunctionExecutor extends AbstractExecution {
     return new ServerRegionFunctionExecutor(this, rs);
   }
 
+  @Override
   public InternalExecution withMemberMappedArgument(MemberMappedArgument argument) {
     if (argument == null) {
       throw new FunctionException(
@@ -359,15 +355,29 @@ public class ServerRegionFunctionExecutor extends AbstractExecution {
     Function functionObject = FunctionService.getFunction(functionName);
     if (functionObject == null) {
       byte[] functionAttributes = getFunctionAttributes(functionName);
+
       if (functionAttributes == null) {
-        ServerRegionProxy srp = getServerRegionProxy();
-        Object obj = srp.getFunctionAttributes(functionName);
-        functionAttributes = (byte[]) obj;
-        addFunctionAttributes(functionName, functionAttributes);
+        // GEODE-5618: Set authentication properties before executing the internal function.
+        try {
+          if (proxyCache != null) {
+            if (this.proxyCache.isClosed()) {
+              throw proxyCache.getCacheClosedException("Cache is closed for this user.");
+            }
+            UserAttributes.userAttributes.set(this.proxyCache.getUserAttributes());
+          }
+
+          ServerRegionProxy srp = getServerRegionProxy();
+          Object obj = srp.getFunctionAttributes(functionName);
+          functionAttributes = (byte[]) obj;
+          addFunctionAttributes(functionName, functionAttributes);
+        } finally {
+          UserAttributes.userAttributes.set(null);
+        }
       }
-      boolean hasResult = ((functionAttributes[0] == 1) ? true : false);
-      boolean isHA = ((functionAttributes[1] == 1) ? true : false);
-      boolean optimizeForWrite = ((functionAttributes[2] == 1) ? true : false);
+
+      boolean isHA = functionAttributes[1] == 1;
+      boolean hasResult = functionAttributes[0] == 1;
+      boolean optimizeForWrite = functionAttributes[2] == 1;
       return executeFunction(functionName, hasResult, isHA, optimizeForWrite);
     } else {
       return executeFunction(functionObject);