Skip to content

Commit

Permalink
fix: role session name length
Browse files Browse the repository at this point in the history
  • Loading branch information
mvanholsteijn committed Oct 11, 2023
1 parent cf4e38d commit 9f6da2c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
16 changes: 15 additions & 1 deletion pkg/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,26 @@ func (c *RootCommand) SetDefaults() {
}
}

func truncate(name string, maxLength int) string {
if len(name) < maxLength {
return name
}
return string([]rune(name)[0:maxLength])
}

// GenerateRoleSessionName generates a valid role session name based on the role name and pipeline id.
func GenerateRoleSessionName(roleName, pipelineId string) string {
maxLength := 64
invalidCharacters := regexp.MustCompile(`[^=,.@A-Za-z0-9_]+`)
validRoleSessionName := strings.Trim(invalidCharacters.ReplaceAllString(roleName, "-"), "-")
if pipelineId == "" {
return validRoleSessionName
return truncate(validRoleSessionName, 64)
} else {
maxLength = 64 - len(pipelineId) - 1
if maxLength <= 0 {
return truncate(pipelineId, 64)
}
validRoleSessionName = truncate(validRoleSessionName, maxLength)
}
return fmt.Sprintf("%s-%s", validRoleSessionName, pipelineId)
}
Expand Down
6 changes: 6 additions & 0 deletions pkg/cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,17 @@ func TestGenerateRoleSessionName(t *testing.T) {
{"multiple invalid chars", args{"/gitlab/role-%^$abc", "1234"}, "gitlab-role-abc-1234"},
{"all valid special chars", args{"[email protected]_", "1234"}, "[email protected]_-1234"},
{"keep dashes", args{"gitlab-role--nice", ""}, "gitlab-role-nice"},
{"truncated to 64 chars", args{"L9i3LA4rF2rtMhImJBdvsKiBEKeltlmz6VLeVMwalW6ZyWFgWtVYZxKQfKVMHK57", "232324"}, "L9i3LA4rF2rtMhImJBdvsKiBEKeltlmz6VLeVMwalW6ZyWFgWtVYZxKQf-232324"},
{"pipeline id longer than chars", args{"gitlab-role", "L9i3LA4rF2rtMhImJBdvsKiBEKeltlmz6VLeVMwalW6ZyWFgWtVYZxKQfKVMHK57AAA"}, "L9i3LA4rF2rtMhImJBdvsKiBEKeltlmz6VLeVMwalW6ZyWFgWtVYZxKQfKVMHK57"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GenerateRoleSessionName(tt.args.roleName, tt.args.pipelineId); got != tt.want {
t.Errorf("GenerateRoleSessionName() = %v, want %v", got, tt.want)
} else {
if len(got) > 64 {
t.Errorf("GenerateRoleSessionName() = %v is over 64 characters long (%d)", got, len(got))
}
}
})
}
Expand Down

0 comments on commit 9f6da2c

Please sign in to comment.