Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkg/wslg/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (commandRunner) Run(ctx context.Context, path string, args []string) (Probe
result.ExitCode = cmd.ProcessState.ExitCode()
}
if stdout.overflow || stderr.overflow {
return ProbeResult{}, ErrProtocol
return ProbeResult{}, errProbeOutputLimit
}
if _, ok := errors.AsType[*exec.ExitError](err); ok {
return result, nil
Expand Down
33 changes: 27 additions & 6 deletions pkg/wslg/wslg.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ var (
ErrCollision = errors.New("reserved WSLg environment assignment")
)

var errProbeOutputLimit = protocolError("output over the limit")

type Target struct {
Distro string `json:"distro"`
User string `json:"user"`
Expand Down Expand Up @@ -261,8 +263,15 @@ func (p displayProbe) value(ctx context.Context, key string) (string, bool, erro
if ctx.Err() != nil {
return "", false, ctx.Err()
}
if errors.Is(err, errProbeOutputLimit) {
return "", false, fmt.Errorf("%w (%s)", errProbeOutputLimit, key)
}
if err != nil {
return "", false, fmt.Errorf("%w (%s)", ErrProtocol, key)
return "", false, fmt.Errorf(
"%w (%s): the command did not run to completion",
ErrProtocol,
key,
)
}
value, present, err := parseResult(result)
if err != nil {
Expand All @@ -277,25 +286,37 @@ func (p displayProbe) value(ctx context.Context, key string) (string, bool, erro
// otherwise a wsl.exe failure would look like a missing variable.
func parseResult(result ProbeResult) (string, bool, error) {
if len(result.Stdout) > outputLimit {
return "", false, ErrProtocol
return "", false, errProbeOutputLimit
}
if result.ExitCode == 1 && len(result.Stdout) == 0 && len(result.Stderr) == 0 {
return "", false, nil
}
if result.ExitCode != 0 {
return "", false, ErrProtocol
return "", false, protocolError(fmt.Sprintf(
"exit code %d, stdout %d bytes, stderr %d bytes",
result.ExitCode,
len(result.Stdout),
len(result.Stderr),
))
}
value, err := parseValue(result.Stdout)
return value, err == nil, err
}

func protocolError(reason string) error {
return fmt.Errorf("%w: %s", ErrProtocol, reason)
}

func parseValue(stdout []byte) (string, error) {
if !utf8.Valid(stdout) || !strings.HasSuffix(string(stdout), "\n") {
return "", ErrProtocol
if !utf8.Valid(stdout) {
return "", protocolError("stdout is not valid UTF-8")
}
if !strings.HasSuffix(string(stdout), "\n") {
return "", protocolError("stdout has no trailing newline")
}
value := strings.TrimSuffix(strings.TrimSuffix(string(stdout), "\n"), "\r")
if hasControl(value) {
return "", ErrProtocol
return "", protocolError("value has control characters")
}
return value, nil
}
51 changes: 48 additions & 3 deletions pkg/wslg/wslg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ const (
testUser = "alice"
testOrdinaryDisplay = "DISPLAY=:9"
testProcessHelper = "-test.run=^TestWSLgProcessHelper$"
testPrivateOutput = "private-output"
testLargeStdout = "large-stdout"
testLargeStderr = "large-stderr"
)

type WSLgSuite struct{ suite.Suite }
Expand Down Expand Up @@ -109,6 +112,25 @@ func (s *WSLgSuite) TestInvalidTargetsNeverRun() {
}
}

func (s *WSLgSuite) TestProtocolErrorsNameTheirReason() {
for _, tc := range []struct {
result ProbeResult
reason string
}{
{ProbeResult{ExitCode: 1, Stderr: []byte("private")}, "exit code 1, stdout 0 bytes, stderr 7 bytes"},
{ProbeResult{ExitCode: 255, Stdout: []byte("ab")}, "exit code 255, stdout 2 bytes, stderr 0 bytes"},
{ProbeResult{Stdout: []byte("private")}, "stdout has no trailing newline"},
{ProbeResult{Stdout: []byte{0xff, '\n'}}, "stdout is not valid UTF-8"},
{ProbeResult{Stdout: []byte("a\x1bb\n")}, "value has control characters"},
{ProbeResult{Stdout: []byte(strings.Repeat("a", outputLimit+1))}, "output over the limit"},
} {
_, _, err := parseResult(tc.result)
s.ErrorIs(err, ErrProtocol)
s.ErrorContains(err, tc.reason)
s.NotContains(err.Error(), "private")
}
}

func (s *WSLgSuite) TestStrictProtocol() {
for _, result := range []ProbeResult{
{Stdout: []byte("private")},
Expand Down Expand Up @@ -190,13 +212,31 @@ func (s *WSLgSuite) TestNamespaceAndOverlay() {
s.Error(ValidateEnvironment(map[string]string{Display: "x\n"}))
}

func (s *WSLgSuite) TestCaptureReportsSubprocessOutputLimit() {
path, err := os.Executable()
s.Require().NoError(err)
for _, mode := range []string{testLargeStdout, testLargeStderr} {
s.Run(mode, func() {
runner := fakeRunner{
run: func(ctx context.Context, path string, _ []string) (ProbeResult, error) {
return (commandRunner{}).Run(ctx, path, []string{testProcessHelper, "--", mode})
},
}
_, err := Capture(s.T().Context(), Target{testDistro, testUser}, path, runner)
s.Require().ErrorIs(err, ErrProtocol)
s.ErrorContains(err, "output over the limit (DISPLAY)")
s.NotContains(err.Error(), testPrivateOutput)
})
}
}

func (s *WSLgSuite) TestSubprocessBoundsAndCancellation() {
path, err := os.Executable()
s.Require().NoError(err)
result, err := (commandRunner{}).Run(
context.Background(),
path,
[]string{testProcessHelper, "--", "large"},
[]string{testProcessHelper, "--", testLargeStdout},
)
s.ErrorIs(err, ErrProtocol)
s.Empty(result.Stdout)
Expand All @@ -223,8 +263,13 @@ func TestWSLgProcessHelper(t *testing.T) {
return
}
switch os.Args[len(os.Args)-1] {
case "large":
_, err := io.WriteString(os.Stdout, strings.Repeat("a", outputLimit+1))
case testLargeStdout, testLargeStderr:
stream := os.Stdout
if os.Args[len(os.Args)-1] == testLargeStderr {
stream = os.Stderr
}
output := testPrivateOutput + strings.Repeat("a", outputLimit+1-len(testPrivateOutput))
_, err := io.WriteString(stream, output)
if err != nil {
os.Exit(2)
}
Expand Down
Loading