sessions.py 14 KB

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