Search in sources :

Example 51 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project cdap by caskdata.

the class SecurityAuthenticationHttpHandler method validateSecuredInterception.

/**
   * Intercepts the HttpMessage for getting the access token in authorization header
   *
   * @param ctx channel handler context delegated from MessageReceived callback
   * @param msg intercepted HTTP message
   * @param inboundChannel
   * @return {@code true} if the HTTP message has valid Access token
   * @throws Exception
   */
private boolean validateSecuredInterception(ChannelHandlerContext ctx, HttpRequest msg, Channel inboundChannel, AuditLogEntry logEntry) throws Exception {
    String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION);
    String accessToken = null;
    /*
     * Parse the access token from authorization header.  The header will be in the form:
     *     Authorization: Bearer ACCESSTOKEN
     *
     * where ACCESSTOKEN is the base64 encoded serialized AccessToken instance.
     */
    if (auth != null) {
        int spIndex = auth.trim().indexOf(' ');
        if (spIndex != -1) {
            accessToken = auth.substring(spIndex + 1).trim();
        }
    }
    HttpMethod httpMethod = msg.getMethod();
    String uri = msg.getUri();
    logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress());
    logEntry.setRequestLine(httpMethod, uri, msg.getProtocolVersion());
    TokenState tokenState = tokenValidator.validate(accessToken);
    if (!tokenState.isValid()) {
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
        logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode());
        JsonObject jsonObject = new JsonObject();
        if (tokenState == TokenState.MISSING) {
            httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\"", realm));
            LOG.debug("Authentication failed due to missing token");
        } else {
            httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\" error=\"invalid_token\"" + " error_description=\"%s\"", realm, tokenState.getMsg()));
            jsonObject.addProperty("error", "invalid_token");
            jsonObject.addProperty("error_description", tokenState.getMsg());
            LOG.debug("Authentication failed due to invalid token, reason={};", tokenState);
        }
        JsonArray externalAuthenticationURIs = new JsonArray();
        // Waiting for service to get discovered
        stopWatchWait(externalAuthenticationURIs);
        jsonObject.add("auth_uri", externalAuthenticationURIs);
        ChannelBuffer content = ChannelBuffers.wrappedBuffer(jsonObject.toString().getBytes(Charsets.UTF_8));
        httpResponse.setContent(content);
        int contentLength = content.readableBytes();
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
        httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
        logEntry.setResponseContentLength(new Long(contentLength));
        ChannelFuture writeFuture = Channels.future(inboundChannel);
        Channels.write(ctx, writeFuture, httpResponse);
        writeFuture.addListener(ChannelFutureListener.CLOSE);
        return false;
    } else {
        AccessTokenTransformer.AccessTokenIdentifierPair accessTokenIdentifierPair = accessTokenTransformer.transform(accessToken);
        AuditLogContent auditLogContent = AUDIT_LOG_LOOKUP_METHOD.contains(httpMethod) ? AUDIT_LOOK_UP.getAuditLogContent(msg.getUri(), httpMethod) : null;
        if (auditLogContent != null) {
            List<String> headerNames = auditLogContent.getHeaderNames();
            if (!headerNames.isEmpty()) {
                Map<String, String> headers = new HashMap<>();
                for (String headerName : headerNames) {
                    headers.put(headerName, msg.getHeader(headerName));
                }
                logEntry.setHeaders(headers);
            }
            if (auditLogContent.isLogRequestBody()) {
                ChannelBuffer body = msg.getContent();
                if (body.readable()) {
                    logEntry.setRequestBody(body.toString(Charsets.UTF_8));
                }
            }
            logEntry.setLogResponseBody(auditLogContent.isLogResponsebody());
        }
        logEntry.setUserName(accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
        msg.setHeader(HttpHeaders.Names.AUTHORIZATION, "CDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr());
        msg.setHeader(Constants.Security.Headers.USER_ID, accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
        msg.setHeader(Constants.Security.Headers.USER_IP, ((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress());
        return true;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) JsonObject(com.google.gson.JsonObject) TokenState(co.cask.cdap.security.auth.TokenState) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) JsonArray(com.google.gson.JsonArray) AccessTokenTransformer(co.cask.cdap.security.auth.AccessTokenTransformer) AuditLogContent(co.cask.cdap.common.logging.AuditLogContent) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpMethod(org.jboss.netty.handler.codec.http.HttpMethod)

Example 52 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project cdap by caskdata.

the class AuthenticationChannelHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
    LOG.error("Got exception: ", e.getCause());
    ChannelFuture future = Channels.future(ctx.getChannel());
    future.addListener(ChannelFutureListener.CLOSE);
    // TODO: add WWW-Authenticate header for 401 response -  REACTOR-900
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
    Channels.write(ctx, future, response);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse)

Example 53 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project dubbo by alibaba.

the class NettyClient method doConnect.

protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // Close old channel
                // copy reference
                Channel oldChannel = NettyClient.this.channel;
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + " client-side timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        if (!isConnected()) {
            future.cancel();
        }
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Channel(org.jboss.netty.channel.Channel) RemotingException(com.alibaba.dubbo.remoting.RemotingException)

Example 54 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project Protocol-Adapter-OSLP by OSGP.

the class OslpChannelHandler method send.

public OslpEnvelope send(final InetSocketAddress address, final OslpEnvelope request, final String deviceIdentification) throws IOException, DeviceSimulatorException {
    LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
    final Callback callback = new Callback(this.connectionTimeout);
    this.lock.lock();
    // Open connection and send message
    ChannelFuture channelFuture = null;
    try {
        channelFuture = this.bootstrap.connect(address);
        channelFuture.awaitUninterruptibly(this.connectionTimeout, TimeUnit.MILLISECONDS);
        if (channelFuture.getChannel() != null && channelFuture.getChannel().isConnected()) {
            LOGGER.info("Connection established to: {}", address);
        } else {
            LOGGER.info("The connnection to the device {} is not successfull", deviceIdentification);
            LOGGER.warn("Unable to connect to: {}", address);
            throw new IOException("Unable to connect");
        }
        this.callbacks.put(channelFuture.getChannel().getId(), callback);
        channelFuture.getChannel().write(request);
    } finally {
        this.lock.unlock();
    }
    // wait for response and close connection
    try {
        final OslpEnvelope response = callback.get(deviceIdentification);
        LOGGER.info("Received OSLP response (after callback): {}", response.getPayloadMessage());
        /*
             * Devices expect the channel to be closed if (and only if) the
             * platform initiated the conversation. If the device initiated the
             * conversation it needs to close the channel itself.
             */
        channelFuture.getChannel().close();
        return response;
    } catch (final IOException | DeviceSimulatorException e) {
        LOGGER.error("send exception", e);
        // Remove callback when exception has occurred
        this.callbacks.remove(channelFuture.getChannel().getId());
        throw e;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DeviceSimulatorException(com.alliander.osgp.webdevicesimulator.exceptions.DeviceSimulatorException) IOException(java.io.IOException) OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Example 55 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project Protocol-Adapter-OSLP by OSGP.

the class OslpChannelHandlerClient method send.

public void send(final InetSocketAddress address, final OslpEnvelope request, final OslpResponseHandler responseHandler, final String deviceIdentification) throws IOException {
    LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
    // Open connection and send message.
    final ChannelFuture channelFuture = this.bootstrap.connect(address);
    this.callbackHandlers.put(channelFuture.getChannel().getId(), new OslpCallbackHandler(responseHandler));
    channelFuture.addListener(new ChannelFutureListener() {

        @Autowired
        protected DeviceResponseMessageSender responseMessageSender;

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                OslpChannelHandlerClient.this.write(future, address, request);
                // What is this call below good for?
                future.getChannel().getId();
            } else {
                LOGGER.info("The connection to the device {} is not successful", deviceIdentification);
                throw new IOException("ChannelFuture - Unable to connect");
            }
        }
    });
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Autowired(org.springframework.beans.factory.annotation.Autowired) DeviceResponseMessageSender(com.alliander.osgp.adapter.protocol.oslp.elster.infra.messaging.DeviceResponseMessageSender) IOException(java.io.IOException) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) IOException(java.io.IOException) NoDeviceResponseException(com.alliander.osgp.shared.exceptionhandling.NoDeviceResponseException)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)122 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)36 Channel (org.jboss.netty.channel.Channel)33 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)29 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)26 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)25 InetSocketAddress (java.net.InetSocketAddress)22 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)22 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)19 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 Test (org.junit.Test)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)8 Test (org.testng.annotations.Test)8 ConnectException (java.net.ConnectException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6