A platform for community discussion. Free, open, simple.
SECURITY: Apply current Guardian visibility to AI prompt context (#43589)
Isaac Janzenba4821b9db2e
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rbindex 34832efd97f..2b9c9d529ce 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/bot_controller.rb@@ -92,6 +92,7 @@ module DiscourseAibot_user_id: post.user_id,agent_id: agent_id,authorization_user_id: authorization_user_id,+ visibility_user_id: current_user.id,reply_post_id: post.id,}diff --git a/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb b/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rbindex 56bf8ef9424..a4f37c22707 100644--- a/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb+++ b/plugins/discourse-ai/app/jobs/regular/create_ai_reply.rb@@ -20,6 +20,14 @@ module Jobsendreturn if authorization_user.nil?+ visibility_user =+ if args.key?(:visibility_user_id)+ User.find_by(id: args[:visibility_user_id])+ else+ post.user+ end+ return if visibility_user.nil?+llm_model_id = args[:llm_model_id]begin@@ -35,6 +43,7 @@ module Jobsfeature_name: "bot",existing_reply_post: reply_post,authorization_user_id: authorization_user.id,+ visibility_user: visibility_user,)rescue DiscourseAi::Agents::Bot::BOT_NOT_FOUNDRails.logger.warn(diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rbindex 4e4e4b75fb0..b915b9ec7d8 100644--- a/plugins/discourse-ai/lib/ai_bot/playground.rb+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb@@ -514,6 +514,7 @@ module DiscourseAiattributed_user: nil,feature_context: nil,authorization_user_id: nil,+ visibility_user: post.user,&blk)# this is a multithreading issue@@ -541,17 +542,19 @@ module DiscourseAi)context_llm = bot.llm+ visibility_guardian = Guardian.new(visibility_user)context =DiscourseAi::Agents::BotContext.new(post: post,user: attributed_user,+ guardian: visibility_guardian,custom_instructions: custom_instructions,feature_name: feature_name,feature_context: feature_context,messages:DiscourseAi::Completions::PromptMessagesBuilder.messages_from_post(post,- guardian: (attributed_user || post.user).guardian,+ guardian: visibility_guardian,style: context_style,max_posts: DiscourseAi::Completions::PromptMessagesBuilder::MAX_CONTEXT_MESSAGES,context_token_budget: context_token_budget(context_llm),diff --git a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rbindex dc636e197fd..749c6b6c6a7 100644--- a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb+++ b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb@@ -143,15 +143,20 @@ module DiscourseAipost_types = [Post.types[:regular]]post_types << Post.types[:whisper] if post.post_type == Post.types[:whisper]- context =+ context_query =post.topic.posts+ .joins(:topic).joins(:user).joins("LEFT JOIN post_custom_prompts ON post_custom_prompts.post_id = posts.id").where("post_number <= ?", post.post_number)- .order("post_number desc").where("post_type in (?)", post_types)++ context =+ guardian+ .filter_hidden_posts(context_query, category: post.topic.category)+ .order("post_number desc").limit(max_posts).pluck("posts.raw",@@ -187,7 +192,14 @@ module DiscourseAi# Tool syntax requires a tool_call_id which we don't have.if message[2] != "function"custom_context = {- content: message[0],+ content:+ filtered_custom_prompt_content(+ message[0],+ include_image_uploads: include_image_uploads,+ include_document_uploads: include_document_uploads,+ allowed_attachment_types: allowed_attachment_types,+ guardian: guardian,+ ),type: message[2].present? ? message[2].to_sym : :model,}@@ -279,6 +291,32 @@ module DiscourseAi[!!include_image_uploads, !!include_document_uploads]end+ def self.filtered_custom_prompt_content(+ content,+ include_image_uploads:,+ include_document_uploads:,+ guardian:,+ allowed_attachment_types: nil+ )+ return content if !content.is_a?(Array)++ upload_ids =+ content.filter_map { |part| part[:upload_id] || part["upload_id"] if part.is_a?(Hash) }+ allowed_upload_ids =+ filtered_upload_ids_for_prompt(+ upload_ids,+ include_image_uploads: include_image_uploads,+ include_document_uploads: include_document_uploads,+ allowed_attachment_types: allowed_attachment_types,+ guardian: guardian,+ ) || []++ content.reject do |part|+ part.is_a?(Hash) && (upload_id = part[:upload_id] || part["upload_id"]) &&+ !allowed_upload_ids.include?(upload_id.to_i)+ end+ end+def self.filtered_upload_ids_for_prompt(upload_ids,include_image_uploads:,diff --git a/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb b/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rbindex 79fcaf14204..5bb06b3fd46 100644--- a/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/prompt_messages_builder_spec.rb@@ -658,6 +658,48 @@ describe DiscourseAi::Completions::PromptMessagesBuilder do# will be brittle, but open to changing thisend+ it "excludes hidden posts the triggering user cannot see from topic context" do+ topic = Fabricate(:topic, title: "Public topic with hidden reply")+ visible_post =+ Fabricate(+ :post,+ topic: topic,+ user: other_user,+ post_number: 1,+ raw: "Visible context for the prompt",+ )+ hidden_post =+ Fabricate(+ :post,+ topic: topic,+ user: other_user,+ post_number: 2,+ raw: "Hidden context that must not reach the prompt",+ hidden: true,+ )+ trigger_post =+ Fabricate(+ :post,+ topic: topic,+ user: user,+ post_number: 3,+ raw: "Please answer using the visible context",+ )+ expect(Guardian.new(user).can_see?(hidden_post)).to eq(false)++ context =+ described_class.messages_from_post(+ trigger_post,+ max_posts: 10,+ bot_usernames: [bot_user.username],+ include_uploads: false,+ )++ content = context.flat_map { |message| Array(message[:content]) }.join+ expect(content).to include(visible_post.raw, trigger_post.raw)+ expect(content).not_to include(hidden_post.raw)+ end+it "includes document post uploads independently from image uploads" doUploadReference.create!(target: third_post, upload: image_upload1)UploadReference.create!(target: third_post, upload: document_upload)diff --git a/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rbindex 4411e1db825..cdc2b0ca541 100644--- a/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/ai_bot/bot_controller_spec.rb@@ -624,6 +624,62 @@ RSpec.describe DiscourseAi::AiBot::BotController doexpect(response.status).to eq(404)end+ it "does not expose a moderator's secure upload when a regular user retries the reply" do+ moderator = Fabricate(:moderator, refresh_auto_groups: true)+ native_vision_model = Fabricate(:llm_model, vision_enabled: true)+ llm_model.update!(vision_llm_model: native_vision_model)+ ai_agent.update!(vision_enabled: true)+ AiAgent.agent_cache.flush!++ source_topic = Fabricate(:private_message_topic, user: moderator)+ source_post = Fabricate(:post, topic: source_topic, user: moderator)+ secure_upload = Fabricate(:image_upload, user: moderator)+ secure_upload.update!(secure: true, access_control_post: source_post)++ topic = Fabricate(:topic, user: moderator)+ trigger_post =+ Fabricate(+ :post,+ topic: topic,+ user: moderator,+ raw: "Inspect this private image: ",+ )++ aggregate_failures do+ expect(Guardian.new(moderator).can_see_upload?(secure_upload)).to eq(true)+ expect(Guardian.new(user).can_see_upload?(secure_upload)).to eq(false)+ end++ reply_post =+ DiscourseAi::Completions::Llm.with_prepared_responses(["Initial response"]) do+ DiscourseAi::AiBot::Playground.new(bot).reply_to(trigger_post)+ end++ post "/discourse-ai/ai-bot/post/#{reply_post.id}/retry"++ response_status = response.status+ response_body = response.body+ job_args = Jobs::CreateAiReply.jobs.last["args"].first.symbolize_keys+ prompts = nil++ DiscourseAi::Completions::Llm.with_prepared_responses(+ ["Retry response"],+ ) do |_, _, captured_prompts|+ Jobs::CreateAiReply.new.execute(job_args)+ prompts = captured_prompts+ end++ prompt_content = prompts.flat_map(&:messages).map { |message| message[:content] }.join++ aggregate_failures do+ expect(response_status).to eq(200)+ expect(response_body).to include("success")+ expect(job_args[:visibility_user_id]).to eq(user.id)+ expect(prompt_content).to include("[Image unavailable]")+ expect(prompt_content).not_to include("upload_id #{secure_upload.id}")+ end+ end+it "allows retrying if LLM model has a negative id (seeded)" doseeded_llm_model = Fabricate(:llm_model, id: -9999, user: bot_user, name: "second-model")diff --git a/plugins/discourse-ai/spec/requests/ai_bot/posts_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/posts_controller_spec.rbindex 44f9c04f62e..c216cacf010 100644--- a/plugins/discourse-ai/spec/requests/ai_bot/posts_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/ai_bot/posts_controller_spec.rb@@ -74,5 +74,56 @@ RSpec.describe PostsController doexpect(response.parsed_body["topic_id"]).to eq(topic.id)endend++ it "does not send a persisted secure upload to the provider after access is revoked" do+ agent =+ Fabricate(+ :ai_agent,+ default_llm_id: llm_model.id,+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],+ allow_topic_mentions: true,+ vision_enabled: true,+ )+ agent.create_user!+ AiAgent.agent_cache.flush!++ conversation = Fabricate(:topic)+ bot_reply = Fabricate(:post, topic: conversation, user: agent.user)+ source_owner = Fabricate(:user)+ source_topic = Fabricate(:private_message_topic, user: source_owner, recipient: user)+ source_post = Fabricate(:post, topic: source_topic, user: source_owner)+ secure_upload = Fabricate(:image_upload, user: source_owner)+ secure_upload.update!(secure: true, access_control_post: source_post)++ PostCustomPrompt.create!(+ post: bot_reply,+ custom_prompt: [+ [["Look at this image", { upload_id: secure_upload.id }], user.username, "user"],+ ],+ )+ source_topic.topic_allowed_users.where(user: user).destroy_all+ Jobs.run_immediately!+ SiteSetting.ai_bot_enabled = true+ sign_in(user)++ prompts = nil+ DiscourseAi::Completions::Llm.with_prepared_responses(+ ["I can help"],+ ) do |_, _, recorded_prompts|+ post "/posts.json",+ params: {+ topic_id: conversation.id,+ raw: "Please help @#{agent.user.username}",+ }+ prompts = recorded_prompts+ end++ expect(response.status).to eq(200)+ expect(response.parsed_body["topic_id"]).to eq(conversation.id)+ expect(user.guardian.can_see_upload?(secure_upload)).to eq(false)+ expect(prompts.first.messages.flat_map { |message| Array(message[:content]) }).not_to include(+ { upload_id: secure_upload.id },+ )+ endendend