Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(autopilots): drop a member's autopilot access when they are removed (#11489)
pseudoyu8b9a5d1728db
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex 0b6ffe284a..a9c90543e3 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -1493,12 +1493,6 @@ func (h *Handler) AddAutopilotCollaborator(w http.ResponseWriter, r *http.Requesif !ok {return}- // Only workspace members can be granted access — agents already reach- // autopilots through their own dispatch path, not this grant list.- if !h.isWorkspaceEntity(r.Context(), "member", req.UserID, workspaceID) {- writeError(w, http.StatusBadRequest, "user_id must be a member of this workspace")- return- }// granted_by is the audit record of who widened access. A grant outlives the// run that made it, so it must name the human who authorized it rather than@@ -1506,7 +1500,36 @@ func (h *Handler) AddAutopilotCollaborator(w http.ResponseWriter, r *http.RequesgrantedByUUID := actor.UserIDgrantedBy := uuidToString(grantedByUUID)- if _, err := h.Queries.AddAutopilotCollaborator(r.Context(), db.AddAutopilotCollaboratorParams{+ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to grant access")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)+ // Member removal prunes grants under this lock; taking it before the+ // membership check keeps a concurrent grant from landing behind the prune.+ if err := qtx.LockSubscriberWrites(r.Context(), db.LockSubscriberWritesParams{+ WorkspaceID: ap.WorkspaceID,+ UserID: targetUUID,+ }); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to grant access")+ return+ }+ // Only workspace members can be granted access — agents already reach+ // autopilots through their own dispatch path, not this grant list.+ if _, err := qtx.LockActiveMember(r.Context(), db.LockActiveMemberParams{+ UserID: targetUUID,+ WorkspaceID: ap.WorkspaceID,+ }); err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ writeError(w, http.StatusBadRequest, "user_id must be a member of this workspace")+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to grant access")+ return+ }+ if _, err := qtx.AddAutopilotCollaborator(r.Context(), db.AddAutopilotCollaboratorParams{AutopilotID: ap.ID,UserType: "member",UserID: targetUUID,@@ -1515,6 +1538,10 @@ func (h *Handler) AddAutopilotCollaborator(w http.ResponseWriter, r *http.RequeswriteError(w, http.StatusInternalServerError, "failed to grant access")return}+ if err := tx.Commit(r.Context()); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to grant access")+ return+ }h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", grantedBy, map[string]any{"autopilot_id": uuidToString(ap.ID),diff --git a/server/internal/handler/autopilot_permissions_test.go b/server/internal/handler/autopilot_permissions_test.goindex 9d02dfbb67..dc543d04d6 100644--- a/server/internal/handler/autopilot_permissions_test.go+++ b/server/internal/handler/autopilot_permissions_test.go@@ -3,9 +3,13 @@ package handlerimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest""testing"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated")// createPlainMember adds a fresh member-role user to the test workspace and@@ -421,3 +425,70 @@ func TestAutopilotWrite_WebhookSecretRedactedForNonWriter(t *testing.T) {t.Fatalf("stranger view: webhook_url leaked: %v", *strangerView.Triggers[0].WebhookURL)}}++// TestAddAutopilotCollaborator_LosesToConcurrentRevoke: a grant that validated+// membership before a removal committed must not land behind the removal's+// prune. It waits for the removal's lock, then rejects the departed member.+func TestAddAutopilotCollaborator_LosesToConcurrentRevoke(t *testing.T) {+ ctx := context.Background()+ apID := createAutopilotAs(t, "", fmt.Sprintf("collaborator-revoke-race-%d", time.Now().UnixNano()))+ target := createPlainMember(t, fmt.Sprintf("collaborator-revoke-race-%[email protected]", time.Now().UnixNano()))++ revokeTx, err := testPool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin revoke tx: %v", err)+ }+ defer revokeTx.Rollback(context.Background())+ holderPID := holderBackendPID(t, ctx, revokeTx)+ qtx := testHandler.Queries.WithTx(revokeTx)+ if err := qtx.LockSubscriberWrites(ctx, db.LockSubscriberWritesParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ UserID: parseUUID(target),+ }); err != nil {+ t.Fatalf("revoke lock: %v", err)+ }+ if err := qtx.DeleteAutopilotCollaboratorsByMember(ctx, db.DeleteAutopilotCollaboratorsByMemberParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ UserID: parseUUID(target),+ }); err != nil {+ t.Fatalf("revoke cleanup: %v", err)+ }+ if _, err := revokeTx.Exec(ctx,+ `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, testWorkspaceID, target,+ ); err != nil {+ t.Fatalf("revoke member delete: %v", err)+ }++ done := make(chan int, 1)+ go func() {+ w := httptest.NewRecorder()+ r := newRequest("POST", "/api/autopilots/"+apID+"/collaborators?workspace_id="+testWorkspaceID, map[string]any{"user_id": target})+ testHandler.AddAutopilotCollaborator(w, withURLParam(r, "id", apID))+ done <- w.Code+ }()+ if !waitForWaiterBlockedBy(t, holderPID, 10*time.Second) {+ t.Fatal("grant did not wait for the removal's lock")+ }+ if err := revokeTx.Commit(ctx); err != nil {+ t.Fatalf("commit revoke: %v", err)+ }+ select {+ case code := <-done:+ if code != http.StatusBadRequest {+ t.Fatalf("grant status = %d, want 400 after the member left", code)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("grant never returned after the removal committed")+ }++ granted, err := testHandler.Queries.IsAutopilotCollaborator(ctx, db.IsAutopilotCollaboratorParams{+ AutopilotID: parseUUID(apID),+ UserID: parseUUID(target),+ })+ if err != nil {+ t.Fatalf("read collaborator: %v", err)+ }+ if granted {+ t.Fatal("grant landed behind the removal's prune")+ }+}diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex 2154949991..7f9aa5b924 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -256,6 +256,16 @@ func (h *Handler) revokeMember(ctx context.Context, workspaceID, userID, memberIreturn empty, err}+ // autopilot_collaborator holds write grants, FK-free like the templates+ // above. A grant left behind would hand a re-invited user their old write+ // access back without anyone granting it.+ if err := qtx.DeleteAutopilotCollaboratorsByMember(ctx, db.DeleteAutopilotCollaboratorsByMemberParams{+ WorkspaceID: workspaceID,+ UserID: userID,+ }); err != nil {+ return empty, err+ }+// App requests waiting on the member would otherwise let a later OAuth// connect, or a stale tab, resume an agent in a workspace they left.cancelledAppRequests, err := qtx.CancelPendingAppActionRequestsForApprover(ctx, db.CancelPendingAppActionRequestsForApproverParams{diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.goindex 5f56d7b7fe..6642493890 100644--- a/server/internal/handler/workspace_test.go+++ b/server/internal/handler/workspace_test.go@@ -1187,6 +1187,66 @@ WHERE autopilot_id = $1 AND user_id = $2}}+// TestDeleteMember_PrunesAutopilotCollaborators: a removed member who is+// invited back must not regain write access to autopilots they were granted+// before. The delete is scoped to that user and to this workspace.+func TestDeleteMember_PrunesAutopilotCollaborators(t *testing.T) {+ fx := setupRevocationFixture(t, "handler-tests-revoke-autopilot-collaborator", "daemon-revoke-autopilot-collaborator")++ insertAutopilot := func(workspaceID string) string {+ id := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": workspaceID,+ "title": "Revocation autopilot collaborator",+ "assignee_type": "agent",+ "assignee_id": fx.AgentID,+ "status": "active",+ "execution_mode": "run_only",+ "created_by_type": "member",+ "created_by_id": testUserID,+ })+ dbfx.Cleanup(t, `DELETE FROM autopilot_collaborator WHERE autopilot_id = $1`, id)+ return id+ }+ autopilotID := insertAutopilot(fx.WorkspaceID)+ otherWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Revocation collaborator other workspace",+ "slug": fmt.Sprintf("handler-tests-revoke-autopilot-collaborator-other-%d", time.Now().UnixNano()),+ "description": "tenant-scope regression fixture",+ "issue_prefix": "RCO",+ })+ otherAutopilotID := insertAutopilot(otherWorkspaceID)+ dbfx.Exec(t, `+INSERT INTO autopilot_collaborator (autopilot_id, user_type, user_id, granted_by)+VALUES ($1, 'member', $3, $4), ($1, 'member', $4, $4), ($2, 'member', $3, $4)+`, autopilotID, otherAutopilotID, fx.TargetUserID, testUserID)++ req := newRequest("DELETE", "/api/workspaces/"+fx.WorkspaceID+"/members/"+fx.MemberID, nil)+ req.Header.Set("X-Workspace-ID", fx.WorkspaceID)+ req = withURLParams(req, "id", fx.WorkspaceID, "memberId", fx.MemberID)+ testutil.Call(t, testHandler.DeleteMember, req).Want(http.StatusNoContent)++ granted := func(autopilotID, userID string) bool {+ t.Helper()+ ok, err := testHandler.Queries.IsAutopilotCollaborator(context.Background(), db.IsAutopilotCollaboratorParams{+ AutopilotID: parseUUID(autopilotID),+ UserID: parseUUID(userID),+ })+ if err != nil {+ t.Fatalf("read collaborator: %v", err)+ }+ return ok+ }+ if granted(autopilotID, fx.TargetUserID) {+ t.Error("removed member still holds write access to the autopilot")+ }+ if !granted(autopilotID, testUserID) {+ t.Error("remaining member's access was pruned")+ }+ if !granted(otherAutopilotID, fx.TargetUserID) {+ t.Error("access in another workspace was pruned")+ }+}+// TestLeaveWorkspace_RevokesOwnRuntimes is the self-removal counterpart: when// a member leaves a workspace voluntarily, their own runtimes are revoked// with the same atomic write set as DeleteMember.diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 28716dd10f..1dd5022e5e 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -528,6 +528,28 @@ func (q *Queries) DeleteAutopilotCollaborator(ctx context.Context, arg DeleteAutreturn err}+const deleteAutopilotCollaboratorsByMember = `-- name: DeleteAutopilotCollaboratorsByMember :exec+DELETE FROM autopilot_collaborator AS c+USING autopilot AS a+WHERE c.autopilot_id = a.id+ AND a.workspace_id = $1+ AND c.user_type = 'member'+ AND c.user_id = $2+`++type DeleteAutopilotCollaboratorsByMemberParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+}++// Collaborator grants carry no FK, so member removal must prune them in the+// same application transaction: a re-invited user must not regain write access+// they were granted before. Scoped to the workspace like the subscriber prune.+func (q *Queries) DeleteAutopilotCollaboratorsByMember(ctx context.Context, arg DeleteAutopilotCollaboratorsByMemberParams) error {+ _, err := q.db.Exec(ctx, deleteAutopilotCollaboratorsByMember, arg.WorkspaceID, arg.UserID)+ return err+}+const deleteAutopilotCollaboratorsForAutopilot = `-- name: DeleteAutopilotCollaboratorsForAutopilot :execDELETE FROM autopilot_collaboratorWHERE autopilot_id = $1diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sqlindex 3503df4272..968b00f4ff 100644--- a/server/pkg/db/queries/autopilot.sql+++ b/server/pkg/db/queries/autopilot.sql@@ -846,6 +846,17 @@ WHERE autopilot_id = $1 AND user_type = $2 AND user_id = $3;DELETE FROM autopilot_collaboratorWHERE autopilot_id = $1;+-- name: DeleteAutopilotCollaboratorsByMember :exec+-- Collaborator grants carry no FK, so member removal must prune them in the+-- same application transaction: a re-invited user must not regain write access+-- they were granted before. Scoped to the workspace like the subscriber prune.+DELETE FROM autopilot_collaborator AS c+USING autopilot AS a+WHERE c.autopilot_id = a.id+ AND a.workspace_id = sqlc.arg(workspace_id)+ AND c.user_type = 'member'+ AND c.user_id = sqlc.arg(user_id);+-- name: IsAutopilotCollaborator :oneSELECT EXISTS (SELECT 1 FROM autopilot_collaborator