Add a URN validation method. (#3386)

This method can be used to check whether or not a URN is well-formed.
This is used by the provider reference parser to avoid panicking on
malformed URNs.
This commit is contained in:
Pat Gavlin 2019-10-21 19:09:39 -07:00 committed by GitHub
parent 76a0079641
commit f14eba46b5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 1 deletions

View file

@ -58,6 +58,9 @@ func GetProviderPackage(typ tokens.Type) tokens.Package {
}
func validateURN(urn resource.URN) error {
if !urn.IsValid() {
return errors.Errorf("%s is not a valid URN", urn)
}
typ := urn.Type()
if typ.Module() != "pulumi:providers" {
return errors.Errorf("invalid module in type: expected 'pulumi:providers', got '%v'", typ.Module())

View file

@ -31,7 +31,8 @@ func TestRoundTripProviderType(t *testing.T) {
func TestParseReferenceInvalidURN(t *testing.T) {
str := "not::a:valid:urn::id"
assert.Panics(t, func() { _, _ = ParseReference(str) })
_, err := ParseReference(str)
assert.Error(t, err)
}
func TestParseReferenceInvalidModule(t *testing.T) {

View file

@ -68,6 +68,14 @@ func NewURN(stack tokens.QName, proj tokens.PackageName, parentType, baseType to
)
}
// IsValid returns true if the URN is well-formed.
func (urn URN) IsValid() bool {
if !strings.HasPrefix(string(urn), URNPrefix) {
return false
}
return len(strings.Split(string(urn), URNNameDelimiter)) == 4
}
// URNName returns the URN name part of a URN (i.e., strips off the prefix).
func (urn URN) URNName() string {
s := string(urn)