Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(cli): validate self-host health before saving config (MUL-8851) (#10240)

Bohan Jiang94908f3c6141
diff --git a/server/cmd/multica/cmd_setup.go b/server/cmd/multica/cmd_setup.go
index 3d251c6ca3..c97960b240 100644
--- a/server/cmd/multica/cmd_setup.go
+++ b/server/cmd/multica/cmd_setup.go
@@ -3,7 +3,9 @@ package main
import (
"bufio"
"context"
+ "encoding/json"
"fmt"
+ "io"
"net"
"net/http"
"net/url"
@@ -227,18 +229,23 @@ func runSetupSelfHost(cmd *cobra.Command, args []string) error {
return nil
}
- // Probe before persisting anything. A failed setup must never overwrite a
- // working config or wipe the saved token: persistSelfHostConfigIfReachable
- // writes only when the server answers, so an unreachable host leaves the
- // existing config untouched and the user stays logged in.
- reachable, err := persistSelfHostConfigIfReachable(serverURL, appURL, profile, probeServer)
+ // Verify backend health before writing so a failed setup preserves the profile.
+ probeResult, err := persistSelfHostConfigIfReachable(serverURL, appURL, profile, probeServer)
if err != nil {
return fmt.Errorf("save config: %w", err)
}
- if !reachable {
- fmt.Fprintf(os.Stderr, "\n⚠ Server at %s is not reachable.\n", serverURL)
+ if !probeResult.healthy {
+ switch probeResult.statusCode {
+ case 0:
+ fmt.Fprintf(os.Stderr, "\n⚠ Server at %s is not reachable.\n", serverURL)
+ case http.StatusOK:
+ fmt.Fprintf(os.Stderr, "\n⚠ Server at %s did not return a healthy Multica backend response.\n", serverURL)
+ fmt.Fprintln(os.Stderr, " A login gateway may be intercepting the request to /health.")
+ default:
+ fmt.Fprintf(os.Stderr, "\n⚠ Server at %s returned HTTP %d (%s) from /health.\n", serverURL, probeResult.statusCode, http.StatusText(probeResult.statusCode))
+ }
fmt.Fprintln(os.Stderr, " Your existing configuration was left unchanged.")
- fmt.Fprintln(os.Stderr, " Verify the URL, then re-run 'multica setup self-host' once it's reachable.")
+ fmt.Fprintln(os.Stderr, " Verify the URL, then re-run 'multica setup self-host' once the backend is healthy.")
return nil
}
@@ -330,25 +337,21 @@ func daemonActiveTaskCount(health map[string]any) int64 {
}
}
-// persistSelfHostConfigIfReachable probes serverURL and, only when it answers,
-// overwrites the profile config with the given self-host URLs. When the server
-// is unreachable it leaves any existing config — and its auth token — untouched
-// and returns false, so a failed `setup self-host` never logs the user out or
-// clobbers a working config (the original ordering saved first, then probed,
-// then bailed — wiping the token on every failed probe). The prober is injected
-// so tests can exercise both branches without real network I/O.
-func persistSelfHostConfigIfReachable(serverURL, appURL, profile string, probe func(string) bool) (bool, error) {
- if !probe(serverURL) {
- return false, nil
+// persistSelfHostConfigIfReachable writes the self-host URLs only after a
+// healthy Multica response, preserving the existing profile on probe failure.
+func persistSelfHostConfigIfReachable(serverURL, appURL, profile string, probe func(string) serverProbeResult) (serverProbeResult, error) {
+ result := probe(serverURL)
+ if !result.healthy {
+ return result, nil
}
cfg := cli.CLIConfig{
ServerURL: serverURL,
AppURL: appURL,
}
if err := cli.SaveCLIConfigForProfile(cfg, profile); err != nil {
- return false, err
+ return result, err
}
- return true, nil
+ return result, nil
}
// resolveSelfHostServerURL picks the backend URL for `setup self-host`: the
@@ -436,21 +439,44 @@ func promptAppURL(serverURL string) (string, error) {
return strings.TrimRight(strings.TrimSpace(line), "/"), nil
}
-// probeServer checks whether a Multica backend is reachable at the given URL.
-func probeServer(baseURL string) bool {
+type serverProbeResult struct {
+ statusCode int
+ healthy bool
+}
+
+const maxServerHealthResponseBytes = 4 * 1024
+
+// probeServer requires a healthy Multica payload, including after redirects.
+func probeServer(baseURL string) serverProbeResult {
url := strings.TrimRight(baseURL, "/") + "/health"
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
- return false
+ return serverProbeResult{}
}
resp, err := (&http.Client{Timeout: 2 * time.Second}).Do(req)
if err != nil {
- return false
+ return serverProbeResult{}
}
defer resp.Body.Close()
- return resp.StatusCode == http.StatusOK
+ result := serverProbeResult{statusCode: resp.StatusCode}
+ if resp.StatusCode != http.StatusOK {
+ return result
+ }
+
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxServerHealthResponseBytes+1))
+ if err != nil || len(body) > maxServerHealthResponseBytes {
+ return result
+ }
+ var health struct {
+ Status string `json:"status"`
+ }
+ if err := json.Unmarshal(body, &health); err != nil || health.Status != "ok" {
+ return result
+ }
+ result.healthy = true
+ return result
}
diff --git a/server/cmd/multica/cmd_setup_test.go b/server/cmd/multica/cmd_setup_test.go
index ef8e178c38..335f0db23a 100644
--- a/server/cmd/multica/cmd_setup_test.go
+++ b/server/cmd/multica/cmd_setup_test.go
@@ -1,6 +1,10 @@
package main
import (
+ "bytes"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"strings"
@@ -11,6 +15,176 @@ import (
"github.com/multica-ai/multica/server/internal/cli"
)
+func TestSelfHostSetupHealthResponses(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ status int
+ redirect bool
+ healthy bool
+ }{
+ {name: "HTML login page", body: "<html>Sign in</html>"},
+ {name: "redirect to HTML login page", body: "<html>Sign in</html>", redirect: true},
+ {name: "unrelated JSON", body: `{"status":"healthy"}`},
+ {name: "unhealthy status", body: `{"status":"error"}`},
+ {name: "missing status", body: `{"pid":123}`},
+ {name: "non-string status", body: `{"status":true}`},
+ {name: "null response", body: `null`},
+ {name: "empty response"},
+ {name: "malformed JSON", body: `{"status":"ok"`},
+ {name: "trailing content", body: `{"status":"ok"}<html>Sign in</html>`},
+ {name: "oversized response", body: `{"status":"ok","extra":"` + strings.Repeat("x", 4096) + `"}`},
+ {name: "non-200 response", body: `{"status":"ok"}`, status: http.StatusServiceUnavailable},
+ {name: "legacy healthy response", body: `{"status":"ok"}`, healthy: true},
+ {name: "healthy response with extra fields", body: `{"status":"ok","pid":123,"commit":"abc123","started_at":"2026-11-10T00:00:00Z","future":{"key":true}}`, healthy: true},
+ {name: "healthy response after redirect", body: `{"status":"ok"}`, redirect: true, healthy: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ redirectTestHome(t, t.TempDir())
+ const profile = "self-host-health-test"
+ existing := cli.CLIConfig{
+ ServerURL: "https://api.old.example",
+ AppURL: "https://old.example",
+ WorkspaceID: "ws-1",
+ Token: "mul_existing_token",
+ DeviceName: "existing-device",
+ RuntimeName: "existing-runtime",
+ }
+ if err := cli.SaveCLIConfigForProfile(existing, profile); err != nil {
+ t.Fatal(err)
+ }
+ path, err := cli.CLIConfigPathForProfile(profile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if tc.redirect && r.URL.Path == "/health" {
+ http.Redirect(w, r, "/redirected", http.StatusFound)
+ return
+ }
+ // A proxy may rewrite Content-Type, so only the payload matters.
+ w.Header().Set("Content-Type", "text/plain")
+ if tc.status != 0 {
+ w.WriteHeader(tc.status)
+ }
+ fmt.Fprint(w, tc.body)
+ }))
+ defer server.Close()
+
+ result, err := persistSelfHostConfigIfReachable(server.URL, "https://new.example", profile, probeServer)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.healthy != tc.healthy {
+ t.Errorf("healthy = %v, want %v", result.healthy, tc.healthy)
+ }
+ if !tc.healthy {
+ after, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(before, after) {
+ t.Error("failed health probe changed the existing profile")
+ }
+ return
+ }
+ got, err := cli.LoadCLIConfigForProfile(profile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.ServerURL != server.URL || got.AppURL != "https://new.example" {
+ t.Error("healthy backend URLs were not saved")
+ }
+ })
+ }
+}
+
+func TestSetupSelfHostProbeFailure(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ existing bool
+ unreachable bool
+ status int
+ wantMessage string
+ wantGatewayHint bool
+ }{
+ {name: "invalid health preserves profile", existing: true, wantMessage: "did not return a healthy Multica backend response", wantGatewayHint: true},
+ {name: "invalid health creates no profile", wantMessage: "did not return a healthy Multica backend response", wantGatewayHint: true},
+ {name: "connection failure preserves profile", existing: true, unreachable: true, wantMessage: "is not reachable"},
+ {name: "unauthorized response", existing: true, status: http.StatusUnauthorized, wantMessage: "returned HTTP 401 (Unauthorized) from /health"},
+ {name: "bad gateway response", existing: true, status: http.StatusBadGateway, wantMessage: "returned HTTP 502 (Bad Gateway) from /health"},
+ {name: "unavailable response", existing: true, status: http.StatusServiceUnavailable, wantMessage: "returned HTTP 503 (Service Unavailable) from /health"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ redirectTestHome(t, t.TempDir())
+ if tc.existing {
+ if err := cli.SaveCLIConfig(cli.CLIConfig{
+ ServerURL: "https://api.old.example", Token: "mul_existing_token", DeviceName: "existing-device",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ path, err := cli.CLIConfigPathForProfile("")
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, err := os.ReadFile(path)
+ if err != nil && !os.IsNotExist(err) {
+ t.Fatal(err)
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if tc.status != 0 {
+ w.WriteHeader(tc.status)
+ }
+ fmt.Fprint(w, "<html>Sign in</html>")
+ }))
+ defer server.Close()
+ if tc.unreachable {
+ server.Close()
+ }
+ cmd := testCmd()
+ cmd.Flags().String("server-url", "", "")
+ cmd.Flags().String("app-url", "", "")
+ cmd.Flags().Int("frontend-port", 3000, "")
+ if err := cmd.Flags().Set("server-url", server.URL); err != nil {
+ t.Fatal(err)
+ }
+ if err := cmd.Flags().Set("app-url", "https://new.example"); err != nil {
+ t.Fatal(err)
+ }
+
+ stderr := captureStderr(t)
+ defer stderr.restore()
+ pipeStdin(t, "y\n", func() {
+ if err := runSetupSelfHost(cmd, nil); err != nil {
+ t.Fatalf("setup: %v", err)
+ }
+ })
+ output := stderr.read()
+ if !strings.Contains(output, tc.wantMessage) || !strings.Contains(output, "configuration was left unchanged") {
+ t.Errorf("missing probe failure message: %s", output)
+ }
+ if strings.Contains(output, "login gateway") != tc.wantGatewayHint {
+ t.Errorf("gateway hint should appear only for invalid HTTP 200 health responses: %s", output)
+ }
+ after, err := os.ReadFile(path)
+ if !tc.existing {
+ if !os.IsNotExist(err) {
+ t.Errorf("failed setup created a profile: read error = %v", err)
+ }
+ } else if err != nil || !bytes.Equal(before, after) {
+ t.Errorf("failed setup changed the existing profile: read error = %v", err)
+ }
+ })
+ }
+}
+
// TestPersistSelfHostConfigIfReachable verifies the fix for the
// setup-wipes-token bug: a failed reachability probe must leave the existing
// config (and its auth token) untouched, instead of overwriting it before the
@@ -30,13 +204,13 @@ func TestPersistSelfHostConfigIfReachable(t *testing.T) {
proceed, err := persistSelfHostConfigIfReachable(
"https://api.new.example", "https://new.example", "",
- func(string) bool { return false },
+ func(string) serverProbeResult { return serverProbeResult{} },
)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if proceed {
- t.Fatalf("proceed: want false for unreachable server")
+ if proceed.statusCode != 0 || proceed.healthy {
+ t.Fatalf("probe result = %v, want unreachable", proceed)
}
got, err := cli.LoadCLIConfig()
@@ -56,13 +230,13 @@ func TestPersistSelfHostConfigIfReachable(t *testing.T) {
proceed, err := persistSelfHostConfigIfReachable(
"https://api.new.example", "https://new.example", "",
- func(string) bool { return true },
+ func(string) serverProbeResult { return serverProbeResult{statusCode: http.StatusOK, healthy: true} },
)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if !proceed {
- t.Fatalf("proceed: want true for reachable server")
+ if !proceed.healthy {
+ t.Fatalf("probe result = %v, want healthy", proceed)
}
got, err := cli.LoadCLIConfig()