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

Sanitize stats name for remote address #716

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 13 additions & 2 deletions src/utils/utilities.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package utils

import (
"regexp"
"strings"

pb "github.com/envoyproxy/go-control-plane/envoy/service/ratelimit/v3"
Expand Down Expand Up @@ -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
}
41 changes: 41 additions & 0 deletions src/utils/utilities_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
Loading