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

Added allow_path_regex to the SessionMiddleware #2316

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ The following arguments are supported:
* `max_age` - Session expiry time in seconds. Defaults to 2 weeks. If set to `None` then the cookie will last as long as the browser session.
* `same_site` - SameSite flag prevents the browser from sending session cookie along with cross-site requests. Defaults to `'lax'`.
* `https_only` - Indicate that Secure flag should be set (can be used with HTTPS only). Defaults to `False`.
* `domain` - Domain of the cookie used to share cookie between subdomains or cross-domains. The browser defaults the domain to the same host that set the cookie, excluding subdomains [refrence](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#domain_attribute).

* `domain` - Domain of the cookie used to share cookie between subdomains or cross-domains. The browser defaults the domain to the same host that set the cookie, excluding subdomains [refrence](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#domain_attribute).
* `allow_path_regex`: A regex string to match against paths that should be permitted to use sessions. eg. `'/api/.*'`. Defaults to `None` (all routes).

## HTTPSRedirectMiddleware

Expand Down
11 changes: 11 additions & 0 deletions starlette/middleware/sessions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import re
import typing
from base64 import b64decode, b64encode

Expand All @@ -21,6 +22,7 @@ def __init__(
same_site: typing.Literal["lax", "strict", "none"] = "lax",
https_only: bool = False,
domain: typing.Optional[str] = None,
allow_path_regex: typing.Optional[str] = None,
) -> None:
self.app = app
self.signer = itsdangerous.TimestampSigner(str(secret_key))
Expand All @@ -32,11 +34,20 @@ def __init__(
self.security_flags += "; secure"
if domain is not None:
self.security_flags += f"; domain={domain}"
compiled_allow_path_regex = None
if allow_path_regex is not None:
compiled_allow_path_regex = re.compile(allow_path_regex)
self.allow_path_regex = compiled_allow_path_regex

async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket"): # pragma: no cover
await self.app(scope, receive, send)
return
if self.allow_path_regex is not None and self.allow_path_regex.match(
scope["path"]
): # pragma: no cover
await self.app(scope, receive, send)
return

connection = HTTPConnection(scope)
initial_session_was_empty = True
Expand Down
19 changes: 18 additions & 1 deletion tests/middleware/test_session.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import re

import pytest

from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.sessions import SessionMiddleware
Expand Down Expand Up @@ -28,9 +30,16 @@ def test_session(test_client_factory):
routes=[
Route("/view_session", endpoint=view_session),
Route("/update_session", endpoint=update_session, methods=["POST"]),
Route("/skipped_path", endpoint=update_session, methods=["POST"]),
Route("/clear_session", endpoint=clear_session, methods=["POST"]),
],
middleware=[Middleware(SessionMiddleware, secret_key="example")],
middleware=[
Middleware(
SessionMiddleware,
secret_key="example",
allow_path_regex=r"^/skipped_path$",
)
],
)
client = test_client_factory(app)

Expand All @@ -55,6 +64,14 @@ def test_session(test_client_factory):
response = client.get("/view_session")
assert response.json() == {"session": {}}

# check allow_path_regex
with pytest.raises(AssertionError):
response = client.post("/skipped_path", json={"some": "skipped-data"})
pass # pragma: nocover

response = client.get("/view_session")
assert response.json() == {"session": {}}


def test_session_expires(test_client_factory):
app = Starlette(
Expand Down