Search in sources :

Example 6 with AuthenticationFailureException

use of com.couchbase.client.core.error.AuthenticationFailureException in project couchbase-jvm-clients by couchbase.

the class SaslAuthenticationHandler method failConnect.

/**
 * Refactored method which is called from many places to fail the connection
 * process because of an issue during SASL auth.
 *
 * <p>Usually errors during auth are very problematic and as a result we cannot continue
 * with this channel connect attempt.</p>
 *
 * @param ctx the channel context.
 */
private void failConnect(final ChannelHandlerContext ctx, final String message, final ByteBuf lastPacket, final Throwable cause, final short status) {
    Optional<Duration> latency = ConnectTimings.stop(ctx.channel(), this.getClass(), false);
    byte[] packetCopy = Bytes.EMPTY_BYTE_ARRAY;
    Map<String, Object> serverContext = null;
    if (lastPacket != null) {
        if (MemcacheProtocol.verifyResponse(lastPacket)) {
            // This is a proper response, try to extract server context
            Optional<ByteBuf> body = MemcacheProtocol.body(lastPacket);
            if (body.isPresent()) {
                byte[] content = ByteBufUtil.getBytes(body.get());
                try {
                    serverContext = Mapper.decodeInto(content, new TypeReference<Map<String, Object>>() {
                    });
                } catch (Exception ex) {
                // Ignore, no displayable content
                }
            }
        } else {
            // This is not a proper memcache response, store the raw packet for debugging purposes
            int ridx = lastPacket.readerIndex();
            lastPacket.readerIndex(lastPacket.writerIndex());
            packetCopy = new byte[lastPacket.readableBytes()];
            lastPacket.readBytes(packetCopy);
            lastPacket.readerIndex(ridx);
        }
    }
    KeyValueIoErrorContext errorContext = new KeyValueIoErrorContext(MemcacheProtocol.decodeStatus(status), endpointContext, serverContext);
    endpointContext.environment().eventBus().publish(new SaslAuthenticationFailedEvent(latency.orElse(Duration.ZERO), errorContext, message, packetCopy));
    interceptedConnectPromise.tryFailure(new AuthenticationFailureException(message, errorContext, cause));
    ctx.pipeline().remove(this);
}
Also used : Duration(java.time.Duration) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) TimeoutException(java.util.concurrent.TimeoutException) SaslException(javax.security.sasl.SaslException) SaslAuthenticationFailedEvent(com.couchbase.client.core.cnc.events.io.SaslAuthenticationFailedEvent) KeyValueIoErrorContext(com.couchbase.client.core.error.context.KeyValueIoErrorContext) TypeReference(com.couchbase.client.core.deps.com.fasterxml.jackson.core.type.TypeReference)

Example 7 with AuthenticationFailureException

use of com.couchbase.client.core.error.AuthenticationFailureException in project connectors-se by Talend.

the class CouchbaseService method healthCheck.

@HealthCheck("healthCheck")
public HealthCheckStatus healthCheck(@Option("configuration.dataset.connection") final CouchbaseDataStore datastore) {
    try {
        openConnection(datastore);
        LOG.debug(i18n.connectionOK());
        return new HealthCheckStatus(HealthCheckStatus.Status.OK, "Connection OK");
    } catch (Exception exception) {
        String message = "";
        if (exception.getCause() instanceof AuthenticationFailureException) {
            message = i18n.invalidPassword();
        } else if (exception.getCause() instanceof RuntimeException && exception.getCause().getCause() instanceof TimeoutException) {
            message = i18n.destinationUnreachable();
        } else {
            message = i18n.connectionKODetailed(exception.getMessage());
        }
        LOG.error(message, exception);
        return new HealthCheckStatus(HealthCheckStatus.Status.KO, message);
    } finally {
        closeConnection(datastore);
    }
}
Also used : AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) HealthCheckStatus(org.talend.sdk.component.api.service.healthcheck.HealthCheckStatus) UnambiguousTimeoutException(com.couchbase.client.core.error.UnambiguousTimeoutException) TimeoutException(java.util.concurrent.TimeoutException) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) ComponentException(org.talend.sdk.component.api.exception.ComponentException) UnambiguousTimeoutException(com.couchbase.client.core.error.UnambiguousTimeoutException) TimeoutException(java.util.concurrent.TimeoutException) HealthCheck(org.talend.sdk.component.api.service.healthcheck.HealthCheck)

