sessions.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import hashlib
  2. import typing as t
  3. import warnings
  4. from collections.abc import MutableMapping
  5. from datetime import datetime
  6. from datetime import timezone
  7. from itsdangerous import BadSignature
  8. from itsdangerous import URLSafeTimedSerializer
  9. from werkzeug.datastructures import CallbackDict
  10. from .helpers import is_ip
  11. from .json.tag import TaggedJSONSerializer
  12. if t.TYPE_CHECKING: # pragma: no cover
  13. import typing_extensions as te
  14. from .app import Flask
  15. from .wrappers import Request, Response
  16. class SessionMixin(MutableMapping):
  17. """Expands a basic dictionary with session attributes."""
  18. @property
  19. def permanent(self) -> bool:
  20. """This reflects the ``'_permanent'`` key in the dict."""
  21. return self.get("_permanent", False)
  22. @permanent.setter
  23. def permanent(self, value: bool) -> None:
  24. self["_permanent"] = bool(value)
  25. #: Some implementations can detect whether a session is newly
  26. #: created, but that is not guaranteed. Use with caution. The mixin
  27. # default is hard-coded ``False``.
  28. new = False
  29. #: Some implementations can detect changes to the session and set
  30. #: this when that happens. The mixin default is hard coded to
  31. #: ``True``.
  32. modified = True
  33. #: Some implementations can detect when session data is read or
  34. #: written and set this when that happens. The mixin default is hard
  35. #: coded to ``True``.
  36. accessed = True
  37. class SecureCookieSession(CallbackDict, SessionMixin):
  38. """Base class for sessions based on signed cookies.
  39. This session backend will set the :attr:`modified` and
  40. :attr:`accessed` attributes. It cannot reliably track whether a
  41. session is new (vs. empty), so :attr:`new` remains hard coded to
  42. ``False``.
  43. """
  44. #: When data is changed, this is set to ``True``. Only the session
  45. #: dictionary itself is tracked; if the session contains mutable
  46. #: data (for example a nested dict) then this must be set to
  47. #: ``True`` manually when modifying that data. The session cookie
  48. #: will only be written to the response if this is ``True``.
  49. modified = False
  50. #: When data is read or written, this is set to ``True``. Used by
  51. # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``
  52. #: header, which allows caching proxies to cache different pages for
  53. #: different users.
  54. accessed = False
  55. def __init__(self, initial: t.Any = None) -> None:
  56. def on_update(self) -> None:
  57. self.modified = True
  58. self.accessed = True
  59. super().__init__(initial, on_update)
  60. def __getitem__(self, key: str) -> t.Any:
  61. self.accessed = True
  62. return super().__getitem__(key)
  63. def get(self, key: str, default: t.Any = None) -> t.Any:
  64. self.accessed = True
  65. return super().get(key, default)
  66. def setdefault(self, key: str, default: t.Any = None) -> t.Any:
  67. self.accessed = True
  68. return super().setdefault(key, default)
  69. class NullSession(SecureCookieSession):
  70. """Class used to generate nicer error messages if sessions are not
  71. available. Will still allow read-only access to the empty session
  72. but fail on setting.
  73. """
  74. def _fail(self, *args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
  75. raise RuntimeError(
  76. "The session is unavailable because no secret "
  77. "key was set. Set the secret_key on the "
  78. "application to something unique and secret."
  79. )
  80. __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail # type: ignore # noqa: B950
  81. del _fail
  82. class SessionInterface:
  83. """The basic interface you have to implement in order to replace the
  84. default session interface which uses werkzeug's securecookie
  85. implementation. The only methods you have to implement are
  86. :meth:`open_session` and :meth:`save_session`, the others have
  87. useful defaults which you don't need to change.
  88. The session object returned by the :meth:`open_session` method has to
  89. provide a dictionary like interface plus the properties and methods
  90. from the :class:`SessionMixin`. We recommend just subclassing a dict
  91. and adding that mixin::
  92. class Session(dict, SessionMixin):
  93. pass
  94. If :meth:`open_session` returns ``None`` Flask will call into
  95. :meth:`make_null_session` to create a session that acts as replacement
  96. if the session support cannot work because some requirement is not
  97. fulfilled. The default :class:`NullSession` class that is created
  98. will complain that the secret key was not set.
  99. To replace the session interface on an application all you have to do
  100. is to assign :attr:`flask.Flask.session_interface`::
  101. app = Flask(__name__)
  102. app.session_interface = MySessionInterface()
  103. Multiple requests with the same session may be sent and handled
  104. concurrently. When implementing a new session interface, consider
  105. whether reads or writes to the backing store must be synchronized.
  106. There is no guarantee on the order in which the session for each
  107. request is opened or saved, it will occur in the order that requests
  108. begin and end processing.
  109. .. versionadded:: 0.8
  110. """
  111. #: :meth:`make_null_session` will look here for the class that should
  112. #: be created when a null session is requested. Likewise the
  113. #: :meth:`is_null_session` method will perform a typecheck against
  114. #: this type.
  115. null_session_class = NullSession
  116. #: A flag that indicates if the session interface is pickle based.
  117. #: This can be used by Flask extensions to make a decision in regards
  118. #: to how to deal with the session object.
  119. #:
  120. #: .. versionadded:: 0.10
  121. pickle_based = False
  122. def make_null_session(self, app: "Flask") -> NullSession:
  123. """Creates a null session which acts as a replacement object if the
  124. real session support could not be loaded due to a configuration
  125. error. This mainly aids the user experience because the job of the
  126. null session is to still support lookup without complaining but
  127. modifications are answered with a helpful error message of what
  128. failed.
  129. This creates an instance of :attr:`null_session_class` by default.
  130. """
  131. return self.null_session_class()
  132. def is_null_session(self, obj: object) -> bool:
  133. """Checks if a given object is a null session. Null sessions are
  134. not asked to be saved.
  135. This checks if the object is an instance of :attr:`null_session_class`
  136. by default.
  137. """
  138. return isinstance(obj, self.null_session_class)
  139. def get_cookie_name(self, app: "Flask") -> str:
  140. """The name of the session cookie. Uses``app.config["SESSION_COOKIE_NAME"]``."""
  141. return app.config["SESSION_COOKIE_NAME"]
  142. def get_cookie_domain(self, app: "Flask") -> t.Optional[str]:
  143. """Returns the domain that should be set for the session cookie.
  144. Uses ``SESSION_COOKIE_DOMAIN`` if it is configured, otherwise
  145. falls back to detecting the domain based on ``SERVER_NAME``.
  146. Once detected (or if not set at all), ``SESSION_COOKIE_DOMAIN`` is
  147. updated to avoid re-running the logic.
  148. """
  149. rv = app.config["SESSION_COOKIE_DOMAIN"]
  150. # set explicitly, or cached from SERVER_NAME detection
  151. # if False, return None
  152. if rv is not None:
  153. return rv if rv else None
  154. rv = app.config["SERVER_NAME"]
  155. # server name not set, cache False to return none next time
  156. if not rv:
  157. app.config["SESSION_COOKIE_DOMAIN"] = False
  158. return None
  159. # chop off the port which is usually not supported by browsers
  160. # remove any leading '.' since we'll add that later
  161. rv = rv.rsplit(":", 1)[0].lstrip(".")
  162. if "." not in rv:
  163. # Chrome doesn't allow names without a '.'. This should only
  164. # come up with localhost. Hack around this by not setting
  165. # the name, and show a warning.
  166. warnings.warn(
  167. f"{rv!r} is not a valid cookie domain, it must contain"
  168. " a '.'. Add an entry to your hosts file, for example"
  169. f" '{rv}.localdomain', and use that instead."
  170. )
  171. app.config["SESSION_COOKIE_DOMAIN"] = False
  172. return None
  173. ip = is_ip(rv)
  174. if ip:
  175. warnings.warn(
  176. "The session cookie domain is an IP address. This may not work"
  177. " as intended in some browsers. Add an entry to your hosts"
  178. ' file, for example "localhost.localdomain", and use that'
  179. " instead."
  180. )
  181. # if this is not an ip and app is mounted at the root, allow subdomain
  182. # matching by adding a '.' prefix
  183. if self.get_cookie_path(app) == "/" and not ip:
  184. rv = f".{rv}"
  185. app.config["SESSION_COOKIE_DOMAIN"] = rv
  186. return rv
  187. def get_cookie_path(self, app: "Flask") -> str:
  188. """Returns the path for which the cookie should be valid. The
  189. default implementation uses the value from the ``SESSION_COOKIE_PATH``
  190. config var if it's set, and falls back to ``APPLICATION_ROOT`` or
  191. uses ``/`` if it's ``None``.
  192. """
  193. return app.config["SESSION_COOKIE_PATH"] or app.config["APPLICATION_ROOT"]
  194. def get_cookie_httponly(self, app: "Flask") -> bool:
  195. """Returns True if the session cookie should be httponly. This
  196. currently just returns the value of the ``SESSION_COOKIE_HTTPONLY``
  197. config var.
  198. """
  199. return app.config["SESSION_COOKIE_HTTPONLY"]
  200. def get_cookie_secure(self, app: "Flask") -> bool:
  201. """Returns True if the cookie should be secure. This currently
  202. just returns the value of the ``SESSION_COOKIE_SECURE`` setting.
  203. """
  204. return app.config["SESSION_COOKIE_SECURE"]
  205. def get_cookie_samesite(self, app: "Flask") -> str:
  206. """Return ``'Strict'`` or ``'Lax'`` if the cookie should use the
  207. ``SameSite`` attribute. This currently just returns the value of
  208. the :data:`SESSION_COOKIE_SAMESITE` setting.
  209. """
  210. return app.config["SESSION_COOKIE_SAMESITE"]
  211. def get_expiration_time(
  212. self, app: "Flask", session: SessionMixin
  213. ) -> t.Optional[datetime]:
  214. """A helper method that returns an expiration date for the session
  215. or ``None`` if the session is linked to the browser session. The
  216. default implementation returns now + the permanent session
  217. lifetime configured on the application.
  218. """
  219. if session.permanent:
  220. return datetime.now(timezone.utc) + app.permanent_session_lifetime
  221. return None
  222. def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:
  223. """Used by session backends to determine if a ``Set-Cookie`` header
  224. should be set for this session cookie for this response. If the session
  225. has been modified, the cookie is set. If the session is permanent and
  226. the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is
  227. always set.
  228. This check is usually skipped if the session was deleted.
  229. .. versionadded:: 0.11
  230. """
  231. return session.modified or (
  232. session.permanent and app.config["SESSION_REFRESH_EACH_REQUEST"]
  233. )
  234. def open_session(
  235. self, app: "Flask", request: "Request"
  236. ) -> t.Optional[SessionMixin]:
  237. """This is called at the beginning of each request, after
  238. pushing the request context, before matching the URL.
  239. This must return an object which implements a dictionary-like
  240. interface as well as the :class:`SessionMixin` interface.
  241. This will return ``None`` to indicate that loading failed in
  242. some way that is not immediately an error. The request
  243. context will fall back to using :meth:`make_null_session`
  244. in this case.
  245. """
  246. raise NotImplementedError()
  247. def save_session(
  248. self, app: "Flask", session: SessionMixin, response: "Response"
  249. ) -> None:
  250. """This is called at the end of each request, after generating
  251. a response, before removing the request context. It is skipped
  252. if :meth:`is_null_session` returns ``True``.
  253. """
  254. raise NotImplementedError()
  255. session_json_serializer = TaggedJSONSerializer()
  256. class SecureCookieSessionInterface(SessionInterface):
  257. """The default session interface that stores sessions in signed cookies
  258. through the :mod:`itsdangerous` module.
  259. """
  260. #: the salt that should be applied on top of the secret key for the
  261. #: signing of cookie based sessions.
  262. salt = "cookie-session"
  263. #: the hash function to use for the signature. The default is sha1
  264. digest_method = staticmethod(hashlib.sha1)
  265. #: the name of the itsdangerous supported key derivation. The default
  266. #: is hmac.
  267. key_derivation = "hmac"
  268. #: A python serializer for the payload. The default is a compact
  269. #: JSON derived serializer with support for some extra Python types
  270. #: such as datetime objects or tuples.
  271. serializer = session_json_serializer
  272. session_class = SecureCookieSession
  273. def get_signing_serializer(
  274. self, app: "Flask"
  275. ) -> t.Optional[URLSafeTimedSerializer]:
  276. if not app.secret_key:
  277. return None
  278. signer_kwargs = dict(
  279. key_derivation=self.key_derivation, digest_method=self.digest_method
  280. )
  281. return URLSafeTimedSerializer(
  282. app.secret_key,
  283. salt=self.salt,
  284. serializer=self.serializer,
  285. signer_kwargs=signer_kwargs,
  286. )
  287. def open_session(
  288. self, app: "Flask", request: "Request"
  289. ) -> t.Optional[SecureCookieSession]:
  290. s = self.get_signing_serializer(app)
  291. if s is None:
  292. return None
  293. val = request.cookies.get(self.get_cookie_name(app))
  294. if not val:
  295. return self.session_class()
  296. max_age = int(app.permanent_session_lifetime.total_seconds())
  297. try:
  298. data = s.loads(val, max_age=max_age)
  299. return self.session_class(data)
  300. except BadSignature:
  301. return self.session_class()
  302. def save_session(
  303. self, app: "Flask", session: SessionMixin, response: "Response"
  304. ) -> None:
  305. name = self.get_cookie_name(app)
  306. domain = self.get_cookie_domain(app)
  307. path = self.get_cookie_path(app)
  308. secure = self.get_cookie_secure(app)
  309. samesite = self.get_cookie_samesite(app)
  310. httponly = self.get_cookie_httponly(app)
  311. # If the session is modified to be empty, remove the cookie.
  312. # If the session is empty, return without setting the cookie.
  313. if not session:
  314. if session.modified:
  315. response.delete_cookie(
  316. name,
  317. domain=domain,
  318. path=path,
  319. secure=secure,
  320. samesite=samesite,
  321. httponly=httponly,
  322. )
  323. return
  324. # Add a "Vary: Cookie" header if the session was accessed at all.
  325. if session.accessed:
  326. response.vary.add("Cookie")
  327. if not self.should_set_cookie(app, session):
  328. return
  329. expires = self.get_expiration_time(app, session)
  330. val = self.get_signing_serializer(app).dumps(dict(session)) # type: ignore
  331. response.set_cookie(
  332. name,
  333. val, # type: ignore
  334. expires=expires,
  335. httponly=httponly,
  336. domain=domain,
  337. path=path,
  338. secure=secure,
  339. samesite=samesite,
  340. )