|
| 1 | +import json |
| 2 | +import typing |
| 3 | +from base64 import b64decode, b64encode |
| 4 | + |
| 5 | +import itsdangerous |
| 6 | +from itsdangerous.exc import BadSignature |
| 7 | +from starlette.datastructures import MutableHeaders |
| 8 | +from starlette.requests import HTTPConnection |
| 9 | +from starlette.types import ASGIApp, Message, Receive, Scope, Send |
| 10 | + |
| 11 | +import nebula |
| 12 | +from nebula.common import create_hash |
| 13 | + |
| 14 | + |
| 15 | +async def get_session_key() -> str: |
| 16 | + key_candidate = create_hash() |
| 17 | + |
| 18 | + query = """ |
| 19 | + INSERT INTO settings (key, value) |
| 20 | + VALUES ('.session_key', $1) |
| 21 | + ON CONFLICT (key) DO UPDATE |
| 22 | + SET value = settings.value |
| 23 | + RETURNING value |
| 24 | + """ |
| 25 | + |
| 26 | + res = await nebula.db.fetchrow(query, key_candidate) |
| 27 | + assert res, "Failed to retrieve session key. This shouldn't happen" |
| 28 | + |
| 29 | + if res["value"] == key_candidate: |
| 30 | + nebula.log.info("Created new session key") |
| 31 | + |
| 32 | + return res["value"] |
| 33 | + |
| 34 | + |
| 35 | +class SessionMiddleware: |
| 36 | + """Custom session middleware for Nebula. |
| 37 | +
|
| 38 | + The main difference with the default Starlette session middleware is that |
| 39 | + it loads the session key from the database so it can be shared between |
| 40 | + multiple replicas of the application. |
| 41 | + """ |
| 42 | + |
| 43 | + _signer: itsdangerous.Signer | None = None |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + app: ASGIApp, |
| 48 | + session_cookie: str = "session", |
| 49 | + max_age: int | None = 14 * 24 * 60 * 60, # 14 days, in seconds |
| 50 | + path: str = "/", |
| 51 | + same_site: typing.Literal["lax", "strict", "none"] = "lax", |
| 52 | + https_only: bool = False, |
| 53 | + domain: str | None = None, |
| 54 | + ) -> None: |
| 55 | + self.app = app |
| 56 | + self.session_cookie = session_cookie |
| 57 | + self.max_age = max_age |
| 58 | + self.path = path |
| 59 | + self.security_flags = "httponly; samesite=" + same_site |
| 60 | + if https_only: # Secure flag can be used with HTTPS only |
| 61 | + self.security_flags += "; secure" |
| 62 | + if domain is not None: |
| 63 | + self.security_flags += f"; domain={domain}" |
| 64 | + |
| 65 | + async def get_signer(self) -> itsdangerous.Signer: |
| 66 | + if self._signer is None: |
| 67 | + key = await get_session_key() |
| 68 | + self._signer = itsdangerous.TimestampSigner(key) |
| 69 | + return self._signer |
| 70 | + |
| 71 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 72 | + if scope["type"] not in ("http", "websocket"): # pragma: no cover |
| 73 | + await self.app(scope, receive, send) |
| 74 | + return |
| 75 | + |
| 76 | + signer = await self.get_signer() |
| 77 | + |
| 78 | + connection = HTTPConnection(scope) |
| 79 | + initial_session_was_empty = True |
| 80 | + |
| 81 | + if self.session_cookie in connection.cookies: |
| 82 | + data = connection.cookies[self.session_cookie].encode("utf-8") |
| 83 | + try: |
| 84 | + data = signer.unsign(data) |
| 85 | + scope["session"] = json.loads(b64decode(data)) |
| 86 | + initial_session_was_empty = False |
| 87 | + except BadSignature: |
| 88 | + scope["session"] = {} |
| 89 | + else: |
| 90 | + scope["session"] = {} |
| 91 | + |
| 92 | + async def send_wrapper(message: Message) -> None: |
| 93 | + if message["type"] == "http.response.start": |
| 94 | + if scope["session"]: |
| 95 | + # We have session data to persist. |
| 96 | + data = b64encode(json.dumps(scope["session"]).encode("utf-8")) |
| 97 | + data = signer.sign(data) |
| 98 | + headers = MutableHeaders(scope=message) |
| 99 | + header_value = "{session_cookie}={data}; path={path}; {max_age}{security_flags}".format( # noqa: E501 |
| 100 | + session_cookie=self.session_cookie, |
| 101 | + data=data.decode("utf-8"), |
| 102 | + path=self.path, |
| 103 | + max_age=f"Max-Age={self.max_age}; " if self.max_age else "", |
| 104 | + security_flags=self.security_flags, |
| 105 | + ) |
| 106 | + headers.append("Set-Cookie", header_value) |
| 107 | + elif not initial_session_was_empty: |
| 108 | + # The session has been cleared. |
| 109 | + headers = MutableHeaders(scope=message) |
| 110 | + header_value = "{session_cookie}={data}; path={path}; {expires}{security_flags}".format( # noqa: E501 |
| 111 | + session_cookie=self.session_cookie, |
| 112 | + data="null", |
| 113 | + path=self.path, |
| 114 | + expires="expires=Thu, 01 Jan 1970 00:00:00 GMT; ", |
| 115 | + security_flags=self.security_flags, |
| 116 | + ) |
| 117 | + headers.append("Set-Cookie", header_value) |
| 118 | + await send(message) |
| 119 | + |
| 120 | + await self.app(scope, receive, send_wrapper) |
0 commit comments