Skip to content

Commit 5c01c81

Browse files
Fix uncacheable 404s on /info/:gem_name causing bot-driven 503s (#6382)
* Don't provide a CSP none on API endpoints & cache compact index 404s in Fastly * Add todo to remove skip session in api controller * Update app/controllers/api/compact_index_controller.rb Co-authored-by: Jenny Shen <42748004+jenshenny@users.noreply.github.com> * Add `info/<gem_name>` surrogate key * Set action_name in the surrogate key --------- Co-authored-by: Jenny Shen <42748004+jenshenny@users.noreply.github.com>
1 parent e9651ff commit 5c01c81

3 files changed

Lines changed: 16 additions & 1 deletion

File tree

app/controllers/api/base_controller.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
# frozen_string_literal: true
22

33
class Api::BaseController < ApplicationController
4+
content_security_policy false
5+
46
skip_before_action :verify_authenticity_token
5-
after_action :skip_session
7+
after_action :skip_session # TODO: verify if this is still needed now that CSP is disabled for API controllers
68

79
rescue_from(Pundit::NotAuthorizedError) do |e|
810
render_forbidden(e.policy.error)

app/controllers/api/compact_index_controller.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ def info
2929

3030
private
3131

32+
def find_rubygem_by_name
33+
super
34+
return if @rubygem
35+
36+
cache_expiry_headers(fastly_expiry: 600)
37+
set_surrogate_key "#{action_name}/404 #{action_name}/#{gem_name}"
38+
end
39+
3240
def render_range(response_body)
3341
headers["ETag"] = %("#{Digest::MD5.hexdigest(response_body)}")
3442
digest = Digest::SHA256.base64digest(response_body)

test/integration/api/compact_index_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,11 @@ def digest(body)
210210

211211
assert_response :not_found
212212
assert_nil @response.headers["ETag"]
213+
assert_nil @response.headers["Set-Cookie"], "Expected no Set-Cookie on /info 404"
214+
assert_includes @response.headers["Cache-Control"], "public"
215+
assert_match(/max-age=60/, @response.headers["Cache-Control"])
216+
assert_match(/max-age=600/, @response.headers["Surrogate-Control"])
217+
assert_equal "info/404 info/donotexist", @response.headers["Surrogate-Key"]
213218
end
214219

215220
test "/info with gzip" do

0 commit comments

Comments
 (0)