Search in sources :

Example 6 with AuthenticationException

use of io.pravega.auth.AuthenticationException in project pravega by pravega.

the class AuthHandlerManager method authenticateAndAuthorize.

/**
 * API to authenticate and authorize access to a given resource.
 * @param resource The resource identifier for which the access needs to be controlled.
 * @param credentials  Credentials used for authentication.
 * @param level    Expected level of access.
 * @return         Returns true if the entity represented by the custom auth headers had given level of access to the resource.
 *                 Returns false if the entity does not have access.
 * @throws AuthenticationException if an authentication failure occurred.
 */
public boolean authenticateAndAuthorize(String resource, String credentials, AuthHandler.Permissions level) throws AuthenticationException {
    Preconditions.checkNotNull(credentials, "credentials");
    boolean retVal = false;
    try {
        String[] parts = extractMethodAndToken(credentials);
        String method = parts[0];
        String token = parts[1];
        AuthHandler handler = getHandler(method);
        Preconditions.checkNotNull(handler, "Can not find handler.");
        Principal principal;
        if ((principal = handler.authenticate(token)) == null) {
            throw new AuthenticationException("Authentication failure");
        }
        retVal = handler.authorize(resource, principal).ordinal() >= level.ordinal();
    } catch (AuthException e) {
        throw new AuthenticationException("Authentication failure");
    }
    return retVal;
}
Also used : AuthHandler(io.pravega.auth.AuthHandler) AuthenticationException(io.pravega.auth.AuthenticationException) AuthException(io.pravega.auth.AuthException) Principal(java.security.Principal)

Example 7 with AuthenticationException

use of io.pravega.auth.AuthenticationException in project pravega by pravega.

the class LargeEventWriter method writeLargeEvent.

/**
 * Write the provided list of events (atomically) to the provided segment.
 *
 * @param segment The segment to write to
 * @param events The events to append
 * @param tokenProvider A token provider
 * @param config Used for retry configuration parameters
 * @throws NoSuchSegmentException If the provided segment does not exit.
 * @throws SegmentSealedException If the segment is sealed.
 * @throws AuthenticationException If the token can't be used for this segment.
 * @throws UnsupportedOperationException If the server does not support large events.
 */
public void writeLargeEvent(Segment segment, List<ByteBuffer> events, DelegationTokenProvider tokenProvider, EventWriterConfig config) throws NoSuchSegmentException, AuthenticationException, SegmentSealedException {
    List<ByteBuf> payloads = createBufs(events);
    int attempts = 1 + Math.max(0, config.getRetryAttempts());
    Retry.withExpBackoff(config.getInitialBackoffMillis(), config.getBackoffMultiple(), attempts, config.getMaxBackoffMillis()).retryWhen(t -> {
        Throwable ex = Exceptions.unwrap(t);
        if (ex instanceof ConnectionFailedException) {
            log.info("Connection failure while sending large event: {}. Retrying", ex.getMessage());
            return true;
        } else if (ex instanceof TokenExpiredException) {
            tokenProvider.signalTokenExpired();
            log.info("Authentication token expired while writing large event to segment {}. Retrying", segment);
            return true;
        } else {
            return false;
        }
    }).run(() -> {
        @Cleanup RawClient client = new RawClient(controller, connectionPool, segment);
        write(segment, payloads, client, tokenProvider);
        return null;
    });
}
Also used : Segment(io.pravega.client.segment.impl.Segment) TokenExpiredException(io.pravega.auth.TokenExpiredException) Retry(io.pravega.common.util.Retry) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) Exceptions(io.pravega.common.Exceptions) ConditionalCheckFailed(io.pravega.shared.protocol.netty.WireCommands.ConditionalCheckFailed) RequiredArgsConstructor(lombok.RequiredArgsConstructor) SegmentIsTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentIsTruncated) Cleanup(lombok.Cleanup) CompletableFuture(java.util.concurrent.CompletableFuture) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) CreateTransientSegment(io.pravega.shared.protocol.netty.WireCommands.CreateTransientSegment) ArrayList(java.util.ArrayList) RawClient(io.pravega.client.connection.impl.RawClient) ConditionalBlockEnd(io.pravega.shared.protocol.netty.WireCommands.ConditionalBlockEnd) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) ByteBuf(io.netty.buffer.ByteBuf) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) MergeSegments(io.pravega.shared.protocol.netty.WireCommands.MergeSegments) SegmentCreated(io.pravega.shared.protocol.netty.WireCommands.SegmentCreated) Futures.getThrowingException(io.pravega.common.concurrent.Futures.getThrowingException) WireCommandType(io.pravega.shared.protocol.netty.WireCommandType) Nonnull(javax.annotation.Nonnull) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Serializer(io.pravega.client.stream.Serializer) SegmentsMerged(io.pravega.shared.protocol.netty.WireCommands.SegmentsMerged) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) lombok.val(lombok.val) AuthenticationException(io.pravega.auth.AuthenticationException) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) InvalidEventNumber(io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) VisibleForTesting(com.google.common.annotations.VisibleForTesting) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Controller(io.pravega.client.control.impl.Controller) TokenExpiredException(io.pravega.auth.TokenExpiredException) RawClient(io.pravega.client.connection.impl.RawClient) ByteBuf(io.netty.buffer.ByteBuf) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Cleanup(lombok.Cleanup)

