Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix: fail closed on agent task auth tokens (#4142)

Bohan Jiangf9c193e06bbf
diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.go
index 87e6d63edc..d642c72c52 100644
--- a/server/cmd/multica/cmd_agent.go
+++ b/server/cmd/multica/cmd_agent.go
@@ -247,6 +247,9 @@ func newAPIClient(cmd *cobra.Command) (*cli.APIClient, error) {
if serverURL == "" {
return nil, fmt.Errorf("server URL not set: use --server-url flag, MULTICA_SERVER_URL env, or 'multica config set server_url <url>'")
}
+ if inAgentExecutionContext() && !strings.HasPrefix(token, "mat_") {
+ return nil, fmt.Errorf("agent execution context requires MULTICA_TOKEN to be a task-scoped mat_ token")
+ }
client := cli.NewAPIClient(serverURL, workspaceID, token)
// When running inside a daemon task, attribute actions to the agent.
diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.go
index 3a0af1fb65..e0ed6caff6 100644
--- a/server/cmd/multica/cmd_agent_test.go
+++ b/server/cmd/multica/cmd_agent_test.go
@@ -108,6 +108,87 @@ func TestResolveWorkspaceID_AgentContextSkipsConfig(t *testing.T) {
})
}
+func TestResolveToken_AgentContextSkipsConfig(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+
+ if err := cli.SaveCLIConfig(cli.CLIConfig{Token: "mul_profile_token"}); err != nil {
+ t.Fatalf("seed config: %v", err)
+ }
+
+ t.Run("outside agent context falls back to config", func(t *testing.T) {
+ t.Setenv("MULTICA_AGENT_ID", "")
+ t.Setenv("MULTICA_TASK_ID", "")
+ t.Setenv("MULTICA_TOKEN", "")
+
+ if got := resolveToken(testCmd()); got != "mul_profile_token" {
+ t.Fatalf("resolveToken() = %q, want profile token", got)
+ }
+ })
+
+ t.Run("agent context without env never reads config", func(t *testing.T) {
+ t.Setenv("MULTICA_AGENT_ID", "agent-123")
+ t.Setenv("MULTICA_TASK_ID", "task-456")
+ t.Setenv("MULTICA_TOKEN", "")
+
+ if got := resolveToken(testCmd()); got != "" {
+ t.Fatalf("resolveToken() = %q, want empty in agent context without MULTICA_TOKEN", got)
+ }
+ })
+
+ t.Run("agent context uses explicit task token env", func(t *testing.T) {
+ t.Setenv("MULTICA_AGENT_ID", "agent-123")
+ t.Setenv("MULTICA_TASK_ID", "task-456")
+ t.Setenv("MULTICA_TOKEN", "mat_task_token")
+
+ if got := resolveToken(testCmd()); got != "mat_task_token" {
+ t.Fatalf("resolveToken() = %q, want MULTICA_TOKEN", got)
+ }
+ })
+}
+
+func TestNewAPIClient_AgentContextRequiresTaskToken(t *testing.T) {
+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:8080")
+ t.Setenv("MULTICA_WORKSPACE_ID", "workspace-123")
+ t.Setenv("MULTICA_AGENT_ID", "agent-123")
+ t.Setenv("MULTICA_TASK_ID", "task-456")
+
+ t.Run("missing token fails closed", func(t *testing.T) {
+ t.Setenv("MULTICA_TOKEN", "")
+
+ _, err := newAPIClient(testCmd())
+ if err == nil {
+ t.Fatal("newAPIClient(): expected error without task token")
+ }
+ if !strings.Contains(err.Error(), "mat_ token") {
+ t.Fatalf("newAPIClient() error = %q, want mat_ token guidance", err.Error())
+ }
+ })
+
+ t.Run("member token fails closed", func(t *testing.T) {
+ t.Setenv("MULTICA_TOKEN", "mul_member_token")
+
+ _, err := newAPIClient(testCmd())
+ if err == nil {
+ t.Fatal("newAPIClient(): expected error with member token")
+ }
+ if !strings.Contains(err.Error(), "mat_ token") {
+ t.Fatalf("newAPIClient() error = %q, want mat_ token guidance", err.Error())
+ }
+ })
+
+ t.Run("task token succeeds", func(t *testing.T) {
+ t.Setenv("MULTICA_TOKEN", "mat_task_token")
+
+ client, err := newAPIClient(testCmd())
+ if err != nil {
+ t.Fatalf("newAPIClient(): %v", err)
+ }
+ if client.Token != "mat_task_token" {
+ t.Fatalf("client token = %q, want task token", client.Token)
+ }
+ })
+}
+
// TestParseCustomEnv covers the --custom-env flag parser used by
// `agent create` and `agent env set`. The flag accepts a JSON object
// of string keys and values; the only clear signal is the explicit
diff --git a/server/cmd/multica/cmd_auth.go b/server/cmd/multica/cmd_auth.go
index 32cbf85ef9..8ed3131cdf 100644
--- a/server/cmd/multica/cmd_auth.go
+++ b/server/cmd/multica/cmd_auth.go
@@ -71,6 +71,9 @@ func resolveToken(cmd *cobra.Command) string {
if v := strings.TrimSpace(os.Getenv("MULTICA_TOKEN")); v != "" {
return v
}
+ if inAgentExecutionContext() {
+ return ""
+ }
profile := resolveProfile(cmd)
cfg, _ := cli.LoadCLIConfigForProfile(profile)
return cfg.Token
diff --git a/server/cmd/multica/cmd_auth_test.go b/server/cmd/multica/cmd_auth_test.go
index 75d4b1b5e9..7c2f1e13f6 100644
--- a/server/cmd/multica/cmd_auth_test.go
+++ b/server/cmd/multica/cmd_auth_test.go
@@ -2,12 +2,20 @@ package main
import (
"net"
+ "os"
"strings"
"testing"
"github.com/spf13/cobra"
)
+func TestMain(m *testing.M) {
+ os.Unsetenv("MULTICA_AGENT_ID")
+ os.Unsetenv("MULTICA_TASK_ID")
+ os.Unsetenv("MULTICA_TOKEN")
+ os.Exit(m.Run())
+}
+
// testCmd returns a minimal cobra.Command with the --profile persistent flag
// registered, matching the rootCmd setup used in production.
func testCmd() *cobra.Command {
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index e13baa49e2..2c93ec5f13 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -33,6 +33,17 @@ const (
taskSlotCapacityBackoff = 5 * time.Second
)
+func taskScopedAuthToken(task Task) (string, error) {
+ token := strings.TrimSpace(task.AuthToken)
+ if token == "" {
+ return "", errors.New("server did not provide task-scoped auth token")
+ }
+ if !strings.HasPrefix(token, "mat_") {
+ return "", errors.New("server provided non-task-scoped auth token")
+ }
+ return token, nil
+}
+
// taskRunner executes a single agent task and returns the result.
// Extracted as an interface so tests can inject a fake without spawning real
// agent processes, while keeping test scaffolding out of the production struct.
@@ -2820,24 +2831,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
prompt := BuildPrompt(task, provider)
- // Pass the daemon's auth credentials and context so the spawned agent CLI
+ // Pass task-scoped auth credentials and context so the spawned agent CLI
// can call the Multica API and the local daemon (e.g. `multica repo checkout`).
// MULTICA_TASK_SLOT is allocated from the daemon-wide concurrency pool, not
// per-agent. When one daemon hosts multiple agents, slots index shared
// daemon-level resources such as GPUs.
- // MULTICA_TOKEN is the credential the agent process will use to call the
- // Multica API. Prefer the task-scoped token the server minted at claim
- // time — that token is bound to (agent, task) and the auth middleware
- // rejects it on owner-only endpoints (e.g. `/api/agents/{id}/env`), so
- // the agent cannot use it to read another agent's secrets. Falls back
- // to the daemon's own credential only when the server returned no
- // auth_token (older server, or cloud / system runtime with no owner) —
- // in that legacy mode lateral-movement protection relies on the
- // runtime not handing the daemon a workspace-owner PAT in the first
- // place. See MUL-2600.
- agentToken := task.AuthToken
- if agentToken == "" {
- agentToken = d.client.Token()
+ // MULTICA_TOKEN is bound to (agent, task) by the server. Never fall back
+ // to the daemon's own credential here: doing so lets agent CLI writes land
+ // as the runtime owner's member actor and can retrigger the same agent.
+ agentToken, err := taskScopedAuthToken(task)
+ if err != nil {
+ taskLog.Error("task auth token invalid; refusing to start agent", "error", err)
+ return TaskResult{}, err
}
agentEnv := map[string]string{
"MULTICA_TOKEN": agentToken,
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index f8d53e6286..d9b5850c9d 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -111,6 +111,55 @@ func TestIsBlockedEnvKey(t *testing.T) {
}
}
+func TestTaskScopedAuthToken(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ token string
+ want string
+ wantErr string
+ }{
+ {
+ name: "missing token fails closed",
+ wantErr: "server did not provide task-scoped auth token",
+ },
+ {
+ name: "member token fails closed",
+ token: "mul_member_token",
+ wantErr: "server provided non-task-scoped auth token",
+ },
+ {
+ name: "task token accepted",
+ token: " mat_task_token ",
+ want: "mat_task_token",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ got, err := taskScopedAuthToken(Task{AuthToken: tt.token})
+ if tt.wantErr != "" {
+ if err == nil {
+ t.Fatalf("taskScopedAuthToken() error = nil, want %q", tt.wantErr)
+ }
+ if err.Error() != tt.wantErr {
+ t.Fatalf("taskScopedAuthToken() error = %q, want %q", err.Error(), tt.wantErr)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("taskScopedAuthToken(): %v", err)
+ }
+ if got != tt.want {
+ t.Fatalf("taskScopedAuthToken() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
// When `brew --prefix` is unavailable but the executable path is under a
// known Cellar root, triggerRestart must recover the prefix from the
// known-prefix list and target <prefix>/bin/multica.
diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.go
index af97796c20..19f4df4192 100644
--- a/server/internal/daemon/types.go
+++ b/server/internal/daemon/types.go
@@ -100,8 +100,8 @@ type Task struct {
// AuthToken is the task-scoped credential the server mints at claim time.
// The daemon injects it into the spawned agent as MULTICA_TOKEN so the
// agent never sees the daemon's own (often workspace-owner) credential.
- // Empty when the server-side runtime has no owning user — the daemon
- // then falls back to its own token. See MUL-2600.
+ // Empty or non-task-scoped values are fatal for writable agent tasks; the
+ // daemon must not fall back to its own token. See MUL-3292.
AuthToken string `json:"auth_token,omitempty"`
}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index b78017d6d1..68e825e0ac 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -320,9 +320,9 @@ type AgentTaskResponse struct {
// this (agent_id, task_id) pair at claim time and treats any request
// authenticated with it as actor=agent, regardless of headers — so the
// agent process cannot use it to read another agent's secrets via the
- // env-management endpoint. Empty when the runtime has no owning user
- // (cloud / system runtimes that pre-date per-task tokens); in that case
- // the daemon falls back to its own credential. See MUL-2600.
+ // env-management endpoint. Claim fails closed when the runtime has no
+ // owning user; the daemon must not fall back to its own credential. See
+ // MUL-3292.
AuthToken string `json:"auth_token,omitempty"`
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 0109212235..2cbf383d58 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1661,38 +1661,49 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {
// process instead of its own credential, so any API call the agent
// makes — even one that strips X-Agent-ID / X-Task-ID headers — is
// recognized server-side as actor=agent, closing the lateral-movement
- // path on owner-only endpoints (e.g. `/api/agents/{id}/env`). MUL-2600.
- //
- // Skip silently when the runtime has no owning user (cloud / system
- // runtimes installed before this PR) — the response carries no
- // `auth_token`, and the daemon falls back to its existing credential.
+ // path on owner-only endpoints (e.g. `/api/agents/{id}/env`). Runtime
+ // owner is required because task tokens are still bound to an owning user;
+ // without one, fail the claim explicitly instead of letting the daemon
+ // fall back to a member/owner credential. MUL-3292.
// Token expires after the queue/runtime upper bound (24h) so it survives
// long-running tasks but cannot outlive a forgotten one.
- if runtime.OwnerID.Valid {
- tokenStr, terr := auth.GenerateAgentTaskToken()
- if terr != nil {
- outcome = "error_token"
- slog.Error("task claim: failed to generate agent task token",
- "task_id", uuidToString(task.ID), "error", terr)
- writeError(w, http.StatusInternalServerError, "failed to mint task token")
- return
- }
- if _, terr := h.Queries.CreateTaskToken(r.Context(), db.CreateTaskTokenParams{
- TokenHash: auth.HashToken(tokenStr),
- TaskID: task.ID,
- AgentID: task.AgentID,
- WorkspaceID: parseUUID(resp.WorkspaceID),
- UserID: runtime.OwnerID,
- ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
- }); terr != nil {
- outcome = "error_token"
- slog.Error("task claim: failed to persist agent task token",
- "task_id", uuidToString(task.ID), "error", terr)
- writeError(w, http.StatusInternalServerError, "failed to persist task token")
- return
+ if !runtime.OwnerID.Valid {
+ outcome = "error_token"
+ slog.Error("task claim: runtime owner missing; cancelling task to avoid unscoped agent credentials",
+ "task_id", uuidToString(task.ID),
+ "runtime_id", runtimeID,
+ "workspace_id", runtimeWorkspaceID,
+ )
+ if _, cerr := h.TaskService.CancelTask(r.Context(), task.ID); cerr != nil {
+ slog.Error("task claim: cancel after missing runtime owner failed",
+ "task_id", uuidToString(task.ID), "error", cerr)
}
- resp.AuthToken = tokenStr
+ writeError(w, http.StatusInternalServerError, "runtime owner required to mint task token")
+ return
+ }
+ tokenStr, terr := auth.GenerateAgentTaskToken()
+ if terr != nil {
+ outcome = "error_token"
+ slog.Error("task claim: failed to generate agent task token",
+ "task_id", uuidToString(task.ID), "error", terr)
+ writeError(w, http.StatusInternalServerError, "failed to mint task token")
+ return
+ }
+ if _, terr := h.Queries.CreateTaskToken(r.Context(), db.CreateTaskTokenParams{
+ TokenHash: auth.HashToken(tokenStr),
+ TaskID: task.ID,
+ AgentID: task.AgentID,
+ WorkspaceID: parseUUID(resp.WorkspaceID),
+ UserID: runtime.OwnerID,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
+ }); terr != nil {
+ outcome = "error_token"
+ slog.Error("task claim: failed to persist agent task token",
+ "task_id", uuidToString(task.ID), "error", terr)
+ writeError(w, http.StatusInternalServerError, "failed to persist task token")
+ return
}
+ resp.AuthToken = tokenStr
slog.Info("task claimed by runtime", "task_id", uuidToString(task.ID), "runtime_id", runtimeID, "agent_id", uuidToString(task.AgentID), "prior_session", resp.PriorSessionID)
writeJSON(w, http.StatusOK, map[string]any{"task": resp})
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index eb08cf7787..de99e74a5c 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -102,11 +102,11 @@ func createClaimReclaimRuntime(t *testing.T, ctx context.Context, name string) s
if err := testPool.QueryRow(ctx, `
INSERT INTO agent_runtime (
workspace_id, daemon_id, name, runtime_mode, provider,
- status, device_info, metadata, last_seen_at, visibility
+ status, device_info, metadata, last_seen_at, visibility, owner_id
)
- VALUES ($1, NULL, $2, 'cloud', 'handler_test_runtime', 'online', 'claim reclaim fixture', '{}'::jsonb, now(), 'private')
+ VALUES ($1, NULL, $2, 'cloud', 'handler_test_runtime', 'online', 'claim reclaim fixture', '{}'::jsonb, now(), 'private', $3)
RETURNING id
- `, testWorkspaceID, name).Scan(&runtimeID); err != nil {
+ `, testWorkspaceID, name, testUserID).Scan(&runtimeID); err != nil {
t.Fatalf("setup: create runtime: %v", err)
}
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })
@@ -423,6 +423,49 @@ func TestClaimTaskByRuntime_WorkspaceContextEmptyWhenUnset(t *testing.T) {
}
}
+func TestClaimTaskByRuntime_MissingRuntimeOwnerCancelsAndRejects(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ ctx := context.Background()
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, daemon_id, name, runtime_mode, provider,
+ status, device_info, metadata, last_seen_at, visibility
+ )
+ VALUES ($1, NULL, 'Missing owner claim runtime', 'cloud', 'handler_test_runtime', 'online', 'claim missing owner fixture', '{}'::jsonb, now(), 'private')
+ RETURNING id
+ `, testWorkspaceID).Scan(&runtimeID); err != nil {
+ t.Fatalf("setup: create runtime: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })
+
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Missing owner claim agent")
+ taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
+
+ w := httptest.NewRecorder()
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
+ testWorkspaceID, "missing-owner-claim")
+ req = withURLParam(req, "runtimeId", runtimeID)
+ testHandler.ClaimTaskByRuntime(w, req)
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("ClaimTaskByRuntime: expected 500, got %d: %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "runtime owner required to mint task token") {
+ t.Fatalf("ClaimTaskByRuntime body = %q, want runtime owner error", w.Body.String())
+ }
+
+ var status string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {
+ t.Fatalf("read task status: %v", err)
+ }
+ if status != "cancelled" {
+ t.Fatalf("task status = %q, want cancelled", status)
+ }
+}
+
func TestDaemonRegister_WithDaemonToken(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
@@ -2450,6 +2493,9 @@ func createRuntimeGuardAgent(t *testing.T, ctx context.Context) (agentID, runtim
}
runtimeID = runtimes[0].(map[string]any)["id"].(string)
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, runtimeID) })
+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET owner_id = $1 WHERE id = $2`, testUserID, runtimeID); err != nil {
+ t.Fatalf("setup: set runtime owner: %v", err)
+ }
if err := testPool.QueryRow(ctx, `
INSERT INTO agent (
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index bbbcac44d9..448a2b5b66 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -121,11 +121,11 @@ func setupHandlerTestFixture(ctx context.Context, pool *pgxpool.Pool) (string, s
var runtimeID string
if err := pool.QueryRow(ctx, `
INSERT INTO agent_runtime (
- workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at
+ workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at
)
- VALUES ($1, NULL, $2, 'cloud', $3, 'online', $4, '{}'::jsonb, now())
+ VALUES ($1, NULL, $2, 'cloud', $3, 'online', $4, '{}'::jsonb, $5, now())
RETURNING id
- `, workspaceID, "Handler Test Runtime", "handler_test_runtime", "Handler test runtime").Scan(&runtimeID); err != nil {
+ `, workspaceID, "Handler Test Runtime", "handler_test_runtime", "Handler test runtime", userID).Scan(&runtimeID); err != nil {
return "", "", err
}
testRuntimeID = runtimeID