Skip to content

Commit 34ef30e

Browse files
authored
fix: harden chat workspace file upload input validation (#30184)
1 parent 81c4057 commit 34ef30e

10 files changed

Lines changed: 199 additions & 20 deletions

File tree

‎coderd/chat_routes.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (api *API) registerChatAPIRoutes(r chi.Router, apiKeyMiddleware func(http.H
8989
r.Post("/title/propose", api.proposeChatTitle)
9090
r.Get("/diff", api.getChatDiffContents)
9191
r.With(
92-
httpmw.RateLimit(api.FilesRateLimit, time.Minute),
92+
httpmw.RateLimitPerCaller(api.FilesRateLimit, time.Minute),
9393
api.chatWorkspaceUploadMiddleware,
9494
).Post("/workspace-files", api.postChatWorkspaceFile)
9595
r.Put("/context", api.refreshChatContext)

‎coderd/exp_chats.go‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7301,6 +7301,7 @@ const (
73017301
chatWorkspaceUploadArchivedMessage = "Cannot upload files to an archived chat."
73027302
chatWorkspaceUploadOwnerOnlyMessage = "Only the chat owner may upload files to a chat's workspace."
73037303
chatWorkspaceUploadMissingFilenameMessage = "Filename is required."
7304+
chatWorkspaceUploadUnusableFilenameMessage = "Filename is unusable."
73047305
chatWorkspaceUploadNoChatAgentMessage = "No chat-compatible workspace agent found."
73057306
chatWorkspaceUploadAgentDialTimeout = 30 * time.Second
73067307
// Transport errors embed the agent's tailnet URL, so they are logged
@@ -7426,16 +7427,25 @@ func (api *API) postChatWorkspaceFile(rw http.ResponseWriter, r *http.Request) {
74267427
filename := chatFilenameFromContentDisposition(r.Header.Get("Content-Disposition"))
74277428
sanitizedName, err := chatfiles.SanitizeWorkspaceUploadName(filename)
74287429
if err != nil {
7430+
if strings.TrimSpace(filename) == "" {
7431+
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
7432+
Message: chatWorkspaceUploadMissingFilenameMessage,
7433+
Detail: "Provide a filename via the Content-Disposition header.",
7434+
})
7435+
return
7436+
}
74297437
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
7430-
Message: chatWorkspaceUploadMissingFilenameMessage,
7431-
Detail: "Provide a filename via the Content-Disposition header.",
7438+
Message: chatWorkspaceUploadUnusableFilenameMessage,
7439+
Detail: "The provided filename has no safe characters left after sanitization or is a reserved device name.",
74327440
})
74337441
return
74347442
}
74357443
name = sanitizedName
74367444

7437-
contentType := chatfiles.BaseMediaType(r.Header.Get("Content-Type"))
7438-
if contentType == "" {
7445+
// The client echoes media_type back as workspace_file_media_type, so
7446+
// it must pass the same strict parse the message endpoint applies.
7447+
contentType, err := chatfiles.ParseBaseMediaType(r.Header.Get("Content-Type"))
7448+
if err != nil {
74397449
contentType = "application/octet-stream"
74407450
}
74417451

@@ -7865,11 +7875,16 @@ func createChatInputFromParts(
78657875
Detail: fmt.Sprintf("%s[%d].workspace_file_path must reference a file uploaded to this chat.", fieldName, i),
78667876
}
78677877
}
7868-
if strings.ContainsRune(part.WorkspaceFileMediaType, 0) {
7869-
return nil, nil, &codersdk.Response{
7870-
Message: "Invalid input part.",
7871-
Detail: fmt.Sprintf("%s[%d].workspace_file_media_type must not contain NUL bytes.", fieldName, i),
7878+
var workspaceFileMediaType string
7879+
if part.WorkspaceFileMediaType != "" {
7880+
parsed, err := chatfiles.ParseBaseMediaType(part.WorkspaceFileMediaType)
7881+
if err != nil {
7882+
return nil, nil, &codersdk.Response{
7883+
Message: "Invalid input part.",
7884+
Detail: fmt.Sprintf("%s[%d].workspace_file_media_type must be a valid media type of at most %d bytes without control characters.", fieldName, i, chatfiles.MaxMediaTypeBytes),
7885+
}
78727886
}
7887+
workspaceFileMediaType = parsed
78737888
}
78747889
// The referenced bytes live in one specific workspace's
78757890
// filesystem. Reject references from a workspace other
@@ -7892,7 +7907,7 @@ func createChatInputFromParts(
78927907
workspaceFilePath,
78937908
part.WorkspaceFileName,
78947909
part.WorkspaceFileSize,
7895-
chatfiles.BaseMediaType(part.WorkspaceFileMediaType),
7910+
workspaceFileMediaType,
78967911
))
78977912
// chatd loads the skill body as the chat owner when the message
78987913
// is sent; only the shape is checked here.

‎coderd/exp_chats_workspace_file_test.go‎

Lines changed: 70 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ func TestCreateChatMessageWorkspaceFileWorkspaceValidation(t *testing.T) {
378378
ctx := testutil.Context(t, testutil.WaitLong)
379379
client, chat := newBoundChat(ctx, t)
380380

381-
for _, name := range []string{" data.csv", "da\u202eta.csv", "da|ta.csv"} {
381+
for _, name := range []string{" data.csv", "da\u202eta.csv", "da|ta.csv", "a$(b);c'd.txt"} {
382382
part := validPart(chat.ID)
383383
part.WorkspaceFileWorkspaceID = *chat.WorkspaceID
384384
part.WorkspaceFileName = name
@@ -391,6 +391,29 @@ func TestCreateChatMessageWorkspaceFileWorkspaceValidation(t *testing.T) {
391391
}
392392
})
393393

394+
t.Run("InvalidMediaType", func(t *testing.T) {
395+
t.Parallel()
396+
397+
ctx := testutil.Context(t, testutil.WaitLong)
398+
client, chat := newBoundChat(ctx, t)
399+
400+
for _, mediaType := range []string{
401+
"garbage",
402+
"text/plain\x00",
403+
"text/plain; charset=\"\x01\"",
404+
"text/plain; x=" + strings.Repeat("a", 255),
405+
} {
406+
part := validPart(chat.ID)
407+
part.WorkspaceFileWorkspaceID = *chat.WorkspaceID
408+
part.WorkspaceFileMediaType = mediaType
409+
_, err := client.CreateChatMessage(ctx, chat.ID, codersdk.CreateChatMessageRequest{
410+
Content: []codersdk.ChatInputPart{part},
411+
})
412+
sdkErr := requireSDKError(t, err, http.StatusBadRequest)
413+
require.Equal(t, "content[0].workspace_file_media_type must be a valid media type of at most 255 bytes without control characters.", sdkErr.Detail, "media type %q", mediaType)
414+
}
415+
})
416+
394417
t.Run("PersistsNormalizedReference", func(t *testing.T) {
395418
t.Parallel()
396419

@@ -697,7 +720,7 @@ func TestPostChatWorkspaceFile(t *testing.T) {
697720
require.Equal(t, uploaded.Name, filepath.Base(uploaded.Path))
698721
})
699722

700-
t.Run("MissingFilename", func(t *testing.T) {
723+
t.Run("InvalidContentType", func(t *testing.T) {
701724
t.Parallel()
702725

703726
ctx := testutil.Context(t, testutil.WaitLong)
@@ -709,12 +732,43 @@ func TestPostChatWorkspaceFile(t *testing.T) {
709732
OrganizationID: firstUser.OrganizationID,
710733
OwnerID: firstUser.UserID,
711734
}).WithAgent().Do()
735+
_ = startChatUploadAgent(t, client, workspaceBuild)
712736
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
713737

714-
res, err := uploadChatWorkspaceFile(ctx, t, client, chat.ID.String(), "", "application/zip", []byte("PK"))
738+
// The client sends the returned media type back as
739+
// workspace_file_media_type, so it must pass message validation.
740+
resp, err := client.UploadChatWorkspaceFile(ctx, chat.ID, "text/plain; bogus", "notes.txt", bytes.NewReader([]byte("hi")))
715741
require.NoError(t, err)
716-
defer res.Body.Close()
717-
require.Equal(t, http.StatusBadRequest, res.StatusCode)
742+
require.Equal(t, "application/octet-stream", resp.MediaType)
743+
})
744+
745+
t.Run("MissingFilename", func(t *testing.T) {
746+
t.Parallel()
747+
748+
ctx := testutil.Context(t, testutil.WaitLong)
749+
client, db := newChatClientWithDatabase(t)
750+
firstUser := coderdtest.CreateFirstUser(t, client.Client)
751+
_ = createChatModel(t, client)
752+
753+
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
754+
OrganizationID: firstUser.OrganizationID,
755+
OwnerID: firstUser.UserID,
756+
}).WithAgent().Do()
757+
chat := createBoundChat(ctx, t, client, firstUser.OrganizationID, workspaceBuild.Workspace.ID)
758+
759+
for _, tc := range []struct {
760+
contentDisposition string
761+
detail string
762+
}{
763+
{"", "Provide a filename via the Content-Disposition header."},
764+
{`attachment; filename="$()"`, "The provided filename has no safe characters left after sanitization or is a reserved device name."},
765+
} {
766+
res, err := uploadChatWorkspaceFile(ctx, t, client, chat.ID.String(), tc.contentDisposition, "application/zip", []byte("PK"))
767+
require.NoError(t, err)
768+
sdkErr := requireSDKError(t, codersdk.ReadBodyAsError(res), http.StatusBadRequest)
769+
_ = res.Body.Close()
770+
require.Equal(t, tc.detail, sdkErr.Detail, tc.contentDisposition)
771+
}
718772
})
719773

720774
t.Run("NoWorkspace", func(t *testing.T) {
@@ -756,9 +810,19 @@ func TestPostChatWorkspaceFile(t *testing.T) {
756810
})
757811
require.NoError(t, err)
758812

813+
otherChat, err := client.CreateChat(ctx, codersdk.CreateChatRequest{
814+
OrganizationID: firstUser.OrganizationID,
815+
Content: []codersdk.ChatInputPart{
816+
{Type: codersdk.ChatInputPartTypeText, Text: "rate limited too"},
817+
},
818+
})
819+
require.NoError(t, err)
820+
821+
// The budget is per user, so a different chat ID does not get a
822+
// fresh bucket.
759823
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
760824
requireSDKError(t, err, http.StatusConflict)
761-
_, err = client.UploadChatWorkspaceFile(ctx, chat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
825+
_, err = client.UploadChatWorkspaceFile(ctx, otherChat.ID, "application/zip", "data.zip", bytes.NewReader([]byte("PK")))
762826
requireSDKError(t, err, http.StatusTooManyRequests)
763827
})
764828

‎coderd/httpmw/ratelimit.go‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,19 @@ func RateLimit(count int, window time.Duration) func(http.Handler) http.Handler
2525
return rateLimitWithEndpointKey(count, window, keyByNormalizedEndpoint, nil)
2626
}
2727

28+
// RateLimitPerCaller returns a handler that limits requests per-minute
29+
// based on IP and user ID (if available), ignoring the request path. Every
30+
// route mounted behind one instance shares one budget per caller, so path
31+
// parameters such as a chat ID cannot be varied to get a fresh bucket.
32+
func RateLimitPerCaller(count int, window time.Duration) func(http.Handler) http.Handler {
33+
return rateLimitWithEndpointKey(count, window,
34+
func(*http.Request) (string, error) {
35+
return "", nil
36+
},
37+
nil,
38+
)
39+
}
40+
2841
// RateLimitOAuth2 returns a handler that limits requests per-minute based on
2942
// the caller. Mount it on each route, since every call is a separate bucket.
3043
//

‎coderd/httpmw/ratelimit_test.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,28 @@ func TestRateLimit(t *testing.T) {
102102
}
103103
})
104104

