Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookie handling #104

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ netty-http
==========
A library to develop HTTP services with `Netty <http://netty.io/>`__. Supports the capability to route end-points based on `JAX-RS <https://jax-rs-spec.java.net/>`__-style annotations. Implements Guava's Service interface to manage the runtime-state of the HTTP service.

Need for this library
Need for this library
---------------------
`Netty <http://netty.io/>`__ is a powerful framework to write asynchronous event-driven high-performance applications. While it is relatively easy to write a RESTful HTTP service using netty, the mapping between HTTP routes to handlers is
not a straight-forward task.
Expand Down Expand Up @@ -142,7 +142,7 @@ Example: Sample HTTP service that manages an application lifecycle:

// Setup HTTP service and add Handlers

// You can either add varargs of HttpHandler or as a list of HttpHanlders as below to the NettyService Builder
// You can either add varargs of HttpHandler or as a list of HttpHandlers as below to the NettyService Builder

List<HttpHandler> handlers = new ArrayList<>();
handlers.add(new PingHandler());
Expand Down Expand Up @@ -175,7 +175,7 @@ Code Sample:
.setCertificatePassword("certificatePassword").build())
.build();

* Set ``String:certificatePassword`` as "null" when not applicable
* Set ``String:certificatePassword`` as "null" when not applicable
* ``File:keyStore`` points to the key store that holds your SSL certificate

References
Expand Down
58 changes: 58 additions & 0 deletions src/main/java/io/cdap/http/internal/CookieParser.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright © 2017-2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package io.cdap.http.internal;

import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.CookieDecoder;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* Parses cookies from a request.
*/
public class CookieParser {
private final boolean strict;

public CookieParser(boolean strict) {
this.strict = strict;
}

public Map<String, Cookie> parseCookies(HttpRequest request) {
List<String> headers = request.headers().getAll(HttpHeaderNames.COOKIE);
if (headers == null || headers.isEmpty()) {
return Collections.emptyMap();
}
ServerCookieDecoder decoder = getCookieDecoder();
Map<String, Cookie> cookies = new LinkedHashMap<>();
for (String value : headers) {
for (Cookie cookie : decoder.decode(value)) {
cookies.put(cookie.name(), cookie);
}
}
return cookies;
}

private ServerCookieDecoder getCookieDecoder() {
return strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX;
}
}
38 changes: 37 additions & 1 deletion src/main/java/io/cdap/http/internal/HttpResourceModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
Expand All @@ -36,6 +38,7 @@
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PathParam;
Expand All @@ -48,7 +51,8 @@
public final class HttpResourceModel {

private static final Set<Class<? extends Annotation>> SUPPORTED_PARAM_ANNOTATIONS =
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(PathParam.class, QueryParam.class, HeaderParam.class)));
Collections.unmodifiableSet(new HashSet<>(Arrays.asList(PathParam.class, QueryParam.class, HeaderParam.class,
CookieParam.class)));

