Merge pull request #2288 from davidism/vary-cookies
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Set "Vary: Cookie" header when session is accessed
authored by David Lord · committed by GitHub · parents a558d47, 5d9dd0b · Browse files · 2 files·+97 added−29 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+97 added−29 removed
- tests:+42 added−0 removed
- other:+55 added−29 removed
Provenance
- Commit
b11f735- Tree
c84aa92- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a558d47- Parent 2
5d9dd0b
2 files changed+97 added−29 removed
modified:flask/sessions.py+55 added-29 removed
47 unmodified lines48 #: long as changes do not happen on mutable structures in the session.49 #: The default mixin implementation just hardcodes ``True`` in.50 modified = True51 52+ #: the accessed variable indicates whether or not the session object has53+ #: been accessed in that request. This allows flask to append a `Vary:54+ #: Cookie` header to the response if the session is being accessed. This55+ #: allows caching proxy servers, like Varnish, to use both the URL and the56+ #: session cookie as keys when caching pages, preventing multiple users57+ #: from being served the same cache.58+ accessed = True59 60 def _tag(value):61 if isinstance(value, tuple):62 return {' t': [_tag(x) for x in value]}60 unmodified lines123 124 def __init__(self, initial=None):125 def on_update(self):126 self.modified = True120- CallbackDict.__init__(self, initial, on_update)127+ self.accessed = True128+129+ super(SecureCookieSession, self).__init__(initial, on_update)130 self.modified = False131+ self.accessed = False132 133+ def __getitem__(self, key):134+ self.accessed = True135+ return super(SecureCookieSession, self).__getitem__(key)136 137+ def get(self, key, default=None):138+ self.accessed = True139+ return super(SecureCookieSession, self).get(key, default)140+141+ def setdefault(self, key, default=None):142+ self.accessed = True143+ return super(SecureCookieSession, self).setdefault(key, default)144+145+146 class NullSession(SecureCookieSession):147 """Class used to generate nicer error messages if sessions are not148 available. Will still allow read-only access to the empty session149 but fail on setting.161 unmodified lines311 if session.permanent:312 return datetime.utcnow() + app.permanent_session_lifetime313 314 def should_set_cookie(self, app, session):293- """Indicates whether a cookie should be set now or not. This is294- used by session backends to figure out if they should emit a295- set-cookie header or not. The default behavior is controlled by296- the ``SESSION_REFRESH_EACH_REQUEST`` config variable. If297- it's set to ``False`` then a cookie is only set if the session is298- modified, if set to ``True`` it's always set if the session is299- permanent.315+ """Used by session backends to determine if a ``Set-Cookie`` header316+ should be set for this session cookie for this response. If the session317+ has been modified, the cookie is set. If the session is permanent and318+ the ``SESSION_REFRESH_EACH_REQUEST`` config is true, the cookie is319+ always set.320+ 321+ This check is usually skipped if the session was deleted.322 301- This check is usually skipped if sessions get deleted.302-323 .. versionadded:: 0.11324 """305- if session.modified:306- return True307- save_each = app.config['SESSION_REFRESH_EACH_REQUEST']308- return save_each and session.permanent325 326+ return session.modified or (327+ session.permanent and app.config['SESSION_REFRESH_EACH_REQUEST']328+ )329+330 def open_session(self, app, request):331 """This method has to be implemented and must either return ``None``332 in case the loading failed because of a configuration error or an333 instance of a session object which implements a dictionary like56 unmodified lines390 def save_session(self, app, session, response):391 domain = self.get_cookie_domain(app)392 path = self.get_cookie_path(app)393 374- # Delete case. If there is no session we bail early.375- # If the session was modified to be empty we remove the376- # whole cookie.394+ # If the session is modified to be empty, remove the cookie.395+ # If the session is empty, return without setting the cookie.396 if not session:397 if session.modified:379- response.delete_cookie(app.session_cookie_name,380- domain=domain, path=path)398+ response.delete_cookie(399+ app.session_cookie_name,400+ domain=domain,401+ path=path402+ )403+404 return405 383- # Modification case. There are upsides and downsides to384- # emitting a set-cookie header each request. The behavior385- # is controlled by the :meth:`should_set_cookie` method386- # which performs a quick check to figure out if the cookie387- # should be set or not. This is controlled by the388- # SESSION_REFRESH_EACH_REQUEST config flag as well as389- # the permanent flag on the session itself.406+ # Add a "Vary: Cookie" header if the session was accessed at all.407+ if session.accessed:408+ response.headers.add('Vary', 'Cookie')409+410 if not self.should_set_cookie(app, session):411 return412 413 httponly = self.get_cookie_httponly(app)414 secure = self.get_cookie_secure(app)415 expires = self.get_expiration_time(app, session)416 val = self.get_signing_serializer(app).dumps(dict(session))397- response.set_cookie(app.session_cookie_name, val,398- expires=expires, httponly=httponly,399- domain=domain, path=path, secure=secure)417+ response.set_cookie(418+ app.session_cookie_name,419+ val,420+ expires=expires,421+ httponly=httponly,422+ domain=domain,423+ path=path,424+ secure=secure425+ )modified:tests/test_basic.py+42 added
527 unmodified lines528 app.config['SESSION_REFRESH_EACH_REQUEST'] = False529 run_test(expect_header=False)530 531 532+def test_session_vary_cookie():533+ app = flask.Flask(__name__)534+ app.secret_key = 'testkey'535+536+ @app.route('/set')537+ def set_session():538+ flask.session['test'] = 'test'539+ return ''540+541+ @app.route('/get')542+ def get():543+ return flask.session.get('test')544+545+ @app.route('/getitem')546+ def getitem():547+ return flask.session['test']548+549+ @app.route('/setdefault')550+ def setdefault():551+ return flask.session.setdefault('test', 'default')552+553+ @app.route('/no-vary-header')554+ def no_vary_header():555+ return ''556+557+ c = app.test_client()558+559+ def expect(path, header=True):560+ rv = c.get(path)561+562+ if header:563+ assert rv.headers['Vary'] == 'Cookie'564+ else:565+ assert 'Vary' not in rv.headers566+567+ expect('/set')568+ expect('/get')569+ expect('/getitem')570+ expect('/setdefault')571+ expect('/no-vary-header', False)572+573+574 def test_flashes():575 app = flask.Flask(__name__)576 app.secret_key = 'testkey'577 1351 unmodified lines