Search in sources :

Example 56 with NotAuthorizedException

use of org.apache.geode.security.NotAuthorizedException in project geode by apache.

the class Put65Test method oldSecurityShouldFailIfNotAuthorized.

@Test
public void oldSecurityShouldFailIfNotAuthorized() throws Exception {
    when(this.securityService.isClientSecurityRequired()).thenReturn(true);
    when(this.securityService.isIntegratedSecurity()).thenReturn(false);
    doThrow(new NotAuthorizedException("")).when(this.authzRequest).putAuthorize(eq(REGION_NAME), eq(KEY), eq(VALUE), eq(true), eq(CALLBACK_ARG));
    this.put65.cmdExecute(this.message, this.serverConnection, 0);
    verify(this.authzRequest).putAuthorize(eq(REGION_NAME), eq(KEY), eq(VALUE), eq(true), eq(CALLBACK_ARG));
    ArgumentCaptor<NotAuthorizedException> argument = ArgumentCaptor.forClass(NotAuthorizedException.class);
    verify(this.errorResponseMessage).addObjPart(argument.capture());
    assertThat(argument.getValue()).isExactlyInstanceOf(NotAuthorizedException.class);
    verify(this.errorResponseMessage).send(this.serverConnection);
}
Also used : NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 57 with NotAuthorizedException

use of org.apache.geode.security.NotAuthorizedException in project geode by apache.

the class PutTest method integratedSecurityShouldThrowIfNotAuthorized.

@Test
public void integratedSecurityShouldThrowIfNotAuthorized() throws Exception {
    when(this.securityService.isClientSecurityRequired()).thenReturn(true);
    when(this.securityService.isIntegratedSecurity()).thenReturn(true);
    doThrow(new NotAuthorizedException("")).when(this.securityService).authorizeRegionWrite(eq(REGION_NAME), eq(KEY));
    this.put.cmdExecute(this.message, this.serverConnection, 0);
    verify(this.securityService).authorizeRegionWrite(eq(REGION_NAME), eq(KEY));
    verify(this.errorResponseMessage).send(this.serverConnection);
}
Also used : NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 58 with NotAuthorizedException

use of org.apache.geode.security.NotAuthorizedException in project geode by apache.

the class RegisterInterest61Test method oldSecurityShouldFailIfNotAuthorized.

@Test
public void oldSecurityShouldFailIfNotAuthorized() throws Exception {
    when(this.securityService.isClientSecurityRequired()).thenReturn(true);
    when(this.securityService.isIntegratedSecurity()).thenReturn(false);
    doThrow(new NotAuthorizedException("")).when(this.authzRequest).registerInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt(), any());
    this.registerInterest61.cmdExecute(this.message, this.serverConnection, 0);
    verify(this.authzRequest).registerInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt(), any());
    ArgumentCaptor<NotAuthorizedException> argument = ArgumentCaptor.forClass(NotAuthorizedException.class);
    verify(this.chunkedResponseMessage).addObjPart(argument.capture());
    assertThat(argument.getValue()).isExactlyInstanceOf(NotAuthorizedException.class);
    verify(this.chunkedResponseMessage).sendChunk(this.serverConnection);
}
Also used : NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) UnitTest(org.apache.geode.test.junit.categories.UnitTest) Test(org.junit.Test)

Example 59 with NotAuthorizedException

use of org.apache.geode.security.NotAuthorizedException in project geode by apache.

the class XmlAuthorization method init.

/**
   * Cache authorization information for all users statically. This method is not thread-safe and is
   * should either be invoked only once, or the caller should take the appropriate locks.
   *
   * @param cache reference to the cache object for the distributed system
   */
