Skip to content

Commit

Permalink
Merge pull request #236 from prometheus/sinjo-validate-label-names
Browse files Browse the repository at this point in the history
Validate label names
  • Loading branch information
Sinjo authored Jan 9, 2022
2 parents 309de65 + 3519342 commit 391aa20
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
11 changes: 9 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,15 @@ 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
raise InvalidLabelError, "label name must match /#{LABEL_NAME_REGEX}/"
end

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

def validate_reserved_key(key)
Expand Down
8 changes: 7 additions & 1 deletion spec/prometheus/client/label_set_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
expect(validator.validate_symbols!(version: 'alpha')).to eql(true)
end

it 'raises Invaliddescribed_classError if a label set is not a hash' do
it 'raises InvalidLabelSetError if a label set is not a hash' do
expect do
validator.validate_symbols!('invalid')
end.to raise_exception invalid
Expand All @@ -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 391aa20

Please sign in to comment.