diff --git a/aws_lambda_powertools/shared/cookies.py b/aws_lambda_powertools/shared/cookies.py index 134258c0622..7c03ffa557b 100644 --- a/aws_lambda_powertools/shared/cookies.py +++ b/aws_lambda_powertools/shared/cookies.py @@ -1,11 +1,12 @@ from __future__ import annotations +from datetime import datetime, timedelta, timezone from enum import Enum from io import StringIO from typing import TYPE_CHECKING if TYPE_CHECKING: - from datetime import datetime + from datetime import date class SameSite(Enum): @@ -24,9 +25,28 @@ class SameSite(Enum): NONE_MODE = "None" -def _format_date(timestamp: datetime) -> str: +def _to_utc(timestamp: date) -> datetime: + # A date (which strftime accepted) means midnight + if not isinstance(timestamp, datetime): + timestamp = datetime(timestamp.year, timestamp.month, timestamp.day) + + # A naive datetime has no offset and is taken as UTC + offset = timestamp.utcoffset() or timedelta(0) + try: + in_utc = timestamp.replace(tzinfo=None) - offset + except OverflowError: + # The instant is before year 1 or after year 9999: use the closest date format_datetime can write + in_utc = datetime.min if offset > timedelta(0) else datetime.max + return in_utc.replace(tzinfo=timezone.utc) + + +def _format_date(timestamp: date) -> str: + # Imported on first use: the event handler imports this module but does not otherwise load email.utils + from email.utils import format_datetime + # Specification example: Wed, 21 Oct 2015 07:28:00 GMT - return timestamp.strftime("%a, %d %b %Y %H:%M:%S GMT") + # Unlike strftime, format_datetime uses English day and month names whatever the LC_TIME locale + return format_datetime(_to_utc(timestamp), usegmt=True) class Cookie: @@ -69,7 +89,8 @@ def __init__( max_age: int | None Defines the period of time after which the cookie is invalid. Use negative values to force cookie deletion. expires: datetime | None - Defines a date where the permanent cookie expires. + Defines a date where the permanent cookie expires. A timezone-aware datetime is sent as the same + instant in GMT; a naive one is taken as UTC. same_site: SameSite | None Determines if the cookie should be sent to third party websites custom_attributes: list[str] | None diff --git a/tests/functional/event_handler/required_dependencies/test_api_gateway.py b/tests/functional/event_handler/required_dependencies/test_api_gateway.py index 4f8d49d2a10..8c72ed839ae 100644 --- a/tests/functional/event_handler/required_dependencies/test_api_gateway.py +++ b/tests/functional/event_handler/required_dependencies/test_api_gateway.py @@ -6,6 +6,7 @@ import zlib from collections import deque from copy import deepcopy +from datetime import datetime, timedelta, timezone from decimal import Decimal from enum import Enum from functools import partial @@ -159,6 +160,30 @@ def get_lambda() -> Response: assert result["multiValueHeaders"]["Set-Cookie"] == ["CookieMonster=MonsterCookie; Secure"] +def test_api_gateway_v1_cookie_expires_in_gmt(): + # GIVEN a Http API V1 proxy type event + app = APIGatewayRestResolver() + # AND a cookie that expires at 12:00 in UTC+2, which is 10:00 UTC + cookie = Cookie( + name="CookieMonster", + value="MonsterCookie", + expires=datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2))), + ) + + @app.get("/my/path") + def get_lambda() -> Response: + return Response(200, content_types.TEXT_PLAIN, "Hello world", cookies=[cookie]) + + # WHEN calling the event handler + result = app(LOAD_GW_EVENT, {}) + + # THEN the cookie is sent with the same instant in GMT + assert result["statusCode"] == 200 + assert result["multiValueHeaders"]["Set-Cookie"] == [ + "CookieMonster=MonsterCookie; Expires=Thu, 01 Jan 2026 10:00:00 GMT; Secure", + ] + + def test_api_gateway(): # GIVEN a Rest API Gateway proxy type event app = ApiGatewayResolver(proxy_type=ProxyEventType.APIGatewayProxyEvent) @@ -257,6 +282,28 @@ def my_path() -> Response: assert result["cookies"] == ["CookieMonster=MonsterCookie; Secure"] +def test_api_gateway_v2_cookie_expires_in_gmt(): + # GIVEN a Http API V2 proxy type event + app = APIGatewayHttpResolver() + # AND a cookie that expires at 12:00 in UTC+2, which is 10:00 UTC + cookie = Cookie( + name="CookieMonster", + value="MonsterCookie", + expires=datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2))), + ) + + @app.post("/my/path") + def my_path() -> Response: + return Response(200, content_types.TEXT_PLAIN, "Hello world", cookies=[cookie]) + + # WHEN calling the event handler + result = app(load_event("apiGatewayProxyV2Event.json"), {}) + + # THEN the cookie is sent with the same instant in GMT + assert result["statusCode"] == 200 + assert result["cookies"] == ["CookieMonster=MonsterCookie; Expires=Thu, 01 Jan 2026 10:00:00 GMT; Secure"] + + def test_include_rule_matching(): # GIVEN app = ApiGatewayResolver() diff --git a/tests/unit/test_cookie_class.py b/tests/unit/test_cookie_class.py index b32010bb9a1..7f4c0e49bb8 100644 --- a/tests/unit/test_cookie_class.py +++ b/tests/unit/test_cookie_class.py @@ -1,6 +1,8 @@ from __future__ import annotations -from datetime import datetime +from datetime import date, datetime, timedelta, timezone + +import pytest from aws_lambda_powertools.shared.cookies import Cookie, SameSite @@ -54,6 +56,63 @@ def test_cookie_with_expires(): assert str(cookie) == "powertools=test; Path=/; Expires=Sat, 31 Dec 2022 00:00:00 GMT; Secure" +def test_cookie_with_expires_in_another_timezone(): + # GIVEN a cookie that expires at 12:00 in UTC+2, which is 10:00 UTC + time_to_expire = datetime(2026, 1, 1, 12, tzinfo=timezone(timedelta(hours=2))) + cookie = Cookie(name="powertools", value="test", path="/", expires=time_to_expire) + + # WHEN getting the cookie's attributes + # THEN Expires should be the same instant in GMT + assert str(cookie) == "powertools=test; Path=/; Expires=Thu, 01 Jan 2026 10:00:00 GMT; Secure" + + +def test_cookie_with_expires_and_non_english_locale(): + # GIVEN an expiry datetime whose strftime names days and months in German, like after + # locale.setlocale(locale.LC_TIME, "de_DE.UTF-8"), without needing that locale installed + class GermanLocaleDatetime(datetime): + def strftime(self, fmt): + return super().strftime(fmt.replace("%a", "Fr.").replace("%b", "Okt.")) + + cookie = Cookie(name="powertools", value="test", path="/", expires=GermanLocaleDatetime(2026, 10, 30, 7, 28)) + + # WHEN getting the cookie's attributes + # THEN Expires should use the English day and month names browsers can parse + assert str(cookie) == "powertools=test; Path=/; Expires=Fri, 30 Oct 2026 07:28:00 GMT; Secure" + + +def test_cookie_with_expires_date(): + # GIVEN a cookie that expires on a date rather than a datetime + cookie = Cookie(name="powertools", value="test", path="/", expires=date(2026, 1, 1)) + + # WHEN getting the cookie's attributes + # THEN Expires should be midnight GMT of that date + assert str(cookie) == "powertools=test; Path=/; Expires=Thu, 01 Jan 2026 00:00:00 GMT; Secure" + + +@pytest.mark.parametrize( + "time_to_expire, expected", + [ + pytest.param( + datetime.max.replace(tzinfo=timezone(timedelta(hours=-5))), + "Fri, 31 Dec 9999 23:59:59 GMT", + id="after year 9999 in UTC", + ), + pytest.param( + datetime.min.replace(tzinfo=timezone(timedelta(hours=5))), + "Mon, 01 Jan 0001 00:00:00 GMT", + id="before year 1 in UTC", + ), + ], +) +def test_cookie_with_expires_outside_years_1_to_9999_in_utc(time_to_expire, expected): + # GIVEN a cookie whose expiry is an instant that UTC cannot represent + cookie = Cookie(name="powertools", value="test", path="/", expires=time_to_expire) + + # WHEN getting the cookie's attributes + # THEN Expires should be the closest date that can be written, without raising + assert str(cookie) == f"powertools=test; Path=/; Expires={expected}; Secure" + + def test_cookie_with_max_age_positive(): # GIVEN a cookie with a positive max age cookie = Cookie(name="powertools", value="test", path="/", max_age=100)