logo

Database

Python Fastapi Html Injection

Description

This detector identifies HTML injection vulnerabilities in FastAPI applications where user-controlled data is directly returned as HTML content without proper sanitization. HTML injection can lead to cross-site scripting (XSS) attacks, allowing attackers to execute malicious scripts in users' browsers.

Weakness:

045 - HTML code injection

Category: Unexpected Injection

Detection Strategy

    • The code must import the FastAPI library

    • FastAPI HTML response classes (like HTMLResponse) or general Response classes must be imported

    • User input or tainted data must flow directly into HTML response constructors or Response objects with HTML content-type

    • The tainted data reaches the response without proper HTML encoding or sanitization

Vulnerable code example

from fastapi import Query
from fastapi.responses import HTMLResponse

async def vuln_endpoint(name: str = Query(default=None)):
    # VULNERABLE: User input directly interpolated into HTML without escaping
    html = f"<html><body><h1>Hello, {name}!</h1></body></html>"
    return HTMLResponse(html)  # XSS vulnerability

✅ Secure code example

from fastapi import Query
from fastapi.responses import HTMLResponse
from markupsafe import escape

async def vuln_endpoint(name: str = Query(default=None)):
    # SAFE: escape() encodes <>&"' preventing script injection
    safe_name = escape(name)
    html = f"<html><body><h1>Hello, {safe_name}!</h1></body></html>"...