Skip to content

Commit 30615f4

Browse files
committed
fix(event_handler): send cookie Expires in GMT with English day and month names
A timezone-aware expires was formatted as its local wall-clock time with a GMT suffix, so the cookie expired early or late by the UTC offset. strftime's %a and %b also followed the process LC_TIME locale, producing names browsers cannot parse. Convert aware datetimes to UTC and format with email.utils.format_datetime. Naive datetimes keep being read as UTC and a date keeps meaning midnight GMT. An instant outside years 1 to 9999 is clamped instead of raising OverflowError.
1 parent a2eb4d5 commit 30615f4

3 files changed

Lines changed: 132 additions & 5 deletions

File tree

‎aws_lambda_powertools/shared/cookies.py‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
from __future__ import annotations
22

3+
from datetime import datetime, timedelta, timezone
34
from enum import Enum
45
from io import StringIO
56
from typing import TYPE_CHECKING
67

78
if TYPE_CHECKING:
8-
from datetime import datetime
9+
from datetime import date
910

1011

1112
class SameSite(Enum):
@@ -24,9 +25,28 @@ class SameSite(Enum):
2425
NONE_MODE = "None"
2526

2627

27-
def _format_date(timestamp: datetime) -> str:
28+
def _to_utc(timestamp: date) -> datetime:
29+
# A date (which strftime accepted) means midnight
30+
if not isinstance(timestamp, datetime):
31+
timestamp = datetime(timestamp.year, timestamp.month, timestamp.day)
32+
33+
# A naive datetime has no offset and is taken as UTC
34+
offset = timestamp.utcoffset() or timedelta(0)
35+
try:
36+
in_utc = timestamp.replace(tzinfo=None) - offset
37+
except OverflowError:
38+
# The instant is before year 1 or after year 9999: use the closest date format_datetime can write
39+
in_utc = datetime.min if offset > timedelta(0) else datetime.max
40+
return in_utc.replace(tzinfo=timezone.utc)
41+
42+
43+
def _format_date(timestamp: date) -> str:
44+
# Imported on first use: the event handler imports this module but does not otherwise load email.utils
45+
from email.utils import format_datetime
46+
2847
# Specification example: Wed, 21 Oct 2015 07:28:00 GMT
29-
return timestamp.strftime("%a, %d %b %Y %H:%M:%S GMT")
48+
# Unlike strftime, format_datetime uses English day and month names whatever the LC_TIME locale
49+
return format_datetime(_to_utc(timestamp), usegmt=True)
3050

3151

3252
class Cookie:
@@ -69,7 +89,8 @@ def __init__(
6989
max_age: int | None
7090
Defines the period of time after which the cookie is invalid. Use negative values to force cookie deletion.
7191
expires: datetime | None
72-
Defines a date where the permanent cookie expires.
92+
Defines a date where the permanent cookie expires. A timezone-aware datetime is sent as the same
93+
instant in GMT; a naive one is taken as UTC.
7394
same_site: SameSite | None
7495
Determines if the cookie should be sent to third party websites
7596
custom_attributes: list[str] | None

‎tests/functional/event_handler/required_dependencies/test_api_gateway.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import zlib
77
from collections import deque
88
from copy import deepcopy
9+
from datetime import datetime, timedelta, timezone
910
from decimal import Decimal
1011
from enum import Enum
1112
from functools import partial
@@ -159,6 +160,30 @@ def get_lambda() -> Response:
159160
assert result["multiValueHeaders"]["Set-Cookie"] == ["CookieMonster=MonsterCookie; Secure"]
160161

161162

163+
def test_api_gateway_v1_cookie_expires_in_gmt():
164+
# GIVEN a Http API V1 proxy type event
165+
app = APIGatewayRestResolver()
166+
# AND a cookie that expires at 12:00 in UTC+2, which is 10:00 UTC
167+
cookie = Cookie(
168+
name="CookieMonster",
169+
value="MonsterCookie",
170+
expires=datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2))),
171+
)
172+
173+
@app.get("/my/path")
174+
def get_lambda() -> Response:
175+
return Response(200, content_types.TEXT_PLAIN, "Hello world", cookies=[cookie])
176+
177+
# WHEN calling the event handler
178+
result = app(LOAD_GW_EVENT, {})
179+
180+
# THEN the cookie is sent with the same instant in GMT
181+
assert result["statusCode"] == 200
182+
assert result["multiValueHeaders"]["Set-Cookie"] == [
183+
"CookieMonster=MonsterCookie; Expires=Thu, 01 Jan 2026 10:00:00 GMT; Secure",
184+
]
185+
186+
162187
def test_api_gateway():
163188
# GIVEN a Rest API Gateway proxy type event
164189
app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent)
@@ -257,6 +282,28 @@ def my_path() -> Response:
257282
assert result["cookies"] == ["CookieMonster=MonsterCookie; Secure"]
258283

259284

285+
def test_api_gateway_v2_cookie_expires_in_gmt():
286+
# GIVEN a Http API V2 proxy type event
287+
app = APIGatewayHttpResolver()
288+
# AND a cookie that expires at 12:00 in UTC+2, which is 10:00 UTC
289+
cookie = Cookie(
290+
name="CookieMonster",
291+
value="MonsterCookie",
292+
expires=datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2))),
293+
)
294+
295+
@app.post("/my/path")
296+
def my_path() -> Response:
297+
return Response(200, content_types.TEXT_PLAIN, "Hello world", cookies=[cookie])
298+
299+
# WHEN calling the event handler
300+
result = app(load_event("apiGatewayProxyV2Event.json"), {})
301+
302+
# THEN the cookie is sent with the same instant in GMT
303+
assert result["statusCode"] == 200
304+
assert result["cookies"] == ["CookieMonster=MonsterCookie; Expires=Thu, 01 Jan 2026 10:00:00 GMT; Secure"]
305+
306+
260307
def test_include_rule_matching():
261308
# GIVEN
262309
app = ApiGatewayResolver()

‎tests/unit/test_cookie_class.py‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from __future__ import annotations
22

3-
from datetime import datetime
3+
from datetime import date, datetime, timedelta, timezone
4+
5+
import pytest
46

57
from aws_lambda_powertools.shared.cookies import Cookie, SameSite
68

@@ -54,6 +56,63 @@ def test_cookie_with_expires():
5456
assert str(cookie) == "powertools=test; Path=/; Expires=Sat, 31 Dec 2022 00:00:00 GMT; Secure"
5557

5658

59+
def test_cookie_with_expires_in_another_timezone():
60+
# GIVEN a cookie that expires at 12:00 in UTC+2, which is 10:00 UTC
61+
time_to_expire = datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2)))
62+
cookie = Cookie(name="powertools", value="test", path="/", expires=time_to_expire)
63+
64+
# WHEN getting the cookie's attributes
65+
# THEN Expires should be the same instant in GMT
66+
assert str(cookie) == "powertools=test; Path=/; Expires=Thu, 01 Jan 2026 10:00:00 GMT; Secure"
67+
68+
69+
def test_cookie_with_expires_and_non_english_locale():
70+
# GIVEN an expiry datetime whose strftime names days and months in German, like after
71+
# locale.setlocale(locale.LC_TIME, "de_DE.UTF-8"), without needing that locale installed
72+
class GermanLocaleDatetime(datetime):
73+
def strftime(self, fmt):
74+
return super().strftime(fmt.replace("%a", "Fr.").replace("%b", "Okt."))
75+
76+
cookie = Cookie(name="powertools", value="test", path="/", expires=GermanLocaleDatetime(2026, 10, 30, 7, 28))
77+
78+
# WHEN getting the cookie's attributes
79+
# THEN Expires should use the English day and month names browsers can parse
80+
assert str(cookie) == "powertools=test; Path=/; Expires=Fri, 30 Oct 2026 07:28:00 GMT; Secure"
81+
82+
83+
def test_cookie_with_expires_date():
84+
# GIVEN a cookie that expires on a date rather than a datetime
85+
cookie = Cookie(name="powertools", value="test", path="/", expires=date(2026, 1, 1))
86+
87+
# WHEN getting the cookie's attributes
88+
# THEN Expires should be midnight GMT of that date
89+
assert str(cookie) == "powertools=test; Path=/; Expires=Thu, 01 Jan 2026 00:00:00 GMT; Secure"
90+
91+
92+
@pytest.mark.parametrize(
93+
"time_to_expire, expected",
94+
[
95+
pytest.param(
96+
datetime.max.replace(tzinfo=timezone(timedelta(hours=-5))),
97+
"Fri, 31 Dec 9999 23:59:59 GMT",
98+
id="after year 9999 in UTC",
99+
),
100+
pytest.param(
101+
datetime.min.replace(tzinfo=timezone(timedelta(hours=5))),
102+
"Mon, 01 Jan 0001 00:00:00 GMT",
103+
id="before year 1 in UTC",
104+
),
105+
],
106+
)
107+
def test_cookie_with_expires_outside_years_1_to_9999_in_utc(time_to_expire, expected):
108+
# GIVEN a cookie whose expiry is an instant that UTC cannot represent
109+
cookie = Cookie(name="powertools", value="test", path="/", expires=time_to_expire)
110+
111+
# WHEN getting the cookie's attributes
112+
# THEN Expires should be the closest date that can be written, without raising
113+
assert str(cookie) == f"powertools=test; Path=/; Expires={expected}; Secure"
114+
115+
57116
def test_cookie_with_max_age_positive():
58117
# GIVEN a cookie with a positive max age
59118
cookie = Cookie(name="powertools", value="test", path="/", max_age=100)

0 commit comments

Comments
 (0)