From 3d0a10dbdd6d24941f22595072c2021f0c2dca10 Mon Sep 17 00:00:00 2001 From: Jacopo Date: Thu, 11 Sep 2025 12:24:39 +0200 Subject: [PATCH] Security: Fix user impersonation via custom bot token If bot_key has no right-hand side (ex: 1-), bot_token will be nil, and the query will match a User record if bot_id matches a valid ID. Fix it relying on `active_bots` instead. --- app/models/user/bot.rb | 2 +- test/controllers/messages/by_bots_controller_test.rb | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/models/user/bot.rb b/app/models/user/bot.rb index 5c554a9..2ec0037 100644 --- a/app/models/user/bot.rb +++ b/app/models/user/bot.rb @@ -19,7 +19,7 @@ module User::Bot def authenticate_bot(bot_key) bot_id, bot_token = bot_key.split("-") - active.find_by(id: bot_id, bot_token: bot_token) + active_bots.find_by(id: bot_id, bot_token: bot_token) end def generate_bot_token diff --git a/test/controllers/messages/by_bots_controller_test.rb b/test/controllers/messages/by_bots_controller_test.rb index 074f9f8..89f81da 100644 --- a/test/controllers/messages/by_bots_controller_test.rb +++ b/test/controllers/messages/by_bots_controller_test.rb @@ -40,6 +40,17 @@ class Messages::ByBotsControlleTest < ActionDispatch::IntegrationTest end end + test "create can't be abused to post messages as any user" do + user = users(:kevin) + bot_key = "#{user.id}-" + + assert_no_difference -> { Message.count } do + post room_bot_messages_url(rooms(:bender_and_kevin), bot_key), params: "Hello 👋!" + end + + assert_response :redirect + end + test "denied index" do get room_messages_url(@room, bot_key: users(:bender).bot_key, format: :json) assert_response :forbidden