use of org.jboss.netty.handler.codec.http.HttpResponse in project voldemort by voldemort.
the class CoordinatorAdminRequestHandler method sendResponse.
public HttpResponse sendResponse(HttpResponseStatus responseCode, String responseBody) {
String actualResponseBody = responseBody + "\n";
HttpResponse response = new DefaultHttpResponse(HTTP_1_1, responseCode);
response.setHeader(CONTENT_LENGTH, actualResponseBody.length());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
outputStream.write(actualResponseBody.getBytes());
} catch (IOException e) {
logger.error("IOException while trying to write the outputStream for an admin response", e);
throw new RuntimeException(e);
}
ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
responseContent.writeBytes(outputStream.toByteArray());
response.setContent(responseContent);
if (logger.isDebugEnabled()) {
logger.debug("Sent " + response);
}
return response;
}
use of org.jboss.netty.handler.codec.http.HttpResponse 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;
}
}
use of org.jboss.netty.handler.codec.http.HttpResponse in project cdap by caskdata.
the class SecurityAuthenticationHttpHandler method writeRequested.
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
AuditLogEntry logEntry = getLogEntry(ctx);
boolean isLogResponseBody = logEntry.isLogResponseBody();
Object message = e.getMessage();
if (message instanceof HttpResponse) {
HttpResponse response = (HttpResponse) message;
logEntry.setResponseCode(response.getStatus().getCode());
if (isLogResponseBody) {
ChannelBuffer body = response.getContent();
if (body.readable()) {
logEntry.setResponseBody(body.toString(Charsets.UTF_8));
}
}
if (response.containsHeader(HttpHeaders.Names.CONTENT_LENGTH)) {
String lengthString = response.getHeader(HttpHeaders.Names.CONTENT_LENGTH);
try {
logEntry.setResponseContentLength(Long.valueOf(lengthString));
} catch (NumberFormatException nfe) {
LOG.warn("Invalid value for content length in HTTP response message: {}", lengthString, nfe);
}
}
} else if (message instanceof ChannelBuffer) {
// for chunked responses the response code will only be present on the first chunk
// so we only look for it the first time around
ChannelBuffer channelBuffer = (ChannelBuffer) message;
if (logEntry.getResponseCode() == null) {
logEntry.setResponseCode(findResponseCode(channelBuffer));
if (logEntry.getResponseCode() != null) {
// we currently only look for a Content-Length header in the first buffer on an HTTP response
// this is a limitation of the implementation that simplifies header parsing
logEntry.setResponseContentLength(findContentLength(channelBuffer));
if (isLogResponseBody) {
logEntry.setResponseBody(findResponseBody(channelBuffer, true));
}
}
} else if (isLogResponseBody) {
logEntry.appendResponseBody(findResponseBody(channelBuffer, false));
}
} else {
LOG.debug("Unhandled response message type: {}", message.getClass());
}
super.writeRequested(ctx, e);
}
use of org.jboss.netty.handler.codec.http.HttpResponse in project cdap by caskdata.
the class HttpRequestHandler method exceptionCaught.
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
Throwable cause = e.getCause();
// avoid handling exception more than once from a handler, to avoid a possible infinite recursion
switch(exceptionsHandled.incrementAndGet()) {
case 1:
// if this is the first error, break and handle the error normally (below)
break;
case 2:
// if its the second time, log and return
LOG.error("Not handling exception due to already having handled an exception in Request Handler {}", ctx.getChannel(), cause);
// fall through
default:
// in an exception and cause recursion
return;
}
if (cause instanceof HandlerException && ((HandlerException) cause).getFailureStatus() != HttpResponseStatus.INTERNAL_SERVER_ERROR) {
LOG.debug("Exception raised in Request Handler {}", ctx.getChannel(), cause);
} else {
LOG.error("Exception raised in Request Handler {}", ctx.getChannel(), cause);
}
if (ctx.getChannel().isConnected() && !channelClosed) {
HttpResponse response = cause instanceof HandlerException ? ((HandlerException) cause).createFailureResponse() : new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
Channels.write(ctx, e.getFuture(), response);
e.getFuture().addListener(ChannelFutureListener.CLOSE);
}
}
use of org.jboss.netty.handler.codec.http.HttpResponse 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);
}
Aggregations