Skip to content

Commit 8646edc

Browse files
committed
set Vary: Cookie header consistently for session
1 parent a6367da commit 8646edc

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

CHANGES.rst

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ Version 2.2.5
44
Unreleased
55

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

89

910
Version 2.2.4

src/flask/sessions.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,10 @@ def save_session(
383383
samesite = self.get_cookie_samesite(app)
384384
httponly = self.get_cookie_httponly(app)
385385

386+
# Add a "Vary: Cookie" header if the session was accessed at all.
387+
if session.accessed:
388+
response.vary.add("Cookie")
389+
386390
# If the session is modified to be empty, remove the cookie.
387391
# If the session is empty, return without setting the cookie.
388392
if not session:
@@ -395,13 +399,10 @@ def save_session(
395399
samesite=samesite,
396400
httponly=httponly,
397401
)
402+
response.vary.add("Cookie")
398403

399404
return
400405

401-
# Add a "Vary: Cookie" header if the session was accessed at all.
402-
if session.accessed:
403-
response.vary.add("Cookie")
404-
405406
if not self.should_set_cookie(app, session):
406407
return
407408

@@ -417,3 +418,4 @@ def save_session(
417418
secure=secure,
418419
samesite=samesite,
419420
)
421+
response.vary.add("Cookie")

tests/test_basic.py

+23
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,11 @@ def getitem():
560560
def setdefault():
561561
return flask.session.setdefault("test", "default")
562562

563+
@app.route("/clear")
564+
def clear():
565+
flask.session.clear()
566+
return ""
567+
563568
@app.route("/vary-cookie-header-set")
564569
def vary_cookie_header_set():
565570
response = flask.Response()
@@ -592,11 +597,29 @@ def expect(path, header_value="Cookie"):
592597
expect("/get")
593598
expect("/getitem")
594599
expect("/setdefault")
600+
expect("/clear")
595601
expect("/vary-cookie-header-set")
596602
expect("/vary-header-set", "Accept-Encoding, Accept-Language, Cookie")
597603
expect("/no-vary-header", None)
598604

599605

606+
def test_session_refresh_vary(app, client):
607+
@app.get("/login")
608+
def login():
609+
flask.session["user_id"] = 1
610+
flask.session.permanent = True
611+
return ""
612+
613+
@app.get("/ignored")
614+
def ignored():
615+
return ""
616+
617+
rv = client.get("/login")
618+
assert rv.headers["Vary"] == "Cookie"
619+
rv = client.get("/ignored")
620+
assert rv.headers["Vary"] == "Cookie"
621+
622+
600623
def test_flashes(app, req_ctx):
601624
assert not flask.session.modified
602625
flask.flash("Zap")

0 commit comments

Comments
 (0)