Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7108 fix(autopilot): judge every autopilot write as the human it acts for (#8107)
Bohan Jiang3ac53a68a61c
diff --git a/server/cmd/multica/cmd_autopilot.go b/server/cmd/multica/cmd_autopilot.goindex 9b74008f91..5fd9da3df3 100644--- a/server/cmd/multica/cmd_autopilot.go+++ b/server/cmd/multica/cmd_autopilot.go@@ -437,7 +437,7 @@ func runAutopilotCreate(cmd *cobra.Command, _ []string) error {var result map[string]anyif err := client.PostJSON(ctx, "/api/autopilots", body, &result); err != nil {- return fmt.Errorf("create autopilot: %w", err)+ return autopilotWriteRequestError("create autopilot", err)}output, _ := cmd.Flags().GetString("output")@@ -528,7 +528,7 @@ func runAutopilotUpdate(cmd *cobra.Command, args []string) error {var result map[string]anyif err := client.PatchJSON(ctx, "/api/autopilots/"+autopilotRef.ID, body, &result); err != nil {- return fmt.Errorf("update autopilot: %w", err)+ return autopilotWriteRequestError("update autopilot", err)}output, _ := cmd.Flags().GetString("output")@@ -554,7 +554,7 @@ func runAutopilotDelete(cmd *cobra.Command, args []string) error {}if err := client.DeleteJSON(ctx, "/api/autopilots/"+autopilotRef.ID); err != nil {- return fmt.Errorf("delete autopilot: %w", err)+ return autopilotWriteRequestError("delete autopilot", err)}fmt.Printf("Autopilot %s deleted.\n", autopilotRef.Display)return nil@@ -627,6 +627,24 @@ func autopilotTriggerRequestError(err error) error {return fmt.Errorf("trigger autopilot: %w", err)}+// autopilotWriteRequestError turns a refused autopilot write into what the user+// should read, for the same reason autopilotTriggerRequestError exists: an+// autopilot write is authorized as the human who asked for it, so when YOU are+// the one running this, "no access" is about them and not about you — and+// FormatError's generic 403 copy cannot say which (MUL-7108). The branch is on+// the server's stable code, never on the English sentence.+func autopilotWriteRequestError(action string, err error) error {+ switch cli.ServerErrorCode(err) {+ case "autopilot_no_originator":+ return cli.WithUserMessage("this run has no originating human, so it cannot change an autopilot on anyone's behalf: an autopilot write is authorized as the person who asked for it", err)+ case "autopilot_forbidden":+ return cli.WithUserMessage("the person this run acts for cannot manage this autopilot: it requires its creator, a workspace admin, or a granted collaborator", err)+ case "autopilot_actor_not_member":+ return cli.WithUserMessage("the person this run acts for is not a member of this workspace, so nothing can be created on their behalf", err)+ }+ return fmt.Errorf("%s: %w", action, err)+}+// autopilotRunStarted reports whether a manual trigger actually dispatched work.//// Mirrors the web client's runNowToastKind whitelist (packages/views/autopilots):@@ -802,7 +820,7 @@ func runAutopilotTriggerAdd(cmd *cobra.Command, args []string) error {var result map[string]anyif err := client.PostJSON(ctx, "/api/autopilots/"+autopilotRef.ID+"/triggers", body, &result); err != nil {- return fmt.Errorf("create trigger: %w", err)+ return autopilotWriteRequestError("create trigger", err)}output, _ := cmd.Flags().GetString("output")@@ -867,7 +885,7 @@ func runAutopilotTriggerRotateURL(cmd *cobra.Command, args []string) error {var result map[string]anypath := "/api/autopilots/" + autopilotRef.ID + "/triggers/" + triggerRef.ID + "/rotate-webhook-token"if err := client.PostJSON(ctx, path, nil, &result); err != nil {- return fmt.Errorf("rotate webhook url: %w", err)+ return autopilotWriteRequestError("rotate webhook url", err)}output, _ := cmd.Flags().GetString("output")@@ -921,7 +939,7 @@ func runAutopilotTriggerUpdate(cmd *cobra.Command, args []string) error {var result map[string]anypath := "/api/autopilots/" + autopilotRef.ID + "/triggers/" + triggerRef.IDif err := client.PatchJSON(ctx, path, body, &result); err != nil {- return fmt.Errorf("update trigger: %w", err)+ return autopilotWriteRequestError("update trigger", err)}output, _ := cmd.Flags().GetString("output")@@ -952,7 +970,7 @@ func runAutopilotTriggerDelete(cmd *cobra.Command, args []string) error {path := "/api/autopilots/" + autopilotRef.ID + "/triggers/" + triggerRef.IDif err := client.DeleteJSON(ctx, path); err != nil {- return fmt.Errorf("delete trigger: %w", err)+ return autopilotWriteRequestError("delete trigger", err)}fmt.Printf("Trigger %s deleted.\n", triggerRef.ID)return nildiff --git a/server/cmd/multica/cmd_autopilot_test.go b/server/cmd/multica/cmd_autopilot_test.goindex efb2ed4746..96e4043eb6 100644--- a/server/cmd/multica/cmd_autopilot_test.go+++ b/server/cmd/multica/cmd_autopilot_test.go@@ -935,6 +935,75 @@ func TestAutopilotRunStarted(t *testing.T) {}}+// TestAutopilotWriteRequestError_SurfacesRefusalToTheUser is the same+// assertion for the other autopilot writes (create / update / delete /+// trigger-*), which refuse for the same reasons a trigger does: an agent whose+// run records no human, or whose human holds nothing here.+//+// It runs the real cli.FormatError for the same reason: FormatError collapses+// every 403 into "no access", which for an agent caller is a statement about+// the WRONG person — the fact worth printing is that the refusal belongs to+// whoever asked (MUL-7108).+func TestAutopilotWriteRequestError_SurfacesRefusalToTheUser(t *testing.T) {+ forbidden := func(body string) error {+ return &cli.HTTPError{+ Method: "PATCH",+ Path: "/api/autopilots/x",+ StatusCode: 403,+ Body: body,+ }+ }++ cases := []struct {+ name string+ body string+ wantText string+ }{+ {+ name: "no originator names the missing human",+ body: `{"error":"no human authorized this change: the calling run records no originator","code":"autopilot_no_originator"}`,+ wantText: "no originating human",+ },+ {+ name: "forbidden names who may manage the autopilot",+ body: `{"error":"only the autopilot creator, a workspace admin, or a granted collaborator can manage this autopilot","code":"autopilot_forbidden"}`,+ wantText: "granted collaborator",+ },+ {+ // create's refusal is a different fact: nobody is being told to+ // go get a collaborator grant they could not hold anyway.+ name: "non-member names the workspace, not a grant",+ body: `{"error":"the person this run acts for is not a member of this workspace","code":"autopilot_actor_not_member"}`,+ wantText: "not a member of this workspace",+ },+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ err := autopilotWriteRequestError("update autopilot", forbidden(tc.body))+ got := cli.FormatError(err, false)+ if !strings.Contains(got, tc.wantText) {+ t.Errorf("output = %q, want it to contain %q", got, tc.wantText)+ }+ if cli.ExitCodeFor(err) == 0 {+ t.Error("a refused write must not exit 0")+ }+ })+ }++ // A 403 this command has not opted into keeps the deliberately vague copy,+ // and the action name still says which call failed.+ t.Run("unrecognized 403 keeps the generic copy", func(t *testing.T) {+ err := autopilotWriteRequestError("delete autopilot", forbidden(`{"error":"some other resource is off limits"}`))+ got := cli.FormatError(err, false)+ if strings.Contains(got, "some other resource is off limits") {+ t.Errorf("output = %q, must not echo an un-opted-in 403 body", got)+ }+ if !strings.Contains(err.Error(), "delete autopilot") {+ t.Errorf("error = %q, want it to name the failed action", err.Error())+ }+ })+}+// TestAutopilotTriggerRequestError_SurfacesRefusalToTheUser is the end-to-end// assertion for what a person (or an agent reading its own output) actually sees// when a manual trigger is refused.diff --git a/server/cmd/server/autopilot_actor_forgery_test.go b/server/cmd/server/autopilot_actor_forgery_test.gonew file mode 100644index 0000000000..f40badc0e0--- /dev/null+++ b/server/cmd/server/autopilot_actor_forgery_test.go@@ -0,0 +1,133 @@+package main++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// Autopilot writes are judged as the human the caller acts for, and for an+// agent caller that human is the run's ORIGINATOR (MUL-7108). That makes the+// question "is this really an agent?" load-bearing, so this test pins the+// answer at the router: only a server-issued mat_ task token makes a request an+// agent's. A member replaying an observable (agent_id, task_id) pair — both are+// returned by GET /api/issues/{id}/task-runs — stays themselves (MUL-3428).+//+// The two halves are deliberately mirror images: the SAME live task, whose+// originator may write this autopilot, is reached once by forgery and once by+// the real credential. Only the credential differs, so the opposite outcomes+// can be explained by nothing else.+func TestAutopilotWritesIgnoreForgedAgentIdentity(t *testing.T) {+ fx := testutil.New(testPool, testWorkspaceID, testUserID)++ var agentID, runtimeID string+ fx.QueryRow(t, `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`, testWorkspaceID).+ Scan(&agentID, &runtimeID)++ // A live run whose originator is the workspace owner — a writer on the+ // autopilot below. This is the identity a forger wants to borrow.+ taskID := fx.Insert(t, "agent_task_queue", testutil.Cols{+ "agent_id": agentID, "runtime_id": runtimeID, "status": "running", "priority": 0,+ "originator_user_id": testUserID, "accountable_user_id": testUserID,+ "originator_source": "direct_human",+ })++ autopilotID := fx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID, "title": "forged actor regression",+ "assignee_id": agentID, "assignee_type": "agent", "execution_mode": "run_only",+ "status": "active", "created_by_type": "member", "created_by_id": testUserID,+ })+ fx.Cleanup(t, `DELETE FROM autopilot_rule_version WHERE autopilot_id = $1`, autopilotID)+ fx.Insert(t, "autopilot_trigger", testutil.Cols{+ "autopilot_id": autopilotID, "kind": "webhook", "enabled": true, "provider": "generic",+ "webhook_token": fmt.Sprintf("tok_forgery_%d", time.Now().UnixNano()),+ "created_by_type": "member", "created_by_id": testUserID,+ })++ // The forger: a workspace member holding no grant on this autopilot.+ email := fmt.Sprintf("autopilot-forger-%[email protected]", time.Now().UnixNano())+ outsider := fx.User(t, "Autopilot Forger", email)+ fx.Member(t, testWorkspaceID, outsider, "member")+ outsiderJWT, err := generateTestJWT(outsider, email, "Autopilot Forger")+ if err != nil {+ t.Fatalf("outsider jwt: %v", err)+ }++ do := func(t *testing.T, method, path string, body any, decorate func(*http.Request)) *http.Response {+ t.Helper()+ var reader *bytes.Reader+ if body != nil {+ b, _ := json.Marshal(body)+ reader = bytes.NewReader(b)+ } else {+ reader = bytes.NewReader(nil)+ }+ req, err := http.NewRequest(method, testServer.URL+path, reader)+ if err != nil {+ t.Fatalf("build request: %v", err)+ }+ req.Header.Set("Content-Type", "application/json")+ decorate(req)+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("request failed: %v", err)+ }+ return resp+ }+ forged := func(req *http.Request) {+ req.Header.Set("Authorization", "Bearer "+outsiderJWT)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ // The forgery: a real, member-readable pair replayed as headers.+ req.Header.Set("X-Agent-ID", agentID)+ req.Header.Set("X-Task-ID", taskID)+ }++ t.Run("forged agent identity is judged as the member", func(t *testing.T) {+ resp := do(t, "GET", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, nil, forged)+ if resp.StatusCode != http.StatusOK {+ resp.Body.Close()+ t.Fatalf("detail status = %d, want 200", resp.StatusCode)+ }+ var detail struct {+ Autopilot handler.AutopilotResponse `json:"autopilot"`+ Triggers []handler.AutopilotTriggerResponse `json:"triggers"`+ }+ readJSON(t, resp, &detail)+ if detail.Autopilot.CanWrite == nil || *detail.Autopilot.CanWrite {+ t.Errorf("can_write = %t, want false: the forged pair must not lend this member the originator's grant",+ detail.Autopilot.CanWrite != nil && *detail.Autopilot.CanWrite)+ }+ for _, tr := range detail.Triggers {+ if tr.WebhookToken != nil || tr.WebhookPath != nil || tr.WebhookURL != nil {+ t.Error("the forged pair yielded the webhook credential, which is a trigger this member cannot otherwise fire")+ }+ }++ writeResp := do(t, "PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID,+ map[string]any{"status": "paused"}, forged)+ defer writeResp.Body.Close()+ if writeResp.StatusCode != http.StatusForbidden {+ t.Fatalf("update status = %d, want 403 — a member must not write through a borrowed agent identity", writeResp.StatusCode)+ }+ })++ t.Run("a real task token is judged by its originator", func(t *testing.T) {+ // Bound to the OUTSIDER as runtime owner: the machine's owner holds no+ // grant here, so admission can only come from the task's originator.+ token := mintAgentTaskToken(t, agentID, taskID, outsider)+ resp := do(t, "PATCH", "/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID,+ map[string]any{"status": "paused"}, func(req *http.Request) {+ req.Header.Set("Authorization", "Bearer "+token)+ })+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ t.Fatalf("update status = %d, want 200 — the ordering human may write this autopilot", resp.StatusCode)+ }+ })+}diff --git a/server/cmd/server/autopilot_webhook_broadcast_test.go b/server/cmd/server/autopilot_webhook_broadcast_test.gonew file mode 100644index 0000000000..99088a06e2--- /dev/null+++ b/server/cmd/server/autopilot_webhook_broadcast_test.go@@ -0,0 +1,141 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/multica-ai/multica/server/internal/handler"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// TestAutopilotWebhookTokenIsNotBroadcastToTheWorkspace is the end-to-end proof+// for the redaction unit-tested in internal/handler: through the real router,+// the real event bus and a real WebSocket client, a member who is refused the+// webhook token by GetAutopilot must not receive it from the fanout either.+//+// Holding that token fires the autopilot through the public ingress route, so a+// leak here is a permission bypass that no write gate can see. The leak predates+// MUL-7108 and is closed with it, since it is the same bypass.+func TestAutopilotWebhookTokenIsNotBroadcastToTheWorkspace(t *testing.T) {+ fx := testutil.New(testPool, testWorkspaceID, testUserID)++ email := fmt.Sprintf("autopilot-broadcast-reader-%[email protected]", time.Now().UnixNano())+ reader := fx.User(t, "Autopilot Broadcast Reader", email)+ fx.Member(t, testWorkspaceID, reader, "member")+ readerToken, err := generateTestJWT(reader, email, "Autopilot Broadcast Reader")+ if err != nil {+ t.Fatalf("reader jwt: %v", err)+ }++ var agentID string+ fx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)+ autopilotID := fx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID, "title": "webhook broadcast redaction",+ "assignee_id": agentID, "assignee_type": "agent", "execution_mode": "run_only",+ "status": "active", "created_by_type": "member", "created_by_id": testUserID,+ })+ triggerID := fx.Insert(t, "autopilot_trigger", testutil.Cols{+ "autopilot_id": autopilotID, "kind": "webhook", "enabled": true,+ "provider": "generic", "webhook_token": fmt.Sprintf("tok_%d", time.Now().UnixNano()),+ "created_by_type": "member", "created_by_id": testUserID,+ })++ // The premise: this member is refused the secret on the read path.+ req, err := http.NewRequest(http.MethodGet, testServer.URL+"/api/autopilots/"+autopilotID+"?workspace_id="+testWorkspaceID, nil)+ if err != nil {+ t.Fatalf("build detail request: %v", err)+ }+ req.Header.Set("Authorization", "Bearer "+readerToken)+ detailResp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("read detail: %v", err)+ }+ if detailResp.StatusCode != http.StatusOK {+ detailResp.Body.Close()+ t.Fatalf("detail status = %d, want 200", detailResp.StatusCode)+ }+ var detail struct {+ Autopilot handler.AutopilotResponse `json:"autopilot"`+ Triggers []handler.AutopilotTriggerResponse `json:"triggers"`+ }+ readJSON(t, detailResp, &detail)+ if detail.Autopilot.CanWrite == nil || *detail.Autopilot.CanWrite {+ t.Fatalf("fixture is wrong: the reader must be a non-writer, got can_write=%v", detail.Autopilot.CanWrite)+ }+ if len(detail.Triggers) != 1 || detail.Triggers[0].WebhookToken != nil {+ t.Fatal("fixture is wrong: the read path must already redact the token for this member")+ }++ wsURL := "ws" + strings.TrimPrefix(testServer.URL, "http") + "/ws?workspace_id=" + testWorkspaceID+ conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)+ if err != nil {+ t.Fatalf("websocket dial: %v", err)+ }+ defer conn.Close()+ if err := conn.WriteJSON(map[string]any{"type": "auth", "payload": map[string]string{"token": readerToken}}); err != nil {+ t.Fatalf("websocket auth: %v", err)+ }+ conn.SetReadDeadline(time.Now().Add(3 * time.Second))+ _, ack, err := conn.ReadMessage()+ if err != nil || !strings.Contains(string(ack), "auth_ack") {+ t.Fatalf("websocket auth_ack: %s %v", ack, err)+ }+ // Same registration barrier the other WebSocket integration test uses: the+ // Hub adds the client to the room on its own goroutine.+ time.Sleep(100 * time.Millisecond)++ rotateResp := authRequest(t, "POST", "/api/autopilots/"+autopilotID+"/triggers/"+triggerID+"/rotate-webhook-token?workspace_id="+testWorkspaceID, nil)+ if rotateResp.StatusCode != http.StatusOK {+ rotateResp.Body.Close()+ t.Fatalf("rotate status = %d, want 200", rotateResp.StatusCode)+ }+ var rotated handler.AutopilotTriggerResponse+ readJSON(t, rotateResp, &rotated)+ // The writer's own response must still carry the live token — otherwise the+ // assertion below would pass on an endpoint that stopped issuing one.+ if rotated.WebhookToken == nil || *rotated.WebhookToken == "" {+ t.Fatal("rotate returned no token to the authorized caller")+ }++ var event struct {+ Type string `json:"type"`+ Payload struct {+ AutopilotID string `json:"autopilot_id"`+ Trigger handler.AutopilotTriggerResponse `json:"trigger"`+ } `json:"payload"`+ }+ deadline := time.Now().Add(3 * time.Second)+ for {+ conn.SetReadDeadline(deadline)+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("no autopilot:updated event reached the workspace room: %v", err)+ }+ if err := json.Unmarshal(raw, &event); err != nil {+ t.Fatalf("parse websocket frame: %v", err)+ }+ if event.Type == "autopilot:updated" && event.Payload.AutopilotID == autopilotID {+ break+ }+ }++ if event.Payload.Trigger.WebhookToken != nil || event.Payload.Trigger.WebhookPath != nil || event.Payload.Trigger.WebhookURL != nil {+ // Presence, not value: a failure message is not a place to print a+ // live credential.+ t.Fatalf("a non-writer received the webhook credential over the workspace websocket: token=%t path=%t url=%t",+ event.Payload.Trigger.WebhookToken != nil,+ event.Payload.Trigger.WebhookPath != nil,+ event.Payload.Trigger.WebhookURL != nil)+ }+ // The event must still arrive and identify the trigger: clients react by+ // refetching through the authenticated endpoint, which is what makes+ // carrying no secret cost nothing.+ if event.Payload.Trigger.ID != triggerID {+ t.Errorf("broadcast trigger id = %q, want %q — clients cannot tell what to refetch", event.Payload.Trigger.ID, triggerID)+ }+}diff --git a/server/cmd/server/comment_trigger_integration_test.go b/server/cmd/server/comment_trigger_integration_test.goindex 7a543e874a..0a8210c6fd 100644--- a/server/cmd/server/comment_trigger_integration_test.go+++ b/server/cmd/server/comment_trigger_integration_test.go@@ -7,16 +7,23 @@ import ("fmt""io""net/http"+ "strings""testing""time"++ "github.com/multica-ai/multica/server/internal/auth")-// authRequestWithAgent makes an authenticated request with X-Agent-ID +-// X-Task-ID headers, causing the server to resolve the actor as an agent-// instead of a member. resolveActor requires both headers to grant agent-// identity (defense against header forgery — see #2359 PR review), so we-// seed a queued task for the agent on demand and pass its UUID as-// X-Task-ID. The task is best-effort cleaned up via test teardown elsewhere.+// authRequestWithAgent makes a request the server resolves as coming from an+// agent, by authenticating with a real `mat_` task token bound to (agent, task,+// workspace, user) — the same credential the daemon injects into an agent+// process.+//+// It used to send a member token plus X-Agent-ID / X-Task-ID headers. That+// stopped working, on purpose: both middlewares now strip client-supplied agent+// identity, because both ids are observable by any workspace member and the+// pair therefore proved nothing (MUL-3428). A test that poses as an agent must+// hold the credential a real agent holds.func authRequestWithAgent(t *testing.T, method, path string, body any, agentID string) *http.Response {t.Helper()var bodyReader io.Reader@@ -29,10 +36,7 @@ func authRequestWithAgent(t *testing.T, method, path string, body any, agentID st.Fatalf("failed to create request: %v", err)}req.Header.Set("Content-Type", "application/json")- req.Header.Set("Authorization", "Bearer "+testToken)- req.Header.Set("X-Workspace-ID", testWorkspaceID)- req.Header.Set("X-Agent-ID", agentID)- req.Header.Set("X-Task-ID", ensureAgentTask(t, agentID))+ req.Header.Set("Authorization", "Bearer "+mintAgentTaskToken(t, agentID, ensureAgentTask(t, agentID), testUserID))r, err := http.DefaultClient.Do(req)if err != nil {@@ -41,10 +45,32 @@ func authRequestWithAgent(t *testing.T, method, path string, body any, agentID sreturn r}-// ensureAgentTask returns a queued task UUID belonging to the given agent,-// inserting one if none exists. Used by authRequestWithAgent so callers-// can keep treating "set X-Agent-ID" as the single knob for posing as an-// agent — resolveActor's pair-required policy is satisfied transparently.+// mintAgentTaskToken issues a task-scoped mat_ token for (agentID, taskID) in+// the test workspace and returns its raw value. The auth middleware re-stamps+// X-User-ID / X-Agent-ID / X-Task-ID / X-Workspace-ID from the stored row, so+// callers pass no identity headers of their own.+// boundUserID is the token's owning human — the runtime owner in production.+// It is NOT the human an agent's request acts for; that is the task's+// originator (MUL-6951), which is why the two are separable in tests.+func mintAgentTaskToken(t *testing.T, agentID, taskID, boundUserID string) string {+ t.Helper()+ raw := fmt.Sprintf("mat_test_%s_%d", strings.ReplaceAll(agentID, "-", ""), time.Now().UnixNano())+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)+ VALUES ($1, $2, $3, $4, $5, now() + interval '1 hour')+ `, auth.HashToken(raw), taskID, agentID, testWorkspaceID, boundUserID); err != nil {+ t.Fatalf("mint task token: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM task_token WHERE token_hash = $1`, auth.HashToken(raw))+ })+ return raw+}++// ensureAgentTask returns a task UUID belonging to the given agent, inserting a+// queued one if none exists. authRequestWithAgent binds its mat_ token to that+// task, so callers keep treating "name the agent" as the single knob for+// posing as one.func ensureAgentTask(t *testing.T, agentID string) string {t.Helper()ctx := context.Background()@@ -222,7 +248,8 @@ func postComment(t *testing.T, issueID, content string, parentID *string) stringreturn comment["id"].(string)}-// postCommentAsAgent posts a comment with the X-Agent-ID header.+// postCommentAsAgent posts a comment authenticated as the agent, using the+// real mat_ task token authRequestWithAgent mints.func postCommentAsAgent(t *testing.T, issueID, content, agentID string, parentID *string) string {t.Helper()body := map[string]any{diff --git a/server/internal/cli/client.go b/server/internal/cli/client.goindex 06ccf283bf..941e0d9f9c 100644--- a/server/internal/cli/client.go+++ b/server/internal/cli/client.go@@ -50,9 +50,15 @@ type APIClient struct {BaseURL stringWorkspaceID stringToken string- AgentID string // When set, requests are attributed to this agent instead of the user.- TaskID string // When set, sent as X-Task-ID for agent-task validation.- HTTPClient *http.Client+ // AgentID / TaskID travel as X-Agent-ID / X-Task-ID execution context.+ // They are NOT what makes the server treat a request as the agent's: the+ // server strips both headers on entry and re-stamps them from the bound+ // mat_ task token, so attribution follows the token, not these fields+ // (MUL-3428). The CLI only sets them inside a daemon-managed task, where+ // MULTICA_TOKEN is that mat_ token.+ AgentID string+ TaskID string+ HTTPClient *http.Client// Identity overrides. Empty values fall back to the package-level// ClientPlatform / ClientVersion / ClientOS.diff --git a/server/internal/handler/actor_guards.go b/server/internal/handler/actor_guards.goindex ee3bc8586c..764eab876c 100644--- a/server/internal/handler/actor_guards.go+++ b/server/internal/handler/actor_guards.go@@ -64,11 +64,11 @@ import (//// - resolveActor's primary job is "agent vs member" classification// for ownership / authorship attribution (issue creator, comment-// author, etc.). It also has a fallback path that trusts-// X-Agent-ID + X-Task-ID for legacy CLI flows; that fallback is-// valid for resolving authorship but is irrelevant here. Billing-// authorization needs the strict "machine credential → forbidden"-// gate, nothing else.+// author, etc.). It also has a fallback path that reads+// X-Agent-ID + X-Task-ID directly; since MUL-3428 both middlewares+// strip those headers, so that path is unreachable from the network+// and irrelevant here either way. Billing authorization needs the+// strict "machine credential → forbidden" gate, nothing else.// - resolveActor takes a workspaceID parameter; billing routes have// no workspace context, so threading one through just to call it// would be misleading.diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.goindex cc997c4d12..d1bdc395d3 100644--- a/server/internal/handler/autopilot.go+++ b/server/internal/handler/autopilot.go@@ -276,6 +276,39 @@ func signingSecretHint(secret string) string {return secret[len(secret)-4:]}+// redactWebhookSecrets removes the webhook credential from a trigger response:+// the bearer token, and the path and URL that embed it. Holding any of the+// three is equivalent to being able to fire the autopilot from outside the+// permission system, so they travel together.+//+// One definition, shared by the read path's non-writer projection and the+// broadcast copy (broadcastAutopilotTriggerResponse), so a field added to one+// cannot be forgotten by the other.+func redactWebhookSecrets(resp *AutopilotTriggerResponse) {+ resp.WebhookToken = nil+ resp.WebhookPath = nil+ resp.WebhookURL = nil+}++// broadcastAutopilotTriggerResponse strips the webhook credential from a+// trigger before it goes onto the WebSocket bus. Mutation handlers call it when+// fanning out autopilot:updated, following the same rule as+// broadcastAgentResponse: autopilot events reach the WHOLE workspace room —+// every member regardless of grant, agent processes on their own task tokens+// included — so a non-redacted broadcast hands them the token GetAutopilot just+// refused them, through a push that never passed a write gate (MUL-7108).+// The caller still receives the live value in the HTTP response; only the+// broadcast copy is redacted.+//+// Nothing downstream loses anything: clients treat these events as "refetch+// this autopilot" (packages/core/realtime/use-realtime-sync.ts), and a writer+// re-reads the token from the authenticated detail endpoint.+func broadcastAutopilotTriggerResponse(resp AutopilotTriggerResponse) AutopilotTriggerResponse {+ out := resp+ redactWebhookSecrets(&out)+ return out+}+// webhookPathForToken composes the path used by the public ingress route.// Kept as a free function (no Handler receiver) so test code that builds// expected URLs without instantiating a Handler can call it.@@ -420,11 +453,12 @@ func (h *Handler) ListAutopilots(w http.ResponseWriter, r *http.Request) {return}- // Resolve the caller's write access for per-row can_write. The collaborator- // grants are fetched once as a set (keyed by autopilot id) so the flag- // costs no per-row query. A missing member (shouldn't happen behind the- // workspace-member middleware) just yields can_write=false everywhere.- caller, callerErr := h.getWorkspaceMember(r.Context(), requestUserID(r), workspaceID)+ // 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+ // flag costs no per-row query. A missing member — an agent run with no+ // originator, or (behind the workspace-member middleware, shouldn't happen) a+ // non-member — just yields can_write=false everywhere.+ caller, callerErr := h.getWorkspaceMember(r.Context(), h.autopilotActingUserID(r, workspaceID), workspaceID)collabSet := map[string]struct{}{}if callerErr == nil {if ids, err := h.Queries.ListAutopilotIDsForCollaborator(r.Context(), caller.UserID); err == nil {@@ -505,16 +539,20 @@ func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {}resp := autopilotToResponse(autopilot, subs)- // Resolve the caller's write access once: it both stamps can_write and+ // Resolve the acting caller's write access once: it both stamps can_write and// gates webhook-secret exposure. Webhook tokens are trigger-granting// secrets (anyone who reads the token can fire the autopilot from outside// the permission system), so only writers — the creator, a workspace// owner/admin, or a granted collaborator — get the live token/URL; every// other member sees the trigger metadata with the secret fields stripped// (MUL-3807).+ //+ // "Acting" is what makes the write gates worth having: judging the+ // authenticated user would hand an agent its runtime owner's tokens, and a+ // token read here is a trigger the write gates never see (MUL-7108).canWrite := falsecanManageAccess := false- if member, err := h.getWorkspaceMember(r.Context(), requestUserID(r), workspaceID); err == nil {+ if member, err := h.getWorkspaceMember(r.Context(), h.autopilotActingUserID(r, workspaceID), workspaceID); err == nil {canWrite = h.memberCanWriteAutopilot(r.Context(), autopilot, member)// Managing the access list is narrower than write: collaborators can// write but cannot re-grant (MUL-3807).@@ -532,9 +570,7 @@ func (h *Handler) GetAutopilot(w http.ResponseWriter, r *http.Request) {for i, t := range triggers {tr := h.triggerToResponse(t)if !canWrite {- tr.WebhookToken = nil- tr.WebhookPath = nil- tr.WebhookURL = nil+ redactWebhookSecrets(&tr)}triggerResp[i] = tr}@@ -607,20 +643,146 @@ func (h *Handler) memberCanWriteAutopilot(ctx context.Context, ap db.Autopilot,return err == nil && granted}+// Stable, machine-readable refusal codes for the autopilot write surface. The+// CLI keys its actionable output on these rather than on the English sentence,+// which is what lets a refusal survive translation and copy edits.+const (+ autopilotNoOriginatorCode = "autopilot_no_originator"+ autopilotForbiddenCode = "autopilot_forbidden"+ autopilotActorNotMemberCode = "autopilot_actor_not_member"+ autopilotTriggerNoOriginatorCode = "autopilot_trigger_no_originator"+ autopilotTriggerForbiddenCode = "autopilot_trigger_forbidden"+)++// autopilotRefusal is the code + sentence a gate answers with when no human+// backs the request, and when the human it acts for holds no grant. Each gate+// carries its own pair so a refusal names the operation actually attempted; the+// resolution below it is shared.+type autopilotRefusal struct {+ noOriginatorCode string+ noOriginatorMsg string+ forbiddenCode string+ forbiddenMsg string+}++var (+ autopilotWriteRefusal = autopilotRefusal{+ noOriginatorCode: autopilotNoOriginatorCode,+ noOriginatorMsg: "no human authorized this change: the calling run records no originator",+ forbiddenCode: autopilotForbiddenCode,+ forbiddenMsg: "only the autopilot creator, a workspace admin, or a granted collaborator can manage this autopilot",+ }+ // Create has no autopilot to hold a grant on, so its only "forbidden" is+ // an acting human who is not in this workspace. That is a different fact+ // from "lacks access to this autopilot" and gets its own code, so the CLI+ // does not tell someone to ask for a collaborator grant they could not+ // hold (MUL-7108).+ autopilotCreateRefusal = autopilotRefusal{+ noOriginatorCode: autopilotNoOriginatorCode,+ noOriginatorMsg: "no human authorized this autopilot: the calling run records no originator",+ forbiddenCode: autopilotActorNotMemberCode,+ forbiddenMsg: "the person this run acts for is not a member of this workspace",+ }+ autopilotAccessRefusal = autopilotRefusal{+ noOriginatorCode: autopilotNoOriginatorCode,+ noOriginatorMsg: "no human authorized this change: the calling run records no originator",+ forbiddenCode: autopilotForbiddenCode,+ forbiddenMsg: "only the autopilot creator or a workspace admin can manage access",+ }+ autopilotTriggerRefusal = autopilotRefusal{+ noOriginatorCode: autopilotTriggerNoOriginatorCode,+ noOriginatorMsg: "no human authorized this trigger: the calling run records no originator",+ forbiddenCode: autopilotTriggerForbiddenCode,+ forbiddenMsg: "only the autopilot creator, a workspace admin, or a granted collaborator can trigger this autopilot",+ }+)++// autopilotActingUserID resolves the human whose authority a request on this+// surface spends, without judging or refusing: a member acts for themselves, an+// agent acts for its run's ORIGINATOR. Returns "" when no human can be+// attributed. Read paths use it directly — they must not refuse an+// unattributed caller, only decline to hand it a writer's secrets.+func (h *Handler) autopilotActingUserID(r *http.Request, workspaceID string) string {+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ return h.invokeOriginatorFromRequest(r, actorType, actorID)+}++// requireAutopilotActingMember resolves the workspace member whose authority an+// autopilot WRITE spends. Every write gate on this surface, and every identity+// it stamps into a row, goes through this one seam so the rule cannot drift+// between endpoints (MUL-7108).+//+// A member acts for themselves. An agent — the CLI running inside a task, or an+// A2A call — acts for its run's ORIGINATOR, the top-of-chain human. That is how+// every other invoke surface in the codebase judges an agent actor (MUL-3963 /+// canInvokeAgent), and an autopilot write is an invoke with a delay on it:+// editing the rule, adding a trigger, rotating a webhook token or granting a+// collaborator all decide what an agent will be told to do later.+//+// Judging the request's authenticated user instead resolves the RUNTIME OWNER+// under a task token (middleware/auth.go stamps the token's bound user, minted+// from rt.OwnerID), which is wrong in both directions. Too broad: it makes every+// agent a standing proxy for its machine's owner, so anyone who can talk to that+// agent inherits the owner's autopilot rights without holding any themselves —+// the escalation MUL-7108 reports. Too narrow, if kept as an ADDITIONAL+// condition: it would refuse a member who may edit this autopilot themselves+// merely because the agent they asked happens to run on a third party's machine,+// which is the shape #8099 rejected for the trigger endpoint. Workspace tenancy+// for the authenticated caller is already enforced by the router's+// RequireWorkspaceMember middleware, so judging the acting human alone loses no+// isolation.+//+// No resolvable human → refuse. A run carrying no originator is one this+// codebase has already decided authorizes nothing (rule_owner is documented+// "deliberately powerless"; a terminal task lends nothing), so it cannot hold+// the pen here either.+//+// On refusal the response is written and ok is false; the caller must return.+func (h *Handler) requireAutopilotActingMember(w http.ResponseWriter, r *http.Request, workspaceID string, refusal autopilotRefusal) (db.Member, bool) {+ userID, ok := requireUserID(w, r)+ if !ok {+ return db.Member{}, false+ }+ actorType, actorID := h.resolveActor(r, userID, workspaceID)+ if actorType != "agent" {+ // A member acts for themselves: unchanged path, keeping the context+ // member and the 404 requireWorkspaceMember writes for a non-member —+ // a write refusal must not confirm that this workspace exists.+ return h.workspaceMember(w, r, workspaceID)+ }+ originator := h.invokeOriginatorFromRequest(r, actorType, actorID)+ if originator == "" {+ // Distinct from the permission refusal below: nothing was denied, there+ // was simply nobody to judge. It carries its own code because it is the+ // one refusal here a workspace can act on.+ writeErrorCode(w, http.StatusForbidden, refusal.noOriginatorCode, refusal.noOriginatorMsg)+ return db.Member{}, false+ }+ member, err := h.getWorkspaceMember(r.Context(), originator, workspaceID)+ if err != nil {+ writeErrorCode(w, http.StatusForbidden, refusal.forbiddenCode, refusal.forbiddenMsg)+ return db.Member{}, false+ }+ return member, true+}+// requireAutopilotWrite enforces memberCanWriteAutopilot for a mutating/-// executing request. On failure it writes the response (404 when the caller is-// not a member of the workspace, 403 otherwise) and returns false; the caller-// must return early. On success it returns true.-func (h *Handler) requireAutopilotWrite(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) bool {- member, ok := h.workspaceMember(w, r, workspaceID)+// executing request, judging the member the request acts for+// (requireAutopilotActingMember). On failure it writes the response (404 when a+// member caller is not in the workspace, 403 otherwise) and returns ok=false;+// the caller must return early. On success it returns that member — the identity+// the handler must also stamp into whatever it writes, so the gate and the row+// can never name two different people (MUL-7108).+func (h *Handler) requireAutopilotWrite(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) (db.Member, bool) {+ member, ok := h.requireAutopilotActingMember(w, r, workspaceID, autopilotWriteRefusal)if !ok {- return false+ return db.Member{}, false}if !h.memberCanWriteAutopilot(r.Context(), ap, member) {- writeError(w, http.StatusForbidden, "only the autopilot creator, a workspace admin, or a granted collaborator can manage this autopilot")- return false+ writeErrorCode(w, http.StatusForbidden, autopilotWriteRefusal.forbiddenCode, autopilotWriteRefusal.forbiddenMsg)+ return db.Member{}, false}- return true+ return member, true}// requireAutopilotAccessManagement enforces the narrower predicate used by the@@ -629,17 +791,18 @@ func (h *Handler) requireAutopilotWrite(w http.ResponseWriter, r *http.Request,// keeps its own write/execute rights (edit, trigger, manage triggers/secrets)// but cannot manage the access list — this stops a collaborator from// re-granting access to others or revoking peers (privilege escalation).-// See MUL-3807.-func (h *Handler) requireAutopilotAccessManagement(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) bool {- member, ok := h.workspaceMember(w, r, workspaceID)+// See MUL-3807. Like every gate here it judges the acting member, since a grant+// is the most durable write on this surface: it outlives the run that made it.+func (h *Handler) requireAutopilotAccessManagement(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) (db.Member, bool) {+ member, ok := h.requireAutopilotActingMember(w, r, workspaceID, autopilotAccessRefusal)if !ok {- return false+ return db.Member{}, false}if !autopilotWriteByOwnership(ap, member) {- writeError(w, http.StatusForbidden, "only the autopilot creator or a workspace admin can manage access")- return false+ writeErrorCode(w, http.StatusForbidden, autopilotAccessRefusal.forbiddenCode, autopilotAccessRefusal.forbiddenMsg)+ return db.Member{}, false}- return true+ return member, true}func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {@@ -672,10 +835,17 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {}workspaceID := h.resolveWorkspaceID(r)- userID, ok := requireUserID(w, r)+ // Everything this handler stamps — created_by, the v1 rule version, the+ // realtime event, the analytics actor — is the human the create acts for,+ // never the runtime owner whose token authenticated it. created_by is the+ // autopilot's own write grant, so stamping the wrong human here would hand+ // that grant to a machine's owner and lock the requesting member out of the+ // autopilot they just asked for (MUL-7108).+ actor, ok := h.requireAutopilotActingMember(w, r, workspaceID, autopilotCreateRefusal)if !ok {return}+ userID := uuidToString(actor.UserID)assigneeUUID, ok := parseUUIDOrBadRequest(w, req.AssigneeID, "assignee_id")if !ok {@@ -737,7 +907,7 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {Status: "active",ExecutionMode: req.ExecutionMode,CreatedByType: "member",- CreatedByID: parseUUID(userID),+ CreatedByID: actor.UserID,Description: ptrToText(req.Description),IssueTitleTemplate: ptrToText(req.IssueTitleTemplate),ProjectID: projectID,@@ -750,7 +920,7 @@ func (h *Handler) CreateAutopilot(w http.ResponseWriter, r *http.Request) {// Creating an autopilot IS a substantive publish: append rule-version v1 with// the creating member as publisher, so every autopilot has an accountable// human at dispatch time (MUL-4302 §3.4).- if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", parseUUID(userID)); err != nil {+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", actor.UserID); err != nil {writeError(w, http.StatusInternalServerError, "failed to create autopilot")return}@@ -874,14 +1044,13 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {if !ok {return}- if !h.requireAutopilotWrite(w, r, prev, workspaceID) {- return- }-- userID, ok := requireUserID(w, r)+ actor, ok := h.requireAutopilotWrite(w, r, prev, workspaceID)if !ok {return}+ // The publisher recorded below is the member the gate just judged, so the+ // rule version names whoever actually authorized the edit (MUL-7108).+ userID := uuidToString(actor.UserID)bodyBytes, err := io.ReadAll(r.Body)if err != nil {@@ -1055,7 +1224,7 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {// AUDIT value only — it is the coarse fallback a run degrades to when its// trigger records no creator, and such a run carries no authorization.if autopilotRuleSubstantiveChange(prev, autopilot) {- if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", parseUUID(userID)); err != nil {+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, autopilot, "member", actor.UserID); err != nil {writeError(w, http.StatusInternalServerError, "failed to update autopilot")return}@@ -1067,7 +1236,7 @@ func (h *Handler) UpdateAutopilot(w http.ResponseWriter, r *http.Request) {if err := qtx.SetAutopilotTriggerPublishersByAutopilot(r.Context(), db.SetAutopilotTriggerPublishersByAutopilotParams{AutopilotID: autopilot.ID,PublishedByType: pgtype.Text{String: "member", Valid: true},- PublishedByID: parseUUID(userID),+ PublishedByID: actor.UserID,}); err != nil {writeError(w, http.StatusInternalServerError, "failed to update autopilot")return@@ -1188,14 +1357,11 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "autopilot not found")return}- if !h.requireAutopilotWrite(w, r, ap, workspaceID) {- return- }-- userID, ok := requireUserID(w, r)+ actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)if !ok {return}+ userID := uuidToString(actor.UserID)// Product "delete" is archival: stop future triggers and hide the// autopilot from default lists while preserving runs, tasks, webhook@@ -1215,7 +1381,7 @@ func (h *Handler) DeleteAutopilot(w http.ResponseWriter, r *http.Request) {return}ap.Status = "archived" // reflect the post-archive state in the version snapshot- if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", parseUUID(userID)); err != nil {+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", actor.UserID); err != nil {writeError(w, http.StatusInternalServerError, "failed to delete autopilot")return}@@ -1259,7 +1425,8 @@ func (h *Handler) AddAutopilotCollaborator(w http.ResponseWriter, r *http.Requesif !ok {return}- if !h.requireAutopilotAccessManagement(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotAccessManagement(w, r, ap, workspaceID)+ if !ok {return}@@ -1283,14 +1450,11 @@ func (h *Handler) AddAutopilotCollaborator(w http.ResponseWriter, r *http.Requesreturn}- grantedBy, ok := requireUserID(w, r)- if !ok {- return- }- grantedByUUID, ok := parseUUIDOrBadRequest(w, grantedBy, "granted_by")- if !ok {- 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+ // the owner of the machine the request came from (MUL-7108).+ grantedByUUID := actor.UserID+ grantedBy := uuidToString(grantedByUUID)if _, err := h.Queries.AddAutopilotCollaborator(r.Context(), db.AddAutopilotCollaboratorParams{AutopilotID: ap.ID,@@ -1321,7 +1485,8 @@ func (h *Handler) RemoveAutopilotCollaborator(w http.ResponseWriter, r *http.Reqif !ok {return}- if !h.requireAutopilotAccessManagement(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotAccessManagement(w, r, ap, workspaceID)+ if !ok {return}targetUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")@@ -1338,8 +1503,7 @@ func (h *Handler) RemoveAutopilotCollaborator(w http.ResponseWriter, r *http.Reqreturn}- actor := requestUserID(r)- h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", actor, map[string]any{+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", uuidToString(actor.UserID), map[string]any{"autopilot_id": uuidToString(ap.ID),})h.writeAutopilotCollaborators(w, r, ap.ID, http.StatusOK)@@ -1355,7 +1519,8 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)if !ok {return}- if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)+ if !ok {return}// A new trigger changes what / when the rule fires — a substantive publish, so@@ -1364,11 +1529,14 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)// paths can write the version inside the same tx as the INSERT — a failed// version write must roll the trigger back, never leave future dispatches// attributed to the previous publisher.- userID, ok := requireUserID(w, r)- if !ok {- return- }- publisherID := parseUUID(userID)+ //+ // This is the most consequential stamp on the surface: the trigger's+ // created_by is the immutable AUTHORIZATION principal every future firing+ // acts as (MUL-6951). Taking it from the acting member is what stops an agent+ // from minting a standing, permanent execution right for its runtime owner+ // out of a one-off request (MUL-7108).+ publisherID := actor.UserID+ userID := uuidToString(publisherID)var req CreateAutopilotTriggerRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {@@ -1475,7 +1643,7 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)resp := h.triggerToResponse(trigger)h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{"autopilot_id": uuidToString(ap.ID),- "trigger": resp,+ "trigger": broadcastAutopilotTriggerResponse(resp),})writeJSON(w, http.StatusCreated, resp)return@@ -1527,7 +1695,7 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)resp := h.triggerToResponse(trigger)h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{"autopilot_id": uuidToString(ap.ID),- "trigger": resp,+ "trigger": broadcastAutopilotTriggerResponse(resp),})writeJSON(w, http.StatusCreated, resp)}@@ -1714,7 +1882,8 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)if !ok {return}- if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)+ if !ok {return}@@ -1819,10 +1988,7 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)params.NextRunAt = pgtype.Timestamptz{Time: t, Valid: true}}- userID, ok := requireUserID(w, r)- if !ok {- return- }+ userID := uuidToString(actor.UserID)tx, err := h.TxStarter.Begin(r.Context())if err != nil {@@ -1850,7 +2016,7 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)prev.Timezone != trigger.Timezone ||!bytes.Equal(prev.EventFilters, trigger.EventFilters)if triggerSubstantiveChange {- if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", parseUUID(userID)); err != nil {+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", actor.UserID); err != nil {writeError(w, http.StatusInternalServerError, "failed to update trigger")return}@@ -1860,7 +2026,7 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)if err := qtx.SetAutopilotTriggerPublisher(r.Context(), db.SetAutopilotTriggerPublisherParams{ID: trigger.ID,PublishedByType: pgtype.Text{String: "member", Valid: true},- PublishedByID: parseUUID(userID),+ PublishedByID: actor.UserID,}); err != nil {writeError(w, http.StatusInternalServerError, "failed to update trigger")return@@ -1874,7 +2040,7 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)resp := h.triggerToResponse(trigger)h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{"autopilot_id": uuidToString(ap.ID),- "trigger": resp,+ "trigger": broadcastAutopilotTriggerResponse(resp),})writeJSON(w, http.StatusOK, resp)}@@ -1905,7 +2071,8 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusNotFound, "autopilot not found")return}- if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)+ if !ok {return}@@ -1915,10 +2082,7 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)return}- userID, ok := requireUserID(w, r)- if !ok {- return- }+ userID := uuidToString(actor.UserID)// Removing a trigger changes what fires — a substantive publish (MUL-4302 §3.4).// Republish the rule version with this member as publisher, atomically with the@@ -1935,7 +2099,7 @@ func (h *Handler) DeleteAutopilotTrigger(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusInternalServerError, "failed to delete trigger")return}- if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", parseUUID(userID)); err != nil {+ if err := h.recordAutopilotRuleVersion(r.Context(), qtx, ap, "member", actor.UserID); err != nil {writeError(w, http.StatusInternalServerError, "failed to delete trigger")return}@@ -1964,7 +2128,8 @@ func (h *Handler) RotateAutopilotTriggerWebhookToken(w http.ResponseWriter, r *hif !ok {return}- if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)+ if !ok {return}@@ -2007,10 +2172,9 @@ func (h *Handler) RotateAutopilotTriggerWebhookToken(w http.ResponseWriter, r *h}resp := h.triggerToResponse(rotated)- userID, _ := requireUserID(w, r)- h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", uuidToString(actor.UserID), map[string]any{"autopilot_id": uuidToString(ap.ID),- "trigger": resp,+ "trigger": broadcastAutopilotTriggerResponse(resp),})writeJSON(w, http.StatusOK, resp)}@@ -2033,7 +2197,8 @@ func (h *Handler) SetAutopilotTriggerSigningSecret(w http.ResponseWriter, r *httif !ok {return}- if !h.requireAutopilotWrite(w, r, ap, workspaceID) {+ actor, ok := h.requireAutopilotWrite(w, r, ap, workspaceID)+ if !ok {return}triggerUUID, ok := parseUUIDOrBadRequest(w, triggerID, "trigger id")@@ -2075,13 +2240,13 @@ func (h *Handler) SetAutopilotTriggerSigningSecret(w http.ResponseWriter, r *htt}resp := h.triggerToResponse(updated)- userID, _ := requireUserID(w, r)// Publish the trigger update so the UI can refresh the has_signing_secret// badge in real time. The event payload only carries the response shape,- // which excludes the secret.- h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{+ // which excludes the signing secret and, on the broadcast copy, the webhook+ // credential as well.+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", uuidToString(actor.UserID), map[string]any{"autopilot_id": uuidToString(ap.ID),- "trigger": resp,+ "trigger": broadcastAutopilotTriggerResponse(resp),})writeJSON(w, http.StatusOK, resp)}@@ -2171,66 +2336,30 @@ func (h *Handler) GetAutopilotRun(w http.ResponseWriter, r *http.Request) {// ── Manual trigger ──────────────────────────────────────────────────────────-// Machine-readable codes for the two ways a manual trigger can be refused. The-// CLI keys its actionable output on these rather than on the English sentence,-// which is what lets a refusal survive translation and copy edits.-const (- autopilotTriggerNoOriginatorCode = "autopilot_trigger_no_originator"- autopilotTriggerForbiddenCode = "autopilot_trigger_forbidden"-)-// requireAutopilotTriggerInvoker resolves the human whose authority a manual// "run now" spends and enforces that they may spend it. It is this endpoint's// ONLY write gate — requireAutopilotWrite is deliberately not called alongside-// it. On refusal it writes 403 and returns false; the caller must return early.-//-// A member acts for themselves. An agent — the CLI running inside a task, or an-// A2A call — acts for its run's ORIGINATOR, the top-of-chain human. That is how-// every other invoke surface in the codebase judges an agent actor (MUL-3963 /-// canInvokeAgent), including this file's own private-leader gate on save.-//-// Judging the request's authenticated user instead resolves the RUNTIME OWNER-// under a task token (middleware/auth.go stamps the token's bound user), which-// is wrong in both directions. Too broad: it makes every agent a standing proxy-// for its machine's owner, so anyone who can talk to the agent inherits that-// owner's autopilot rights. Too narrow: keeping it as an ADDITIONAL condition-// would refuse a member who may trigger this autopilot themselves merely because-// the agent they asked happens to run on a third party's machine — the run would-// then need two unrelated humans to hold the same grant, which is not what "act-// for the ordering human" means and not what was decided for #8078. Workspace-// tenancy for the authenticated caller is already enforced by the router's-// RequireWorkspaceMember middleware, so dropping the second check loses no-// isolation.+// it, since both now judge the same human and requiring the grant twice would+// mean requiring it of two unrelated people (#8099, and see+// requireAutopilotActingMember for why the runtime owner is not one of them).+// On refusal it writes 403 and returns false; the caller must return early.//-// No resolvable human → refuse. The alternative considered was the workspace-broad-// exception invokeAgentDecision grants unattributed agent/system principals on a-// public_to-workspace agent, which would have admitted an originator-less chain-// here too. Rejected (Bohan's ruling on #8078): a manual trigger is by definition-// somebody's decision, and a chain reaching this gate with no human at its top-// means something upstream dropped it — that should surface, not be papered over.-func (h *Handler) requireAutopilotTriggerInvoker(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID, actorType, actorID string) (pgtype.UUID, bool) {- invoker := h.invokeOriginatorFromRequest(r, actorType, actorID)- invokerUserID, err := util.ParseUUID(invoker)- if invoker == "" || err != nil {- // Distinct from the permission refusal below: nothing was denied, there- // was simply nobody to judge. It carries its own code because it is the- // one refusal here a workspace can act on, and because the- // operator-visible half of #8078 was a message describing a trigger row- // that a manual run never has.- writeErrorCode(w, http.StatusForbidden, autopilotTriggerNoOriginatorCode,- "no human authorized this trigger: the calling run records no originator")+// The refusals keep their own codes: FormatError collapses every other 403 into+// generic "no access" copy, and these two are the ones an operator can act on —+// the CLI branches on them by code, never on the English sentence (#8078).+func (h *Handler) requireAutopilotTriggerInvoker(w http.ResponseWriter, r *http.Request, ap db.Autopilot, workspaceID string) (pgtype.UUID, bool) {+ member, ok := h.requireAutopilotActingMember(w, r, workspaceID, autopilotTriggerRefusal)+ if !ok {return pgtype.UUID{}, false}- member, err := h.getWorkspaceMember(r.Context(), invoker, workspaceID)- if err != nil || !h.memberCanWriteAutopilot(r.Context(), ap, member) {+ if !h.memberCanWriteAutopilot(r.Context(), ap, member) {// Deliberately the same sentence and code whether the ordering human is// a non-member or simply lacks the grant: a caller must not be able to// probe workspace membership through this endpoint.- writeErrorCode(w, http.StatusForbidden, autopilotTriggerForbiddenCode,- "only the autopilot creator, a workspace admin, or a granted collaborator can trigger this autopilot")+ writeErrorCode(w, http.StatusForbidden, autopilotTriggerRefusal.forbiddenCode, autopilotTriggerRefusal.forbiddenMsg)return pgtype.UUID{}, false}- return invokerUserID, true+ return member.UserID, true}func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {@@ -2242,17 +2371,11 @@ func (h *Handler) TriggerAutopilot(w http.ResponseWriter, r *http.Request) {return}// A manual "run now" is a direct human action, so the run is attributed- // direct_human to the human who authorized it (MUL-4302 §4). Resolve the actor- // the same way assign/promote does, then resolve the human that actor acts FOR- // — see requireAutopilotTriggerInvoker, which is this endpoint's only write- // gate. Authorization runs before the status check so an unauthorized caller- // cannot tell an inactive autopilot from an active one.- userID, ok := requireUserID(w, r)- if !ok {- return- }- actorType, actorID := h.resolveActor(r, userID, workspaceID)- invokerUserID, ok := h.requireAutopilotTriggerInvoker(w, r, autopilot, workspaceID, actorType, actorID)+ // direct_human to the human who authorized it (MUL-4302 §4) — the human this+ // caller acts for, see requireAutopilotTriggerInvoker, which is this+ // endpoint's only write gate. Authorization runs before the status check so an+ // unauthorized caller cannot tell an inactive autopilot from an active one.+ invokerUserID, ok := h.requireAutopilotTriggerInvoker(w, r, autopilot, workspaceID)if !ok {return}diff --git a/server/internal/handler/autopilot_acting_member_test.go b/server/internal/handler/autopilot_acting_member_test.gonew file mode 100644index 0000000000..654b656ac1--- /dev/null+++ b/server/internal/handler/autopilot_acting_member_test.go@@ -0,0 +1,552 @@+package handler++import (+ "fmt"+ "net/http"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// Every write on the autopilot surface is judged as the human it acts FOR — the+// caller themselves for a member, the run's ORIGINATOR for an agent — never as+// the runtime owner whose task token authenticated the request (MUL-7108).+//+// The escalation these tests exist for: a task token carries its runtime's+// OWNER as X-User-ID (daemon.go mints it from rt.OwnerID), so judging the+// authenticated user made every agent a standing proxy for its machine's owner.+// A member with no grant could @ an agent running on an admin's machine and have+// it pause the autopilot, re-point a webhook, or grant themselves a+// collaborator row — none of which they could do in the UI.+//+// TriggerAutopilot's half of this rule landed first (#8099) and keeps its own+// tests in autopilot_manual_trigger_invoker_test.go, including the code-level+// assertions on its distinct refusal codes.++// actingCaller is who a request comes from on the wire. agentID == "" is a+// member calling the API directly; otherwise it is the CLI speaking from inside+// a task, authenticated as authUserID (the runtime owner) but stamped by the+// auth middleware as a task-token actor.+type actingCaller struct {+ authUserID string+ agentID string+ taskID string+}++func (c actingCaller) request(method, path string, body any) *http.Request {+ r := newRequestAs(c.authUserID, method, path, body)+ if c.agentID != "" {+ r.Header.Set("X-Actor-Source", "task_token")+ r.Header.Set("X-Agent-ID", c.agentID)+ r.Header.Set("X-Task-ID", c.taskID)+ }+ return r+}++// actingFixture is one autopilot owned outright by orderingHuman — a plain+// member who is its creator and therefore its only non-admin writer — with the+// trigger rows the per-trigger endpoints need.+type actingFixture struct {+ autopilotID string+ agentID string+ orderingHuman string+ scheduleTriggerID string+ webhookTriggerID string+ grantTarget string+}++func newActingFixture(t *testing.T, label string) actingFixture {+ t.Helper()++ var agentID string+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)++ orderingHuman := plainMember(t, "ordering-human")+ title := fmt.Sprintf("acting member %s %d", label, time.Now().UnixNano())+ autopilotID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID,+ "title": title,+ "assignee_id": agentID,+ "assignee_type": "agent",+ "execution_mode": "create_issue",+ "issue_title_template": title,+ "status": "active",+ "created_by_type": "member",+ "created_by_id": orderingHuman,+ })+ // Rows the handlers themselves write, which dbfx cannot register: cleanup+ // runs in reverse registration order, so these go before the autopilot.+ dbfx.Cleanup(t, `DELETE FROM autopilot_rule_version WHERE autopilot_id = $1`, autopilotID)+ dbfx.Cleanup(t, `DELETE FROM autopilot_collaborator WHERE autopilot_id = $1`, autopilotID)+ dbfx.Cleanup(t, `DELETE FROM autopilot_trigger WHERE autopilot_id = $1`, autopilotID)++ trigger := func(kind string, over testutil.Cols) string {+ cols := testutil.Cols{+ "autopilot_id": autopilotID,+ "kind": kind,+ "enabled": true,+ "created_by_type": "member",+ "created_by_id": orderingHuman,+ "published_by_type": "member",+ "published_by_id": orderingHuman,+ }+ for k, v := range over {+ cols[k] = v+ }+ return dbfx.Insert(t, "autopilot_trigger", cols)+ }++ return actingFixture{+ autopilotID: autopilotID,+ agentID: agentID,+ orderingHuman: orderingHuman,+ scheduleTriggerID: trigger("schedule", testutil.Cols{+ "cron_expression": "0 9 * * *",+ "timezone": "UTC",+ }),+ webhookTriggerID: trigger("webhook", testutil.Cols{+ "provider": "generic",+ "webhook_token": fmt.Sprintf("tok_%d", time.Now().UnixNano()),+ }),+ grantTarget: plainMember(t, "grant-target"),+ }+}++// autopilotWriteEndpoint is one mutating endpoint behind requireAutopilotWrite+// or requireAutopilotAccessManagement. wantAdmitted is what the endpoint answers+// once the gate lets the request through — the assertion is on the gate, so a+// non-403 that proves admission is enough where the success path costs more+// setup than it is worth.+type autopilotWriteEndpoint struct {+ name string+ wantAdmitted int+ send func(fx actingFixture, c actingCaller) *http.Request+ handler func(w http.ResponseWriter, r *http.Request)+}++func autopilotWriteEndpoints() []autopilotWriteEndpoint {+ ws := "?workspace_id=" + testWorkspaceID+ return []autopilotWriteEndpoint{+ {+ name: "update-autopilot",+ wantAdmitted: http.StatusOK,+ handler: testHandler.UpdateAutopilot,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("PATCH", "/api/autopilots/"+fx.autopilotID+ws,+ map[string]any{"status": "paused"}), "id", fx.autopilotID)+ },+ },+ {+ name: "delete-autopilot",+ wantAdmitted: http.StatusNoContent,+ handler: testHandler.DeleteAutopilot,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("DELETE", "/api/autopilots/"+fx.autopilotID+ws, nil),+ "id", fx.autopilotID)+ },+ },+ {+ name: "replay-delivery",+ // Admission lands on "delivery not found" for a delivery id that+ // never existed: the gate ran, and building a real delivery row+ // would test the replay path rather than the gate.+ wantAdmitted: http.StatusNotFound,+ handler: testHandler.ReplayAutopilotDelivery,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ deliveryID := uuid.NewString()+ return withURLParams(c.request("POST",+ "/api/autopilots/"+fx.autopilotID+"/deliveries/"+deliveryID+"/replay"+ws, nil),+ "id", fx.autopilotID, "deliveryId", deliveryID)+ },+ },+ {+ name: "create-trigger",+ wantAdmitted: http.StatusCreated,+ handler: testHandler.CreateAutopilotTrigger,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("POST", "/api/autopilots/"+fx.autopilotID+"/triggers"+ws,+ map[string]any{"kind": "schedule", "cron_expression": "0 10 * * *", "timezone": "UTC"}),+ "id", fx.autopilotID)+ },+ },+ {+ name: "update-trigger",+ wantAdmitted: http.StatusOK,+ handler: testHandler.UpdateAutopilotTrigger,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("PATCH",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.scheduleTriggerID+ws,+ map[string]any{"enabled": false}),+ "id", fx.autopilotID, "triggerId", fx.scheduleTriggerID)+ },+ },+ {+ name: "delete-trigger",+ wantAdmitted: http.StatusNoContent,+ handler: testHandler.DeleteAutopilotTrigger,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("DELETE",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.scheduleTriggerID+ws, nil),+ "id", fx.autopilotID, "triggerId", fx.scheduleTriggerID)+ },+ },+ {+ name: "rotate-webhook-token",+ wantAdmitted: http.StatusOK,+ handler: testHandler.RotateAutopilotTriggerWebhookToken,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("POST",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.webhookTriggerID+"/rotate-token"+ws, nil),+ "id", fx.autopilotID, "triggerId", fx.webhookTriggerID)+ },+ },+ {+ name: "set-signing-secret",+ wantAdmitted: http.StatusOK,+ handler: testHandler.SetAutopilotTriggerSigningSecret,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("PUT",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.webhookTriggerID+"/signing-secret"+ws,+ map[string]any{"signing_secret": "0123456789abcdef"}),+ "id", fx.autopilotID, "triggerId", fx.webhookTriggerID)+ },+ },+ {+ name: "add-collaborator",+ wantAdmitted: http.StatusCreated,+ handler: testHandler.AddAutopilotCollaborator,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("POST", "/api/autopilots/"+fx.autopilotID+"/collaborators"+ws,+ map[string]any{"user_id": fx.grantTarget}), "id", fx.autopilotID)+ },+ },+ {+ name: "remove-collaborator",+ wantAdmitted: http.StatusOK,+ handler: testHandler.RemoveAutopilotCollaborator,+ send: func(fx actingFixture, c actingCaller) *http.Request {+ return withURLParams(c.request("DELETE",+ "/api/autopilots/"+fx.autopilotID+"/collaborators/"+fx.grantTarget+ws, nil),+ "id", fx.autopilotID, "userId", fx.grantTarget)+ },+ },+ }+}++// TestAutopilotWrites_JudgeTheActingHuman runs every write endpoint through the+// four cases that define the rule. The two agent-caller cases are deliberately+// cross-identity: the ordering human and the runtime owner hold OPPOSITE+// permissions in each, so neither outcome can be explained by the request's+// authenticated user.+func TestAutopilotWrites_JudgeTheActingHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ for _, ep := range autopilotWriteEndpoints() {+ t.Run(ep.name, func(t *testing.T) {+ t.Run("ordering human holds the grant", func(t *testing.T) {+ fx := newActingFixture(t, ep.name+" admitted")+ // The machine belongs to a plain member with no grant on this+ // autopilot, so only the ordering human's authority can carry+ // this request.+ caller := actingCaller{+ authUserID: plainMember(t, "machine-owner"),+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, fx.orderingHuman),+ }+ testutil.Call(t, ep.handler, ep.send(fx, caller)).Want(ep.wantAdmitted)+ })++ t.Run("ordering human holds nothing", func(t *testing.T) {+ fx := newActingFixture(t, ep.name+" refused")+ // Authenticated as the workspace owner, who DOES hold write+ // here — so a pass could only come from judging the token's+ // bound user, which is the escalation itself.+ caller := actingCaller{+ authUserID: testUserID,+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, plainMember(t, "outsider")),+ }+ var body triggerErrorBody+ testutil.Call(t, ep.handler, ep.send(fx, caller)).Want(http.StatusForbidden).JSON(&body)+ if body.Code != autopilotForbiddenCode {+ t.Errorf("error code = %q, want %q", body.Code, autopilotForbiddenCode)+ }+ })++ t.Run("no ordering human at all", func(t *testing.T) {+ fx := newActingFixture(t, ep.name+" unattributed")+ caller := actingCaller{+ authUserID: testUserID,+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, ""),+ }+ var body triggerErrorBody+ testutil.Call(t, ep.handler, ep.send(fx, caller)).Want(http.StatusForbidden).JSON(&body)+ // Its own code: nothing was denied, there was nobody to judge —+ // the one refusal here a workspace can act on.+ if body.Code != autopilotNoOriginatorCode {+ t.Errorf("error code = %q, want %q", body.Code, autopilotNoOriginatorCode)+ }+ })++ t.Run("member calling directly", func(t *testing.T) {+ // The half that was never broken, and must stay unbroken: a+ // member is judged as themselves, with no originator lookup in+ // the way.+ fx := newActingFixture(t, ep.name+" member")+ testutil.Call(t, ep.handler, ep.send(fx, actingCaller{authUserID: testUserID})).Want(ep.wantAdmitted)+ })+ })+ }+}++// TestCreateAutopilot_StampsTheOrderingHuman covers the create endpoint, which+// has no autopilot to check a grant against but stamps the most important+// identity on the surface: created_by IS the autopilot's write grant.+//+// Stamping the runtime owner would both hand that owner a grant nobody gave+// them and lock the requesting member out of the autopilot they just asked for —+// the gate would then refuse them every later edit, because they are neither+// creator nor collaborator. The gate and the stamp have to name one person.+func TestCreateAutopilot_StampsTheOrderingHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ var agentID string+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)+ orderingHuman := plainMember(t, "creating-human")+ title := fmt.Sprintf("acting member create %d", time.Now().UnixNano())++ // Authenticated as the workspace owner; ordered by a plain member.+ caller := actingCaller{+ authUserID: testUserID,+ agentID: agentID,+ taskID: callerTask(t, agentID, orderingHuman),+ }+ var ap AutopilotResponse+ testutil.Call(t, testHandler.CreateAutopilot, caller.request("POST", "/api/autopilots?workspace_id="+testWorkspaceID,+ map[string]any{+ "title": title,+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ "issue_title_template": title,+ })).Want(http.StatusCreated).JSON(&ap)+ dbfx.Cleanup(t, `DELETE FROM autopilot_rule_version WHERE autopilot_id = $1`, ap.ID)+ dbfx.Cleanup(t, `DELETE FROM autopilot WHERE id = $1`, ap.ID)++ var createdBy string+ dbfx.QueryRow(t, `SELECT created_by_id FROM autopilot WHERE id = $1`, ap.ID).Scan(&createdBy)+ if createdBy != orderingHuman {+ t.Fatalf("created_by_id = %s, want the ordering human %s (runtime owner is %s)", createdBy, orderingHuman, testUserID)+ }+ var publishedBy string+ dbfx.QueryRow(t, `SELECT published_by_id FROM autopilot_rule_version WHERE autopilot_id = $1 ORDER BY created_at ASC LIMIT 1`, ap.ID).Scan(&publishedBy)+ if publishedBy != orderingHuman {+ t.Errorf("rule version published_by_id = %s, want the ordering human %s", publishedBy, orderingHuman)+ }++ // The whole point of stamping the same human the gate judges: the member who+ // asked for this autopilot can go on editing it through the agent.+ editCaller := actingCaller{+ authUserID: plainMember(t, "another-machine-owner"),+ agentID: agentID,+ taskID: callerTask(t, agentID, orderingHuman),+ }+ testutil.Call(t, testHandler.UpdateAutopilot, withURLParams(+ editCaller.request("PATCH", "/api/autopilots/"+ap.ID+"?workspace_id="+testWorkspaceID,+ map[string]any{"status": "paused"}), "id", ap.ID)).Want(http.StatusOK)+}++// TestCreateAutopilot_NoOrderingHumanRefused: an autopilot created with nobody+// behind it would have a NULL-equivalent creator and no accountable human at+// dispatch time, which is exactly the state MUL-4302 §3.4 exists to prevent.+func TestCreateAutopilot_NoOrderingHumanRefused(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ var agentID string+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)+ title := fmt.Sprintf("acting member create unattributed %d", time.Now().UnixNano())+ caller := actingCaller{+ authUserID: testUserID,+ agentID: agentID,+ taskID: callerTask(t, agentID, ""),+ }++ var body triggerErrorBody+ testutil.Call(t, testHandler.CreateAutopilot, caller.request("POST", "/api/autopilots?workspace_id="+testWorkspaceID,+ map[string]any{+ "title": title,+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ })).Want(http.StatusForbidden).JSON(&body)+ if body.Code != autopilotNoOriginatorCode {+ t.Errorf("error code = %q, want %q", body.Code, autopilotNoOriginatorCode)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM autopilot WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title); n != 0 {+ t.Errorf("autopilot rows = %d, want 0 — the refusal must land before the insert", n)+ }+}++// TestCreateAutopilot_OrderingHumanMustBeAWorkspaceMember covers create's own+// refusal. It is a different fact from the other endpoints' "you hold no grant+// on this autopilot" — there is no autopilot yet — so it carries its own code:+// telling someone to ask for a collaborator grant would send them after+// something that could not help (MUL-7108).+func TestCreateAutopilot_OrderingHumanMustBeAWorkspaceMember(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ var agentID string+ dbfx.QueryRow(t, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID)+ // A user of the platform, but not of THIS workspace — the shape an+ // originator has after leaving it.+ stranger := dbfx.User(t, "Autopilot Stranger", fmt.Sprintf("autopilot-stranger-%[email protected]", time.Now().UnixNano()))+ title := fmt.Sprintf("acting member create stranger %d", time.Now().UnixNano())++ caller := actingCaller{+ authUserID: testUserID,+ agentID: agentID,+ taskID: callerTask(t, agentID, stranger),+ }+ var body triggerErrorBody+ testutil.Call(t, testHandler.CreateAutopilot, caller.request("POST", "/api/autopilots?workspace_id="+testWorkspaceID,+ map[string]any{+ "title": title,+ "assignee_id": agentID,+ "execution_mode": "create_issue",+ })).Want(http.StatusForbidden).JSON(&body)+ if body.Code != autopilotActorNotMemberCode {+ t.Errorf("error code = %q, want %q", body.Code, autopilotActorNotMemberCode)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM autopilot WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title); n != 0 {+ t.Errorf("autopilot rows = %d, want 0", n)+ }+}++// TestCreateAutopilotTrigger_StampsTheOrderingHuman pins the durable half of the+// escalation. A trigger's created_by is the immutable authorization principal+// every future firing acts as (MUL-6951, "the run acts as this member forever"),+// so a trigger stamped with the runtime owner is not a one-off unauthorized+// edit — it is a standing execution right in that owner's name, minted by+// someone who holds nothing, and outliving the run that asked for it.+func TestCreateAutopilotTrigger_StampsTheOrderingHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ fx := newActingFixture(t, "trigger stamp")+ caller := actingCaller{+ authUserID: testUserID, // workspace owner: holds write, but is not who asked+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, fx.orderingHuman),+ }+ var trigger AutopilotTriggerResponse+ testutil.Call(t, testHandler.CreateAutopilotTrigger, withURLParams(+ caller.request("POST", "/api/autopilots/"+fx.autopilotID+"/triggers?workspace_id="+testWorkspaceID,+ map[string]any{"kind": "schedule", "cron_expression": "0 11 * * *", "timezone": "UTC"}),+ "id", fx.autopilotID)).Want(http.StatusCreated).JSON(&trigger)++ var createdBy, publishedBy string+ dbfx.QueryRow(t, `SELECT created_by_id, published_by_id FROM autopilot_trigger WHERE id = $1`, trigger.ID).+ Scan(&createdBy, &publishedBy)+ if createdBy != fx.orderingHuman {+ t.Fatalf("trigger created_by_id = %s, want the ordering human %s — every future firing acts as this member",+ createdBy, fx.orderingHuman)+ }+ if publishedBy != fx.orderingHuman {+ t.Errorf("trigger published_by_id = %s, want the ordering human %s", publishedBy, fx.orderingHuman)+ }+}++// TestAddAutopilotCollaborator_GrantedByIsTheOrderingHuman: a grant is the+// longest-lived write here — it shows up in the access UI and survives the run+// that made it — so its audit column must name the human who authorized it.+func TestAddAutopilotCollaborator_GrantedByIsTheOrderingHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ fx := newActingFixture(t, "grant stamp")+ caller := actingCaller{+ authUserID: plainMember(t, "machine-owner"),+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, fx.orderingHuman),+ }+ testutil.Call(t, testHandler.AddAutopilotCollaborator, withURLParams(+ caller.request("POST", "/api/autopilots/"+fx.autopilotID+"/collaborators?workspace_id="+testWorkspaceID,+ map[string]any{"user_id": fx.grantTarget}), "id", fx.autopilotID)).Want(http.StatusCreated)++ var grantedBy string+ dbfx.QueryRow(t, `SELECT granted_by FROM autopilot_collaborator WHERE autopilot_id = $1 AND user_id = $2`,+ fx.autopilotID, fx.grantTarget).Scan(&grantedBy)+ if grantedBy != fx.orderingHuman {+ t.Errorf("granted_by = %s, want the ordering human %s", grantedBy, fx.orderingHuman)+ }+}++// TestGetAutopilot_WebhookTokenFollowsTheActingHuman closes the door the write+// gates leave open on their own. A webhook token IS a trigger — the built-in+// skill says so in as many words — and it is handed out on the READ path, gated+// by the same can_write predicate. Judging the authenticated user there would+// let an agent read its runtime owner's tokens and fire the autopilot from+// outside the permission system entirely, which no write gate would ever see.+func TestGetAutopilot_WebhookTokenFollowsTheActingHuman(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ fx := newActingFixture(t, "token exposure")+ get := func(c actingCaller) (bool, bool) {+ t.Helper()+ var got struct {+ Autopilot AutopilotResponse `json:"autopilot"`+ Triggers []AutopilotTriggerResponse `json:"triggers"`+ }+ testutil.Call(t, testHandler.GetAutopilot, withURLParams(+ c.request("GET", "/api/autopilots/"+fx.autopilotID+"?workspace_id="+testWorkspaceID, nil),+ "id", fx.autopilotID)).Want(http.StatusOK).JSON(&got)+ tokenVisible := false+ for _, tr := range got.Triggers {+ if tr.WebhookToken != nil {+ tokenVisible = true+ }+ }+ return got.Autopilot.CanWrite != nil && *got.Autopilot.CanWrite, tokenVisible+ }++ // Authenticated as the workspace owner, who may read these tokens; ordered+ // by a member who may not.+ canWrite, tokenVisible := get(actingCaller{+ authUserID: testUserID,+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, plainMember(t, "token-outsider")),+ })+ if canWrite || tokenVisible {+ t.Errorf("can_write = %v, webhook token visible = %v; want both false — the token would be a trigger the write gates never see",+ canWrite, tokenVisible)+ }++ // The ordering human owns this autopilot, so the same request is a writer's+ // read and the token comes back.+ canWrite, tokenVisible = get(actingCaller{+ authUserID: plainMember(t, "machine-owner"),+ agentID: fx.agentID,+ taskID: callerTask(t, fx.agentID, fx.orderingHuman),+ })+ if !canWrite || !tokenVisible {+ t.Errorf("can_write = %v, webhook token visible = %v; want both true for the autopilot's own creator", canWrite, tokenVisible)+ }++ // A member reading directly is judged as themselves, unchanged.+ if canWrite, _ := get(actingCaller{authUserID: testUserID}); !canWrite {+ t.Error("can_write = false for the workspace owner reading directly; the member path must be unchanged")+ }+}diff --git a/server/internal/handler/autopilot_broadcast_redaction_test.go b/server/internal/handler/autopilot_broadcast_redaction_test.gonew file mode 100644index 0000000000..01fb46a69d--- /dev/null+++ b/server/internal/handler/autopilot_broadcast_redaction_test.go@@ -0,0 +1,136 @@+package handler++import (+ "net/http"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// A webhook token IS a trigger: whoever holds it fires the autopilot through+// the public ingress route, outside the permission system. That is why+// GetAutopilot redacts it for non-writers — but `autopilot:updated` fans out to+// the WHOLE workspace room, so publishing the live trigger response handed every+// member exactly what the read path had just refused them, through a push no+// write gate ever sees.+//+// The leak predates MUL-7108 but is the same authorization bypass, so it is+// closed with it. The fix follows the rule broadcastAgentResponse already+// established for agents: the HTTP caller keeps the live value, the broadcast+// copy carries none.+func TestAutopilotTriggerBroadcastsCarryNoWebhookCredential(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ fx := newActingFixture(t, "broadcast redaction")+ ws := "?workspace_id=" + testWorkspaceID+ // The workspace owner is a writer here, so every call below is authorized:+ // what is under test is what the FANOUT carries, not who may make the call.+ writer := actingCaller{authUserID: testUserID}++ // The bus is synchronous, so the event for a request has been recorded by+ // the time the handler returns. Filtering on this autopilot keeps the+ // assertion deterministic even if another test publishes on the same topic.+ var mu sync.Mutex+ var broadcasts []AutopilotTriggerResponse+ testHandler.Bus.Subscribe(protocol.EventAutopilotUpdated, func(e events.Event) {+ payload, ok := e.Payload.(map[string]any)+ if !ok || payload["autopilot_id"] != fx.autopilotID {+ return+ }+ trigger, ok := payload["trigger"].(AutopilotTriggerResponse)+ if !ok {+ return+ }+ mu.Lock()+ broadcasts = append(broadcasts, trigger)+ mu.Unlock()+ })+ lastBroadcast := func(t *testing.T) AutopilotTriggerResponse {+ t.Helper()+ mu.Lock()+ defer mu.Unlock()+ if len(broadcasts) == 0 {+ t.Fatal("no autopilot:updated event was published; the UI would never refetch")+ }+ return broadcasts[len(broadcasts)-1]+ }++ cases := []struct {+ name string+ request func() *http.Request+ handler func(w http.ResponseWriter, r *http.Request)+ want int+ }{+ {+ name: "create-webhook-trigger",+ want: http.StatusCreated,+ handler: testHandler.CreateAutopilotTrigger,+ request: func() *http.Request {+ return withURLParams(writer.request("POST", "/api/autopilots/"+fx.autopilotID+"/triggers"+ws,+ map[string]any{"kind": "webhook", "label": "ci"}), "id", fx.autopilotID)+ },+ },+ {+ name: "update-trigger",+ want: http.StatusOK,+ handler: testHandler.UpdateAutopilotTrigger,+ request: func() *http.Request {+ return withURLParams(writer.request("PATCH",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.webhookTriggerID+ws,+ map[string]any{"enabled": false}),+ "id", fx.autopilotID, "triggerId", fx.webhookTriggerID)+ },+ },+ {+ name: "rotate-webhook-token",+ want: http.StatusOK,+ handler: testHandler.RotateAutopilotTriggerWebhookToken,+ request: func() *http.Request {+ return withURLParams(writer.request("POST",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.webhookTriggerID+"/rotate-token"+ws, nil),+ "id", fx.autopilotID, "triggerId", fx.webhookTriggerID)+ },+ },+ {+ name: "set-signing-secret",+ want: http.StatusOK,+ handler: testHandler.SetAutopilotTriggerSigningSecret,+ request: func() *http.Request {+ return withURLParams(writer.request("PUT",+ "/api/autopilots/"+fx.autopilotID+"/triggers/"+fx.webhookTriggerID+"/signing-secret"+ws,+ map[string]any{"signing_secret": "0123456789abcdef"}),+ "id", fx.autopilotID, "triggerId", fx.webhookTriggerID)+ },+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ var resp AutopilotTriggerResponse+ testutil.Call(t, tc.handler, tc.request()).Want(tc.want).JSON(&resp)+ // The authorized caller still gets the live credential; without+ // this the redaction assertion below would pass on an endpoint+ // that had simply stopped issuing tokens.+ if resp.WebhookToken == nil || *resp.WebhookToken == "" {+ t.Fatalf("HTTP response carries no webhook token; the broadcast assertion would prove nothing")+ }++ event := lastBroadcast(t)+ if event.WebhookToken != nil || event.WebhookPath != nil || event.WebhookURL != nil {+ t.Errorf("broadcast leaked the webhook credential: token=%v path=%v url=%v — every workspace member receives this event",+ derefStr(event.WebhookToken), derefStr(event.WebhookPath), derefStr(event.WebhookURL))+ }+ // The event must still identify what changed: clients react by+ // refetching through the authenticated detail endpoint, which is+ // what makes carrying no secret free.+ if event.ID == "" {+ t.Error("broadcast carries no trigger id; clients cannot tell what to refetch")+ }+ })+ }+}diff --git a/server/internal/handler/chat_history.go b/server/internal/handler/chat_history.goindex 80a808e7e8..aba295ac9d 100644--- a/server/internal/handler/chat_history.go+++ b/server/internal/handler/chat_history.go@@ -214,11 +214,15 @@ func (h *Handler) GetChatThread(w http.ResponseWriter, r *http.Request) {}// chatHistorySession authorizes the request and returns the caller's own chat-// session. It is authorized by the task-scoped token alone: middleware stamps-// the token's task into X-Actor-Source=task_token + X-Task-ID (a normal JWT /-// mul_ PAT leaves X-Actor-Source empty and does NOT strip a client-forged-// X-Task-ID), so requiring the task-token actor is load-bearing — without it a-// member could forge X-Task-ID and read another session's history.+// session. It is authorized by the task-scoped token alone: the auth middleware+// deletes client-supplied X-Actor-Source / X-Agent-ID / X-Task-ID from every+// request and re-stamps them only on the mat_ branch (MUL-3428), so a normal+// JWT / mul_ PAT arrives here carrying no task context at all.+//+// The actor check stays anyway, and stays load-bearing: this endpoint returns+// another member's chat history if its task binding is ever wrong, so it names+// the credential it requires rather than inheriting that guarantee silently+// from a middleware two layers away.type chatHistoryScope struct {sessionID pgtype.UUIDcontextRevision pgtype.Int8diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex c0acf26e5b..c96517806b 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1768,10 +1768,10 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {// task originator is unattributed, effectiveUser resolves to "", and the// private-agent gate denies the wake (MUL-4015).//- // The header is NOT client-chosen: the task token forces X-Task-ID and- // X-Agent-ID from its own row, and resolveActor rejects the JWT path unless- // the named task belongs to the named agent. So the stamp always records the- // authoring agent's own run.+ // The header is NOT client-chosen: the auth middleware deletes any+ // client-supplied X-Agent-ID / X-Task-ID and re-stamps both from the mat_+ // token's own row (MUL-3428). So the stamp always records the authoring+ // agent's own run.//// It is deliberately NOT scoped to that run's own issue (MUL-6490 / GH// #7328). A run that legitimately comments on ANOTHER issue — the ordinarydiff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 82bb0efa95..80ad685251 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -506,14 +506,13 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {if taskID := r.FormValue("task_id"); taskID != "" {// Authoritative task-token boundary (load-bearing, mirrors// chat_history.go:chatHistorySession). X-Task-ID is only trustworthy- // when the auth middleware set it from a task-scoped `mat_` token —- // that path is also the ONLY one that stamps X-Actor-Source=task_token- // and strips a client-forged X-Task-ID. A normal JWT / `mul_` PAT- // leaves X-Actor-Source empty and does NOT strip a forged X-Task-ID,- // and resolveActor's fallback will accept a real X-Agent-ID +- // X-Task-ID pair. So without this gate a member who learns a task ID- // could forge both headers and inject an attachment onto another chat- // task's assistant reply — a cross-session/privacy leak.+ // when the auth middleware set it from a task-scoped `mat_` token:+ // that is the only branch that stamps it, because the middleware+ // deletes any client-supplied agent/task identity first (MUL-3428).+ // The gate is kept explicit because of what it protects — an+ // attachment injected onto another chat task's assistant reply is a+ // cross-session privacy leak, and this endpoint should say which+ // credential it requires rather than rely on a distant strip.if r.Header.Get("X-Actor-Source") != "task_token" {writeError(w, http.StatusForbidden, "task_id upload is only available from within an agent task")returndiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 07e638063a..6edc70029f 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -823,21 +823,25 @@ func requestUserID(r *http.Request) string {// stripped by the agent process. This is the path MUL-2600 relies on to// reject agent-process traffic on owner-only endpoints.//-// Fallback signal (legacy CLI / member-token paths): the request MUST-// carry both X-Agent-ID and a valid X-Task-ID, and the task must belong-// to the claimed agent. Otherwise we fall back to "member".+// Fallback signal: the request MUST carry both X-Agent-ID and a valid+// X-Task-ID, and the task must belong to the claimed agent. Otherwise we+// fall back to "member".//-// X-Agent-ID alone is not trusted: any workspace member can guess or observe-// an agent's UUID, and a member-supplied X-Agent-ID would otherwise let that-// member impersonate the agent and bypass the private-agent gate (#2359-// review). The daemon always pairs the two headers, so requiring both has-// no effect on legitimate agent callers but closes the impersonation path.+// This fallback is NOT a security boundary and must not be read as one. Both+// ids are observable by any workspace member (GET /api/issues/{id}/task-runs+// returns the pair), so requiring both proves nothing on its own — the older+// comment here claimed it "closes the impersonation path", and it did not.+// What closes it is the Auth / DaemonAuth middleware stripping both headers+// from every client, leaving the mat_ branch as the only writer (MUL-3428).+// The fallback survives that strip only for in-process callers and handler+// unit tests, which set the headers directly.//// Returns ("agent", agentID) on success, ("member", userID) otherwise.func (h *Handler) resolveActor(r *http.Request, userID, workspaceID string) (actorType, actorID string) {if r.Header.Get("X-Actor-Source") == "task_token" {- // Server-set header — auth middleware also forced X-Agent-ID- // from the token row. Trust it directly without re-querying.+ // Server-set header — the auth middleware stripped whatever the+ // client sent and re-stamped X-Agent-ID from the token row. Trust+ // it directly without re-querying.return "agent", r.Header.Get("X-Agent-ID")}agentID := r.Header.Get("X-Agent-ID")diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex ba28af3e44..efeda7fbea 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -2959,13 +2959,13 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {// so resolveOriginatorForIssueTask can inherit its originator — the// same trick CreateComment uses with comment.source_task_id (MUL-4015).//- // The task id is taken from the SERVER-trusted X-Task-ID: resolveActor- // only returns creatorType=="agent" when either X-Actor-Source=task_token- // (the auth middleware bound X-Agent-ID/X-Task-ID from the mat_ token and- // stripped any client value) or the X-Agent-ID/X-Task-ID pair was- // validated against the DB. A member-forged X-Task-ID never reaches here- // because it would have resolved to creatorType=="member". We still- // re-check the task belongs to the acting agent before trusting it.+ // The task id is taken from the SERVER-trusted X-Task-ID: the auth+ // middleware deletes whatever the client sent and re-stamps+ // X-Agent-ID / X-Task-ID only from a validated mat_ token (MUL-3428), so+ // a member-forged pair never reaches here — it is gone before+ // resolveActor runs, and the request resolves to creatorType=="member".+ // We still re-check the task belongs to the acting agent before trusting+ // it.if taskIDHeader := r.Header.Get("X-Task-ID"); taskIDHeader != "" {if taskUUID, perr := util.ParseUUID(taskIDHeader); perr == nil {if task, terr := h.Queries.GetAgentTask(r.Context(), taskUUID); terr == nil && uuidToString(task.AgentID) == actualCreatorID {diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.goindex 1b11571d34..30423ee6bc 100644--- a/server/internal/handler/webhook_delivery.go+++ b/server/internal/handler/webhook_delivery.go@@ -243,7 +243,7 @@ func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Requestif !ok {return}- if !h.requireAutopilotWrite(w, r, autopilot, workspaceID) {+ if _, ok := h.requireAutopilotWrite(w, r, autopilot, workspaceID); !ok {return}original, ok := h.loadDeliveryForAutopilot(w, r, autopilot, deliveryID)diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.goindex ac028ffeb6..2551c448d8 100644--- a/server/internal/middleware/auth.go+++ b/server/internal/middleware/auth.go@@ -60,6 +60,21 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV// from a non-task-token path.r.Header.Del("X-Actor-Source")+ // Agent identity is server-set for exactly the same reason,+ // and the rest of the codebase already assumes it (see+ // resolveActor, actor_guards.go, CreateIssue). Only the mat_+ // branch below re-stamps these from the token row.+ //+ // Without the strip, resolveActor's pair requirement was not a+ // boundary: BOTH ids are readable by any workspace member+ // (GET /api/issues/{id}/task-runs returns agent_id + task_id),+ // so a member could replay a live pair on their own JWT/PAT and+ // be resolved as that agent — and, since MUL-6951, act with the+ // authority of that run's originator. MUL-3428, reported and+ // fixed in #4313.+ r.Header.Del("X-Agent-ID")+ r.Header.Del("X-Task-ID")+tokenString, fromCookie := extractToken(r)if tokenString == "" {slog.Debug("auth: no token found", "path", r.URL.Path)diff --git a/server/internal/middleware/auth_test.go b/server/internal/middleware/auth_test.goindex b6f474d70e..efd3cf01e0 100644--- a/server/internal/middleware/auth_test.go+++ b/server/internal/middleware/auth_test.go@@ -304,6 +304,41 @@ func TestAuth_StripsClientSuppliedActorSource(t *testing.T) {}}+// TestAuth_StripsForgedAgentIdentityHeaders pins the boundary that makes+// agent identity unforgeable: X-Agent-ID and X-Task-ID are server-set, so any+// value a client sends must be gone before a handler can read it.+//+// Without the strip, resolveActor's "both headers, and the task belongs to the+// agent" rule proved nothing, because both ids are readable by any workspace+// member (GET /api/issues/{id}/task-runs returns the pair). A member could+// replay a live pair on their own JWT and be resolved as that agent — and,+// since MUL-6951, act with the authority of that run's originator. MUL-3428.+func TestAuth_StripsForgedAgentIdentityHeaders(t *testing.T) {+ var gotAgentID, gotTaskID string+ mw := Auth(nil, nil, nil)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotAgentID = r.Header.Get("X-Agent-ID")+ gotTaskID = r.Header.Get("X-Task-ID")+ w.WriteHeader(http.StatusOK)+ }))++ token := generateToken(validClaims(), auth.JWTSecret())+ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer "+token)+ // A real, observable (agent, task) pair replayed by a member.+ req.Header.Set("X-Agent-ID", "11111111-1111-1111-1111-111111111111")+ req.Header.Set("X-Task-ID", "22222222-2222-2222-2222-222222222222")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotAgentID != "" || gotTaskID != "" {+ t.Fatalf("agent identity headers must be cleared on non-task-token paths, got agent=%q task=%q", gotAgentID, gotTaskID)+ }+}+// TestAuth_PATCacheHit pins the optimization: when the PAT cache already// holds an entry for this token, the middleware MUST NOT call into queries// — it short-circuits before the DB lookup and the last_used_at update.diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.goindex cc9646a224..0455c08888 100644--- a/server/internal/middleware/daemon_auth.go+++ b/server/internal/middleware/daemon_auth.go@@ -89,6 +89,14 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.// request arrived on.r.Header.Del("X-Actor-Source")+ // Agent identity is server-set too: strip any client-supplied+ // value here as well, so a handler reached through the daemon+ // chain gets the same guarantee as one reached through Auth.+ // The daemon's own endpoints take task ids in the request body,+ // never these headers (MUL-3428, #4313).+ r.Header.Del("X-Agent-ID")+ r.Header.Del("X-Task-ID")+authHeader := r.Header.Get("Authorization")if authHeader == "" {slog.Debug("daemon_auth: missing authorization header", "path", r.URL.Path)diff --git a/server/internal/middleware/daemon_auth_test.go b/server/internal/middleware/daemon_auth_test.goindex 3c7657c8b9..624edfd23a 100644--- a/server/internal/middleware/daemon_auth_test.go+++ b/server/internal/middleware/daemon_auth_test.go@@ -150,6 +150,45 @@ func TestDaemonAuth_StripsClientSuppliedActorSource(t *testing.T) {}}+// TestDaemonAuth_StripsForgedAgentIdentityHeaders mirrors+// TestAuth_StripsForgedAgentIdentityHeaders on the daemon chain, so a handler+// reachable through either middleware gets the same guarantee. The daemon's+// own endpoints carry task ids in the request body, never in these headers,+// so the strip costs the daemon nothing. MUL-3428.+func TestDaemonAuth_StripsForgedAgentIdentityHeaders(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := auth.NewDaemonTokenCache(rdb)++ const rawToken = "mdt_agent_header_strip_test"+ hash := auth.HashToken(rawToken)+ cache.Set(context.Background(), hash, auth.DaemonTokenIdentity{+ WorkspaceID: "ws-1",+ DaemonID: "daemon-1",+ }, auth.AuthCacheTTL)++ var gotAgentID, gotTaskID string+ mw := DaemonAuth(nil, nil, cache, nil)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotAgentID = r.Header.Get("X-Agent-ID")+ gotTaskID = r.Header.Get("X-Task-ID")+ w.WriteHeader(http.StatusOK)+ }))++ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)+ req.Header.Set("Authorization", "Bearer "+rawToken)+ req.Header.Set("X-Agent-ID", "11111111-1111-1111-1111-111111111111")+ req.Header.Set("X-Task-ID", "22222222-2222-2222-2222-222222222222")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotAgentID != "" || gotTaskID != "" {+ t.Fatalf("agent identity headers must be cleared on the mdt_ path, got agent=%q task=%q", gotAgentID, gotTaskID)+ }+}+func TestDaemonAuth_InvalidMDT_NilQueries(t *testing.T) {mw := DaemonAuth(nil, nil, nil, nil) // no caches, no DBhandler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/server/internal/service/builtin_skills/multica-platform/references/autopilots.md b/server/internal/service/builtin_skills/multica-platform/references/autopilots.mdindex c48eaacc6f..c8ed7f1d91 100644--- a/server/internal/service/builtin_skills/multica-platform/references/autopilots.md+++ b/server/internal/service/builtin_skills/multica-platform/references/autopilots.md@@ -81,13 +81,21 @@ keeps write/execute but cannot re-grant or revoke peers. `get` stamps twoper-caller booleans — `can_write` and the narrower `can_manage_access` — readthose rather than inferring from role.-When YOU run `trigger`, the run is authorized as the human who asked you to —-your run's originator — not as the owner of the machine you execute on, whose-grants are not consulted. So the person who gave you the instruction needs that-write access, and you cannot trigger an autopilot they could not trigger-themselves. A run that carries no originator at all cannot trigger anything: the-server answers `403` naming the missing originator rather than skipping quietly,-and the CLI prints that reason instead of a generic permission error.+When YOU do any of this — `trigger`, `create`, `update`, `delete`, the+`trigger-*` commands, or a webhook-secret or collaborator change over the API —+the request is authorized as the human who asked you to (your run's originator),+not as the owner of the machine you execute on, whose grants are not consulted.+So the person who gave you the instruction needs that write access, and you+cannot change or trigger an autopilot they could not themselves. The same human+is stamped into what you write: an autopilot you create is theirs, and a trigger+you add fires as them for as long as it exists.++A run that carries no originator cannot write here at all: the server+answers `403` naming the missing originator rather than failing quietly, and the+CLI prints that reason instead of a generic permission error. Reads are+unaffected — except that `get` redacts the webhook token unless the human you+act for may write, since holding that token is equivalent to being able to+trigger.## Side effects