Skip to content

Commit

Permalink
Stricter validation
Browse files Browse the repository at this point in the history
Previously some of our regex checks were not properly bounded. By adding
^ and $ to our regex, we can ensure the entire string gets checked.
  • Loading branch information
kfdm committed Feb 9, 2024
1 parent 46b1f9f commit 7fadbc4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
13 changes: 12 additions & 1 deletion promgen/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from django.core.exceptions import ValidationError

from promgen import models
from promgen import models, validators
from promgen.tests import PromgenTest


Expand All @@ -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)]]",
)
10 changes: 7 additions & 3 deletions promgen/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 7fadbc4

Please sign in to comment.