Skip to main content

Sonar: Enable Jinja2 Autoescape

sonar:python/enable-jinja2-autoescape-S5247

ImportanceReview GuidanceRequires Scanning Tool
HighMerge After ReviewYes (Sonar)

This codemod acts upon the following Sonar rules: python:S5247.

This codemod enables autoescaping of HTML content in jinja2. Unfortunately, the jinja2 default behavior is to not autoescape when rendering templates, which makes your applications potentially vulnerable to Cross-Site Scripting (XSS) attacks.

Our codemod checks if you forgot to enable autoescape or if you explicitly disabled it. The change looks as follows:

  from jinja2 import Environment

- env = Environment()
- env = Environment(autoescape=False, loader=some_loader)
+ env = Environment(autoescape=True)
+ env = Environment(autoescape=True, loader=some_loader)
...

If you have feedback on this codemod, please let us know!

F.A.Q.

Why is this codemod marked as Merge After Review?

This codemod protects your applications against XSS attacks. However, it's possible you would like to set the autoescape parameter to a custom callable.

Codemod Settings

N/A

References