ruby
8 lines · 1 tab
Kai Nakamura
Apr 2026
1 tab
base_path = Rails.root.join('storage', 'exports').realpath
requested = base_path.join(params[:filename].to_s).cleanpath
unless requested.to_s.start_with?(base_path.to_s) && requested.file?
raise ActionController::RoutingError, 'Not Found'
end
send_file requested, disposition: 'attachment'
1 file · ruby
Explain with highlit
Any endpoint that reads from disk needs path normalization and strict base-directory enforcement. I never trust user-supplied file names and I avoid passing them straight into shell commands. Safe file access is mostly about refusing to be clever.
Related snips
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]
sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first
SQL injection prevention with unsafe and safe query patterns
sql-injection
owasp
database
by Kai Nakamura
3 tabs
ruby
RegistrationSchema = Dry::Schema.Params do
required(:email).filled(:string, format?: URI::MailTo::EMAIL_REGEXP)
required(:password).filled(:string, min_size?: 12)
optional(:marketing_opt_in).filled(:bool)
optional(:country).filled(:string, included_in?: %w[US CA GB AU])
end
Input validation with allowlists and explicit schemas
input-validation
schemas
secure-coding
by Kai Nakamura
1 tab
ruby
raw_token = SecureRandom.urlsafe_base64(32)
token_digest = Digest::SHA256.hexdigest(raw_token)
PasswordReset.create!(
user: user,
token_digest: token_digest,
Secure random token generation for sessions and recovery flows
randomness
tokens
authentication
by Kai Nakamura
1 tab
python
import psycopg
with psycopg.connect(conninfo) as connection:
with connection.cursor() as cursor:
cursor.execute(
'SELECT id, email FROM users WHERE email = %s',
Parameterized queries in Python with psycopg
python
sql-injection
psycopg
by Kai Nakamura
1 tab
python
from defusedxml.ElementTree import fromstring
payload = request.data.decode('utf-8')
root = fromstring(payload)
invoice_number = root.findtext('invoice_number')
XXE safe XML parsing with external entity resolution disabled
xxe
xml
parsing
by Kai Nakamura
1 tab
ruby
allowed_types = ['image/png', 'image/jpeg', 'application/pdf']
uploaded = params.require(:document)
raise ActionController::BadRequest, 'file too large' if uploaded.size > 10.megabytes
raise ActionController::BadRequest, 'type not allowed' unless allowed_types.include?(uploaded.content_type)
Hardening file uploads with MIME checks and storage isolation
file-uploads
validation
malware
by Kai Nakamura
1 tab
Share this code
Here's the card — post it anywhere.