Skip to content

Commit

Permalink
Merge pull request from GHSA-m2qf-hxjv-5gpq
Browse files Browse the repository at this point in the history
set `Vary: Cookie` header consistently for session
  • Loading branch information
davidism authored May 1, 2023
2 parents 9532cba + 8705dd3 commit 70f906c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/flask/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,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 @@ -341,13 +345,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 @@ -363,3 +364,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 @@ -501,6 +501,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 @@ -533,11 +538,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 70f906c

Please sign in to comment.