Example 8 with AuthenticationFailureException

use of com.couchbase.client.core.error.AuthenticationFailureException in project couchbase-jdbc-driver by couchbaselabs.

the class ConnectionHandle method clusterVersion.

/**
 * Retrieves the raw cluster version as a string.
 *
 * @return the cluster version as a string if successful.
 * @throws SQLException if fetching the cluster version failed.
 */
public String clusterVersion() throws SQLException {
    CoreHttpClient client = cluster.core().httpClient(RequestTarget.manager());
    CompletableFuture<CoreHttpResponse> exec = client.get(path("/pools"), CoreCommonOptions.DEFAULT).build().exec(cluster.core());
    try {
        JsonNode root = Mapper.decodeIntoTree(exec.get().content());
        return root.get("implementationVersion").asText();
    } catch (ExecutionException ex) {
        if (ex.getCause() instanceof AuthenticationFailureException) {
            throw authError(ex);
        } else {
            throw new SQLException("Failed to fetch cluster version", ex);
        }
    } catch (Exception e) {
        throw new SQLException("Failed to fetch cluster version", e);
    }
}
Also used : SQLException(java.sql.SQLException) CoreHttpClient(com.couchbase.client.core.endpoint.http.CoreHttpClient) JsonNode(com.couchbase.client.core.deps.com.fasterxml.jackson.databind.JsonNode) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) ExecutionException(java.util.concurrent.ExecutionException) CoreHttpResponse(com.couchbase.client.core.endpoint.http.CoreHttpResponse) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) ExecutionException(java.util.concurrent.ExecutionException) SQLException(java.sql.SQLException)

Example 9 with AuthenticationFailureException

use of com.couchbase.client.core.error.AuthenticationFailureException in project couchbase-jvm-clients by couchbase.

the class SelectBucketHandler method channelRead.

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    Optional<Duration> latency = ConnectTimings.stop(ctx.channel(), this.getClass(), false);
    if (msg instanceof ByteBuf) {
        short status = status((ByteBuf) msg);
        if (status == MemcacheProtocol.Status.SUCCESS.status()) {
            endpointContext.environment().eventBus().publish(new SelectBucketCompletedEvent(latency.orElse(Duration.ZERO), ioContext, bucketName));
            interceptedConnectPromise.trySuccess();
            ctx.pipeline().remove(this);
            ctx.fireChannelActive();
        } else if (status == MemcacheProtocol.Status.ACCESS_ERROR.status()) {
            // If the promise has been already completed with an error from a downstream handler, there is no
            // need to WARN because it will just spam and reduce the visibility of the actual source error.
            Event.Severity severity = interceptedConnectPromise.isDone() && !interceptedConnectPromise.isSuccess() ? Event.Severity.DEBUG : Event.Severity.WARN;
            endpointContext.environment().eventBus().publish(new SelectBucketFailedEvent(severity, ioContext, status));
            interceptedConnectPromise.tryFailure(new AuthenticationFailureException("Either the bucket with name \"" + redactMeta(bucketName) + "\" is not present or the user does not have " + "the right privileges to access it", new KeyValueIoErrorContext(MemcacheProtocol.decodeStatus(status), endpointContext, null), null));
        } else if (status == MemcacheProtocol.Status.NOT_FOUND.status()) {
            // NOT_FOUND severity is lowered to debug because it shows up when bootstrapping against
            // a node in a MDS setup without the kv service / bucket enabled. If the bucket is legit not
            // present, we'd get the access error from above (which is an error).
            endpointContext.environment().eventBus().publish(new SelectBucketFailedEvent(Event.Severity.DEBUG, ioContext, status));
            interceptedConnectPromise.tryFailure(BucketNotFoundException.forBucket(bucketName));
        } else {
            endpointContext.environment().eventBus().publish(new SelectBucketFailedEvent(Event.Severity.ERROR, ioContext, status));
            interceptedConnectPromise.tryFailure(new CouchbaseException("Select bucket failed with unexpected status code 0x" + Integer.toHexString(status)));
        }
    } else {
        interceptedConnectPromise.tryFailure(new CouchbaseException("Unexpected response type on channel read, this is a bug " + "- please report." + msg));
    }
    ReferenceCountUtil.release(msg);
}
Also used : SelectBucketFailedEvent(com.couchbase.client.core.cnc.events.io.SelectBucketFailedEvent) CouchbaseException(com.couchbase.client.core.error.CouchbaseException) KeyValueIoErrorContext(com.couchbase.client.core.error.context.KeyValueIoErrorContext) SelectBucketCompletedEvent(com.couchbase.client.core.cnc.events.io.SelectBucketCompletedEvent) Duration(java.time.Duration) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException) ByteBuf(com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)

