Skip to content

A platform for community discussion. Free, open, simple.

FIX: Validate the `ai_agent_id` topic custom field on topic creation (#42275)

Rafael dos Santos Silva7df32723f1c8
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 8d82fa886b3..c6fbc0d58d2 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -424,6 +424,9 @@ en:
logging_subject: "Spam detection"
ai_bot:
+ errors:
+ invalid_agent_id: "The specified AI agent does not exist or you do not have access to it"
+ cannot_send_pm_to_agent: "You cannot send personal messages to this AI agent"
reply_error: "Sorry, it looks like our system encountered an unexpected issue while trying to reply.\n\n[details='Error details']\n%{details}\n[/details]"
default_pm_prefix: "[Untitled AI bot PM]"
thinking: "Thinking"
diff --git a/plugins/discourse-ai/lib/ai_bot.rb b/plugins/discourse-ai/lib/ai_bot.rb
index ad88c3e4247..baa9456ef83 100644
--- a/plugins/discourse-ai/lib/ai_bot.rb
+++ b/plugins/discourse-ai/lib/ai_bot.rb
@@ -7,6 +7,8 @@ module DiscourseAi
POST_AI_LLM_NAME_FIELD = "ai_llm_name"
POST_AI_LLM_MODEL_ID_FIELD = "ai_llm_model_id"
POST_AI_AGENT_ID_FIELD = "ai_agent_id"
+ TOPIC_AI_AGENT_ID_FIELD = "ai_agent_id"
+ TOPIC_AI_AGENT_ID_MAX_LENGTH = 20
PERSONAL_MESSAGE_CONTEXT = "discourse_ai.ai_bot_personal_message"
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
index 254186af319..78ce7bfdbe7 100644
--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb
+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
@@ -283,6 +283,15 @@ module DiscourseAi
end
plugin.register_editable_topic_custom_field(:ai_agent_id)
+ plugin.register_topic_custom_field_type(
+ :ai_agent_id,
+ :string,
+ max_length: TOPIC_AI_AGENT_ID_MAX_LENGTH,
+ )
+
+ plugin.on(:after_validate_topic) do |topic, topic_creator|
+ DiscourseAi::AiBot::TopicAgentValidator.validate(topic, topic_creator)
+ end
plugin.add_api_key_scope(
:ai,
diff --git a/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb b/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb
new file mode 100644
index 00000000000..0301829567a
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_bot/topic_agent_validator.rb
@@ -0,0 +1,87 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module AiBot
+ class TopicAgentValidator
+ def self.validate(topic, topic_creator)
+ new(topic, topic_creator).validate
+ end
+
+ def initialize(topic, topic_creator)
+ @topic = topic
+ @user = topic_creator.user
+ @opts = topic_creator.opts
+ end
+
+ def validate
+ validate_agent_field
+ validate_agent_recipients if @topic.private_message?
+ end
+
+ private
+
+ def validate_agent_field
+ # in PostCreator opts, topic custom fields live under topic_opts and
+ # are merged over the top-level (post) custom_fields at create time
+ fields = @opts.dig(:topic_opts, :custom_fields) || @opts[:custom_fields]
+ raw_agent_id = fields && (fields[TOPIC_AI_AGENT_ID_FIELD] || fields[:ai_agent_id])
+ return if raw_agent_id.blank?
+
+ raw_agent_id = raw_agent_id.to_s
+
+ if raw_agent_id.bytesize > TOPIC_AI_AGENT_ID_MAX_LENGTH
+ @topic.errors.add(
+ :base,
+ I18n.t(
+ "custom_fields.validations.max_value_length",
+ max_value_length: TOPIC_AI_AGENT_ID_MAX_LENGTH,
+ ),
+ )
+ return
+ end
+
+ agent = accessible_agent(raw_agent_id.to_i) if raw_agent_id.match?(/\A-?\d+\z/)
+
+ if agent.blank? || (@topic.private_message? && !agent.allow_personal_messages)
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
+ end
+ end
+
+ # an agent's dedicated user can be targeted directly, bypassing the
+ # custom field entirely, so the agent's PM policy must also be enforced
+ # from the recipient side
+ def validate_agent_recipients
+ targeted_agents.each do |targeted_agent|
+ agent = accessible_agent(targeted_agent.id)
+
+ if agent.blank? || !agent.allow_personal_messages
+ @topic.errors.add(:base, I18n.t("discourse_ai.ai_bot.errors.cannot_send_pm_to_agent"))
+ break
+ end
+ end
+ end
+
+ def targeted_agents
+ usernames = @opts[:target_usernames]
+ user_ids = @opts[:target_user_ids]
+
+ if usernames.present?
+ usernames = usernames.split(",") if usernames.is_a?(String)
+ AiAgent.joins(:user).where(
+ users: {
+ username_lower: usernames.map { |username| username.to_s.strip.downcase },
+ },
+ )
+ elsif user_ids.present?
+ AiAgent.where(user_id: user_ids)
+ else
+ AiAgent.none
+ end
+ end
+
+ def accessible_agent(id)
+ DiscourseAi::Agents::Agent.find_by(user: @user, id: id)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
new file mode 100644
index 00000000000..54504eb48ea
--- /dev/null
+++ b/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
@@ -0,0 +1,203 @@
+# frozen_string_literal: true
+
+RSpec.describe "AI agent topic custom field" do
+ fab!(:current_user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:llm_model) { Fabricate(:llm_model, name: "gpt-4") }
+ fab!(:agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ )
+ end
+
+ let(:bot_user) { llm_model.reload.user }
+
+ before do
+ enable_current_plugin
+ toggle_enabled_bots(bots: [llm_model])
+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]
+ SiteSetting.personal_message_enabled_groups = Group::AUTO_GROUPS[:trust_level_0]
+ sign_in(current_user)
+ end
+
+ def create_pm(ai_agent_id)
+ post "/posts.json",
+ params: {
+ raw: "Hello there, this is a personal message for a bot.",
+ title: "Bot personal message",
+ archetype: Archetype.private_message,
+ target_recipients: bot_user.username,
+ topic_custom_fields: {
+ ai_agent_id: ai_agent_id,
+ },
+ }
+ end
+
+ it "stores an agent the user is allowed to use in personal messages" do
+ create_pm(agent.id)
+
+ expect(response.status).to eq(200)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.custom_fields["ai_agent_id"]).to eq(agent.id.to_s)
+ end
+
+ it "stores a built-in system agent, which has a negative id" do
+ system_agent =
+ AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
+ system_agent.update!(
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ enabled: true,
+ )
+
+ create_pm(system_agent.id)
+
+ expect(response.status).to eq(200)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.custom_fields["ai_agent_id"]).to eq(system_agent.id.to_s)
+ end
+
+ it "rejects an agent that is not enabled for personal messages" do
+ agent.update!(allow_personal_messages: false)
+
+ create_pm(agent.id)
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"),
+ )
+ expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
+ end
+
+ it "rejects an agent the user is not in the allowed groups for" do
+ agent.update!(allowed_group_ids: [Group::AUTO_GROUPS[:staff]])
+
+ create_pm(agent.id)
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"),
+ )
+ expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
+ end
+
+ it "rejects a value that does not identify an agent" do
+ create_pm("not-an-agent")
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"),
+ )
+ expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
+ end
+
+ it "rejects an oversized value before it reaches the database" do
+ create_pm("a" * 1_000_000)
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("custom_fields.validations.max_value_length", max_value_length: 20),
+ )
+ expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
+ end
+
+ it "validates the topic agent id even when post custom fields are also supplied" do
+ agent.update!(allow_personal_messages: false)
+
+ creator =
+ PostCreator.new(
+ current_user,
+ title: "Bot personal message",
+ raw: "Hello there, this is a personal message for a bot.",
+ archetype: Archetype.private_message,
+ target_usernames: bot_user.username,
+ custom_fields: {
+ foo: "bar",
+ },
+ topic_opts: {
+ custom_fields: {
+ ai_agent_id: agent.id,
+ },
+ },
+ )
+
+ expect(creator.create).to be_nil
+ expect(creator.errors[:base]).to include(I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
+ expect(TopicCustomField.where(name: "ai_agent_id")).to be_empty
+ end
+
+ it "rejects an unusable agent supplied through the deprecated meta_data param" do
+ agent.update!(allow_personal_messages: false)
+
+ post "/posts.json",
+ params: {
+ raw: "Hello there, this is a personal message for a bot.",
+ title: "Bot personal message",
+ archetype: Archetype.private_message,
+ target_recipients: bot_user.username,
+ meta_data: {
+ ai_agent_id: agent.id,
+ },
+ }
+
+ expect(response.status).to eq(422)
+ expect(TopicCustomField.where(name: "ai_agent_id").count).to eq(0)
+ end
+
+ context "when the PM directly targets an agent's dedicated user" do
+ before { agent.create_user! }
+
+ def create_pm_to_agent_user
+ post "/posts.json",
+ params: {
+ raw: "Hello there, this is a personal message for an agent.",
+ title: "Agent personal message",
+ archetype: Archetype.private_message,
+ target_recipients: agent.reload.user.username,
+ }
+ end
+
+ it "accepts the PM when the agent is accessible and allows personal messages" do
+ create_pm_to_agent_user
+
+ expect(response.status).to eq(200)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.allowed_users).to include(agent.user)
+ end
+
+ it "rejects the PM when the agent does not allow personal messages" do
+ agent.update!(allow_personal_messages: false)
+
+ create_pm_to_agent_user
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.cannot_send_pm_to_agent"),
+ )
+ end
+
+ it "rejects the PM when the user is not in the agent's allowed groups" do
+ agent.update!(allowed_group_ids: [Group::AUTO_GROUPS[:staff]])
+
+ create_pm_to_agent_user
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_ai.ai_bot.errors.cannot_send_pm_to_agent"),
+ )
+ end
+
+ it "still accepts a PM to a default LLM bot user without an agent id" do
+ post "/posts.json",
+ params: {
+ raw: "Hello there, this is a personal message for a bot.",
+ title: "Bot personal message",
+ archetype: Archetype.private_message,
+ target_recipients: bot_user.username,
+ }
+
+ expect(response.status).to eq(200)
+ end
+ end
+end