Search in sources :

Example 21 with NotAuthorizedException

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

the class RequestTest method integratedSecurityShouldFailIfNotAuthorized.

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

Example 22 with NotAuthorizedException

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

the class UnregisterInterestTest 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).getAuthorize(eq(REGION_NAME), eq(KEY), any());
    this.unregisterInterest.cmdExecute(this.message, this.serverConnection, 0);
    verify(this.authzRequest).unregisterInterestAuthorize(eq(REGION_NAME), eq(KEY), anyInt());
    verify(this.replyMessage).send(eq(this.serverConnection));
}
Also used : NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) UnitTest(org.apache.geode.test.junit.categories.UnitTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 23 with NotAuthorizedException

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

the class Get70 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long startparam) throws IOException {
    long start = startparam;
    Part regionNamePart = null, keyPart = null, valuePart = null;
    String regionName = null;
    Object callbackArg = null, key = null;
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    StringId errMessage = null;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    // requiresResponse = true;
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadGetRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    int parts = clientMessage.getNumberOfParts();
    regionNamePart = clientMessage.getPart(0);
    keyPart = clientMessage.getPart(1);
    // valuePart = null; (redundant assignment)
    if (parts > 2) {
        valuePart = clientMessage.getPart(2);
        try {
            callbackArg = valuePart.getObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            // responded = true;
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    regionName = regionNamePart.getString();
    try {
        key = keyPart.getStringOrObject();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        // responded = true;
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received 7.0 get request ({} bytes) from {} for region {} key {} txId {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key, clientMessage.getTransactionId());
    }
    // Process the get request
    if (key == null || regionName == null) {
        if ((key == null) && (regionName == null)) {
            errMessage = LocalizedStrings.Request_THE_INPUT_REGION_NAME_AND_KEY_FOR_THE_GET_REQUEST_ARE_NULL;
        } else if (key == null) {
            errMessage = LocalizedStrings.Request_THE_INPUT_KEY_FOR_THE_GET_REQUEST_IS_NULL;
        } else if (regionName == null) {
            errMessage = LocalizedStrings.Request_THE_INPUT_REGION_NAME_FOR_THE_GET_REQUEST_IS_NULL;
        }
        String s = errMessage.toLocalizedString();
        logger.warn("{}: {}", serverConnection.getName(), s);
        writeErrorResponse(clientMessage, MessageType.REQUESTDATAERROR, s, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    Region region = serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.Request__0_WAS_NOT_FOUND_DURING_GET_REQUEST.toLocalizedString(regionName);
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    GetOperationContext getContext = null;
    try {
        // for integrated security
        this.securityService.authorizeRegionRead(regionName, key.toString());
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            getContext = authzRequest.getAuthorize(regionName, key, callbackArg);
            callbackArg = getContext.getCallbackArg();
        }
    } catch (NotAuthorizedException ex) {
        writeException(clientMessage, ex, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // Get the value and update the statistics. Do not deserialize
    // the value if it is a byte[].
    Entry entry;
    try {
        entry = getEntry(region, key, callbackArg, serverConnection);
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    @Retained final Object originalData = entry.value;
    Object data = originalData;
    try {
        boolean isObject = entry.isObject;
        VersionTag versionTag = entry.versionTag;
        boolean keyNotPresent = entry.keyNotPresent;
        try {
            AuthorizeRequestPP postAuthzRequest = serverConnection.getPostAuthzRequest();
            if (postAuthzRequest != null) {
                try {
                    getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
                    GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
                    Object newData = gci.getRawValue();
                    if (newData != data) {
                        // user changed the value
                        isObject = getContext.isObject();
                        data = newData;
                    }
                } finally {
                    if (getContext != null) {
                        ((GetOperationContextImpl) getContext).release();
                    }
                }
            }
        } catch (NotAuthorizedException ex) {
            writeException(clientMessage, ex, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        // post process
        data = this.securityService.postProcess(regionName, key, data, entry.isObject);
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessGetTime(start - oldStart);
        if (region instanceof PartitionedRegion) {
            PartitionedRegion pr = (PartitionedRegion) region;
            if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
                writeResponseWithRefreshMetadata(data, callbackArg, clientMessage, isObject, serverConnection, pr, pr.getNetworkHopType(), versionTag, keyNotPresent);
                pr.clearNetworkHopData();
            } else {
                writeResponse(data, callbackArg, clientMessage, isObject, versionTag, keyNotPresent, serverConnection);
            }
        } else {
            writeResponse(data, callbackArg, clientMessage, isObject, versionTag, keyNotPresent, serverConnection);
        }
    } finally {
        OffHeapHelper.release(originalData);
    }
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Wrote get response back to {} for region {} {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, entry);
    }
    stats.incWriteGetResponseTime(DistributionStats.getStatTime() - start);
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) AuthorizeRequestPP(org.apache.geode.internal.security.AuthorizeRequestPP) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) GetOperationContextImpl(org.apache.geode.cache.operations.internal.GetOperationContextImpl) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) IOException(java.io.IOException) GetOperationContext(org.apache.geode.cache.operations.GetOperationContext) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) StringId(org.apache.geode.i18n.StringId) Retained(org.apache.geode.internal.offheap.annotations.Retained) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) LocalRegion(org.apache.geode.internal.cache.LocalRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion)

Example 24 with NotAuthorizedException

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

the class GetAll70 method fillAndSendGetAllResponseChunks.

private void fillAndSendGetAllResponseChunks(Region region, String regionName, Object[] keys, ServerConnection servConn, boolean requestSerializedValues) throws IOException {
    // Interpret null keys object as a request to get all key,value entry pairs
    // of the region; otherwise iterate each key and perform the get behavior.
    Iterator allKeysIter;
    int numKeys;
    if (keys != null) {
        allKeysIter = null;
        numKeys = keys.length;
    } else {
        Set allKeys = region.keySet();
        allKeysIter = allKeys.iterator();
        numKeys = allKeys.size();
    }
    // Shouldn't it be 'keys != null' below?
    // The answer is no.
    // Note that the current implementation of client/server getAll the "keys" will always be
    // non-null.
    // The server callects and returns the values in the same order as the keys it received.
    // So the server does not need to send the keys back to the client.
    // When the client receives the server's "values" it calls setKeys using the key list the client
    // already has.
    // So the only reason we would tell the VersionedObjectList that it needs to track keys is if we
    // are running
    // in the old mode (which may be impossible since we only used that mode pre 7.0) in which the
    // client told us
    // to get and return all the keys and values. I think this was used for register interest.
    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, keys == null, region.getAttributes().getConcurrencyChecksEnabled(), requestSerializedValues);
    try {
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
        Get70 request = (Get70) Get70.getCommand();
        final boolean isDebugEnabled = logger.isDebugEnabled();
        for (int i = 0; i < numKeys; i++) {
            // Send the intermediate chunk if necessary
            if (values.size() == MAXIMUM_CHUNK_SIZE) {
                // Send the chunk and clear the list
                values.setKeys(null);
                sendGetAllResponseChunk(region, values, false, servConn);
                values.clear();
            }
            Object key;
            boolean keyNotPresent = false;
            if (keys != null) {
                key = keys[i];
            } else {
                key = allKeysIter.next();
            }
            if (isDebugEnabled) {
                logger.debug("{}: Getting value for key={}", servConn.getName(), key);
            }
            // Determine if the user authorized to get this key
            GetOperationContext getContext = null;
            if (authzRequest != null) {
                try {
                    getContext = authzRequest.getAuthorize(regionName, key, null);
                    if (isDebugEnabled) {
                        logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
                    }
                } catch (NotAuthorizedException ex) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                    values.addExceptionPart(key, ex);
                    continue;
                }
            }
            try {
                this.securityService.authorizeRegionRead(regionName, key.toString());
            } catch (NotAuthorizedException ex) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                values.addExceptionPart(key, ex);
                continue;
            }
            // Get the value and update the statistics. Do not deserialize
            // the value if it is a byte[].
            // Getting a value in serialized form is pretty nasty. I split this out
            // so the logic can be re-used by the CacheClientProxy.
            Get70.Entry entry = request.getEntry(region, key, null, servConn);
            @Retained final Object originalData = entry.value;
            Object data = originalData;
            if (logger.isDebugEnabled()) {
                logger.debug("retrieved key={} {}", key, entry);
            }
            boolean addedToValues = false;
            try {
                boolean isObject = entry.isObject;
                VersionTag versionTag = entry.versionTag;
                keyNotPresent = entry.keyNotPresent;
                if (postAuthzRequest != null) {
                    try {
                        getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
                        GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
                        Object newData = gci.getRawValue();
                        if (newData != data) {
                            // user changed the value
                            isObject = getContext.isObject();
                            data = newData;
                        }
                    } catch (NotAuthorizedException ex) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                        values.addExceptionPart(key, ex);
                        continue;
                    } finally {
                        if (getContext != null) {
                            ((GetOperationContextImpl) getContext).release();
                        }
                    }
                }
                data = this.securityService.postProcess(regionName, key, data, entry.isObject);
                // Add the entry to the list that will be returned to the client
                if (keyNotPresent) {
                    values.addObjectPartForAbsentKey(key, data, versionTag);
                    addedToValues = true;
                } else {
                    values.addObjectPart(key, data, isObject, versionTag);
                    addedToValues = true;
                }
            } finally {
                if (!addedToValues || data != originalData) {
                    OffHeapHelper.release(originalData);
                }
            }
        }
        // Send the last chunk even if the list is of zero size.
        if (Version.GFE_701.compareTo(servConn.getClientVersion()) <= 0) {
            // 7.0.1 and later clients do not expect the keys in the response
            values.setKeys(null);
        }
        sendGetAllResponseChunk(region, values, true, servConn);
        servConn.setAsTrue(RESPONDED);
    } finally {
        values.release();
    }
}
Also used : Set(java.util.Set) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) AuthorizeRequestPP(org.apache.geode.internal.security.AuthorizeRequestPP) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) GetOperationContextImpl(org.apache.geode.cache.operations.internal.GetOperationContextImpl) GetOperationContext(org.apache.geode.cache.operations.GetOperationContext) Retained(org.apache.geode.internal.offheap.annotations.Retained) Iterator(java.util.Iterator) VersionTag(org.apache.geode.internal.cache.versions.VersionTag)

