Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: add cloud runtime fleet proxy API (MUL-2453) (#2986)
Multica Eve41cb91abd945
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f021f37dcf..633ff12f3a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -138,6 +138,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusUseDailyRollupForDashboard: os.Getenv("USAGE_DASHBOARD_ROLLUP_ENABLED") == "true",PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),+ CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),+ CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),}h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)if opts.DaemonWakeup != nil {@@ -196,7 +198,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Use(cors.Handler(cors.Options{AllowedOrigins: origins,AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Workspace-Slug", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token", "X-Client-Platform", "X-Client-Version", "X-Client-OS"},+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Workspace-ID", "X-Workspace-Slug", "X-Request-ID", "X-Agent-ID", "X-Task-ID", "X-CSRF-Token", "X-Client-Platform", "X-Client-Version", "X-Client-OS", "X-User-PAT"},AllowCredentials: true,MaxAge: 300,}))@@ -589,6 +591,22 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus})})+ // Cloud Runtime fleet proxy. The remote service URL is configured+ // on SaaS API nodes only; self-hosted deployments return 503.+ r.Route("/api/cloud-runtime", func(r chi.Router) {+ r.Get("/", h.GetCloudRuntimeService)+ r.Get("/healthz", h.GetCloudRuntimeHealth)+ r.Get("/readyz", h.GetCloudRuntimeReady)+ r.Get("/nodes", h.ListCloudRuntimeNodes)+ r.Post("/nodes", h.CreateCloudRuntimeNode)+ r.Delete("/nodes", h.DeleteCloudRuntimeNode)+ r.Post("/nodes/start", h.StartCloudRuntimeNode)+ r.Post("/nodes/stop", h.StopCloudRuntimeNode)+ r.Post("/nodes/reboot", h.RebootCloudRuntimeNode)+ r.Post("/nodes/status", h.GetCloudRuntimeNodeStatus)+ r.Post("/nodes/exec", h.ExecCloudRuntimeNode)+ })+// Tasks (user-facing, with ownership check)r.Post("/api/tasks/{taskId}/cancel", h.CancelTaskByUser)@@ -724,3 +742,10 @@ func splitAndTrim(s string) []string {}return res}++func cloudRuntimeFleetURLFromEnv() string {+ if url := strings.TrimSpace(os.Getenv("MULTICA_CLOUD_FLEET_URL")); url != "" {+ return url+ }+ return strings.TrimSpace(os.Getenv("MULTICA_FLEET_URL"))+}diff --git a/server/internal/cloudruntime/client.go b/server/internal/cloudruntime/client.gonew file mode 100644index 0000000000..ab5490f59d--- /dev/null+++ b/server/internal/cloudruntime/client.go@@ -0,0 +1,128 @@+package cloudruntime++import (+ "bytes"+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"+)++const (+ defaultTimeout = 35 * time.Second+ maxResponseBodySize = 1 << 20+)++var (+ ErrDisabled = errors.New("cloud runtime fleet URL is not configured")+ ErrInvalidBaseURL = errors.New("cloud runtime fleet URL is invalid")+)++type Config struct {+ BaseURL string+ Timeout time.Duration+ HTTPClient *http.Client+}++type Request struct {+ Method string+ Path string+ Query url.Values+ Body []byte+ UserID string+ UserPAT string+ RequestID string+}++type Response struct {+ StatusCode int+ Header http.Header+ Body []byte+}++type Client struct {+ baseURL string+ httpClient *http.Client+}++func NewClient(cfg Config) *Client {+ timeout := cfg.Timeout+ if timeout <= 0 {+ timeout = defaultTimeout+ }+ httpClient := cfg.HTTPClient+ if httpClient == nil {+ httpClient = &http.Client{Timeout: timeout}+ }+ return &Client{+ baseURL: strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/"),+ httpClient: httpClient,+ }+}++func (c *Client) Enabled() bool {+ return c != nil && c.baseURL != ""+}++func (c *Client) Do(ctx context.Context, req Request) (*Response, error) {+ if c == nil || c.baseURL == "" {+ return nil, ErrDisabled+ }++ base, err := url.Parse(c.baseURL)+ if err != nil || base.Scheme == "" || base.Host == "" {+ return nil, fmt.Errorf("%w: %s", ErrInvalidBaseURL, c.baseURL)+ }+ if !strings.HasPrefix(req.Path, "/") {+ return nil, fmt.Errorf("cloud runtime path must start with /: %s", req.Path)+ }++ u := *base+ u.Path = strings.TrimRight(base.Path, "/") + req.Path+ u.RawQuery = req.Query.Encode()++ var body io.Reader+ if len(req.Body) > 0 {+ body = bytes.NewReader(req.Body)+ }+ httpReq, err := http.NewRequestWithContext(ctx, req.Method, u.String(), body)+ if err != nil {+ return nil, err+ }+ httpReq.Header.Set("Accept", "application/json")+ if len(req.Body) > 0 {+ httpReq.Header.Set("Content-Type", "application/json")+ }+ if req.UserID != "" {+ httpReq.Header.Set("X-User-ID", req.UserID)+ }+ if req.UserPAT != "" {+ httpReq.Header.Set("X-User-PAT", req.UserPAT)+ }+ if req.RequestID != "" {+ httpReq.Header.Set("X-Request-ID", req.RequestID)+ }++ resp, err := c.httpClient.Do(httpReq)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()++ data, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize+1))+ if err != nil {+ return nil, err+ }+ if len(data) > maxResponseBodySize {+ return nil, fmt.Errorf("cloud runtime response exceeds %d bytes", maxResponseBodySize)+ }+ return &Response{+ StatusCode: resp.StatusCode,+ Header: resp.Header.Clone(),+ Body: data,+ }, nil+}diff --git a/server/internal/cloudruntime/client_test.go b/server/internal/cloudruntime/client_test.gonew file mode 100644index 0000000000..96b42e7aa6--- /dev/null+++ b/server/internal/cloudruntime/client_test.go@@ -0,0 +1,90 @@+package cloudruntime++import (+ "context"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "testing"+)++func TestClientDoForwardsFleetRequest(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ t.Fatalf("method = %s, want POST", r.Method)+ }+ if r.URL.Path != "/base/api/v1/nodes" {+ t.Fatalf("path = %s, want /base/api/v1/nodes", r.URL.Path)+ }+ if r.URL.RawQuery != "limit=20&offset=0" {+ t.Fatalf("query = %s, want limit=20&offset=0", r.URL.RawQuery)+ }+ if got := r.Header.Get("Accept"); got != "application/json" {+ t.Fatalf("Accept = %q", got)+ }+ if got := r.Header.Get("Content-Type"); got != "application/json" {+ t.Fatalf("Content-Type = %q", got)+ }+ if got := r.Header.Get("X-User-ID"); got != "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001" {+ t.Fatalf("X-User-ID = %q", got)+ }+ if got := r.Header.Get("X-User-PAT"); got != "mul_test_pat" {+ t.Fatalf("X-User-PAT = %q", got)+ }+ if got := r.Header.Get("X-Request-ID"); got != "request-123" {+ t.Fatalf("X-Request-ID = %q", got)+ }+ body, err := io.ReadAll(r.Body)+ if err != nil {+ t.Fatalf("read body: %v", err)+ }+ if got := string(body); got != `{"instance_type":"g5.xlarge"}` {+ t.Fatalf("body = %s", got)+ }+ w.Header().Set("X-Request-ID", "fleet-request-456")+ w.WriteHeader(http.StatusCreated)+ w.Write([]byte(`{"status":"launching"}`))+ }))+ defer srv.Close()++ client := NewClient(Config{BaseURL: srv.URL + "/base/"})+ resp, err := client.Do(context.Background(), Request{+ Method: http.MethodPost,+ Path: "/api/v1/nodes",+ Query: url.Values{"limit": []string{"20"}, "offset": []string{"0"}},+ Body: []byte(`{"instance_type":"g5.xlarge"}`),+ UserID: "01972f7e-7e8d-77ef-a13d-1b0ce3e9c001",+ UserPAT: "mul_test_pat",+ RequestID: "request-123",+ })+ if err != nil {+ t.Fatalf("Do: %v", err)+ }+ if resp.StatusCode != http.StatusCreated {+ t.Fatalf("status = %d", resp.StatusCode)+ }+ if got := resp.Header.Get("X-Request-ID"); got != "fleet-request-456" {+ t.Fatalf("response X-Request-ID = %q", got)+ }+ if got := string(resp.Body); got != `{"status":"launching"}` {+ t.Fatalf("response body = %s", got)+ }+}++func TestClientDoDisabled(t *testing.T) {+ client := NewClient(Config{})+ _, err := client.Do(context.Background(), Request{Method: http.MethodGet, Path: "/healthz"})+ if !errors.Is(err, ErrDisabled) {+ t.Fatalf("err = %v, want ErrDisabled", err)+ }+}++func TestClientDoInvalidBaseURL(t *testing.T) {+ client := NewClient(Config{BaseURL: "http://%"})+ _, err := client.Do(context.Background(), Request{Method: http.MethodGet, Path: "/healthz"})+ if !errors.Is(err, ErrInvalidBaseURL) {+ t.Fatalf("err = %v, want ErrInvalidBaseURL", err)+ }+}diff --git a/server/internal/handler/cloud_runtime.go b/server/internal/handler/cloud_runtime.gonew file mode 100644index 0000000000..a01f6a4eb4--- /dev/null+++ b/server/internal/handler/cloud_runtime.go@@ -0,0 +1,240 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "log/slog"+ "net/http"+ "net/url"+ "strings"++ chimw "github.com/go-chi/chi/v5/middleware"+ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/cloudruntime"+ "github.com/multica-ai/multica/server/internal/logger"+)++const maxCloudRuntimeRequestBodySize = 1 << 20++type cloudRuntimeProxyOptions struct {+ withUserID bool+ withQuery bool+ withBody bool+ withUserPAT bool+}++func (h *Handler) GetCloudRuntimeService(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodGet, "/api/v1/", cloudRuntimeProxyOptions{+ withUserID: true,+ })+}++func (h *Handler) GetCloudRuntimeHealth(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodGet, "/healthz", cloudRuntimeProxyOptions{})+}++func (h *Handler) GetCloudRuntimeReady(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodGet, "/readyz", cloudRuntimeProxyOptions{})+}++func (h *Handler) ListCloudRuntimeNodes(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodGet, "/api/v1/nodes", cloudRuntimeProxyOptions{+ withUserID: true,+ withQuery: true,+ })+}++func (h *Handler) CreateCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ withUserPAT: true,+ })+}++func (h *Handler) DeleteCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodDelete, "/api/v1/nodes", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ })+}++func (h *Handler) StartCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes/start", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ })+}++func (h *Handler) StopCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes/stop", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ })+}++func (h *Handler) RebootCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes/reboot", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ })+}++func (h *Handler) GetCloudRuntimeNodeStatus(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes/status", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ })+}++func (h *Handler) ExecCloudRuntimeNode(w http.ResponseWriter, r *http.Request) {+ h.proxyCloudRuntime(w, r, http.MethodPost, "/api/v1/nodes/exec", cloudRuntimeProxyOptions{+ withUserID: true,+ withBody: true,+ })+}++func (h *Handler) proxyCloudRuntime(w http.ResponseWriter, r *http.Request, method, path string, opts cloudRuntimeProxyOptions) {+ if h.CloudRuntime == nil || !h.CloudRuntime.Enabled() {+ writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")+ return+ }++ var userID string+ if opts.withUserID {+ var ok bool+ userID, ok = requireUserID(w, r)+ if !ok {+ return+ }+ }++ userPAT, ok := h.cloudRuntimeUserPAT(w, r, userID, opts.withUserPAT)+ if !ok {+ return+ }++ var body []byte+ if opts.withBody {+ body, ok = readCloudRuntimeJSONBody(w, r)+ if !ok {+ return+ }+ }++ var query url.Values+ if opts.withQuery {+ query = r.URL.Query()+ }++ resp, err := h.CloudRuntime.Do(r.Context(), cloudruntime.Request{+ Method: method,+ Path: path,+ Query: query,+ Body: body,+ UserID: userID,+ UserPAT: userPAT,+ RequestID: cloudRuntimeRequestID(r),+ })+ if err != nil {+ writeCloudRuntimeError(w, r, err)+ return+ }+ writeCloudRuntimeResponse(w, resp)+}++func readCloudRuntimeJSONBody(w http.ResponseWriter, r *http.Request) ([]byte, bool) {+ r.Body = http.MaxBytesReader(w, r.Body, maxCloudRuntimeRequestBodySize)+ data, err := io.ReadAll(r.Body)+ if err != nil {+ var maxErr *http.MaxBytesError+ if errors.As(err, &maxErr) {+ writeError(w, http.StatusRequestEntityTooLarge, "request body is too large")+ return nil, false+ }+ writeError(w, http.StatusBadRequest, "invalid request body")+ return nil, false+ }+ if len(bytes.TrimSpace(data)) == 0 {+ writeError(w, http.StatusBadRequest, "request body is required")+ return nil, false+ }+ var raw json.RawMessage+ if err := json.Unmarshal(data, &raw); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return nil, false+ }+ return data, true+}++func cloudRuntimeRequestID(r *http.Request) string {+ if id := r.Header.Get("X-Request-ID"); id != "" {+ return id+ }+ return chimw.GetReqID(r.Context())+}++func (h *Handler) cloudRuntimeUserPAT(w http.ResponseWriter, r *http.Request, userID string, enabled bool) (string, bool) {+ if !enabled {+ return "", true+ }+ if pat := strings.TrimSpace(r.Header.Get("X-User-PAT")); pat != "" {+ if !strings.HasPrefix(pat, "mul_") {+ writeError(w, http.StatusBadRequest, "invalid X-User-PAT")+ return "", false+ }+ if h.Queries == nil {+ writeError(w, http.StatusInternalServerError, "failed to validate X-User-PAT")+ return "", false+ }+ token, err := h.Queries.GetPersonalAccessTokenByHash(r.Context(), auth.HashToken(pat))+ if err != nil || uuidToString(token.UserID) != userID {+ writeError(w, http.StatusForbidden, "invalid X-User-PAT")+ return "", false+ }+ return pat, true+ }++ authHeader := strings.TrimSpace(r.Header.Get("Authorization"))+ const prefix = "Bearer "+ if strings.HasPrefix(authHeader, prefix+"mul_") {+ // Safe: auth middleware has already verified this PAT and set X-User-ID to its owner.+ return strings.TrimPrefix(authHeader, prefix), true+ }+ return "", true+}++func writeCloudRuntimeResponse(w http.ResponseWriter, resp *cloudruntime.Response) {+ if requestID := resp.Header.Get("X-Request-ID"); requestID != "" {+ w.Header().Set("X-Request-ID", requestID)+ }+ body := bytes.TrimSpace(resp.Body)+ if len(body) == 0 {+ w.WriteHeader(resp.StatusCode)+ return+ }+ if json.Valid(body) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(resp.StatusCode)+ w.Write(body)+ return+ }+ writeJSON(w, resp.StatusCode, map[string]string{"error": string(body)})+}++func writeCloudRuntimeError(w http.ResponseWriter, r *http.Request, err error) {+ switch {+ case errors.Is(err, cloudruntime.ErrDisabled):+ writeError(w, http.StatusServiceUnavailable, "cloud runtime is not configured")+ case errors.Is(err, cloudruntime.ErrInvalidBaseURL):+ writeError(w, http.StatusServiceUnavailable, "cloud runtime is misconfigured")+ case errors.Is(err, context.DeadlineExceeded):+ writeError(w, http.StatusGatewayTimeout, "cloud runtime request timed out")+ default:+ slog.Warn("cloud runtime request failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusBadGateway, "cloud runtime request failed")+ }+}diff --git a/server/internal/handler/cloud_runtime_test.go b/server/internal/handler/cloud_runtime_test.gonew file mode 100644index 0000000000..63741977da--- /dev/null+++ b/server/internal/handler/cloud_runtime_test.go@@ -0,0 +1,287 @@+package handler++import (+ "bytes"+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/cloudruntime"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type fakeCloudRuntimeProxy struct {+ enabled bool+ req cloudruntime.Request+ resp *cloudruntime.Response+ err error+ called bool+}++func (f *fakeCloudRuntimeProxy) Enabled() bool {+ return f.enabled+}++func (f *fakeCloudRuntimeProxy) Do(ctx context.Context, req cloudruntime.Request) (*cloudruntime.Response, error) {+ f.called = true+ f.req = req+ if f.err != nil {+ return nil, f.err+ }+ return f.resp, nil+}++func useCloudRuntimeProxy(t *testing.T, proxy cloudRuntimeProxy) {+ t.Helper()++ prevProxy := testHandler.CloudRuntime+ testHandler.CloudRuntime = proxy+ t.Cleanup(func() { testHandler.CloudRuntime = prevProxy })+}++func TestCreateCloudRuntimeNodeForwardsValidatedPAT(t *testing.T) {+ rawPAT := "mul_cloud_runtime_test_valid_pat"+ _, err := testHandler.Queries.CreatePersonalAccessToken(context.Background(), db.CreatePersonalAccessTokenParams{+ UserID: parseUUID(testUserID),+ Name: "cloud runtime test",+ TokenHash: auth.HashToken(rawPAT),+ TokenPrefix: rawPAT[:12],+ ExpiresAt: pgtype.Timestamptz{},+ })+ if err != nil {+ t.Fatalf("create PAT: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE token_hash = $1`, auth.HashToken(rawPAT))+ })++ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusCreated,+ Header: http.Header{"X-Request-Id": []string{"fleet-request-id"}},+ Body: []byte(`{"status":"launching"}`),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{+ "instance_type": "g5.xlarge",+ })+ req.Header.Set("X-User-PAT", rawPAT)+ req.Header.Set("X-Request-ID", "api-request-id")+ w := httptest.NewRecorder()++ testHandler.CreateCloudRuntimeNode(w, req)++ if w.Code != http.StatusCreated {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if !proxy.called {+ t.Fatal("cloud runtime proxy was not called")+ }+ if proxy.req.Method != http.MethodPost || proxy.req.Path != "/api/v1/nodes" {+ t.Fatalf("proxied request = %s %s", proxy.req.Method, proxy.req.Path)+ }+ if proxy.req.UserID != testUserID {+ t.Fatalf("proxied user id = %q", proxy.req.UserID)+ }+ if proxy.req.UserPAT != rawPAT {+ t.Fatalf("proxied PAT = %q", proxy.req.UserPAT)+ }+ if proxy.req.RequestID != "api-request-id" {+ t.Fatalf("proxied request id = %q", proxy.req.RequestID)+ }+ if got := w.Header().Get("X-Request-ID"); got != "fleet-request-id" {+ t.Fatalf("response request id = %q", got)+ }+}++func TestCreateCloudRuntimeNodeRejectsUnownedPAT(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusCreated,+ Body: []byte(`{"status":"launching"}`),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{+ "instance_type": "g5.xlarge",+ })+ req.Header.Set("X-User-PAT", "mul_cloud_runtime_test_missing_pat")+ w := httptest.NewRecorder()++ testHandler.CreateCloudRuntimeNode(w, req)++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if proxy.called {+ t.Fatal("cloud runtime proxy should not be called")+ }+}++func TestCreateCloudRuntimeNodeRejectsExpiredPAT(t *testing.T) {+ rawPAT := "mul_cloud_runtime_test_expired_pat"+ _, err := testHandler.Queries.CreatePersonalAccessToken(context.Background(), db.CreatePersonalAccessTokenParams{+ UserID: parseUUID(testUserID),+ Name: "cloud runtime expired test",+ TokenHash: auth.HashToken(rawPAT),+ TokenPrefix: rawPAT[:12],+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(-time.Hour), Valid: true},+ })+ if err != nil {+ t.Fatalf("create PAT: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE token_hash = $1`, auth.HashToken(rawPAT))+ })++ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusCreated,+ Body: []byte(`{"status":"launching"}`),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{+ "instance_type": "g5.xlarge",+ })+ req.Header.Set("X-User-PAT", rawPAT)+ w := httptest.NewRecorder()++ testHandler.CreateCloudRuntimeNode(w, req)++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if proxy.called {+ t.Fatal("cloud runtime proxy should not be called")+ }+}++func TestCloudRuntimeDisabledReturnsUnavailable(t *testing.T) {+ useCloudRuntimeProxy(t, &fakeCloudRuntimeProxy{enabled: false})++ req := newRequest(http.MethodGet, "/api/cloud-runtime/nodes", nil)+ w := httptest.NewRecorder()++ testHandler.ListCloudRuntimeNodes(w, req)++ if w.Code != http.StatusServiceUnavailable {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+}++func TestListCloudRuntimeNodesForwardsQuery(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusOK,+ Body: []byte(`[]`),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodGet, "/api/cloud-runtime/nodes?limit=10&offset=20", nil)+ w := httptest.NewRecorder()++ testHandler.ListCloudRuntimeNodes(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if !proxy.called {+ t.Fatal("cloud runtime proxy was not called")+ }+ if proxy.req.Method != http.MethodGet || proxy.req.Path != "/api/v1/nodes" {+ t.Fatalf("proxied request = %s %s", proxy.req.Method, proxy.req.Path)+ }+ if got := proxy.req.Query.Encode(); got != "limit=10&offset=20" {+ t.Fatalf("proxied query = %q", got)+ }+}++func TestCloudRuntimeNonJSONResponseIsWrapped(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusBadGateway,+ Body: []byte("fleet failed\n"),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodGet, "/api/cloud-runtime/healthz", nil)+ w := httptest.NewRecorder()++ testHandler.GetCloudRuntimeHealth(w, req)++ if w.Code != http.StatusBadGateway {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if ct := w.Header().Get("Content-Type"); ct != "application/json" {+ t.Fatalf("content type = %q", ct)+ }+ if got := w.Body.String(); !strings.Contains(got, `"error":"fleet failed"`) {+ t.Fatalf("body = %s", got)+ }+}++func TestCloudRuntimeEmptyResponseKeepsStatus(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusNoContent,+ Body: nil,+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodGet, "/api/cloud-runtime/healthz", nil)+ w := httptest.NewRecorder()++ testHandler.GetCloudRuntimeHealth(w, req)++ if w.Code != http.StatusNoContent {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if body := w.Body.String(); body != "" {+ t.Fatalf("body = %s", body)+ }+}++func TestCreateCloudRuntimeNodeRejectsLargeBody(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusCreated,+ Body: []byte(`{"status":"launching"}`),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ body := bytes.NewReader(bytes.Repeat([]byte("a"), maxCloudRuntimeRequestBodySize+1))+ req := httptest.NewRequest(http.MethodPost, "/api/cloud-runtime/nodes", body)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-User-ID", testUserID)+ w := httptest.NewRecorder()++ testHandler.CreateCloudRuntimeNode(w, req)++ if w.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if proxy.called {+ t.Fatal("cloud runtime proxy should not be called")+ }+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 71bba15a80..05bbc02649 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -9,6 +9,7 @@ import ("log/slog""net/http""net/netip"+ "time""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5"@@ -16,6 +17,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/middleware"@@ -87,6 +89,16 @@ type Config struct {// webhook limiter from being bypassed by a spoofed XFF on deployments// without a header-stripping reverse proxy in front.TrustedProxies []netip.Prefix+ // CloudRuntimeFleetURL enables the SaaS-only remote Fleet adapter when set.+ // Empty keeps self-hosted deployments explicit: cloud runtime endpoints+ // return 503 instead of attempting to dial a hard-coded private service.+ CloudRuntimeFleetURL string+ CloudRuntimeFleetTimeout time.Duration+}++type cloudRuntimeProxy interface {+ Enabled() bool+ Do(ctx context.Context, req cloudruntime.Request) (*cloudruntime.Response, error)}type Handler struct {@@ -113,6 +125,7 @@ type Handler struct {MembershipCache *auth.MembershipCacheWebhookRateLimiter WebhookRateLimiterWebhookIPRateLimiter WebhookRateLimiter+ CloudRuntime cloudRuntimeProxycfg Config}@@ -154,7 +167,11 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventAnalytics: analyticsClient,WebhookRateLimiter: NewMemoryWebhookRateLimiter(DefaultWebhookRateLimit()),WebhookIPRateLimiter: NewMemoryWebhookIPRateLimiter(DefaultWebhookIPRateLimit()),- cfg: cfg,+ CloudRuntime: cloudruntime.NewClient(cloudruntime.Config{+ BaseURL: cfg.CloudRuntimeFleetURL,+ Timeout: cfg.CloudRuntimeFleetTimeout,+ }),+ cfg: cfg,}}