Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(auth): block machine credentials from minting long-lived tokens (MUL-8154) (#9421)
Multica Eveda278c7d42a7
diff --git a/server/cmd/server/credential_mint_actor_integration_test.go b/server/cmd/server/credential_mint_actor_integration_test.gonew file mode 100644index 0000000000..d2a643d77b--- /dev/null+++ b/server/cmd/server/credential_mint_actor_integration_test.go@@ -0,0 +1,134 @@+package main++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/auth"+)++// TestCredentialRoutesRejectTaskToken exercises the real Auth -> router ->+// handler chain for MUL-8154: an agent's mat_ task token authenticates as the+// runtime owner, and must not be able to mint a session JWT or manage the+// owner's PATs. The client also forges X-Actor-Source to prove Auth's+// server-set stamp wins.+func TestCredentialRoutesRejectTaskToken(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()++ var agentID string+ if err := testPool.QueryRow(ctx, `+ SELECT id::text FROM agent WHERE workspace_id = $1 ORDER BY created_at LIMIT 1+ `, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load integration-test agent: %v", err)+ }+ taskID := ensureAgentTask(t, agentID)+ matToken := mintAgentTaskToken(t, agentID, taskID, testUserID)++ // A human PAT for the same user, so the revoke route has a real target+ // and we can assert it survives the rejected request.+ humanPAT, err := auth.GeneratePATToken()+ if err != nil {+ t.Fatalf("generate pat: %v", err)+ }+ var patID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO personal_access_token (user_id, name, token_hash, token_prefix)+ VALUES ($1, 'mul-8154-target', $2, $3) RETURNING id::text+ `, testUserID, auth.HashToken(humanPAT), humanPAT[:12]).Scan(&patID); err != nil {+ t.Fatalf("insert pat: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE user_id = $1 AND name IN ('mul-8154-target', 'mul-8154-escalation', 'mul-8154-human')`, testUserID)+ })++ countPATs := func() int {+ var n int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM personal_access_token WHERE user_id = $1 AND NOT revoked`, testUserID).Scan(&n); err != nil {+ t.Fatalf("count pats: %v", err)+ }+ return n+ }++ do := func(t *testing.T, method, path, bearer string, body any) *http.Response {+ t.Helper()+ var buf bytes.Buffer+ if body != nil {+ if err := json.NewEncoder(&buf).Encode(body); err != nil {+ t.Fatalf("encode body: %v", err)+ }+ }+ req, err := http.NewRequest(method, testServer.URL+path, &buf)+ if err != nil {+ t.Fatalf("create request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+bearer)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("X-Actor-Source", "member")+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("perform request: %v", err)+ }+ return resp+ }++ before := countPATs()+ for _, tc := range []struct {+ name string+ method string+ path string+ body any+ }{+ {name: "cli-token", method: http.MethodPost, path: "/api/cli-token"},+ {name: "create pat", method: http.MethodPost, path: "/api/tokens", body: map[string]any{"name": "mul-8154-escalation"}},+ {name: "list pats", method: http.MethodGet, path: "/api/tokens"},+ {name: "revoke pat", method: http.MethodDelete, path: "/api/tokens/" + patID},+ {name: "renew current", method: http.MethodPost, path: "/api/tokens/current/renew"},+ } {+ t.Run("mat_ "+tc.name, func(t *testing.T) {+ resp := do(t, tc.method, tc.path, matToken, tc.body)+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusForbidden {+ t.Fatalf("status = %d, want 403", resp.StatusCode)+ }+ })+ }+ if after := countPATs(); after != before {+ t.Fatalf("active PAT count changed %d -> %d; rejected requests must have no side effect", before, after)+ }++ // Human credentials keep working through the same chain.+ t.Run("jwt cli-token", func(t *testing.T) {+ resp := do(t, http.MethodPost, "/api/cli-token", testToken, nil)+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("status = %d, want 200", resp.StatusCode)+ }+ })+ t.Run("jwt create pat", func(t *testing.T) {+ resp := do(t, http.MethodPost, "/api/tokens", testToken, map[string]any{"name": "mul-8154-human"})+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusCreated {+ t.Fatalf("status = %d, want 201", resp.StatusCode)+ }+ })+ t.Run("mul_ list pats", func(t *testing.T) {+ resp := do(t, http.MethodGet, "/api/tokens", humanPAT, nil)+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("status = %d, want 200", resp.StatusCode)+ }+ })+ t.Run("mul_ renew current", func(t *testing.T) {+ resp := do(t, http.MethodPost, "/api/tokens/current/renew", humanPAT, nil)+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("status = %d, want 200", resp.StatusCode)+ }+ })+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 812103a599..2a6ce4128e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1662,7 +1662,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Patch("/api/me/onboarding", h.PatchOnboarding)r.Post("/api/me/onboarding/complete", h.CompleteOnboarding)r.Post("/api/me/onboarding/cloud-waitlist", h.JoinCloudWaitlist)- r.Post("/api/cli-token", h.IssueCliToken)+ // Credential minting is human-only (MUL-8154): an agent task token+ // (mat_) or cloud-node PAT (mcn_) authenticates as its owner, so+ // without this guard a prompt-injected agent could trade its scoped,+ // short-lived credential for a 30-day session JWT.+ r.With(handler.RequireHumanActor).Post("/api/cli-token", h.IssueCliToken)// Sliding session renewal for clients that hold the session as a// string (Desktop, mobile). Browsers get theirs re-issued inline by// middleware.Auth and never call this (MUL-7436).@@ -1925,7 +1929,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Post("/api/invitations/{id}/decline", h.DeclineInvitation)r.Post("/api/share-links/join", h.JoinByShareLink)+ // PAT management is human-only (MUL-8154): a machine credential must+ // not mint a non-expiring PAT, enumerate the owner's PATs, or revoke+ // them. /current/renew already accepts only mul_ PATs, which are human+ // credentials, so the group-wide guard does not change its behavior.r.Route("/api/tokens", func(r chi.Router) {+ r.Use(handler.RequireHumanActor)r.Get("/", h.ListPersonalAccessTokens)r.Post("/", h.CreatePersonalAccessToken)r.Post("/current/renew", h.RenewCurrentPersonalAccessToken)diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.goindex 389281cff4..08ff8c20a3 100644--- a/server/internal/handler/auth.go+++ b/server/internal/handler/auth.go@@ -745,7 +745,15 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {// IssueCliToken returns a fresh JWT for the authenticated user.// This allows cookie-authenticated browser sessions to obtain a bearer token// that can be handed off to the CLI via the cli_callback redirect.+//+// Machine credentials (mat_ task tokens, mcn_ cloud-node PATs) are refused+// here as well as at the router (MUL-8154), so a route refactor cannot turn+// a scoped agent credential into a long-lived session.func (h *Handler) IssueCliToken(w http.ResponseWriter, r *http.Request) {+ if isMachineCredentialActor(r) {+ writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")+ return+ }userID, ok := requireUserID(w, r)if !ok {returndiff --git a/server/internal/handler/credential_mint_guard_test.go b/server/internal/handler/credential_mint_guard_test.gonew file mode 100644index 0000000000..b4a5fba68a--- /dev/null+++ b/server/internal/handler/credential_mint_guard_test.go@@ -0,0 +1,81 @@+package handler++import (+ "bytes"+ "context"+ "net/http"+ "net/http/httptest"+ "testing"+)++// TestCredentialMintHandlers_RejectMachineCredentials pins the handler-level+// backstop for MUL-8154: even if a route refactor drops RequireHumanActor,+// IssueCliToken and CreatePersonalAccessToken must refuse machine actors and+// must not write a PAT row.+func TestCredentialMintHandlers_RejectMachineCredentials(t *testing.T) {+ if testHandler == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ countPATs := func() int {+ var n int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM personal_access_token WHERE user_id = $1`, parseUUID(testUserID)).Scan(&n); err != nil {+ t.Fatalf("count pats: %v", err)+ }+ return n+ }++ for _, source := range []string{"task_token", "cloud_pat"} {+ t.Run(source, func(t *testing.T) {+ before := countPATs()++ req := newRequest("POST", "/api/tokens", map[string]any{"name": "escalation"})+ req.Header.Set("X-Actor-Source", source)+ w := httptest.NewRecorder()+ testHandler.CreatePersonalAccessToken(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("CreatePersonalAccessToken status = %d, want 403 (body: %s)", w.Code, w.Body.String())+ }+ if after := countPATs(); after != before {+ t.Fatalf("PAT rows changed %d -> %d; rejected request must have no side effect", before, after)+ }++ req = newRequest("POST", "/api/cli-token", nil)+ req.Header.Set("X-Actor-Source", source)+ w = httptest.NewRecorder()+ testHandler.IssueCliToken(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("IssueCliToken status = %d, want 403 (body: %s)", w.Code, w.Body.String())+ }+ if bytes.Contains(w.Body.Bytes(), []byte(`"token"`)) {+ t.Fatalf("IssueCliToken leaked a token on rejection: %s", w.Body.String())+ }+ })+ }+}++// TestCredentialMintHandlers_AllowHumanActors guards against the backstop+// over-blocking: a request with no machine actor source (JWT / mul_ PAT)+// still mints credentials.+func TestCredentialMintHandlers_AllowHumanActors(t *testing.T) {+ if testHandler == nil {+ t.Skip("no database connection")+ }++ req := newRequest("POST", "/api/tokens", map[string]any{"name": "human-pat"})+ w := httptest.NewRecorder()+ testHandler.CreatePersonalAccessToken(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreatePersonalAccessToken status = %d, want 201 (body: %s)", w.Code, w.Body.String())+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM personal_access_token WHERE user_id = $1 AND name = 'human-pat'`, parseUUID(testUserID))+ })++ req = newRequest("POST", "/api/cli-token", nil)+ w = httptest.NewRecorder()+ testHandler.IssueCliToken(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("IssueCliToken status = %d, want 200 (body: %s)", w.Code, w.Body.String())+ }+}diff --git a/server/internal/handler/personal_access_token.go b/server/internal/handler/personal_access_token.goindex 8bc9c5a82f..61ac5f0c79 100644--- a/server/internal/handler/personal_access_token.go+++ b/server/internal/handler/personal_access_token.go@@ -57,7 +57,15 @@ type CreatePATRequest struct {ExpiresInDays *int `json:"expires_in_days"`}+// CreatePersonalAccessToken mints a PAT for the caller. Machine credentials+// are refused here as a backstop to the router guard (MUL-8154): a PAT may be+// non-expiring, so minting one from an agent task token would escalate a+// 24-hour scoped credential into permanent account access.func (h *Handler) CreatePersonalAccessToken(w http.ResponseWriter, r *http.Request) {+ if isMachineCredentialActor(r) {+ writeError(w, http.StatusForbidden, "this endpoint is only available to human actors")+ return+ }userID, ok := requireUserID(w, r)if !ok {return