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
Changes from 1 commit
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
Next Next commit
Implemented String-based cookie handling.
kennethjor committed Nov 16, 2021
commit ad4911b79b6ca183c2e7eebd26fdb885e62398e9
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;
}
}
25 changes: 24 additions & 1 deletion src/main/java/io/cdap/http/internal/HttpResourceModel.java
Original file line number Diff line number Diff line change
@@ -23,6 +23,7 @@
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 java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@@ -36,6 +37,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;
@@ -48,7 +50,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;
@@ -58,6 +61,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.
@@ -125,6 +129,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) {
@@ -137,6 +143,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++;
}

@@ -195,6 +204,17 @@ 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(defaultValue(annotations));
return hasCookie ? info.convert(cookies.get(cookieName)) : null;
}

/**
* Returns a List of String created based on the {@link DefaultValue} if it is presented in the annotations Map.
*
@@ -239,6 +259,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);
}
21 changes: 21 additions & 0 deletions src/main/java/io/cdap/http/internal/ParamConvertUtils.java
Original file line number Diff line number Diff line change
@@ -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;
@@ -89,6 +90,26 @@ 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();
}
};
}
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:
28 changes: 27 additions & 1 deletion src/test/java/io/cdap/http/HttpServerTest.java
Original file line number Diff line number Diff line change
@@ -42,6 +42,9 @@
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.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;
@@ -542,7 +545,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());

@@ -697,6 +700,29 @@ 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 {
String cookie = ClientCookieEncoder.LAX.encode("ck1", "cookie value");
HttpURLConnection urlConn = request("/test/v1/stringCookieParam", HttpMethod.GET);
urlConn.addRequestProperty(HttpHeaderNames.COOKIE.toString(), cookie);
Assert.assertEquals(200, urlConn.getResponseCode());
Assert.assertEquals("ck1:cookie value", getContent(urlConn));
urlConn.disconnect();
}

@Test
public void testMultipleStringCookieParam() throws IOException {
String cookie = ClientCookieEncoder.LAX.encode(
new DefaultCookie("ck1", "cookie value 1"),
new DefaultCookie("ck2", "cookie value 2")
);
HttpURLConnection urlConn = request("/test/v1/multipleStringCookieParam", HttpMethod.GET);
urlConn.addRequestProperty(HttpHeaderNames.COOKIE.toString(), cookie);
Assert.assertEquals(200, urlConn.getResponseCode());
Assert.assertEquals("ck1:cookie value 1,ck2:cookie value 2", getContent(urlConn));
urlConn.disconnect();
}

@Test
public void testListHeaderParam() throws IOException {
List<String> names = Arrays.asList("name1", "name3", "name2", "name1");
14 changes: 14 additions & 0 deletions src/test/java/io/cdap/http/TestHandler.java
Original file line number Diff line number Diff line change
@@ -43,6 +43,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;
@@ -530,6 +531,19 @@ public void testSortedSetQueryParam(HttpRequest request, HttpResponder responder
responder.sendString(HttpResponseStatus.OK, GSON.toJson(ids));
}

@Path("/stringCookieParam")
@GET
public void stringCookieParam(HttpRequest request, HttpResponder responder, @CookieParam("ck1") 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("/listHeaderParam")
@GET
public void testListHeaderParam(HttpRequest request, HttpResponder responder,
55 changes: 55 additions & 0 deletions src/test/java/io/cdap/http/internal/CookieParserTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* 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.DefaultHttpHeaders;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
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 org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


public class CookieParserTest {
private CookieParser cookieParser = new CookieParser(false);

@Test
public void testCookieDecode() {
List<Cookie> cookies = Arrays.asList(
new DefaultCookie("c1", "v1"),
new DefaultCookie("c2", "v2")
);
String cookieHeader = ClientCookieEncoder.LAX.encode(cookies);
HttpHeaders headers = new DefaultHttpHeaders()
.set(HttpHeaderNames.COOKIE, cookieHeader);
DefaultHttpRequest request = new DefaultHttpRequest(HTTP_1_1, GET, "test", headers);
Map<String, Cookie> parsed = cookieParser.parseCookies(request);
Assert.assertEquals(new HashSet<>(Arrays.asList("c1", "c2")), parsed.keySet());
Assert.assertEquals(new HashSet<>(cookies), new HashSet<>(parsed.values()));
}
}