From 9f6da2c94ea440eb527d6d351cce0688a58c4b1c Mon Sep 17 00:00:00 2001 From: Mark van Holsteijn Date: Wed, 11 Oct 2023 16:23:58 +0200 Subject: [PATCH] fix: role session name length --- pkg/cmd/root.go | 16 +++++++++++++++- pkg/cmd/root_test.go | 6 ++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index 9bd18fa..f2d2248 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -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) } diff --git a/pkg/cmd/root_test.go b/pkg/cmd/root_test.go index d119b67..7386bff 100644 --- a/pkg/cmd/root_test.go +++ b/pkg/cmd/root_test.go @@ -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{"foo=bar@binx.io_", "1234"}, "foo=bar@binx.io_-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)) + } } }) }