A platform for community discussion. Free, open, simple.
DEV: Block external requests in system specs via Chrome DNS resolver (#40685)
David Taylorb447f125566b
diff --git a/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rb b/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rbindex cd7868506e0..d062514ce87 100644--- a/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rb+++ b/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rb@@ -9,7 +9,7 @@ RSpec.describe "Signup with captcha" doSiteSetting.discourse_captcha_enabled = trueend- context "with hCaptcha" do+ context "with hCaptcha", allow_network: %w[hcaptcha.com *.hcaptcha.com] dobefore doSiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHASiteSetting.hcaptcha_site_key = "10000000-ffff-ffff-ffff-000000000001"@@ -66,7 +66,7 @@ RSpec.describe "Signup with captcha" doendend- context "with reCaptcha" do+ context "with reCaptcha", allow_network: %w[www.google.com www.gstatic.com] dobefore doSiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHASiteSetting.recaptcha_site_key = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"diff --git a/plugins/discourse-subscriptions/spec/system/campaign_banner_spec.rb b/plugins/discourse-subscriptions/spec/system/campaign_banner_spec.rbindex db05825ac26..019a6ecfbd0 100644--- a/plugins/discourse-subscriptions/spec/system/campaign_banner_spec.rb+++ b/plugins/discourse-subscriptions/spec/system/campaign_banner_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe "Campaign Banner" do+RSpec.describe "Campaign Banner", allow_network: ["js.stripe.com"] dofab!(:user)fab!(:contributor) { Fabricate(:user, username: "contributor1") }diff --git a/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb b/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rbindex f020b2532d1..fab36a60783 100644--- a/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb+++ b/plugins/discourse-subscriptions/spec/system/pricing_table_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe "Pricing Table" do+RSpec.describe "Pricing Table", allow_network: ["js.stripe.com"] dofab!(:admin)fab!(:product) { Fabricate(:product, external_id: "prod_OiK") }let(:dialog) { PageObjects::Components::Dialog.new }diff --git a/plugins/discourse-subscriptions/spec/system/subscription_product_spec.rb b/plugins/discourse-subscriptions/spec/system/subscription_product_spec.rbindex 4941b91b78f..c12329020c4 100644--- a/plugins/discourse-subscriptions/spec/system/subscription_product_spec.rb+++ b/plugins/discourse-subscriptions/spec/system/subscription_product_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-describe "Subscription products" do+describe "Subscription products", allow_network: ["js.stripe.com"] dofab!(:admin)fab!(:product) { Fabricate(:product, external_id: "prod_OiK") }let(:dialog) { PageObjects::Components::Dialog.new }diff --git a/spec/rails_helper.rb b/spec/rails_helper.rbindex dc999ab4444..0720191a82d 100644--- a/spec/rails_helper.rb+++ b/spec/rails_helper.rb@@ -177,7 +177,7 @@ RSpec.configure do |config|config.before(:each, type: :system) do |example|SystemDrivers.preload_model_schemas!- SystemDrivers.register!(color_scheme: example.metadata[:color_scheme])+ SystemDrivers.register!(example)driven_by SystemDrivers.driver_for(example)setup_system_testdiff --git a/spec/support/system/driver.rb b/spec/support/system/driver.rbindex 09bfaca22ec..d73107a13c4 100644--- a/spec/support/system/driver.rb+++ b/spec/support/system/driver.rb@@ -21,20 +21,32 @@ module SystemDrivers@schemas_preloaded = trueend- # Builds the registered driver name for the example (mobile vs desktop chrome).+ MOBILE_USER_AGENT =+ "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Mobile/15E148 Safari/604.1"++ def self.allow_network_hosts(example)+ Array(example.metadata[:allow_network]).map(&:to_s).map(&:strip).reject(&:empty?).uniq.sort+ end++ # Builds the registered driver name for the example. Mobile vs desktop, plus a+ # suffix for the `allow_network:` host set so each set gets its own browser+ # (host-resolver-rules are a launch arg and can't be changed per-test).def self.driver_for(example)driver = [:playwright]driver << :mobile if example.metadata[:mobile]driver << :chrome++ hosts = allow_network_hosts(example)+ driver << "net#{Digest::SHA1.hexdigest(hosts.join(","))[0, 10]}" if hosts.any?+driver.join("_").to_symend- def self.register!(color_scheme:)- driver_options = {+ def self.register!(example)+ base_options = {browser_type: :chromium,channel: :chromium,headless: (ENV["PLAYWRIGHT_HEADLESS"].presence || ENV["SELENIUM_HEADLESS"].presence) != "0",- args: apply_base_chrome_args,acceptDownloads: true,downloadsPath: Downloads::FOLDER,slowMo: ENV["PLAYWRIGHT_SLOW_MO_MS"].to_i, # https://playwright.dev/docs/api/class-browsertype#browser-type-launch-option-slow-mo@@ -43,40 +55,58 @@ module SystemDrivers# NOTE: timezoneId is NOT set here because the driver is cached and reused,# so only the first test's timezone would be applied. Instead, we use CDP# to override the timezone per-test in the system before(:each) hook.- colorScheme: color_scheme,+ colorScheme: example.metadata[:color_scheme],}if ENV["CAPYBARA_REMOTE_DRIVER_URL"].present?- driver_options[:browser] = :remote- driver_options[:url] = ENV["CAPYBARA_REMOTE_DRIVER_URL"]+ base_options[:browser] = :remote+ base_options[:url] = ENV["CAPYBARA_REMOTE_DRIVER_URL"]end- Capybara.register_driver(:playwright_mobile_chrome) do |app|- Capybara::Playwright::Driver.new(- app,- **driver_options,- deviceScaleFactor: 3,- isMobile: true,- hasTouch: true,- userAgent:- "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.4 Mobile/15E148 Safari/604.1",- defaultBrowserType: "webkit",- viewport: ENV["PLAYWRIGHT_NO_VIEWPORT"] == "1" ? nil : { width: 390, height: 664 },- )- end-- Capybara.register_driver(:playwright_chrome) do |app|- Capybara::Playwright::Driver.new(- app,- **driver_options,- viewport: ENV["PLAYWRIGHT_NO_VIEWPORT"] == "1" ? nil : { width: 1400, height: 1400 },+ register_chrome(+ :playwright_mobile_chrome,+ **base_options,+ args: apply_base_chrome_args,+ mobile: true,+ )+ register_chrome(:playwright_chrome, **base_options, args: apply_base_chrome_args, mobile: false)++ # Specs that need a specific external host register their own browser, with+ # those hosts excluded from the request block (see apply_base_chrome_args).+ hosts = allow_network_hosts(example)+ if hosts.any?+ register_chrome(+ driver_for(example),+ **base_options,+ args: apply_base_chrome_args(allow_network: hosts),+ mobile: !!example.metadata[:mobile],)endCapybara.default_driver = :playwright_chromeend- def self.apply_base_chrome_args(args = [])+ def self.register_chrome(name, mobile:, **options)+ mobile_options =+ if mobile+ {+ deviceScaleFactor: 3,+ isMobile: true,+ hasTouch: true,+ userAgent: MOBILE_USER_AGENT,+ defaultBrowserType: "webkit",+ viewport: ENV["PLAYWRIGHT_NO_VIEWPORT"] == "1" ? nil : { width: 390, height: 664 },+ }+ else+ { viewport: ENV["PLAYWRIGHT_NO_VIEWPORT"] == "1" ? nil : { width: 1400, height: 1400 } }+ end++ Capybara.register_driver(name) do |app|+ Capybara::Playwright::Driver.new(app, **options, **mobile_options)+ end+ end++ def self.apply_base_chrome_args(args = [], allow_network: [])base_args = %w[--disable-search-engine-choice-screen--no-sandbox@@ -96,6 +126,26 @@ module SystemDrivers# Bypass the OS resolver for localhost lookups inside the browser.resolver_rules.push("MAP localhost [::1]", "MAP *.localhost [::1]")end++ # Block external network access from the browser by resolving any host that+ # isn't explicitly excluded to NXDOMAIN. System specs should never reach out+ # to the real internet; this fails fast instead of hanging or leaking+ # requests. Unlike Playwright request interception it leaves the HTTP cache+ # enabled. Rules are first-match-wins, so the excludes and the MAPs above+ # take precedence.+ minio_domain = ENV["MINIO_RUNNER_MINIO_DOMAIN"].presence || "minio.local"+ resolver_rules.push(+ "EXCLUDE localhost",+ "EXCLUDE *.localhost",+ "EXCLUDE #{Capybara.server_host}",+ "EXCLUDE #{minio_domain}",+ "EXCLUDE *.#{minio_domain}",+ )+ # Hosts a spec opted into via `allow_network:` resolve normally; everything+ # else falls through to NXDOMAIN.+ allow_network.each { |host| resolver_rules.push("EXCLUDE #{host}") }+ resolver_rules.push("MAP * ~NOTFOUND")+base_args << "--host-resolver-rules=#{resolver_rules.join(",")}"# A file that contains just a list of paths like so:@@ -116,7 +166,7 @@ module SystemDriversbase_args + argsend- private_class_method :apply_base_chrome_args+ private_class_method :apply_base_chrome_args, :register_chrome, :allow_network_hostsendRSpec.configure do |config|diff --git a/spec/system/finish_installation_spec.rb b/spec/system/finish_installation_spec.rbindex 162f9ba0f9b..51fd54f6b8c 100644--- a/spec/system/finish_installation_spec.rb+++ b/spec/system/finish_installation_spec.rb@@ -46,9 +46,18 @@ RSpec.describe "Finish Installation" doendit "creates multiple admin users when multiple emails are configured" do+ OmniAuth.config.test_mode = true+ OmniAuth.config.mock_auth[:discourse_id] = OmniAuth::AuthHash.new(+ provider: "discourse_id",+ uid: "12345",+ info: OmniAuth::AuthHash::InfoHash.new(email: "[email protected]", nickname: "dev1"),+ )+finish_installation_page.visit_pagefinish_installation_page.click_login_with_discourse_id+ expect(page).to have_current_path("/wizard")+user1 = User.find_by_email("[email protected]")user2 = User.find_by_email("[email protected]")@@ -56,8 +65,8 @@ RSpec.describe "Finish Installation" doexpect(user1.admin).to eq(true)expect(user2).to be_presentexpect(user2.admin).to eq(true)-- expect(page.current_url).to include("id.discourse.com")+ ensure+ reset_omniauth_config(:discourse_id)endit "skips creating users that already exist" do