From 8b4738f7fd367455b82f654f231c0bc940554908 Mon Sep 17 00:00:00 2001 From: Matous Jobanek Date: Tue, 17 Dec 2024 10:12:13 +0100 Subject: [PATCH] replace special chars in user names --- pkg/cmd/generate/cluster.go | 15 ++++++++++++++- pkg/cmd/generate/cluster_test.go | 14 +++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/pkg/cmd/generate/cluster.go b/pkg/cmd/generate/cluster.go index b34b5f3..067a0f6 100644 --- a/pkg/cmd/generate/cluster.go +++ b/pkg/cmd/generate/cluster.go @@ -1,6 +1,9 @@ package generate import ( + "regexp" + "strings" + "github.com/kubesaw/ksctl/pkg/configuration" ) @@ -52,7 +55,7 @@ func ensureUsers(ctx *clusterContext, objsCache objectsCache) error { m := &permissionsManager{ objectsCache: objsCache, createSubject: ensureUserIdentityAndGroups(user.ID, user.Groups), - subjectBaseName: user.Name, + subjectBaseName: sanitizeUserName(user.Name), } // create the subject if explicitly requested (even if there is no specific permissions) if user.AllClusters { @@ -67,3 +70,13 @@ func ensureUsers(ctx *clusterContext, objsCache objectsCache) error { return nil } + +var specialCharRegexp = regexp.MustCompile("[^A-Za-z0-9]") + +func sanitizeUserName(userName string) string { + sanitized := specialCharRegexp.ReplaceAllString(userName, "-") + for strings.Contains(sanitized, "--") { + sanitized = strings.ReplaceAll(sanitized, "--", "-") + } + return strings.Trim(sanitized, "-") +} diff --git a/pkg/cmd/generate/cluster_test.go b/pkg/cmd/generate/cluster_test.go index 43afe19..eea46a0 100644 --- a/pkg/cmd/generate/cluster_test.go +++ b/pkg/cmd/generate/cluster_test.go @@ -9,6 +9,7 @@ import ( "github.com/kubesaw/ksctl/pkg/assets" "github.com/kubesaw/ksctl/pkg/configuration" . "github.com/kubesaw/ksctl/pkg/test" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -138,7 +139,7 @@ func TestUsers(t *testing.T) { HostClusterRoleBindings("cluster-monitoring-view"), MemberRoleBindings("toolchain-member-operator", Role("restart-deployment"), ClusterRole("view")), MemberClusterRoleBindings("cluster-monitoring-view")), - User("alice-clusteradmin", []string{"12340"}, true, ""), + User("alice-@#$%^:+clusteradmin", []string{"12340"}, true, ""), ), ) @@ -238,3 +239,14 @@ func newKubeSawAdminsWithDefaultClusters(serviceAccounts []assets.ServiceAccount serviceAccounts, users) } + +func TestSanitizeUserName(t *testing.T) { + assert.Equal(t, "special-name", sanitizeUserName("special-name")) + assert.Equal(t, "special-name", sanitizeUserName("special!@$#%^&*(+)name")) + assert.Equal(t, "special-name", sanitizeUserName("special---name")) + assert.Equal(t, "special-name", sanitizeUserName("special-$-%^-name")) + assert.Equal(t, "special-name", sanitizeUserName("special---name")) + assert.Equal(t, "special", sanitizeUserName("special-")) + assert.Equal(t, "name", sanitizeUserName("-name")) + assert.Equal(t, "special-name", sanitizeUserName("!@special-name*&+")) +}