Fix SQL Injection (Legacy & Modern) in Grape
Grape is a micro-framework for building APIs in Ruby. While it provides robust parameter validation, it does not inherently sanitize database queries. SQL Injection (SQLi) occurs when untrusted user input from Grape's 'params' hash is concatenated directly into SQL strings, bypassing the abstraction layers of ORMs like ActiveRecord or Sequel. Legacy systems often suffer from raw string interpolation, while modern variants involve dynamic 'ORDER BY' clauses or 'Arel' manipulation that bypasses standard sanitization.
The Vulnerable Pattern
class API < Grape::API resource :users do desc 'Get user by legacy ID' params do requires :id, type: String end get ':id' do # VULNERABLE: Direct string interpolation into raw SQL @user = ActiveRecord::Base.connection.execute("SELECT * FROM users WHERE id = '#{params[:id]}'").first enddesc 'Search users with dynamic ordering' params do optional :sort_column, type: String, default: 'id' end get :search do # MODERN VULNERABILITY: Unvalidated column name in ORDER BY User.order("#{params[:sort_column]} DESC") end
end end
The Secure Implementation
The fix involves two primary strategies: Parameterization and Whitelisting. For standard queries, use ActiveRecord's hash syntax or '?' placeholders; this ensures the database driver treats the input as a literal value rather than executable code. For 'Modern' SQLi—such as dynamic table names or sort columns—parameterization often fails because SQL does not allow placeholders for identifiers. In these cases, you must use Grape's 'values' validator to enforce a strict whitelist, ensuring only pre-approved, safe strings reach the query engine.
class API < Grape::API # Define allowed columns for sorting to prevent modern SQLi ALLOWED_SORT_COLUMNS = ['id', 'username', 'created_at'].freezeresource :users do desc ‘Get user by ID’ params do requires :id, type: Integer # Strict typing end get ‘:id’ do # SECURE: Use ActiveRecord’s find or parameterized where @user = User.find_by(id: params[:id]) end
desc 'Search users with secure ordering' params do optional :sort_column, type: String, values: ALLOWED_SORT_COLUMNS, default: 'id' end get :search do # SECURE: Input is validated against a whitelist via 'values' User.order(params[:sort_column].to_sym => :desc) end
end end
Your Grape API
might be exposed to SQL Injection (Legacy & Modern)
74% of Grape apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.