From d813360470016e97f28f23d7de331ec67f35e642 Mon Sep 17 00:00:00 2001 From: staebler Date: Wed, 21 Nov 2018 15:07:20 -0500 Subject: [PATCH] asset/installconfig: move uri validation to validation package Move the uri validation from pkg/asset/installconfig/libvirt to pkg/validation for consistency with other validation functions. https://jira.coreos.com/browse/CORS-850 --- pkg/asset/installconfig/libvirt/libvirt.go | 17 ++----------- pkg/validate/validate.go | 13 ++++++++++ pkg/validate/validate_test.go | 29 ++++++++++++++++++++++ 3 files changed, 44 insertions(+), 15 deletions(-) diff --git a/pkg/asset/installconfig/libvirt/libvirt.go b/pkg/asset/installconfig/libvirt/libvirt.go index ce06a438cb4..f12d8da9758 100644 --- a/pkg/asset/installconfig/libvirt/libvirt.go +++ b/pkg/asset/installconfig/libvirt/libvirt.go @@ -3,14 +3,13 @@ package libvirt import ( "context" - "fmt" - "net/url" "github.com/pkg/errors" survey "gopkg.in/AlecAivazis/survey.v1" "github.com/openshift/installer/pkg/rhcos" "github.com/openshift/installer/pkg/types/libvirt" + "github.com/openshift/installer/pkg/validate" ) const ( @@ -55,17 +54,5 @@ func Platform() (*libvirt.Platform, error) { // uriValidator validates if the answer provided in prompt is a valid // url and has non-empty scheme. func uriValidator(ans interface{}) error { - return validURI(ans.(string)) -} - -// validURI validates if the URI is a valid URI with a non-empty scheme. -func validURI(uri string) error { - parsed, err := url.Parse(uri) - if err != nil { - return err - } - if parsed.Scheme == "" { - return fmt.Errorf("invalid URI %q (no scheme)", uri) - } - return nil + return validate.URI(ans.(string)) } diff --git a/pkg/validate/validate.go b/pkg/validate/validate.go index d52d894a720..dc89541f916 100644 --- a/pkg/validate/validate.go +++ b/pkg/validate/validate.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "net" + "net/url" "regexp" "strconv" "strings" @@ -220,3 +221,15 @@ func SSHPublicKey(v string) error { _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(v)) return err } + +// URI validates if the URI is a valid absolute URI. +func URI(uri string) error { + parsed, err := url.Parse(uri) + if err != nil { + return err + } + if !parsed.IsAbs() { + return fmt.Errorf("invalid URI %q (no scheme)", uri) + } + return nil +} diff --git a/pkg/validate/validate_test.go b/pkg/validate/validate_test.go index c791ac15bde..b2d3ff2a1c4 100644 --- a/pkg/validate/validate_test.go +++ b/pkg/validate/validate_test.go @@ -384,3 +384,32 @@ func TestSSHPublicKey(t *testing.T) { }) } } + +func TestURI(t *testing.T) { + cases := []struct { + name string + uri string + valid bool + }{ + { + name: "valid", + uri: "https://example.com", + valid: true, + }, + { + name: "missing scheme", + uri: "example.com", + valid: false, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := URI(tc.uri) + if tc.valid { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } + }) + } +}