Skip to content

Commit

Permalink
replace special chars in user names
Browse files Browse the repository at this point in the history
  • Loading branch information
MatousJobanek committed Dec 17, 2024
1 parent 9ef0ea0 commit 8b4738f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
15 changes: 14 additions & 1 deletion pkg/cmd/generate/cluster.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package generate

import (
"regexp"
"strings"

"github.com/kubesaw/ksctl/pkg/configuration"
)

Expand Down Expand Up @@ -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 {
Expand All @@ -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, "-")
}
14 changes: 13 additions & 1 deletion pkg/cmd/generate/cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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, ""),
),
)

Expand Down Expand Up @@ -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*&+"))
}

0 comments on commit 8b4738f

Please sign in to comment.