Skip to content
133 changes: 129 additions & 4 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
> [!NOTE]
> Starting with version 8.0.0, the configuration file is no longer auto-discovered; a warning is logged for the deprecated behavior where `solarwinds_apm_config.rb` was loaded from the current working directory.


#### Custom Location

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's remove this Custom Location section, it's redudant with the Config File Selection section added below.


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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor but i am OCD and bothered by it, can we say APM Ruby instead of the agent everywhere in this doc?

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this section can be a lot shorter now, i think it's enough to outline the permission check logic, no need to show how to use chmod.


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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
> **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.
> [!NOTE]
> File permissions is only checked on POSIX systems.


### 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=<app user>` (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
Expand Down Expand Up @@ -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). <br> 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 |
Expand Down
92 changes: 58 additions & 34 deletions lib/solarwinds_apm/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
##
Expand All @@ -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: <startup_dir>/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
# <Rails root>/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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part is now making me think:

Rails loads every file in config/initializers regardless.

in line 54 we're calling load(config_file) if config_file. Does that mean if APM Ruby config is given as a Rails initializer, it ends up being loaded twice?

#
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 <Rails root>/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
Expand Down
92 changes: 92 additions & 0 deletions lib/solarwinds_apm/support/secure_path.rb
Original file line number Diff line number Diff line change
@@ -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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xuan-cao-swi this seems very strongly worded and potentially misleading for what we're trying to achieve. We can only minimize risk by checking obviously bad permissions, not guarantee that a file is safe to execute. Can this module be somehing like PosixPermissionCheck instead?

#
# 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)

@cheempz cheempz Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@xuan-cao-swi sorry, i suggested the euid check, but from more research this could be an issue in containers if the config file is mounted from the host. Depending on the OS and container runtime, the mounted file's UID may or may not be remapped to a UID in the container (and even if remapped, it could very well be different from EUID of the application process). The remapping typically is enabled in Docker Desktop (which would mask this problem) but not in Linux. How about let's remove this check?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i see a lot of digital ink was spilled in the CONFIGURATION section to document these cases ;)... can get rid of all that too.

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
2 changes: 1 addition & 1 deletion test/minitest_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading