From 0ec3fee6ec97f74ff0c84e3ed04380abb75c8ccd Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Fri, 13 Nov 2026 12:23:13 -0500 Subject: [PATCH 01/11] NH-155201: restrict the config file permission --- CONFIGURATION.md | 11 ++- lib/solarwinds_apm/config.rb | 112 ++++++++++++++++++++++------- test/solarwinds_apm/config_test.rb | 112 +++++++++++++++++++++++++++++ 3 files changed, 208 insertions(+), 27 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 7f26da4e..964f72c1 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -212,6 +212,15 @@ Override the default configuration file location: export SW_APM_CONFIG_RUBY=/path/to/your/config.rb ``` +### Config File Selection + +At most one configuration file is loaded: + +1. If `SW_APM_CONFIG_RUBY` is set, only that file is used. If it can't be found, no configuration file is loaded; the agent doesn't fall back to the default locations. +2. Otherwise, the agent looks in the application root for `config/initializers/solarwinds_apm.rb` first and then `solarwinds_apm_config.rb`. The application root is `Rails.root` when it's available, then the directory of the Gemfile in use (`BUNDLE_GEMFILE`), and finally the current working directory. + +Config files are executed as Ruby code with the application's privileges. The agent refuses to load a configuration file that is world-writable, or that is in a world-writable directory without the sticky bit. + ## Configuration Topics ### Transaction Filtering @@ -314,7 +323,7 @@ export SW_APM_TRANSACTION_NAME=my-lambda-function | -------------------- | --------------- | ----------- | ------- | | `SW_APM_AUTO_CONFIGURE` | N/A | By default the library is configured to work out-of-the-box with all automatic instrumentation libraries enabled. Set this to `false` to custom initialize the library with configuration options for instrumentation, see [Programmatic Configuration](#programmatic-configuration) for details. | `true` | | `SW_APM_COLLECTOR` | N/A | Override the default collector endpoint to which the library connects and exports data. It should be defined using the format host:port. | `apm.collector.na-01.cloud.solarwinds.com:443` | -| `SW_APM_CONFIG_RUBY` | N/A | Override the default location for the configuration file. This can be an absolute or relative filename, or the directory under which the `solarwinds_apm_config.rb` file would be looked for. | None | +| `SW_APM_CONFIG_RUBY` | N/A | Override the default location for the configuration file. This can be an absolute or relative filename, or the directory under which the `solarwinds_apm_config.rb` file would be looked for. When set, default locations are not searched. | None | | `SW_APM_DEBUG_LEVEL` | `:debug_level` | Set the library's logging level, valid values are -1 through 6 (least to most verbose).
Setting -1 disables logging from the library. | 3 | | `SW_APM_ENABLED` | N/A | Enable/disable the library, setting `false` is an alternative to uninstalling `solarwinds_apm` since it will prevent the library from loading. | `true` | | `SW_APM_SERVICE_KEY` | `:service_key` | API token and service name in the form of `token:service_name`, **required**. | None | diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index 0738f19f..afa3a8ae 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -27,33 +27,58 @@ module Config @@config = {} + RAILS_CONFIG_FILE = 'config/initializers/solarwinds_apm.rb' + DEFAULT_CONFIG_FILE = 'solarwinds_apm_config.rb' + ## # load_config_file # - # There are 3 possible locations for the config file: - # Rails default, ENV['SW_APM_CONFIG_RUBY'], or the gem's default + # Selects and loads at most one Ruby config file. # Config will be used in OboeInitOptions but ENV variable has higher priority # e.g. ENV['SW_APM_SERVICE_KEY'] || SolarWindsAPM::Config[:service_key] # - # Hierarchie: - # 1 - Rails default: config/initializers/solarwinds_apm.rb - # (also loaded by Rails, but we can't reliably determine if Rails is running) - # 2 - ENV['SW_APM_CONFIG_RUBY'] - # 3 - Gem default: /solarwinds_apm_config.rb + # Selection: + # 1 - If ENV['SW_APM_CONFIG_RUBY'] is set, only that file is considered. + # If it can't be found, no other location is probed (fail closed). + # 2 - Otherwise, look in the application root (see app_root_dir) for: + # a - Rails default: config/initializers/solarwinds_apm.rb + # (also loaded by Rails, but we can't reliably determine if Rails is running) + # b - Gem default: solarwinds_apm_config.rb + # + # Files that are world-writable, or that live in a world-writable directory + # without the sticky bit, are refused. # def self.load_config_file - config_files = [] + config_file = explicit_config_path? ? config_file_from_env : default_config_file + + load(config_file) if config_file && trusted_config_file?(config_file) + + set_log_level # sets SolarWindsAPM::Config[:debug_level], SolarWindsAPM.logger.level + end - # Check for the rails config file - config_file = File.join(Dir.pwd, 'config/initializers/solarwinds_apm.rb') - config_files << config_file if File.exist?(config_file) + def self.explicit_config_path? + !ENV.fetch('SW_APM_CONFIG_RUBY', '').strip.empty? + end - # Check for file set by env variable - config_files << config_file_from_env if ENV.key?('SW_APM_CONFIG_RUBY') + def self.config_file_from_env + env_path = ENV.fetch('SW_APM_CONFIG_RUBY', '').strip + + if !env_path.empty? && File.file?(env_path) + config_file = env_path + elsif !env_path.empty? && File.file?(File.join(env_path, DEFAULT_CONFIG_FILE)) + config_file = File.join(env_path, DEFAULT_CONFIG_FILE) + else + SolarWindsAPM.logger.warn do + "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." + end + end + config_file + end - # Check for default config file - config_file = File.join(Dir.pwd, 'solarwinds_apm_config.rb') - config_files << config_file if File.exist?(config_file) + def self.default_config_file + base_dir = app_root_dir + config_files = [RAILS_CONFIG_FILE, DEFAULT_CONFIG_FILE].map { |file| File.join(base_dir, file) } + .select { |file| File.file?(file) } SolarWindsAPM.logger.debug { "[#{name}/#{__method__}] Available config_files: #{config_files.join(', ')}" } if config_files.size > 1 @@ -61,23 +86,58 @@ def self.load_config_file "[#{name}/#{__method__}] Multiple configuration files configured, using the first one listed: #{config_files.join(', ')}" end end - load(config_files[0]) if config_files.size.positive? + config_files.first + end - set_log_level # sets SolarWindsAPM::Config[:debug_level], SolarWindsAPM.logger.level + ## + # app_root_dir + # + # Directory used to resolve the default config file locations, in order: + # Rails.root (if the Rails application is already defined), + # the directory of the Gemfile in use (BUNDLE_GEMFILE, set by bundler and by Rails' config/boot.rb), + # and finally the current working directory. + # + def self.app_root_dir + if defined?(::Rails) && ::Rails.respond_to?(:root) + rails_root = ::Rails.root.to_s + return rails_root unless rails_root.empty? + end + + gemfile = ENV.fetch('BUNDLE_GEMFILE', '').strip + return File.dirname(File.expand_path(gemfile)) unless gemfile.empty? + + Dir.pwd + rescue StandardError => e + SolarWindsAPM.logger.debug { "[#{name}/#{__method__}] Failed to determine application root: #{e.message}" } + Dir.pwd end - def self.config_file_from_env - if File.exist?(ENV.fetch('SW_APM_CONFIG_RUBY', nil)) && !File.directory?(ENV.fetch('SW_APM_CONFIG_RUBY', nil)) - config_file = ENV.fetch('SW_APM_CONFIG_RUBY', nil) - elsif File.exist?(File.join(ENV.fetch('SW_APM_CONFIG_RUBY', nil), 'solarwinds_apm_config.rb')) - config_file = File.join(ENV.fetch('SW_APM_CONFIG_RUBY', nil), 'solarwinds_apm_config.rb') - else + def self.trusted_config_file?(config_file) + file_stat = File.stat(config_file) + dir_stat = File.stat(File.dirname(File.expand_path(config_file))) + + if file_stat.world_writable? + reason = 'the file is world-writable' + elsif dir_stat.world_writable? && !dir_stat.sticky? + reason = 'its directory is world-writable' + end + + # return true unless reason + + if reason SolarWindsAPM.logger.warn do - "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{ENV.fetch('SW_APM_CONFIG_RUBY', nil)}" + "[#{name}/#{__method__}] The configuration file #{config_file} is not trusted because #{reason}. + The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600). + Please change the permissions to make it secure. + In next release, apm-ruby will refuse to load configuration files from an insecure path." end end - config_file + true + rescue SystemCallError => e + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Unable to inspect configuration file #{config_file}: #{e.message}" } + false end + private_class_method :explicit_config_path?, :default_config_file, :app_root_dir, :trusted_config_file? def self.set_log_level log_level = (ENV['SW_APM_DEBUG_LEVEL'] || SolarWindsAPM::Config[:debug_level] || 3).to_i diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 6f0553d5..7ba5f1e6 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -5,6 +5,8 @@ require 'minitest_helper' require 'logger' +require 'tmpdir' +require 'fileutils' require './lib/solarwinds_apm/config' describe 'Config Test' do @@ -598,6 +600,116 @@ end end + describe '#load_config_file' do + def write_config(path, marker) + FileUtils.mkdir_p(File.dirname(path)) + File.write(path, "SolarWindsAPM::Config[:config_file_marker] = '#{marker}'\n") + File.chmod(0o644, path) + path + end + + before do + @original_env = ENV.to_h.slice('SW_APM_CONFIG_RUBY', 'BUNDLE_GEMFILE') + ENV.delete('SW_APM_CONFIG_RUBY') + ENV.delete('BUNDLE_GEMFILE') + @tmpdir = File.realpath(Dir.mktmpdir('sw_apm_config')) + @app_dir = File.join(@tmpdir, 'app').tap { |d| FileUtils.mkdir_p(d) } + @cwd = File.join(@tmpdir, 'work').tap { |d| FileUtils.mkdir_p(d) } + @trusted = write_config(File.join(@tmpdir, 'trusted', 'trusted.rb'), 'trusted') + SolarWindsAPM::Config[:config_file_marker] = nil + end + + after do + %w[SW_APM_CONFIG_RUBY BUNDLE_GEMFILE].each { |k| ENV.delete(k) } + ENV.update(@original_env) + FileUtils.rm_rf(@tmpdir) + SolarWindsAPM::Config[:config_file_marker] = nil + end + + it 'loads only SW_APM_CONFIG_RUBY even when a cwd rails initializer exists' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'trusted' + end + + it 'does not fall back to cwd files when SW_APM_CONFIG_RUBY is missing' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + ENV['SW_APM_CONFIG_RUBY'] = File.join(@tmpdir, 'missing.rb') + + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + + it 'resolves default files against the Gemfile directory instead of cwd' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') + ENV['BUNDLE_GEMFILE'] = File.join(@app_dir, 'Gemfile') + + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'app_rails' + end + + it 'does not load a cwd file outside the Gemfile directory' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + ENV['BUNDLE_GEMFILE'] = File.join(@app_dir, 'Gemfile') + + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + + it 'falls back to cwd when no application root is known, preferring the rails initializer' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_rails' + end + + it 'treats an empty SW_APM_CONFIG_RUBY as unset' do + write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + ENV['SW_APM_CONFIG_RUBY'] = '' + + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_default' + end + + it 'refuses to load a world-writable config file' do + File.chmod(0o666, @trusted) + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + SolarWindsAPM::Config.load_config_file + + assert SolarWindsAPM::Config[:config_file_marker] + end + + it 'refuses to load a config file in a world-writable non-sticky directory' do + File.chmod(0o777, File.dirname(@trusted)) + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + SolarWindsAPM::Config.load_config_file + + assert SolarWindsAPM::Config[:config_file_marker] + end + + it 'loads a config file in a world-writable sticky directory' do + File.chmod(0o1777, File.dirname(@trusted)) + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + SolarWindsAPM::Config.load_config_file + + _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'trusted' + end + end + describe 'update! and merge!' do it 'updates config with hash data' do SolarWindsAPM::Config.update!({ test_update_key: 'test_value' }) From 5fa85baee81dd61e2fb9955ce9ec113d9973fdd1 Mon Sep 17 00:00:00 2001 From: Xuan <112967240+xuan-cao-swi@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:30:44 -0500 Subject: [PATCH 02/11] Change config loading behavior for world-writable files Update configuration handling to warn instead of refuse loading world-writable files and directories. Adjust tests to reflect the new behavior. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- CONFIGURATION.md | 2 +- lib/solarwinds_apm/config.rb | 5 +++-- test/solarwinds_apm/config_test.rb | 28 ++++++++++++++++++++++------ 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 964f72c1..270daf41 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -219,7 +219,7 @@ At most one configuration file is loaded: 1. If `SW_APM_CONFIG_RUBY` is set, only that file is used. If it can't be found, no configuration file is loaded; the agent doesn't fall back to the default locations. 2. Otherwise, the agent looks in the application root for `config/initializers/solarwinds_apm.rb` first and then `solarwinds_apm_config.rb`. The application root is `Rails.root` when it's available, then the directory of the Gemfile in use (`BUNDLE_GEMFILE`), and finally the current working directory. -Config files are executed as Ruby code with the application's privileges. The agent refuses to load a configuration file that is world-writable, or that is in a world-writable directory without the sticky bit. +Config files are executed as Ruby code with the application's privileges. The agent currently warns, but still loads, a configuration file that is world-writable or that is in a world-writable directory without the sticky bit. Refusal to load these files is planned for the next release; secure the file and directory permissions now. ## Configuration Topics diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index afa3a8ae..78edb95b 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -114,11 +114,12 @@ def self.app_root_dir def self.trusted_config_file?(config_file) file_stat = File.stat(config_file) - dir_stat = File.stat(File.dirname(File.expand_path(config_file))) + directories = [File.dirname(File.expand_path(config_file)), File.dirname(File.realpath(config_file))] + dir_stats = directories.uniq.map { |directory| File.stat(directory) } if file_stat.world_writable? reason = 'the file is world-writable' - elsif dir_stat.world_writable? && !dir_stat.sticky? + elsif dir_stats.any? { |stat| stat.world_writable? && !stat.sticky? } reason = 'its directory is world-writable' end diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 7ba5f1e6..f369ff31 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -682,22 +682,38 @@ def write_config(path, marker) _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_default' end - it 'refuses to load a world-writable config file' do + it 'warns but loads a world-writable config file' do File.chmod(0o666, @trusted) ENV['SW_APM_CONFIG_RUBY'] = @trusted - SolarWindsAPM::Config.load_config_file + warnings = [] + SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do + SolarWindsAPM::Config.load_config_file + end - assert SolarWindsAPM::Config[:config_file_marker] + expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n" \ + " The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n" \ + " Please change the permissions to make it secure.\n" \ + ' In next release, apm-ruby will refuse to load configuration files from an insecure path.' + assert_equal [expected_warning], warnings + assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] end - it 'refuses to load a config file in a world-writable non-sticky directory' do + it 'warns but loads a config file in a world-writable non-sticky directory' do File.chmod(0o777, File.dirname(@trusted)) ENV['SW_APM_CONFIG_RUBY'] = @trusted - SolarWindsAPM::Config.load_config_file + warnings = [] + SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do + SolarWindsAPM::Config.load_config_file + end - assert SolarWindsAPM::Config[:config_file_marker] + expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n" \ + " The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n" \ + " Please change the permissions to make it secure.\n" \ + ' In next release, apm-ruby will refuse to load configuration files from an insecure path.' + assert_equal [expected_warning], warnings + assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] end it 'loads a config file in a world-writable sticky directory' do From 066ec3dc573a153eee1dc2e1654b92219cfab89b Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Mon, 16 Nov 2026 12:09:06 -0500 Subject: [PATCH 03/11] lint --- test/solarwinds_apm/config_test.rb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index f369ff31..c3ca56b8 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -691,10 +691,10 @@ def write_config(path, marker) SolarWindsAPM::Config.load_config_file end - expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n" \ - " The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n" \ - " Please change the permissions to make it secure.\n" \ - ' In next release, apm-ruby will refuse to load configuration files from an insecure path.' + expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n " \ + "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ + "Please change the permissions to make it secure.\n " \ + 'In next release, apm-ruby will refuse to load configuration files from an insecure path.' assert_equal [expected_warning], warnings assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] end @@ -708,10 +708,10 @@ def write_config(path, marker) SolarWindsAPM::Config.load_config_file end - expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n" \ - " The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n" \ - " Please change the permissions to make it secure.\n" \ - ' In next release, apm-ruby will refuse to load configuration files from an insecure path.' + expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n " \ + "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ + "Please change the permissions to make it secure.\n " \ + 'In next release, apm-ruby will refuse to load configuration files from an insecure path.' assert_equal [expected_warning], warnings assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] end From a299eb658b541ba137c696d41d5fd7843764886e Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Wed, 18 Nov 2026 13:59:25 -0500 Subject: [PATCH 04/11] revision --- CONFIGURATION.md | 2 ++ lib/solarwinds_apm/config.rb | 9 +++++---- test/minitest_helper.rb | 2 +- test/patch/sw_mysql2_patch_integrate_test.rb | 3 +-- test/patch/sw_pg_patch_integrate_test.rb | 3 +-- test/sampling_test_helper.rb | 3 +-- test/solarwinds_apm/config_test.rb | 12 ++++++------ 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 270daf41..f0c172d6 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -221,6 +221,8 @@ At most one configuration file is loaded: Config files are executed as Ruby code with the application's privileges. The agent currently warns, but still loads, a configuration file that is world-writable or that is in a world-writable directory without the sticky bit. Refusal to load these files is planned for the next release; secure the file and directory permissions now. +> **Note:** This permission check relies on POSIX file permissions and **does not apply on Windows**, where file permission bits are not meaningful. Secure the configuration file with Windows ACLs instead. + ## Configuration Topics ### Transaction Filtering diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index 78edb95b..0957b42d 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -47,6 +47,7 @@ module Config # # Files that are world-writable, or that live in a world-writable directory # without the sticky bit, are refused. + # NOTE: This permission check relies on POSIX file permissions and does not apply on Windows. # def self.load_config_file config_file = explicit_config_path? ? config_file_from_env : default_config_file @@ -112,6 +113,7 @@ def self.app_root_dir Dir.pwd end + # Checks POSIX world-writable permissions only; this check does not apply on Windows. def self.trusted_config_file?(config_file) file_stat = File.stat(config_file) directories = [File.dirname(File.expand_path(config_file)), File.dirname(File.realpath(config_file))] @@ -123,17 +125,16 @@ def self.trusted_config_file?(config_file) reason = 'its directory is world-writable' end - # return true unless reason + return true unless reason if reason SolarWindsAPM.logger.warn do "[#{name}/#{__method__}] The configuration file #{config_file} is not trusted because #{reason}. The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600). - Please change the permissions to make it secure. - In next release, apm-ruby will refuse to load configuration files from an insecure path." + Please change the permissions to make it secure." end end - true + false rescue SystemCallError => e SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Unable to inspect configuration file #{config_file}: #{e.message}" } false diff --git a/test/minitest_helper.rb b/test/minitest_helper.rb index 998fb89b..f33170a4 100644 --- a/test/minitest_helper.rb +++ b/test/minitest_helper.rb @@ -54,7 +54,7 @@ def extract(carrier, context: ::OpenTelemetry::Context.current, getter: ::OpenTe # Dummy Exporter for testing module Exporter class Dummy - def flush(); end + def flush; end end end diff --git a/test/patch/sw_mysql2_patch_integrate_test.rb b/test/patch/sw_mysql2_patch_integrate_test.rb index 0715c703..ecf34909 100644 --- a/test/patch/sw_mysql2_patch_integrate_test.rb +++ b/test/patch/sw_mysql2_patch_integrate_test.rb @@ -12,13 +12,12 @@ require './lib/solarwinds_apm/support' require './lib/solarwinds_apm/patch/tag_sql/sw_dbo_utils' -# rubocop:disable Naming/MethodName +# rubocop:disable-next Naming/MethodName module SolarWindsAPM module Span def self.createSpan(trans_name, domain, span_time, has_error); end end end -# rubocop:enable Naming/MethodName describe 'mysql2 patch integrate test' do puts "\n\033[1m=== TEST RUN MYSQL2 PATCH TEST: #{RUBY_VERSION} #{File.basename(__FILE__)} #{Time.now.strftime('%Y-%m-%d %H:%M')} ===\033[0m\n" diff --git a/test/patch/sw_pg_patch_integrate_test.rb b/test/patch/sw_pg_patch_integrate_test.rb index 1fa58aa0..f423b8ee 100644 --- a/test/patch/sw_pg_patch_integrate_test.rb +++ b/test/patch/sw_pg_patch_integrate_test.rb @@ -12,13 +12,12 @@ require './lib/solarwinds_apm/support' require './lib/solarwinds_apm/patch/tag_sql/sw_dbo_utils' -# rubocop:disable Naming/MethodName +# rubocop:disable-next Naming/MethodName module SolarWindsAPM module Span def self.createSpan(trans_name, domain, span_time, has_error); end end end -# rubocop:enable Naming/MethodName def pg_dbo_integration_verification(sql, finished_spans) pattern = %r{/\*traceparent='[\da-f-]+'*\*/$} diff --git a/test/sampling_test_helper.rb b/test/sampling_test_helper.rb index 1fb5848b..e9ebb7ac 100644 --- a/test/sampling_test_helper.rb +++ b/test/sampling_test_helper.rb @@ -133,7 +133,7 @@ def check_counters(metric_exporter, counters = []) end end -# rubocop:disable Lint/DuplicateMethods +# rubocop:disable-next Lint/DuplicateMethods class OboeTestSampler < SolarWindsAPM::OboeSampler attr_accessor :response_headers, :local_settings, :request_headers @@ -155,7 +155,6 @@ def request_headers(_params) @request_headers end end -# rubocop:enable Lint/DuplicateMethods def replace_sampler(sampler) OpenTelemetry.tracer_provider.sampler = OpenTelemetry::SDK::Trace::Samplers.parent_based( diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index c3ca56b8..b27b2ec0 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -693,10 +693,10 @@ def write_config(path, marker) expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n " \ "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ - "Please change the permissions to make it secure.\n " \ - 'In next release, apm-ruby will refuse to load configuration files from an insecure path.' + 'Please change the permissions to make it secure.' + assert_equal [expected_warning], warnings - assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] + assert_nil SolarWindsAPM::Config[:config_file_marker] end it 'warns but loads a config file in a world-writable non-sticky directory' do @@ -710,10 +710,10 @@ def write_config(path, marker) expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n " \ "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ - "Please change the permissions to make it secure.\n " \ - 'In next release, apm-ruby will refuse to load configuration files from an insecure path.' + 'Please change the permissions to make it secure.' + assert_equal [expected_warning], warnings - assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] + assert_nil SolarWindsAPM::Config[:config_file_marker] end it 'loads a config file in a world-writable sticky directory' do From 485f114ab11193b2a3a2d62af1173b4cea0c244e Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Thu, 19 Nov 2026 11:52:42 -0500 Subject: [PATCH 05/11] update test and doc --- CONFIGURATION.md | 2 +- test/solarwinds_apm/config_test.rb | 34 ------------------------------ 2 files changed, 1 insertion(+), 35 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index f0c172d6..f849256f 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -219,7 +219,7 @@ At most one configuration file is loaded: 1. If `SW_APM_CONFIG_RUBY` is set, only that file is used. If it can't be found, no configuration file is loaded; the agent doesn't fall back to the default locations. 2. Otherwise, the agent looks in the application root for `config/initializers/solarwinds_apm.rb` first and then `solarwinds_apm_config.rb`. The application root is `Rails.root` when it's available, then the directory of the Gemfile in use (`BUNDLE_GEMFILE`), and finally the current working directory. -Config files are executed as Ruby code with the application's privileges. The agent currently warns, but still loads, a configuration file that is world-writable or that is in a world-writable directory without the sticky bit. Refusal to load these files is planned for the next release; secure the file and directory permissions now. +Config files are executed as Ruby code with the application's privileges. The agent refuses to load, and logs a warning for, a configuration file that is world-writable or that is in a world-writable directory without the sticky bit. Secure the file and directory permissions (e.g. file permission `600`) so the file is loaded. > **Note:** This permission check relies on POSIX file permissions and **does not apply on Windows**, where file permission bits are not meaningful. Secure the configuration file with Windows ACLs instead. diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index b27b2ec0..cd38ce25 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -682,40 +682,6 @@ def write_config(path, marker) _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_default' end - it 'warns but loads a world-writable config file' do - File.chmod(0o666, @trusted) - ENV['SW_APM_CONFIG_RUBY'] = @trusted - - warnings = [] - SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do - SolarWindsAPM::Config.load_config_file - end - - expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n " \ - "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ - 'Please change the permissions to make it secure.' - - assert_equal [expected_warning], warnings - assert_nil SolarWindsAPM::Config[:config_file_marker] - end - - it 'warns but loads a config file in a world-writable non-sticky directory' do - File.chmod(0o777, File.dirname(@trusted)) - ENV['SW_APM_CONFIG_RUBY'] = @trusted - - warnings = [] - SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do - SolarWindsAPM::Config.load_config_file - end - - expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n " \ - "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ - 'Please change the permissions to make it secure.' - - assert_equal [expected_warning], warnings - assert_nil SolarWindsAPM::Config[:config_file_marker] - end - it 'loads a config file in a world-writable sticky directory' do File.chmod(0o1777, File.dirname(@trusted)) ENV['SW_APM_CONFIG_RUBY'] = @trusted From 213507c9b08dc6c42cc77dd2ce498a0691f53a0f Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Fri, 20 Nov 2026 10:18:46 -0500 Subject: [PATCH 06/11] revert get tests case back --- test/solarwinds_apm/config_test.rb | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index cd38ce25..5d2fa293 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -682,6 +682,40 @@ def write_config(path, marker) _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_default' end + it 'reject to load a world-writable config file' do + File.chmod(0o666, @trusted) + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + warnings = [] + SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do + SolarWindsAPM::Config.load_config_file + end + + expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n " \ + "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ + 'Please change the permissions to make it secure.' + + assert_equal [expected_warning], warnings + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + + it 'reject to load a config file in a world-writable non-sticky directory' do + File.chmod(0o777, File.dirname(@trusted)) + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + warnings = [] + SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do + SolarWindsAPM::Config.load_config_file + end + + expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n " \ + "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ + 'Please change the permissions to make it secure.' + + assert_equal [expected_warning], warnings + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + it 'loads a config file in a world-writable sticky directory' do File.chmod(0o1777, File.dirname(@trusted)) ENV['SW_APM_CONFIG_RUBY'] = @trusted From 1e56e9912705b25d054046fa34a524881651d6ff Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Mon, 23 Nov 2026 13:42:59 -0500 Subject: [PATCH 07/11] update the file path discovery --- CONFIGURATION.md | 30 +++- lib/solarwinds_apm/config.rb | 123 +++++--------- lib/solarwinds_apm/support/secure_path.rb | 69 ++++++++ test/solarwinds_apm/config_test.rb | 166 ++++++++++--------- test/solarwinds_apm/solarwinds_apm_config.rb | 4 - test/support/secure_path_test.rb | 119 +++++++++++++ 6 files changed, 335 insertions(+), 176 deletions(-) create mode 100644 lib/solarwinds_apm/support/secure_path.rb delete mode 100644 test/solarwinds_apm/solarwinds_apm_config.rb create mode 100644 test/support/secure_path_test.rb diff --git a/CONFIGURATION.md b/CONFIGURATION.md index f849256f..651e46ae 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -195,18 +195,24 @@ This creates `config/initializers/solarwinds_apm.rb` with documented configurati #### Non-Rails Applications -Create a file named `solarwinds_apm_config.rb` in your application's root directory: +Create the configuration file anywhere (for example `/etc/solarwinds_apm/config.rb`) and set `SW_APM_CONFIG_RUBY` to its **absolute** path: ```ruby -# solarwinds_apm_config.rb +# /etc/solarwinds_apm/config.rb SolarWindsAPM::Config[:service_key] = 'your-token:your-service' SolarWindsAPM::Config[:debug_level] = 3 SolarWindsAPM::Config[:tag_sql] = true ``` +```bash +export SW_APM_CONFIG_RUBY=/etc/solarwinds_apm/config.rb +``` + +Configuration files are not auto-discovered for non-Rails applications. A `solarwinds_apm_config.rb` in the current working directory isn't loaded; the agent logs a warning instead. + #### Custom Location -Override the default configuration file location: +Rails applications can also use a different file by setting `SW_APM_CONFIG_RUBY` to its absolute path: ```bash export SW_APM_CONFIG_RUBY=/path/to/your/config.rb @@ -216,12 +222,20 @@ export SW_APM_CONFIG_RUBY=/path/to/your/config.rb At most one configuration file is loaded: -1. If `SW_APM_CONFIG_RUBY` is set, only that file is used. If it can't be found, no configuration file is loaded; the agent doesn't fall back to the default locations. -2. Otherwise, the agent looks in the application root for `config/initializers/solarwinds_apm.rb` first and then `solarwinds_apm_config.rb`. The application root is `Rails.root` when it's available, then the directory of the Gemfile in use (`BUNDLE_GEMFILE`), and finally the current working directory. +1. If `SW_APM_CONFIG_RUBY` is set, only that file is used. It must be an absolute path to a file. A relative path, a directory, or a missing file means no configuration file is loaded, and the agent doesn't fall back to the Rails initializer. +2. Otherwise, for Rails applications only, the agent loads `config/initializers/solarwinds_apm.rb` from the Rails application root. The root is `Rails.root` when it's available, or the directory of the absolute `BUNDLE_GEMFILE` set by the Rails `config/boot.rb`. The current working directory is never searched. + +### Config File Security + +Config files are executed as Ruby code with the application's privileges. On POSIX systems (Linux, macOS), the agent refuses to load a configuration file, and logs a warning, if: + +- the file is world-writable, +- the file isn't owned by `root` or by the effective user running the application, or +- the file is in a world-writable directory without the sticky bit. -Config files are executed as Ruby code with the application's privileges. The agent refuses to load, and logs a warning for, a configuration file that is world-writable or that is in a world-writable directory without the sticky bit. Secure the file and directory permissions (e.g. file permission `600`) so the file is loaded. +Secure the file's ownership and permissions (e.g. owned by the application user with file permission `600`) so the file is loaded. -> **Note:** This permission check relies on POSIX file permissions and **does not apply on Windows**, where file permission bits are not meaningful. Secure the configuration file with Windows ACLs instead. +> **Note:** On non-POSIX systems (Windows), file permission bits aren't meaningful, so the agent skips these checks. Secure the configuration file with Windows ACLs instead. ## Configuration Topics @@ -325,7 +339,7 @@ export SW_APM_TRANSACTION_NAME=my-lambda-function | -------------------- | --------------- | ----------- | ------- | | `SW_APM_AUTO_CONFIGURE` | N/A | By default the library is configured to work out-of-the-box with all automatic instrumentation libraries enabled. Set this to `false` to custom initialize the library with configuration options for instrumentation, see [Programmatic Configuration](#programmatic-configuration) for details. | `true` | | `SW_APM_COLLECTOR` | N/A | Override the default collector endpoint to which the library connects and exports data. It should be defined using the format host:port. | `apm.collector.na-01.cloud.solarwinds.com:443` | -| `SW_APM_CONFIG_RUBY` | N/A | Override the default location for the configuration file. This can be an absolute or relative filename, or the directory under which the `solarwinds_apm_config.rb` file would be looked for. When set, default locations are not searched. | None | +| `SW_APM_CONFIG_RUBY` | N/A | Absolute path of the configuration file. Required to load a configuration file in non-Rails applications. Relative paths and directories are rejected. When set, the Rails initializer location is not searched. | None | | `SW_APM_DEBUG_LEVEL` | `:debug_level` | Set the library's logging level, valid values are -1 through 6 (least to most verbose).
Setting -1 disables logging from the library. | 3 | | `SW_APM_ENABLED` | N/A | Enable/disable the library, setting `false` is an alternative to uninstalling `solarwinds_apm` since it will prevent the library from loading. | `true` | | `SW_APM_SERVICE_KEY` | `:service_key` | API token and service name in the form of `token:service_name`, **required**. | None | diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index 0957b42d..d76c4da7 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -7,6 +7,7 @@ # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. require 'set' +require_relative 'support/secure_path' module SolarWindsAPM ## @@ -28,7 +29,7 @@ module Config @@config = {} RAILS_CONFIG_FILE = 'config/initializers/solarwinds_apm.rb' - DEFAULT_CONFIG_FILE = 'solarwinds_apm_config.rb' + LEGACY_CONFIG_FILE = 'solarwinds_apm_config.rb' ## # load_config_file @@ -38,108 +39,66 @@ module Config # e.g. ENV['SW_APM_SERVICE_KEY'] || SolarWindsAPM::Config[:service_key] # # Selection: - # 1 - If ENV['SW_APM_CONFIG_RUBY'] is set, only that file is considered. - # If it can't be found, no other location is probed (fail closed). - # 2 - Otherwise, look in the application root (see app_root_dir) for: - # a - Rails default: config/initializers/solarwinds_apm.rb - # (also loaded by Rails, but we can't reliably determine if Rails is running) - # b - Gem default: solarwinds_apm_config.rb + # 1 - If ENV['SW_APM_CONFIG_RUBY'] is set, it must be the absolute path of the config file. + # If it is relative or can't be found, no other location is probed (fail closed). + # 2 - Otherwise, only for Rails applications, the prescribed Rails initializer + # /config/initializers/solarwinds_apm.rb (also loaded later by Rails itself). # - # Files that are world-writable, or that live in a world-writable directory - # without the sticky bit, are refused. - # NOTE: This permission check relies on POSIX file permissions and does not apply on Windows. + # The selected file is loaded only if SolarWindsAPM::SecurePath.trusted? accepts it. # def self.load_config_file - config_file = explicit_config_path? ? config_file_from_env : default_config_file - - load(config_file) if config_file && trusted_config_file?(config_file) - - set_log_level # sets SolarWindsAPM::Config[:debug_level], SolarWindsAPM.logger.level - end - - def self.explicit_config_path? - !ENV.fetch('SW_APM_CONFIG_RUBY', '').strip.empty? - end - - def self.config_file_from_env env_path = ENV.fetch('SW_APM_CONFIG_RUBY', '').strip + config_file = env_path.empty? ? rails_config_file : config_file_from_env(env_path) + load(config_file) if config_file - if !env_path.empty? && File.file?(env_path) - config_file = env_path - elsif !env_path.empty? && File.file?(File.join(env_path, DEFAULT_CONFIG_FILE)) - config_file = File.join(env_path, DEFAULT_CONFIG_FILE) - else - SolarWindsAPM.logger.warn do - "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." - end - end - config_file + set_log_level # sets SolarWindsAPM::Config[:debug_level], SolarWindsAPM.logger.level end - def self.default_config_file - base_dir = app_root_dir - config_files = [RAILS_CONFIG_FILE, DEFAULT_CONFIG_FILE].map { |file| File.join(base_dir, file) } - .select { |file| File.file?(file) } - - SolarWindsAPM.logger.debug { "[#{name}/#{__method__}] Available config_files: #{config_files.join(', ')}" } - if config_files.size > 1 - SolarWindsAPM.logger.warn do - "[#{name}/#{__method__}] Multiple configuration files configured, using the first one listed: #{config_files.join(', ')}" + def self.config_file_from_env(env_path) + if File.absolute_path?(env_path) + if File.file?(env_path) && SolarWindsAPM::SecurePath.trusted?(env_path) + return env_path + else + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." } end + else + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] SW_APM_CONFIG_RUBY must be the absolute path of the configuration file (current setting is #{env_path}). No configuration file will be loaded." } end - config_files.first + nil end ## - # app_root_dir + # rails_config_file # - # Directory used to resolve the default config file locations, in order: - # Rails.root (if the Rails application is already defined), - # the directory of the Gemfile in use (BUNDLE_GEMFILE, set by bundler and by Rails' config/boot.rb), - # and finally the current working directory. + # Path of /config/initializers/solarwinds_apm.rb, or nil when Rails is not loaded, + # its root can't be determined, or the file doesn't exist. + # When the gem is required by Bundler.require, the Rails application class isn't defined yet + # (Rails.root is nil), so fall back to the directory of the Gemfile that Rails' config/boot.rb + # sets in BUNDLE_GEMFILE. Only an absolute BUNDLE_GEMFILE is used, never the current directory. # - def self.app_root_dir + def self.rails_config_file + rails_root = '' if defined?(::Rails) && ::Rails.respond_to?(:root) rails_root = ::Rails.root.to_s - return rails_root unless rails_root.empty? - end - - gemfile = ENV.fetch('BUNDLE_GEMFILE', '').strip - return File.dirname(File.expand_path(gemfile)) unless gemfile.empty? - - Dir.pwd - rescue StandardError => e - SolarWindsAPM.logger.debug { "[#{name}/#{__method__}] Failed to determine application root: #{e.message}" } - Dir.pwd - end - - # Checks POSIX world-writable permissions only; this check does not apply on Windows. - def self.trusted_config_file?(config_file) - file_stat = File.stat(config_file) - directories = [File.dirname(File.expand_path(config_file)), File.dirname(File.realpath(config_file))] - dir_stats = directories.uniq.map { |directory| File.stat(directory) } + gemfile = ENV.fetch('BUNDLE_GEMFILE', '').strip + rails_root = File.dirname(gemfile) if rails_root.empty? && File.absolute_path?(gemfile) - if file_stat.world_writable? - reason = 'the file is world-writable' - elsif dir_stats.any? { |stat| stat.world_writable? && !stat.sticky? } - reason = 'its directory is world-writable' + if rails_root.empty? + legacy_file = File.join(Dir.pwd, LEGACY_CONFIG_FILE) + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Set SW_APM_CONFIG_RUBY to its absolute path to load it. Legacy file #{LEGACY_CONFIG_FILE} is no longer loaded." } if File.file?(legacy_file) + return nil + end end - return true unless reason + config_file = File.join(rails_root, RAILS_CONFIG_FILE) + return config_file if File.file?(config_file) - if reason - SolarWindsAPM.logger.warn do - "[#{name}/#{__method__}] The configuration file #{config_file} is not trusted because #{reason}. - The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600). - Please change the permissions to make it secure." - end - end - false - rescue SystemCallError => e - SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Unable to inspect configuration file #{config_file}: #{e.message}" } - false + SolarWindsAPM.logger.debug { "[#{name}/#{__method__}] Rails configuration file #{config_file} not found." } + nil + rescue StandardError => e + SolarWindsAPM.logger.debug { "[#{name}/#{__method__}] Failed to determine Rails root: #{e.message}" } + nil end - private_class_method :explicit_config_path?, :default_config_file, :app_root_dir, :trusted_config_file? def self.set_log_level log_level = (ENV['SW_APM_DEBUG_LEVEL'] || SolarWindsAPM::Config[:debug_level] || 3).to_i diff --git a/lib/solarwinds_apm/support/secure_path.rb b/lib/solarwinds_apm/support/secure_path.rb new file mode 100644 index 00000000..156e9a76 --- /dev/null +++ b/lib/solarwinds_apm/support/secure_path.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +# © 2026 SolarWinds Worldwide, LLC. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at:http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + +module SolarWindsAPM + ## + # SecurePath + # + # Verifies that a file is safe to execute (e.g. load as Ruby code) with the application's privileges. + # + # On POSIX systems, a file is untrusted if it is world-writable, is not owned by root or by the + # effective user of this process, or lives in a world-writable directory without the sticky bit. + # Permission checks are skipped on Windows, where POSIX permission bits are not meaningful. + # + module SecurePath + ## + # trusted? + # + # === Argument: + # + # * +path+ - Path of the file to verify + # + # === Example: + # + # load(config_file) if SolarWindsAPM::SecurePath.trusted?(config_file) + # + # === Returns: + # * Boolean - true if the file can be trusted; false otherwise (a warning with the reason is logged) + # + def self.trusted?(path) + return true if Gem.win_platform? + + reason = untrusted_reason(path) + return true unless reason + + SolarWindsAPM.logger.warn do + "[#{name}/#{__method__}] The file #{path} is not trusted because #{reason}. " \ + 'The file must be owned by root or by the user running the application, and neither the file nor its directory may be world-writable (e.g. file permission 600). ' \ + 'Please change the ownership or permissions to make it secure.' + end + false + rescue SystemCallError => e + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Unable to inspect file #{path}: #{e.message}" } + false + end + + def self.untrusted_reason(path) + file_stat = File.stat(path) + return 'the file is world-writable' if file_stat.world_writable? + + euid = Process.euid + return "the file is owned by uid #{file_stat.uid}, not by root or the effective user (uid #{euid})" unless [0, euid].include?(file_stat.uid) + + # Check both the given directory and the symlink-resolved one. + directories = [File.dirname(File.expand_path(path)), File.dirname(File.realpath(path))].uniq + 'its directory is world-writable' if directories.any? { |directory| insecure_directory?(directory) } + end + + def self.insecure_directory?(directory) + dir_stat = File.stat(directory) + dir_stat.world_writable? && !dir_stat.sticky? + end + private_class_method :untrusted_reason, :insecure_directory? + end +end diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 5d2fa293..182c7d81 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -15,28 +15,33 @@ ENV.delete('SW_APM_CONFIG_RUBY') end - it 'with empty SW_APM_CONFIG_RUBY should return nil' do - ENV['SW_APM_CONFIG_RUBY'] = 'tmp/' - config_file = SolarWindsAPM::Config.config_file_from_env - assert_nil(config_file) + it 'returns the absolute path of an existing file' do + config_path = File.expand_path('lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb') + ENV['SW_APM_CONFIG_RUBY'] = config_path + assert_equal config_path, SolarWindsAPM::Config.config_file_from_env end - it 'with correct SW_APM_CONFIG_RUBY should return file' do + it 'rejects a relative path even if the file exists' do ENV['SW_APM_CONFIG_RUBY'] = 'lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb' - config_file = SolarWindsAPM::Config.config_file_from_env - _(config_file).must_equal 'lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb' + + warnings = [] + SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do + assert_nil SolarWindsAPM::Config.config_file_from_env + end + + assert_equal ['[SolarWindsAPM::Config/config_file_from_env] SW_APM_CONFIG_RUBY must be the absolute path of the configuration file ' \ + '(current setting is lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb). No configuration file will be loaded.'], + warnings end - it 'with correct SW_APM_CONFIG_RUBY path should return file path' do - ENV['SW_APM_CONFIG_RUBY'] = 'test/solarwinds_apm/' - config_file = SolarWindsAPM::Config.config_file_from_env - _(config_file).must_equal 'test/solarwinds_apm/solarwinds_apm_config.rb' + it 'rejects a directory instead of searching it for a config file' do + ENV['SW_APM_CONFIG_RUBY'] = File.expand_path('lib/rails/generators/solarwinds_apm/templates') + assert_nil SolarWindsAPM::Config.config_file_from_env end - it 'with incorrect SW_APM_CONFIG_RUBY path should return nil' do - ENV['SW_APM_CONFIG_RUBY'] = 'test/opentelemetry/' - config_file = SolarWindsAPM::Config.config_file_from_env - assert_nil(config_file) + it 'returns nil for a non-existent absolute path' do + ENV['SW_APM_CONFIG_RUBY'] = '/nonexistent/path/file.rb' + assert_nil SolarWindsAPM::Config.config_file_from_env end end @@ -585,21 +590,6 @@ end end - describe 'config_file_from_env' do - it 'returns nil for non-existent file' do - original = ENV.fetch('SW_APM_CONFIG_RUBY', nil) - ENV['SW_APM_CONFIG_RUBY'] = '/nonexistent/path/file.rb' - result = SolarWindsAPM::Config.config_file_from_env - assert_nil result - ensure - if original - ENV['SW_APM_CONFIG_RUBY'] = original - else - ENV.delete('SW_APM_CONFIG_RUBY') - end - end - end - describe '#load_config_file' do def write_config(path, marker) FileUtils.mkdir_p(File.dirname(path)) @@ -608,6 +598,23 @@ def write_config(path, marker) path end + def capture_logs(level, &test_block) + messages = [] + SolarWindsAPM.logger.stub(level, ->(message = nil, &block) { messages << (block ? block.call : message) }, &test_block) + messages + end + + def with_rails_root(root) + original_rails = Object.send(:remove_const, :Rails) if defined?(Rails) + rails = Module.new + rails.define_singleton_method(:root) { root } + Object.const_set(:Rails, rails) + yield + ensure + Object.send(:remove_const, :Rails) + Object.const_set(:Rails, original_rails) if original_rails + end + before do @original_env = ENV.to_h.slice('SW_APM_CONFIG_RUBY', 'BUNDLE_GEMFILE') ENV.delete('SW_APM_CONFIG_RUBY') @@ -626,103 +633,98 @@ def write_config(path, marker) SolarWindsAPM::Config[:config_file_marker] = nil end - it 'loads only SW_APM_CONFIG_RUBY even when a cwd rails initializer exists' do - write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') - write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + it 'loads only SW_APM_CONFIG_RUBY even when a rails initializer exists' do + write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') ENV['SW_APM_CONFIG_RUBY'] = @trusted - Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } - _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'trusted' + assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] end - it 'does not fall back to cwd files when SW_APM_CONFIG_RUBY is missing' do - write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') - ENV['SW_APM_CONFIG_RUBY'] = File.join(@tmpdir, 'missing.rb') + it 'does not load a relative SW_APM_CONFIG_RUBY resolved against cwd' do + write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + ENV['SW_APM_CONFIG_RUBY'] = 'solarwinds_apm_config.rb' Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } assert_nil SolarWindsAPM::Config[:config_file_marker] end - it 'resolves default files against the Gemfile directory instead of cwd' do - write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + it 'does not fall back to other files when SW_APM_CONFIG_RUBY is missing' do write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') - ENV['BUNDLE_GEMFILE'] = File.join(@app_dir, 'Gemfile') + ENV['SW_APM_CONFIG_RUBY'] = File.join(@tmpdir, 'missing.rb') - Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } - _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'app_rails' + assert_nil SolarWindsAPM::Config[:config_file_marker] end - it 'does not load a cwd file outside the Gemfile directory' do + it 'does not auto-discover config files in cwd for non-Rails applications' do write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') - ENV['BUNDLE_GEMFILE'] = File.join(@app_dir, 'Gemfile') + write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + ENV['BUNDLE_GEMFILE'] = File.join(@cwd, 'Gemfile') - Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + warnings = capture_logs(:warn) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } assert_nil SolarWindsAPM::Config[:config_file_marker] + assert_equal ['[SolarWindsAPM::Config/warn_legacy_config_file] Set SW_APM_CONFIG_RUBY to its absolute path to load it. ' \ + 'Legacy file solarwinds_apm_config.rb is no longer loaded.'], + warnings end - it 'falls back to cwd when no application root is known, preferring the rails initializer' do + it 'loads the rails initializer from Rails.root instead of cwd' do write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') - write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') - Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + with_rails_root(@app_dir) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } - _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_rails' + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] end - it 'treats an empty SW_APM_CONFIG_RUBY as unset' do - write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') - ENV['SW_APM_CONFIG_RUBY'] = '' + it 'does not load the gem default file from the Rails root' do + write_config(File.join(@app_dir, 'solarwinds_apm_config.rb'), 'app_default') - Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } - _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'cwd_default' + assert_nil SolarWindsAPM::Config[:config_file_marker] end - it 'reject to load a world-writable config file' do - File.chmod(0o666, @trusted) - ENV['SW_APM_CONFIG_RUBY'] = @trusted + it 'resolves the rails root from an absolute BUNDLE_GEMFILE before the application is defined' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') + ENV['BUNDLE_GEMFILE'] = File.join(@app_dir, 'Gemfile') - warnings = [] - SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do - SolarWindsAPM::Config.load_config_file - end + with_rails_root(nil) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } + + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] + end + + it 'does not resolve the rails root from a relative BUNDLE_GEMFILE' do + write_config(File.join(@cwd, 'config/initializers/solarwinds_apm.rb'), 'cwd_rails') + ENV['BUNDLE_GEMFILE'] = 'Gemfile' - expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because the file is world-writable.\n " \ - "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ - 'Please change the permissions to make it secure.' + with_rails_root(nil) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } - assert_equal [expected_warning], warnings assert_nil SolarWindsAPM::Config[:config_file_marker] end - it 'reject to load a config file in a world-writable non-sticky directory' do - File.chmod(0o777, File.dirname(@trusted)) - ENV['SW_APM_CONFIG_RUBY'] = @trusted - - warnings = [] - SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do - SolarWindsAPM::Config.load_config_file - end + it 'treats an empty SW_APM_CONFIG_RUBY as unset' do + write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') + ENV['SW_APM_CONFIG_RUBY'] = '' - expected_warning = "[SolarWindsAPM::Config/trusted_config_file?] The configuration file #{@trusted} is not trusted because its directory is world-writable.\n " \ - "The configuration file must come from a secure path: the file and its directory must not be world-writable (e.g. file permission 600).\n " \ - 'Please change the permissions to make it secure.' + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } - assert_equal [expected_warning], warnings - assert_nil SolarWindsAPM::Config[:config_file_marker] + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] end - it 'loads a config file in a world-writable sticky directory' do - File.chmod(0o1777, File.dirname(@trusted)) + it 'does not load a config file rejected by SecurePath' do + File.chmod(0o666, @trusted) ENV['SW_APM_CONFIG_RUBY'] = @trusted SolarWindsAPM::Config.load_config_file - _(SolarWindsAPM::Config[:config_file_marker]).must_equal 'trusted' + assert_nil SolarWindsAPM::Config[:config_file_marker] end end diff --git a/test/solarwinds_apm/solarwinds_apm_config.rb b/test/solarwinds_apm/solarwinds_apm_config.rb deleted file mode 100644 index cbd9d901..00000000 --- a/test/solarwinds_apm/solarwinds_apm_config.rb +++ /dev/null @@ -1,4 +0,0 @@ -# frozen_string_literal: true - -# this is file for config_test.rb:with correct SW_APM_CONFIG_RUBY path should return file path -# diff --git a/test/support/secure_path_test.rb b/test/support/secure_path_test.rb new file mode 100644 index 00000000..1e37929e --- /dev/null +++ b/test/support/secure_path_test.rb @@ -0,0 +1,119 @@ +# frozen_string_literal: true + +# Copyright (c) 2026 SolarWinds, LLC. +# All rights reserved. + +require 'minitest_helper' +require 'tmpdir' +require 'fileutils' +require 'delegate' +require './lib/solarwinds_apm/support/secure_path' + +describe 'SolarWindsAPM::SecurePath' do + def capture_warnings(&test_block) + warnings = [] + SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }, &test_block) + warnings + end + + # CI runs tests as root, so fake the owner/effective user instead of relying on real file ownership. + def with_file_owner(path, uid, euid, &test_block) + original_stat = File.method(:stat) + owned_stat = SimpleDelegator.new(original_stat.call(path)) + owned_stat.define_singleton_method(:uid) { uid } + stat_stub = ->(file) { file == path ? owned_stat : original_stat.call(file) } + Process.stub(:euid, euid) { File.stub(:stat, stat_stub, &test_block) } + end + + def untrusted_warning(path, reason) + "[SolarWindsAPM::SecurePath/trusted?] The file #{path} is not trusted because #{reason}. " \ + 'The file must be owned by root or by the user running the application, and neither the file nor its directory may be world-writable (e.g. file permission 600). ' \ + 'Please change the ownership or permissions to make it secure.' + end + + before do + @tmpdir = File.realpath(Dir.mktmpdir('sw_apm_secure_path')) + @dir = File.join(@tmpdir, 'secure').tap { |d| FileUtils.mkdir_p(d) } + @file = File.join(@dir, 'config.rb') + File.write(@file, "# config\n") + File.chmod(0o644, @file) + end + + after do + FileUtils.rm_rf(@tmpdir) + end + + it 'trusts a file owned by the current user that is not world-writable' do + assert SolarWindsAPM::SecurePath.trusted?(@file) + end + + it 'rejects a world-writable file' do + File.chmod(0o666, @file) + + warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(@file) } + + assert_equal [untrusted_warning(@file, 'the file is world-writable')], warnings + end + + it 'rejects a file in a world-writable non-sticky directory' do + File.chmod(0o777, @dir) + + warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(@file) } + + assert_equal [untrusted_warning(@file, 'its directory is world-writable')], warnings + end + + it 'rejects a symlink whose target is in a world-writable non-sticky directory' do + unsafe_dir = File.join(@tmpdir, 'unsafe').tap { |d| FileUtils.mkdir_p(d) } + target = File.join(unsafe_dir, 'config.rb') + File.write(target, "# config\n") + File.chmod(0o644, target) + File.chmod(0o777, unsafe_dir) + link = File.join(@dir, 'link.rb') + File.symlink(target, link) + + warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(link) } + + assert_equal [untrusted_warning(link, 'its directory is world-writable')], warnings + end + + it 'trusts a file in a world-writable sticky directory' do + File.chmod(0o1777, @dir) + + assert SolarWindsAPM::SecurePath.trusted?(@file) + end + + it 'rejects a file owned by a user other than root or the effective user' do + warnings = capture_warnings do + with_file_owner(@file, 4242, 1000) { refute SolarWindsAPM::SecurePath.trusted?(@file) } + end + + assert_equal [untrusted_warning(@file, 'the file is owned by uid 4242, not by root or the effective user (uid 1000)')], warnings + end + + it 'trusts a file owned by the effective user' do + with_file_owner(@file, 1000, 1000) { assert SolarWindsAPM::SecurePath.trusted?(@file) } + end + + it 'trusts a file owned by root' do + with_file_owner(@file, 0, 1000) { assert SolarWindsAPM::SecurePath.trusted?(@file) } + end + + it 'rejects a file that cannot be inspected' do + missing = File.join(@dir, 'missing.rb') + + warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(missing) } + + assert_equal ["[SolarWindsAPM::SecurePath/trusted?] Unable to inspect file #{missing}: No such file or directory @ rb_file_s_stat - #{missing}"], warnings + end + + it 'skips permission checks on Windows' do + File.chmod(0o666, @file) + + warnings = capture_warnings do + Gem.stub(:win_platform?, true) { assert SolarWindsAPM::SecurePath.trusted?(@file) } + end + + assert_empty warnings + end +end From 1944e0dc88a8652e30dc127e7ecaecd26a67ba38 Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Mon, 23 Nov 2026 14:11:31 -0500 Subject: [PATCH 08/11] update test --- lib/solarwinds_apm/config.rb | 8 +++----- test/solarwinds_apm/config_test.rb | 29 +++++++++++++++-------------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index d76c4da7..c3b1c83e 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -56,11 +56,9 @@ def self.load_config_file def self.config_file_from_env(env_path) if File.absolute_path?(env_path) - if File.file?(env_path) && SolarWindsAPM::SecurePath.trusted?(env_path) - return env_path - else - SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." } - end + return env_path if File.file?(env_path) && SolarWindsAPM::SecurePath.trusted?(env_path) + + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." } else SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] SW_APM_CONFIG_RUBY must be the absolute path of the configuration file (current setting is #{env_path}). No configuration file will be loaded." } end diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 182c7d81..1ec3dc7b 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -11,22 +11,17 @@ describe 'Config Test' do describe '#config_file_from_env' do - after do - ENV.delete('SW_APM_CONFIG_RUBY') - end - it 'returns the absolute path of an existing file' do config_path = File.expand_path('lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb') - ENV['SW_APM_CONFIG_RUBY'] = config_path - assert_equal config_path, SolarWindsAPM::Config.config_file_from_env + assert_equal config_path, SolarWindsAPM::Config.config_file_from_env(config_path) end it 'rejects a relative path even if the file exists' do - ENV['SW_APM_CONFIG_RUBY'] = 'lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb' + relative_path = 'lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb' warnings = [] SolarWindsAPM.logger.stub(:warn, ->(message = nil, &block) { warnings << (block ? block.call : message) }) do - assert_nil SolarWindsAPM::Config.config_file_from_env + assert_nil SolarWindsAPM::Config.config_file_from_env(relative_path) end assert_equal ['[SolarWindsAPM::Config/config_file_from_env] SW_APM_CONFIG_RUBY must be the absolute path of the configuration file ' \ @@ -35,13 +30,11 @@ end it 'rejects a directory instead of searching it for a config file' do - ENV['SW_APM_CONFIG_RUBY'] = File.expand_path('lib/rails/generators/solarwinds_apm/templates') - assert_nil SolarWindsAPM::Config.config_file_from_env + assert_nil SolarWindsAPM::Config.config_file_from_env(File.expand_path('lib/rails/generators/solarwinds_apm/templates')) end it 'returns nil for a non-existent absolute path' do - ENV['SW_APM_CONFIG_RUBY'] = '/nonexistent/path/file.rb' - assert_nil SolarWindsAPM::Config.config_file_from_env + assert_nil SolarWindsAPM::Config.config_file_from_env('/nonexistent/path/file.rb') end end @@ -665,10 +658,18 @@ def with_rails_root(root) write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') ENV['BUNDLE_GEMFILE'] = File.join(@cwd, 'Gemfile') - warnings = capture_logs(:warn) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } + Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + + it 'warns about a legacy cwd config file when the Rails root cannot be determined' do + write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') + + warnings = capture_logs(:warn) { with_rails_root(nil) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } } assert_nil SolarWindsAPM::Config[:config_file_marker] - assert_equal ['[SolarWindsAPM::Config/warn_legacy_config_file] Set SW_APM_CONFIG_RUBY to its absolute path to load it. ' \ + assert_equal ['[SolarWindsAPM::Config/rails_config_file] Set SW_APM_CONFIG_RUBY to its absolute path to load it. ' \ 'Legacy file solarwinds_apm_config.rb is no longer loaded.'], warnings end From ab5c7c4ce28d78266f7604d64714c7b86a71c8db Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Mon, 23 Nov 2026 14:21:32 -0500 Subject: [PATCH 09/11] update --- CONFIGURATION.md | 4 +++- lib/solarwinds_apm/config.rb | 23 ++++++++++++----------- test/solarwinds_apm/config_test.rb | 26 ++++++++++++++++++++++++-- 3 files changed, 39 insertions(+), 14 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 651e46ae..2e36841c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -227,7 +227,7 @@ At most one configuration file is loaded: ### Config File Security -Config files are executed as Ruby code with the application's privileges. On POSIX systems (Linux, macOS), the agent refuses to load a configuration file, and logs a warning, if: +Config files are executed as Ruby code with the application's privileges. On POSIX systems (Linux, macOS), the agent refuses to load the file set by `SW_APM_CONFIG_RUBY`, and logs a warning, if: - the file is world-writable, - the file isn't owned by `root` or by the effective user running the application, or @@ -235,6 +235,8 @@ Config files are executed as Ruby code with the application's privileges. On POS Secure the file's ownership and permissions (e.g. owned by the application user with file permission `600`) so the file is loaded. +These checks don't apply to the Rails initializer `config/initializers/solarwinds_apm.rb`, because Rails loads every file in `config/initializers` regardless. Protect it like the rest of your application code. + > **Note:** On non-POSIX systems (Windows), file permission bits aren't meaningful, so the agent skips these checks. Secure the configuration file with Windows ACLs instead. ## Configuration Topics diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index c3b1c83e..6970ca93 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -44,7 +44,8 @@ module Config # 2 - Otherwise, only for Rails applications, the prescribed Rails initializer # /config/initializers/solarwinds_apm.rb (also loaded later by Rails itself). # - # The selected file is loaded only if SolarWindsAPM::SecurePath.trusted? accepts it. + # Only the SW_APM_CONFIG_RUBY file is checked with SolarWindsAPM::SecurePath.trusted?. The Rails + # initializer isn't, because Rails loads every file in config/initializers regardless. # def self.load_config_file env_path = ENV.fetch('SW_APM_CONFIG_RUBY', '').strip @@ -55,12 +56,12 @@ def self.load_config_file end def self.config_file_from_env(env_path) - if File.absolute_path?(env_path) - return env_path if File.file?(env_path) && SolarWindsAPM::SecurePath.trusted?(env_path) - - SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." } - else + if !File.absolute_path?(env_path) SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] SW_APM_CONFIG_RUBY must be the absolute path of the configuration file (current setting is #{env_path}). No configuration file will be loaded." } + elsif !File.file?(env_path) + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." } + elsif SolarWindsAPM::SecurePath.trusted?(env_path) + return env_path end nil end @@ -80,12 +81,12 @@ def self.rails_config_file rails_root = ::Rails.root.to_s gemfile = ENV.fetch('BUNDLE_GEMFILE', '').strip rails_root = File.dirname(gemfile) if rails_root.empty? && File.absolute_path?(gemfile) + end - if rails_root.empty? - legacy_file = File.join(Dir.pwd, LEGACY_CONFIG_FILE) - SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Set SW_APM_CONFIG_RUBY to its absolute path to load it. Legacy file #{LEGACY_CONFIG_FILE} is no longer loaded." } if File.file?(legacy_file) - return nil - end + if rails_root.empty? + legacy_file = File.join(Dir.pwd, LEGACY_CONFIG_FILE) + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Set SW_APM_CONFIG_RUBY to its absolute path to load it. Legacy file #{LEGACY_CONFIG_FILE} is no longer loaded." } if File.file?(legacy_file) + return nil end config_file = File.join(rails_root, RAILS_CONFIG_FILE) diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 1ec3dc7b..9a631293 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -658,9 +658,18 @@ def with_rails_root(root) write_config(File.join(@cwd, 'solarwinds_apm_config.rb'), 'cwd_default') ENV['BUNDLE_GEMFILE'] = File.join(@cwd, 'Gemfile') - Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } + warnings = capture_logs(:warn) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } assert_nil SolarWindsAPM::Config[:config_file_marker] + assert_equal ['[SolarWindsAPM::Config/rails_config_file] Set SW_APM_CONFIG_RUBY to its absolute path to load it. ' \ + 'Legacy file solarwinds_apm_config.rb is no longer loaded.'], + warnings + end + + it 'does not resolve the rails initializer against the filesystem root for non-Rails applications' do + capture_logs(:warn) do + File.stub(:file?, true) { assert_nil SolarWindsAPM::Config.rails_config_file } + end end it 'warns about a legacy cwd config file when the Rails root cannot be determined' do @@ -723,9 +732,22 @@ def with_rails_root(root) File.chmod(0o666, @trusted) ENV['SW_APM_CONFIG_RUBY'] = @trusted - SolarWindsAPM::Config.load_config_file + warnings = capture_logs(:warn) { SolarWindsAPM::Config.load_config_file } assert_nil SolarWindsAPM::Config[:config_file_marker] + assert_equal ["[SolarWindsAPM::SecurePath/trusted?] The file #{@trusted} is not trusted because the file is world-writable. " \ + 'The file must be owned by root or by the user running the application, and neither the file nor its directory may be world-writable (e.g. file permission 600). ' \ + 'Please change the ownership or permissions to make it secure.'], + warnings + end + + it 'loads the rails initializer without SecurePath checks' do + initializer = write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') + File.chmod(0o666, initializer) + + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } + + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] end end From b4fab26696080fb4a07e4fd570edd54af7708826 Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Mon, 23 Nov 2026 17:05:59 -0500 Subject: [PATCH 10/11] copilot revision --- CONFIGURATION.md | 32 +++++++-- lib/solarwinds_apm/config.rb | 18 +++-- lib/solarwinds_apm/support/secure_path.rb | 69 ++++++++++++------ test/solarwinds_apm/config_test.rb | 16 ++++- test/support/secure_path_test.rb | 86 ++++++++++++++++------- 5 files changed, 160 insertions(+), 61 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 2e36841c..d745e02e 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -227,13 +227,37 @@ At most one configuration file is loaded: ### Config File Security -Config files are executed as Ruby code with the application's privileges. On POSIX systems (Linux, macOS), the agent refuses to load the file set by `SW_APM_CONFIG_RUBY`, and logs a warning, if: +Config files are executed as Ruby code with the application's privileges. On POSIX systems (Linux, macOS), the agent resolves symlinks in the path set by `SW_APM_CONFIG_RUBY`, then refuses to load the file, and logs a warning, if: - the file is world-writable, -- the file isn't owned by `root` or by the effective user running the application, or -- the file is in a world-writable directory without the sticky bit. +- the file isn't owned by `root` or by the effective user running the application, +- any directory in the resolved path, up to `/`, isn't owned by `root` or by the effective user, or +- any directory in the resolved path is world-writable without the sticky bit. -Secure the file's ownership and permissions (e.g. owned by the application user with file permission `600`) so the file is loaded. +Secure the file's and its directories' ownership and permissions (e.g. owned by the application user with file permission `600`) so the file is loaded. The agent loads the resolved file, so a symlink can't be retargeted between the check and the load. + +For example, if the application runs as the user `app`, make the file owned by that user and readable only by it: + +```bash +sudo chown app /etc/solarwinds_apm/config.rb +sudo chmod 600 /etc/solarwinds_apm/config.rb +``` + +Or keep the file owned by `root` and let the application read it: + +```bash +sudo chown root:root /etc/solarwinds_apm/config.rb +sudo chmod 644 /etc/solarwinds_apm/config.rb +``` + +A `root`-owned file with permission `600` passes the checks, but only an application running as `root` can read it. + +Standard locations such as `/etc` or the application user's home directory already meet the directory requirements. Common reasons a file is rejected: + +- The file is owned by another user, such as a deploy or CI user. Change its owner to the application user or `root`. +- The file is under a world-writable directory without the sticky bit, such as a shared mount with permission `777`. Move the file or fix that directory's permissions. + +The warning names the file or directory that failed the check and the reason. These checks don't apply to the Rails initializer `config/initializers/solarwinds_apm.rb`, because Rails loads every file in `config/initializers` regardless. Protect it like the rest of your application code. diff --git a/lib/solarwinds_apm/config.rb b/lib/solarwinds_apm/config.rb index 6970ca93..d1193cef 100644 --- a/lib/solarwinds_apm/config.rb +++ b/lib/solarwinds_apm/config.rb @@ -44,8 +44,9 @@ module Config # 2 - Otherwise, only for Rails applications, the prescribed Rails initializer # /config/initializers/solarwinds_apm.rb (also loaded later by Rails itself). # - # Only the SW_APM_CONFIG_RUBY file is checked with SolarWindsAPM::SecurePath.trusted?. The Rails - # initializer isn't, because Rails loads every file in config/initializers regardless. + # Only the SW_APM_CONFIG_RUBY file is checked with SolarWindsAPM::SecurePath.trusted_path, and its + # validated real path is what gets loaded. The Rails initializer isn't checked, because Rails loads + # every file in config/initializers regardless. # def self.load_config_file env_path = ENV.fetch('SW_APM_CONFIG_RUBY', '').strip @@ -56,14 +57,17 @@ def self.load_config_file end def self.config_file_from_env(env_path) - if !File.absolute_path?(env_path) + unless File.absolute_path?(env_path) SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] SW_APM_CONFIG_RUBY must be the absolute path of the configuration file (current setting is #{env_path}). No configuration file will be loaded." } - elsif !File.file?(env_path) + return + end + + unless File.file?(env_path) SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Could not find the configuration file set by the SW_APM_CONFIG_RUBY environment variable: #{env_path}. No configuration file will be loaded." } - elsif SolarWindsAPM::SecurePath.trusted?(env_path) - return env_path + return end - nil + + SolarWindsAPM::SecurePath.trusted_path(env_path) end ## diff --git a/lib/solarwinds_apm/support/secure_path.rb b/lib/solarwinds_apm/support/secure_path.rb index 156e9a76..1c0e287f 100644 --- a/lib/solarwinds_apm/support/secure_path.rb +++ b/lib/solarwinds_apm/support/secure_path.rb @@ -12,13 +12,20 @@ module SolarWindsAPM # # Verifies that a file is safe to execute (e.g. load as Ruby code) with the application's privileges. # - # On POSIX systems, a file is untrusted if it is world-writable, is not owned by root or by the - # effective user of this process, or lives in a world-writable directory without the sticky bit. + # On POSIX systems, the path is resolved to its real path (no symlinks) first. The file is untrusted if + # it is world-writable or is not owned by root or by the effective user of this process. Every directory + # of the real path, up to the filesystem root, must also be owned by root or by the effective user, and + # must not be world-writable unless it has the sticky bit. + # + # Callers must use the returned real path rather than the original one: no untrusted user can modify + # any component of the validated real path, whereas a symlink in the original path could be retargeted + # after validation. + # # Permission checks are skipped on Windows, where POSIX permission bits are not meaningful. # module SecurePath ## - # trusted? + # trusted_path # # === Argument: # @@ -26,44 +33,60 @@ module SecurePath # # === Example: # - # load(config_file) if SolarWindsAPM::SecurePath.trusted?(config_file) + # trusted_file = SolarWindsAPM::SecurePath.trusted_path(config_file) + # load(trusted_file) if trusted_file # # === Returns: - # * Boolean - true if the file can be trusted; false otherwise (a warning with the reason is logged) + # * String - the validated real path of the file (the given path on Windows) + # * nil - if the file can't be trusted (a warning with the reason is logged) # - def self.trusted?(path) - return true if Gem.win_platform? + def self.trusted_path(path) + return path if Gem.win_platform? - reason = untrusted_reason(path) - return true unless reason + real_path = File.realpath(path) + reason = file_untrusted_reason(real_path) || directory_untrusted_reason(File.dirname(real_path)) + return real_path unless reason SolarWindsAPM.logger.warn do "[#{name}/#{__method__}] The file #{path} is not trusted because #{reason}. " \ - 'The file must be owned by root or by the user running the application, and neither the file nor its directory may be world-writable (e.g. file permission 600). ' \ + 'The file and every directory in its path must be owned by root or by the user running the application, ' \ + 'the file must not be world-writable (e.g. file permission 600), and the directories must not be world-writable unless they have the sticky bit. ' \ 'Please change the ownership or permissions to make it secure.' end - false + nil rescue SystemCallError => e SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Unable to inspect file #{path}: #{e.message}" } - false + nil end - def self.untrusted_reason(path) - file_stat = File.stat(path) + def self.file_untrusted_reason(real_path) + file_stat = File.lstat(real_path) return 'the file is world-writable' if file_stat.world_writable? - euid = Process.euid - return "the file is owned by uid #{file_stat.uid}, not by root or the effective user (uid #{euid})" unless [0, euid].include?(file_stat.uid) + owner_untrusted_reason("the file #{real_path}", file_stat) + end + + # Walks up to the filesystem root; any untrusted ancestor could rename or replace the entries below it. + def self.directory_untrusted_reason(directory) + loop do + dir_stat = File.lstat(directory) + reason = owner_untrusted_reason("directory #{directory}", dir_stat) + return reason if reason + return "directory #{directory} is world-writable" if dir_stat.world_writable? && !dir_stat.sticky? - # Check both the given directory and the symlink-resolved one. - directories = [File.dirname(File.expand_path(path)), File.dirname(File.realpath(path))].uniq - 'its directory is world-writable' if directories.any? { |directory| insecure_directory?(directory) } + parent = File.dirname(directory) + return nil if parent == directory + + directory = parent + end end - def self.insecure_directory?(directory) - dir_stat = File.stat(directory) - dir_stat.world_writable? && !dir_stat.sticky? + def self.owner_untrusted_reason(subject, stat) + euid = Process.euid + return if [0, euid].include?(stat.uid) + + "#{subject} is owned by uid #{stat.uid}, not by root or the effective user (uid #{euid})" end - private_class_method :untrusted_reason, :insecure_directory? + private_class_method :file_untrusted_reason, :directory_untrusted_reason, :owner_untrusted_reason end end diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 9a631293..9aba4d49 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -735,12 +735,24 @@ def with_rails_root(root) warnings = capture_logs(:warn) { SolarWindsAPM::Config.load_config_file } assert_nil SolarWindsAPM::Config[:config_file_marker] - assert_equal ["[SolarWindsAPM::SecurePath/trusted?] The file #{@trusted} is not trusted because the file is world-writable. " \ - 'The file must be owned by root or by the user running the application, and neither the file nor its directory may be world-writable (e.g. file permission 600). ' \ + assert_equal ["[SolarWindsAPM::SecurePath/trusted_path] The file #{@trusted} is not trusted because the file is world-writable. " \ + 'The file and every directory in its path must be owned by root or by the user running the application, ' \ + 'the file must not be world-writable (e.g. file permission 600), and the directories must not be world-writable unless they have the sticky bit. ' \ 'Please change the ownership or permissions to make it secure.'], warnings end + it 'loads the validated real path of a symlinked SW_APM_CONFIG_RUBY' do + link = File.join(@tmpdir, 'link.rb') + File.symlink(@trusted, link) + ENV['SW_APM_CONFIG_RUBY'] = link + loaded = [] + + SolarWindsAPM::Config.stub(:load, ->(file) { loaded << file }) { SolarWindsAPM::Config.load_config_file } + + assert_equal [@trusted], loaded + end + it 'loads the rails initializer without SecurePath checks' do initializer = write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') File.chmod(0o666, initializer) diff --git a/test/support/secure_path_test.rb b/test/support/secure_path_test.rb index 1e37929e..58953f12 100644 --- a/test/support/secure_path_test.rb +++ b/test/support/secure_path_test.rb @@ -16,18 +16,22 @@ def capture_warnings(&test_block) warnings end - # CI runs tests as root, so fake the owner/effective user instead of relying on real file ownership. - def with_file_owner(path, uid, euid, &test_block) - original_stat = File.method(:stat) - owned_stat = SimpleDelegator.new(original_stat.call(path)) - owned_stat.define_singleton_method(:uid) { uid } - stat_stub = ->(file) { file == path ? owned_stat : original_stat.call(file) } - Process.stub(:euid, euid) { File.stub(:stat, stat_stub, &test_block) } + # CI runs tests as root, so fake the owner of the given paths instead of relying on real file ownership. + def with_owners(uids_by_path, &test_block) + original_lstat = File.method(:lstat) + lstat_stub = lambda do |file| + stat = original_lstat.call(file) + return stat unless uids_by_path.key?(file) + + SimpleDelegator.new(stat).tap { |owned_stat| owned_stat.define_singleton_method(:uid) { uids_by_path[file] } } + end + File.stub(:lstat, lstat_stub, &test_block) end def untrusted_warning(path, reason) - "[SolarWindsAPM::SecurePath/trusted?] The file #{path} is not trusted because #{reason}. " \ - 'The file must be owned by root or by the user running the application, and neither the file nor its directory may be world-writable (e.g. file permission 600). ' \ + "[SolarWindsAPM::SecurePath/trusted_path] The file #{path} is not trusted because #{reason}. " \ + 'The file and every directory in its path must be owned by root or by the user running the application, ' \ + 'the file must not be world-writable (e.g. file permission 600), and the directories must not be world-writable unless they have the sticky bit. ' \ 'Please change the ownership or permissions to make it secure.' end @@ -43,14 +47,23 @@ def untrusted_warning(path, reason) FileUtils.rm_rf(@tmpdir) end - it 'trusts a file owned by the current user that is not world-writable' do - assert SolarWindsAPM::SecurePath.trusted?(@file) + it 'returns the path of a file owned by the current user that is not world-writable' do + assert_equal @file, SolarWindsAPM::SecurePath.trusted_path(@file) + end + + it 'returns the resolved target of a symlink so that the link cannot be retargeted before loading' do + shared_dir = File.join(@tmpdir, 'shared').tap { |d| FileUtils.mkdir_p(d) } + File.chmod(0o1777, shared_dir) + link = File.join(shared_dir, 'link.rb') + File.symlink(@file, link) + + with_owners(link => 4242) { assert_equal @file, SolarWindsAPM::SecurePath.trusted_path(link) } end it 'rejects a world-writable file' do File.chmod(0o666, @file) - warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(@file) } + warnings = capture_warnings { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } assert_equal [untrusted_warning(@file, 'the file is world-writable')], warnings end @@ -58,9 +71,17 @@ def untrusted_warning(path, reason) it 'rejects a file in a world-writable non-sticky directory' do File.chmod(0o777, @dir) - warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(@file) } + warnings = capture_warnings { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } - assert_equal [untrusted_warning(@file, 'its directory is world-writable')], warnings + assert_equal [untrusted_warning(@file, "directory #{@dir} is world-writable")], warnings + end + + it 'rejects a file below a world-writable non-sticky ancestor directory' do + File.chmod(0o777, @tmpdir) + + warnings = capture_warnings { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } + + assert_equal [untrusted_warning(@file, "directory #{@tmpdir} is world-writable")], warnings end it 'rejects a symlink whose target is in a world-writable non-sticky directory' do @@ -72,46 +93,61 @@ def untrusted_warning(path, reason) link = File.join(@dir, 'link.rb') File.symlink(target, link) - warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(link) } + warnings = capture_warnings { assert_nil SolarWindsAPM::SecurePath.trusted_path(link) } - assert_equal [untrusted_warning(link, 'its directory is world-writable')], warnings + assert_equal [untrusted_warning(link, "directory #{unsafe_dir} is world-writable")], warnings end it 'trusts a file in a world-writable sticky directory' do File.chmod(0o1777, @dir) - assert SolarWindsAPM::SecurePath.trusted?(@file) + assert_equal @file, SolarWindsAPM::SecurePath.trusted_path(@file) end it 'rejects a file owned by a user other than root or the effective user' do warnings = capture_warnings do - with_file_owner(@file, 4242, 1000) { refute SolarWindsAPM::SecurePath.trusted?(@file) } + with_owners(@file => 4242) { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } + end + + assert_equal [untrusted_warning(@file, "the file #{@file} is owned by uid 4242, not by root or the effective user (uid #{Process.euid})")], warnings + end + + it 'rejects a file in a directory owned by a user other than root or the effective user' do + warnings = capture_warnings do + with_owners(@dir => 4242) { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } end - assert_equal [untrusted_warning(@file, 'the file is owned by uid 4242, not by root or the effective user (uid 1000)')], warnings + assert_equal [untrusted_warning(@file, "directory #{@dir} is owned by uid 4242, not by root or the effective user (uid #{Process.euid})")], warnings end - it 'trusts a file owned by the effective user' do - with_file_owner(@file, 1000, 1000) { assert SolarWindsAPM::SecurePath.trusted?(@file) } + it 'rejects a file in a world-writable sticky directory owned by another user' do + File.chmod(0o1777, @dir) + + warnings = capture_warnings do + with_owners(@dir => 4242) { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } + end + + assert_equal [untrusted_warning(@file, "directory #{@dir} is owned by uid 4242, not by root or the effective user (uid #{Process.euid})")], warnings end it 'trusts a file owned by root' do - with_file_owner(@file, 0, 1000) { assert SolarWindsAPM::SecurePath.trusted?(@file) } + with_owners(@file => 0) { assert_equal @file, SolarWindsAPM::SecurePath.trusted_path(@file) } end it 'rejects a file that cannot be inspected' do missing = File.join(@dir, 'missing.rb') - warnings = capture_warnings { refute SolarWindsAPM::SecurePath.trusted?(missing) } + warnings = capture_warnings { assert_nil SolarWindsAPM::SecurePath.trusted_path(missing) } - assert_equal ["[SolarWindsAPM::SecurePath/trusted?] Unable to inspect file #{missing}: No such file or directory @ rb_file_s_stat - #{missing}"], warnings + assert_equal 1, warnings.size + assert_match(%r{\A\[SolarWindsAPM::SecurePath/trusted_path\] Unable to inspect file #{Regexp.escape(missing)}: No such file or directory}, warnings.first) end it 'skips permission checks on Windows' do File.chmod(0o666, @file) warnings = capture_warnings do - Gem.stub(:win_platform?, true) { assert SolarWindsAPM::SecurePath.trusted?(@file) } + Gem.stub(:win_platform?, true) { assert_equal @file, SolarWindsAPM::SecurePath.trusted_path(@file) } end assert_empty warnings From 5553afc6f86e3fa74db92ef4f0f919f223f662a8 Mon Sep 17 00:00:00 2001 From: xuan-cao-swi Date: Tue, 24 Nov 2026 11:26:04 -0500 Subject: [PATCH 11/11] fix ci and add more doc for docker/k8s config file binding --- CONFIGURATION.md | 74 ++++++++++++++++++++++++++++++ test/solarwinds_apm/config_test.rb | 9 +++- 2 files changed, 82 insertions(+), 1 deletion(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index d745e02e..9b7bf2f1 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -257,12 +257,86 @@ Standard locations such as `/etc` or the application user's home directory alrea - The file is owned by another user, such as a deploy or CI user. Change its owner to the application user or `root`. - The file is under a world-writable directory without the sticky bit, such as a shared mount with permission `777`. Move the file or fix that directory's permissions. +For Docker and Kubernetes, see [Containers (Docker and Kubernetes)](#containers-docker-and-kubernetes). + The warning names the file or directory that failed the check and the reason. These checks don't apply to the Rails initializer `config/initializers/solarwinds_apm.rb`, because Rails loads every file in `config/initializers` regardless. Protect it like the rest of your application code. > **Note:** On non-POSIX systems (Windows), file permission bits aren't meaningful, so the agent skips these checks. Secure the configuration file with Windows ACLs instead. +### Containers (Docker and Kubernetes) + +Rails applications that use `config/initializers/solarwinds_apm.rb` without setting `SW_APM_CONFIG_RUBY` aren't affected by the [Config File Security](#config-file-security) checks. When `SW_APM_CONFIG_RUBY` is set in a container, the checks use the user the container runs as, which is often different from the user that owns the application files. The simplest setup that works for any container user is a file owned by `root` with permission `644`, in a directory owned by `root` that isn't world-writable, such as `/etc/solarwinds_apm`. + +#### Docker + +`COPY` creates files owned by `root` unless `--chown` is given, so copy the file outside the application directory and set its permission: + +```dockerfile +COPY solarwinds_apm_config.rb /etc/solarwinds_apm/config.rb +RUN chmod 644 /etc/solarwinds_apm/config.rb +ENV SW_APM_CONFIG_RUBY=/etc/solarwinds_apm/config.rb +``` + +The file is rejected in these common cases: + +- The file is copied with `COPY --chown=` (or sits in an application directory owned by that user), but the container runs as a different user: as `root` because the image has no `USER` instruction, through `docker run --user`, or with an arbitrary user ID assigned by the platform (e.g. OpenShift). Keep the file owned by `root`, or run the container as the user that owns it. +- The file is bind-mounted (`docker run -v`, Compose `volumes`) from a Linux host, where it keeps the host user's ID. It's trusted only if that ID is `0` or matches the container user. Docker Desktop on macOS presents bind-mounted files as owned by the container user. +- The file or one of its directories was made world-writable, for example with `chmod -R 777` to work around permission errors. + +#### Kubernetes + +How the file is mounted determines whether it passes the checks: + +| Volume type | Result | Reason | +|---|---|---| +| `configMap` mounted as a directory | Rejected | The kubelet creates the mount directory with permission `777` and no sticky bit, even though the volume is mounted read-only. | +| `configMap` mounted with `subPath` | Trusted | The file is mounted directly into a directory owned by `root`. | +| `secret` or `projected` | Trusted | The mount directory is a `tmpfs` with permission `1777` (sticky bit set). | +| `emptyDir` (e.g. populated by an init container) | Rejected | The directory has permission `777` and no sticky bit. | + +The file must also be owned by `root` or by the container user. ConfigMap, Secret and projected files are owned by `root`, so `runAsUser` and `fsGroup` don't affect them. Don't set `defaultMode` to a world-writable mode such as `0666` or `0777`. + +For example, mount a ConfigMap key with `subPath`: + +```yaml +apiVersion: v1 +kind: Pod +metadata: + name: my-app +spec: + containers: + - name: app + image: my-app:latest + env: + - name: SW_APM_CONFIG_RUBY + value: /etc/solarwinds_apm/config.rb + volumeMounts: + - name: solarwinds-apm-config + mountPath: /etc/solarwinds_apm/config.rb + subPath: config.rb + volumes: + - name: solarwinds-apm-config + configMap: + name: solarwinds-apm-config +``` + +Files mounted with `subPath` don't receive ConfigMap updates. This doesn't matter here, because the configuration file is only read when the application starts. + +Or mount a Secret as a directory: + +```yaml + volumeMounts: + - name: solarwinds-apm-config + mountPath: /etc/solarwinds_apm + readOnly: true + volumes: + - name: solarwinds-apm-config + secret: + secretName: solarwinds-apm-config +``` + ## Configuration Topics ### Transaction Filtering diff --git a/test/solarwinds_apm/config_test.rb b/test/solarwinds_apm/config_test.rb index 9aba4d49..17fe4ace 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -12,8 +12,15 @@ describe 'Config Test' do describe '#config_file_from_env' do it 'returns the absolute path of an existing file' do - config_path = File.expand_path('lib/rails/generators/solarwinds_apm/templates/solarwinds_apm_initializer.rb') + # The repo checkout may be owned by another user (e.g. CI containers running as root), which SecurePath rejects + tmpdir = File.realpath(Dir.mktmpdir('sw_apm_config')) + config_path = File.join(tmpdir, 'solarwinds_apm_config.rb') + File.write(config_path, '') + File.chmod(0o644, config_path) + assert_equal config_path, SolarWindsAPM::Config.config_file_from_env(config_path) + ensure + FileUtils.rm_rf(tmpdir) if tmpdir end it 'rejects a relative path even if the file exists' do