Skip to content
Myr

enable secret key rotation

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 7522c4b · Browse files · 12 files+232 added−184 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+232 added−184 removed

  • tests:+199 added−177 removed
  • other:+33 added−7 removed

12 files+232 added−184 removed

modified:docs/config.rst+16 added
123 unmodified lines
124 **Do not reveal the secret key when posting questions or committing code.**125126 Default: ``None``127128.. py:data:: SECRET_KEY_FALLBACKS129130 A list of old secret keys that can still be used for unsigning, most recent131 first. This allows a project to implement key rotation without invalidating132 active sessions or other recently-signed secrets.133134 Keys should be removed after an appropriate period of time, as checking each135 additional key adds some overhead.136137 Flask's built-in secure cookie session supports this. Extensions that use138 :data:`SECRET_KEY` may not support this yet.139140 Default: ``None``141142 .. versionadded:: 3.1143144.. py:data:: SESSION_COOKIE_NAME145146 The name of the session cookie. Can be changed in case you already have a147 cookie with the same name.
665 unmodified lines
modified:src/flask/app.py+1 added
178 unmodified lines
179 "DEBUG": None,180 "TESTING": False,181 "PROPAGATE_EXCEPTIONS": None,182 "SECRET_KEY": None,183 "SECRET_KEY_FALLBACKS": None,184 "PERMANENT_SESSION_LIFETIME": timedelta(days=31),185 "USE_X_SENDFILE": False,186 "SERVER_NAME": None,187 "APPLICATION_ROOT": "/",
1334 unmodified lines
modified:src/flask/sessions.py+11 added-5 removed
313 unmodified lines
314315 def get_signing_serializer(self, app: Flask) -> URLSafeTimedSerializer | None:316 if not app.secret_key:317 return None318 signer_kwargs = dict(319 key_derivation=self.key_derivation, digest_method=self.digest_method320 )318319 keys: list[str | bytes] = [app.secret_key]320321 if fallbacks := app.config["SECRET_KEY_FALLBACKS"]:322 keys.extend(fallbacks)323324 return URLSafeTimedSerializer(322 app.secret_key,325 keys, # type: ignore[arg-type]326 salt=self.salt,327 serializer=self.serializer,325 signer_kwargs=signer_kwargs,328 signer_kwargs={329 "key_derivation": self.key_derivation,330 "digest_method": self.digest_method,331 },332 )333334 def open_session(self, app: Flask, request: Request) -> SecureCookieSession | None:335 s = self.get_signing_serializer(app)
61 unmodified lines
added:tests/type_check/typing_app_decorators.py+32 added
1from __future__ import annotations23from flask import Flask4from flask import Response56app = Flask(__name__)789@app.after_request10def after_sync(response: Response) -> Response:11 return Response()121314@app.after_request15async def after_async(response: Response) -> Response:16 return Response()171819@app.before_request20def before_sync() -> None: ...212223@app.before_request24async def before_async() -> None: ...252627@app.teardown_appcontext28def teardown_sync(exc: BaseException | None) -> None: ...293031@app.teardown_appcontext32async def teardown_async(exc: BaseException | None) -> None: ...
added:tests/type_check/typing_error_handler.py+33 added
1from __future__ import annotations23from http import HTTPStatus45from werkzeug.exceptions import BadRequest6from werkzeug.exceptions import NotFound78from flask import Flask910app = Flask(__name__)111213@app.errorhandler(400)14@app.errorhandler(HTTPStatus.BAD_REQUEST)15@app.errorhandler(BadRequest)16def handle_400(e: BadRequest) -> str:17 return ""181920@app.errorhandler(ValueError)21def handle_custom(e: ValueError) -> str:22 return ""232425@app.errorhandler(ValueError)26def handle_accept_base(e: Exception) -> str:27 return ""282930@app.errorhandler(BadRequest)31@app.errorhandler(404)32def handle_multiple(e: BadRequest | NotFound) -> str:33 return ""
added:tests/type_check/typing_route.py+112 added
1from __future__ import annotations23import typing as t4from http import HTTPStatus56from flask import Flask7from flask import jsonify8from flask import stream_template9from flask.templating import render_template10from flask.views import View11from flask.wrappers import Response1213app = Flask(__name__)141516@app.route("/str")17def hello_str() -> str:18 return "<p>Hello, World!</p>"192021@app.route("/bytes")22def hello_bytes() -> bytes:23 return b"<p>Hello, World!</p>"242526@app.route("/json")27def hello_json() -> Response:28 return jsonify("Hello, World!")293031@app.route("/json/dict")32def hello_json_dict() -> dict[str, t.Any]:33 return {"response": "Hello, World!"}343536@app.route("/json/dict")37def hello_json_list() -> list[t.Any]:38 return [{"message": "Hello"}, {"message": "World"}]394041class StatusJSON(t.TypedDict):42 status: str434445@app.route("/typed-dict")46def typed_dict() -> StatusJSON:47 return {"status": "ok"}484950@app.route("/generator")51def hello_generator() -> t.Generator[str, None, None]:52 def show() -> t.Generator[str, None, None]:53 for x in range(100):54 yield f"data:{x}\n\n"5556 return show()575859@app.route("/generator-expression")60def hello_generator_expression() -> t.Iterator[bytes]:61 return (f"data:{x}\n\n".encode() for x in range(100))626364@app.route("/iterator")65def hello_iterator() -> t.Iterator[str]:66 return iter([f"data:{x}\n\n" for x in range(100)])676869@app.route("/status")70@app.route("/status/<int:code>")71def tuple_status(code: int = 200) -> tuple[str, int]:72 return "hello", code737475@app.route("/status-enum")76def tuple_status_enum() -> tuple[str, int]:77 return "hello", HTTPStatus.OK787980@app.route("/headers")81def tuple_headers() -> tuple[str, dict[str, str]]:82 return "Hello, World!", {"Content-Type": "text/plain"}838485@app.route("/template")86@app.route("/template/<name>")87def return_template(name: str | None = None) -> str:88 return render_template("index.html", name=name)899091@app.route("/template")92def return_template_stream() -> t.Iterator[str]:93 return stream_template("index.html", name="Hello")949596@app.route("/async")97async def async_route() -> str:98 return "Hello"99100101class RenderTemplateView(View):102 def __init__(self: RenderTemplateView, template_name: str) -> None:103 self.template_name = template_name104105 def dispatch_request(self: RenderTemplateView) -> str:106 return render_template(self.template_name)107108109app.add_url_rule(110 "/about",111 view_func=RenderTemplateView.as_view("about_page", template_name="about.html"),112)
deleted:tests/typing/typing_app_decorators.py-32 removed
1from __future__ import annotations23from flask import Flask4from flask import Response56app = Flask(__name__)789@app.after_request10def after_sync(response: Response) -> Response:11 return Response()121314@app.after_request15async def after_async(response: Response) -> Response:16 return Response()171819@app.before_request20def before_sync() -> None: ...212223@app.before_request24async def before_async() -> None: ...252627@app.teardown_appcontext28def teardown_sync(exc: BaseException | None) -> None: ...293031@app.teardown_appcontext32async def teardown_async(exc: BaseException | None) -> None: ...
deleted:tests/typing/typing_error_handler.py-33 removed
1from __future__ import annotations23from http import HTTPStatus45from werkzeug.exceptions import BadRequest6from werkzeug.exceptions import NotFound78from flask import Flask910app = Flask(__name__)111213@app.errorhandler(400)14@app.errorhandler(HTTPStatus.BAD_REQUEST)15@app.errorhandler(BadRequest)16def handle_400(e: BadRequest) -> str:17 return ""181920@app.errorhandler(ValueError)21def handle_custom(e: ValueError) -> str:22 return ""232425@app.errorhandler(ValueError)26def handle_accept_base(e: Exception) -> str:27 return ""282930@app.errorhandler(BadRequest)31@app.errorhandler(404)32def handle_multiple(e: BadRequest | NotFound) -> str:33 return ""
deleted:tests/typing/typing_route.py-112 removed
1from __future__ import annotations23import typing as t4from http import HTTPStatus56from flask import Flask7from flask import jsonify8from flask import stream_template9from flask.templating import render_template10from flask.views import View11from flask.wrappers import Response1213app = Flask(__name__)141516@app.route("/str")17def hello_str() -> str:18 return "<p>Hello, World!</p>"192021@app.route("/bytes")22def hello_bytes() -> bytes:23 return b"<p>Hello, World!</p>"242526@app.route("/json")27def hello_json() -> Response:28 return jsonify("Hello, World!")293031@app.route("/json/dict")32def hello_json_dict() -> dict[str, t.Any]:33 return {"response": "Hello, World!"}343536@app.route("/json/dict")37def hello_json_list() -> list[t.Any]:38 return [{"message": "Hello"}, {"message": "World"}]394041class StatusJSON(t.TypedDict):42 status: str434445@app.route("/typed-dict")46def typed_dict() -> StatusJSON:47 return {"status": "ok"}484950@app.route("/generator")51def hello_generator() -> t.Generator[str, None, None]:52 def show() -> t.Generator[str, None, None]:53 for x in range(100):54 yield f"data:{x}\n\n"5556 return show()575859@app.route("/generator-expression")60def hello_generator_expression() -> t.Iterator[bytes]:61 return (f"data:{x}\n\n".encode() for x in range(100))626364@app.route("/iterator")65def hello_iterator() -> t.Iterator[str]:66 return iter([f"data:{x}\n\n" for x in range(100)])676869@app.route("/status")70@app.route("/status/<int:code>")71def tuple_status(code: int = 200) -> tuple[str, int]:72 return "hello", code737475@app.route("/status-enum")76def tuple_status_enum() -> tuple[str, int]:77 return "hello", HTTPStatus.OK787980@app.route("/headers")81def tuple_headers() -> tuple[str, dict[str, str]]:82 return "Hello, World!", {"Content-Type": "text/plain"}838485@app.route("/template")86@app.route("/template/<name>")87def return_template(name: str | None = None) -> str:88 return render_template("index.html", name=name)899091@app.route("/template")92def return_template_stream() -> t.Iterator[str]:93 return stream_template("index.html", name="Hello")949596@app.route("/async")97async def async_route() -> str:98 return "Hello"99100101class RenderTemplateView(View):102 def __init__(self: RenderTemplateView, template_name: str) -> None:103 self.template_name = template_name104105 def dispatch_request(self: RenderTemplateView) -> str:106 return render_template(self.template_name)107108109app.add_url_rule(110 "/about",111 view_func=RenderTemplateView.as_view("about_page", template_name="about.html"),112)
modified:tests/test_basic.py+22 added
1import gc2import re3import typing as t4import uuid5import warnings6import weakref7from datetime import datetime
361 unmodified lines
369 expect_exception(flask.session.__setitem__, "foo", 42)370 expect_exception(flask.session.pop, "foo")371372373def test_session_secret_key_fallbacks(app, client) -> None:374 @app.post("/")375 def set_session() -> str:376 flask.session["a"] = 1377 return ""378379 @app.get("/")380 def get_session() -> dict[str, t.Any]:381 return dict(flask.session)382383 # Set session with initial secret key384 client.post()385 assert client.get().json == {"a": 1}386 # Change secret key, session can't be loaded and appears empty387 app.secret_key = "new test key"388 assert client.get().json == {}389 # Add initial secret key as fallback, session can be loaded390 app.config["SECRET_KEY_FALLBACKS"] = ["test key"]391 assert client.get().json == {"a": 1}392393394def test_session_expiration(app, client):395 permanent = True396397 @app.route("/")
1497 unmodified lines
modified:CHANGES.rst+3 added
18 unmodified lines
19 ``SESSION_COOKIE_PARTITIONED`` config. :issue`5472`20- ``-e path`` takes precedence over default ``.env`` and ``.flaskenv`` files.21 ``load_dotenv`` loads default files in addition to a path unless22 ``load_defaults=False`` is passed. :issue:`5628`23- Support key rotation with the ``SECRET_KEY_FALLBACKS`` config, a list of old24 secret keys that can still be used for unsigning. Extensions will need to25 add support. :issue:`5621`262728Version 3.0.329-------------
1563 unmodified lines
modified:pyproject.toml+2 added-2 removed
77 unmodified lines
78source = ["src", "*/site-packages"]7980[tool.mypy]81python_version = "3.9"82files = ["src/flask", "tests/typing"]82files = ["src/flask", "tests/type_check"]83show_error_codes = true84pretty = true85strict = true86
7 unmodified lines
94ignore_missing_imports = true9596[tool.pyright]97pythonVersion = "3.9"98include = ["src/flask", "tests/typing"]98include = ["src/flask", "tests/type_check"]99typeCheckingMode = "basic"100101[tool.ruff]102src = ["src"]
22 unmodified lines