Search in sources :

Example 6 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project camel by apache.

the class HttpServerChannelHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    HttpRequest request = (HttpRequest) messageEvent.getMessage();
    LOG.debug("Message received: {}", request);
    if (consumer.isSuspended()) {
        // are we suspended?
        LOG.debug("Consumer suspended, cannot service request {}", request);
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, SERVICE_UNAVAILABLE);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    // if its an OPTIONS request then return which methods is allowed
    boolean isRestrictedToOptions = consumer.getEndpoint().getHttpMethodRestrict() != null && consumer.getEndpoint().getHttpMethodRestrict().contains("OPTIONS");
    if ("OPTIONS".equals(request.getMethod().getName()) && !isRestrictedToOptions) {
        String s;
        if (consumer.getEndpoint().getHttpMethodRestrict() != null) {
            s = "OPTIONS," + consumer.getEndpoint().getHttpMethodRestrict();
        } else {
            // allow them all
            s = "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,CONNECT,PATCH";
        }
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        response.setChunked(false);
        response.headers().set("Allow", s);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    if (consumer.getEndpoint().getHttpMethodRestrict() != null && !consumer.getEndpoint().getHttpMethodRestrict().contains(request.getMethod().getName())) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    if ("TRACE".equals(request.getMethod().getName()) && !consumer.getEndpoint().isTraceEnabled()) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    // must include HOST header as required by HTTP 1.1
    if (!request.headers().contains(HttpHeaders.Names.HOST)) {
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, BAD_REQUEST);
        response.setChunked(false);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        messageEvent.getChannel().close();
        return;
    }
    // is basic auth configured
    NettyHttpSecurityConfiguration security = consumer.getEndpoint().getSecurityConfiguration();
    if (security != null && security.isAuthenticate() && "Basic".equalsIgnoreCase(security.getConstraint())) {
        String url = request.getUri();
        // drop parameters from url
        if (url.contains("?")) {
            url = ObjectHelper.before(url, "?");
        }
        // we need the relative path without the hostname and port
        URI uri = new URI(request.getUri());
        String target = uri.getPath();
        // strip the starting endpoint path so the target is relative to the endpoint uri
        String path = consumer.getConfiguration().getPath();
        if (path != null) {
            // need to match by lower case as we want to ignore case on context-path
            path = path.toLowerCase(Locale.US);
            String match = target.toLowerCase(Locale.US);
            if (match.startsWith(path)) {
                target = target.substring(path.length());
            }
        }
        // is it a restricted resource?
        String roles;
        if (security.getSecurityConstraint() != null) {
            // if restricted returns null, then the resource is not restricted and we should not authenticate the user
            roles = security.getSecurityConstraint().restricted(target);
        } else {
            // assume any roles is valid if no security constraint has been configured
            roles = "*";
        }
        if (roles != null) {
            // basic auth subject
            HttpPrincipal principal = extractBasicAuthSubject(request);
            // authenticate principal and check if the user is in role
            Subject subject = null;
            boolean inRole = true;
            if (principal != null) {
                subject = authenticate(security.getSecurityAuthenticator(), security.getLoginDeniedLoggingLevel(), principal);
                if (subject != null) {
                    String userRoles = security.getSecurityAuthenticator().getUserRoles(subject);
                    inRole = matchesRoles(roles, userRoles);
                }
            }
            if (principal == null || subject == null || !inRole) {
                if (principal == null) {
                    LOG.debug("Http Basic Auth required for resource: {}", url);
                } else if (subject == null) {
                    LOG.debug("Http Basic Auth not authorized for username: {}", principal.getUsername());
                } else {
                    LOG.debug("Http Basic Auth not in role for username: {}", principal.getUsername());
                }
                // restricted resource, so send back 401 to require valid username/password
                HttpResponse response = new DefaultHttpResponse(HTTP_1_1, UNAUTHORIZED);
                response.headers().set("WWW-Authenticate", "Basic realm=\"" + security.getRealm() + "\"");
                response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
                response.headers().set(Exchange.CONTENT_LENGTH, 0);
                response.setContent(ChannelBuffers.copiedBuffer(new byte[] {}));
                messageEvent.getChannel().write(response).syncUninterruptibly();
                messageEvent.getChannel().close();
                return;
            } else {
                LOG.debug("Http Basic Auth authorized for username: {}", principal.getUsername());
            }
        }
    }
    // let Camel process this message
    // It did the way as camel-netty component does
    super.messageReceived(ctx, messageEvent);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) NettyHttpSecurityConfiguration(org.apache.camel.component.netty.http.NettyHttpSecurityConfiguration) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) URI(java.net.URI) HttpPrincipal(org.apache.camel.component.netty.http.HttpPrincipal) Subject(javax.security.auth.Subject)

