Skip to content

Commit

Permalink
Merge pull request #241 from hosswald/master
Browse files Browse the repository at this point in the history
add a sanitized version of the hostname (replace any character matchi…
  • Loading branch information
cjimti authored Sep 13, 2022
2 parents dedd745 + 5b720ae commit 8eca9de
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pkg/fwdport/fwdport.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"fmt"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -248,6 +250,19 @@ func (pfo *PortForwardOpts) addHost(host string) {

// add host to /etc/hosts
pfo.HostFile.Hosts.AddHost(pfo.LocalIp.String(), 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
Expand Down
23 changes: 23 additions & 0 deletions pkg/fwdport/fwdport_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}

0 comments on commit 8eca9de

Please sign in to comment.