From b9bc6aad37def26977a2b3ef0ab279c879bb25e6 Mon Sep 17 00:00:00 2001 From: duonglaiquang Date: Thu, 12 Mar 2026 10:54:33 +0900 Subject: [PATCH] Fix a bug where cookies with Max-Age too big are not stored --- .../httpclient/HtmlUnitMaxAgeHandler.java | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/htmlunit/httpclient/HtmlUnitMaxAgeHandler.java b/src/main/java/org/htmlunit/httpclient/HtmlUnitMaxAgeHandler.java index e24b699e10..8d7e11b589 100644 --- a/src/main/java/org/htmlunit/httpclient/HtmlUnitMaxAgeHandler.java +++ b/src/main/java/org/htmlunit/httpclient/HtmlUnitMaxAgeHandler.java @@ -15,6 +15,7 @@ package org.htmlunit.httpclient; import java.util.Date; +import java.util.regex.Pattern; import org.apache.http.cookie.MalformedCookieException; import org.apache.http.cookie.SetCookie; @@ -25,22 +26,36 @@ * Customized BasicMaxAgeHandler for HtmlUnit. * * @author Ronald Brill + * @author Lai Quang Duong */ final class HtmlUnitMaxAgeHandler extends BasicMaxAgeHandler { + // Max-Age should be 400 days at most + // https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#section-5.5 + private static final int MAX_MAX_AGE = 400 * 24 * 60 * 60; + + private static final Pattern MAX_AGE_PATTERN = Pattern.compile("-?[0-9]+"); + @Override public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { Args.notNull(cookie, "Cookie"); - if (value == null) { + if (value == null || value.isEmpty()) { throw new MalformedCookieException("Missing value for 'max-age' attribute"); } - final int age; + if (!MAX_AGE_PATTERN.matcher(value).matches()) { + throw new MalformedCookieException("Invalid 'max-age' attribute: " + value); + } + if (value.startsWith("-")) { + cookie.setExpiryDate(new Date(0L)); + return; + } + int age; try { - age = Integer.parseInt(value); + age = Math.min(Integer.parseInt(value), MAX_MAX_AGE); } catch (final NumberFormatException e) { - throw new MalformedCookieException("Invalid 'max-age' attribute: " + value, e); + age = MAX_MAX_AGE; } cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); }