Skip to content
Merged
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
22 changes: 6 additions & 16 deletions defaults.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package purl

import (
"net/url"
"strings"
)

Expand Down Expand Up @@ -39,22 +40,11 @@ func IsNonDefaultRegistry(purlType, registryURL string) bool {
return !IsDefaultRegistry(purlType, registryURL)
}

// extractHost extracts the host from a URL string without using net/url.Parse.
// extractHost extracts the hostname from a URL string using net/url.Parse.
func extractHost(rawURL string) string {
s := rawURL
// Strip scheme
if i := strings.Index(s, "://"); i >= 0 {
s = s[i+3:]
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
// Strip userinfo
if i := strings.Index(s, "@"); i >= 0 {
s = s[i+1:]
}
// Strip path, query, fragment
for _, sep := range []byte{'/', '?', '#'} {
if i := strings.IndexByte(s, sep); i >= 0 {
s = s[:i]
}
}
return s
return u.Hostname()
}
18 changes: 18 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,24 @@ func TestIsNonDefaultRegistry(t *testing.T) {
}
}

func TestExtractHostRejectsUserinfo(t *testing.T) {
tests := []struct {
input string
want string
}{
{"https://evil.com@registry.npmjs.org/path", "registry.npmjs.org"},
{"https://registry.npmjs.org", "registry.npmjs.org"},
{"https://user:pass@evil.com/path", "evil.com"},
{"not-a-url", ""},
}
for _, tt := range tests {
got := extractHost(tt.input)
if got != tt.want {
t.Errorf("extractHost(%q) = %q, want %q", tt.input, got, tt.want)
}
}
}

func TestIsPrivateRegistry(t *testing.T) {
tests := []struct {
purl string
Expand Down