Skip to content

Commit

Permalink
fix: generate role session name should only contain valid chars
Browse files Browse the repository at this point in the history
  • Loading branch information
mvanholsteijn committed Sep 18, 2023
1 parent 65b003e commit 4caa1ae
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
19 changes: 13 additions & 6 deletions pkg/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"errors"
"fmt"
"os"
"regexp"
"strconv"
"strings"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
Expand Down Expand Up @@ -81,6 +83,16 @@ func (c *RootCommand) SetDefaults() {
}
}

// GenerateRoleSessionName generates a valid role session name based on the role name and pipeline id.
func GenerateRoleSessionName(roleName, pipelineId string) string {
invalidCharacters := regexp.MustCompile(`[^=,.@A-Za-z0-9_]+`)
validRoleSessionName := strings.Trim(invalidCharacters.ReplaceAllString(roleName, "-"), "-")
if pipelineId == "" {
return validRoleSessionName
}
return fmt.Sprintf("%s-%s", validRoleSessionName, pipelineId)
}

// GetSTSCredentials gets the STS credentials based upon the gitlab pipeline id token.
func (c *RootCommand) GetSTSCredentials() error {
if c.RoleName == "" {
Expand All @@ -100,12 +112,7 @@ func (c *RootCommand) GetSTSCredentials() error {
}

if c.RoleSessionName == "" {
if c.PipelineId == "" {
c.RoleSessionName = c.RoleName

} else {
c.RoleSessionName = fmt.Sprintf("%s-%s", c.RoleName, c.PipelineId)
}
c.RoleSessionName = GenerateRoleSessionName(c.RoleName, c.PipelineId)
}

var err error
Expand Down
27 changes: 27 additions & 0 deletions pkg/cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,30 @@ func TestSetDefaultsInvalidDuration(t *testing.T) {
t.Errorf("expected the default of 3600 as duration seconds")
}
}

func TestGenerateRoleSessionName(t *testing.T) {
type args struct {
roleName string
pipelineId string
}
tests := []struct {
name string
args args
want string
}{
{"no pipeline", args{"role", ""}, "role"},
{"role and pipeline", args{"role", "1234"}, "role-1234"},
{"no leading or trailing dash", args{"-role-", ""}, "role"},
{"invalid chars", args{"/gitlab/role", "1234"}, "gitlab-role-1234"},
{"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"},
}
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)
}
})
}
}

0 comments on commit 4caa1ae

Please sign in to comment.