troubleshoot icon indicating copy to clipboard operation
troubleshoot copied to clipboard

strings.TrimLeft is used instead of TrimPrefix

Open GrosQuildu opened this issue 2 years ago • 3 comments

Bug Description

The PortForward method incorrectly uses strings.TrimLeft. The "htps:/" argument is treated as a cutset (set of characters) and not as a prefix.

https://github.com/replicatedhq/troubleshoot/blob/6493064e4599adb2a4f1255d90052872e73f5d8c/pkg/k8sutil/portforward.go#L23

The hostIP will be set to esis.example.com instead of thesis.example.com for config.Host https://thesis.example.com.

Fix is to use strings.TrimPrefix.

GrosQuildu avatar Apr 18 '23 16:04 GrosQuildu

Thanks for bringing this to our attention. We will prioritise to get it fixed.

banjoh avatar Apr 20 '23 13:04 banjoh

Likely the most reliable option is to use https://pkg.go.dev/net/url#URL.Hostname rather than a string function.

xavpaice avatar May 29 '23 02:05 xavpaice

I got burnt by this exact bug in a completely different project. Stumbled upon this issue while searching the Internet.

Here are my suggestions:

// Suggested Solution 1
hostIP := strings.TrimPrefix(strings.TrimPrefix(config.Host, "http://"), "https://")

// Suggested Solution 2
var regexURLScheme = regexp.MustCompile(`(?i)^https?://`)
hostIP := regexURLScheme.ReplaceAllString(config.Host, "")

// Suggested Solution 3
hostURL, err := url.Parse(config.Host)
if err != nil {
	panic(err)
}
hostIP := hostURL.Host

Svintooo avatar Sep 08 '23 13:09 Svintooo