Skip to content

Commit 09c98be

Browse files
committed
gh-153677: Fix ValueError in http.cookiejar.http2time() for a strict-format fake month
The STRICT_DATE_RE fast path in http2time() matched date strings whose month field fit the pattern but named a non-existent month (for example "Foo"), then called MONTHS_LOWER.index() which raised a raw ValueError. The documented contract is to return None for unrecognized formats, and the slower parser already does so. Guard the fast-path month lookup and fall through to the slower parser on failure.
1 parent 832bc0b commit 09c98be

3 files changed

Lines changed: 18 additions & 4 deletions

File tree

Lib/http/cookiejar.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,16 @@ def http2time(text):
262262
m = STRICT_DATE_RE.search(text)
263263
if m:
264264
g = m.groups()
265-
mon = MONTHS_LOWER.index(g[1].lower()) + 1
266-
tt = (int(g[2]), mon, int(g[0]),
267-
int(g[3]), int(g[4]), float(g[5]))
268-
return _timegm(tt)
265+
try:
266+
mon = MONTHS_LOWER.index(g[1].lower()) + 1
267+
except ValueError:
268+
# The month field matched the pattern but is not a real month
269+
# name, so fall through to the slower parser.
270+
pass
271+
else:
272+
tt = (int(g[2]), mon, int(g[0]),
273+
int(g[3]), int(g[4]), float(g[5]))
274+
return _timegm(tt)
269275

270276
# No, we need some messy parsing...
271277

Lib/test/test_http_cookiejar.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,11 @@ def test_http2time_formats(self):
121121
'08-01-3697739',
122122
'09 Feb 19942632 22:23:32 GMT',
123123
'Wed, 09 Feb 1994834 22:23:32 GMT',
124+
# Strictly formatted string with a non-existent month name. The
125+
# month field matches the STRICT_DATE_RE fast path but is not a
126+
# real month, and must not leak a ValueError.
127+
'Wed, 09 Foo 1994 22:23:32 GMT',
128+
'Mon, 01 Aaa 2000 00:00:00 GMT',
124129
])
125130
def test_http2time_garbage(self, test):
126131
self.assertIsNone(http2time(test))
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`!http.cookiejar.http2time` now returns ``None`` instead of raising
2+
:exc:`ValueError` when the date string matches its strict fast-path pattern
3+
but names a month that does not exist. Patch by tonghuaroot.

0 commit comments

Comments
 (0)