Skip to content

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

DEV: Improved error message when not allowed to edit posts with AI tool (#37547)

Sam6095ed3d0c37
diff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rb
index 50cdb0f8c3a..8f9d3523e6a 100644
--- a/plugins/discourse-ai/lib/personas/tool_runner.rb
+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb
@@ -888,6 +888,11 @@ module DiscourseAi
user = resolve_user(username)
return { error: "User not found: #{username}" } if user.nil?
+ guardian = Guardian.new(user)
+ unless guardian.can_edit?(post)
+ return { error: "User is not allowed to edit this post" }
+ end
+
revisor = PostRevisor.new(post)
if revisor.revise!(user, { raw: raw, edit_reason: edit_reason })
{ success: true, post_id: post.id }
diff --git a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
index 28a6be12ac8..d466e4d862b 100644
--- a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
+++ b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
@@ -197,6 +197,28 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
expect(post.reload.last_editor_id).to eq(other_user.id)
end
+ it "denies editing a post when the user lacks permission" do
+ post_author = Fabricate(:user)
+ unprivileged_user = Fabricate(:user)
+ post = Fabricate(:post, user: post_author)
+ original_raw = post.raw
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.editPost(params.post_id, 'hacked content', { username: '#{unprivileged_user.username}' }); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ post_id: post.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ expect { runner.invoke }.to raise_error(/Permission denied|not allowed to edit/)
+ expect(post.reload.raw).to eq(original_raw)
+ end
+
it "can generate JSON from LLM" do
tool.update!(script: "function invoke() { return llm.generate('test', { json: true }); }")