Skip to content
Open
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
28 changes: 26 additions & 2 deletions rmqctl/internal/studio/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ import (

const DefaultTimeout = 30 * time.Second

// maxResponseBytes caps how much of a Studio response body is buffered in
// memory. Studio envelopes are small JSON documents; an unbounded ReadAll
// would let a misbehaving endpoint exhaust the CLI before validation runs.
const maxResponseBytes = 64 << 20 // 64 MiB

const (
toolCallPath = "/api/mcp/tools/call"
mcpPath = "/api/mcp"
Expand Down Expand Up @@ -75,6 +80,8 @@ func (t Target) validate() error {

type Client struct {
httpClient *http.Client
// maxResponseBytes bounds how much of a Studio response body is buffered.
maxResponseBytes int64
}

type APIError struct {
Expand All @@ -92,7 +99,7 @@ func (e *APIError) Error() string {
// validate the dependency when it is used so offline commands can still be
// constructed when an App has no HTTP client.
func NewClient(httpClient *http.Client) Client {
return Client{httpClient: httpClient}
return Client{httpClient: httpClient, maxResponseBytes: maxResponseBytes}
}

func NewHTTPClient() *http.Client {
Expand Down Expand Up @@ -141,7 +148,11 @@ func (c Client) request(ctx context.Context, target Target, method string, path
return err
}
defer response.Body.Close()
data, err := io.ReadAll(response.Body)
limit := c.maxResponseBytes
if limit <= 0 {
limit = maxResponseBytes
}
data, err := readBounded(response.Body, limit)
if err != nil {
return err
}
Expand Down Expand Up @@ -199,3 +210,16 @@ func responseError(statusCode int, data []byte) error {
func hasJSONData(data json.RawMessage) bool {
return len(data) > 0 && string(data) != "null"
}

// readBounded reads at most max bytes from body. It returns an error instead
// of buffering an unbounded stream when the limit is exceeded.
func readBounded(body io.Reader, max int64) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(body, max+1))
if err != nil {
return nil, err
}
if int64(len(data)) > max {
return nil, fmt.Errorf("studio response exceeds %d bytes", max)
}
return data, nil
}
87 changes: 86 additions & 1 deletion rmqctl/internal/studio/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@
*/
package studio

import "testing"
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

// TestValidateServerSchemeAdaptiveHTTP verifies the adaptive scheme policy:
// HTTPS is always accepted, plain HTTP is accepted for loopback / RFC1918
Expand Down Expand Up @@ -76,3 +82,82 @@ func TestIsPrivateHost(t *testing.T) {
}
}
}

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

t.Run("accepts body at the limit", func(t *testing.T) {
t.Parallel()
body := strings.NewReader("12345")
data, err := readBounded(body, 5)
if err != nil {
t.Fatalf("readBounded() error = %v", err)
}
if string(data) != "12345" {
t.Fatalf("readBounded() = %q, want 12345", data)
}
})

t.Run("rejects body over the limit", func(t *testing.T) {
t.Parallel()
body := strings.NewReader("123456")
if _, err := readBounded(body, 5); err == nil {
t.Fatal("readBounded() error = nil, want size-cap error")
} else if !strings.Contains(err.Error(), "exceeds") {
t.Fatalf("readBounded() error = %v, want mentions exceeds", err)
}
})
}

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

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"code":200,"data":`))
_, _ = w.Write([]byte(strings.Repeat("x", 64)))
_, _ = w.Write([]byte(`}`))
}))
t.Cleanup(server.Close)

client := NewClient(server.Client())
client.maxResponseBytes = 16
target := Target{
Server: server.URL,
InstanceID: "inst",
Credential: Credential{AccessKey: "ak", SecretKey: "sk"},
}

err := client.request(context.Background(), target, http.MethodGet, "/api/mcp", nil, &map[string]any{})
if err == nil {
t.Fatal("request() error = nil, want size-cap error")
}
if !strings.Contains(err.Error(), "exceeds") {
t.Fatalf("request() error = %v, want size-cap error", err)
}
}

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

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"code":200,"data":{"ok":true}}`))
}))
t.Cleanup(server.Close)

client := NewClient(server.Client())
target := Target{
Server: server.URL,
InstanceID: "inst",
Credential: Credential{AccessKey: "ak", SecretKey: "sk"},
}

var out map[string]any
if err := client.request(context.Background(), target, http.MethodGet, "/api/mcp", nil, &out); err != nil {
t.Fatalf("request() error = %v", err)
}
if out["ok"] != true {
t.Fatalf("request() out = %#v, want ok=true", out)
}
}