Skip to content

Commit

Permalink
Validate label names
Browse files Browse the repository at this point in the history
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
Signed-off-by: Chris Sinjakli <chris@sinjakli.co.uk>
  • Loading branch information
Sinjo committed Dec 25, 2021
1 parent fefde16 commit b06f8e7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/prometheus/client/label_set_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module Client
class LabelSetValidator
# TODO: we might allow setting :instance in the future
BASE_RESERVED_LABELS = [:job, :instance, :pid].freeze
LABEL_NAME_REGEX = /\A[a-zA-Z_][a-zA-Z0-9_]*\Z/

class LabelSetError < StandardError; end
class InvalidLabelSetError < LabelSetError; end
Expand Down Expand Up @@ -59,9 +60,16 @@ def validate_symbol(key)
end

def validate_name(key)
return true unless key.to_s.start_with?('__')
if key.to_s.start_with?('__')
raise ReservedLabelError, "label #{key} must not start with __"
end

unless key.to_s =~ LABEL_NAME_REGEX
msg = "label name must match /#{LABEL_NAME_REGEX}/"
raise InvalidLabelError, msg
end

raise ReservedLabelError, "label #{key} must not start with __"
true
end

def validate_reserved_key(key)
Expand Down
6 changes: 6 additions & 0 deletions spec/prometheus/client/label_set_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@
end.to raise_exception(described_class::ReservedLabelError)
end

it 'raises InvalidLabelError if a label key contains invalid characters' do
expect do
validator.validate_symbols!(:@foo => 'key')
end.to raise_exception(described_class::InvalidLabelError)
end

it 'raises ReservedLabelError if a label key is reserved' do
[:job, :instance, :pid].each do |label|
expect do
Expand Down

0 comments on commit b06f8e7

Please sign in to comment.