Search in sources :

Example 1 with InvalidTokenException

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

the class SegmentOutputStreamImpl method reconnect.

@VisibleForTesting
void reconnect() {
    if (state.isClosed()) {
        return;
    }
    log.debug("(Re)connect invoked, Segment: {}, writerID: {}", segmentName, writerId);
    state.setupConnection.registerAndRunReleaser(() -> {
        // retry on all exceptions.
        retrySchedule.retryWhen(t -> t instanceof Exception).runAsync(() -> {
            log.debug("Running reconnect for segment {} writer {}", segmentName, writerId);
            if (state.isClosed() || state.needSuccessors.get()) {
                // stop reconnect when writer is closed or resend inflight to successors has been triggered.
                return CompletableFuture.completedFuture(null);
            }
            Preconditions.checkState(state.getConnection() == null);
            log.info("Fetching endpoint for segment {}, writer {}", segmentName, writerId);
            return controller.getEndpointForSegment(segmentName).thenComposeAsync((PravegaNodeUri uri) -> {
                log.info("Establishing connection to {} for {}, writerID: {}", uri, segmentName, writerId);
                return establishConnection(uri);
            }, connectionPool.getInternalExecutor()).thenCombineAsync(tokenProvider.retrieveToken(), AbstractMap.SimpleEntry<ClientConnection, String>::new, connectionPool.getInternalExecutor()).thenComposeAsync(pair -> {
                ClientConnection connection = pair.getKey();
                String token = pair.getValue();
                CompletableFuture<Void> connectionSetupFuture = state.newConnection(connection);
                SetupAppend cmd = new SetupAppend(requestId, writerId, segmentName, token);
                try {
                    connection.send(cmd);
                } catch (ConnectionFailedException e1) {
                    // This needs to be invoked here because call to failConnection from netty may occur before state.newConnection above.
                    state.failConnection(e1);
                    throw Exceptions.sneakyThrow(e1);
                }
                return connectionSetupFuture.exceptionally(t1 -> {
                    Throwable exception = Exceptions.unwrap(t1);
                    if (exception instanceof InvalidTokenException) {
                        log.info("Ending reconnect attempts on writer {} to {} because token verification failed due to invalid token", writerId, segmentName);
                        return null;
                    }
                    if (exception instanceof SegmentSealedException) {
                        log.info("Ending reconnect attempts on writer {} to {} because segment is sealed", writerId, segmentName);
                        return null;
                    }
                    if (exception instanceof NoSuchSegmentException) {
                        log.info("Ending reconnect attempts on writer {} to {} because segment is truncated", writerId, segmentName);
                        return null;
                    }
                    throw Exceptions.sneakyThrow(t1);
                });
            }, connectionPool.getInternalExecutor());
        }, connectionPool.getInternalExecutor()).exceptionally(t -> {
            log.error("Error while attempting to establish connection for writer {}", writerId, t);
            failAndRemoveUnackedEvents(t);
            return null;
        });
    }, new CompletableFuture<ClientConnection>());
}
Also used : TokenExpiredException(io.pravega.auth.TokenExpiredException) Retry(io.pravega.common.util.Retry) RequiredArgsConstructor(lombok.RequiredArgsConstructor) ClientConnection(io.pravega.client.connection.impl.ClientConnection) FailingReplyProcessor(io.pravega.shared.protocol.netty.FailingReplyProcessor) Map(java.util.Map) ToString(lombok.ToString) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) Flow(io.pravega.client.connection.impl.Flow) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) UUID(java.util.UUID) ReusableFutureLatch(io.pravega.common.util.ReusableFutureLatch) GuardedBy(javax.annotation.concurrent.GuardedBy) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Entry(java.util.Map.Entry) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Controller(io.pravega.client.control.impl.Controller) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) SimpleImmutableEntry(java.util.AbstractMap.SimpleImmutableEntry) PendingEvent(io.pravega.client.stream.impl.PendingEvent) Append(io.pravega.shared.protocol.netty.Append) ArrayList(java.util.ArrayList) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) KeepAlive(io.pravega.shared.protocol.netty.WireCommands.KeepAlive) ReusableLatch(io.pravega.common.util.ReusableLatch) NameUtils(io.pravega.shared.NameUtils) RetryWithBackoff(io.pravega.common.util.Retry.RetryWithBackoff) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) Consumer(java.util.function.Consumer) WireCommand(io.pravega.shared.protocol.netty.WireCommand) AbstractMap(java.util.AbstractMap) InvalidTokenException(io.pravega.auth.InvalidTokenException) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) InvalidTokenException(io.pravega.auth.InvalidTokenException) ToString(lombok.ToString) TokenExpiredException(io.pravega.auth.TokenExpiredException) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) InvalidTokenException(io.pravega.auth.InvalidTokenException) CompletableFuture(java.util.concurrent.CompletableFuture) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) ClientConnection(io.pravega.client.connection.impl.ClientConnection) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 2 with InvalidTokenException

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

