Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: server auto-generates PAT for cloud runtime bootstrap (#3002)
LinYushene288eff2c5c7
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 8fe1c7bf65..c63db3838f 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -188,7 +188,6 @@ describe("ApiClient", () => {await client.listCloudRuntimeNodes({ limit: 20, offset: 5 });await client.createCloudRuntimeNode({ instance_type: "g5.xlarge", name: "gpu-dev-01" },- { userPAT: "mul_cloud_bootstrap_pat" },);const listCall = fetchMock.mock.calls[0]!;@@ -207,9 +206,7 @@ describe("ApiClient", () => {name: "gpu-dev-01",}),});- expect((createCall[1]!.headers as Record<string, string>)["X-User-PAT"]).toBe(- "mul_cloud_bootstrap_pat",- );+ expect((createCall[1]!.headers as Record<string, string>)["X-User-PAT"]).toBeUndefined();});it("falls back when Cloud Runtime node responses drift", async () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 49aab78b5c..ec6ac4433c 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -103,7 +103,6 @@ import type {import type { OnboardingCompletionPath } from "../onboarding/types";import type {CloudRuntimeNode,- CreateCloudRuntimeNodeOptions,CreateCloudRuntimeNodeRequest,ListCloudRuntimeNodesParams,} from "../runtimes/cloud-runtime";@@ -855,17 +854,11 @@ export class ApiClient {async createCloudRuntimeNode(data: CreateCloudRuntimeNodeRequest,- options?: CreateCloudRuntimeNodeOptions,): Promise<CloudRuntimeNode> {- const extraHeaders: Record<string, string> = {- "Content-Type": "application/json",- };- const userPAT = options?.userPAT?.trim();- if (userPAT) extraHeaders["X-User-PAT"] = userPAT;const res = await this.fetchRaw("/api/cloud-runtime/nodes", {method: "POST",body: JSON.stringify(data),- extraHeaders,+ extraHeaders: { "Content-Type": "application/json" },});const raw = await res.json() as unknown;return parseWithFallback(diff --git a/packages/core/runtimes/cloud-runtime.ts b/packages/core/runtimes/cloud-runtime.tsindex a08bf98762..7a8a1ec3ea 100644--- a/packages/core/runtimes/cloud-runtime.ts+++ b/packages/core/runtimes/cloud-runtime.ts@@ -34,10 +34,6 @@ export interface CreateCloudRuntimeNodeRequest {tags?: Record<string, string>;}-export interface CreateCloudRuntimeNodeOptions {- userPAT?: string;-}-export const cloudRuntimeKeys = {all: (wsId: string) => ["cloud-runtime", wsId] as const,nodes: (wsId: string) => [...cloudRuntimeKeys.all(wsId), "nodes"] as const,@@ -76,13 +72,8 @@ export function cloudRuntimeNodeListOptions(export function useCreateCloudRuntimeNode(wsId: string) {const qc = useQueryClient();return useMutation({- mutationFn: ({- data,- userPAT,- }: {- data: CreateCloudRuntimeNodeRequest;- userPAT?: string;- }) => api.createCloudRuntimeNode(data, { userPAT }),+ mutationFn: (data: CreateCloudRuntimeNodeRequest) =>+ api.createCloudRuntimeNode(data),onSettled: () => {qc.invalidateQueries({ queryKey: cloudRuntimeKeys.all(wsId) });},diff --git a/packages/views/runtimes/components/cloud-runtime-dialog.tsx b/packages/views/runtimes/components/cloud-runtime-dialog.tsxindex 326aa94a37..39004fb91d 100644--- a/packages/views/runtimes/components/cloud-runtime-dialog.tsx+++ b/packages/views/runtimes/components/cloud-runtime-dialog.tsx@@ -74,11 +74,9 @@ export function CloudRuntimeDialog({ onClose }: { onClose: () => void }) {try {await createNode.mutateAsync({- data: {- instance_type: instanceType,- name: valueOrUndefined(name),- disk_size_gb: diskSize,- },+ instance_type: instanceType,+ name: valueOrUndefined(name),+ disk_size_gb: diskSize,});toast.success(t(($) => $.cloud_runtime.toast_created));setName("");diff --git a/server/internal/handler/cloud_runtime.go b/server/internal/handler/cloud_runtime.goindex a01f6a4eb4..2020608cd1 100644--- a/server/internal/handler/cloud_runtime.go+++ b/server/internal/handler/cloud_runtime.go@@ -10,11 +10,13 @@ import ("net/http""net/url""strings"+ "time"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"+ db "github.com/multica-ai/multica/server/pkg/db/generated")const maxCloudRuntimeRequestBodySize = 1 << 20@@ -112,19 +114,20 @@ func (h *Handler) proxyCloudRuntime(w http.ResponseWriter, r *http.Request, meth}}- userPAT, ok := h.cloudRuntimeUserPAT(w, r, userID, opts.withUserPAT)- if !ok {- return- }-var body []byteif opts.withBody {+ var ok boolbody, ok = readCloudRuntimeJSONBody(w, r)if !ok {return}}+ userPAT, patGenerated, ok := h.cloudRuntimeUserPAT(w, r, userID, opts.withUserPAT)+ if !ok {+ return+ }+var query url.Valuesif opts.withQuery {query = r.URL.Query()@@ -140,9 +143,15 @@ func (h *Handler) proxyCloudRuntime(w http.ResponseWriter, r *http.Request, methRequestID: cloudRuntimeRequestID(r),})if err != nil {+ if patGenerated {+ h.revokeGeneratedPAT(r.Context(), userPAT)+ }writeCloudRuntimeError(w, r, err)return}+ if patGenerated && resp.StatusCode >= 300 {+ h.revokeGeneratedPAT(r.Context(), userPAT)+ }writeCloudRuntimeResponse(w, resp)}@@ -177,34 +186,69 @@ func cloudRuntimeRequestID(r *http.Request) string {return chimw.GetReqID(r.Context())}-func (h *Handler) cloudRuntimeUserPAT(w http.ResponseWriter, r *http.Request, userID string, enabled bool) (string, bool) {+func (h *Handler) cloudRuntimeUserPAT(w http.ResponseWriter, r *http.Request, userID string, enabled bool) (pat string, generated bool, ok bool) {if !enabled {- return "", true+ return "", false, true}- if pat := strings.TrimSpace(r.Header.Get("X-User-PAT")); pat != "" {- if !strings.HasPrefix(pat, "mul_") {+ if p := strings.TrimSpace(r.Header.Get("X-User-PAT")); p != "" {+ if !strings.HasPrefix(p, "mul_") {writeError(w, http.StatusBadRequest, "invalid X-User-PAT")- return "", false+ return "", false, false}if h.Queries == nil {writeError(w, http.StatusInternalServerError, "failed to validate X-User-PAT")- return "", false+ return "", false, false}- token, err := h.Queries.GetPersonalAccessTokenByHash(r.Context(), auth.HashToken(pat))+ token, err := h.Queries.GetPersonalAccessTokenByHash(r.Context(), auth.HashToken(p))if err != nil || uuidToString(token.UserID) != userID {writeError(w, http.StatusForbidden, "invalid X-User-PAT")- return "", false+ return "", false, false}- return pat, true+ return p, false, 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 strings.TrimPrefix(authHeader, prefix), false, true+ }++ // Auto-generate a PAT for cloud runtime bootstrap.+ p, err := h.generateCloudRuntimePAT(r.Context(), userID)+ if err != nil {+ slog.Error("failed to generate cloud runtime PAT", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to generate cloud runtime PAT")+ return "", false, false+ }+ return p, true, true+}++func (h *Handler) generateCloudRuntimePAT(ctx context.Context, userID string) (string, error) {+ rawToken, err := auth.GeneratePATToken()+ if err != nil {+ return "", err+ }+ prefix := rawToken[:12]+ _, err = h.Queries.CreatePersonalAccessToken(ctx, db.CreatePersonalAccessTokenParams{+ UserID: parseUUID(userID),+ Name: "Cloud Runtime (auto)",+ TokenHash: auth.HashToken(rawToken),+ TokenPrefix: prefix,+ })+ if err != nil {+ return "", err+ }+ return rawToken, nil+}++func (h *Handler) revokeGeneratedPAT(ctx context.Context, rawToken string) {+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)+ defer cancel()+ hash := auth.HashToken(rawToken)+ if _, err := h.DB.Exec(ctx, `UPDATE personal_access_token SET revoked = TRUE WHERE token_hash = $1`, hash); err != nil {+ slog.Warn("failed to revoke auto-generated cloud runtime PAT", "error", err)}- return "", true+ h.PATCache.Invalidate(ctx, hash)}func writeCloudRuntimeResponse(w http.ResponseWriter, resp *cloudruntime.Response) {diff --git a/server/internal/handler/cloud_runtime_test.go b/server/internal/handler/cloud_runtime_test.goindex 63741977da..8a80c242c0 100644--- a/server/internal/handler/cloud_runtime_test.go+++ b/server/internal/handler/cloud_runtime_test.go@@ -169,6 +169,38 @@ func TestCreateCloudRuntimeNodeRejectsExpiredPAT(t *testing.T) {}}+func TestCreateCloudRuntimeNodeAutoGeneratesPAT(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusCreated,+ Header: http.Header{},+ Body: []byte(`{"status":"launching"}`),+ },+ }+ useCloudRuntimeProxy(t, proxy)++ req := newRequest(http.MethodPost, "/api/cloud-runtime/nodes", map[string]any{+ "instance_type": "g5.xlarge",+ })+ // No X-User-PAT header set — should auto-generate.+ 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 !strings.HasPrefix(proxy.req.UserPAT, "mul_") {+ t.Fatalf("expected auto-generated PAT with mul_ prefix, got %q", proxy.req.UserPAT)+ }+ // Clean up the auto-generated PAT.+ _, _ = testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE token_hash = $1`, auth.HashToken(proxy.req.UserPAT))+}+func TestCloudRuntimeDisabledReturnsUnavailable(t *testing.T) {useCloudRuntimeProxy(t, &fakeCloudRuntimeProxy{enabled: false})