Skip to content

Commit d15e143

Browse files
duonglaiquangrbri
authored andcommitted
Fix a bug where cookies with Max-Age too big are not stored
1 parent 845916c commit d15e143

1 file changed

Lines changed: 19 additions & 4 deletions

File tree

src/main/java/org/htmlunit/httpclient/HtmlUnitMaxAgeHandler.java

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package org.htmlunit.httpclient;
1616

1717
import java.util.Date;
18+
import java.util.regex.Pattern;
1819

1920
import org.apache.http.cookie.MalformedCookieException;
2021
import org.apache.http.cookie.SetCookie;
@@ -25,22 +26,36 @@
2526
* Customized BasicMaxAgeHandler for HtmlUnit.
2627
*
2728
* @author Ronald Brill
29+
* @author Lai Quang Duong
2830
*/
2931
final class HtmlUnitMaxAgeHandler extends BasicMaxAgeHandler {
3032

33+
// Max-Age should be 400 days at most
34+
// https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#section-5.5
35+
private static final int MAX_MAX_AGE = 400 * 24 * 60 * 60;
36+
37+
private static final Pattern MAX_AGE_PATTERN = Pattern.compile("-?[0-9]+");
38+
3139
@Override
3240
public void parse(final SetCookie cookie, final String value)
3341
throws MalformedCookieException {
3442
Args.notNull(cookie, "Cookie");
35-
if (value == null) {
43+
if (value == null || value.isEmpty()) {
3644
throw new MalformedCookieException("Missing value for 'max-age' attribute");
3745
}
38-
final int age;
46+
if (!MAX_AGE_PATTERN.matcher(value).matches()) {
47+
throw new MalformedCookieException("Invalid 'max-age' attribute: " + value);
48+
}
49+
if (value.startsWith("-")) {
50+
cookie.setExpiryDate(new Date(0L));
51+
return;
52+
}
53+
int age;
3954
try {
40-
age = Integer.parseInt(value);
55+
age = Math.min(Integer.parseInt(value), MAX_MAX_AGE);
4156
}
4257
catch (final NumberFormatException e) {
43-
throw new MalformedCookieException("Invalid 'max-age' attribute: " + value, e);
58+
age = MAX_MAX_AGE;
4459
}
4560
cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
4661
}

0 commit comments

Comments
 (0)