Skip to content

Commit

Permalink
fix: Remove prepended SQL comments when truncating
Browse files Browse the repository at this point in the history
Previously, when a SQL query with a prepended comment
exceeded the obfuscation limit, the query would be truncated without
obfuscation.

Now, when the obfuscator detects a prepended comment in a query that
needs to be truncated, the prepended comment will be replaced with the
placeholder and the remaining query will be truncated to the
obfuscation limit.
  • Loading branch information
kaylareopelle committed Sep 4, 2024
1 parent f817d6b commit 9a4fe90
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ module SqlObfuscation
hexadecimal_literals comments multi_line_comments]
}.freeze

PREPENDED_COMMENT_REGEX = %r{^/\*.*\*/}

PLACEHOLDER = '?'

# We use these to check whether the query contains any quote characters
Expand Down Expand Up @@ -127,6 +129,8 @@ def obfuscate_sql(sql, obfuscation_limit: 2000, adapter: :default)

# @api private
def truncate_statement(sql, regex, limit)
sql = sql.gsub(PREPENDED_COMMENT_REGEX, PLACEHOLDER) if sql.match?(PREPENDED_COMMENT_REGEX)

first_match_index = sql.index(regex)
truncation_message = "SQL truncated (> #{limit} characters)"
return truncation_message unless first_match_index
Expand Down
9 changes: 9 additions & 0 deletions helpers/sql-obfuscation/test/helpers/sql_obfuscation_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ def test_obfuscation_limit_truncates_query_after_first_match
assert_equal(expected, result)
end

def test_obfuscation_limit_obfuscates_and_truncates_when_query_has_prepended_comment
comment = '/*service.name:foo,deployment.environtment:production,tracecontext:00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00,rails.route:examples/bars#index,host.name:baz-abc123.example.com*/'
sql = "#{comment} SELECT user.id FROM users where user.login = 'secretUserNameThatShouldBeObfuscated'"
expected = "? SELECT user.id FROM users where user.login = ...\nSQL truncated (> 42 characters)"
result = OpenTelemetry::Helpers::SqlObfuscation.obfuscate_sql(sql, obfuscation_limit: 42)

assert_equal(expected, result)
end

def test_obfuscation_limit_truncates_when_query_not_encoded_with_utf8
sql = "SELECT * from 😄 where users.id = 1 and users.😄 = 'test@test.com'"
expected = "SELECT * from where users.id = ...\nSQL truncated (> 42 characters)"
Expand Down

0 comments on commit 9a4fe90

Please sign in to comment.