Skip to content

Commit 375e841

Browse files
Delta456pujagani
andauthored
[java] Escape cookie values when required for tests (#14486)
Co-authored-by: Puja Jagani <[email protected]>
1 parent b8b76bb commit 375e841

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

java/test/org/openqa/selenium/environment/webserver/CookieHandler.java

+44-3
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,9 @@ private Collection<Cookie> getCookies(HttpRequest request) {
116116
private void addCookie(HttpResponse response, Cookie cook) {
117117
StringBuilder cookie = new StringBuilder();
118118

119-
// TODO: escape string as necessary
120-
String name = cook.getName();
121-
cookie.append(name).append("=").append(cook.getValue()).append("; ");
119+
String name = escapeCookieValue(cook.getName());
120+
String value = escapeCookieValue(cook.getValue());
121+
cookie.append(name).append("=").append(value).append("; ");
122122

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

192192
return builder.build();
193193
}
194+
195+
private String escapeCookieValue(String value) {
196+
if (value == null || value.isEmpty()) {
197+
return "";
198+
}
199+
200+
StringBuilder cookieValue = new StringBuilder();
201+
202+
for (char c : value.toCharArray()) {
203+
switch (c) {
204+
case '\\':
205+
cookieValue.append("\\\\");
206+
break;
207+
case '"':
208+
cookieValue.append("\\\"");
209+
break;
210+
case ';':
211+
cookieValue.append("\\;");
212+
break;
213+
case ',':
214+
cookieValue.append("\\,");
215+
break;
216+
case '\r':
217+
case '\n':
218+
// Skip carriage return and newline characters
219+
break;
220+
case '<':
221+
cookieValue.append("&lt;");
222+
break;
223+
case '>':
224+
cookieValue.append("&gt;");
225+
break;
226+
case '&':
227+
cookieValue.append("&amp;");
228+
break;
229+
default:
230+
cookieValue.append(c); // Append safe characters as they are
231+
}
232+
}
233+
return cookieValue.toString();
234+
}
194235
}

0 commit comments

Comments
 (0)