GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in Hug

SQL Injection in Hug occurs when untrusted user input is concatenated directly into SQL statements, bypassing the separation between data and logic. While Hug provides type validation, it does not sanitize data for database engines. To kill SQLi, you must move from string interpolation to parameterized queries or modern ORM abstractions that treat input as data, not executable code.

The Vulnerable Pattern

import hug
import sqlite3

@hug.get(‘/search’) def search_users(username: hug.types.text): db = sqlite3.connect(‘app.db’) cursor = db.cursor() # VULNERABLE: Direct f-string interpolation allows ‘admin’— payload query = f”SELECT * FROM users WHERE username = ‘{username}’” return cursor.execute(query).fetchall()

The Secure Implementation

The vulnerable snippet uses Python f-strings to build a query, allowing an attacker to break out of the quote context and append malicious SQL commands. The legacy fix utilizes the DB-API 2.0 standard of passing parameters as a separate tuple, ensuring the database driver handles escaping. The modern approach leverages SQLAlchemy's `text()` construct with named bind parameters, which provides a higher level of abstraction and safety against complex injection vectors like second-order SQLi.

import hug
import sqlite3
from sqlalchemy import create_engine, text

Legacy approach: Parameterized Queries

@hug.get(‘/search_legacy’) def search_legacy(username: hug.types.text): db = sqlite3.connect(‘app.db’) cursor = db.cursor() # SECURE: Use ’?’ placeholder; data is bound separately return cursor.execute(“SELECT * FROM users WHERE username = ?”, (username,)).fetchall()

Modern approach: SQLAlchemy Core with Hug

engine = create_engine(‘sqlite:///app.db’)

@hug.get(‘/search_modern’) def search_modern(username: hug.types.text): with engine.connect() as conn: # SECURE: Explicit bindparam prevents injection stmt = text(“SELECT * FROM users WHERE username = :u”) return conn.execute(stmt, {“u”: username}).fetchall()

System Alert • ID: 2964
Target: Hug API
Potential Vulnerability

Your Hug API might be exposed to SQL Injection (Legacy & Modern)

74% of Hug apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.