Skip to content

Commit

Permalink
ensure filtered params aren't revealed in sql
Browse files Browse the repository at this point in the history
  • Loading branch information
kennyevil committed Nov 7, 2024
1 parent fb9bd70 commit aa1e03b
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/rails_semantic_logger/active_record/log_subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,13 @@ def sql(event)

# When multiple values are received for a single bound field, it is converted into an array
def add_bind_value(binds, key, value)
key = key.downcase.to_sym unless key.nil?
value = (Array(binds[key]) << value) if binds.key?(key)
key = key.downcase.to_sym unless key.nil?
if Rails.configuration.filter_parameters.include? key
value = "[FILTERED]"
elsif binds.key?(key)
value = (Array(binds[key]) << value)
end

binds[key] = value
end

Expand Down
28 changes: 28 additions & 0 deletions test/active_record_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,34 @@ class ActiveRecordTest < Minitest::Test
assert_instance_of Integer, messages[0].payload[:allocations] if Rails.version.to_i >= 6
end

it "filtered bind value" do
filter_params_setting true, %i[name] do
expected_sql =
if Rails.version.to_f >= 5.2
"SELECT #{extra_space}\"samples\".* FROM \"samples\" WHERE \"samples\".\"name\" = ? ORDER BY \"samples\".\"id\" ASC LIMIT ?"
else
"SELECT \"samples\".* FROM \"samples\" WHERE \"samples\".\"name\" = ? ORDER BY \"samples\".\"id\" ASC LIMIT ?"
end

messages = semantic_logger_events do
Sample.where(name: "Jack").first
end
assert_equal 1, messages.count, messages

assert_semantic_logger_event(
messages[0],
level: :debug,
name: "ActiveRecord",
message: "Sample Load",
payload_includes: {
sql: expected_sql,
binds: {name: "[FILTERED]", limit: 1}
}
)
assert_instance_of Integer, messages[0].payload[:allocations] if Rails.version.to_i >= 6
end
end

it "multiple bind values" do
skip "Not applicable to older rails" if Rails.version.to_f <= 5.1

Expand Down
Binary file modified test/dummy/db/test.sqlite3
Binary file not shown.
7 changes: 7 additions & 0 deletions test/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,10 @@
Minitest::Test.include SemanticLogger::Test::Minitest

ActionMailer::Base.delivery_method = :test

def filter_params_setting(value, user_defined_params, &block)
Rails.configuration.filter_parameters += user_defined_params
block.call
ensure
Rails.configuration.filter_parameters -= user_defined_params
end

0 comments on commit aa1e03b

Please sign in to comment.