Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions app/controllers/static_pages_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
11 changes: 6 additions & 5 deletions config/environments/production.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion config/environments/test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions config/initializers/cache_control_fix.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions config/initializers/canonical_trailing_slash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions config/initializers/fingerprinted_asset_cache.rb
Original file line number Diff line number Diff line change
@@ -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
)
3 changes: 3 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 <link> 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',
Expand Down
1 change: 1 addition & 0 deletions lib/asset_staleness_middleware.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
59 changes: 59 additions & 0 deletions lib/fingerprinted_asset_cache_middleware.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# 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

# 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'
# 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 fingerprinted && CACHEABLE_STATUSES.include?(status)
headers['cache-control'] = IMMUTABLE
end
# Return the original array to avoid unnecessary object creation.
result
end
end
Empty file removed public/favicon.ico
Empty file.
25 changes: 25 additions & 0 deletions test/integration/cdn_caching_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
76 changes: 76 additions & 0 deletions test/lib/fingerprinted_asset_cache_middleware_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# 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

# 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'],
'immutable'
)
end
end
Loading