From 7067295e67bf051546c6d3580368da3889a87302 Mon Sep 17 00:00:00 2001 From: Raphael Deem Date: Thu, 3 Jan 2019 15:01:54 -0800 Subject: [PATCH] enforce integer for max-age cookie --- sanic/cookies.py | 4 ++++ tests/test_cookies.py | 10 +++++++--- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/sanic/cookies.py b/sanic/cookies.py index 13526555..8988af41 100644 --- a/sanic/cookies.py +++ b/sanic/cookies.py @@ -1,6 +1,7 @@ import re import string +DEFAULT_MAX_AGE = 0 # ------------------------------------------------------------ # # SimpleCookie @@ -103,6 +104,9 @@ class Cookie(dict): if key not in self._keys: raise KeyError("Unknown cookie property") if value is not False: + if key.lower() == "max-age": + if not str(value).isdigit(): + value = DEFAULT_MAX_AGE return super().__setitem__(key, value) def encode(self, encoding): diff --git a/tests/test_cookies.py b/tests/test_cookies.py index 4a7d4e18..0cff041c 100644 --- a/tests/test_cookies.py +++ b/tests/test_cookies.py @@ -2,7 +2,7 @@ from datetime import datetime, timedelta from http.cookies import SimpleCookie from sanic.response import text import pytest -from sanic.cookies import Cookie +from sanic.cookies import Cookie, DEFAULT_MAX_AGE # ------------------------------------------------------------ # # GET @@ -138,7 +138,7 @@ def test_cookie_set_same_key(app): assert response.cookies["test"].value == "pass" -@pytest.mark.parametrize("max_age", ["0", 30, "30"]) +@pytest.mark.parametrize("max_age", ["0", 30, "30", "test"]) def test_cookie_max_age(app, max_age): cookies = {"test": "wait"} @@ -153,7 +153,11 @@ def test_cookie_max_age(app, max_age): assert response.status == 200 assert response.cookies["test"].value == "pass" - assert response.cookies["test"]["max-age"] == str(max_age) + + if str(max_age).isdigit(): + assert response.cookies["test"]["max-age"] == str(max_age) + else: + assert response.cookies["test"]["max-age"] == str(DEFAULT_MAX_AGE) @pytest.mark.parametrize(