Skip to content

Commit 8e982a4

Browse files
authored
Sanitize username for use as a label (#116)
1 parent 703f6aa commit 8e982a4

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

internal/webhook/appwrapper_webhook.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ func (w *AppWrapperWebhook) Default(ctx context.Context, obj runtime.Object) err
7979
return err
8080
}
8181
userInfo := request.UserInfo
82-
aw.Labels = utilmaps.MergeKeepFirst(map[string]string{AppWrapperUsernameLabel: userInfo.Username, AppWrapperUserIDLabel: userInfo.UID}, aw.Labels)
82+
username := utils.SanitizeLabel(userInfo.Username)
83+
aw.Labels = utilmaps.MergeKeepFirst(map[string]string{AppWrapperUsernameLabel: username, AppWrapperUserIDLabel: userInfo.UID}, aw.Labels)
8384
return nil
8485
}
8586

pkg/utils/utils.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package utils
1818

1919
import (
2020
"fmt"
21+
"regexp"
2122
"strconv"
2223
"strings"
2324

@@ -346,3 +347,18 @@ func ValidatePodSets(obj *unstructured.Unstructured, podSets []workloadv1beta2.A
346347

347348
return nil
348349
}
350+
351+
var labelRegex = regexp.MustCompile(`[^-_.\w]`)
352+
353+
// SanitizeLabel sanitizes a string for use as a label
354+
func SanitizeLabel(label string) string {
355+
// truncate to max length
356+
if len(label) > 63 {
357+
label = label[0:63]
358+
}
359+
// replace invalid characters with underscores
360+
label = labelRegex.ReplaceAllString(label, "_")
361+
// trim non-alphanumeric characters at both ends
362+
label = strings.Trim(label, "-_.")
363+
return label
364+
}

0 commit comments

Comments
 (0)