the class SegmentMetadataClientTest method testTokenCheckFailure.

@Test(timeout = 10000)
public void testTokenCheckFailure() throws ConnectionFailedException {
    Segment segment = new Segment("scope", "testRetry", 4);
    PravegaNodeUri endpoint = new PravegaNodeUri("localhost", 0);
    @Cleanup MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    @Cleanup MockController controller = new MockController(endpoint.getEndpoint(), endpoint.getPort(), cf, true);
    @Cleanup ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(endpoint, connection);
    @Cleanup SegmentMetadataClientImpl client = new SegmentMetadataClientImpl(segment, controller, cf, "");
    client.getConnection();
    ReplyProcessor processor = cf.getProcessor(endpoint);
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            WireCommands.GetStreamSegmentInfo getStreamInfo = invocation.getArgument(0);
            processor.process(new WireCommands.AuthTokenCheckFailed(getStreamInfo.getRequestId(), "server-stacktrace", WireCommands.AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED));
            return null;
        }
    }).when(connection).send(any(WireCommands.GetStreamSegmentInfo.class));
    AssertExtensions.assertThrows("TokenException was not thrown or server stacktrace contained unexpected content.", () -> client.fetchCurrentSegmentLength().join(), e -> e instanceof InvalidTokenException && e.getMessage().contains("serverStackTrace=server-stacktrace"));
}
Also used : InvalidTokenException(io.pravega.auth.InvalidTokenException) Cleanup(lombok.Cleanup) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) InvocationOnMock(org.mockito.invocation.InvocationOnMock) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) ReplyProcessor(io.pravega.shared.protocol.netty.ReplyProcessor) Test(org.junit.Test)

Example 3 with InvalidTokenException

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

the class SegmentMetadataClientTest method testTokenCheckFailed.

@Test(timeout = 10000)
public void testTokenCheckFailed() throws ConnectionFailedException {
    Segment segment = new Segment("scope", "testRetry", 4);
    PravegaNodeUri endpoint = new PravegaNodeUri("localhost", 0);
    @Cleanup MockConnectionFactoryImpl cf = new MockConnectionFactoryImpl();
    @Cleanup MockController controller = new MockController(endpoint.getEndpoint(), endpoint.getPort(), cf, true);
    @Cleanup ClientConnection connection = mock(ClientConnection.class);
    cf.provideConnection(endpoint, connection);
    @Cleanup SegmentMetadataClientImpl client = new SegmentMetadataClientImpl(segment, controller, cf, "");
    client.getConnection();
    ReplyProcessor processor = cf.getProcessor(endpoint);
    Mockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            WireCommands.GetStreamSegmentInfo getStreamInfo = invocation.getArgument(0);
            processor.process(new WireCommands.AuthTokenCheckFailed(getStreamInfo.getRequestId(), "server-stacktrace", WireCommands.AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED));
            return null;
        }
    }).when(connection).send(any(WireCommands.GetStreamSegmentInfo.class));
    AssertExtensions.assertThrows("TokenException was not thrown or server stacktrace contained unexpected content.", () -> client.fetchCurrentSegmentLength().join(), e -> e instanceof InvalidTokenException && e.getMessage().contains("serverStackTrace=server-stacktrace"));
}
Also used : InvalidTokenException(io.pravega.auth.InvalidTokenException) Cleanup(lombok.Cleanup) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) InvocationOnMock(org.mockito.invocation.InvocationOnMock) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) ReplyProcessor(io.pravega.shared.protocol.netty.ReplyProcessor) Test(org.junit.Test)

