Skip to content
Myr

fix: prevent completions from mutating os.Args via append side effect (#2356)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes #2257 When getCompletions() checks for interspersed flags, it calls append(finalArgs, "--") to temporarily add a "--" sentinel. However, finalArgs is a sub-slice of the original args (ultimately derived from os.Args[1:] or SetArgs), and if the sub-slice has spare capacity in its backing array, append writes "--" into the shared array, corrupting the caller's data. This is particularly visible when TraverseChildren is enabled: the Traverse method returns sub-slices that share the original backing array. A user's ValidArgsFunction inspecting os.Args would then see "--" where a real argument should be. Copy trimmedArgs at the top of getCompletions to prevent any future append from accidentally mutating the caller's backing array.

authored by Varun Chawla · committed by GitHub · parent f2878ba · Browse files · 2 files+59 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

Diff stats

2 files+59 added−1 removed

  • other:+59 added−1 removed

2 files+59 added−1 removed

modified:completions_test.go+55 added
4070 unmodified lines
4071 }4072 })4073 }4074}40754076func TestCompletionDoesNotMutateOsArgs(t *testing.T) {4077 // Test for https://github.com/spf13/cobra/issues/22574078 // Verify that os.Args is not corrupted when shell completion runs4079 // with TraverseChildren enabled.4080 //4081 // The bug: getCompletions() calls append(finalArgs, "--") where4082 // finalArgs is a sub-slice of the original args (from os.Args[1:]).4083 // If there's spare capacity, append writes "--" into the shared4084 // backing array, mutating os.Args in place.40854086 // Save and restore os.Args since we need to override it.4087 origArgs := os.Args4088 defer func() { os.Args = origArgs }()40894090 // Set os.Args to simulate: root __completeNoDesc x4091 // We do NOT use SetArgs so the code falls through to os.Args[1:].4092 // The program name must not be "cobra.test" to bypass the test guard4093 // in ExecuteC().4094 os.Args = []string{"root", ShellCompNoDescRequestCmd, "x"}40954096 rootCmd := &Command{4097 Use: "root",4098 TraverseChildren: true,4099 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {4100 return []string{"mycompletion"}, ShellCompDirectiveDefault4101 },4102 Run: emptyRun,4103 }41044105 buf := new(bytes.Buffer)4106 rootCmd.SetOut(buf)4107 rootCmd.SetErr(buf)41084109 _, err := rootCmd.ExecuteC()4110 if err != nil {4111 t.Fatalf("Unexpected error: %v", err)4112 }41134114 // Without the fix, os.Args[2] would be changed from "x" to "--"4115 // because append(finalArgs, "--") in getCompletions wrote into4116 // the shared backing array of os.Args.4117 if len(os.Args) != 3 {4118 t.Fatalf("os.Args length changed: expected 3, got %d", len(os.Args))4119 }4120 if os.Args[0] != "root" {4121 t.Errorf("os.Args[0] was mutated: expected %q, got %q", "root", os.Args[0])4122 }4123 if os.Args[1] != ShellCompNoDescRequestCmd {4124 t.Errorf("os.Args[1] was mutated: expected %q, got %q", ShellCompNoDescRequestCmd, os.Args[1])4125 }4126 if os.Args[2] != "x" {4127 t.Errorf("os.Args[2] was mutated: expected %q, got %q", "x", os.Args[2])4128 }4129}
modified:completions.go+4 added-1 removed
315 unmodified lines
316func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) {317 // The last argument, which is not completely typed by the user,318 // should not be part of the list of arguments319 toComplete := args[len(args)-1]320 trimmedArgs := args[:len(args)-1]320 // Copy trimmedArgs to a new slice to avoid mutating the caller's321 // backing array (which may be os.Args) when later appending "--".322 trimmedArgs := make([]string, len(args)-1)323 copy(trimmedArgs, args[:len(args)-1])324325 var finalCmd *Command326 var finalArgs []string327 var err error
697 unmodified lines