Files
fizzy/lib/rails_ext/active_storage_authorization.rb
T
Mike Dalessio 628571fc79 Don't set public Cache-Control on proxied non-public blobs
Rails' ActiveStorage proxy controllers hardcode `http_cache_forever public: true`,
which sets `Cache-Control: public, immutable`. For non-public blobs behind auth,
this allows CDN caching that serves responses without authorization checks.

Override `http_cache_forever` in the Authorize concern to downgrade `public` to
`false` for non-public blobs.

See https://github.com/basecamp/fizzy/pull/2251 for context
2026-03-26 14:58:40 -04:00

54 lines
1.5 KiB
Ruby

ActiveSupport.on_load :active_storage_blob do
def accessible_to?(user)
attachments.includes(:record).any? { |attachment| attachment.accessible_to?(user) } || attachments.none?
end
def publicly_accessible?
attachments.includes(:record).any? { |attachment| attachment.publicly_accessible? }
end
end
ActiveSupport.on_load :active_storage_attachment do
def accessible_to?(user)
record.try(:accessible_to?, user)
end
def publicly_accessible?
record.try(:publicly_accessible?)
end
end
Rails.application.config.to_prepare do
module ActiveStorage::Authorize
extend ActiveSupport::Concern
include Authentication
included do
# Ensure require_authentication runs after set_blob.
skip_before_action :require_authentication
before_action :require_authentication, :ensure_accessible, unless: :publicly_accessible_blob?
end
private
def publicly_accessible_blob?
@blob.publicly_accessible?
end
def ensure_accessible
unless @blob.accessible_to?(Current.user)
head :forbidden
end
end
def http_cache_forever(public: false, &block)
super(public: public && publicly_accessible_blob?, &block)
end
end
ActiveStorage::Blobs::RedirectController.include ActiveStorage::Authorize
ActiveStorage::Blobs::ProxyController.include ActiveStorage::Authorize
ActiveStorage::Representations::RedirectController.include ActiveStorage::Authorize
ActiveStorage::Representations::ProxyController.include ActiveStorage::Authorize
end