Skip to content

Commit

Permalink
fix: Only allow certain types of Numeric values as attribute values. (#…
Browse files Browse the repository at this point in the history
…1173)

* Check for specific Numeric classes
  • Loading branch information
plantfansam committed Apr 8, 2022
1 parent 329e2c1 commit b22c5c6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
10 changes: 7 additions & 3 deletions sdk/lib/opentelemetry/sdk/internal.rb
Expand Up @@ -13,15 +13,19 @@ module Internal
extend self

def boolean?(value)
value.is_a?(TrueClass) || value.is_a?(FalseClass)
value.instance_of?(TrueClass) || value.instance_of?(FalseClass)
end

def valid_key?(key)
key.instance_of?(String)
end

def numeric?(value)
value.instance_of?(Integer) || value.instance_of?(Float)
end

def valid_simple_value?(value)
value.instance_of?(String) || value == false || value == true || value.is_a?(Numeric)
value.instance_of?(String) || boolean?(value) || numeric?(value)
end

def valid_array_value?(value)
Expand All @@ -34,7 +38,7 @@ def valid_array_value?(value)
when TrueClass, FalseClass
value.all? { |v| boolean?(v) }
when Numeric
value.all? { |v| v.is_a?(Numeric) }
value.all? { |v| numeric?(v) }
else
false
end
Expand Down
25 changes: 25 additions & 0 deletions sdk/test/opentelemetry/sdk/trace/span_test.rb
Expand Up @@ -105,6 +105,23 @@
end
end

it 'reports an error for a non-standard library Numeric subclass, which is invalid' do
OpenTelemetry::TestHelpers.with_test_logger do |log_stream|
numeric_klass = Class.new(Numeric) {}
span.set_attribute('foo', numeric_klass.new)
span.finish
_(log_stream.string).must_match(/invalid span attribute value type #<Class(.*)for key 'foo' on span 'name'/)
end
end

it 'reports an error for a NilClass value, which is invalid' do
OpenTelemetry::TestHelpers.with_test_logger do |log_stream|
span.set_attribute('foo', nil)
span.finish
_(log_stream.string).must_match(/invalid span attribute value type NilClass for key 'foo' on span 'name'/)
end
end

it 'reports an error for an invalid key' do
OpenTelemetry::TestHelpers.with_test_logger do |log_stream|
span.set_attribute(nil, 'bar')
Expand Down Expand Up @@ -165,6 +182,14 @@
_(events.first.attributes).must_equal(attrs)
end

it 'does not keep nil-valued attributes' do
attrs = { 'foo' => nil }
span.add_event('added', attributes: attrs)
events = span.events
_(events.size).must_equal(1)
_(events.first.attributes).must_equal({})
end

it 'accepts array-valued attributes' do
attrs = { 'foo' => [1, 2, 3] }
span.add_event('added', attributes: attrs)
Expand Down

0 comments on commit b22c5c6

Please sign in to comment.