From 70083a92eb4ba97984c0efe38223010de3dfdbd1 Mon Sep 17 00:00:00 2001 From: "David A. Wheeler" Date: Fri, 13 Nov 2026 11:37:43 -0500 Subject: [PATCH 1/3] Mark only fingerprinted static files as immutable We previously served every file in public/ with a 1-year "immutable" Cache-Control. That's correct for fingerprinted assets, whose URL changes whenever their content does. However, it is *not* correct for files with fixed URLs such as 404.html, 422.html, 500.html, and the Google verifier. Once cached, fixes to those can't reach browsers or the CDN. It also hid a bug: public/favicon.ico was an empty file left over from the 2015 Rails scaffold, so anything requesting /favicon.ico directly got zero bytes, cached as immutable for a year. To fix this and make the mistake hard to repeat: * public/ files now get a 1-day default (FingerprintedAssetCacheMiddleware::DEFAULT_HEADERS), shared by the production and test configs. * New middleware wrapping ActionDispatch::Static upgrades a response to immutable only if its URL has a Sprockets SHA-256 fingerprint. A new file can't get the long lifetime unless its URL changes with its content. * /favicon.ico now 301-redirects to the fingerprinted icon from app/assets/images/favicon.ico. The redirect is cached for 1 day, the icon for a year. We removed the empty public/favicon.ico. * StaticPagesController lists its locale-free actions once. Tests cover the fingerprint pattern (including near misses), the middleware, real static responses, and the favicon redirect. After deploying, purge Fastly; it's caching the empty /favicon.ico and the error pages with a 1-year lifetime. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: David A. Wheeler --- app/controllers/static_pages_controller.rb | 21 +++++-- config/environments/production.rb | 11 ++-- config/environments/test.rb | 4 +- .../initializers/fingerprinted_asset_cache.rb | 11 ++++ config/routes.rb | 3 + lib/fingerprinted_asset_cache_middleware.rb | 55 +++++++++++++++++ public/favicon.ico | 0 test/integration/cdn_caching_test.rb | 25 ++++++++ ...ngerprinted_asset_cache_middleware_test.rb | 60 +++++++++++++++++++ 9 files changed, 179 insertions(+), 11 deletions(-) create mode 100644 config/initializers/fingerprinted_asset_cache.rb create mode 100644 lib/fingerprinted_asset_cache_middleware.rb delete mode 100644 public/favicon.ico create mode 100644 test/lib/fingerprinted_asset_cache_middleware_test.rb diff --git a/app/controllers/static_pages_controller.rb b/app/controllers/static_pages_controller.rb index d8a576516..b08fc5f69 100644 --- a/app/controllers/static_pages_controller.rb +++ b/app/controllers/static_pages_controller.rb @@ -9,21 +9,23 @@ class StaticPagesController < ApplicationController include SessionsHelper - # If a page is *invariant* regardless of locale, don't bother + # Pages that are *invariant* regardless of locale and visitor. + LOCALE_FREE_PAGES = %i[robots security_txt favicon].freeze + + # If a page is invariant regardless of locale, don't bother # to figure out what the locale is. - skip_before_action :set_locale_to_best_available, - only: %i[robots security_txt] + skip_before_action :set_locale_to_best_available, only: LOCALE_FREE_PAGES # There's no value in redirecting these pages to a locale, # so do *not* redirect them to a URL based on locale. skip_before_action :redir_missing_locale, - only: %i[robots security_txt error_404 google_verifier] + only: [*LOCALE_FREE_PAGES, :error_404, :google_verifier] # Omit session cookie. # We *must not* set error messages in the flash area, # because flashes are stored in the session. before_action :omit_session_cookie, - only: %i[robots security_txt google_verifier] + only: [*LOCALE_FREE_PAGES, :google_verifier] # Cache "unchanging" pages on the CDN for anonymous users -- pages whose # output does not change until the next deploy. These actions render @@ -92,4 +94,13 @@ def security_txt respond_to :text expires_in 7.days, public: true end + + # Browsers and bots request /favicon.ico directly. Redirect to the + # fingerprinted asset, which can be cached as immutable; the redirect + # itself must stay short-lived, since the fingerprint changes with the icon. + # @return [void] + def favicon + expires_in 1.day, public: true + redirect_to helpers.asset_path('favicon.ico'), status: :moved_permanently + end end diff --git a/config/environments/production.rb b/config/environments/production.rb index b8e80cc4f..1a540cd0d 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -4,6 +4,8 @@ # OpenSSF Best Practices badge contributors # SPDX-License-Identifier: MIT +require_relative '../../lib/fingerprinted_asset_cache_middleware' + # rubocop:disable-next Metrics/BlockLength Rails.application.configure do # Settings specified here will take precedence over those in @@ -203,12 +205,11 @@ # "config.serve_static_assets = true". However, this has since been # renamed to "config.serve_static_files", which we already conditionally set. - # Cache static content. Cache for a long time; the asset cache is + # Cache static content from public/. This default applies to every + # file there, so it must NOT be "immutable"; middleware upgrades only + # fingerprinted asset URLs. See lib/fingerprinted_asset_cache_middleware.rb. config.public_file_server.headers = - { - 'Cache-Control' => - 'public, s-maxage=31536000, max-age=31536000, immutable' - } + FingerprintedAssetCacheMiddleware::DEFAULT_HEADERS # Enable Rack's built-in compression mechanism; this is important for people # with slow network connections diff --git a/config/environments/test.rb b/config/environments/test.rb index 31c3a4301..0a74b0a9b 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -4,6 +4,8 @@ # OpenSSF Best Practices badge contributors # SPDX-License-Identifier: MIT +require_relative '../../lib/fingerprinted_asset_cache_middleware' + # rubocop:disable-next Metrics/BlockLength Rails.application.configure do # Settings specified here will take precedence over those in @@ -23,7 +25,7 @@ # Configure static file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = - { 'Cache-Control' => 'public, max-age=3600' } + FingerprintedAssetCacheMiddleware::DEFAULT_HEADERS # Show full error reports and disable caching. config.consider_all_requests_local = true diff --git a/config/initializers/fingerprinted_asset_cache.rb b/config/initializers/fingerprinted_asset_cache.rb new file mode 100644 index 000000000..121093a58 --- /dev/null +++ b/config/initializers/fingerprinted_asset_cache.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +# Copyright the OpenSSF Best Practices badge contributors +# SPDX-License-Identifier: MIT + +require_relative '../../lib/fingerprinted_asset_cache_middleware' + +# Wrap the static file server so we see (and can adjust) its responses. +Rails.application.config.middleware.insert_before( + ActionDispatch::Static, FingerprintedAssetCacheMiddleware +) diff --git a/config/routes.rb b/config/routes.rb index 7b83a0acb..89767b87e 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -108,6 +108,9 @@ get '/.well-known/security.txt' => 'static_pages#security_txt', defaults: FORMAT_TEXT, as: :security_txt + # Bots and browsers request /favicon.ico regardless of our tags. + get '/favicon.ico' => 'static_pages#favicon', as: :favicon + # These routes never use locales, so that the cache is shared across locales. get '/project_stats/total_projects.json', to: 'project_stats#total_projects', as: 'total_projects_project_stats', diff --git a/lib/fingerprinted_asset_cache_middleware.rb b/lib/fingerprinted_asset_cache_middleware.rb new file mode 100644 index 000000000..f09daec6f --- /dev/null +++ b/lib/fingerprinted_asset_cache_middleware.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +# Copyright the OpenSSF Best Practices badge contributors +# SPDX-License-Identifier: MIT + +# Rack middleware that marks a static file "immutable" (cacheable for a +# year by browsers and the CDN) only if its URL is fingerprinted, i.e., +# includes a cryptographic hash derived from its content. Then any content +# change produces a new URL, so a cached copy can never be stale. +# +# Everything else in public/ (e.g., /404.html) keeps the shorter DEFAULT +# set via config.public_file_server.headers. Never put "immutable" there: +# it applies to *every* file in public/, and we once served security.txt +# and an empty /favicon.ico that way, so fixes couldn't reach caches. +# Deriving immutability from the URL means a new file can't get it by +# accident. +class FingerprintedAssetCacheMiddleware + # Cache-Control for public/ files whose URL doesn't change with content. + # Use as the value of config.public_file_server.headers. + DEFAULT_HEADERS = { 'cache-control' => 'public, max-age=86400' }.freeze + + # 31536000 seconds = 365 days, the conventional "forever". + IMMUTABLE = 'public, s-maxage=31536000, max-age=31536000, immutable' + + # Sprockets fingerprints precompiled assets as NAME-SHA256HEX.EXT, + # e.g., /assets/favicon-f098...588f.ico (64 lowercase hex digits). + # That SHA-256 covers the content plus pipeline settings (such as + # config.assets.version), so it isn't the file's plain hash, but + # any content change still changes it. + FINGERPRINTED = %r{\A/assets/(?:[^/]+/)*[^/]+-[0-9a-f]{64}\.[^/]+\z} + + # Statuses the static file server returns for a served file. + CACHEABLE_STATUSES = [200, 206, 304].freeze + + # @param path [String] the request path (no query string) + # @return [Boolean] true iff the path is a fingerprinted asset URL + def self.fingerprinted?(path) + FINGERPRINTED.match?(path) + end + + def initialize(app) + @app = app + end + + def call(env) + result = @app.call(env) + status, headers, _body = result + if CACHEABLE_STATUSES.include?(status) && + self.class.fingerprinted?(env['PATH_INFO']) + headers['cache-control'] = IMMUTABLE + end + # Return the original array to avoid unnecessary object creation. + result + end +end diff --git a/public/favicon.ico b/public/favicon.ico deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/integration/cdn_caching_test.rb b/test/integration/cdn_caching_test.rb index 5a05f3786..ca0db1a2e 100644 --- a/test/integration/cdn_caching_test.rb +++ b/test/integration/cdn_caching_test.rb @@ -317,4 +317,29 @@ def unchanging_paths(locale) assert_equal 'private, no-store', response.headers['Cache-Control'] assert_nil response.headers['Surrogate-Control'] end + + # Only a URL that includes a hash of its content may be cached as immutable; + # other public/ files get the short default. These go through the real + # static file server, so they'd catch the middleware being dropped. + test 'static files are immutable only when fingerprinted' do + get ActionController::Base.helpers.asset_path('favicon.ico') + assert_response :success + assert_equal FingerprintedAssetCacheMiddleware::IMMUTABLE, + response.headers['Cache-Control'] + + get '/404.html' + assert_response :success + assert_equal FingerprintedAssetCacheMiddleware::DEFAULT_HEADERS['cache-control'], + response.headers['Cache-Control'] + end + + # /favicon.ico redirects (briefly cached) to the immutable fingerprinted icon. + test '/favicon.ico redirects to the fingerprinted icon' do + get '/favicon.ico' + assert_response :moved_permanently + assert_redirected_to ActionController::Base.helpers.asset_path('favicon.ico') + # 86400 seconds = 1 day. + assert_equal 'max-age=86400, public', response.headers['Cache-Control'] + assert_nil response.headers['Set-Cookie'] + end end diff --git a/test/lib/fingerprinted_asset_cache_middleware_test.rb b/test/lib/fingerprinted_asset_cache_middleware_test.rb new file mode 100644 index 000000000..cc8e7d817 --- /dev/null +++ b/test/lib/fingerprinted_asset_cache_middleware_test.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +# Copyright the OpenSSF Best Practices badge contributors +# SPDX-License-Identifier: MIT + +require 'test_helper' + +class FingerprintedAssetCacheMiddlewareTest < ActiveSupport::TestCase + HASH = 'f098b7364af46f181ea6b6d164e21494cbdb923eb9707491086ed622020f588f' + + def cache_control_for(path, status: 200) + app = ->(_env) { [status, { 'cache-control' => 'unchanged' }, []] } + middleware = FingerprintedAssetCacheMiddleware.new(app) + middleware.call('PATH_INFO' => path)[1]['cache-control'] + end + + test 'fingerprinted asset paths are recognized' do + [ + "/assets/favicon-#{HASH}.ico", + "/assets/application-#{HASH}.css", + "/assets/project-logos/linux-#{HASH}.png", + "/assets/Thumbs_up-#{HASH}.svg.gz" + ].each do |path| + assert FingerprintedAssetCacheMiddleware.fingerprinted?(path), path + end + end + + test 'non-fingerprinted paths are not recognized' do + [ + '/favicon.ico', + '/404.html', + '/.well-known/security.txt', + '/assets/sources', + '/assets/project-logos-originals/NOTES', + "/assets/favicon-#{HASH[0..-2]}.ico", # Too short + "/assets/favicon-#{HASH.upcase}.ico", # Sprockets uses lowercase + "/assets/favicon-#{HASH}", # No extension + "/en/projects/favicon-#{HASH}.ico", # Not under /assets/ + "/assets/favicon-#{HASH}.ico/../../secret" + ].each do |path| + assert_not FingerprintedAssetCacheMiddleware.fingerprinted?(path), path + end + end + + test 'only served fingerprinted files become immutable' do + immutable = FingerprintedAssetCacheMiddleware::IMMUTABLE + path = "/assets/favicon-#{HASH}.ico" + assert_equal immutable, cache_control_for(path) + assert_equal immutable, cache_control_for(path, status: 304) + assert_equal 'unchanged', cache_control_for(path, status: 404) + assert_equal 'unchanged', cache_control_for('/404.html') + end + + test 'the default for public/ files is never immutable' do + assert_not_includes( + FingerprintedAssetCacheMiddleware::DEFAULT_HEADERS['cache-control'], + 'immutable' + ) + end +end From e08d13c4adb39094eb14967358b407ccaa0df70a Mon Sep 17 00:00:00 2001 From: "David A. Wheeler" Date: Fri, 13 Nov 2026 13:18:21 -0500 Subject: [PATCH 2/3] Check the asset path before calling the app CI failed the test CdnCachingTest#test_static_files_are_immutable_only_when_fingerprinted: the fingerprinted favicon got Sprockets' "public, max-age=31536000, immutable" instead of our IMMUTABLE value. CI runs the tests without precompiled assets, so Sprockets' server, mounted at /assets, serves them. That mount strips "/assets" from env['PATH_INFO'], and FingerprintedAssetCacheMiddleware read PATH_INFO *after* calling the app, so the path no longer matched the fingerprint pattern. Locally the test passed only because public/assets existed, so ActionDispatch::Static served the file without touching PATH_INFO. We now check the path before calling the app. A new unit test uses an app that rewrites PATH_INFO, so this fails regardless of whether assets are precompiled. I also ran the full suite both with and without public/assets. That should prevent future similar problems. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: David A. Wheeler --- lib/fingerprinted_asset_cache_middleware.rb | 7 +++++-- .../fingerprinted_asset_cache_middleware_test.rb | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lib/fingerprinted_asset_cache_middleware.rb b/lib/fingerprinted_asset_cache_middleware.rb index f09daec6f..893acc885 100644 --- a/lib/fingerprinted_asset_cache_middleware.rb +++ b/lib/fingerprinted_asset_cache_middleware.rb @@ -43,10 +43,13 @@ def initialize(app) end def call(env) + # Check the path *before* calling the app: a mounted app can change + # PATH_INFO. E.g., when assets aren't precompiled (as in CI), Sprockets' + # server mounted at /assets serves them and strips that prefix. + fingerprinted = self.class.fingerprinted?(env['PATH_INFO']) result = @app.call(env) status, headers, _body = result - if CACHEABLE_STATUSES.include?(status) && - self.class.fingerprinted?(env['PATH_INFO']) + if fingerprinted && CACHEABLE_STATUSES.include?(status) headers['cache-control'] = IMMUTABLE end # Return the original array to avoid unnecessary object creation. diff --git a/test/lib/fingerprinted_asset_cache_middleware_test.rb b/test/lib/fingerprinted_asset_cache_middleware_test.rb index cc8e7d817..db8208523 100644 --- a/test/lib/fingerprinted_asset_cache_middleware_test.rb +++ b/test/lib/fingerprinted_asset_cache_middleware_test.rb @@ -51,6 +51,22 @@ def cache_control_for(path, status: 200) assert_equal 'unchanged', cache_control_for('/404.html') end + # Regression test: a mounted app (e.g., Sprockets' /assets server, used + # when assets aren't precompiled) strips its mount prefix from PATH_INFO. + # The middleware must decide from the path as the request arrived. + test 'uses the request path even if the app changes PATH_INFO' do + app = + lambda do |env| + env['PATH_INFO'] = env['PATH_INFO'].delete_prefix('/assets') + [200, { 'cache-control' => 'unchanged' }, []] + end + middleware = FingerprintedAssetCacheMiddleware.new(app) + _status, headers, _body = + middleware.call('PATH_INFO' => "/assets/favicon-#{HASH}.ico") + assert_equal FingerprintedAssetCacheMiddleware::IMMUTABLE, + headers['cache-control'] + end + test 'the default for public/ files is never immutable' do assert_not_includes( FingerprintedAssetCacheMiddleware::DEFAULT_HEADERS['cache-control'], From 0bcd0b89622a8c20ef42f0df70d92ca2f0a18cf3 Mon Sep 17 00:00:00 2001 From: "David A. Wheeler" Date: Fri, 13 Nov 2026 13:31:55 -0500 Subject: [PATCH 3/3] Add comments, Rack env != process env Add comments to clarify when we use *Rack* env vs. *process* env. We're using standard conventions, but those standard conventions can be a little confusing; better to make it clear what we're doing. Signed-off-by: David A. Wheeler --- config/initializers/cache_control_fix.rb | 1 + config/initializers/canonical_trailing_slash.rb | 1 + lib/asset_staleness_middleware.rb | 1 + lib/fingerprinted_asset_cache_middleware.rb | 1 + 4 files changed, 4 insertions(+) diff --git a/config/initializers/cache_control_fix.rb b/config/initializers/cache_control_fix.rb index c1c0b8927..342aa0824 100644 --- a/config/initializers/cache_control_fix.rb +++ b/config/initializers/cache_control_fix.rb @@ -22,6 +22,7 @@ def initialize(app) @app = app end + # env is this request's Rack environment, not the process's ENV. def call(env) result = @app.call(env) _status, headers, _body = result diff --git a/config/initializers/canonical_trailing_slash.rb b/config/initializers/canonical_trailing_slash.rb index 5fb59fbe2..27afd0567 100644 --- a/config/initializers/canonical_trailing_slash.rb +++ b/config/initializers/canonical_trailing_slash.rb @@ -18,6 +18,7 @@ def initialize(app) @app = app end + # env is this request's Rack environment, not the process's ENV. def call(env) request = Rack::Request.new env if %r{^/(.*)/$}.match?(request.path_info) diff --git a/lib/asset_staleness_middleware.rb b/lib/asset_staleness_middleware.rb index fa2d6caf1..e00df3c93 100644 --- a/lib/asset_staleness_middleware.rb +++ b/lib/asset_staleness_middleware.rb @@ -14,6 +14,7 @@ def initialize(app) @checked = false end + # env is this request's Rack environment, not the process's ENV. def call(env) # Only check once per server lifetime unless @checked diff --git a/lib/fingerprinted_asset_cache_middleware.rb b/lib/fingerprinted_asset_cache_middleware.rb index 893acc885..6069134f7 100644 --- a/lib/fingerprinted_asset_cache_middleware.rb +++ b/lib/fingerprinted_asset_cache_middleware.rb @@ -42,6 +42,7 @@ def initialize(app) @app = app end + # env is this request's Rack environment, not the process's ENV. def call(env) # Check the path *before* calling the app: a mounted app can change # PATH_INFO. E.g., when assets aren't precompiled (as in CI), Sprockets'