Skip to content

Commit

Permalink
Added NewArnFromString to generalize the functionality of ARN parsing (
Browse files Browse the repository at this point in the history
  • Loading branch information
vgarvardt committed Nov 10, 2022
1 parent d6fbd49 commit ff48c35
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
22 changes: 22 additions & 0 deletions pkg/notification/notification.go
Expand Up @@ -21,6 +21,7 @@ import (
"encoding/xml"
"errors"
"fmt"
"strings"

"github.com/minio/minio-go/v7/pkg/set"
)
Expand Down Expand Up @@ -88,6 +89,27 @@ func NewArn(partition, service, region, accountID, resource string) Arn {
}
}

var (
// ErrInvalidArnPrefix is returned when ARN string format does not start with 'arn'
ErrInvalidArnPrefix = errors.New("invalid ARN format, must start with 'arn:'")
// ErrInvalidArnFormat is returned when ARN string format is not valid
ErrInvalidArnFormat = errors.New("invalid ARN format, must be 'arn:<partition>:<service>:<region>:<accountID>:<resource>'")
)

// NewArnFromString parses string representation of ARN into Arn object.
// Returns an error if the string format is incorrect.
func NewArnFromString(arn string) (Arn, error) {
parts := strings.Split(arn, ":")
if len(parts) != 6 {
return Arn{}, ErrInvalidArnFormat
}
if parts[0] != "arn" {
return Arn{}, ErrInvalidArnPrefix
}

return NewArn(parts[1], parts[2], parts[3], parts[4], parts[5]), nil
}

// String returns the string format of the ARN
func (arn Arn) String() string {
return "arn:" + arn.Partition + ":" + arn.Service + ":" + arn.Region + ":" + arn.AccountID + ":" + arn.Resource
Expand Down
28 changes: 28 additions & 0 deletions pkg/notification/notification_test.go
Expand Up @@ -1405,3 +1405,31 @@ func TestConfigEqual(t *testing.T) {
})
}
}

func TestNewArnFromString(t *testing.T) {
t.Run("valid ARN", func(t *testing.T) {
arn := NewArn("partition", "service", "region", "accountID", "resource")
arnString := arn.String()
arnFromString, err := NewArnFromString(arnString)
if err != nil {
t.Fatalf("did not exect an error, but got %v", err)
}
if arnFromString.String() != arnString {
t.Errorf("expected ARNs to be equal, but they are not: arnFromString = %s, arn = %s", arnFromString.String(), arnString)
}
})

t.Run("invalid ARN format", func(t *testing.T) {
_, err := NewArnFromString("arn:only:four:parts")
if err != ErrInvalidArnFormat {
t.Errorf("expected an error %v, but got %v", ErrInvalidArnFormat, err)
}
})

t.Run("invalid ARN prefix", func(t *testing.T) {
_, err := NewArnFromString("non-arn:partition:service:region:accountID:resource")
if err != ErrInvalidArnPrefix {
t.Errorf("expected an error %v, but got %v", ErrInvalidArnPrefix, err)
}
})
}

0 comments on commit ff48c35

Please sign in to comment.