private final Set<HttpMethod> httpMethods;
private final String path;
Expand All @@ -58,6 +62,7 @@ public final class HttpResourceModel {
private final ExceptionHandler exceptionHandler;
private final boolean isSecured;
private final String[] requiredRoles;
private final CookieParser cookieParser = new CookieParser(false);

/**
* Construct a resource model with HttpMethod, method that handles httprequest, Object that contains the method.
Expand Down Expand Up @@ -125,6 +130,8 @@ public HttpMethodInfo handle(HttpRequest request,
if (httpMethods.contains(request.method())) {
//Setup args for reflection call
Object [] args = new Object[paramsInfo.size()];
// Parse cookies
Map<String, Cookie> cookies = cookieParser.parseCookies(request);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One of the problems with parsing here is that an invalid cookie will cause the request to fail, even if the method doesn't care about it. It could potentially cause backwards incompatibilities, as somebody could upgrade this library and then see their requests failing due to some headers they never looked at before.

instead of parsing all the cookies here, it would be better to only lookup the relevant header in the getCookieParamValue() method and decode it there.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have moved it to the method so it will only be run on-demand. It does mean though that every cookie will result in parsing all the cookies. Is there a way to cache this? All the members on the HttpResourceModel are final and set in the constructor, so I wasn't sure if it would be ok to add a cookie parsing cache there, which is the approach I'd normally take.


int idx = 0;
for (Map<Class<? extends Annotation>, ParameterInfo<?>> info : paramsInfo) {
Expand All @@ -137,6 +144,9 @@ public HttpMethodInfo handle(HttpRequest request,
if (info.containsKey(HeaderParam.class)) {
args[idx] = getHeaderParamValue(info, request);
}
if (info.containsKey(CookieParam.class)) {
args[idx] = getCookieParamValue(info, request, cookies);
}
idx++;
}

Expand Down Expand Up @@ -195,6 +205,16 @@ private Object getHeaderParamValue(Map<Class<? extends Annotation>, ParameterInf
return hasHeader ? info.convert(request.headers().getAll(headerName)) : info.convert(defaultValue(annotations));
}

@SuppressWarnings("unchecked")
private Object getCookieParamValue(Map<Class<? extends Annotation>, ParameterInfo<?>> annotations,
HttpRequest request, Map<String, Cookie> cookies) throws Exception {
ParameterInfo<Cookie> info = (ParameterInfo<Cookie>) annotations.get(CookieParam.class);
CookieParam cookieParam = info.getAnnotation();
String cookieName = cookieParam.value();
boolean hasCookie = cookies.containsKey(cookieName);
return hasCookie ? info.convert(cookies.get(cookieName)) : info.convert(defaultCookie(cookieName, annotations));
}

/**
* Returns a List of String created based on the {@link DefaultValue} if it is presented in the annotations Map.
*
Expand All @@ -210,6 +230,19 @@ private List<String> defaultValue(Map<Class<? extends Annotation>, ParameterInfo
return Collections.singletonList(defaultValue.value());
}

/**
* Returns a Cookie created based on the {@link DefaultValue} if it is presented in the annotations Map.
*
* @return a Cookie or null if {@link DefaultValue} is not presented
*/
private Cookie defaultCookie(String name, Map<Class<? extends Annotation>, ParameterInfo<?>> annotations) {
List<String> strings = defaultValue(annotations);
if (strings == null || strings.isEmpty()) {
return null;
}
return new DefaultCookie(name, strings.get(0));
}

/**
* Gathers all parameters' annotations for the given method, starting from the third parameter.
*/
Expand Down Expand Up @@ -239,6 +272,9 @@ private List<Map<Class<? extends Annotation>, ParameterInfo<?>>> createParameter
} else if (HeaderParam.class.isAssignableFrom(annotationType)) {
parameterInfo = ParameterInfo.create(annotation,
ParamConvertUtils.createHeaderParamConverter(parameterTypes[i]));
} else if (CookieParam.class.isAssignableFrom(annotationType)) {
parameterInfo = ParameterInfo.create(annotation,
ParamConvertUtils.createCookieParamConverter(parameterTypes[i]));
} else {
parameterInfo = ParameterInfo.create(annotation, null);
}
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/io/cdap/http/internal/ParamConvertUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package io.cdap.http.internal;

import io.netty.handler.codec.http.cookie.Cookie;
import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.Array;
Expand Down Expand Up @@ -89,6 +90,37 @@ public static Converter<List<String>, Object> createHeaderParamConverter(Type re
return createListConverter(resultType);
}

/**
* Creates a converter function that converts cookie value into an object of the given result type.
* Currently, only {@link String} result types are supported.
*/
public static Converter<Cookie, Object> createCookieParamConverter(Type resultType) {
Class<?> resultClass = getRawClass(resultType);

// For string, return the cookie value
if (resultClass == String.class) {
return new Converter<Cookie, Object>() {
@Nullable
@Override
public Object convert(Cookie from) throws Exception {
return from.value();
}
};
}
// For cookie objects, convert appropriately.
if (resultClass == Cookie.class) {
return new Converter<Cookie, Object>() {
@Nullable
@Override
public Object convert(Cookie from) throws Exception {
return from;
}
};
}

throw new IllegalArgumentException("Unsupported CookieParam type " + resultType);
}

