diff --git a/src/utils/utilities.go b/src/utils/utilities.go index abe787c0..8a25458f 100644 --- a/src/utils/utilities.go +++ b/src/utils/utilities.go @@ -1,6 +1,7 @@ package utils import ( + "regexp" "strings" pb "github.com/envoyproxy/go-control-plane/envoy/service/ratelimit/v3" @@ -62,8 +63,18 @@ func MaskCredentialsInUrl(url string) string { return strings.Join(urls, ",") } -// Remove invalid characters from the stat name. +// remoteAddressRegex is used to replace remote addresses in stat names with a sanitized version. +// 1. replace masked_remote_address_1.2.3.4/32 with masked_remote_address_1_2_3_4_32 +// 2. replace remote_address_1.2.3.4 with remote_address_1_2_3_4 +var remoteAddressRegex = regexp.MustCompile(`remote_address_\d+\.\d+\.\d+\.\d+`) + +// SanitizeStatName remove invalid characters from the stat name. func SanitizeStatName(s string) string { r := strings.NewReplacer(":", "_", "|", "_") - return r.Replace(s) + result := r.Replace(s) + + for _, m := range remoteAddressRegex.FindAllString(s, -1) { + result = strings.Replace(result, m, strings.Replace(m, ".", "_", -1), -1) + } + return result } diff --git a/src/utils/utilities_test.go b/src/utils/utilities_test.go new file mode 100644 index 00000000..7c0af6b7 --- /dev/null +++ b/src/utils/utilities_test.go @@ -0,0 +1,41 @@ +package utils + +import ( + "testing" +) + +func TestSanitizeStatName(t *testing.T) { + cases := []struct { + input string + expected string + }{ + { + input: "domain.foo|bar", + expected: "domain.foo_bar", + }, + { + input: "domain.foo:bar", + expected: "domain.foo_bar", + }, + { + input: "domain.masked_remote_address_0.0.0.0/0", + expected: "domain.masked_remote_address_0_0_0_0/0", + }, + { + input: "domain.remote_address_172.18.0.1", + expected: "domain.remote_address_172_18_0_1", + }, + { + input: "domain.masked_remote_address_0.0.0.0/0_remote_address_172.18.0.1", + expected: "domain.masked_remote_address_0_0_0_0/0_remote_address_172_18_0_1", + }, + } + + for _, c := range cases { + t.Run(c.input, func(t *testing.T) { + if actual := SanitizeStatName(c.input); actual != c.expected { + t.Errorf("SanitizeStatName(%s): expected %s, actual %s", c.input, c.expected, actual) + } + }) + } +}