package main import ( "bytes" "context" "errors" "io" "net/http" "net/http/httptest" "path/filepath" "strconv" "strings" "testing" "time" ) // The panel (index.js NODE_FS_WRITE_TOO_LARGE_MARKER, nodes.js // NODE_FS_WRITE_TOO_LARGE_MARKER_NODES, utils/dashboard-assistant-tools.js // NODE_FS_WRITE_TOO_LARGE_MARKER_ASSISTANT) maps the daemon's 400 for an // over-budget write body to its friendly 413 by matching the substring // "content too large". These tests pin the split readJSON contract: over-cap // bodies keep that marker substring while malformed JSON gets a distinct // message that must NOT carry it (the responses used to share the combined // "bad json or content too large (max 10MB)" text, so a malformed body was // misreported as exceeding the 10 MB editor limit). const fsWriteTooLargeMarker = "content too large" func TestFSWriteHandlersWithdrawExpiredRequestsWhileStorageIsLocked(t *testing.T) { agent := newReinstallRaceTestAgent(t) const serverName = "alpha" serverDir := seedRaceServer(t, agent, serverName) t.Cleanup(agent.lockUploadScope(serverDir)) for _, scenario := range []struct { name string handler http.HandlerFunc body string }{ {"shared files endpoint", agent.handleFSWrite, `{"server":"alpha","path":` + strconv.Quote(filepath.Join(serverDir, "world-data.txt")) + `,"content":"stale"}`}, {"server files endpoint", func(w http.ResponseWriter, r *http.Request) { agent.handleFilesWrite(w, r, serverName) }, `{"path":"world-data.txt","content":"stale"}`}, } { t.Run(scenario.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() response := httptest.NewRecorder() request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(scenario.body)).WithContext(ctx) done := make(chan struct{}) go func() { defer close(done) scenario.handler(response, request) }() select { case <-done: if response.Code != http.StatusRequestTimeout { t.Fatalf("expected the waiting write to withdraw without acquiring storage, got %d: %s", response.Code, response.Body.String()) } case <-time.After(2 * time.Second): t.Fatal("expired write kept waiting for the storage lock") } assertServerDirUntouched(t, agent, serverName, serverDir) }) } } // fsWriteRawBody posts a raw (not necessarily valid JSON) body to a handler. func fsWriteRawBody(t *testing.T, handler func(http.ResponseWriter, *http.Request), path string, body []byte) *httptest.ResponseRecorder { t.Helper() req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() handler(rr, req) return rr } // fsJSONBodyOfLen builds a valid {"content":"aaa…"} body of exactly total // bytes (minimum 14: the 12-byte prefix + closing quote and brace). func fsJSONBodyOfLen(total int) []byte { var buf bytes.Buffer buf.WriteString(`{"content":"`) buf.WriteString(strings.Repeat("a", total-14)) buf.WriteString(`"}`) if buf.Len() != total { panic("fsJSONBodyOfLen built wrong size") } return buf.Bytes() } // The 10 MiB write cap is inclusive: a body of exactly 10,485,760 bytes must // decode, only cap+1 fails, and the failure must be classified via // *http.MaxBytesError (errBodyTooLarge), not error-string sniffing. func TestReadJSON_SizeCapBoundaryInclusive(t *testing.T) { const cap = 10 << 20 exact := fsJSONBodyOfLen(cap) over := fsJSONBodyOfLen(cap + 1) // httptest.NewRequest only sets ContentLength for a few concrete reader // types; the multiReader variant exercises the unknown-length (chunked) // path through the same MaxBytesReader. unknown := func(b []byte) io.Reader { return io.MultiReader(bytes.NewReader(b)) } var dst struct{ Content string } w := httptest.NewRecorder() for _, tc := range []struct { name string body io.Reader }{ {"exact cap, known length", bytes.NewReader(exact)}, {"exact cap, unknown length", unknown(exact)}, } { if err := readJSON(w, httptest.NewRequest(http.MethodPost, "/t", tc.body), cap, &dst); err != nil { t.Fatalf("%s: body of exactly cap bytes must decode, got %v", tc.name, err) } } for _, tc := range []struct { name string body io.Reader }{ {"over cap, known length", bytes.NewReader(over)}, {"over cap, unknown length", unknown(over)}, } { err := readJSON(w, httptest.NewRequest(http.MethodPost, "/t", tc.body), cap, &dst) if !errors.Is(err, errBodyTooLarge) { t.Fatalf("%s: body of cap+1 bytes must be classified errBodyTooLarge, got %v", tc.name, err) } } // A parse failure must never be classified as over-cap. err := readJSON(w, httptest.NewRequest(http.MethodPost, "/t", strings.NewReader(`{"content":`)), cap, &dst) if err == nil || errors.Is(err, errBodyTooLarge) { t.Fatalf("truncated JSON must be a plain decode error, got %v", err) } } // A malformed body (syntax error, wrong type, unknown field, empty body) must // be answered with a distinct message that does not carry the panel's // too-large marker. func TestFSWriteHandlers_MalformedBodyNotReportedAsTooLarge(t *testing.T) { a, _, _ := newFSScopeTestAgent(t) handlers := []struct { name string handler func(http.ResponseWriter, *http.Request) path string }{ {"handleFSWrite", a.handleFSWrite, "/v1/fs/write"}, {"handleFilesWrite", func(w http.ResponseWriter, r *http.Request) { a.handleFilesWrite(w, r, "alpha") }, "/v1/servers/alpha/files"}, } bodies := []struct { name string body string }{ {"syntax error", `{"path":"a.txt",`}, {"type failure", `{"path":"a.txt","server":"alpha","content":5}`}, {"unknown field", `{"path":"a.txt","server":"alpha","content":"x","extra":1}`}, {"empty body", ``}, } for _, h := range handlers { for _, b := range bodies { rr := fsWriteRawBody(t, h.handler, h.path, []byte(b.body)) if rr.Code != 400 { t.Fatalf("%s/%s: expected 400, got %d (%s)", h.name, b.name, rr.Code, rr.Body.String()) } if !strings.Contains(rr.Body.String(), "invalid JSON body") { t.Fatalf("%s/%s: expected the invalid-JSON message, got %s", h.name, b.name, rr.Body.String()) } if strings.Contains(rr.Body.String(), fsWriteTooLargeMarker) { t.Fatalf("%s/%s: malformed body must not carry the too-large marker: %s", h.name, b.name, rr.Body.String()) } } } } // An over-cap body must keep the "content too large" marker the panel maps to // its friendly 413, and must not be reported as invalid JSON. func TestFSWriteHandlers_OversizeBodyKeepsTooLargeMarker(t *testing.T) { a, _, _ := newFSScopeTestAgent(t) handlers := []struct { name string handler func(http.ResponseWriter, *http.Request) path string }{ {"handleFSWrite", a.handleFSWrite, "/v1/fs/write"}, {"handleFilesWrite", func(w http.ResponseWriter, r *http.Request) { a.handleFilesWrite(w, r, "alpha") }, "/v1/servers/alpha/files"}, } body := `{"path":"big.txt","server":"alpha","content":"` + strings.Repeat("a", 10<<20) + `"}` for _, h := range handlers { rr := fsWriteRawBody(t, h.handler, h.path, []byte(body)) if rr.Code != 400 { t.Fatalf("%s: expected 400, got %d (%s)", h.name, rr.Code, rr.Body.String()) } if !strings.Contains(rr.Body.String(), fsWriteTooLargeMarker) { t.Fatalf("%s: over-cap body must keep the too-large marker: %s", h.name, rr.Body.String()) } if strings.Contains(rr.Body.String(), "invalid JSON body") { t.Fatalf("%s: over-cap body must not be reported as invalid JSON: %s", h.name, rr.Body.String()) } } }