Skip to content

Commit

Permalink
set Vary: Cookie header consistently for session
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism committed May 2, 2023
1 parent a6367da commit 8646edc
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Version 2.2.5
Unreleased

- Update for compatibility with Werkzeug 2.3.3.
- Set ``Vary: Cookie`` header when the session is accessed, modified, or refreshed.


Version 2.2.4
Expand Down
10 changes: 6 additions & 4 deletions src/flask/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,10 @@ def save_session(
samesite = self.get_cookie_samesite(app)
httponly = self.get_cookie_httponly(app)

# Add a "Vary: Cookie" header if the session was accessed at all.
if session.accessed:
response.vary.add("Cookie")

# If the session is modified to be empty, remove the cookie.
# If the session is empty, return without setting the cookie.
if not session:
Expand All @@ -395,13 +399,10 @@ def save_session(
samesite=samesite,
httponly=httponly,
)
response.vary.add("Cookie")

return

# Add a "Vary: Cookie" header if the session was accessed at all.
if session.accessed:
response.vary.add("Cookie")

if not self.should_set_cookie(app, session):
return

Expand All @@ -417,3 +418,4 @@ def save_session(
secure=secure,
samesite=samesite,
)
response.vary.add("Cookie")
23 changes: 23 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,11 @@ def getitem():
def setdefault():
return flask.session.setdefault("test", "default")

@app.route("/clear")
def clear():
flask.session.clear()
return ""

@app.route("/vary-cookie-header-set")
def vary_cookie_header_set():
response = flask.Response()
Expand Down Expand Up @@ -592,11 +597,29 @@ def expect(path, header_value="Cookie"):
expect("/get")
expect("/getitem")
expect("/setdefault")
expect("/clear")
expect("/vary-cookie-header-set")
expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")
expect("/no-vary-header", None)


def test_session_refresh_vary(app, client):
@app.get("/login")
def login():
flask.session["user_id"] = 1
flask.session.permanent = True
return ""

@app.get("/ignored")
def ignored():
return ""

rv = client.get("/login")
assert rv.headers["Vary"] == "Cookie"
rv = client.get("/ignored")
assert rv.headers["Vary"] == "Cookie"


def test_flashes(app, req_ctx):
assert not flask.session.modified
flask.flash("Zap")
Expand Down

0 comments on commit 8646edc

Please sign in to comment.