Skip to content

Commit

Permalink
Fix BadSignature exception handling in SessionMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
hanneskuettner committed Aug 12, 2021
1 parent e45c579 commit 024c811
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions starlette/middleware/sessions.py
Expand Up @@ -3,7 +3,7 @@
from base64 import b64decode, b64encode

import itsdangerous
from itsdangerous.exc import BadTimeSignature, SignatureExpired
from itsdangerous.exc import BadSignature

from starlette.datastructures import MutableHeaders, Secret
from starlette.requests import HTTPConnection
Expand Down Expand Up @@ -42,7 +42,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
data = self.signer.unsign(data, max_age=self.max_age)
scope["session"] = json.loads(b64decode(data))
initial_session_was_empty = False
except (BadTimeSignature, SignatureExpired):
except BadSignature:
scope["session"] = {}
else:
scope["session"] = {}
Expand Down
13 changes: 13 additions & 0 deletions tests/middleware/test_session.py
Expand Up @@ -112,3 +112,16 @@ def test_session_cookie_subpath(test_client_factory):
cookie = response.headers["set-cookie"]
cookie_path = re.search(r"; path=(\S+);", cookie).groups()[0]
assert cookie_path == "/second_app"


def test_invalid_session_cookie():
app = create_app()
app.add_middleware(SessionMiddleware, secret_key="example")
client = TestClient(app)

response = client.post("/update_session", json={"some": "data"})
assert response.json() == {"session": {"some": "data"}}

# we expect it to not raise an exception if we provide a bogus session cookie
response = client.get("/view_session", cookies={"session": "invalid"})
assert response.json() == {"session": {}}

0 comments on commit 024c811

Please sign in to comment.