All posts

How to Fix Xss Vulnerability in Flask

A practical guide to resolving Xss Vulnerability in Flask, with real code examples and debugging tips.

XSS Vulnerabilities in Flask

Flask uses Jinja2 which auto-escapes template variables by default, but XSS can occur when using |safe filter, Markup(), or returning raw HTML from routes.

How It Happens

  • Using |safe or Markup() on user input
  • render_template_string() with user data
  • API routes returning HTML with unescaped content

Resolution

Rely on auto-escaping and sanitize when needed:

from flask import Flask, render_template, request
from markupsafe import Markup, escape
import bleach

app = Flask(__name__)

# WRONG: XSS vulnerability
# return Markup(f"<p>{user_input}</p>")

# RIGHT: auto-escaping in templates
@app.route('/comment', methods=['POST'])
def add_comment():
    comment = request.form.get('comment', '')

    # If you need to allow some HTML:
    safe_html = bleach.clean(
        comment,
        tags=['b', 'i', 'em', 'strong', 'a'],
        attributes={'a': ['href']},
        strip=True
    )
    return render_template('comment.html', comment=safe_html)

# Set security headers
@app.after_request
def security_headers(response):
    response.headers['Content-Security-Policy'] = "default-src 'self'"
    response.headers['X-Content-Type-Options'] = 'nosniff'
    return response

Never use |safe or Markup() on user-provided data. Use bleach when you need to allow limited HTML.

Avoiding Recurrence

Once you fix this error, add a regression test that reproduces the exact scenario. Document the root cause in your team's knowledge base so others can recognize the pattern. Configure monitoring alerts for early detection if the issue appears again in a different part of the codebase.

Bugsly for Flask

Bugsly detects potential XSS by flagging errors where HTML-like content appears in user input fields, alerting you to potential attack attempts.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free