Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(autopilots): keep autopilots on a private project inside it (#10320)
pseudoyu6ccbdd178ac7
diff --git a/server/cmd/server/private_project_realtime.go b/server/cmd/server/private_project_realtime.goindex 89936631fa..eaf90123f0 100644--- a/server/cmd/server/private_project_realtime.go+++ b/server/cmd/server/private_project_realtime.go@@ -39,6 +39,7 @@ type audienceQuerier interface {GetIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)GetCommentIssueProjectID(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)+ GetAutopilot(ctx context.Context, id pgtype.UUID) (db.Autopilot, error)projectaccess.TaskQuerier}@@ -217,7 +218,7 @@ func (a *dbPrivateProjectAudience) workspace(ctx context.Context, workspaceID st// eventProjectIDs resolves the projects an event is about, or none. It reads// the payload's own references first and only falls back to the database for-// a bare issue, comment or task id.+// a bare issue, comment, autopilot or task id.func (a *dbPrivateProjectAudience) eventProjectIDs(ctx context.Context, e events.Event) ([]string, error) {refs := extractEventRefs(e.Type, e.Payload)if refs.projectKnown {@@ -243,6 +244,12 @@ func (a *dbPrivateProjectAudience) eventProjectIDs(ctx context.Context, e eventsif refs.commentID != "" {return lookup(refs.commentID, a.q.GetCommentIssueProjectID)}+ if refs.autopilotID != "" {+ return lookup(refs.autopilotID, func(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {+ ap, err := a.q.GetAutopilot(ctx, id)+ return ap.ProjectID, err+ })+ }if e.TaskID != "" && e.ChatSessionID == "" {return a.taskProjectIDs(ctx, e)}@@ -314,6 +321,7 @@ type eventRefs struct {projectID stringissueID stringcommentID string+ autopilotID string}// extractEventRefs reads project / issue / comment references from an event@@ -361,6 +369,17 @@ func extractEventRefs(eventType string, payload any) eventRefs {if id, ok := str(top, "project_id"); ok && id != "" && (isProjectEvent || eventType == protocol.EventProjectMembersChanged) {return eventRefs{projectKnown: true, projectID: id}}+ // An autopilot bound to a private project carries its prompt and runs.+ if strings.HasPrefix(eventType, "autopilot:") {+ if ap := object("autopilot"); ap != nil {+ if pid, ok := str(ap, "project_id"); ok {+ return eventRefs{projectKnown: true, projectID: pid}+ }+ }+ if id, ok := str(top, "autopilot_id"); ok && id != "" {+ return eventRefs{autopilotID: id}+ }+ }if issue := object("issue"); issue != nil {if pid, ok := str(issue, "project_id"); ok {return eventRefs{projectKnown: true, projectID: pid}diff --git a/server/cmd/server/private_project_realtime_test.go b/server/cmd/server/private_project_realtime_test.goindex 214f53b9cd..0f1f2df93d 100644--- a/server/cmd/server/private_project_realtime_test.go+++ b/server/cmd/server/private_project_realtime_test.go@@ -98,6 +98,13 @@ func (fakeAudienceQuerier) GetAgentTask(_ context.Context, id pgtype.UUID) (db.Areturn db.AgentTaskQueue{}, pgx.ErrNoRows}+func (fakeAudienceQuerier) GetAutopilot(_ context.Context, id pgtype.UUID) (db.Autopilot, error) {+ if util.UUIDToString(id) == ppAutopilot {+ return db.Autopilot{ID: id, ProjectID: ppUUID(ppPrivate)}, nil+ }+ return db.Autopilot{}, pgx.ErrNoRows+}+func (f fakeAudienceQuerier) ListIssueProjectIDs(ctx context.Context, ids []pgtype.UUID) ([]db.ListIssueProjectIDsRow, error) {var rows []db.ListIssueProjectIDsRowfor _, id := range ids {@@ -145,6 +152,11 @@ func TestRegisterListeners_PrivateProjectEventsReachOnlyItsAudience(t *testing.T{Type: protocol.EventProjectUpdated, Payload: map[string]any{"project": map[string]any{"id": ppPrivate}}},{Type: protocol.EventProjectMembersChanged, Payload: map[string]any{"project_id": ppPrivate}},{Type: protocol.EventTaskMessage, TaskID: ppSecretTask, Payload: map[string]any{"task_id": ppSecretTask}},+ // Autopilots bound to the project, by payload object and by bare id.+ {Type: protocol.EventAutopilotCreated, Payload: map[string]any{"autopilot": map[string]any{"id": ppAutopilot, "project_id": ppPrivate}}},+ {Type: protocol.EventAutopilotUpdated, Payload: map[string]any{"autopilot_id": ppAutopilot}},+ {Type: protocol.EventAutopilotRunStart, Payload: map[string]any{"autopilot_id": ppAutopilot, "run_id": "r"}},+ {Type: protocol.EventAutopilotRunDone, Payload: map[string]any{"autopilot_id": ppAutopilot, "run_id": "r"}},// Issue-less runs read the project too: a run-only autopilot and a// quick-create into it.{Type: protocol.EventTaskMessage, TaskID: ppAutopilotTask, Payload: map[string]any{"task_id": ppAutopilotTask}},@@ -171,6 +183,8 @@ func TestRegisterListeners_PrivateProjectEventsReachOnlyItsAudience(t *testing.T// A deleted issue cannot be resolved: keep fanout, never go silent.{Type: protocol.EventIssueDeleted, Payload: map[string]any{"issue_id": "00000000-0000-0000-0000-00000000dead"}},{Type: protocol.EventAgentStatus, Payload: map[string]any{"agent_id": "a"}},+ {Type: protocol.EventAutopilotUpdated, Payload: map[string]any{"autopilot": map[string]any{"id": "x", "project_id": nil}}},+ {Type: protocol.EventAutopilotDeleted, Payload: map[string]any{"autopilot_id": "00000000-0000-0000-0000-00000000dead"}},}for _, e := range public {bus := events.New()diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 59107f7d1e..ad2a25b439 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -452,6 +452,21 @@ func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list autopilots")return}+ // Autopilots on private projects the caller cannot see are left out+ // (MUL-8472), as loadAutopilotInWorkspace answers them like missing ones.+ hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ if !ok {+ return+ }+ if !hidden.Empty() {+ visible := autopilots[:0:0]+ for _, row := range autopilots {+ if hidden.CanSeeProject(row.Autopilot.ProjectID) {+ visible = append(visible, row)+ }+ }+ autopilots = visible+ }// Resolve the acting caller's write access for per-row can_write. The// collaborator grants are fetched once as a set (keyed by autopilot id) so the@@ -611,6 +626,12 @@ func (h *Handler) loadAutopilotInWorkspace(w http.ResponseWriter, r *http.RequeswriteError(w, http.StatusNotFound, "autopilot not found")return db.Autopilot{}, false}+ // An autopilot on a private project (MUL-8472) is part of that project:+ // its prompt, runs and triggers answer like a missing autopilot to anyone+ // who cannot see the project.+ if !h.requireProjectVisible(w, r, workspaceID, autopilot.ProjectID, http.StatusNotFound, "autopilot not found") {+ return db.Autopilot{}, false+ }return autopilot, true}@@ -1362,6 +1383,9 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "autopilot not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, ap.ProjectID, http.StatusNotFound, "autopilot not found") {+ return+ }actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)if !ok {return@@ -2076,6 +2100,9 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusNotFound, "autopilot not found")return}+ if !h.requireProjectVisible(w, r, workspaceID, ap.ProjectID, http.StatusNotFound, "autopilot not found") {+ return+ }actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)if !ok {returndiff --git a/server/internal/handler/private_project_autopilot_test.go b/server/internal/handler/private_project_autopilot_test.gonew file mode 100644index 0000000000..2781ca3402--- /dev/null+++ b/server/internal/handler/private_project_autopilot_test.go@@ -0,0 +1,85 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++// An autopilot bound to a private project is part of it: its title, prompt,+// triggers and runs answer like a missing autopilot to members outside the+// project, and it is left out of their list.+func TestPrivateProjectAutopilotsHiddenFromOutsiders(t *testing.T) {+ f := newPrivateProjectFixture(t)+ var agentID string+ if err := testPool.QueryRow(context.Background(),+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = 'Handler Test Agent'`, testWorkspaceID,+ ).Scan(&agentID); err != nil {+ t.Fatalf("load seeded agent: %v", err)+ }+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": f.marker + " secret autopilot",+ "description": f.marker + " secret prompt",+ "assignee_id": agentID,+ "execution_mode": "run_only",+ "project_id": f.projectID,+ "created_by_type": "member",+ "created_by_id": f.insider,+ })+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{+ "autopilot_id": autopilotID,+ "source": "manual",+ "status": "completed",+ "result": testutil.Raw(`'{"output":"secret result"}'::jsonb`),+ })++ call := func(userID string, h http.HandlerFunc, path string, params map[string]string) *httptest.ResponseRecorder {+ req := asUser(newRequest(http.MethodGet, path, nil), userID)+ var kv []string+ for k, v := range params {+ kv = append(kv, k, v)+ }+ req = withURLParams(req, kv...)+ rec := httptest.NewRecorder()+ h(rec, req)+ return rec+ }+ for _, tc := range []struct {+ name string+ userID string+ want int+ }{+ {"workspace member outside the project", f.outsider, http.StatusNotFound},+ {"project member", f.insider, http.StatusOK},+ {"workspace owner outside the member list", testUserID, http.StatusOK},+ } {+ list := call(tc.userID, testHandler.ListAutopilots, "/api/autopilots", nil)+ listed := strings.Contains(list.Body.String(), autopilotID)+ if list.Code != http.StatusOK || listed != (tc.want == http.StatusOK) {+ t.Errorf("%s: list = %d, autopilot listed %v", tc.name, list.Code, listed)+ }+ for _, r := range []struct {+ route string+ h http.HandlerFunc+ path string+ p map[string]string+ }{+ {"detail", testHandler.GetAutopilot, "/api/autopilots/" + autopilotID, map[string]string{"id": autopilotID}},+ {"runs", testHandler.ListAutopilotRuns, "/api/autopilots/" + autopilotID + "/runs", map[string]string{"id": autopilotID}},+ {"run", testHandler.GetAutopilotRun, "/api/autopilots/" + autopilotID + "/runs/" + runID, map[string]string{"id": autopilotID, "runId": runID}},+ } {+ rec := call(tc.userID, r.h, r.path, r.p)+ if rec.Code != tc.want {+ t.Errorf("%s: %s = %d, want %d", tc.name, r.route, rec.Code, tc.want)+ }+ if tc.want == http.StatusNotFound && strings.Contains(rec.Body.String(), f.marker) {+ t.Errorf("%s: %s names the private autopilot: %s", tc.name, r.route, rec.Body.String())+ }+ }+ }+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 4105df60a0..1cb8dc1436 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -616,6 +616,14 @@ func (s *AutopilotService) dispatchAutopilotRun(run *db.AutopilotRun,actorUserID pgtype.UUID,) (*db.AutopilotRun, dispatch.ReasonCode, error) {+ if err := s.guardAutopilotProjectAccess(ctx, autopilot, run, actorUserID); err != nil {+ if skipped, code := s.handleDispatchSkip(ctx, autopilot, run, err); skipped != nil {+ return skipped, code, nil+ }+ s.failRun(ctx, run.ID, err.Error())+ s.captureAutopilotRunFailed(autopilot, *run, source, err.Error())+ return run, dispatch.ReasonInternalError, fmt.Errorf("check project access: %w", err)+ }switch autopilot.ExecutionMode {case "create_issue":triggerTimezone := s.resolveAutopilotTriggerTimezone(ctx, triggerID)@@ -670,6 +678,44 @@ func (s *AutopilotService) dispatchAutopilotRun(return run, "", nil}+// guardAutopilotProjectAccess skips a run whose autopilot is bound to a+// private project (MUL-8472) that the run's human or the executing agent's+// owner cannot see. It runs before any side effect, so neither mode writes an+// issue into the project or hands its context to a run: create_issue used to+// file the issue and only then have the enqueue refuse, and run_only had no+// check at all. The human is the one the run will act for: the member who+// clicked "run now", else the trigger's owner, else the agent's owner, the+// same order the run's attribution falls back through.+func (s *AutopilotService) guardAutopilotProjectAccess(ctx context.Context, ap db.Autopilot, run *db.AutopilotRun, actorUserID pgtype.UUID) error {+ current, err := s.Queries.GetAutopilotInWorkspace(ctx, db.GetAutopilotInWorkspaceParams{+ ID: ap.ID,+ WorkspaceID: ap.WorkspaceID,+ })+ if err != nil {+ return fmt.Errorf("refresh autopilot: %w", err)+ }+ if !current.ProjectID.Valid {+ return nil+ }+ leader, _, err := s.resolveAutopilotLeader(ctx, current)+ if err != nil {+ // The mode-specific dispatch reports an unresolvable assignee.+ return nil+ }+ human := actorUserID+ if !human.Valid {+ human = ResolveAutopilotTriggerPrincipal(ctx, s.Queries, run.TriggerID, current.ID, current.WorkspaceID)+ }+ err = s.TaskSvc.guardRunProjectsAccess(ctx, current.WorkspaceID, leader, human, leader.OwnerID, current.ProjectID)+ if errors.Is(err, ErrProjectAccessDenied) {+ return &errDispatchSkipped{+ reason: "the person this run acts for or the agent's owner cannot access the autopilot's private project",+ code: dispatch.ReasonProjectAccessBlocked,+ }+ }+ return err+}+// dispatchFailReasonCode types a dispatch error that fell through to failRun.// It inspects the error with typed checks (never substring matching): a// fail-closed attribution refusal is attribution_blocked; everything else is andiff --git a/server/internal/service/autopilot_project_access_test.go b/server/internal/service/autopilot_project_access_test.gonew file mode 100644index 0000000000..bd06c46681--- /dev/null+++ b/server/internal/service/autopilot_project_access_test.go@@ -0,0 +1,58 @@+package service++import (+ "testing"++ "github.com/multica-ai/multica/server/internal/projectaccess"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// An autopilot bound to a private project (MUL-8472) must not run for a human+// who cannot see the project: create_issue used to file the issue into it and+// only then have the enqueue refuse, and run_only handed the project's context+// to a run with no check at all.+func TestAutopilotDispatch_PrivateProjectNeedsTheRunsHuman(t *testing.T) {+ for _, mode := range []string{"run_only", "create_issue"} {+ t.Run(mode, func(t *testing.T) {+ fx, creatorA := newPrincipalFixture(t)+ triggerOwnerB := fx.member(t, "project-b")+ projectID := fx.Project(t, "private ap project", testutil.Cols{"visibility": projectaccess.VisibilityPrivate})+ fx.InsertNoID(t, "project_member", testutil.Cols{+ "workspace_id": fx.WorkspaceID,+ "project_id": projectID,+ "user_id": creatorA,+ }, "project_id = $1 AND user_id = $2", projectID, creatorA)++ // B owns the agent and the trigger, so invocation admits B; only+ // the project stands between B and the run.+ agentID := fx.privateAgentOwnedBy(t, triggerOwnerB, "project-"+mode)+ autopilotID, triggerID := fx.autopilotWithTrigger(t, agentID, creatorA, triggerOwnerB)+ fx.Exec(t, `UPDATE autopilot SET project_id = $2, execution_mode = $3, issue_title_template = 'ap issue' WHERE id = $1`,+ autopilotID, projectID, mode)++ run := fx.dispatch(t, autopilotID, triggerID)+ if run.Status != "skipped" || run.ReasonCode.String != "project_access_blocked" {+ t.Fatalf("dispatch = %q (%q), want skipped with project_access_blocked", run.Status, run.ReasonCode.String)+ }+ if n := fx.Count(t, `SELECT count(*) FROM issue WHERE project_id = $1`, projectID); n != 0 {+ t.Errorf("refused dispatch still filed %d issues into the private project", n)+ }+ if n := fx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE autopilot_run_id = $1`, run.ID); n != 0 {+ t.Errorf("refused dispatch still enqueued %d tasks", n)+ }++ // Once B can see the project, the same autopilot runs.+ fx.InsertNoID(t, "project_member", testutil.Cols{+ "workspace_id": fx.WorkspaceID,+ "project_id": projectID,+ "user_id": triggerOwnerB,+ }, "project_id = $1 AND user_id = $2", projectID, triggerOwnerB)+ fx.Cleanup(t, `DELETE FROM issue WHERE project_id = $1`, projectID)+ fx.Cleanup(t, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)+ run = fx.dispatch(t, autopilotID, triggerID)+ if run.Status == "skipped" {+ t.Fatalf("dispatch refused (%q) for a project member", run.FailureReason.String)+ }+ })+ }+}