A platform for community discussion. Free, open, simple.
FEATURE: Allow custom Telegram API base URL (#41818)
Sergei Dmitriev8def92409e4c
diff --git a/plugins/discourse-chat-integration/config/locales/client.en.yml b/plugins/discourse-chat-integration/config/locales/client.en.ymlindex 4b462f7d693..adc986a2fb4 100644--- a/plugins/discourse-chat-integration/config/locales/client.en.yml+++ b/plugins/discourse-chat-integration/config/locales/client.en.yml@@ -138,6 +138,8 @@ en:webhook_setup_failed: "Could not register the webhook with Telegram. Check the token and try again."channel_not_found: "The specified channel does not exist on Telegram"forbidden: "The bot does not have permission to post to this channel"+ invalid_api_base_url: "The Telegram API base URL site setting is not a valid HTTPS URL."+ api_base_url_blocked: "Requests to the Telegram API base URL were blocked. Hosts on private networks must be added to the allowed internal hosts site setting."################################################## DISCORD STRINGS ###########diff --git a/plugins/discourse-chat-integration/config/locales/server.en.yml b/plugins/discourse-chat-integration/config/locales/server.en.ymlindex 50238f5c833..1989839ac7b 100644--- a/plugins/discourse-chat-integration/config/locales/server.en.yml+++ b/plugins/discourse-chat-integration/config/locales/server.en.yml@@ -18,12 +18,14 @@ en:errors:chat_integration_slack_api_configs_are_empty: "You must enter either an outbound webhook URL, or an access token"+ chat_integration_telegram_api_base_url_invalid: "The Telegram API base URL must be a valid HTTPS URL without credentials, a query string, or a fragment"################################################ TELEGRAM SETTINGS ##################################################chat_integration_telegram_enabled: "Enable the Telegram chat-integration provider"chat_integration_telegram_access_token: "Your bot's access token from the Telegram botfather"+ chat_integration_telegram_api_base_url: "Base URL used for Telegram Bot API requests. Change this only when routing requests through a trusted HTTPS proxy. Hosts on private networks must also be added to the allowed internal hosts site setting."chat_integration_telegram_excerpt_length: "Telegram post excerpt length"chat_integration_telegram_enable_slash_commands: "Allow telegram subscriptions to be managed using 'slash commands'"diff --git a/plugins/discourse-chat-integration/config/settings.yml b/plugins/discourse-chat-integration/config/settings.ymlindex 6347ef3330e..07e8f92dec8 100644--- a/plugins/discourse-chat-integration/config/settings.yml+++ b/plugins/discourse-chat-integration/config/settings.yml@@ -40,6 +40,9 @@ chat_integration:chat_integration_telegram_access_token:default: ''secret: true+ chat_integration_telegram_api_base_url:+ default: 'https://api.telegram.org'+ validator: "ChatIntegrationTelegramApiBaseUrlSettingValidator"chat_integration_telegram_excerpt_length:default: 400chat_integration_telegram_enable_slash_commands:diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator.rbnew file mode 100644index 00000000000..ea06a50bc2e--- /dev/null+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++class ChatIntegrationTelegramApiBaseUrlSettingValidator+ def initialize(opts = {})+ @opts = opts+ end++ def valid_value?(value)+ DiscourseChatIntegration::Provider::TelegramProvider.parse_base_url(value).present?+ end++ def error_message+ I18n.t("site_settings.errors.chat_integration_telegram_api_base_url_invalid")+ end+enddiff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_command_controller.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_command_controller.rbindex 14b90d3eeb0..f1b84fa8ad4 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_command_controller.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_command_controller.rb@@ -13,6 +13,16 @@ module DiscourseChatIntegration::Provider::TelegramProvideronly: :commanddef command+ send_reply++ # Always give telegram a success message, otherwise we'll stop receiving webhooks+ data = { success: true }+ render json: data+ end++ private++ def send_reply# If it's a new message (telegram also sends hooks for other reasons that we don't care about)if params.key?("message")chat_id = params["message"]["chat"]["id"]@@ -48,14 +58,10 @@ module DiscourseChatIntegration::Provider::TelegramProviderDiscourseChatIntegration::Provider::TelegramProvider.sendMessage(message)end-- # Always give telegram a success message, otherwise we'll stop receiving webhooks- data = { success: true }- render json: data+ rescue DiscourseChatIntegration::ProviderError => e+ Rails.logger.warn("Failed to send telegram command reply: #{e.info.to_json}")end- private-def process_command(message)return unless message["text"] # No command to be processeddiff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rbindex f7a892fa796..dce51b14a62 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb@@ -81,17 +81,47 @@ module DiscourseChatIntegrationdo_api_request("sendMessage", message)end- def self.do_api_request(method_name, message, access_token: nil)- http = FinalDestination::HTTP.new("api.telegram.org", 443)- http.use_ssl = true+ def self.parse_base_url(value)+ uri = URI(value)++ if uri.is_a?(URI::HTTPS) && uri.host.present? && uri.userinfo.blank? && uri.query.blank? &&+ uri.fragment.blank?+ uri+ end+ rescue URI::Error, TypeError+ nil+ end+ def self.do_api_request(method_name, message, access_token: nil)token = access_token.presence || SiteSetting.chat_integration_telegram_access_token- uri = URI("https://api.telegram.org/bot#{token}/#{method_name}")+ uri = parse_base_url(SiteSetting.chat_integration_telegram_api_base_url)++ if uri.nil?+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.telegram.errors.invalid_api_base_url",+ },+ )+ end++ uri.path = File.join(uri.path, "bot#{token}", method_name)++ http = FinalDestination::HTTP.new(uri.host, uri.port)+ http.use_ssl = truereq = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")req.body = message.to_json- response = http.request(req)++ begin+ response = http.request(req)+ rescue FinalDestination::SSRFDetector::DisallowedIpError+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.telegram.errors.api_base_url_blocked",+ },+ )+ endJSON.parse(response.body)enddiff --git a/plugins/discourse-chat-integration/plugin.rb b/plugins/discourse-chat-integration/plugin.rbindex 8ac5eef0d0c..9151b3bc0dd 100644--- a/plugins/discourse-chat-integration/plugin.rb+++ b/plugins/discourse-chat-integration/plugin.rb@@ -20,6 +20,7 @@ end# Site setting validators must be loaded before initializerequire_relative "lib/discourse_chat_integration/provider/slack/slack_enabled_setting_validator"+require_relative "lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator"require_relative "lib/discourse_chat_integration/chat_integration_reference_post"after_initialize dodiff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator_spec.rbnew file mode 100644index 00000000000..d3fcb1e4571--- /dev/null+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_api_base_url_setting_validator_spec.rb@@ -0,0 +1,31 @@+# frozen_string_literal: true++RSpec.describe ChatIntegrationTelegramApiBaseUrlSettingValidator do+ subject(:validator) { described_class.new }++ describe "#valid_value?" do+ it "accepts HTTPS base URLs" do+ valid_urls = %w[+ https://api.telegram.org+ https://telegram.example.com/+ https://telegram.example.com/api+ ]++ expect(valid_urls.select { |url| validator.valid_value?(url) }).to eq(valid_urls)+ end++ it "rejects unsafe or malformed base URLs" do+ invalid_urls = [+ "http://telegram.example.com",+ "https:///telegram",+ "https://user:[email protected]",+ "https://telegram.example.com/?route=telegram",+ "https://telegram.example.com/#telegram",+ "not a URL",+ "",+ ]++ expect(invalid_urls.reject { |url| validator.valid_value?(url) }).to eq(invalid_urls)+ end+ end+enddiff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_command_controller_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_command_controller_spec.rbindex 3f813804bf7..0dfa6def309 100644--- a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_command_controller_spec.rb+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_command_controller_spec.rb@@ -195,6 +195,25 @@ describe "Telegram Command Controller", type: :request doexpect(stub).to have_been_requested.times(1)end+ it "still returns success when the reply cannot be sent" do+ SiteSetting.stubs(:chat_integration_telegram_api_base_url).returns(+ "http://telegram.example.com",+ )++ post "/chat-integration/telegram/command/shhh.json",+ params: {+ message: {+ chat: {+ id: 123,+ },+ text: "/help",+ },+ }++ expect(response.status).to eq(200)+ expect(stub).to have_been_requested.times(0)+ end+context "when 'text' is missing" doit "does not break" dopost "/chat-integration/telegram/command/shhh.json",diff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rbindex ba75d99b390..edbebfe0472 100644--- a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rb+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rb@@ -34,6 +34,32 @@ RSpec.describe DiscourseChatIntegration::Provider::TelegramProvider doexpect(stub1).to have_been_requested.onceend+ it "uses the configured API base URL" do+ SiteSetting.chat_integration_telegram_api_base_url = "https://telegram.example.com/api/"+ request_stub =+ stub_request(:post, "https://telegram.example.com/api/botTOKEN/sendMessage").to_return(+ body: "{\"ok\":true}",+ )++ described_class.trigger_notification(post, chan1, nil)++ expect(request_stub).to have_been_requested.once+ end++ it "raises a provider error when the effective base URL is invalid" do+ SiteSetting.stubs(:chat_integration_telegram_api_base_url).returns(+ "http://telegram.example.com",+ )++ expect { described_class.trigger_notification(post, chan1, nil) }.to raise_error(+ DiscourseChatIntegration::ProviderError,+ ) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.telegram.errors.invalid_api_base_url",+ )+ end+ end+it "handles errors correctly" dostub1 =stub_request(:post, "https://api.telegram.org/botTOKEN/sendMessage").to_return(@@ -47,6 +73,13 @@ RSpec.describe DiscourseChatIntegration::Provider::TelegramProvider doendend+ describe ".parse_base_url" do+ it "returns the parsed URI for valid values and nil otherwise" do+ expect(described_class.parse_base_url("https://telegram.example.com/api")).to be_a(URI::HTTPS)+ expect(described_class.parse_base_url("http://telegram.example.com")).to be_nil+ end+ end+describe ".get_channel_by_name" doit "returns the right channel" doexpected =@@ -97,6 +130,19 @@ RSpec.describe DiscourseChatIntegration::Provider::TelegramProvider doexpect(SiteSetting.chat_integration_telegram_enabled).to eq(true)end+ it "registers the webhook through a custom API base URL" do+ SiteSetting.chat_integration_telegram_api_base_url = "https://telegram.example.com/"++ stub =+ stub_request(:post, %r{https://telegram\.example\.com/botnewtok/setWebhook}).to_return(+ body: "{\"ok\":true}",+ )++ described_class.setup(admin, { chat_integration_telegram_access_token: "newtok" })++ expect(stub).to have_been_requested.once+ end+it "raises and does not change stored token when setWebhook fails" doSiteSetting.chat_integration_telegram_access_token = "unchanged"SiteSetting.chat_integration_telegram_secret = "existing-secret"