From fde6df977fd185a108056018ad162cf1e30bf9a7 Mon Sep 17 00:00:00 2001 From: Francesco Ilario Date: Tue, 19 Mar 2024 16:44:25 +0100 Subject: [PATCH] optimizing EncodeUserIdentifier (#415) * move regex compilation out of EncodeUserIdentifier Signed-off-by: Francesco Ilario * remove regexp from EncodeUserIdentifier Signed-off-by: Francesco Ilario --------- Signed-off-by: Francesco Ilario Co-authored-by: Alexey Kazakov --- pkg/signup/service/signup_service.go | 42 ++++++++++++++++------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/pkg/signup/service/signup_service.go b/pkg/signup/service/signup_service.go index 567254fd..e268b1f8 100644 --- a/pkg/signup/service/signup_service.go +++ b/pkg/signup/service/signup_service.go @@ -30,10 +30,7 @@ import ( ) const ( - DNS1123NameMaximumLength = 63 - DNS1123NotAllowedCharacters = "[^-a-z0-9]" - DNS1123NotAllowedStartCharacters = "^[^a-z0-9]+" - DNS1123NotAllowedEndCharacters = "[^a-z0-9]+$" + DNS1123NameMaximumLength = 63 // NoSpaceKey is the query key for specifying whether the UserSignup should be created without a Space NoSpaceKey = "no-space" @@ -236,20 +233,8 @@ func extractEmailHost(email string) string { // resources. If a change is absolutely required, then all existing UserSignup instances must be migrated // to the new value func EncodeUserIdentifier(subject string) string { - // Convert to lower case - encoded := strings.ToLower(subject) - - // Remove all invalid characters - nameNotAllowedChars := regexp.MustCompile(DNS1123NotAllowedCharacters) - encoded = nameNotAllowedChars.ReplaceAllString(encoded, "") - - // Remove invalid start characters - nameNotAllowedStartChars := regexp.MustCompile(DNS1123NotAllowedStartCharacters) - encoded = nameNotAllowedStartChars.ReplaceAllString(encoded, "") - - // Remove invalid end characters - nameNotAllowedEndChars := regexp.MustCompile(DNS1123NotAllowedEndCharacters) - encoded = nameNotAllowedEndChars.ReplaceAllString(encoded, "") + // Sanitize subject to be compliant with DNS labels format (RFC-1123) + encoded := sanitizeDNS1123(subject) // Add a checksum prefix if the encoded value is different to the original subject value if encoded != subject { @@ -264,6 +249,27 @@ func EncodeUserIdentifier(subject string) string { return encoded } +func sanitizeDNS1123(str string) string { + // convert to lowercase + lstr := strings.ToLower(str) + + // remove unwanted characters + b := strings.Builder{} + for _, r := range lstr { + switch { + case r >= '0' && r <= '9': + fallthrough + case r >= 'a' && r <= 'z': + fallthrough + case r == '-': + b.WriteRune(r) + } + } + + // remove leading and trailing '-' + return strings.Trim(b.String(), "-") +} + // Signup reactivates the deactivated UserSignup resource or creates a new one with the specified username and userID // if doesn't exist yet. func (s *ServiceImpl) Signup(ctx *gin.Context) (*toolchainv1alpha1.UserSignup, error) {