class HTML::Pipeline::Gitlab::GitlabEmailImageFilter

HTML filter that replaces linked images with inline images in emails.

Public Instance Methods

base64_encode_image(file_path) click to toggle source
# File lib/html/pipeline/gitlab/gitlab_email_image_filter.rb, line 30
def base64_encode_image(file_path)
  mime_type = MIME::Types.type_for(file_path).first
  return nil if mime_type.nil?

  content_type = mime_type.content_type
  img = File.read(file_path)
  encoded_image = Base64.encode64(img)
  "data:#{content_type};base64,#{encoded_image}"
end
call() click to toggle source
# File lib/html/pipeline/gitlab/gitlab_email_image_filter.rb, line 11
def call
  doc.search('img').each do |img|
    next if img['src'].nil?

    src = img['src'].strip
    next unless src.start_with?(context[:base_url])

    file_path =
      get_file_path(src, context[:upload_path], context[:base_url])
    next unless File.file?(file_path)
    encoded_image = base64_encode_image(file_path)
    next unless encoded_image.present?

    img['src'] = encoded_image
  end

  doc
end
get_file_path(url, upload_path, base_url) click to toggle source
# File lib/html/pipeline/gitlab/gitlab_email_image_filter.rb, line 40
def get_file_path(url, upload_path, base_url)
  # replace base url with location in file system
  url.gsub!(base_url, '')
  file_path = prevent_path_traversal(url)
  File.join(upload_path, file_path)
end
prevent_path_traversal(file_path) click to toggle source
# File lib/html/pipeline/gitlab/gitlab_email_image_filter.rb, line 47
def prevent_path_traversal(file_path)
  # decode the url. We don't want encoded chars in our file path
  file_path = URI.decode(file_path).to_s
  # remove all occurences of ".." from the url
  # to prevent path traversing
  file_path = file_path.gsub('..', '')
  # replace unnecessary double slashes
  file_path.gsub('//', '/')
end