diff --git a/java/test/org/openqa/selenium/environment/webserver/CookieHandler.java b/java/test/org/openqa/selenium/environment/webserver/CookieHandler.java index a6abb8ca9c10a..b28d09bb15072 100644 --- a/java/test/org/openqa/selenium/environment/webserver/CookieHandler.java +++ b/java/test/org/openqa/selenium/environment/webserver/CookieHandler.java @@ -116,9 +116,9 @@ private Collection 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); @@ -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("<"); + break; + case '>': + cookieValue.append(">"); + break; + case '&': + cookieValue.append("&"); + break; + default: + cookieValue.append(c); // Append safe characters as they are + } + } + return cookieValue.toString(); + } }