105+
t.Run("PerCallerSharesBucketAcrossPaths", func(t *testing.T) {
106+
t.Parallel()
107+
rtr := chi.NewRouter()
108+
rtr.With(httpmw.RateLimitPerCaller(1, time.Second)).Post("/chats/{chat}/workspace-files", func(rw http.ResponseWriter, r *http.Request) {
109+
rw.WriteHeader(http.StatusOK)
110+
})
111+
112+
remoteAddr := randRemoteAddr()
113+
for i, p := range []string{
114+
"/chats/00000000-0000-0000-0000-000000000001/workspace-files",
115+
"/chats/00000000-0000-0000-0000-000000000002/workspace-files",
116+
} {
117+
req := httptest.NewRequest("POST", p, nil)
118+
req.RemoteAddr = remoteAddr
119+
rec := httptest.NewRecorder()
120+
rtr.ServeHTTP(rec, req)
121+
resp := rec.Result()
122+
_ = resp.Body.Close()
123+
require.Equal(t, i != 0, resp.StatusCode == http.StatusTooManyRequests, "request %d (%s)", i, p)
124+
}
125+
})
126+
105127
t.Run("RandomIPs", func(t *testing.T) {
106128
t.Parallel()
107129
rtr := chi.NewRouter()

‎coderd/x/chatfiles/mime.go‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ import (
1919

2020
const MaxStoredFileNameBytes = 255
2121

22+
// MaxMediaTypeBytes bounds client-supplied media types, parameters
23+
// included.
24+
const MaxMediaTypeBytes = 255
25+
2226
var (
2327
// ErrStoredFileNameRequired indicates that a durable file name is empty
2428
// after normalization.
@@ -57,6 +61,28 @@ func BaseMediaType(mediaType string) string {
5761
return mediaType
5862
}
5963

64+
// ParseBaseMediaType strictly parses a client-supplied media type and
65+
// returns its lowercased type/subtype without parameters. Unlike
66+
// BaseMediaType, it rejects values that do not parse instead of
67+
// returning them unchanged.
68+
func ParseBaseMediaType(mediaType string) (string, error) {
69+
if len(mediaType) > MaxMediaTypeBytes {
70+
return "", xerrors.Errorf("media type exceeds %d bytes", MaxMediaTypeBytes)
71+
}
72+
if strings.ContainsFunc(mediaType, unicode.IsControl) {
73+
return "", xerrors.New("media type contains control characters")
74+
}
75+
parsed, _, err := mime.ParseMediaType(mediaType)
76+
if err != nil {
77+
return "", xerrors.Errorf("parse media type: %w", err)
78+
}
79+
// mime.ParseMediaType also accepts bare Content-Disposition tokens.
80+
if !strings.Contains(parsed, "/") {
81+
return "", xerrors.New("media type must be type/subtype")
82+
}
83+
return parsed, nil
84+
}
85+
6086
// AllowedPromptInputMediaTypesString returns the supported prompt input media
6187
// types as a comma-separated list.
6288
func AllowedPromptInputMediaTypesString() string {

‎coderd/x/chatfiles/mime_test.go‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,38 @@ func TestIsAllowedPromptInputMediaType(t *testing.T) {
343343
require.False(t, chatfiles.IsAllowedPromptInputMediaType("application/zip"))
344344
}
345345

346+
func TestParseBaseMediaType(t *testing.T) {
347+
t.Parallel()
348+
349+
tests := []struct {
350+
name string
351+
input string
352+
want string
353+
wantErr bool
354+
}{
355+
{name: "plain", input: "text/csv", want: "text/csv"},
356+
{name: "parameters_lowercased", input: "Text/Plain; charset=utf-8", want: "text/plain"},
357+
{name: "no_subtype", input: "garbage", wantErr: true},
358+
{name: "invalid_parameter", input: "text/plain; bogus", wantErr: true},
359+
{name: "control_in_quoted_parameter", input: "text/plain; charset=\"\x01\"", wantErr: true},
360+
{name: "nul", input: "text/plain\x00", wantErr: true},
361+
{name: "too_long", input: "text/plain; x=" + strings.Repeat("a", chatfiles.MaxMediaTypeBytes), wantErr: true},
362+
{name: "empty", input: "", wantErr: true},
363+
}
364+
for _, tt := range tests {
365+
t.Run(tt.name, func(t *testing.T) {
366+
t.Parallel()
367+
got, err := chatfiles.ParseBaseMediaType(tt.input)
368+
if tt.wantErr {
369+
require.Error(t, err)
370+
return
371+
}
372+
require.NoError(t, err)
373+
require.Equal(t, tt.want, got)
374+
})
375+
}
376+
}
377+
346378
func TestIsInlineRenderableStoredMediaType(t *testing.T) {
347379
t.Parallel()
348380

‎coderd/x/chatfiles/workspace.go‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@ const (
2828
var ErrWorkspaceUploadNameRequired = xerrors.New("workspace upload file name is required")
2929

3030
// SanitizeWorkspaceUploadName extracts a basename, normalizes unsafe
31-
// whitespace, control characters, and Windows-invalid punctuation to
32-
// underscores, strips edge dots, and truncates the result to
31+
// whitespace, control characters, Windows-invalid punctuation, and
32+
// shell, quote, and bracket characters to underscores, strips edge dots,
33+
// and truncates the result to
3334
// MaxWorkspaceUploadFileNameBytes. It returns
3435
// ErrWorkspaceUploadNameRequired when no safe name remains.
3536
func SanitizeWorkspaceUploadName(name string) (string, error) {
@@ -70,7 +71,10 @@ func isUnsafeWorkspaceUploadRune(r rune) bool {
7071
return true
7172
}
7273
switch r {
73-
case '<', '>', ':', '"', '|', '?', '*':
74+
// With the basename step resolving `/` and `\`, this covers the frontend
75+
// sanitizeChatFileName set so API callers cannot bypass the UI rewrite.
76+
case '<', '>', ':', '"', '|', '?', '*',
77+
'(', ')', '[', ']', '{', '}', '\'', '`', ';', ',', '&', '#', '$':
7478
return true
7579
default:
7680
return false

‎coderd/x/chatfiles/workspace_test.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ func TestSanitizeWorkspaceUploadName(t *testing.T) {
2828
{name: "strip_control_chars", input: "foo\x00\x01\x1fbar.zip", want: "foo_bar.zip"},
2929
{name: "strip_unicode_control_chars", input: "foo\u202ebar.zip", want: "foo_bar.zip"},
3030
{name: "replace_windows_invalid_chars", input: `bad:name*?.zip`, want: "bad_name_.zip"},
31+
{name: "replace_shell_quote_bracket_chars", input: "a$(b);c'd.txt", want: "a_b_c_d.txt"},
32+
{name: "replace_remaining_frontend_unsafe_chars", input: "x`y[z]{w},v&u#t", want: "x_y_z_w_v_u_t"},
33+
{name: "only_shell_chars", input: "$()", wantErr: true},
3134
{name: "trim_leading_dots", input: "....bashrc", want: "bashrc"},
3235
{name: "trim_trailing_dots", input: "report...", want: "report"},
3336
{name: "unicode_passes_through", input: "résumé.pdf", want: "résumé.pdf"},

‎site/src/pages/AgentsPage/utils/chatAttachments.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ const unsafeChatFileNameChars = /[()[\]{}<>'"`;,:*?|&#$\\/\s\p{Cc}]/gu;
266266
* LLM prompts, audit logs, path interpolation) with underscores. Keeps
267267
* dots, dashes, underscores, ASCII alphanumerics, and non-ASCII letters
268268
* so localized names remain readable. The server still applies its own
269-
* normalization (control-char strip plus 255-byte truncate) on top of this.
269+
* normalization on top of this.
270270
*
271271
* If the sanitized name is empty after trimming leading or trailing `_`,
272272
* `.`, or whitespace, falls back to `"file"` so the server's

0 commit comments

Comments
 (0)