/**
* Creates a converter function that converts query parameter into an object of the given result type.
* It follows the supported types of {@link QueryParam} with the following exceptions:
Expand Down
45 changes: 44 additions & 1 deletion src/test/java/io/cdap/http/HttpServerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.cookie.ClientCookieEncoder;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.cookie.ServerCookieEncoder;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.ResourceLeakDetector;
Expand Down Expand Up @@ -82,6 +86,7 @@
import java.util.zip.DeflaterInputStream;
import java.util.zip.GZIPInputStream;
import javax.annotation.Nullable;
import javax.ws.rs.ext.RuntimeDelegate;

/**
* Test the HttpServer.
Expand Down Expand Up @@ -542,7 +547,7 @@ public void testMultiplePathParameters() throws IOException {

//Test the end point where the parameter in path and order of declaration in method signature are different
@Test
public void testMultiplePathParametersWithParamterInDifferentOrder() throws IOException {
public void testMultiplePathParametersWithParameterInDifferentOrder() throws IOException {
HttpURLConnection urlConn = request("/test/v1/message/21/user/sree", HttpMethod.GET);
Assert.assertEquals(200, urlConn.getResponseCode());

Expand Down Expand Up @@ -697,6 +702,35 @@ public void testSortedSetQueryParam() throws IOException {
testContent("/test/v1/sortedSetQueryParam?id=20&id=30&id=20&id=10", expectedContent, HttpMethod.GET);
}

@Test
public void testStringCookieParam() throws IOException {
testContent("/test/v1/stringCookieParam", "ck1:cookie value",
new DefaultCookie("ck1", "cookie value"));
}

@Test
public void testStringCookieParamDefaultValue() throws IOException {
testContent("/test/v1/stringCookieParam", "ck1:def", new Cookie[0]);
}

@Test
public void testMultipleStringCookieParam() throws IOException {
testContent("/test/v1/multipleStringCookieParam", "ck1:cookie value 1,ck2:cookie value 2",
new DefaultCookie("ck1", "cookie value 1"),
new DefaultCookie("ck2", "cookie value 2"));
}

@Test
public void testNettyCookieCookieParam() throws IOException {
testContent("/test/v1/nettyCookieParam", "ck1:cookie value",
new DefaultCookie("ck1", "cookie value"));
}

@Test
public void testNettyCookieParamDefaultValue() throws IOException {
testContent("/test/v1/nettyCookieParam", "ck1:def", new Cookie[0]);
}

@Test
public void testListHeaderParam() throws IOException {
List<String> names = Arrays.asList("name1", "name3", "name2", "name1");
Expand Down Expand Up @@ -972,6 +1006,15 @@ private void testContent(String path, String content, HttpMethod method) throws
urlConn.disconnect();
}

private void testContent(String path, String content, Cookie... cookies) throws IOException {
String cookie = ClientCookieEncoder.LAX.encode(cookies);
HttpURLConnection urlConn = request(path, HttpMethod.GET);
urlConn.addRequestProperty(HttpHeaderNames.COOKIE.toString(), cookie);
Assert.assertEquals(200, urlConn.getResponseCode());
Assert.assertEquals(content, getContent(urlConn));
urlConn.disconnect();
}

private HttpURLConnection request(String path, HttpMethod method) throws IOException {
return request(path, method, false);
}
Expand Down
24 changes: 24 additions & 0 deletions src/test/java/io/cdap/http/TestHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import org.junit.Assert;

import java.io.File;
Expand All @@ -43,6 +45,7 @@
import java.util.SortedSet;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.ws.rs.CookieParam;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
Expand Down Expand Up @@ -530,6 +533,27 @@ public void testSortedSetQueryParam(HttpRequest request, HttpResponder responder
responder.sendString(HttpResponseStatus.OK, GSON.toJson(ids));
}

@Path("/stringCookieParam")
@GET
public void testStringCookieParam(HttpRequest request, HttpResponder responder,
@CookieParam("ck1") @DefaultValue("def") String ck1) {
responder.sendString(HttpResponseStatus.OK, "ck1:" + ck1);
}

@Path("/multipleStringCookieParam")
@GET
public void testMultipleStringCookieParam(HttpRequest request, HttpResponder responder,
@CookieParam("ck1") String ck1, @CookieParam("ck2") String ck2) {
responder.sendString(HttpResponseStatus.OK, "ck1:" + ck1 + ",ck2:" + ck2);
}

@Path("/nettyCookieParam")
@GET
public void testNettyCookieParam(HttpRequest request, HttpResponder responder,
@CookieParam("ck1") @DefaultValue("def") Cookie ck1) {
responder.sendString(HttpResponseStatus.OK, "ck1:" + ck1.value());
}

@Path("/listHeaderParam")
@GET
public void testListHeaderParam(HttpRequest request, HttpResponder responder,
Expand Down
Loading