Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 7 min read

Cache Website Favicons Safely in Ruby and Audit the favicon Gem

Bookmark managers, RSS readers, and link-preview cards all hit the same annoying problem: websites declare icons inconsistently across /favicon.ico, <link rel="icon">, SVG tags, and web manifests. Delegating that lookup

Bookmark managers, RSS readers, and link-preview cards all hit the same annoying problem: websites declare icons inconsistently across /favicon.ico, <link rel="icon">, SVG tags, and web manifests. Delegating that lookup to an external resolver is tempting, yet hotlinking third-party icon URLs directly inside <img src="..."> leaks visitor IP addresses and Referer headers, breaks when an upstream hostname changes, and triggers mixed-content blocks if the URL uses plain http://.

paladini/favicon (published on RubyGems as favicon 0.1.1 under the MIT License) is a tiny, zero-runtime-dependency Ruby gem created to turn a target URL into a Google /s2/favicons lookup URL. Inspecting its tagged v0.1.1 release alongside its unreleased master branch reveals a textbook set of real-world package maintenance lessons: an upstream apex-domain 404 regression in the published gem, Ruby singleton method visibility rules, case-sensitive scheme matching, and unencoded query parameters.

In this tutorial, you will inspect both v0.1.1 and master, wrap Favicon.find in a server-side Ruby caching helper using only standard-library modules (uri, ipaddr, net/http, digest, and fileutils), and verify every edge case locally with Minitest.

