Skip to content

Commit

Permalink
Reject unknown sub-commands
Browse files Browse the repository at this point in the history
Cobra has the property of not reporting any unrecognized sub-commands
and simply displaying the help page for any command that doesn't have a
run function set.

Add a unit test that probes all sub-commands to properly reject unknown
sub-commands. Whenever a sub-command is added that accepts arguments and
doesn't declare them as ValidArgs, it must be added to the ignore list
at the beginning of that test.

Signed-off-by: Tom Wieczorek <[email protected]>
  • Loading branch information
twz123 committed Dec 20, 2024
1 parent d8739ee commit ca4856b
Show file tree
Hide file tree
Showing 39 changed files with 248 additions and 96 deletions.
2 changes: 2 additions & 0 deletions cmd/airgap/airgap.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ func NewAirgapCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "airgap",
Short: "Manage airgap setup",
Args: cobra.NoArgs,
Run: func(*cobra.Command, []string) { /* Enforce arg validation. */ },
}

cmd.AddCommand(NewAirgapListImagesCmd())
Expand Down
3 changes: 2 additions & 1 deletion cmd/airgap/listimages.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ func NewAirgapListImagesCmd() *cobra.Command {
Use: "list-images",
Short: "List image names and version needed for air-gap install",
Example: `k0s airgap list-images`,
RunE: func(cmd *cobra.Command, args []string) error {
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand Down
12 changes: 5 additions & 7 deletions cmd/airgap/listimages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package airgap
package airgap_test

import (
"errors"
Expand All @@ -26,6 +26,7 @@ import (
"testing"
"testing/iotest"

"github.com/k0sproject/k0s/cmd"
internalio "github.com/k0sproject/k0s/internal/io"
"github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1"

Expand All @@ -46,15 +47,12 @@ func TestAirgapListImages(t *testing.T) {

t.Run("HonorsIOErrors", func(t *testing.T) {
var writes uint
underTest := NewAirgapListImagesCmd()
underTest.SetIn(iotest.ErrReader(errors.New("unexpected read from standard input")))
underTest, _, stderr := newAirgapListImagesCmdWithConfig(t, "")
underTest.SilenceUsage = true // Cobra writes usage to stdout on errors 🤔
underTest.SetOut(internalio.WriterFunc(func(p []byte) (int, error) {
writes++
return 0, assert.AnError
}))
var stderr strings.Builder
underTest.SetErr(&stderr)

assert.Same(t, assert.AnError, underTest.Execute())
assert.Equal(t, uint(1), writes, "Expected a single write to stdout")
Expand Down Expand Up @@ -127,8 +125,8 @@ func newAirgapListImagesCmdWithConfig(t *testing.T, config string, args ...strin
require.NoError(t, os.WriteFile(configFile, []byte(config), 0644))

out, err = new(strings.Builder), new(strings.Builder)
cmd := NewAirgapListImagesCmd()
cmd.SetArgs(append([]string{"--config=" + configFile}, args...))
cmd := cmd.NewRootCmd()
cmd.SetArgs(append([]string{"airgap", "--config=" + configFile, "list-images"}, args...))
cmd.SetIn(iotest.ErrReader(errors.New("unexpected read from standard input")))
cmd.SetOut(out)
cmd.SetErr(err)
Expand Down
3 changes: 2 additions & 1 deletion cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,13 @@ func NewAPICmd() *cobra.Command {
cmd := &cobra.Command{
Use: "api",
Short: "Run the controller API",
Args: cobra.NoArgs,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
logrus.SetOutput(cmd.OutOrStdout())
k0slog.SetInfoLevel()
return config.CallParentPersistentPreRun(cmd, args)
},
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand Down
5 changes: 3 additions & 2 deletions cmd/backup/backup_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ func NewBackupCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "backup",
Short: "Back-Up k0s configuration. Must be run as root (or with sudo)",
Args: cobra.NoArgs,
PreRun: func(cmd *cobra.Command, args []string) {
// ensure logs don't mess up output
logrus.SetOutput(cmd.ErrOrStderr())
},
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand All @@ -69,7 +70,7 @@ func NewBackupCmd() *cobra.Command {

func (c *command) backup(savePath string, out io.Writer) error {
if os.Geteuid() != 0 {
logrus.Fatal("this command must be run as root!")
return errors.New("this command must be run as root!")
}

if savePath != "-" && !dir.IsDirectory(savePath) {
Expand Down
1 change: 1 addition & 0 deletions cmd/backup/backup_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func NewBackupCmd() *cobra.Command {
return &cobra.Command{
Use: "backup",
Short: "Back-Up k0s configuration. Not supported on Windows OS",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return errors.New("unsupported Operating System for this command")
},
Expand Down
19 changes: 19 additions & 0 deletions cmd/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,29 @@ func NewConfigCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "config",
Short: "Configuration related sub-commands",
Args: cobra.NoArgs,
Run: func(*cobra.Command, []string) { /* Enforce arg validation. */ },
}
cmd.AddCommand(NewCreateCmd())
cmd.AddCommand(NewEditCmd())
cmd.AddCommand(NewStatusCmd())
cmd.AddCommand(NewValidateCmd())
return cmd
}

func reExecKubectl(cmd *cobra.Command, kubectlArgs ...string) error {
args := []string{"kubectl"}
if dataDir, err := cmd.Flags().GetString("data-dir"); err != nil {
return err
} else if dataDir != "" {
args = append(args, "--data-dir", dataDir)
}

root := cmd.Root()
root.SetArgs(append(args, kubectlArgs...))

silenceErrors := root.SilenceErrors
defer func() { root.SilenceErrors = silenceErrors }()
root.SilenceErrors = true // So that errors aren't printed twice.
return root.Execute()
}
64 changes: 64 additions & 0 deletions cmd/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
Copyright 2024 k0s authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package config_test

import (
"errors"
"fmt"
"slices"
"strings"
"testing"
"testing/iotest"

"github.com/k0sproject/k0s/cmd"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)

func TestConfigCmd_RejectsUnknownCommands(t *testing.T) {
for _, cmds := range [][]string{
{"config"},
{"config", "create"},
{"config", "edit"},
{"config", "status"},
{"config", "validate"},
} {
subCommand := strings.Join(cmds, " ")
t.Run(subCommand, func(t *testing.T) {
var stdout, stderr strings.Builder
underTest := cmd.NewRootCmd()

// Reset any "required" annotations on flags
if cmd, _, err := underTest.Find(cmds); assert.NoError(t, err) {
flags := cmd.Flags()
flags.VisitAll(func(flag *pflag.Flag) {
flag.Annotations = nil
})
}

underTest.SetArgs(slices.Concat(cmds, []string{"bogus"}))
underTest.SetIn(iotest.ErrReader(errors.New("unexpected read from standard input")))
underTest.SetOut(&stdout)
underTest.SetErr(&stderr)

msg := fmt.Sprintf(`unknown command "bogus" for "k0s %s"`, subCommand)
assert.ErrorContains(t, underTest.Execute(), msg)
assert.Equal(t, "Error: "+msg+"\n", stderr.String())
assert.Empty(t, stdout.String())
})
}
}
3 changes: 2 additions & 1 deletion cmd/config/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ func NewCreateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "create",
Short: "Output the default k0s configuration yaml to stdout",
RunE: func(cmd *cobra.Command, args []string) error {
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
config := v1beta1.DefaultClusterConfig()
if !includeImages {
config.Spec.Images = nil
Expand Down
10 changes: 2 additions & 8 deletions cmd/config/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ limitations under the License.
package config

import (
"os"

"github.com/k0sproject/k0s/pkg/config"

"github.com/spf13/cobra"
Expand All @@ -28,13 +26,9 @@ func NewEditCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "edit",
Short: "Launch the editor configured in your shell to edit k0s configuration",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
}
os.Args = []string{os.Args[0], "kubectl", "--data-dir", opts.K0sVars.DataDir, "-n", "kube-system", "edit", "clusterconfig", "k0s"}
return cmd.Execute()
return reExecKubectl(cmd, "-n", "kube-system", "edit", "clusterconfig", "k0s")
},
}
cmd.PersistentFlags().AddFlagSet(config.GetKubeCtlFlagSet())
Expand Down
14 changes: 5 additions & 9 deletions cmd/config/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ limitations under the License.
package config

import (
"os"

"github.com/k0sproject/k0s/pkg/config"

"github.com/spf13/cobra"
Expand All @@ -30,16 +28,14 @@ func NewStatusCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "Display dynamic configuration reconciliation status",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
}
os.Args = []string{os.Args[0], "kubectl", "--data-dir", opts.K0sVars.DataDir, "-n", "kube-system", "get", "event", "--field-selector", "involvedObject.name=k0s"}
args := []string{"-n", "kube-system", "get", "event", "--field-selector", "involvedObject.name=k0s"}
if outputFormat != "" {
os.Args = append(os.Args, "-o", outputFormat)
args = append(args, "-o", outputFormat)
}
return cmd.Execute()

return reExecKubectl(cmd, args...)
},
}
cmd.PersistentFlags().AddFlagSet(config.GetKubeCtlFlagSet())
Expand Down
3 changes: 2 additions & 1 deletion cmd/config/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ func NewValidateCmd() *cobra.Command {
Short: "Validate k0s configuration",
Long: `Example:
k0s config validate --config path_to_config.yaml`,
RunE: func(cmd *cobra.Command, args []string) error {
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
var reader io.Reader

// config.CfgFile is the global value holder for --config flag, set by cobra/pflag
Expand Down
1 change: 1 addition & 0 deletions cmd/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ func NewControllerCmd() *cobra.Command {
or CLI flag:
$ k0s controller --token-file [path_to_file]
Note: Token can be passed either as a CLI argument or as a flag`,
Args: cobra.MaximumNArgs(1),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
logrus.SetOutput(cmd.OutOrStdout())
k0slog.SetInfoLevel()
Expand Down
2 changes: 2 additions & 0 deletions cmd/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func NewEtcdCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "etcd",
Short: "Manage etcd cluster",
Args: cobra.NoArgs,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := config.CallParentPersistentPreRun(cmd, args); err != nil {
return err
Expand All @@ -51,6 +52,7 @@ func NewEtcdCmd() *cobra.Command {
}
return nil
},
Run: func(*cobra.Command, []string) { /* Enforce arg validation. */ },
}
cmd.AddCommand(etcdLeaveCmd())
cmd.AddCommand(etcdListCmd())
Expand Down
2 changes: 1 addition & 1 deletion cmd/etcd/leave.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func etcdLeaveCmd() *cobra.Command {
Use: "leave",
Short: "Leave the etcd cluster, or remove a specific peer",
Args: cobra.NoArgs, // accept peer address via flag, not via arg
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion cmd/etcd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func etcdListCmd() *cobra.Command {
// ensure logs don't mess up the output
logrus.SetOutput(cmd.ErrOrStderr())
},
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand Down
32 changes: 0 additions & 32 deletions cmd/etcd/list_test.go

This file was deleted.

3 changes: 2 additions & 1 deletion cmd/install/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ With the controller subcommand you can setup a single node cluster by running:
k0s install controller --single
`,
RunE: func(cmd *cobra.Command, args []string) error {
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand Down
2 changes: 2 additions & 0 deletions cmd/install/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func NewInstallCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "install",
Short: "Install k0s on a brand-new system. Must be run as root (or with sudo)",
Args: cobra.NoArgs,
Run: func(*cobra.Command, []string) { /* Enforce arg validation. */ },
}

cmd.AddCommand(installControllerCmd(&installFlags))
Expand Down
3 changes: 2 additions & 1 deletion cmd/install/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ func installWorkerCmd(installFlags *installFlags) *cobra.Command {
All default values of worker command will be passed to the service stub unless overridden.
Windows flags like "--api-server", "--cidr-range" and "--cluster-dns" will be ignored since install command doesn't yet support Windows services`,
RunE: func(cmd *cobra.Command, args []string) error {
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
opts, err := config.GetCmdOpts(cmd)
if err != nil {
return err
Expand Down
1 change: 1 addition & 0 deletions cmd/kubeconfig/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func kubeConfigAdminCmd() *cobra.Command {
Example: ` $ k0s kubeconfig admin > ~/.kube/config
$ export KUBECONFIG=~/.kube/config
$ kubectl get nodes`,
Args: cobra.NoArgs,
PreRun: func(cmd *cobra.Command, args []string) {
// ensure logs don't mess up the output
logrus.SetOutput(cmd.ErrOrStderr())
Expand Down
Loading

0 comments on commit ca4856b

Please sign in to comment.