Example 8 with AuthenticationException

use of io.pravega.auth.AuthenticationException in project pravega by pravega.

the class EventStreamWriterImpl method writeLargeEvent.

@GuardedBy("writeFlushLock")
private void writeLargeEvent(String routingKey, List<ByteBuffer> events, CompletableFuture<Void> ackFuture) {
    flush();
    boolean success = false;
    LargeEventWriter writer = new LargeEventWriter(UUID.randomUUID(), controller, connectionPool);
    while (!success) {
        Segment segment = selector.getSegmentForEvent(routingKey);
        try {
            writer.writeLargeEvent(segment, events, tokenProvider, config);
            success = true;
            ackFuture.complete(null);
        } catch (SegmentSealedException | NoSuchSegmentException e) {
            log.warn("Write large event on segment {} failed due to {}, it will be retried.", segment, e.getMessage());
            handleLogSealed(segment);
            tryWaitForSuccessors();
            // Make sure that the successors are not sealed themselves.
            if (selector.isStreamSealed()) {
                ackFuture.completeExceptionally(new SegmentSealedException(segment.toString()));
                break;
            }
            handleMissingLog();
        } catch (AuthenticationException e) {
            ackFuture.completeExceptionally(e);
            break;
        }
    }
}
Also used : AuthenticationException(io.pravega.auth.AuthenticationException) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) Segment(io.pravega.client.segment.impl.Segment) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) GuardedBy(javax.annotation.concurrent.GuardedBy)

Example 9 with AuthenticationException

use of io.pravega.auth.AuthenticationException in project pravega by pravega.

the class SegmentHelper method handleExpectedReplies.

/**
 * This method handles the reply returned from RawClient.sendRequest given the expected success and failure cases.
 *
 * @param callerRequestId     request id issues by the client
 * @param reply               actual reply received
 * @param client              RawClient for sending request
 * @param qualifiedStreamSegmentName StreamSegmentName
 * @param requestType         request which reply need to be transformed
 * @param type                WireCommand for this request
 * @param expectedSuccessReplies the expected replies for a successful case
 * @param expectedFailureReplies the expected replies for a failing case
 * @throws ConnectionFailedException in case the reply is unexpected
 */
protected void handleExpectedReplies(long callerRequestId, Reply reply, RawClient client, String qualifiedStreamSegmentName, Class<? extends Request> requestType, WireCommandType type, Map<Class<? extends Request>, Set<Class<? extends Reply>>> expectedSuccessReplies, Map<Class<? extends Request>, Set<Class<? extends Reply>>> expectedFailureReplies) throws ConnectionFailedException {
    closeConnection(reply, client, callerRequestId);
    Set<Class<? extends Reply>> expectedReplies = expectedSuccessReplies.get(requestType);
    Set<Class<? extends Reply>> expectedFailingReplies = expectedFailureReplies.get(requestType);
    if (expectedReplies != null && expectedReplies.contains(reply.getClass())) {
        log.debug(callerRequestId, "{} {} {} {}.", requestType.getSimpleName(), qualifiedStreamSegmentName, reply.getClass().getSimpleName(), reply.getRequestId());
    } else if (expectedFailingReplies != null && expectedFailingReplies.contains(reply.getClass())) {
        log.debug(callerRequestId, "{} {} {} {}.", requestType.getSimpleName(), qualifiedStreamSegmentName, reply.getClass().getSimpleName(), reply.getRequestId());
        if (reply instanceof WireCommands.NoSuchSegment) {
            throw new WireCommandFailedException(type, WireCommandFailedException.Reason.SegmentDoesNotExist);
        } else if (reply instanceof WireCommands.TableSegmentNotEmpty) {
            throw new WireCommandFailedException(type, WireCommandFailedException.Reason.TableSegmentNotEmpty);
        } else if (reply instanceof WireCommands.TableKeyDoesNotExist) {
            throw new WireCommandFailedException(type, WireCommandFailedException.Reason.TableKeyDoesNotExist);
        } else if (reply instanceof WireCommands.TableKeyBadVersion) {
            throw new WireCommandFailedException(type, WireCommandFailedException.Reason.TableKeyBadVersion);
        }
    } else if (reply instanceof WireCommands.AuthTokenCheckFailed) {
        log.warn(callerRequestId, "Auth Check Failed {} {} {} {} with error code {}.", requestType.getSimpleName(), qualifiedStreamSegmentName, reply.getClass().getSimpleName(), reply.getRequestId(), ((WireCommands.AuthTokenCheckFailed) reply).getErrorCode());
        throw new WireCommandFailedException(new AuthenticationException(reply.toString()), type, WireCommandFailedException.Reason.AuthFailed);
    } else if (reply instanceof WireCommands.WrongHost) {
        log.warn(callerRequestId, "Wrong Host {} {} {} {}.", requestType.getSimpleName(), qualifiedStreamSegmentName, reply.getClass().getSimpleName(), reply.getRequestId());
        throw new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost);
    } else {
        log.error(callerRequestId, "Unexpected reply {} {} {} {}.", requestType.getSimpleName(), qualifiedStreamSegmentName, reply.getClass().getSimpleName(), reply.getRequestId());
        throw new ConnectionFailedException("Unexpected reply of " + reply + " when expecting one of " + expectedReplies.stream().map(Object::toString).collect(Collectors.joining(", ")));
    }
}
Also used : AuthenticationException(io.pravega.auth.AuthenticationException) Reply(io.pravega.shared.protocol.netty.Reply) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 10 with AuthenticationException

