Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate label names #236

Merged
merged 2 commits into from
Jan 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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/
dmagliola marked this conversation as resolved.
Show resolved Hide resolved

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