package main // Regression tests for the /v1/fs/uploadUrl response-loss bug: the server-wide // WriteTimeout (120s) is armed once when the request starts being read, but // handleFSUploadURL only writes its response after the full remote download // (bounded by the 30-minute fetch context). Every download that outlived the // write deadline committed the file and then lost the response; the panel's // relay (nodes.js /upload-url) answered 502 on the dropped connection and the // user re-ran an upload that had already succeeded. // // The tests scale the same geometry down to milliseconds: a handler whose // work outlasts the server's WriteTimeout by a wide margin. Two control tests // prove the harness itself on every platform (a handler WITHOUT the deadline // extension loses its response; the exact extension mechanism the fix uses // beats the server-wide timeout); the end-to-end regression then runs the real // handler against a delayed download fixture and skips, like the existing // upload_url_filename_test.go e2e, on hosts with no fetchable outbound // address. import ( "bytes" "context" "encoding/json" "fmt" "io" "net" "net/http" "net/http/httptest" "net/netip" "os" "path/filepath" "testing" "time" ) // deadlineHarnessWriteTimeout mirrors the production server's 120s // WriteTimeout scaled down; every deadlineHarnessSleep below outlasts it by // 2.5x or more, so "the handler writes after the deadline" is an absolute // property of the schedule, not a race. const ( deadlineHarnessWriteTimeout = 120 * time.Millisecond deadlineHarnessSleep = 300 * time.Millisecond deadlineFixtureDelay = 400 * time.Millisecond ) // startDeadlineTestServer hosts h behind a REAL listener with a short // server-wide WriteTimeout — httptest.NewServer would leave WriteTimeout at // zero and the whole bug class would not reproduce. func startDeadlineTestServer(t *testing.T, h http.Handler) *httptest.Server { t.Helper() srv := httptest.NewUnstartedServer(h) srv.Config.ReadTimeout = 5 * time.Second srv.Config.ReadHeaderTimeout = 2 * time.Second srv.Config.WriteTimeout = deadlineHarnessWriteTimeout srv.Config.IdleTimeout = 5 * time.Second srv.Start() t.Cleanup(srv.Close) return srv } // Control: with the stock server config and no per-connection deadline // extension, a handler that responds after the WriteTimeout loses the // response (the client sees a dropped connection, exactly the reported // symptom). If this ever starts passing, the harness geometry is broken and // the regression below proves nothing. func TestWriteTimeoutWithoutExtensionLosesResponse(t *testing.T) { srv := startDeadlineTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(deadlineHarnessSleep) jsonWrite(w, 200, map[string]any{"ok": true}) })) resp, err := http.Post(srv.URL, "application/json", bytes.NewReader(nil)) if err == nil { resp.Body.Close() t.Fatalf("expected the response to be lost when the handler writes %v after a %v WriteTimeout, got status %d", deadlineHarnessSleep, deadlineHarnessWriteTimeout, resp.StatusCode) } } // Control: the exact mechanism the fix relies on — // http.NewResponseController(w).SetWriteDeadline — overrides the server-wide // WriteTimeout for this connection, so a handler that extends before its long // work still delivers the response. func TestWriteDeadlineExtensionBeatsServerWriteTimeout(t *testing.T) { srv := startDeadlineTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(30 * time.Second)) time.Sleep(deadlineHarnessSleep) jsonWrite(w, 200, map[string]any{"ok": true}) })) resp, err := http.Post(srv.URL, "application/json", bytes.NewReader(nil)) if err != nil { t.Fatalf("deadline extension did not beat the server-wide WriteTimeout: %v", err) } defer resp.Body.Close() var out map[string]any if err := json.NewDecoder(resp.Body).Decode(&out); err != nil || out["ok"] != true { t.Fatalf("extended-deadline response = (%v, %v)", out, err) } } // serveDelayedURLUploadFixture serves one fixed body after a fixed delay from // a listener bound to a fetchable local address (same gating as // serveURLUploadFixture in upload_url_filename_test.go): the delay makes the // daemon handler's response land far past the harness WriteTimeout, the // scaled-down shape of the reported bug. func serveDelayedURLUploadFixture(t *testing.T, delay time.Duration, body []byte) string { t.Helper() ip := uploadURLTestAddress(t) l, err := net.Listen("tcp", net.JoinHostPort(ip.String(), "0")) if err != nil { t.Skipf("listen on %s: %v", ip, err) } srv := &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(delay) w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body))) _, _ = w.Write(body) }), } go func() { _ = srv.Serve(l) }() t.Cleanup(func() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() _ = srv.Shutdown(ctx) }) return "http://" + l.Addr().String() } // The regression: handleFSUploadURL must deliver its 200 (and the committed // file) even when the remote download outlives the server's WriteTimeout. // Before the fix this exact shape lost the response: the download (delayed // 400ms here, minutes in production) outlasted the 120ms/120s WriteTimeout, // the connection dropped after the commit, and the relay answered 502. func TestUploadURLResponseSurvivesServerWriteTimeout(t *testing.T) { a, serverDir := newURLUploadFilenameTestAgent(t) // The fixture listens on a non-standard port; the any-port escape hatch is // the established, tested way to lift the 80/443 allowlist for it. t.Setenv("REMOTE_FETCH_ALLOW_ANY_PORT", "1") content := bytes.Repeat([]byte("B"), 4096) baseURL := serveDelayedURLUploadFixture(t, deadlineFixtureDelay, content) srv := startDeadlineTestServer(t, http.HandlerFunc(a.handleFSUploadURL)) payload, err := json.Marshal(map[string]any{ "dir": serverDir, "server": "alpha", "url": baseURL + "/slow.bin", "filename": "slow.bin", }) if err != nil { t.Fatalf("marshal payload: %v", err) } // Fresh client: no connection reuse, so the outcome is not confounded by // retry-on-reused-connection semantics. client := &http.Client{Timeout: 30 * time.Second} resp, err := client.Post(srv.URL, "application/json", bytes.NewReader(payload)) if err != nil { t.Fatalf("response lost after a %v download under a %v WriteTimeout: %v", deadlineFixtureDelay, deadlineHarnessWriteTimeout, err) } defer resp.Body.Close() if resp.StatusCode != 200 { body, _ := io.ReadAll(resp.Body) t.Fatalf("upload-url after slow download: status %d body %s", resp.StatusCode, body) } var out struct { OK bool `json:"ok"` Filename string `json:"filename"` Bytes int64 `json:"bytes"` } if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { t.Fatalf("decode response: %v", err) } if !out.OK || out.Filename != "slow.bin" || out.Bytes != int64(len(content)) { t.Fatalf("response = %+v, want ok filename slow.bin %d bytes", out, len(content)) } stored, err := os.ReadFile(filepath.Join(serverDir, "slow.bin")) if err != nil { t.Fatalf("read stored file: %v", err) } if !bytes.Equal(stored, content) { t.Fatalf("stored slow.bin content mismatch (%d bytes)", len(stored)) } } // Guards the fixture helper itself: the daemon's outbound filter must accept // the fixture address, else the regression above would skip everywhere and // never run. Runs the same classification the filter uses; skipped silently // on hosts with no fetchable address (the regression skips there too). func TestUploadURLDeadlineFixtureAddressIsFetchable(t *testing.T) { ip := uploadURLTestAddress(t) addr, ok := netip.AddrFromSlice(ip) if !ok || isBlockedOutboundAddr(addr) { t.Fatalf("fixture address %s must pass isBlockedOutboundAddr for the e2e deadline test to run", ip) } }