From 44f3482feef7a3690ca87a1591eafe6a278c512a Mon Sep 17 00:00:00 2001 From: Nathan Date: Thu, 17 Aug 2023 02:19:09 -0600 Subject: [PATCH] Trims whitespace from command arguments in RootCmd (#24218) - Prevents commands from receiving potential whitespace characters - Adds a new root test case ensuring various whitespace characters are removed Co-authored-by: Nathan Geist --- server/cmd/mmctl/commands/root.go | 3 ++ server/cmd/mmctl/commands/root_test.go | 48 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 server/cmd/mmctl/commands/root_test.go diff --git a/server/cmd/mmctl/commands/root.go b/server/cmd/mmctl/commands/root.go index 9d11590095..32ce53307f 100644 --- a/server/cmd/mmctl/commands/root.go +++ b/server/cmd/mmctl/commands/root.go @@ -73,6 +73,9 @@ var RootCmd = &cobra.Command{ Long: `Mattermost offers workplace messaging across web, PC and phones with archiving, search and integration with your existing systems. Documentation available at https://docs.mattermost.com`, DisableAutoGenTag: true, PersistentPreRun: func(cmd *cobra.Command, args []string) { + for i, arg := range args { + args[i] = strings.TrimSpace(arg) + } format := viper.GetString("format") if viper.GetBool("disable-pager") { printer.OverrideEnablePager(false) diff --git a/server/cmd/mmctl/commands/root_test.go b/server/cmd/mmctl/commands/root_test.go new file mode 100644 index 0000000000..903bfbfd9d --- /dev/null +++ b/server/cmd/mmctl/commands/root_test.go @@ -0,0 +1,48 @@ +// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. +// See LICENSE.txt for license information. + +package commands + +import ( + "bytes" + "fmt" + "strings" + + "github.com/spf13/cobra" +) + +func executeRawCommand(root *cobra.Command, args string) (c *cobra.Command, output string, err error) { + + actual := new(bytes.Buffer) + RootCmd.SetOut(actual) + RootCmd.SetErr(actual) + RootCmd.SetArgs(strings.Split(args, " ")) + c, err = RootCmd.ExecuteC() + return c, actual.String(), err +} + +func (s *MmctlUnitTestSuite) TestArgumentsHaveWhitespaceTrimmed() { + + arguments := []string{"value_1", "value_2"} + lineEndings := []string{"\n", "\r", "\r\n"} + prettyNames := []string{"-n", "-r", "-r-n"} + commandCalled := false + + for i, lineEnding := range lineEndings { + testName := fmt.Sprintf("Commands have their arguments stripped of whitespace[%s]", prettyNames[i]) + s.Run(testName, func() { + commandCalled = false + commandFunction := func(command *cobra.Command, args []string) { + commandCalled = true + s.Equal(arguments, args, "Expected arguments to have their whitespace trimmed") + + } + mockCommand := &cobra.Command{Use: "test", Run: commandFunction} + commandString := strings.Join([]string{"test", " ", arguments[0], lineEnding, " ", arguments[1], lineEnding}, "") + RootCmd.AddCommand(mockCommand) + executeRawCommand(RootCmd, commandString) + s.Require().True(commandCalled, "Expected mock command to be called") + }) + } + +}