Skip to content

Commit

Permalink
[java] Escape cookie values when required for tests (#14486)
Browse files Browse the repository at this point in the history
Co-authored-by: Puja Jagani <[email protected]>
  • Loading branch information
Delta456 and pujagani authored Sep 17, 2024
1 parent b8b76bb commit 375e841
Showing 1 changed file with 44 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ private Collection<Cookie> getCookies(HttpRequest request) {
private void addCookie(HttpResponse response, Cookie cook) {
StringBuilder cookie = new StringBuilder();

// TODO: escape string as necessary
String name = cook.getName();
cookie.append(name).append("=").append(cook.getValue()).append("; ");
String name = escapeCookieValue(cook.getName());
String value = escapeCookieValue(cook.getValue());
cookie.append(name).append("=").append(value).append("; ");

append(cookie, cook.getDomain(), str -> "Domain=" + str);
append(cookie, cook.getPath(), str -> "Path=" + str);
Expand Down Expand Up @@ -191,4 +191,45 @@ private Cookie parse(String cookieString) {

return builder.build();
}

private String escapeCookieValue(String value) {
if (value == null || value.isEmpty()) {
return "";
}

StringBuilder cookieValue = new StringBuilder();

for (char c : value.toCharArray()) {
switch (c) {
case '\\':
cookieValue.append("\\\\");
break;
case '"':
cookieValue.append("\\\"");
break;
case ';':
cookieValue.append("\\;");
break;
case ',':
cookieValue.append("\\,");
break;
case '\r':
case '\n':
// Skip carriage return and newline characters
break;
case '<':
cookieValue.append("&lt;");
break;
case '>':
cookieValue.append("&gt;");
break;
case '&':
cookieValue.append("&amp;");
break;
default:
cookieValue.append(c); // Append safe characters as they are
}
}
return cookieValue.toString();
}
}

0 comments on commit 375e841

Please sign in to comment.