From 7fadbc4b076321368a6e894bc3405a8fc65f1e52 Mon Sep 17 00:00:00 2001 From: Paul Traylor Date: Fri, 9 Feb 2024 12:45:58 +0900 Subject: [PATCH] Stricter validation Previously some of our regex checks were not properly bounded. By adding ^ and $ to our regex, we can ensure the entire string gets checked. --- promgen/tests/test_models.py | 13 ++++++++++++- promgen/validators.py | 10 +++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/promgen/tests/test_models.py b/promgen/tests/test_models.py index 96c96a650..373146d68 100644 --- a/promgen/tests/test_models.py +++ b/promgen/tests/test_models.py @@ -4,7 +4,7 @@ from django.core.exceptions import ValidationError -from promgen import models +from promgen import models, validators from promgen.tests import PromgenTest @@ -23,3 +23,14 @@ def test_names(self): # Fail a name with \ models.Service(name=r"foo/bar", owner=self.user).full_clean() models.Service(name=r"foo\bar", owner=self.user).full_clean() + + def test_validators(self): + with self.assertRaises(ValidationError, msg="Javascript injection"): + validators.metricname( + "asdasd[[1-1]]')) || (this.$el.ownerDocument.defaultView.alert('1337", + ) + + with self.assertRaises(ValidationError, msg="Vue.js injection"): + validators.metricname( + "[[this.$el.ownerDocument.defaultView.alert(1337)]]", + ) diff --git a/promgen/validators.py b/promgen/validators.py index e887f4ec9..7703f61e5 100644 --- a/promgen/validators.py +++ b/promgen/validators.py @@ -19,14 +19,18 @@ # Label Value Definition # https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels metricname = RegexValidator( - r"[a-zA-Z_:][a-zA-Z0-9_:]*", "Only alphanumeric characters are allowed." + r"^[a-zA-Z_:][a-zA-Z0-9_:]*$", + "Only alphanumeric characters are allowed.", +) +labelname = RegexValidator( + r"^[a-zA-Z_][a-zA-Z0-9_]*$", + "Only alphanumeric characters are allowed.", ) -labelname = RegexValidator(r"[a-zA-Z_][a-zA-Z0-9_]*", "Only alphanumeric characters are allowed.") # While Prometheus accepts label values of any unicode character, our values sometimes # make it into URLs, so we want to make sure we do not have stray / characters labelvalue = RegexValidator( - r"^[\w][- \w]+\Z", "Unicode letters, numbers, underscores, or hyphens or spaces" + r"^[\w][- \w]+$", "Unicode letters, numbers, underscores, or hyphens or spaces" ) hostname = RegexValidator(