A Rails app keeps private property-inspection photos in Active Storage; how would you put a CDN in front of them without exposing them to anyone holding a link?
answer
- proxy routes on the CDN host
- direct route with route_for and host
- public cache header on every proxy response
- expiring signed ids vs cache hit rate
- draw_routes false plus own controller
basics
~20 sThe built-in CDN recipe (proxy routes on a CDN host) caches files publicly for anyone holding a URL. For private photos, expire signed ids at some cost to hit rate, or disable the default routes and serve through an authorizing controller.
solid answer
~40 sThe guide's recipe uses proxy mode: a `direct :cdn_image` route builds `rails_service_blob_proxy` or `rails_blob_representation_proxy` URLs with `host: ENV["CDN_HOST"]`, and the proxy controller's `http_cache_forever public: true` lets the CDN cache each file for good. That suits public images, but the CDN then serves an inspection photo to anyone who has its URL, and Active Storage's controllers check no login. Options: shorten exposure by passing `expires_in:` to `signed_id` (the guide's route reads `ActiveStorage.urls_expire_in`), which changes URLs over time and lowers the hit rate; split public and private files so only public ones go through the CDN; or set `config.active_storage.draw_routes = false` and serve private photos from your own controller that authorizes the user and redirects to a short-lived `blob.url`, or streams with private cache headers. Purging the original does not clear copies the CDN already holds.
code
erb · 5 lines<%# public listing image through the CDN %>
<%= image_tag cdn_image_url(listing.cover.variant(resize_to_limit: [600, 400])) %>
<%# private inspection photo through the authorizing controller %>
<%= image_tag inspection_photo_path(@inspection, photo) %>go deeper
Recall that Active Storage URLs are public to anyone holding them and that a CDN caches proxied files.
Explain the guide's direct route that builds proxy URLs on a CDN host, and why the proxy's public cache header makes it suitable only for files that may be public.
Design delivery for private files: expiring signed ids versus hit rate, draw_routes false with an authorizing controller, and CDN invalidation on deletion.
Set the policy that classifies files by sensitivity and assigns each class a delivery path, link lifetime and incident response for leaked URLs.
## The built-in recipe Active Storage's guide describes how to cache attachments on a CDN: 1. **Use proxy mode** so files are served by your app, whose proxy controllers send `Cache-Control: public, immutable` with a 100-year `max-age` (`http_cache_forever public: true`) and no session cookie. 2. **Point URLs at the CDN host** with a custom `direct` route in `config/routes.rb` that calls `route_for(:rails_service_blob_proxy, ...)` for blobs and `route_for(:rails_blob_representation_proxy, ...)` for variants, passing `host: ENV["CDN_HOST"]`. 3. The CDN forwards a cache miss to the app, the app streams the file once, and the CDN keeps it. ```ruby # config/routes.rb direct :cdn_image do |model, options| expires_in = options.delete(:expires_in) { ActiveStorage.urls_expire_in } if model.respond_to?(:signed_id) route_for(:rails_service_blob_proxy, model.signed_id(expires_in: expires_in), model.filename, options.merge(host: ENV["CDN_HOST"])) else route_for(:rails_blob_representation_proxy, model.blob.signed_id(expires_in: expires_in), model.variation.key, model.blob.filename, options.merge(host: ENV["CDN_HOST"])) end end ``` Views then call `cdn_image_url(photo.variant(resize_to_limit: [800, 800]))`. ## Why that is wrong for private photos as it stands - **Every response is marked public.** The CDN, and any shared cache on the way, may store and serve the photo to anyone who requests the same URL. - **No authorization.** The guide states that all Active Storage controllers are publicly accessible by default; your `ApplicationController` login filter does not run there. - **Links live forever.** With `urls_expire_in` at its default `nil`, the signed id never expires, so a forwarded report email works for years. - **Deletion does not reach the edge.** Purging a blob removes the file from storage; copies the CDN cached stay until they are evicted or you invalidate them through the CDN's own tooling. ## Designs that work | Approach | How | Trade-off | |---|---|---| | Split public from private | public listing photos on a `public: true` service or proxied CDN URLs; inspection photos through redirect mode | simplest; private photos get no CDN benefit | | Expiring CDN URLs | set `config.active_storage.urls_expire_in` (or pass `expires_in:`) so signed ids in CDN URLs expire | URLs change as they are regenerated, so each new URL is a fresh cache miss; cached copies remain until evicted | | Authorizing controller | `config.active_storage.draw_routes = false`; your controller checks the user, then `redirect_to photo.url` (5-minute service URL) | full control; CDN caching only if your controller sets cacheable headers you trust | | CDN-level auth | the CDN validates its own signed URLs or cookies before forwarding | strongest edge caching; vendor-specific, outside Active Storage | Two details make the expiring-URL row workable. `signed_id(expires_in:)` embeds the expiry in the signed message, so URLs generated a minute apart differ; round the expiry to fixed windows (for example, regenerate links once per hour) if you want URLs to repeat and stay cacheable within a window. And remember that when an expired URL reaches the CDN, a cached copy may still be served; the expiry protects the origin, not the edge. ## An authorizing controller ```ruby # config/application.rb config.active_storage.draw_routes = false # config/routes.rb resources :inspections do resources :photos, only: :show end # app/controllers/photos_controller.rb class PhotosController < ApplicationController def show inspection = Current.user.inspections.find(params.expect(:inspection_id)) photo = inspection.photos.find(params.expect(:id)) redirect_to photo.url(expires_in: 1.minute), allow_other_host: true end end ``` With `draw_routes` off, the built-in redirect, proxy, representation and direct-upload routes disappear, so the only way to a file is through this check (re-add a direct-upload route to your own subclass if you use direct uploads). If you only want to move the built-in routes, `config.active_storage.routes_prefix` changes their mount point without adding any protection. ## A checklist for the review - Classify files: which are public marketing images, which are customer data. - Keep customer data off `public` cache headers unless the CDN enforces access itself. - Decide link lifetime explicitly instead of inheriting `urls_expire_in = nil`. - Plan deletion: purge in storage, invalidate at the CDN, and know how long cached copies may live. - Load-test the miss path, because proxy misses hold app threads.
- Does setting routes_prefix to something obscure protect private files?No. `config.active_storage.routes_prefix` only moves where the built-in routes are mounted; the controllers still serve any valid signed id without authorization, and the prefix appears in every generated URL anyway. Protection needs `draw_routes = false` with your own controller, or expiring signed ids.
- After purging a leaked photo, why might the CDN still serve it?Purging deletes the blob row and the file in storage, but the proxy response told the CDN it may cache the file publicly for 100 years. Until the CDN evicts it or you invalidate that URL through the CDN, requests are answered from the edge without reaching Rails.
- Active Storage's default controllers respect the ApplicationController login filter
- Proxy mode keeps CDN-cached files private because the URLs contain a signed id
- Purging the blob immediately removes the photo from every CDN edge
- Changing routes_prefix to an unguessable path secures private attachments
- Short-lived signed ids have no effect on the CDN's cache hit rate