Skip to content

Commit 863adb0

Browse files
committed
Restrict attribute keys to non-empty strings
According to the spec: > The attribute key, which MUST be a non-null and non-empty string. https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/common.md
1 parent 2a726e4 commit 863adb0

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2020
([#2044](https://github.com/open-telemetry/opentelemetry-python/pull/2044))
2121
- `opentelemetry-sdk` Fixed bugs (#2041, #2042 & #2045) in Span Limits
2222
([#2044](https://github.com/open-telemetry/opentelemetry-python/pull/2044))
23+
- `opentelemetry-api` Attribute keys must be non-empty strings.
24+
([#2057](https://github.com/open-telemetry/opentelemetry-python/pull/2057))
2325

2426
## [0.23.1](https://github.com/open-telemetry/opentelemetry-python/pull/1987) - 2021-07-26
2527

opentelemetry-api/src/opentelemetry/attributes/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,11 @@ def _clean_attribute(
4747
- It needs to be encoded/decoded e.g, bytes to strings.
4848
"""
4949

50-
if key is None or key == "":
50+
#if key is None or key == "":
51+
# _logger.warning("invalid key `%s` (empty or null)", key)
52+
# return None
53+
54+
if not isinstance(key, str) or not key:
5155
_logger.warning("invalid key `%s` (empty or null)", key)
5256
return None
5357

opentelemetry-api/tests/attributes/test_attributes.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ def assertValid(self, value, key="k"):
3131
def assertInvalid(self, value, key="k"):
3232
self.assertIsNone(_clean_attribute(key, value, None))
3333

34+
def test_attribute_key_validation(self):
35+
# only non-empty strings are valid keys
36+
self.assertInvalid(1, "")
37+
self.assertInvalid(1, 1)
38+
self.assertInvalid(1, {})
39+
self.assertInvalid(1, [])
40+
self.assertInvalid(1, b"1")
41+
self.assertValid(1, "k")
42+
self.assertValid(1, "1")
43+
3444
def test_clean_attribute(self):
3545
self.assertInvalid([1, 2, 3.4, "ss", 4])
3646
self.assertInvalid([dict(), 1, 2, 3.4, 4])
@@ -142,10 +152,10 @@ def test_bounded_dict(self):
142152
def test_no_limit_code(self):
143153
bdict = BoundedAttributes(maxlen=None, immutable=False)
144154
for num in range(100):
145-
bdict[num] = num
155+
bdict[str(num)] = num
146156

147157
for num in range(100):
148-
self.assertEqual(bdict[num], num)
158+
self.assertEqual(bdict[str(num)], num)
149159

150160
def test_immutable(self):
151161
bdict = BoundedAttributes()

0 commit comments

Comments
 (0)