private static void init(final Cache cache) throws NotAuthorizedException {
    final LogWriter systemLogWriter = cache.getLogger();
    final String xmlDocumentUri = (String) cache.getDistributedSystem().getSecurityProperties().get(DOC_URI_PROP_NAME);
    try {
        if (xmlDocumentUri == null) {
            throw new NotAuthorizedException("No ACL file defined using tag [" + DOC_URI_PROP_NAME + "] in system properties");
        }
        if (xmlDocumentUri.equals(XmlAuthorization.currentDocUri)) {
            if (XmlAuthorization.xmlLoadFailure != null) {
                throw XmlAuthorization.xmlLoadFailure;
            }
            return;
        }
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setValidating(true);
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final XmlErrorHandler errorHandler = new XmlErrorHandler(systemLogWriter, xmlDocumentUri);
        builder.setErrorHandler(errorHandler);
        builder.setEntityResolver(new AuthzDtdResolver());
        final Document xmlDocument = builder.parse(xmlDocumentUri);
        XmlAuthorization.userRoles = new HashMap<String, HashSet<String>>();
        XmlAuthorization.rolePermissions = new HashMap<String, Map<String, Map<OperationCode, FunctionSecurityPrmsHolder>>>();
        final NodeList roleUserNodes = xmlDocument.getElementsByTagName(TAG_ROLE);
        for (int roleIndex = 0; roleIndex < roleUserNodes.getLength(); roleIndex++) {
            final Node roleUserNode = roleUserNodes.item(roleIndex);
            final String roleName = getAttributeValue(roleUserNode, ATTR_ROLENAME);
            final NodeList userNodes = roleUserNode.getChildNodes();
            for (int userIndex = 0; userIndex < userNodes.getLength(); userIndex++) {
                final Node userNode = userNodes.item(userIndex);
                if (TAG_USER.equals(userNode.getNodeName())) {
                    final String userName = getNodeValue(userNode);
                    HashSet<String> userRoleSet = XmlAuthorization.userRoles.get(userName);
                    if (userRoleSet == null) {
                        userRoleSet = new HashSet<String>();
                        XmlAuthorization.userRoles.put(userName, userRoleSet);
                    }
                    userRoleSet.add(roleName);
                } else {
                    throw new SAXParseException("Unknown tag [" + userNode.getNodeName() + "] as child of tag [" + TAG_ROLE + ']', null);
                }
            }
        }
        final NodeList rolePermissionNodes = xmlDocument.getElementsByTagName(TAG_PERMS);
        for (int permIndex = 0; permIndex < rolePermissionNodes.getLength(); permIndex++) {
            final Node rolePermissionNode = rolePermissionNodes.item(permIndex);
            final String roleName = getAttributeValue(rolePermissionNode, ATTR_ROLE);
            Map<String, Map<OperationCode, FunctionSecurityPrmsHolder>> regionOperationMap = XmlAuthorization.rolePermissions.get(roleName);
            if (regionOperationMap == null) {
                regionOperationMap = new HashMap<String, Map<OperationCode, FunctionSecurityPrmsHolder>>();
                XmlAuthorization.rolePermissions.put(roleName, regionOperationMap);
            }
            final NodeList operationNodes = rolePermissionNode.getChildNodes();
            final HashMap<OperationCode, FunctionSecurityPrmsHolder> operationMap = new HashMap<OperationCode, FunctionSecurityPrmsHolder>();
            for (int opIndex = 0; opIndex < operationNodes.getLength(); opIndex++) {
                final Node operationNode = operationNodes.item(opIndex);
                if (TAG_OP.equals(operationNode.getNodeName())) {
                    final String operationName = getNodeValue(operationNode);
                    final OperationCode code = OperationCode.valueOf(operationName);
                    if (code == null) {
                        throw new SAXParseException("Unknown operation [" + operationName + ']', null);
                    }
                    if (code != OperationCode.EXECUTE_FUNCTION) {
                        operationMap.put(code, null);
                    } else {
                        final String optimizeForWrite = getAttributeValue(operationNode, ATTR_FUNCTION_OPTIMIZE_FOR_WRITE);
                        final String functionAttr = getAttributeValue(operationNode, ATTR_FUNCTION_IDS);
                        final String keysAttr = getAttributeValue(operationNode, ATTR_FUNCTION_KEY_SET);
                        Boolean isOptimizeForWrite;
                        HashSet<String> functionIds;
                        HashSet<String> keySet;
                        if (optimizeForWrite == null || optimizeForWrite.length() == 0) {
                            isOptimizeForWrite = null;
                        } else {
                            isOptimizeForWrite = Boolean.parseBoolean(optimizeForWrite);
                        }
                        if (functionAttr == null || functionAttr.length() == 0) {
                            functionIds = null;
                        } else {
                            final String[] functionArray = functionAttr.split(",");
                            functionIds = new HashSet<String>();
                            for (int strIndex = 0; strIndex < functionArray.length; ++strIndex) {
                                functionIds.add((functionArray[strIndex]));
                            }
                        }
                        if (keysAttr == null || keysAttr.length() == 0) {
                            keySet = null;
                        } else {
                            final String[] keySetArray = keysAttr.split(",");
                            keySet = new HashSet<String>();
                            for (int strIndex = 0; strIndex < keySetArray.length; ++strIndex) {
                                keySet.add((keySetArray[strIndex]));
                            }
                        }
                        final FunctionSecurityPrmsHolder functionContext = new FunctionSecurityPrmsHolder(isOptimizeForWrite, functionIds, keySet);
                        operationMap.put(code, functionContext);
                    }
                } else {
                    throw new SAXParseException("Unknown tag [" + operationNode.getNodeName() + "] as child of tag [" + TAG_PERMS + ']', null);
                }
            }
            final String regionNames = getAttributeValue(rolePermissionNode, ATTR_REGIONS);
            if (regionNames == null || regionNames.length() == 0) {
                regionOperationMap.put(EMPTY_VALUE, operationMap);
            } else {
                final String[] regionNamesSplit = regionNames.split(",");
                for (int strIndex = 0; strIndex < regionNamesSplit.length; ++strIndex) {
                    regionOperationMap.put(normalizeRegionName(regionNamesSplit[strIndex]), operationMap);
                }
            }
        }
        XmlAuthorization.currentDocUri = xmlDocumentUri;
    } catch (Exception ex) {
        String message;
        if (ex instanceof NotAuthorizedException) {
            message = ex.getMessage();
        } else {
            message = ex.getClass().getName() + ": " + ex.getMessage();
        }
        systemLogWriter.warning("XmlAuthorization.init: " + message);
        XmlAuthorization.xmlLoadFailure = new NotAuthorizedException(message, ex);
        throw XmlAuthorization.xmlLoadFailure;
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) HashMap(java.util.HashMap) OperationCode(org.apache.geode.cache.operations.OperationContext.OperationCode) Node(org.w3c.dom.Node) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) Document(org.w3c.dom.Document) SAXParseException(org.xml.sax.SAXParseException) HashSet(java.util.HashSet) NodeList(org.w3c.dom.NodeList) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) LogWriter(org.apache.geode.LogWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) HashMap(java.util.HashMap) Map(java.util.Map) NamedNodeMap(org.w3c.dom.NamedNodeMap)

