Files
once-campfire/app/controllers/messages/by_bots_controller.rb
T
John-Mason Shackelford 5340f3da01 fix: Ensure bot can only read messages from rooms it is a member of
Added explicit RecordNotFound handling to return 404 when a bot tries to
read messages from a room it's not a member of. This matches the security
model used by the create action.

Added tests to verify:
- Bot gets 404 when trying to read from room it's not a member of
- Bot can successfully read from room it IS a member of

Co-authored-by: openhands <openhands@all-hands.dev>
2026-04-08 13:56:02 -04:00

69 lines
1.5 KiB
Ruby

class Messages::ByBotsController < MessagesController
allow_bot_access only: %i[ index create ]
def index
set_room
@messages = find_paged_messages
render json: messages_as_json(@messages)
rescue ActiveRecord::RecordNotFound
head :not_found
end
def create
super
head :created, location: message_url(@message)
end
private
def messages_as_json(messages)
{
room: {
id: @room.id,
name: @room.name
},
messages: messages.map { |m| message_as_json(m) },
pagination: pagination_info(messages)
}
end
def message_as_json(message)
{
id: message.id,
body: {
plain: message.plain_text_body,
html: message.body&.body&.to_s
},
created_at: message.created_at.iso8601,
creator: {
id: message.creator.id,
name: message.creator.name,
is_bot: message.creator.role == "bot"
}
}
end
def pagination_info(messages)
return {} if messages.empty?
{
oldest_id: messages.last.id,
newest_id: messages.first.id,
has_more: messages.size == Message::PAGE_SIZE
}
end
def message_params
if params[:attachment]
params.permit(:attachment)
else
reading(request.body) { |body| { body: body } }
end
end
def reading(io)
io.rewind
yield io.read.force_encoding("UTF-8")
ensure
io.rewind
end
end