Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(quick-actions): scope private actions to the human a task represents (MUL-10007) (#11336)
Jiayuan Zhange933d3dfc0eb
diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.goindex 9d29d50f93..91384dceb8 100644--- a/server/internal/handler/agent_access.go+++ b/server/internal/handler/agent_access.go@@ -2,9 +2,11 @@ package handlerimport ("context"+ "errors""log/slog""net/http"+ "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/projectaccess""github.com/multica-ai/multica/server/internal/util"@@ -245,6 +247,51 @@ func (h *Handler) invokeOriginatorFromRequest(r *http.Request, actorType, actorIreturn ""}+// requestRepresentsUser reports whether a request may reach data private to+// userID. Human credentials (JWT, mul_ PAT) carry no X-Actor-Source and always+// do. A task token carries its runtime owner's user id whoever triggered the+// run, so it qualifies only for a live task that this same user started, on a+// runtime they still own. A cloud-node PAT has no task binding or human trigger+// and never qualifies.+//+// A missing task or runtime is a plain (false, nil); any other lookup error is+// returned so the caller can tell an outage from a denial.+func (h *Handler) requestRepresentsUser(r *http.Request, userID string, workspaceID pgtype.UUID) (bool, error) {+ switch r.Header.Get("X-Actor-Source") {+ case "":+ return true, nil+ case "task_token":+ default:+ return false, nil+ }+ notFound := func(err error) (bool, error) {+ if errors.Is(err, pgx.ErrNoRows) {+ return false, nil+ }+ return false, err+ }+ taskID, err := util.ParseUUID(r.Header.Get("X-Task-ID"))+ if err != nil {+ return false, nil+ }+ task, err := h.Queries.GetAgentTask(r.Context(), taskID)+ if err != nil {+ return notFound(err)+ }+ if isTerminalTaskStatus(task.Status) ||+ !task.OriginatorUserID.Valid || uuidToString(task.OriginatorUserID) != userID ||+ uuidToString(task.AgentID) != r.Header.Get("X-Agent-ID") {+ return false, nil+ }+ runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{+ ID: task.RuntimeID, WorkspaceID: workspaceID,+ })+ if err != nil {+ return notFound(err)+ }+ return runtime.OwnerID.Valid && uuidToString(runtime.OwnerID) == userID, nil+}+// isTerminalTaskStatus reports whether a task has finished, in any of the three// ways it can. Mirrors the agent_task_queue status CHECK constraint; a status the// constraint does not know is treated as NOT terminal so an added in-flight statediff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex e8be1cc461..cca83f0c07 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -3,17 +3,14 @@ package handlerimport ("context""encoding/json"- "errors""log/slog""net/http""strconv""github.com/go-chi/chi/v5"- "github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/inbox""github.com/multica-ai/multica/server/internal/logger"- "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -274,47 +271,15 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {// that same human upstream; every inbox endpoint goes through this gate. Auth// strips client identity headers and stamps the task/agent from the token.func (h *Handler) requireInboxOwnerAccess(w http.ResponseWriter, r *http.Request, userID string, workspaceID pgtype.UUID) bool {- source := r.Header.Get("X-Actor-Source")- if source == "" {- return true- }- deny := func() bool {- writeError(w, http.StatusForbidden, "inbox access requires the runtime owner's verified human trigger")- return false- }- queryFailure := func(err error) bool {- if errors.Is(err, pgx.ErrNoRows) {- return deny()- }+ ok, err := h.requestRepresentsUser(r, userID, workspaceID)+ if err != nil {slog.Warn("resolve inbox access failed", append(logger.RequestAttrs(r), "error", err)...)writeInboxReadError(w, err, "failed to resolve inbox access")return false}- // A cloud-node PAT has no authenticated task binding or human trigger.- if source != "task_token" {- return deny()- }- taskID, err := util.ParseUUID(r.Header.Get("X-Task-ID"))- if err != nil {- return deny()- }- task, err := h.Queries.GetAgentTask(r.Context(), taskID)- if err != nil {- return queryFailure(err)- }- if isTerminalTaskStatus(task.Status) ||- !task.OriginatorUserID.Valid || uuidToString(task.OriginatorUserID) != userID ||- uuidToString(task.AgentID) != r.Header.Get("X-Agent-ID") {- return deny()- }- runtime, err := h.Queries.GetAgentRuntimeForWorkspace(r.Context(), db.GetAgentRuntimeForWorkspaceParams{- ID: task.RuntimeID, WorkspaceID: workspaceID,- })- if err != nil {- return queryFailure(err)- }- if !runtime.OwnerID.Valid || uuidToString(runtime.OwnerID) != userID {- return deny()+ if !ok {+ writeError(w, http.StatusForbidden, "inbox access requires the runtime owner's verified human trigger")+ return false}return true}diff --git a/server/internal/handler/quick_action.go b/server/internal/handler/quick_action.goindex 8ac26fb7da..b96bf7fb61 100644--- a/server/internal/handler/quick_action.go+++ b/server/internal/handler/quick_action.go@@ -13,6 +13,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid""github.com/multica-ai/multica/server/pkg/protocol"@@ -446,13 +447,36 @@ func (h *Handler) loadReachableQuickAction(writeError(w, http.StatusNotFound, "quick action not found")return db.QuickAction{}, false}- if qa.Visibility == "private" && uuidToString(qa.CreatedByID) != userID {- writeError(w, http.StatusNotFound, "quick action not found")- return db.QuickAction{}, false+ if qa.Visibility == "private" {+ viewer := h.quickActionViewer(r, userID, workspaceID)+ if !viewer.Valid || viewer != qa.CreatedByID {+ writeError(w, http.StatusNotFound, "quick action not found")+ return db.QuickAction{}, false+ }}return qa, true}+// quickActionViewer is the member whose private quick actions this request may+// reach. A task token's user id is the runtime owner, not whoever started the+// run, so a run another member started gets an invalid UUID: it matches no+// creator and leaves only public actions. Lookup failures fail closed the same+// way.+func (h *Handler) quickActionViewer(r *http.Request, userID string, workspaceID pgtype.UUID) pgtype.UUID {+ ok, err := h.requestRepresentsUser(r, userID, workspaceID)+ if err != nil {+ slog.Warn("resolve quick action viewer failed", append(logger.RequestAttrs(r), "error", err)...)+ }+ if !ok {+ return pgtype.UUID{}+ }+ viewer, err := util.ParseUUID(userID)+ if err != nil {+ return pgtype.UUID{}+ }+ return viewer+}+// requirePublicQuickActionRole gates writes that leave an action `public`.// Returns false having already written the error response.func (h *Handler) requirePublicQuickActionRole(w http.ResponseWriter, r *http.Request, workspaceID string) bool {@@ -465,7 +489,9 @@ func (h *Handler) requirePublicQuickActionRole(w http.ResponseWriter, r *http.Re// ListQuickActions returns the workspace catalog. It performs NO permission// work: `private` rows are scoped to their creator by the query (that is what// the field means, not a permission check), and every other row is returned to-// everyone. Whether the caller may RUN one is answered by RunQuickAction.+// everyone. Whether the caller may RUN one is answered by RunQuickAction. The+// creator is matched against quickActionViewer, never the raw user id, because+// a task token's user id is its runtime owner.func (h *Handler) ListQuickActions(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")@@ -476,8 +502,7 @@ func (h *Handler) ListQuickActions(w http.ResponseWriter, r *http.Request) {if !ok {return}- viewerUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")- if !ok {+ if _, ok := parseUUIDOrBadRequest(w, userID, "user id"); !ok {return}@@ -485,7 +510,7 @@ func (h *Handler) ListQuickActions(w http.ResponseWriter, r *http.Request) {rows, err := h.Queries.ListQuickActions(r.Context(), db.ListQuickActionsParams{WorkspaceID: wsUUID,IncludeArchived: includeArchived,- ViewerID: viewerUUID,+ ViewerID: h.quickActionViewer(r, userID, wsUUID),})if err != nil {slog.Warn("list quick actions failed", append(logger.RequestAttrs(r), "error", err)...)diff --git a/server/internal/handler/quick_action_task_access_test.go b/server/internal/handler/quick_action_task_access_test.gonew file mode 100644index 0000000000..8393fa923b--- /dev/null+++ b/server/internal/handler/quick_action_task_access_test.go@@ -0,0 +1,146 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// A task token's user id is its runtime owner, whoever started the run. Private+// quick actions belong to their creator, so a run another member started on+// the owner's runtime must see, preview, and run only public actions.+func TestQuickActionTaskTokenPrivateAccess(t *testing.T) {+ other := createPlainMember(t, "qa-originator-"+uuid.NewString()+"@example.test")+ const secret = "runtime owner's private prompt"+ privateID := dbfx.Insert(t, "quick_action", testutil.Cols{+ "workspace_id": testWorkspaceID, "name": "Owner private", "description": "",+ "assignee_type": "", "prompt": secret, "visibility": "private",+ "created_by_type": "member", "created_by_id": testUserID,+ })+ publicID := dbfx.Insert(t, "quick_action", testutil.Cols{+ "workspace_id": testWorkspaceID, "name": "Shared public", "description": "",+ "assignee_type": "", "prompt": "shared prompt", "visibility": "public",+ "created_by_type": "member", "created_by_id": testUserID,+ })+ issueID := dbfx.Issue(t, "Quick action task access", nil)+ dbfx.Cleanup(t, `DELETE FROM comment WHERE issue_id = $1`, issueID)++ serve := func(handler func(*Handler, http.ResponseWriter, *http.Request)) http.HandlerFunc {+ return middleware.Auth(testHandler.Queries, nil, nil, nil)(+ middleware.RequireWorkspaceMember(testHandler.Queries)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler(testHandler, w, r)+ })),+ ).ServeHTTP+ }+ request := func(token, method, path string, params ...string) *http.Request {+ req := testutil.WithHeaders(testutil.JSONRequest(method, path, nil),+ "Authorization", "Bearer "+token, "X-Workspace-ID", testWorkspaceID)+ if len(params) > 0 {+ req = testutil.WithURLParams(req, params...)+ }+ return req+ }+ listIDs := func(t *testing.T, token string) map[string]bool {+ t.Helper()+ var resp ListQuickActionsResponse+ testutil.Call(t, serve((*Handler).ListQuickActions), request(token, http.MethodGet, "/api/quick-actions")).+ Want(http.StatusOK).JSON(&resp)+ ids := map[string]bool{}+ for _, qa := range resp.QuickActions {+ ids[qa.ID] = true+ }+ return ids+ }+ actionPath := func(id, suffix string) string {+ return "/api/issues/" + issueID + "/quick-actions/" + id + suffix+ }+ render := func(t *testing.T, token, id string) *testutil.Response {+ t.Helper()+ return testutil.Call(t, serve((*Handler).RenderQuickAction),+ request(token, http.MethodPost, actionPath(id, "/render"), "id", issueID, "quickActionId", id))+ }+ run := func(t *testing.T, token, id string) *testutil.Response {+ t.Helper()+ return testutil.Call(t, serve((*Handler).RunQuickAction),+ request(token, http.MethodPost, actionPath(id, "/run"), "id", issueID, "quickActionId", id))+ }+ secretComments := func(t *testing.T) int {+ t.Helper()+ var n int+ dbfx.QueryRow(t, `SELECT count(*) FROM comment WHERE issue_id = $1 AND quick_action_id = $2`, issueID, privateID).Scan(&n)+ return n+ }++ for _, tc := range []struct {+ name string+ originator any+ status string+ private bool+ }{+ {"runtime owner started the run", testUserID, "running", true},+ {"another member started the run", other, "running", false},+ {"no human started the run", nil, "running", false},+ {"finished run with a lingering token", testUserID, "completed", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "Quick action runtime")+ agentID := dbfx.Agent(t, "Quick action agent", runtimeID)+ accountable := tc.originator+ if accountable == nil {+ accountable = testUserID+ }+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID, "issue_id": issueID, "status": tc.status,+ "originator_user_id": tc.originator, "accountable_user_id": accountable,+ })+ token := inboxTaskCredential(t, taskID, agentID, testWorkspaceID, testUserID)++ ids := listIDs(t, token)+ if !ids[publicID] {+ t.Fatal("public action missing from the list")+ }+ if ids[privateID] != tc.private {+ t.Fatalf("private action listed = %v, want %v", ids[privateID], tc.private)+ }++ render(t, token, publicID).Want(http.StatusOK)+ before := secretComments(t)+ if !tc.private {+ render(t, token, privateID).Want(http.StatusNotFound)+ run(t, token, privateID).Want(http.StatusNotFound)+ if got := secretComments(t); got != before {+ t.Fatalf("refused run still posted the private prompt: %d comments, want %d", got, before)+ }+ return+ }+ var preview struct {+ Content string `json:"content"`+ }+ render(t, token, privateID).Want(http.StatusOK).JSON(&preview)+ if preview.Content != secret {+ t.Fatalf("preview = %q, want the owner's prompt", preview.Content)+ }+ run(t, token, privateID).Want(http.StatusCreated)+ if got := secretComments(t); got != before+1 {+ t.Fatalf("run posted %d comments, want %d", got, before+1)+ }+ })+ }++ // A human credential still reaches the creator's own private action.+ t.Run("human session", func(t *testing.T) {+ var resp ListQuickActionsResponse+ testutil.Call(t, testHandler.ListQuickActions, newRequest(http.MethodGet, "/api/quick-actions", nil)).+ Want(http.StatusOK).JSON(&resp)+ found := false+ for _, qa := range resp.QuickActions {+ found = found || qa.ID == privateID+ }+ if !found {+ t.Fatal("creator lost access to their own private action")+ }+ })+}