diff --git a/pkg/fwdport/fwdport.go b/pkg/fwdport/fwdport.go index b31f5023..70b2e8af 100644 --- a/pkg/fwdport/fwdport.go +++ b/pkg/fwdport/fwdport.go @@ -7,6 +7,7 @@ import ( "net/http" "regexp" "strconv" + "strings" "sync" "time" @@ -250,14 +251,20 @@ func (pfo *PortForwardOpts) addHost(host string) { // add host to /etc/hosts pfo.HostFile.Hosts.AddHost(pfo.LocalIp.String(), host) - // replace illegal characters with underscore and add another entry if this changes the hostname - hostnameIllegalChars := regexp.MustCompile(`[^a-zA-Z0-9\-.]`) - sanitizedHost := hostnameIllegalChars.ReplaceAllString(host, `_`) + sanitizedHost := sanitizeHost(host) if host != sanitizedHost { pfo.addHost(sanitizedHost) //should recurse only once } } +// make sure any non-alphanumeric characters in the context name don't make it to the generated hostname +func sanitizeHost(host string) string { + hostnameIllegalChars := regexp.MustCompile(`[^a-zA-Z0-9\-]`) + replacementChar := `-` + sanitizedHost := strings.Trim(hostnameIllegalChars.ReplaceAllString(host, replacementChar), replacementChar) + return sanitizedHost +} + // AddHosts adds hostname entries to /etc/hosts func (pfo *PortForwardOpts) AddHosts() { diff --git a/pkg/fwdport/fwdport_test.go b/pkg/fwdport/fwdport_test.go new file mode 100644 index 00000000..e13a0ac4 --- /dev/null +++ b/pkg/fwdport/fwdport_test.go @@ -0,0 +1,23 @@ +package fwdport + +import "testing" + +func Test_sanitizeHost(t *testing.T) { + tests := []struct { + contextName string + want string + }{ + { // This is how Openshift generates context names + contextName: "service-name.namespace.project-name/cluster-name:6443/username", + want: "service-name-namespace-project-name-cluster-name-6443-username", + }, + {contextName: "-----test-----", want: "test"}, + } + for _, tt := range tests { + t.Run("Sanitize hostname generated from context and namespace: "+tt.contextName, func(t *testing.T) { + if got := sanitizeHost(tt.contextName); got != tt.want { + t.Errorf("sanitizeHost() = %v, want %v", got, tt.want) + } + }) + } +}