Skip to content

Commit

Permalink
Merge pull request #12 from armosec/fixwlid
Browse files Browse the repository at this point in the history
do not truncate wlid if namespace is empty, use string builder
  • Loading branch information
David Wertenteil authored Dec 11, 2023
2 parents 88a416b + 8d05ad4 commit fb8ffc6
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 11 deletions.
27 changes: 16 additions & 11 deletions wlid/wlid.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,24 +81,29 @@ func generateWLID(pLevel0, level0, pLevel1, level1, k, name string) string {
kind := strings.ToLower(k)
kind = strings.Replace(kind, "-", "", -1)

wlid := WlidPrefix
wlid += fmt.Sprintf("%s%s", pLevel0, level0)
if level1 == "" {
return wlid
}
wlid += fmt.Sprintf("/%s%s", pLevel1, level1)
var wlid strings.Builder
wlid.WriteString(WlidPrefix)
wlid.WriteString(pLevel0)
wlid.WriteString(level0)

// don't exit if level1 is empty
wlid.WriteString("/")
wlid.WriteString(pLevel1)
wlid.WriteString(level1)

if kind == "" {
return wlid
return wlid.String()
}
wlid += fmt.Sprintf("/%s", kind)
wlid.WriteString("/")
wlid.WriteString(kind)

if name == "" {
return wlid
return wlid.String()
}
wlid += fmt.Sprintf("-%s", name)
wlid.WriteString("-")
wlid.WriteString(name)

return wlid
return wlid.String()
}

// GetWLID get the calculated wlid
Expand Down
49 changes: 49 additions & 0 deletions wlid/wlid_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package wlid

import (
"github.com/stretchr/testify/assert"
"testing"
)

Expand All @@ -27,3 +28,51 @@ func TestSpiffeSIDInfoSuccess(t *testing.T) {
t.Errorf("TestSpiffeSIDInfoSuccess failed to parse %v", SID)
}
}

func Test_generateWLID(t *testing.T) {
type args struct {
pLevel0 string
level0 string
pLevel1 string
level1 string
k string
name string
}
tests := []struct {
name string
args args
want string
}{
{
name: "k8s wlid",
args: args{
pLevel0: ClusterWlidPrefix,
level0: "HipsterShopCluster2",
pLevel1: NamespaceWlidPrefix,
level1: "prod",
k: "Deployment",
name: "cartservice",
},
want: "wlid://cluster-HipsterShopCluster2/namespace-prod/deployment-cartservice",
},
{
name: "k8s wlid no namespace",
args: args{
pLevel0: ClusterWlidPrefix,
level0: "HipsterShopCluster2",
pLevel1: NamespaceWlidPrefix,
level1: "",
k: "ClusterRoleBinding",
name: "cartservice",
},
want: "wlid://cluster-HipsterShopCluster2/namespace-/clusterrolebinding-cartservice",
// FIXME: do we want "wlid://cluster-HipsterShopCluster2/clusterrolebinding-cartservice" instead?
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := generateWLID(tt.args.pLevel0, tt.args.level0, tt.args.pLevel1, tt.args.level1, tt.args.k, tt.args.name)
assert.Equal(t, tt.want, got)
})
}
}

0 comments on commit fb8ffc6

Please sign in to comment.