ruby 94 lines · 4 tabs

Safer File Attachments: Content Type + Size Validation

Shared by codesnips Jan 2026
4 tabs
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
4 files · ruby Explain with highlit

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

Share this code

Here's the card — post it anywhere.

Safer File Attachments: Content Type + Size Validation — share card
Link copied