diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 7f26da4e..9b7bf2f1 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -195,23 +195,148 @@ 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 ``` +### Config File Selection + +At most one configuration file is loaded: + +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 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, +- 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 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. + +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 @@ -314,7 +439,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 | 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 0738f19f..d1193cef 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 ## @@ -27,56 +28,79 @@ module Config @@config = {} + RAILS_CONFIG_FILE = 'config/initializers/solarwinds_apm.rb' + LEGACY_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, 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). + # + # 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 - config_files = [] - - # 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) + 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 - # Check for file set by env variable - config_files << config_file_from_env if ENV.key?('SW_APM_CONFIG_RUBY') + set_log_level # sets SolarWindsAPM::Config[:debug_level], SolarWindsAPM.logger.level + 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.config_file_from_env(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." } + return + end - 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(', ')}" - 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." } + return end - load(config_files[0]) if config_files.size.positive? - set_log_level # sets SolarWindsAPM::Config[:debug_level], SolarWindsAPM.logger.level + SolarWindsAPM::SecurePath.trusted_path(env_path) 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 - 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)}" - end + ## + # rails_config_file + # + # 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.rails_config_file + rails_root = '' + if defined?(::Rails) && ::Rails.respond_to?(:root) + 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 - config_file + + 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) + return config_file if File.file?(config_file) + + 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 def self.set_log_level diff --git a/lib/solarwinds_apm/support/secure_path.rb b/lib/solarwinds_apm/support/secure_path.rb new file mode 100644 index 00000000..1c0e287f --- /dev/null +++ b/lib/solarwinds_apm/support/secure_path.rb @@ -0,0 +1,92 @@ +# 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, 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_path + # + # === Argument: + # + # * +path+ - Path of the file to verify + # + # === Example: + # + # trusted_file = SolarWindsAPM::SecurePath.trusted_path(config_file) + # load(trusted_file) if trusted_file + # + # === Returns: + # * 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(path) + return path if Gem.win_platform? + + 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 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 + nil + rescue SystemCallError => e + SolarWindsAPM.logger.warn { "[#{name}/#{__method__}] Unable to inspect file #{path}: #{e.message}" } + nil + end + + def self.file_untrusted_reason(real_path) + file_stat = File.lstat(real_path) + return 'the file is world-writable' if file_stat.world_writable? + + 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? + + parent = File.dirname(directory) + return nil if parent == directory + + directory = parent + end + end + + 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 :file_untrusted_reason, :directory_untrusted_reason, :owner_untrusted_reason + end +end 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 6f0553d5..17fe4ace 100644 --- a/test/solarwinds_apm/config_test.rb +++ b/test/solarwinds_apm/config_test.rb @@ -5,36 +5,43 @@ require 'minitest_helper' require 'logger' +require 'tmpdir' +require 'fileutils' require './lib/solarwinds_apm/config' describe 'Config Test' do describe '#config_file_from_env' do - after do - ENV.delete('SW_APM_CONFIG_RUBY') + it 'returns the absolute path of an existing file' do + # 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 '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) - end + it 'rejects a relative path even if the file exists' do + 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(relative_path) + end - it 'with correct SW_APM_CONFIG_RUBY should return file' 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' + 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 + assert_nil SolarWindsAPM::Config.config_file_from_env(File.expand_path('lib/rails/generators/solarwinds_apm/templates')) 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 + assert_nil SolarWindsAPM::Config.config_file_from_env('/nonexistent/path/file.rb') end end @@ -583,19 +590,184 @@ 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 + 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 + + 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 - if original - ENV['SW_APM_CONFIG_RUBY'] = original - else - ENV.delete('SW_APM_CONFIG_RUBY') + 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') + 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 rails initializer exists' do + write_config(File.join(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } + + assert_equal 'trusted', SolarWindsAPM::Config[:config_file_marker] + end + + 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 '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['SW_APM_CONFIG_RUBY'] = File.join(@tmpdir, 'missing.rb') + + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + + 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') + 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 } } + + 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 + 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/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 '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(@app_dir, 'config/initializers/solarwinds_apm.rb'), 'app_rails') + + with_rails_root(@app_dir) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } + + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] + end + + 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') + + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + end + + 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') + + 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' + + with_rails_root(nil) { Dir.chdir(@cwd) { SolarWindsAPM::Config.load_config_file } } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + 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'] = '' + + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } + + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] + end + + it 'does not load a config file rejected by SecurePath' do + File.chmod(0o666, @trusted) + ENV['SW_APM_CONFIG_RUBY'] = @trusted + + warnings = capture_logs(:warn) { SolarWindsAPM::Config.load_config_file } + + assert_nil SolarWindsAPM::Config[:config_file_marker] + 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) + + with_rails_root(@app_dir) { SolarWindsAPM::Config.load_config_file } + + assert_equal 'app_rails', SolarWindsAPM::Config[:config_file_marker] + end end describe 'update! and merge!' do 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..58953f12 --- /dev/null +++ b/test/support/secure_path_test.rb @@ -0,0 +1,155 @@ +# 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 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_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 + + 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 '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 { assert_nil SolarWindsAPM::SecurePath.trusted_path(@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 { assert_nil SolarWindsAPM::SecurePath.trusted_path(@file) } + + 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 + 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 { assert_nil SolarWindsAPM::SecurePath.trusted_path(link) } + + 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_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_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, "directory #{@dir} is owned by uid 4242, not by root or the effective user (uid #{Process.euid})")], warnings + end + + 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_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 { assert_nil SolarWindsAPM::SecurePath.trusted_path(missing) } + + 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_equal @file, SolarWindsAPM::SecurePath.trusted_path(@file) } + end + + assert_empty warnings + end +end