TL;DR

  • Published favicon 0.1.1 builds http://google.com/s2/favicons?domain=..., which now returns HTTP 404; unreleased master (PR #1) switches to https://www.google.com/s2/favicons?domain=..., which redirects (301) to gstatic.com and serves a 200 image/png.
  • Even on master, raw string concatenation leaves uppercase schemes (HTTPS://), query strings (?a=1&sz=128), and internal hosts unfiltered.
  • Normalizing the host with Ruby's URI and IPAddr classes, encoding query parameters with URI.encode_www_form, and caching verified image bytes on your server follows the gem README's own advice to store icons locally.

Prerequisites

  • Ruby 3.1+ (ruby -v; tested locally on Ruby 4.0.6 with bundled minitest).
  • Git to clone paladini/favicon and compare tag v0.1.1 against master.
  • Familiarity with basic Ruby modules, URI.parse, and HTTP redirects.

Minimal Working Path

Clone the repository and compare tag v0.1.1 (cad75ab) against master (a06424a):

git clone https://github.com/paladini/favicon.git
cd favicon
git diff v0.1.1..master -- lib/favicon.rb

On master, lib/favicon.rb holds the whole gem:

module Favicon

    public
        @base_url_google = "https://www.google.com/s2/favicons?domain="

        def self.find(url)

            # Prepare the URL for API Request
            url = prepareUrl(url)

            # Return the values
            return find_favicon(url)
        end

    private

        # Preparing url before the API request.
        def self.prepareUrl(url)
            if url[/^https?:\/\//]
              url = url
            else
              url = 'http://' + url
            end
            return url
        end

        def self.find_favicon(url)
            return @base_url_google + url
        end

end

In v0.1.1 (installed by gem install favicon), @base_url_google is "http://google.com/s2/favicons?domain=" without https:// or www.. Because test/test_favicon.rb still holds Jeweler's flunk placeholder, save test_safe_favicon.rb outside the repository. It wraps Favicon.find, normalizes hosts to HTTPS, caches verified icon bytes, and runs five Minitest checks:

# frozen_string_literal: true

$LOAD_PATH.unshift(File.expand_path("favicon/lib", __dir__))
require "favicon"
require "digest"
require "fileutils"
require "ipaddr"
require "minitest/autorun"
require "net/http"
require "tmpdir"
require "uri"

module SafeFaviconCache
  ALLOWED_TYPES = %w[image/png image/x-icon image/vnd.microsoft.icon image/webp image/gif].freeze
  MAX_BYTES = 65_536
  module_function

  def normalize_host(raw_url)
    s = raw_url.to_s.strip
    raise ArgumentError, "empty URL" if s.empty?
    if s.match?(%r{\A[a-z][a-z0-9+.-]*:(?://|[^0-9])}i) && !s.match?(%r{\Ahttps?://}i)
      raise ArgumentError, "unsupported scheme"
    end

    uri = URI.parse(s.match?(%r{\Ahttps?://}i) ? s : "https://#{s}")
    host = uri.host&.downcase&.chomp(".")
    raise ArgumentError, "invalid host" if host.nil? || host == "localhost" || !host.include?(".")

    begin
      IPAddr.new(host.delete_prefix("[").delete_suffix("]"))
      raise ArgumentError, "IP literals denied"
    rescue IPAddr::InvalidAddressError
      host
    end
  rescue URI::InvalidURIError => e
    raise ArgumentError, e.message
  end

  def build_lookup_uri(raw_url)
    host = normalize_host(raw_url)
    parsed = URI.parse(Favicon.find("https://#{host}"))
    URI::HTTPS.build(
      host: parsed.host == "google.com" ? "www.google.com" : parsed.host,
      path: parsed.path,
      query: URI.encode_www_form(domain: "https://#{host}")
    )
  end

  def fetch_and_store(raw_url, cache_dir:, http_get: method(:default_get))
    host = normalize_host(raw_url)
    status, content_type, body = http_get.call(build_lookup_uri(raw_url))
    type = content_type.to_s.split(";").first.to_s.strip.downcase
    raise "HTTP #{status}" unless status == 200
    raise "disallowed type #{type}" unless ALLOWED_TYPES.include?(type)
    raise "invalid size" unless body.bytesize.between?(1, MAX_BYTES)

    FileUtils.mkdir_p(cache_dir)
    ext = type.include?("png") ? "png" : "ico"
    dest = File.join(cache_dir, "#{host}-#{Digest::SHA256.hexdigest(host)[0, 12]}.#{ext}")
    File.binwrite(dest, body)
    dest
  end

  def default_get(uri, limit = 3)
    raise "redirect limit" if limit <= 0

    Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 5, read_timeout: 5) do |http|
      res = http.request(Net::HTTP::Get.new(uri))
      return [res.code.to_i, res["content-type"], res.body.to_s] if res.is_a?(Net::HTTPSuccess)
      return [res.code.to_i, res["content-type"], ""] unless res.is_a?(Net::HTTPRedirection)

      next_uri = URI.join(uri, res["location"])
      raise "HTTPS downgrade" unless next_uri.scheme == "https"

      default_get(next_uri, limit - 1)
    end
  end
end

class FaviconAuditTest < Minitest::Test
  def test_gem_singleton_visibility_and_edge_cases
    assert_includes Favicon.singleton_methods, :prepareUrl
    assert_match(%r{domain=http://HTTPS://Example\.com\z}, Favicon.find("HTTPS://Example.com"))
    assert_includes Favicon.find("example.com/p?a=1&sz=128"), "&sz=128"
  end

  def test_safe_lookup_upgrades_to_https
    uri = SafeFaviconCache.build_lookup_uri("HTTPS://GitHub.com/paladini/favicon?sz=128")
    assert_equal "https://www.google.com/s2/favicons?domain=https%3A%2F%2Fgithub.com", uri.to_s
  end

  def test_rejects_unsafe_targets
    %w[javascript:alert(1) ftp://files.example.com http://localhost:3000 http://127.0.0.1].each do |bad|
      assert_raises(ArgumentError) { SafeFaviconCache.build_lookup_uri(bad) }
    end
  end

  def test_caches_verified_png
    png = "\x89PNG\r\n\x1a\nstub".b
    Dir.mktmpdir do |dir|
      saved = SafeFaviconCache.fetch_and_store("github.com/paladini/favicon", cache_dir: dir, http_get: ->(_) { [200, "image/png", png] })
      assert_equal png, File.binread(saved)
    end
  end
end

Expected Result and Reproducible Verification

Run the suite from the parent directory against both v0.1.1 and master:

git -C favicon checkout v0.1.1
ruby test_safe_favicon.rb --seed 42
git -C favicon checkout master
ruby test_safe_favicon.rb --seed 42

Both checkouts produce passing output:

Run options: --seed 42

# Running:

....

Finished in 0.019982s, 200.1812 runs/s, 600.5435 assertions/s.

4 runs, 12 assertions, 0 failures, 0 errors, 0 skips

Against a live network check for github.com, https://www.google.com/s2/favicons?domain=https%3A%2F%2Fgithub.com returns HTTP 301 to gstatic.com, then HTTP 200 (image/png, 330 bytes, PNG header 89504e470d0a1a0a). Requesting the unmodified v0.1.1 URL (http://google.com/s2/favicons?domain=http://github.com) returns HTTP 404.

Why It Works

  1. Apex google.com vs. www.google.com. Version 0.1.1 targets bare google.com, where /s2/favicons returns 404 over both HTTP and HTTPS. Rewriting parsed.host == "google.com" to "www.google.com" inside URI::HTTPS.build aligns the published gem with master without patching installed gem files.
  2. Canonical host extraction. Favicon.prepareUrl checks url[/^https?:\/\//] case-sensitively and keeps full paths and query strings. Parsing only the lowercased hostname via URI.parse stops HTTPS://GitHub.com from turning into http://HTTPS://GitHub.com and keeps pasted query parameters out of the upstream request.
  3. Server-side caching over hotlinking. README.md advises storing icons locally because /s2/favicons is undocumented. Serving verified cached bytes avoids mixed-content blocks (MDN Mixed Content) and prevents visitor IP and Referer leakage.

Failure Modes, Limitations, and Security Boundaries

  • Published gem vs. master drift. VERSION and favicon.gemspec stay at 0.1.1 after PR #1 merged in November 2018, so RubyGems still serves the 2014 code unless you pin master (a06424a) in your Gemfile or normalize the returned URI.
  • Ruby private does not hide def self.method. Inside a module body, private only scopes instance methods. Favicon.singleton_methods exposes [:find, :find_favicon, :prepareUrl]; hiding singleton helpers requires private_class_method or class << self.
  • Legacy development group. Gemfile uses http://rubygems.org and pins jeweler ~> 2.0.1 and rdoc ~> 3.12. Load lib/favicon.rb directly rather than installing the 2014 :development group.
  • Third-party availability and SSRF controls. /s2/favicons has no SLA and returns a fallback globe icon for unknown domains. Deny localhost, single-label hosts, non-HTTP schemes, IP literals, HTTPS downgrades, non-image MIME types, and payloads over 65_536 bytes.

FAQ

Does favicon add runtime gem dependencies?

No. favicon.gemspec scopes shoulda, rdoc, bundler, jeweler, and simplecov to development on modern RubyGems (specification_version = 4), while lib/favicon.rb uses core Ruby only.

Why does Favicon.find("github.com") return 404 on RubyGems 0.1.1?

Version 0.1.1 uses http://google.com/s2/favicons, and bare google.com returns 404 on that path. Switching the host to https://www.google.com restores the 301 redirect to gstatic.com.

Why normalize to the hostname instead of passing the full page URL?

Favicons belong to the site origin. Sending full URLs leaks path slugs and query tokens to a third-party endpoint while duplicating cache entries per page.

Takeaway

Small utility gems are easiest to adopt safely when you verify what is actually published on RubyGems against master and wrap external URL builders behind URI, IPAddr, and bounded server-side caching. That small boundary turns a fragile string concatenation into a deterministic, testable component.

Disclosure: This tutorial was researched and drafted with AI assistance. Every repository file, commit diff (v0.1.1 vs. master), RubyGems API record, live HTTP status code, and Minitest result was verified locally on Ruby 4.0.6.

When your application displays icons or link previews for user-submitted URLs, do you proxy and cache assets on the backend or resolve them directly from the origin HTML?

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.