class AttachmentContentTypeValidator < ActiveModel::EachValidator
SIGNATURES = {
"image/png" => ["\x89PNG\r\n\x1a\n".b],
"image/jpeg" => ["\xFF\xD8\xFF".b],
"image/gif" => ["GIF87a".b, "GIF89a".b],
"application/pdf" => ["%PDF-".b]
}.freeze
def validate_each(record, attribute, value)
return unless value.attached?
Array(value).each do |attachment|
blob = attachment.blob
validate_size(record, attribute, blob)
validate_declared_type(record, attribute, blob)
validate_sniffed_type(record, attribute, blob)
end
end
private
def validate_size(record, attribute, blob)
max = options[:max_size]
return unless max && blob.byte_size > max
record.errors.add(attribute, "is too large (max #{max / 1.megabyte}MB)")
end
def validate_declared_type(record, attribute, blob)
allowed = Array(options[:content_types])
return if allowed.include?(blob.content_type)
record.errors.add(attribute, "has an unsupported type: #{blob.content_type}")
end
def validate_sniffed_type(record, attribute, blob)
sniffed = sniff_content_type(blob)
return if sniffed.nil? || sniffed == blob.content_type
record.errors.add(attribute, "content does not match its declared type")
end
def sniff_content_type(blob)
head = blob.download(range: 0...16).to_s.b
SIGNATURES.each do |type, magics|
return type if magics.any? { |m| head.start_with?(m) }
end
nil
end
end
module HasSafeAttachment
extend ActiveSupport::Concern
class_methods do
def has_safe_attachment(name, content_types:, max_size:, **opts)
has_one_attached(name, **opts)
validates name, attachment_content_type: {
content_types: content_types,
max_size: max_size
}
end
end
end
class Document < ApplicationRecord
include HasSafeAttachment
belongs_to :owner, class_name: "User"
has_safe_attachment :file,
content_types: %w[image/png image/jpeg application/pdf],
max_size: 10.megabytes
validates :title, presence: true
end
class DocumentsController < ApplicationController
before_action :authenticate_user!
def create
document = current_user.documents.new(document_params)
if document.save
render json: { id: document.id, url: url_for(document.file) }, status: :created
else
render json: { errors: document.errors.full_messages }, status: :unprocessable_entity
end
end
private
def document_params
params.require(:document).permit(:title, :file)
end
end
Client-supplied content_type values on uploads are trivially spoofable, so relying on them alone lets a renamed executable slip through as an image/png. This snippet shows a defense-in-depth approach for Active Storage attachments that combines a declarative validator, a reusable model concern, and a controller that surfaces failures cleanly.
In AttachmentContentTypeValidator, the custom validator walks each attached blob and checks two things: the declared blob.content_type against an allow-list, and the actual leading bytes of the uploaded data (the file's magic number) against a signature table. The sniff_content_type method downloads a small prefix via blob.download with a byte range so it never pulls the whole file into memory, then matches known signatures for PNG, JPEG, PDF, and GIF. If the declared type and the sniffed type disagree, the record is rejected — this is what catches spoofed extensions. Size is enforced separately so an oversized-but-valid file gets a distinct, actionable message.
The HasSafeAttachment concern packages this into one macro, has_safe_attachment. It calls has_one_attached, then registers the validator with the caller's content_types and max_size options. Centralizing the wiring keeps every model consistent and avoids copy-pasting validation blocks. Document simply declares has_safe_attachment :file, content_types: %w[...], max_size: 10.megabytes, so its intent is readable at a glance.
DocumentsController demonstrates the request-side story. It builds the record, and because validations run on save, an invalid or spoofed upload never reaches storage in a committed state — Active Storage's attach stages the blob, but a failed save leaves the record unpersisted. The controller renders record.errors as JSON so the client learns exactly which rule failed.
The main trade-off is cost: sniffing requires a partial download, which adds latency and a storage read per validated attachment. For high-volume uploads a background job or a size cap before download mitigates this. The signature table is also intentionally small; extending it means adding entries to SIGNATURES. A remaining pitfall is that magic-byte checks confirm a file starts like a given type but do not fully validate its structure, so untrusted images still warrant reprocessing or scanning downstream.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
Share this code
Here's the card — post it anywhere.