Example 10 with AuthenticationFailureException

use of com.couchbase.client.core.error.AuthenticationFailureException in project couchbase-jvm-clients by couchbase.

the class SaslListMechanismsHandler method failConnection.

/**
 * Helper method to fail the connection due to an unsuccessful sasl list mechs event.
 *
 * @param message the message that should be part of the error
 * @param status the status code from the memcached response
 * @param duration the duration how long it took overall
 */
private void failConnection(final String message, final short status, final Optional<Duration> duration) {
    KeyValueIoErrorContext errorContext = new KeyValueIoErrorContext(MemcacheProtocol.decodeStatus(status), endpointContext, null);
    ioContext.environment().eventBus().publish(new SaslMechanismsListingFailedEvent(duration.orElse(Duration.ZERO), errorContext, message));
    interceptedConnectPromise.tryFailure(new AuthenticationFailureException(message, errorContext, null));
}
Also used : KeyValueIoErrorContext(com.couchbase.client.core.error.context.KeyValueIoErrorContext) SaslMechanismsListingFailedEvent(com.couchbase.client.core.cnc.events.io.SaslMechanismsListingFailedEvent) AuthenticationFailureException(com.couchbase.client.core.error.AuthenticationFailureException)

Aggregations

AuthenticationFailureException (com.couchbase.client.core.error.AuthenticationFailureException)12 CouchbaseException (com.couchbase.client.core.error.CouchbaseException)5 ByteBuf (com.couchbase.client.core.deps.io.netty.buffer.ByteBuf)4 Duration (java.time.Duration)4 IndexNotFoundException (com.couchbase.client.core.error.IndexNotFoundException)3 InternalServerFailureException (com.couchbase.client.core.error.InternalServerFailureException)3 KeyValueIoErrorContext (com.couchbase.client.core.error.context.KeyValueIoErrorContext)3 ChannelFuture (com.couchbase.client.core.deps.io.netty.channel.ChannelFuture)2 ErrorCodeAndMessage (com.couchbase.client.core.error.ErrorCodeAndMessage)2 IndexExistsException (com.couchbase.client.core.error.IndexExistsException)2 ParsingFailureException (com.couchbase.client.core.error.ParsingFailureException)2 QuotaLimitedException (com.couchbase.client.core.error.QuotaLimitedException)2 RateLimitedException (com.couchbase.client.core.error.RateLimitedException)2 UnambiguousTimeoutException (com.couchbase.client.core.error.UnambiguousTimeoutException)2 InetSocketAddress (java.net.InetSocketAddress)2 TimeoutException (java.util.concurrent.TimeoutException)2 Test (org.junit.jupiter.api.Test)2 Core (com.couchbase.client.core.Core)1 SimpleEventBus (com.couchbase.client.core.cnc.SimpleEventBus)1 SaslAuthenticationFailedEvent (com.couchbase.client.core.cnc.events.io.SaslAuthenticationFailedEvent)1