Example 25 with NotAuthorizedException

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

the class GetAllWithCallback method fillAndSendGetAllResponseChunks.

private void fillAndSendGetAllResponseChunks(Region region, String regionName, Object[] keys, ServerConnection servConn, Object callback) throws IOException {
    assert keys != null;
    int numKeys = keys.length;
    VersionedObjectList values = new VersionedObjectList(MAXIMUM_CHUNK_SIZE, false, region.getAttributes().getConcurrencyChecksEnabled(), false);
    try {
        AuthorizeRequest authzRequest = servConn.getAuthzRequest();
        AuthorizeRequestPP postAuthzRequest = servConn.getPostAuthzRequest();
        Get70 request = (Get70) Get70.getCommand();
        for (int i = 0; i < numKeys; i++) {
            // Send the intermediate chunk if necessary
            if (values.size() == MAXIMUM_CHUNK_SIZE) {
                // Send the chunk and clear the list
                sendGetAllResponseChunk(region, values, false, servConn);
                values.clear();
            }
            Object key;
            boolean keyNotPresent = false;
            key = keys[i];
            if (logger.isDebugEnabled()) {
                logger.debug("{}: Getting value for key={}", servConn.getName(), key);
            }
            // Determine if the user authorized to get this key
            GetOperationContext getContext = null;
            if (authzRequest != null) {
                try {
                    getContext = authzRequest.getAuthorize(regionName, key, callback);
                    if (logger.isDebugEnabled()) {
                        logger.debug("{}: Passed GET pre-authorization for key={}", servConn.getName(), key);
                    }
                } catch (NotAuthorizedException ex) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                    values.addExceptionPart(key, ex);
                    continue;
                }
            }
            try {
                this.securityService.authorizeRegionRead(regionName, key.toString());
            } catch (NotAuthorizedException ex) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                values.addExceptionPart(key, ex);
                continue;
            }
            // Get the value and update the statistics. Do not deserialize
            // the value if it is a byte[].
            // Getting a value in serialized form is pretty nasty. I split this out
            // so the logic can be re-used by the CacheClientProxy.
            Get70.Entry entry = request.getEntry(region, key, callback, servConn);
            @Retained final Object originalData = entry.value;
            Object data = originalData;
            if (logger.isDebugEnabled()) {
                logger.debug("retrieved key={} {}", key, entry);
            }
            boolean addedToValues = false;
            try {
                boolean isObject = entry.isObject;
                VersionTag versionTag = entry.versionTag;
                keyNotPresent = entry.keyNotPresent;
                if (postAuthzRequest != null) {
                    try {
                        getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
                        GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
                        Object newData = gci.getRawValue();
                        if (newData != data) {
                            // user changed the value
                            isObject = getContext.isObject();
                            data = newData;
                        }
                    } catch (NotAuthorizedException ex) {
                        logger.warn(LocalizedMessage.create(LocalizedStrings.GetAll_0_CAUGHT_THE_FOLLOWING_EXCEPTION_ATTEMPTING_TO_GET_VALUE_FOR_KEY_1, new Object[] { servConn.getName(), key }), ex);
                        values.addExceptionPart(key, ex);
                        continue;
                    } finally {
                        if (getContext != null) {
                            ((GetOperationContextImpl) getContext).release();
                        }
                    }
                }
                // Add the entry to the list that will be returned to the client
                if (keyNotPresent) {
                    values.addObjectPartForAbsentKey(key, data, versionTag);
                    addedToValues = true;
                } else {
                    values.addObjectPart(key, data, isObject, versionTag);
                    addedToValues = true;
                }
            } finally {
                if (!addedToValues || data != originalData) {
                    OffHeapHelper.release(originalData);
                }
            }
        }
        // Send the last chunk even if the list is of zero size.
        sendGetAllResponseChunk(region, values, true, servConn);
        servConn.setAsTrue(RESPONDED);
    } finally {
        values.release();
    }
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) AuthorizeRequestPP(org.apache.geode.internal.security.AuthorizeRequestPP) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) GetOperationContextImpl(org.apache.geode.cache.operations.internal.GetOperationContextImpl) GetOperationContext(org.apache.geode.cache.operations.GetOperationContext) Retained(org.apache.geode.internal.offheap.annotations.Retained) VersionTag(org.apache.geode.internal.cache.versions.VersionTag)

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