use of io.pravega.auth.AuthenticationException in project pravega by pravega.

the class SegmentHelper method processAndRethrowException.

@VisibleForTesting
<T extends Request & WireCommand> void processAndRethrowException(long callerRequestId, T request, Throwable e) {
    Throwable unwrap = Exceptions.unwrap(e);
    WireCommandFailedException ex = null;
    if (unwrap instanceof ConnectionFailedException || unwrap instanceof ConnectionClosedException) {
        log.warn(callerRequestId, "Connection dropped {}", request.getRequestId());
        throw new WireCommandFailedException(request.getType(), WireCommandFailedException.Reason.ConnectionFailed);
    } else if (unwrap instanceof AuthenticationException) {
        log.warn(callerRequestId, "Authentication Exception {}", request.getRequestId());
        throw new WireCommandFailedException(request.getType(), WireCommandFailedException.Reason.AuthFailed);
    } else if (unwrap instanceof TokenExpiredException) {
        log.warn(callerRequestId, "Token expired {}", request.getRequestId());
        throw new WireCommandFailedException(request.getType(), WireCommandFailedException.Reason.AuthFailed);
    } else if (unwrap instanceof TimeoutException) {
        log.warn(callerRequestId, "Request timed out. {}", request.getRequestId());
        throw new WireCommandFailedException(request.getType(), WireCommandFailedException.Reason.ConnectionFailed);
    } else {
        log.error(callerRequestId, "Request failed {}", request.getRequestId(), e);
        throw new CompletionException(e);
    }
}
Also used : TokenExpiredException(io.pravega.auth.TokenExpiredException) AuthenticationException(io.pravega.auth.AuthenticationException) CompletionException(java.util.concurrent.CompletionException) ConnectionClosedException(io.pravega.client.stream.impl.ConnectionClosedException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) TimeoutException(java.util.concurrent.TimeoutException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

AuthenticationException (io.pravega.auth.AuthenticationException)19 ConnectionFailedException (io.pravega.shared.protocol.netty.ConnectionFailedException)12 WireCommands (io.pravega.shared.protocol.netty.WireCommands)10 CompletableFuture (java.util.concurrent.CompletableFuture)9 Test (org.junit.Test)7 TokenExpiredException (io.pravega.auth.TokenExpiredException)6 Cleanup (lombok.Cleanup)6 ConnectionClosedException (io.pravega.client.stream.impl.ConnectionClosedException)5 Reply (io.pravega.shared.protocol.netty.Reply)5 WrongHost (io.pravega.shared.protocol.netty.WireCommands.WrongHost)5 VisibleForTesting (com.google.common.annotations.VisibleForTesting)4 Segment (io.pravega.client.segment.impl.Segment)4 List (java.util.List)4 UUID (java.util.UUID)4 Unpooled (io.netty.buffer.Unpooled)3 TxnFailedException (io.pravega.client.stream.TxnFailedException)3 MockConnectionFactoryImpl (io.pravega.client.stream.mock.MockConnectionFactoryImpl)3 MockController (io.pravega.client.stream.mock.MockController)3 Exceptions (io.pravega.common.Exceptions)3 FailingReplyProcessor (io.pravega.shared.protocol.netty.FailingReplyProcessor)3