Skip to content

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

DEV: Gate Data Explorer RunSql AI tool behind admin check (#40185)

Natalie Tay8b642380252c
diff --git a/plugins/discourse-data-explorer/config/locales/server.en.yml b/plugins/discourse-data-explorer/config/locales/server.en.yml
index dc2d817d872..592420ee34d 100644
--- a/plugins/discourse-data-explorer/config/locales/server.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/server.en.yml
@@ -18,6 +18,8 @@ en:
ai:
error_agent_not_configured: "AI agent is not configured. Please check the AI features settings."
error_no_sql_returned: "AI did not return a valid SQL query. Please try again or write the query manually."
+ errors:
+ tool_not_allowed: "You are not allowed to use this tool"
discourse_automation:
scriptables:
recurring_data_explorer_result_pm:
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/tools/run_sql.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/tools/run_sql.rb
index c3555178df6..23cb29920a7 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/tools/run_sql.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/tools/run_sql.rb
@@ -31,6 +31,10 @@ module DiscourseDataExplorer
end
def invoke
+ if !context.user&.admin?
+ return error_response(I18n.t("discourse_data_explorer.errors.tool_not_allowed"))
+ end
+
sql = parameters[:sql].to_s.strip
return error_response("SQL query is empty") if sql.blank?
diff --git a/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb b/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb
new file mode 100644
index 00000000000..3228ae55992
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/tools/run_sql_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+describe DiscourseDataExplorer::Tools::RunSql do
+ fab!(:llm_model)
+ fab!(:admin)
+ fab!(:user)
+
+ let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.ai_bot_enabled = true
+ end
+
+ def invoke_with(user:)
+ described_class.new(
+ { sql: "SELECT 1 AS one" },
+ bot_user: bot_user,
+ llm: llm,
+ context: DiscourseAi::Agents::BotContext.new(user: user),
+ ).invoke
+ end
+
+ it "returns success for an admin caller" do
+ result = invoke_with(user: admin)
+
+ expect(result[:status]).to eq("success")
+ expect(result[:columns]).to eq(["one"])
+ end
+
+ it "blocks a non-admin caller without running the SQL" do
+ allow(DiscourseDataExplorer::DataExplorer).to receive(:run_query)
+
+ result = invoke_with(user: user)
+
+ expect(result[:status]).to eq("error")
+ expect(result[:error]).to eq(I18n.t("discourse_data_explorer.errors.tool_not_allowed"))
+ expect(DiscourseDataExplorer::DataExplorer).not_to have_received(:run_query)
+ end
+end