sessions.py 15 KB

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