Example 60 with NotAuthorizedException

use of org.apache.geode.security.NotAuthorizedException in project geode by apache.

the class DeployCommands method deploy.

/**
   * Deploy one or more JAR files to members of a group or all members.
   * 
   * @param groups Group(s) to deploy the JAR to or null for all members
   * @param jar JAR file to deploy
   * @param dir Directory of JAR files to deploy
   * @return The result of the attempt to deploy
   */
@CliCommand(value = { CliStrings.DEPLOY }, help = CliStrings.DEPLOY__HELP)
@CliMetaData(interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommands$Interceptor", relatedTopic = { CliStrings.TOPIC_GEODE_CONFIG })
public Result deploy(@CliOption(key = { CliStrings.DEPLOY__GROUP }, help = CliStrings.DEPLOY__GROUP__HELP, optionContext = ConverterHint.MEMBERGROUP) String[] groups, @CliOption(key = { CliStrings.DEPLOY__JAR }, help = CliStrings.DEPLOY__JAR__HELP) String jar, @CliOption(key = { CliStrings.DEPLOY__DIR }, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
    try {
        // since deploy function can potentially do a lot of damage to security, this action should
        // require these following privileges
        SecurityService securityService = SecurityService.getSecurityService();
        securityService.authorizeClusterManage();
        securityService.authorizeClusterWrite();
        securityService.authorizeDataManage();
        securityService.authorizeDataWrite();
        TabularResultData tabularData = ResultBuilder.createTabularResultData();
        byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
        String[] jarNames = CliUtil.bytesToNames(shellBytesData);
        byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
        Set<DistributedMember> targetMembers;
        targetMembers = CliUtil.findMembers(groups, null);
        if (targetMembers.size() > 0) {
            // this deploys the jars to all the matching servers
            ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction, new Object[] { jarNames, jarBytes }, targetMembers);
            List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
            for (CliFunctionResult result : results) {
                if (result.getThrowable() != null) {
                    tabularData.accumulate("Member", result.getMemberIdOrName());
                    tabularData.accumulate("Deployed JAR", "");
                    tabularData.accumulate("Deployed JAR Location", "ERROR: " + result.getThrowable().getClass().getName() + ": " + result.getThrowable().getMessage());
                    tabularData.setStatus(Status.ERROR);
                } else {
                    String[] strings = (String[]) result.getSerializables();
                    for (int i = 0; i < strings.length; i += 2) {
                        tabularData.accumulate("Member", result.getMemberIdOrName());
                        tabularData.accumulate("Deployed JAR", strings[i]);
                        tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
                    }
                }
            }
        }
        Result result = ResultBuilder.buildResult(tabularData);
        persistClusterConfiguration(result, () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
        return result;
    } catch (NotAuthorizedException e) {
        // for NotAuthorizedException, will catch this later in the code
        throw e;
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable t) {
        SystemFailure.checkFailure();
        return ResultBuilder.createGemFireErrorResult(String.format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
    }
}
Also used : TabularResultData(org.apache.geode.management.internal.cli.result.TabularResultData) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) ConverterHint(org.apache.geode.management.cli.ConverterHint) GfshParseResult(org.apache.geode.management.internal.cli.GfshParseResult) Result(org.apache.geode.management.cli.Result) FileResult(org.apache.geode.management.internal.cli.result.FileResult) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) CliFunctionResult(org.apache.geode.management.internal.cli.functions.CliFunctionResult) SecurityService(org.apache.geode.internal.security.SecurityService) DistributedMember(org.apache.geode.distributed.DistributedMember) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData)

