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
40 changes: 40 additions & 0 deletions coderd/util/strings/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ package strings

import (
"fmt"
"strconv"
"strings"
"unicode"

"github.com/acarl005/stripansi"
"github.com/microcosm-cc/bluemonday"
)

// JoinWithConjunction joins a slice of strings with commas except for the last
Expand All @@ -28,3 +33,38 @@ func Truncate(s string, n int) string {
}
return s[:n]
}

var bmPolicy = bluemonday.StrictPolicy()

// UISanitize sanitizes a string for display in the UI.
// The following transformations are applied, in order:
// - HTML tags are removed using bluemonday's strict policy.
// - ANSI escape codes are stripped using stripansi.
// - Consecutive backslashes are replaced with a single backslash.
// - Non-printable characters are removed.
// - Whitespace characters are replaced with spaces.
// - Multiple spaces are collapsed into a single space.
// - Leading and trailing whitespace is trimmed.
func UISanitize(in string) string {
if unq, err := strconv.Unquote(`"` + in + `"`); err == nil {
in = unq
}
in = bmPolicy.Sanitize(in)
in = stripansi.Strip(in)
var b strings.Builder
var spaceSeen bool
for _, r := range in {
if unicode.IsSpace(r) {
if !spaceSeen {
_, _ = b.WriteRune(' ')
spaceSeen = true
}
continue
}
spaceSeen = false
if unicode.IsPrint(r) {
_, _ = b.WriteRune(r)
}
}
return strings.TrimSpace(b.String())
}
39 changes: 39 additions & 0 deletions coderd/util/strings/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package strings_test
import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/coder/coder/v2/coderd/util/strings"
Expand Down Expand Up @@ -37,3 +38,41 @@ func TestTruncate(t *testing.T) {
})
}
}

