refactor: reuse access token scope helper for direct uploads

This commit is contained in:
Shivam Mishra
2026-05-26 12:32:27 +05:30
parent 1987abf9e2
commit f778057b18
3 changed files with 31 additions and 0 deletions
@@ -1,5 +1,7 @@
class Api::V1::Accounts::Conversations::DirectUploadsController < ActiveStorage::DirectUploadsController
include EnsureCurrentAccountHelper
include AccessTokenAuthHelper
before_action :prevent_read_only_access_token!
before_action :current_account
before_action :conversation
@@ -36,4 +36,15 @@ module AccessTokenAuthHelper
def agent_bot_accessible?
BOT_ACCESSIBLE_ENDPOINTS.fetch(params[:controller], []).include?(params[:action])
end
# Blocks read-only access tokens from reaching write endpoints that live outside
# Api::BaseController (e.g. controllers inheriting from ActiveStorage). Resolves
# the token directly since these controllers skip the Api::BaseController chain.
def prevent_read_only_access_token!
ensure_access_token
return unless @access_token&.scope == 'read_only'
render json: { error: 'This access token is read-only and cannot perform write operations.' },
status: :forbidden
end
end
@@ -29,6 +29,24 @@ RSpec.describe '/api/v1/accounts/:account_id/conversations/:conversation_id/dire
json_response = response.parsed_body
expect(json_response['content_type']).to eq('image/png')
end
it 'rejects requests made with a read-only access token' do
read_only_token = agent.read_only_access_token
post api_v1_account_conversation_direct_uploads_path(account_id: account.id, conversation_id: conversation.display_id),
params: {
blob: {
filename: 'avatar.png',
byte_size: '1234',
checksum: 'dsjbsdhbfif3874823mnsdbf',
content_type: 'image/png'
}
},
headers: { api_access_token: read_only_token.token },
as: :json
expect(response).to have_http_status(:forbidden)
end
end
end
end