Skip to content

Commit b548061

Browse files
committed
Add sanitization and a test
1 parent 63fc065 commit b548061

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

elasticapm/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import logging
3737
import os
3838
import platform
39+
import re
3940
import sys
4041
import threading
4142
import time
@@ -425,11 +426,10 @@ def get_user_agent(self) -> str:
425426
to the APM Server
426427
"""
427428
if self.config.service_version:
428-
return "apm-agent-python/{} ({} {})".format(
429-
elasticapm.VERSION, self.config.service_name, self.config.service_version
430-
).encode("utf-8")
429+
service_version = re.sub(r"[^\t _\x21-\x27\x2a-\x5b\x5d-\x7e\x80-\xff]", "_", self.config.service_version)
430+
return "apm-agent-python/{} ({} {})".format(elasticapm.VERSION, self.config.service_name, service_version)
431431
else:
432-
return "apm-agent-python/{} ({})".format(elasticapm.VERSION, self.config.service_name).encode("utf-8")
432+
return "apm-agent-python/{} ({})".format(elasticapm.VERSION, self.config.service_name)
433433

434434
def build_metadata(self):
435435
data = {

tests/client/client_tests.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -867,3 +867,15 @@ def test_backdating_transaction(elasticapm_client):
867867
elasticapm_client.end_transaction()
868868
transaction = elasticapm_client.events[TRANSACTION][0]
869869
assert 1000 < transaction["duration"] < 2000
870+
871+
872+
@pytest.mark.parametrize(
873+
"elasticapm_client,expected",
874+
[
875+
({"service_version": "v2"}, "v2"),
876+
({"service_version": "v2 \x00"}, "v2 _"),
877+
],
878+
indirect=["elasticapm_client"],
879+
)
880+
def test_user_agent(elasticapm_client, expected):
881+
assert elasticapm_client.get_user_agent() == "apm-agent-python/unknown (myapp {})".format(expected)

0 commit comments

Comments
 (0)