Skip to content

Comments

Enable autoescape by default in Jinja2Templates#3146

Open
RinZ27 wants to merge 1 commit intoKludex:mainfrom
RinZ27:fix-jinja2-autoescape-default
Open

Enable autoescape by default in Jinja2Templates#3146
RinZ27 wants to merge 1 commit intoKludex:mainfrom
RinZ27:fix-jinja2-autoescape-default

Conversation

@RinZ27
Copy link

@RinZ27 RinZ27 commented Feb 15, 2026

Summary

Noticed that Jinja2Templates currently defaults to having autoescape disabled. It puts the burden on the developer to remember to enable it, which I've seen lead to XSS vulnerabilities in applications that render user-provided content.

While investigating, I also discovered that Jinja2Templates was missing support for **env_options in its constructor, making it difficult to customize the environment even though the documentation suggested it was supported.

Updated the implementation to:

  • Use jinja2.select_autoescape() by default for HTML/XML files to ensure a secure baseline.
  • Add support for **env_options in the Jinja2Templates constructor, allowing full customization of the Jinja2 environment.

Changes

  • Modified Jinja2Templates.__init__ to accept and use **env_options.
  • Enabled autoescape by default using select_autoescape() if not explicitly provided.
  • Added test cases in tests/test_templates.py to verify both the secure default and the ability to override it.

Checklist

  • Understood that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • Added a test for each change that was introduced, while I tried as much as possible to make a single atomic change.
  • Updated the documentation accordingly.

@RinZ27 RinZ27 force-pushed the fix-jinja2-autoescape-default branch 3 times, most recently from fd4589c to bc466d6 Compare February 15, 2026 06:43
@RinZ27
Copy link
Author

RinZ27 commented Feb 21, 2026

@Kludex, noticed #3148 covers the autoescape change. Moving forward with that is cool, though I'm happy to sync this PR with the new docs refactor if keeping the **env_options support makes sense.

Missing implementation for **env_options was something I spotted while checking the docs, so I've included it here.

@RinZ27 RinZ27 force-pushed the fix-jinja2-autoescape-default branch from 47374a4 to 6e35ce1 Compare February 21, 2026 08:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant