updated regex to properly handle more cases, extended tests and update pattern access

Signed-off-by: Yannick Alexander <yannick@alexanderdev.io>
pull/31986/head
Yannick Alexander 3 months ago
parent 0c347d2f9e
commit 592e4c7365
No known key found for this signature in database

@ -229,7 +229,7 @@ type (
// hostRegex is a pretty naive regex for validating host urls. The goal of it is not to ultimately validate all possible valid hosts,
// but to catch common user errors such as including a scheme or path in the host string.
var hostRegex = regexp.MustCompile(`^(?P<scheme>[a-z]*:\/\/)?(?P<host>[a-zA-Z0-9-\.\:]+)(?P<path>\/.*)?$`)
var hostRegex = regexp.MustCompile(`^(?P<scheme>[a-zA-Z][a-zA-Z0-9+\-.]*:\/\/)?(?P<host>[a-zA-Z0-9\-._:\[\]]+)(?P<path>\/.*)?$`)
// validateHost checks that the host matches some required pre-checks e.g. does not contain a scheme or path.
// While ORAS will also validate some of these things, the current errors are a bit opaque.
@ -240,8 +240,8 @@ func validateHost(host string) error {
return fmt.Errorf("invalid host: %q", host)
}
scheme := matches[1]
path := matches[3]
scheme := matches[hostRegex.SubexpIndex("scheme")]
path := matches[hostRegex.SubexpIndex("path")]
if scheme != "" {
return fmt.Errorf("host should not contain a scheme (e.g. http://), found %q", scheme)

@ -169,6 +169,51 @@ func TestValidateHost(t *testing.T) {
host: "oci://ghcr.io",
wantErr: true,
},
{
name: "domain with uppercase scheme",
host: "HTTPS://ghcr.io",
wantErr: true,
},
{
name: "scheme with plus sign",
host: "coap+tcp://ghcr.io",
wantErr: true,
},
{
name: "scheme with dot and hyphen",
host: "my.custom-scheme://ghcr.io",
wantErr: true,
},
{
name: "IPv6 loopback with port",
host: "[::1]:5000",
wantErr: false,
},
{
name: "IPv6 full address with port",
host: "[2001:db8::1]:443",
wantErr: false,
},
{
name: "IPv4 address with port",
host: "192.168.1.1:5000",
wantErr: false,
},
{
name: "host with underscore",
host: "my_registry.local",
wantErr: false,
},
{
name: "scheme with path",
host: "https://ghcr.io/myrepo",
wantErr: true,
},
{
name: "empty string",
host: "",
wantErr: true,
},
}
for _, tt := range tests {

Loading…
Cancel
Save