Compare commits

..

2 Commits

Author SHA1 Message Date
L. Kärkkäinen
a202435283 Skip empty cookie records. Add tests. 2023-10-14 20:03:43 +01:00
L. Kärkkäinen
6d433af406 Accept bare cookies 2023-10-14 18:27:26 +00:00
3 changed files with 30 additions and 13 deletions

View File

@@ -73,12 +73,16 @@ def parse_cookie(raw: str) -> Dict[str, List[str]]:
cookies: Dict[str, List[str]] = {}
for token in raw.split(";"):
name, __, value = token.partition("=")
name, sep, value = token.partition("=")
name = name.strip()
value = value.strip()
if not name:
continue
# Support cookies =value or plain value with no name
# https://github.com/httpwg/http-extensions/issues/159
if not sep:
if not name:
continue # Empty value like ;; or a cookie header with no value
name, value = "", name
if COOKIE_NAME_RESERVED_CHARS.search(name): # no cov
continue

View File

@@ -3,7 +3,6 @@ from __future__ import annotations
import os
import ssl
from pathlib import Path, PurePath
from typing import Any, Dict, Iterable, Optional, Union
from sanic.log import logger
@@ -40,23 +39,23 @@ def create_context(
def shorthand_to_ctx(
ctxdef: Union[None, ssl.SSLContext, dict, PurePath, str]
ctxdef: Union[None, ssl.SSLContext, dict, str]
) -> Optional[ssl.SSLContext]:
"""Convert an ssl argument shorthand to an SSLContext object."""
if ctxdef is None or isinstance(ctxdef, ssl.SSLContext):
return ctxdef
if isinstance(ctxdef, (PurePath, str)):
return load_cert_dir(Path(ctxdef))
if isinstance(ctxdef, str):
return load_cert_dir(ctxdef)
if isinstance(ctxdef, dict):
return CertSimple(**ctxdef)
raise ValueError(
f"Invalid ssl argument {type(ctxdef)}."
" Expecting one/list of: certdir | dict | SSLContext"
" Expecting a list of certdirs, a dict or an SSLContext."
)
def process_to_context(
ssldef: Union[None, ssl.SSLContext, dict, PurePath, str, list, tuple]
ssldef: Union[None, ssl.SSLContext, dict, str, list, tuple]
) -> Optional[ssl.SSLContext]:
"""Process app.run ssl argument from easy formats to full SSLContext."""
return (
@@ -66,11 +65,11 @@ def process_to_context(
)
def load_cert_dir(p: Path) -> ssl.SSLContext:
if p.is_file():
def load_cert_dir(p: str) -> ssl.SSLContext:
if os.path.isfile(p):
raise ValueError(f"Certificate folder expected but {p} is a file.")
keyfile = p / "privkey.pem"
certfile = p / "fullchain.pem"
keyfile = os.path.join(p, "privkey.pem")
certfile = os.path.join(p, "fullchain.pem")
if not os.access(keyfile, os.R_OK):
raise ValueError(
f"Certificate not found or permission denied {keyfile}"

View File

@@ -11,6 +11,20 @@ from sanic.cookies.request import CookieRequestParameters
from sanic.exceptions import ServerError
from sanic.response import text
from sanic.response.convenience import json
from sanic.cookies.request import parse_cookie
def test_request_cookies():
cdict = parse_cookie("foo=one; foo=two; abc = xyz;;bare;=bare2")
assert cdict == {
"foo": ["one", "two"],
"abc": ["xyz"],
"": ["bare", "bare2"],
}
c = CookieRequestParameters(cdict)
assert c.getlist("foo") == ["one", "two"]
assert c.getlist("abc") == ["xyz"]
assert c.getlist("") == ["bare", "bare2"]
assert c.getlist("bare") == None # [] might be sensible but we got None for now
# ------------------------------------------------------------ #