GuardAPI Logo
GuardAPI

Fix SQL Injection (Legacy & Modern) in Hanami

Hanami's persistence layer is built on ROM (Ruby Object Mapper) and Sequel. While these tools provide robust abstractions, SQL injection vulnerabilities creep in when developers bypass the DSL to use raw SQL fragments with string interpolation. In Hanami 1.x (Legacy) and 2.x (Modern), the risk is identical: treating untrusted input as part of the query structure rather than a parameter.

The Vulnerable Pattern

class UserRepository < Hanami::Repository
  def find_by_unsafe_search(input)
    # LEAK: String interpolation inside a WHERE fragment
    # Example input: "' OR 1=1 --"
    users.where("username = '#{input}'").to_a
  end

def raw_exec(id) # LEAK: Direct execution of interpolated strings users.read(“SELECT * FROM users WHERE id = #{id}”) end end

The Secure Implementation

The vulnerability stems from the database driver's inability to distinguish between SQL commands and user-supplied data when they are concatenated into a single string. In the vulnerable example, an attacker can break out of the single quotes to manipulate the logic of the query. The secure examples utilize Sequel's parameter binding. By passing the input as a separate argument to the .where method (either via a Hash or a placeholder), the underlying database driver treats the input as a literal value, automatically escaping dangerous characters and ensuring the query structure remains intact. Always avoid literal string interpolation inside Hanami repository methods.

class UserRepository < Hanami::Repository
  def find_by_safe_search(input)
    # FIX 1: Use Hash syntax (Preferred ROM/Sequel style)
    users.where(username: input).to_a
  end

def find_by_placeholder(input) # FIX 2: Use positional placeholders users.where(“username = ?”, input).to_a end

def find_by_named_binding(input) # FIX 3: Use named placeholders users.where(“username = :name”, name: input).to_a end end

System Alert • ID: 6078
Target: Hanami API
Potential Vulnerability

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

74% of Hanami 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.