diff options
| author | mo khan <mo@mokhan.ca> | 2025-04-02 17:14:27 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-04-02 17:14:27 -0600 |
| commit | 678aaa9789e15e765acf5b3761606704bf13b6b0 (patch) | |
| tree | 331b7d4df8e5aacad0fb9b7473c532a48c7d610a | |
| parent | 5c870c548107085c2582f856e3b2d63b747dcd1e (diff) | |
test: parse different types of global id
| -rw-r--r-- | pkg/gid/gid.go | 18 | ||||
| -rw-r--r-- | pkg/gid/gid_test.go | 38 |
2 files changed, 53 insertions, 3 deletions
diff --git a/pkg/gid/gid.go b/pkg/gid/gid.go index e82b073..3b9b29b 100644 --- a/pkg/gid/gid.go +++ b/pkg/gid/gid.go @@ -8,13 +8,25 @@ import ( ) func NewEntityUID(globalID string) cedar.EntityUID { + if !strings.HasPrefix(globalID, "gid://") { + return DefaultEntityUID(globalID) + } + url, err := url.Parse(globalID) if err != nil { - return cedar.NewEntityUID("User", cedar.String(globalID)) + return DefaultEntityUID(globalID) + } + items := strings.SplitN(url.Path, "/", 3) + if len(items) != 3 { + return DefaultEntityUID(globalID) } return cedar.NewEntityUID( - cedar.EntityType(url.Hostname()), - cedar.String(strings.TrimPrefix(url.Path, "/")), + cedar.EntityType(items[1]), + cedar.String(items[2]), ) } + +func DefaultEntityUID(id string) cedar.EntityUID { + return cedar.NewEntityUID("User", cedar.String(id)) +} diff --git a/pkg/gid/gid_test.go b/pkg/gid/gid_test.go new file mode 100644 index 0000000..e1f6285 --- /dev/null +++ b/pkg/gid/gid_test.go @@ -0,0 +1,38 @@ +package gid + +import ( + "testing" + + "github.com/cedar-policy/cedar-go" + "github.com/stretchr/testify/assert" +) + +func TestNewEntityUID(t *testing.T) { + t.Run("returns an Entity UID with an integer id", func(t *testing.T) { + result := NewEntityUID("gid://example/User/1") + + assert.Equal(t, cedar.EntityType("User"), result.Type) + assert.Equal(t, cedar.String("1"), result.ID) + }) + + t.Run("returns an Entity UID with a UUID", func(t *testing.T) { + result := NewEntityUID("gid://example/User/4707ce42-1017-11f0-acdf-7ec11f4b308c") + + assert.Equal(t, cedar.EntityType("User"), result.Type) + assert.Equal(t, cedar.String("4707ce42-1017-11f0-acdf-7ec11f4b308c"), result.ID) + }) + + t.Run("returns an Entity UID with a namespace", func(t *testing.T) { + result := NewEntityUID("gid://example/Authn::User/1") + + assert.Equal(t, cedar.EntityType("Authn::User"), result.Type) + assert.Equal(t, cedar.String("1"), result.ID) + }) + + t.Run("returns a default when a global id is not provided", func(t *testing.T) { + result := NewEntityUID("alice") + + assert.Equal(t, cedar.EntityType("User"), result.Type) + assert.Equal(t, cedar.String("alice"), result.ID) + }) +} |