Example 7 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project camel by apache.

the class NettyHttpConverter method convertToHttpRequest.

/**
     * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types.
     */
@FallbackConverter
public static Object convertToHttpRequest(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // if we want to covert to HttpRequest
    if (value != null && HttpRequest.class.isAssignableFrom(type)) {
        // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage
        // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the
        // HttpRequest from the NettyHttpMessage
        NettyHttpMessage msg;
        if (exchange.hasOut()) {
            msg = exchange.getOut(NettyHttpMessage.class);
        } else {
            msg = exchange.getIn(NettyHttpMessage.class);
        }
        if (msg != null && msg.getBody() == value) {
            // ensure the http request content is reset so we can read all the content out-of-the-box
            HttpRequest request = msg.getHttpRequest();
            request.getContent().resetReaderIndex();
            return request;
        }
    }
    return null;
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) FallbackConverter(org.apache.camel.FallbackConverter)

Example 8 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project camel by apache.

the class NettyHttpEndpoint method createExchange.

@Override
public Exchange createExchange(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    Exchange exchange = createExchange();
    // use the http binding
    HttpRequest request = (HttpRequest) messageEvent.getMessage();
    Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
    exchange.setIn(in);
    // setup the common message headers 
    updateMessageHeader(in, ctx, messageEvent);
    // honor the character encoding
    String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class);
    String charset = NettyHttpHelper.getCharsetFromContentType(contentType);
    if (charset != null) {
        exchange.setProperty(Exchange.CHARSET_NAME, charset);
        in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset);
    }
    return exchange;
}
Also used : Exchange(org.apache.camel.Exchange) HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) Message(org.apache.camel.Message)

Example 9 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project cdap by caskdata.

the class SecurityAuthenticationHttpHandler method messageReceived.

@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent event) throws Exception {
    Object msg = event.getMessage();
    if (!(msg instanceof HttpRequest)) {
        super.messageReceived(ctx, event);
    } else {
        AuditLogEntry logEntry = new AuditLogEntry();
        ctx.setAttachment(logEntry);
        HttpRequest req = (HttpRequest) msg;
        if (matchBypassPattern(req) || validateSecuredInterception(ctx, req, event.getChannel(), logEntry)) {
            Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress());
        }
    // we write the response directly for authentication failure, so nothing to do for else
    }
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) AuditLogEntry(co.cask.cdap.common.logging.AuditLogEntry) JsonObject(com.google.gson.JsonObject)

Example 10 with HttpRequest

use of org.jboss.netty.handler.codec.http.HttpRequest in project cdap by caskdata.

the class AuthenticationChannelHandler method messageReceived.

/**
   * Decode the AccessTokenIdentifier passed as a header and set it in a ThreadLocal.
   * Returns a 401 if the identifier is malformed.
   */
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Object message = e.getMessage();
    if (message instanceof HttpRequest) {
        // TODO: authenticate the user using user id - CDAP-688
        HttpRequest request = (HttpRequest) message;
        currentUserId = request.getHeader(Constants.Security.Headers.USER_ID);
        currentUserIP = request.getHeader(Constants.Security.Headers.USER_IP);
        SecurityRequestContext.setUserId(currentUserId);
        SecurityRequestContext.setUserIP(currentUserIP);
    } else if (message instanceof HttpChunk) {
        SecurityRequestContext.setUserId(currentUserId);
        SecurityRequestContext.setUserIP(currentUserIP);
    }
    super.messageReceived(ctx, e);
}
Also used : HttpRequest(org.jboss.netty.handler.codec.http.HttpRequest) HttpChunk(org.jboss.netty.handler.codec.http.HttpChunk)

Aggregations

HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)136 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)69 Channel (org.jboss.netty.channel.Channel)47 Test (org.junit.Test)47 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)46 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)43 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)31 ChannelFuture (org.jboss.netty.channel.ChannelFuture)26 List (java.util.List)19 ArrayList (java.util.ArrayList)17 Map (java.util.Map)17 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)17 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)17 InetSocketAddress (java.net.InetSocketAddress)14 ChannelHandlerContext (org.jboss.netty.channel.ChannelHandlerContext)13 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)13 SimpleHttpResponseHandler (com.linkedin.databus.core.test.netty.SimpleHttpResponseHandler)12 SimpleTestHttpClient (com.linkedin.databus.core.test.netty.SimpleTestHttpClient)12 Configuration (org.apache.hadoop.conf.Configuration)12 YarnConfiguration (org.apache.hadoop.yarn.conf.YarnConfiguration)12