Commit 678aaa9
Changed files (2)
pkg
gid
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))
+}
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)
+ })
+}