Skip to content

Commit

Permalink
Validate quote balance in installFlags (#556)
Browse files Browse the repository at this point in the history
* Validate balanced quotes in installFlags

Signed-off-by: Kimmo Lehto <klehto@mirantis.com>
  • Loading branch information
kke committed Sep 12, 2023
1 parent 6342c65 commit 4f8975d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
28 changes: 28 additions & 0 deletions pkg/apis/k0sctl.k0sproject.io/v1beta1/cluster/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,33 @@ func (h *Host) SetDefaults() {
}
}

func validateBalancedQuotes(val any) error {
s, ok := val.(string)
if !ok {
return fmt.Errorf("invalid type")
}

quoteCount := make(map[rune]int)

for i, ch := range s {
if i > 0 && s[i-1] == '\\' {
continue
}

if ch == '\'' || ch == '"' {
quoteCount[ch]++
}
}

for _, count := range quoteCount {
if count%2 != 0 {
return fmt.Errorf("unbalanced quotes in %s", s)
}
}

return nil
}

func (h *Host) Validate() error {
// For rig validation
v := validator.New()
Expand All @@ -89,6 +116,7 @@ func (h *Host) Validate() error {
validation.Field(&h.PrivateAddress, is.IP),
validation.Field(&h.Files),
validation.Field(&h.NoTaints, validation.When(h.Role != "controller+worker", validation.NotIn(true).Error("noTaints can only be true for controller+worker role"))),
validation.Field(&h.InstallFlags, validation.Each(validation.By(validateBalancedQuotes))),
)
}

Expand Down
19 changes: 19 additions & 0 deletions pkg/apis/k0sctl.k0sproject.io/v1beta1/cluster/host_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,22 @@ func TestK0sInstallCommand(t *testing.T) {
require.NoError(t, err)
require.Equal(t, `k0s install worker --enable-cloud-provider --data-dir=/tmp/k0s --token-file "from-configurer"`, cmd)
}

func TestValidation(t *testing.T) {
t.Run("installFlags", func(t *testing.T) {
h := Host{
Role: "worker",
InstallFlags: []string{"--foo"},
}
require.NoError(t, h.Validate())

h.InstallFlags = []string{`--foo=""`, `--bar=''`}
require.NoError(t, h.Validate())

h.InstallFlags = []string{`--foo="`, "--bar"}
require.ErrorContains(t, h.Validate(), "unbalanced quotes")

h.InstallFlags = []string{"--bar='"}
require.ErrorContains(t, h.Validate(), "unbalanced quotes")
})
}

0 comments on commit 4f8975d

Please sign in to comment.