Skip to content

Commit 9c4ff92

Browse files
committed
Validate label names
Up to now, we've only been performing limited validation of label names. This commit validates that the characters use match the regex `/\A[a-zA-Z_][a-zA-Z0-9_]*\Z/` as specified by: https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels
1 parent 733a05f commit 9c4ff92

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

lib/prometheus/client/label_set_validator.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ module Client
77
class LabelSetValidator
88
# TODO: we might allow setting :instance in the future
99
BASE_RESERVED_LABELS = [:job, :instance, :pid].freeze
10+
LABEL_NAME_REGEX = /\A[a-zA-Z_][a-zA-Z0-9_]*\Z/
1011

1112
class LabelSetError < StandardError; end
1213
class InvalidLabelSetError < LabelSetError; end
@@ -59,9 +60,16 @@ def validate_symbol(key)
5960
end
6061

6162
def validate_name(key)
62-
return true unless key.to_s.start_with?('__')
63+
if key.to_s.start_with?('__')
64+
raise ReservedLabelError, "label #{key} must not start with __"
65+
end
66+
67+
unless key.to_s =~ LABEL_NAME_REGEX
68+
msg = "label name must match /#{LABEL_NAME_REGEX}/"
69+
raise InvalidLabelError, msg
70+
end
6371

64-
raise ReservedLabelError, "label #{key} must not start with __"
72+
true
6573
end
6674

6775
def validate_reserved_key(key)

spec/prometheus/client/label_set_validator_spec.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@
3636
end.to raise_exception(described_class::ReservedLabelError)
3737
end
3838

39+
it 'raises InvalidLabelError if a label key contains invalid characters' do
40+
expect do
41+
validator.validate_symbols!(:@foo => 'key')
42+
end.to raise_exception(described_class::InvalidLabelError)
43+
end
44+
3945
it 'raises ReservedLabelError if a label key is reserved' do
4046
[:job, :instance, :pid].each do |label|
4147
expect do

0 commit comments

Comments
 (0)