Debian Codegraph @

src/flask_session/base.py

raw
1 import secrets
2 import warnings
3 from abc import ABC, abstractmethod
4 from contextlib import suppress
5
6 try:
7 import cPickle as pickle
8 except ImportError:
9 import pickle
10
11 import random
12 from datetime import timedelta as TimeDelta
13 from typing import Any, Dict, Optional
14
15 import msgspec
16 from flask import Flask, Request, Response
17 from flask.sessions import SessionInterface as FlaskSessionInterface
18 from flask.sessions import SessionMixin
19 from itsdangerous import BadSignature, Signer, want_bytes
20 from werkzeug.datastructures import CallbackDict
21
22 from ._utils import retry_query
23 from .defaults import Defaults
24
25
26 class ServerSideSession(CallbackDict, SessionMixin):
27 """Baseclass for server-side based sessions. This can be accessed through ``flask.session``.
28
29 .. attribute:: sid
30
31 Session id, internally we use :func:`secrets.token_urlsafe` to generate one
32 session id.
33
34 .. attribute:: modified
35
36 When data is changed, this is set to ``True``. Only the session dictionary
37 itself is tracked; if the session contains mutable data (for example a nested
38 dict) then this must be set to ``True`` manually when modifying that data. The
39 session cookie will only be written to the response if this is ``True``.
40
41 .. attribute:: accessed
42
43 When data is read (or attempted read) or written, this is set to ``True``. Used by
44 :class:`.ServerSideSessionInterface` to add a ``Vary: Cookie``
45 header, which allows caching proxies to cache different pages for
46 different users.
47
48 Default is ``False``.
49
50 .. attribute:: permanent
51
52 This sets and reflects the ``'_permanent'`` key in the dict.
53
54 Default is ``False``.
55
56 """
57
58 def __bool__(self) -> bool:
59 return bool(dict(self)) and self.keys() != {"_permanent"}
60
61 def __init__(
62 self,
63 initial: Optional[Dict[str, Any]] = None,
64 sid: Optional[str] = None,
65 permanent: Optional[bool] = None,
66 ):
67 def on_update(self) -> None:
68 self.modified = True
69 self.accessed = True
70
71 CallbackDict.__init__(self, initial, on_update)
72 self.sid = sid
73 if permanent:
74 self.permanent = permanent
75 self.modified = False
76 self.accessed = False
77
78 def __getitem__(self, key: str) -> Any:
79 self.accessed = True
80 return super().__getitem__(key)
81
82 def get(self, key: str, default: Any = None) -> Any:
83 self.accessed = True
84 return super().get(key, default)
85
86 def setdefault(self, key: str, default: Any = None) -> Any:
87 self.accessed = True
88 return super().setdefault(key, default)
89
90 def clear(self) -> None:
91 """Clear the session except for the '_permanent' key."""
92 permanent = self.get("_permanent", False)
93 super().clear()
94 self["_permanent"] = permanent
95
96
97 class Serializer(ABC):
98 """Baseclass for session serialization."""
99
100 @abstractmethod
101 def decode(self, serialized_data: bytes) -> dict:
102 """Deserialize the session data."""
103 raise NotImplementedError()
104
105 @abstractmethod
106 def encode(self, session: ServerSideSession) -> bytes:
107 """Serialize the session data."""
108 raise NotImplementedError()
109
110
111 class MsgSpecSerializer(Serializer):
112 def __init__(self, app: Flask, format: str):
113 self.app: Flask = app
114 self.encoder: msgspec.msgpack.Encoder or msgspec.json.Encoder
115 self.decoder: msgspec.msgpack.Decoder or msgspec.json.Decoder
116 self.alternate_decoder: msgspec.msgpack.Decoder or msgspec.json.Decoder
117
118 if format == "msgpack":
119 self.encoder = msgspec.msgpack.Encoder()
120 self.decoder = msgspec.msgpack.Decoder()
121 self.alternate_decoder = msgspec.json.Decoder()
122 elif format == "json":
123 self.encoder = msgspec.json.Encoder()
124 self.decoder = msgspec.json.Decoder()
125 self.alternate_decoder = msgspec.msgpack.Decoder()
126 else:
127 raise ValueError(f"Unsupported serialization format: {format}")
128
129 def encode(self, session: ServerSideSession) -> bytes:
130 """Serialize the session data."""
131 try:
132 return self.encoder.encode(dict(session))
133 except Exception as e:
134 self.app.logger.error(f"Failed to serialize session data: {e}")
135 raise
136
137 def decode(self, serialized_data: bytes) -> dict:
138 """Deserialize the session data."""
139 # TODO: Remove the pickle fallback in 1.0.0
140 with suppress(msgspec.DecodeError):
141 return self.decoder.decode(serialized_data)
142 with suppress(msgspec.DecodeError):
143 return self.alternate_decoder.decode(serialized_data)
144 with suppress(pickle.UnpicklingError):
145 return pickle.loads(serialized_data)
146 # If all decoders fail, raise the final exception
147 self.app.logger.error("Failed to deserialize session data", exc_info=True)
148 raise pickle.UnpicklingError("Failed to deserialize session data")
149
150
151 class ServerSideSessionInterface(FlaskSessionInterface, ABC):
152 """Used to open a :class:`flask.sessions.ServerSideSessionInterface` instance."""
153
154 session_class = ServerSideSession
155 serializer = None
156 ttl = True
157
158 def __init__(
159 self,
160 app: Flask,
161 key_prefix: str = Defaults.SESSION_KEY_PREFIX,
162 use_signer: bool = Defaults.SESSION_USE_SIGNER,
163 permanent: bool = Defaults.SESSION_PERMANENT,
164 sid_length: int = Defaults.SESSION_ID_LENGTH,
165 serialization_format: str = Defaults.SESSION_SERIALIZATION_FORMAT,
166 cleanup_n_requests: Optional[int] = Defaults.SESSION_CLEANUP_N_REQUESTS,
167 ):
168 self.app = app
169 self.key_prefix = key_prefix
170 self.use_signer = use_signer
171 if use_signer:
172 warnings.warn(
173 "The 'use_signer' option is deprecated and will be removed in the next minor release. "
174 "Please update your configuration accordingly or open an issue.",
175 DeprecationWarning,
176 stacklevel=1,
177 )
178 self.permanent = permanent
179 self.sid_length = sid_length
180 self.has_same_site_capability = hasattr(self, "get_cookie_samesite")
181 self.cleanup_n_requests = cleanup_n_requests
182
183 # Cleanup settings for non-TTL databases only
184 if getattr(self, "ttl", None) is False:
185 if self.cleanup_n_requests:
186 self.app.before_request(self._cleanup_n_requests)
187 else:
188 self._register_cleanup_app_command()
189
190 # Set the serialization format
191 self.serializer = MsgSpecSerializer(format=serialization_format, app=app)
192
193 # INTERNAL METHODS
194
195 def _generate_sid(self, session_id_length: int) -> str:
196 """Generate a random session id."""
197 return secrets.token_urlsafe(session_id_length)
198
199 # TODO: Remove in 1.0.0
200 def _get_signer(self, app: Flask) -> Signer:
201 if not hasattr(app, "secret_key") or not app.secret_key:
202 raise KeyError("SECRET_KEY must be set when SESSION_USE_SIGNER=True")
203 return Signer(app.secret_key, salt="flask-session", key_derivation="hmac")
204
205 # TODO: Remove in 1.0.0
206 def _unsign(self, app, sid: str) -> str:
207 signer = self._get_signer(app)
208 sid_as_bytes = signer.unsign(sid)
209 sid = sid_as_bytes.decode()
210 return sid
211
212 # TODO: Remove in 1.0.0
213 def _sign(self, app, sid: str) -> str:
214 signer = self._get_signer(app)
215 sid_as_bytes = want_bytes(sid)
216 return signer.sign(sid_as_bytes).decode("utf-8")
217
218 def _get_store_id(self, sid: str) -> str:
219 return self.key_prefix + sid
220
221 def should_set_storage(self, app: Flask, session: ServerSideSession) -> bool:
222 """Used by session backends to determine if session in storage
223 should be set for this session cookie for this response. If the session
224 has been modified, the session is set to storage. If
225 the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the session is
226 always set to storage. In the second case, this means refreshing the
227 storage expiry even if the session has not been modified.
228
229 .. versionadded:: 0.7.0
230 """
231
232 return session.modified or app.config["SESSION_REFRESH_EACH_REQUEST"]
233
234 # CLEANUP METHODS FOR NON TTL DATABASES
235
236 def _register_cleanup_app_command(self):
237 """
238 Register a custom Flask CLI command for cleaning up expired sessions.
239
240 Run the command with `flask session_cleanup`. Run with a cron job
241 or scheduler such as Heroku Scheduler to automatically clean up expired sessions.
242 """
243
244 @self.app.cli.command("session_cleanup")
245 def session_cleanup():
246 with self.app.app_context():
247 self._delete_expired_sessions()
248
249 def _cleanup_n_requests(self) -> None:
250 """
251 Delete expired sessions on average every N requests.
252
253 This is less desirable than using the scheduled app command cleanup as it may
254 slow down some requests but may be useful for rapid development.
255 """
256 if self.cleanup_n_requests and random.randint(0, self.cleanup_n_requests) == 0:
257 self._delete_expired_sessions()
258
259 # SECURITY API METHODS
260
261 def regenerate(self, session: ServerSideSession) -> None:
262 """Regenerate the session id for the given session. Can be used by calling ``flask.session_interface.regenerate()``."""
263 if session:
264 # Remove the old session from storage
265 self._delete_session(self._get_store_id(session.sid))
266 # Generate a new session ID
267 new_sid = self._generate_sid(self.sid_length)
268 session.sid = new_sid
269 # Mark the session as modified to ensure it gets saved
270 session.modified = True
271
272 # METHODS OVERRIDE FLASK SESSION INTERFACE
273
274 def save_session(
275 self, app: Flask, session: ServerSideSession, response: Response
276 ) -> None:
277
278 # Get the domain and path for the cookie from the app
279 domain = self.get_cookie_domain(app)
280 path = self.get_cookie_path(app)
281 name = self.get_cookie_name(app)
282
283 # Generate a prefixed session id
284 store_id = self._get_store_id(session.sid)
285
286 # Add a "Vary: Cookie" header if the session was accessed at all.
287 # This assumes the app is checking the session values in a request that
288 # behaves differently based on those values. ie. session.get("is_authenticated")
289 if session.accessed:
290 response.vary.add("Cookie")
291
292 # If the session is empty, do not save it to the database or set a cookie
293 if not session:
294 # If the session was deleted (empty and modified), delete the saved session from the database and tell the client to delete the cookie
295 if session.modified:
296 self._delete_session(store_id)
297 response.delete_cookie(key=name, domain=domain, path=path)
298 response.vary.add("Cookie")
299 return
300
301 if not self.should_set_storage(app, session):
302 return
303
304 # Update existing or create new session in the database
305 self._upsert_session(app.permanent_session_lifetime, session, store_id)
306
307 if not self.should_set_cookie(app, session):
308 return
309
310 # Get the additional required cookie settings
311 value = self._sign(app, session.sid) if self.use_signer else session.sid
312 expires = self.get_expiration_time(app, session)
313 httponly = self.get_cookie_httponly(app)
314 secure = self.get_cookie_secure(app)
315 samesite = (
316 self.get_cookie_samesite(app) if self.has_same_site_capability else None
317 )
318
319 # Set the browser cookie
320 response.set_cookie(
321 key=name,
322 value=value,
323 expires=expires,
324 httponly=httponly,
325 domain=domain,
326 path=path,
327 secure=secure,
328 samesite=samesite,
329 )
330 response.vary.add("Cookie")
331
332 def open_session(self, app: Flask, request: Request) -> ServerSideSession:
333 # Get the session ID from the cookie
334 sid = request.cookies.get(app.config["SESSION_COOKIE_NAME"])
335
336 # If there's no session ID, generate a new one
337 if not sid:
338 sid = self._generate_sid(self.sid_length)
339 return self.session_class(sid=sid, permanent=self.permanent)
340 # If the session ID is signed, unsign it
341 if self.use_signer:
342 try:
343 sid = self._unsign(app, sid)
344 except BadSignature:
345 sid = self._generate_sid(self.sid_length)
346 return self.session_class(sid=sid, permanent=self.permanent)
347
348 # Retrieve the session data from the database
349 store_id = self._get_store_id(sid)
350 saved_session_data = self._retrieve_session_data(store_id)
351
352 # If the saved session exists, load the session data from the document
353 if saved_session_data is not None:
354 return self.session_class(saved_session_data, sid=sid)
355
356 # If the saved session does not exist, create a new session
357 sid = self._generate_sid(self.sid_length)
358 return self.session_class(sid=sid, permanent=self.permanent)
359
360 # METHODS TO BE IMPLEMENTED BY SUBCLASSES
361
362 @abstractmethod
363 @retry_query() # use only when retry not supported directly by the client
364 def _retrieve_session_data(self, store_id: str) -> Optional[dict]:
365 """Get the saved session from the session storage."""
366 raise NotImplementedError()
367
368 @abstractmethod
369 @retry_query() # use only when retry not supported directly by the client
370 def _delete_session(self, store_id: str) -> None:
371 """Delete session from the session storage."""
372 raise NotImplementedError()
373
374 @abstractmethod
375 @retry_query() # use only when retry not supported directly by the client
376 def _upsert_session(
377 self, session_lifetime: TimeDelta, session: ServerSideSession, store_id: str
378 ) -> None:
379 """Update existing or create new session in the session storage."""
380 raise NotImplementedError()
381
382 @retry_query() # use only when retry not supported directly by the client
383 def _delete_expired_sessions(self) -> None:
384 """Delete expired sessions from the session storage. Only required for non-TTL databases."""
385 pass