Skip to content

Commit

Permalink
Merge pull request #33 from s4nchez/master
Browse files Browse the repository at this point in the history
Prevent malformed flash cookie from breaking requests
  • Loading branch information
danielbodart committed Mar 15, 2016
2 parents d9250b8 + d979539 commit 96810c3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/com/googlecode/utterlyidle/flash/FlashHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
import com.googlecode.utterlyidle.cookies.CookieAttribute;
import com.googlecode.utterlyidle.cookies.CookieParameters;

import java.util.Map;

import static com.googlecode.totallylazy.Maps.map;
import static com.googlecode.totallylazy.Pair.pair;
import static com.googlecode.totallylazy.Sequences.sequence;
import static com.googlecode.totallylazy.Strings.isBlank;
Expand Down Expand Up @@ -54,7 +57,15 @@ private static void setIncomingFlashValues(Request request, Flash flash) {
if (!requestCookies.contains(FLASH_COOKIE) || isEmptyJson(requestCookies.getValue(FLASH_COOKIE)) || isBlank(requestCookies.getValue(FLASH_COOKIE)))
return;

flash.merge(Json.parseMap(requestCookies.getValue(FLASH_COOKIE)).value());
flash.merge(safelyParse(requestCookies.getValue(FLASH_COOKIE)));
}

private static Map<String, Object> safelyParse(final String value) {
try {
return Json.parseMap(value).value();
} catch (RuntimeException ignored) {
}
return map();
}

private Response setFlashCookie(Request request, Response response) {
Expand Down
8 changes: 8 additions & 0 deletions test/com/googlecode/utterlyidle/flash/FlashHandlerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import static com.googlecode.utterlyidle.Request.get;
import static com.googlecode.utterlyidle.Request.post;
import static com.googlecode.utterlyidle.Response.response;
import static com.googlecode.utterlyidle.Status.NO_CONTENT;
import static com.googlecode.utterlyidle.Status.OK;
import static com.googlecode.utterlyidle.annotations.AnnotatedBindings.annotatedClass;
import static com.googlecode.utterlyidle.cookies.CookieAttribute.httpOnly;
Expand Down Expand Up @@ -95,6 +96,13 @@ public void shouldAppendValuesToFlashUntilASuccessfulResponseIsReturned() throws
is(Json.json(Maps.map("key", list("Error 1", "Error 2")))));
}

@Test
public void handlesCorruptedJsonCookie() throws Exception {
Response response = application.handle(Request.get("/get", cookie(FLASH_COOKIE, "invalid cookie")));

assertThat(response.status(), is(NO_CONTENT));
}

@Test
public void onlySetCookieIfValueChanges() throws Exception {
Response response = application.handle(withFlashCookie(CLEARED_FLASH_COOKIE_VALUE, Request.get("/hi")));
Expand Down

0 comments on commit 96810c3

Please sign in to comment.