func TestUISanitize(t *testing.T) {
t.Parallel()

for _, tt := range []struct {
s string
expected string
}{
{"normal text", "normal text"},
{"\tfoo \r\\nbar ", "foo bar"},
{"通常のテキスト", "通常のテキスト"},
{"foo\nbar", "foo bar"},
{"foo\tbar", "foo bar"},
{"foo\rbar", "foo bar"},
{"foo\x00bar", "foobar"},
{"\u202Eabc", "abc"},
{"\u200Bzero width", "zero width"},
{"foo\x1b[31mred\x1b[0mbar", "fooredbar"},
{"foo\u0008bar", "foobar"},
{"foo\x07bar", "foobar"},
{"foo\uFEFFbar", "foobar"},
{"<a href='javascript:alert(1)'>link</a>", "link"},
{"<style>body{display:none}</style>", ""},
{"<html>HTML</html>", "HTML"},
{"<br>line break", "line break"},
{"<link rel='stylesheet' href='evil.css'>", ""},
{"<img src=1 onerror=alert(1)>", ""},
{"<!-- comment -->visible", "visible"},
{"<script>alert('xss')</script>", ""},
{"<iframe src='evil.com'></iframe>", ""},
} {
t.Run(tt.expected, func(t *testing.T) {
t.Parallel()
actual := strings.UISanitize(tt.s)
assert.Equal(t, tt.expected, actual)
})
}
}
6 changes: 5 additions & 1 deletion coderd/workspaceagents.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import (
"github.com/coder/coder/v2/coderd/rbac/policy"
"github.com/coder/coder/v2/coderd/telemetry"
maputil "github.com/coder/coder/v2/coderd/util/maps"
strutil "github.com/coder/coder/v2/coderd/util/strings"
"github.com/coder/coder/v2/coderd/wspubsub"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
Expand Down Expand Up @@ -383,6 +384,9 @@ func (api *API) patchWorkspaceAgentAppStatus(rw http.ResponseWriter, r *http.Req
return
}

// Treat the message as untrusted input.
cleaned := strutil.UISanitize(req.Message)

// nolint:gocritic // This is a system restricted operation.
_, err = api.Database.InsertWorkspaceAppStatus(dbauthz.AsSystemRestricted(ctx), database.InsertWorkspaceAppStatusParams{
ID: uuid.New(),
Expand All @@ -391,7 +395,7 @@ func (api *API) patchWorkspaceAgentAppStatus(rw http.ResponseWriter, r *http.Req
AgentID: workspaceAgent.ID,
AppID: app.ID,
State: database.WorkspaceAppStatusState(req.State),
Message: req.Message,
Message: cleaned,
Uri: sql.NullString{
String: req.URI,
Valid: req.URI != "",
Expand Down
63 changes: 47 additions & 16 deletions codersdk/toolsdk/bash.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ import (
)

type WorkspaceBashArgs struct {
Workspace string `json:"workspace"`
Command string `json:"command"`
TimeoutMs int `json:"timeout_ms,omitempty"`
Workspace string `json:"workspace"`
Command string `json:"command"`
TimeoutMs int `json:"timeout_ms,omitempty"`
Background bool `json:"background,omitempty"`
}

type WorkspaceBashResult struct {
Expand All @@ -50,9 +51,13 @@ The workspace parameter supports various formats:
The timeout_ms parameter specifies the command timeout in milliseconds (defaults to 60000ms, maximum of 300000ms).
If the command times out, all output captured up to that point is returned with a cancellation message.

For background commands (background: true), output is captured until the timeout is reached, then the command
continues running in the background. The captured output is returned as the result.

Examples:
- workspace: "my-workspace", command: "ls -la"
- workspace: "john/dev-env", command: "git status", timeout_ms: 30000
- workspace: "my-workspace", command: "npm run dev", background: true, timeout_ms: 10000
- workspace: "my-workspace.main", command: "docker ps"`,
Schema: aisdk.Schema{
Properties: map[string]any{
Expand All @@ -70,6 +75,10 @@ Examples:
"default": 60000,
"minimum": 1,
},
"background": map[string]any{
"type": "boolean",
"description": "Whether to run the command in the background. Output is captured until timeout, then the command continues running in the background.",
},
},
Required: []string{"workspace", "command"},
},
Expand Down Expand Up @@ -137,23 +146,35 @@ Examples:

// Set default timeout if not specified (60 seconds)
timeoutMs := args.TimeoutMs
defaultTimeoutMs := 60000
if timeoutMs <= 0 {
timeoutMs = 60000
timeoutMs = defaultTimeoutMs
}
command := args.Command
if args.Background {
// For background commands, use nohup directly to ensure they survive SSH session
// termination. This captures output normally but allows the process to continue
// running even after the SSH connection closes.
command = fmt.Sprintf("nohup %s </dev/null 2>&1", args.Command)
}

// Create context with timeout
ctx, cancel = context.WithTimeout(ctx, time.Duration(timeoutMs)*time.Millisecond)
defer cancel()
// Create context with command timeout (replace the broader MCP timeout)
commandCtx, commandCancel := context.WithTimeout(ctx, time.Duration(timeoutMs)*time.Millisecond)
defer commandCancel()

// Execute command with timeout handling
output, err := executeCommandWithTimeout(ctx, session, args.Command)
output, err := executeCommandWithTimeout(commandCtx, session, command)
outputStr := strings.TrimSpace(string(output))

// Handle command execution results
if err != nil {
// Check if the command timed out
if errors.Is(context.Cause(ctx), context.DeadlineExceeded) {
outputStr += "\nCommand canceled due to timeout"
if errors.Is(context.Cause(commandCtx), context.DeadlineExceeded) {
if args.Background {
outputStr += "\nCommand continues running in background"
} else {
outputStr += "\nCommand canceled due to timeout"
}
return WorkspaceBashResult{
Output: outputStr,
ExitCode: 124,
Expand Down Expand Up @@ -387,21 +408,27 @@ func executeCommandWithTimeout(ctx context.Context, session *gossh.Session, comm
return safeWriter.Bytes(), err
case <-ctx.Done():
// Context was canceled (timeout or other cancellation)
// Close the session to stop the command
_ = session.Close()
// Close the session to stop the command, but handle errors gracefully
closeErr := session.Close()

// Give a brief moment to collect any remaining output
timer := time.NewTimer(50 * time.Millisecond)
// Give a brief moment to collect any remaining output and for goroutines to finish
timer := time.NewTimer(100 * time.Millisecond)
defer timer.Stop()

select {
case <-timer.C:
// Timer expired, return what we have
break
case err := <-done:
// Command finished during grace period
return safeWriter.Bytes(), err
if closeErr == nil {
return safeWriter.Bytes(), err
}
// If session close failed, prioritize the context error
break
}

// Return the collected output with the context error
return safeWriter.Bytes(), context.Cause(ctx)
}
}
Expand All @@ -421,5 +448,9 @@ func (sw *syncWriter) Write(p []byte) (n int, err error) {
func (sw *syncWriter) Bytes() []byte {
sw.mu.Lock()
defer sw.mu.Unlock()
return sw.w.Bytes()
// Return a copy to prevent race conditions with the underlying buffer
b := sw.w.Bytes()
result := make([]byte, len(b))
copy(result, b)
return result
}
Loading
Loading