Require authorization for direct uploads

Respond with 403 to JSON requests that are unauthorized, instead of
redirecting.
This commit is contained in:
Rosa Gutierrez
2025-12-22 21:05:55 +01:00
committed by Rosa Gutierrez
parent 43dd149ff2
commit 3fcf5a9d08
3 changed files with 27 additions and 7 deletions
+6 -1
View File
@@ -26,7 +26,12 @@ module Authorization
end
def ensure_can_access_account
redirect_to session_menu_path(script_name: nil) if Current.user.blank? || !Current.user.active?
if Current.user.blank? || !Current.user.active?
respond_to do |format|
format.html { redirect_to session_menu_path(script_name: nil) }
format.json { head :forbidden }
end
end
end
def redirect_existing_user
+1
View File
@@ -40,6 +40,7 @@ module ActiveStorageDirectUploadsControllerExtensions
included do
include Authentication
include Authorization
skip_forgery_protection if: :authenticate_by_bearer_token
end
end
@@ -54,19 +54,33 @@ class ActiveStorage::DirectUploadsControllerTest < ActionDispatch::IntegrationTe
test "create unauthenticated" do
post rails_direct_uploads_path,
params: @blob_params.merge(authenticity_token: csrf_token),
params: @blob_params,
as: :json
assert_response :redirect
end
test "create in another account is forbidden" do
sign_in_as :david
post rails_direct_uploads_path(script_name: "/#{ActiveRecord::FixtureSet.identify("initech")}"),
params: @blob_params,
as: :json
assert_response :forbidden
end
test "create with valid access token in another account is forbidden" do
post rails_direct_uploads_path(script_name: "/#{ActiveRecord::FixtureSet.identify("initech")}"),
params: @blob_params,
headers: bearer_token_header(identity_access_tokens(:davids_api_token).token),
as: :json
assert_response :forbidden
end
private
def bearer_token_header(token)
{ "Authorization" => "Bearer #{token}" }
end
def csrf_token
get new_session_url
response.body[/name="csrf-token" content="([^"]+)"/, 1]
end
end