From 82416c651ec6e80b04c165509ba6a037e6bdb829 Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 13 Oct 2024 00:50:52 +1300 Subject: [PATCH] Remove invalid characters from tags. --- lib/metrics/tags.rb | 6 +++++- test/metrics/tags.rb | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 test/metrics/tags.rb diff --git a/lib/metrics/tags.rb b/lib/metrics/tags.rb index 60a3b83..f5f462b 100644 --- a/lib/metrics/tags.rb +++ b/lib/metrics/tags.rb @@ -5,11 +5,15 @@ module Metrics module Tags + INVALID_TAG_CHARACTERS = /[^a-z0-9\-_\.:\\]/i + def self.normalize(tags) return nil unless tags&.any? if tags.is_a?(Hash) - tags = tags.map{|key, value| "#{key}:#{value}"} + tags = tags.map do |key, value| + "#{key}:#{value}".gsub(INVALID_TAG_CHARACTERS, "_").slice(0, 127) + end end return Array(tags) diff --git a/test/metrics/tags.rb b/test/metrics/tags.rb new file mode 100644 index 0000000..5f25faa --- /dev/null +++ b/test/metrics/tags.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# Released under the MIT License. +# Copyright, 2024, by Samuel Williams. + +require "metrics/tags" + +describe Metrics::Tags do + it "can normalize an ipv6 address" do + tags = subject.normalize({"ip" => "[::1]"}) + + expect(tags).to be == ["ip:_::1_"] + end +end