Aggregations

NotAuthorizedException (org.apache.geode.security.NotAuthorizedException)75 UnitTest (org.apache.geode.test.junit.categories.UnitTest)54 Test (org.junit.Test)54 AuthorizeRequest (org.apache.geode.internal.security.AuthorizeRequest)12 IOException (java.io.IOException)9 ObjectPartList (org.apache.geode.internal.cache.tier.sockets.ObjectPartList)9 Part (org.apache.geode.internal.cache.tier.sockets.Part)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 GetOperationContext (org.apache.geode.cache.operations.GetOperationContext)6 AuthorizeRequestPP (org.apache.geode.internal.security.AuthorizeRequestPP)6 LocalRegion (org.apache.geode.internal.cache.LocalRegion)5 GetOperationContextImpl (org.apache.geode.cache.operations.internal.GetOperationContextImpl)4 StringId (org.apache.geode.i18n.StringId)4 CacheServerStats (org.apache.geode.internal.cache.tier.sockets.CacheServerStats)4 Result (org.apache.geode.management.cli.Result)4 HashSet (java.util.HashSet)3 Iterator (java.util.Iterator)3 Set (java.util.Set)3 Region (org.apache.geode.cache.Region)3 VersionTag (org.apache.geode.internal.cache.versions.VersionTag)3