Example 4 with InvalidTokenException

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

the class PravegaRequestProcessorAuthFailedTest method setUp.

@Before
public void setUp() throws Exception {
    StreamSegmentStore store = mock(StreamSegmentStore.class);
    connection = mock(ServerConnection.class);
    processor = new PravegaRequestProcessor(store, mock(TableStore.class), new TrackedConnection(connection), SegmentStatsRecorder.noOp(), TableSegmentStatsRecorder.noOp(), (resource, token, expectedLevel) -> {
        throw new InvalidTokenException("Token verification failed.");
    }, false);
}
Also used : TOKEN_CHECK_FAILED(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED) InvalidTokenException(io.pravega.auth.InvalidTokenException) TableStore(io.pravega.segmentstore.contracts.tables.TableStore) After(org.junit.After) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) Test(org.junit.Test) WireCommands(io.pravega.shared.protocol.netty.WireCommands) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) TableSegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.TableSegmentStatsRecorder) Before(org.junit.Before) Mockito.mock(org.mockito.Mockito.mock) Mockito.verify(org.mockito.Mockito.verify) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) InvalidTokenException(io.pravega.auth.InvalidTokenException) Before(org.junit.Before)

Example 5 with InvalidTokenException

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

the class JwtParser method parseClaims.

@VisibleForTesting
static Claims parseClaims(String token, byte[] signingKey) throws TokenExpiredException, InvalidTokenException {
    if (Strings.isNullOrEmpty(token)) {
        throw new InvalidTokenException("Token is null or empty");
    }
    try {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token);
        log.debug("Successfully parsed JWT token.");
        return claimsJws.getBody();
    } catch (ExpiredJwtException e) {
        throw new TokenExpiredException(e);
    } catch (JwtException e) {
        throw new InvalidTokenException(e);
    }
}
Also used : InvalidTokenException(io.pravega.auth.InvalidTokenException) Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) TokenExpiredException(io.pravega.auth.TokenExpiredException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) JwtException(io.jsonwebtoken.JwtException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

InvalidTokenException (io.pravega.auth.InvalidTokenException)9 Test (org.junit.Test)4 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 TokenExpiredException (io.pravega.auth.TokenExpiredException)3 ClientConnection (io.pravega.client.connection.impl.ClientConnection)3 StreamSegmentStore (io.pravega.segmentstore.contracts.StreamSegmentStore)3 PravegaNodeUri (io.pravega.shared.protocol.netty.PravegaNodeUri)3 WireCommands (io.pravega.shared.protocol.netty.WireCommands)3 Claims (io.jsonwebtoken.Claims)2 MockConnectionFactoryImpl (io.pravega.client.stream.mock.MockConnectionFactoryImpl)2 MockController (io.pravega.client.stream.mock.MockController)2 Exceptions (io.pravega.common.Exceptions)2 TableStore (io.pravega.segmentstore.contracts.tables.TableStore)2 SegmentStatsRecorder (io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder)2 TableSegmentStatsRecorder (io.pravega.segmentstore.server.host.stat.TableSegmentStatsRecorder)2 ReplyProcessor (io.pravega.shared.protocol.netty.ReplyProcessor)2 TOKEN_CHECK_FAILED (io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED)2 Cleanup (lombok.Cleanup)2 Before (org.junit.Before)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2