Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 5571 #5839

Merged
merged 9 commits into from
Oct 24, 2021
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/5571.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add treat_as_secure_origin parameter to CookieJar init
33 changes: 30 additions & 3 deletions aiohttp/cookiejar.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import contextlib
import datetime
import os # noqa
import pathlib
Expand All @@ -12,6 +13,7 @@
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Set,
Expand All @@ -24,7 +26,7 @@

from .abc import AbstractCookieJar, ClearCookiePredicate
from .helpers import is_ip_address, next_whole_second
from .typedefs import LooseCookies, PathLike
from .typedefs import LooseCookies, PathLike, StrOrURL

__all__ = ("CookieJar", "DummyCookieJar")

Expand Down Expand Up @@ -55,14 +57,32 @@ class CookieJar(AbstractCookieJar):

MAX_32BIT_TIME = datetime.datetime.utcfromtimestamp(2 ** 31 - 1)

def __init__(self, *, unsafe: bool = False, quote_cookie: bool = True) -> None:
def __init__(
self,
*,
unsafe: bool = False,
quote_cookie: bool = True,
treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None
) -> None:
self._loop = asyncio.get_running_loop()
self._cookies = defaultdict(
SimpleCookie
) # type: DefaultDict[str, SimpleCookie[str]]
self._host_only_cookies = set() # type: Set[Tuple[str, str]]
self._unsafe = unsafe
self._quote_cookie = quote_cookie
if treat_as_secure_origin is None:
treat_as_secure_origin = []
elif isinstance(treat_as_secure_origin, URL):
treat_as_secure_origin = [treat_as_secure_origin.origin()]
elif isinstance(treat_as_secure_origin, str):
treat_as_secure_origin = [URL(treat_as_secure_origin).origin()]
else:
treat_as_secure_origin = [
URL(url).origin() if isinstance(url, str) else url.origin()
for url in treat_as_secure_origin
]
self._treat_as_secure_origin = treat_as_secure_origin
self._next_expiration = next_whole_second()
self._expirations = {} # type: Dict[Tuple[str, str], datetime.datetime]
# #4515: datetime.max may not be representable on 32-bit platforms
Expand Down Expand Up @@ -227,7 +247,14 @@ def filter_cookies(
SimpleCookie() if self._quote_cookie else BaseCookie()
)
hostname = request_url.raw_host or ""
is_not_secure = request_url.scheme not in ("https", "wss")
request_origin = URL()
with contextlib.suppress(ValueError):
request_origin = request_url.origin()

is_not_secure = (
request_url.scheme not in ("https", "wss")
and request_origin not in self._treat_as_secure_origin
)

for cookie in self:
name = cookie.key
Expand Down
14 changes: 10 additions & 4 deletions docs/client_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1778,7 +1778,7 @@ BasicAuth
CookieJar
^^^^^^^^^

.. class:: CookieJar(*, unsafe=False, quote_cookie=True, loop=None)
.. class:: CookieJar(*, unsafe=False, quote_cookie=True, treat_as_secure_origin = [])

The cookie jar instance is available as :attr:`ClientSession.cookie_jar`.

Expand Down Expand Up @@ -1810,11 +1810,17 @@ CookieJar

.. versionadded:: 3.7

:param bool loop: an :ref:`event loop<asyncio-event-loop>` instance.
See :class:`aiohttp.abc.AbstractCookieJar`
:param treat_as_secure_origin: (optional) Mark origins as secure
for cookies marked as Secured. Possible types are

.. deprecated:: 2.0
Possible types are:

- :class:`tuple` or :class:`list` of
:class:`str` or :class:`yarl.URL`
- :class:`str`
- :class:`yarl.URL`

.. versionadded:: 3.8

.. method:: update_cookies(cookies, response_url=None)

Expand Down
3 changes: 2 additions & 1 deletion docs/testing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -744,7 +744,8 @@ Test Client
first with ``TestServer(app)``.

:param cookie_jar: an optional :class:`aiohttp.CookieJar` instance,
may be useful with ``CookieJar(unsafe=True)``
may be useful with
``CookieJar(unsafe=True, treat_as_secure_origin="http://127.0.0.1")``
option.

:param str scheme: HTTP scheme, non-protected ``"http"`` by default.
Expand Down
32 changes: 32 additions & 0 deletions tests/test_cookiejar.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,3 +756,35 @@ async def test_cookie_jar_clear_domain() -> None:
assert morsel.value == "bar"
with pytest.raises(StopIteration):
next(iterator)


@pytest.mark.parametrize(
"url",
[
"http://127.0.0.1/index.html",
URL("http://127.0.0.1/index.html"),
["http://127.0.0.1/index.html"],
[URL("http://127.0.0.1/index.html")],
],
)
async def test_treat_as_secure_origin_init(url) -> None:
jar = CookieJar(unsafe=True, treat_as_secure_origin=url)
assert jar._treat_as_secure_origin == [URL("http://127.0.0.1")]


async def test_treat_as_secure_origin() -> None:
endpoint = URL("http://127.0.0.1/")

jar = CookieJar(unsafe=True, treat_as_secure_origin=[endpoint])
secure_cookie = SimpleCookie(
"cookie-key=cookie-value; HttpOnly; Path=/; Secure",
)

jar.update_cookies(
secure_cookie,
endpoint,
)

assert len(jar) == 1
filtered_cookies = jar.filter_cookies(request_url=endpoint)
assert len(filtered_cookies) == 1