From aa9966b942c9fbf11ef327f12e65d22fd604d679 Mon Sep 17 00:00:00 2001 From: Tom Martensen Date: Fri, 8 Sep 2023 09:09:27 +0200 Subject: [PATCH] add cluster name validation to infractl --- cmd/infractl/cluster/create/command.go | 26 ++++++++++++++++++++++++- cmd/infractl/cluster/create/create.bats | 10 ++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/cmd/infractl/cluster/create/command.go b/cmd/infractl/cluster/create/command.go index 6d3959d8f..46c995d29 100644 --- a/cmd/infractl/cluster/create/command.go +++ b/cmd/infractl/cluster/create/command.go @@ -118,7 +118,12 @@ func run(ctx context.Context, conn *grpc.ClientConn, cmd *cobra.Command, args [] displayUserNotes(cmd, args, &req) if len(args) > 1 { - req.Parameters["name"] = args[1] + name := args[1] + err := validateName(name) + if err != nil { + return nil, err + } + req.Parameters["name"] = name } else { name, err := determineName(ctx, conn, args[0]) if err != nil { @@ -146,6 +151,25 @@ func run(ctx context.Context, conn *grpc.ClientConn, cmd *cobra.Command, args [] return prettyResourceByID(*clusterID), nil } +func validateName(name string) error { + if len(name) < 3 { + return errors.New("cluster name too short") + } + if len(name) > 28 { + return errors.New("cluster name too long") + } + + match, err := regexp.MatchString(`^(?:[a-z](?:[-a-z0-9]{0,28}[a-z0-9])?)$`, name) + if err != nil { + return err + } + if !match { + return errors.New("The name does not match its requirements. Only lowercase letters, numbers, and '-' allowed, must start with a letter and end with a letter or number.") + } + + return nil +} + func determineWorkingEnvironment() { workingEnvironment.gitTopLevel = "" workingEnvironment.tag = "" diff --git a/cmd/infractl/cluster/create/create.bats b/cmd/infractl/cluster/create/create.bats index d432329df..732010ce1 100644 --- a/cmd/infractl/cluster/create/create.bats +++ b/cmd/infractl/cluster/create/create.bats @@ -123,6 +123,16 @@ setup() { assert_output --partial "parameter \"main-image\" was not provided" } +@test "provided name is too short" { + run infractl create test-qa-demo ab + assert_failure + assert_output --partial "Error: cluster name too short" +} + +# @test "provided name is too long" + +# @test "provided name does not match regex" + infractl() { "$ROOT"/bin/infractl -e localhost:8443 -k "$@" }