Skip to content

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

Go

fix(auth): refuse task tokens whose task has ended (MUL-10044) (#11391)

Bohan Jiang5350b49fd4d3
diff --git a/server/cmd/server/comment_trigger_integration_test.go b/server/cmd/server/comment_trigger_integration_test.go
index b1f10a37e2..63a3ca595f 100644
--- a/server/cmd/server/comment_trigger_integration_test.go
+++ b/server/cmd/server/comment_trigger_integration_test.go
@@ -67,16 +67,19 @@ func mintAgentTaskToken(t *testing.T, agentID, taskID, boundUserID string) strin
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.
+// ensureAgentTask returns a live 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. A terminal task would not do: auth refuses a token
+// whose task has ended (GitHub #11378).
func ensureAgentTask(t *testing.T, agentID string) string {
t.Helper()
ctx := context.Background()
var taskID string
if err := testPool.QueryRow(ctx,
- `SELECT id::text FROM agent_task_queue WHERE agent_id = $1 LIMIT 1`,
+ `SELECT id::text FROM agent_task_queue
+ WHERE agent_id = $1 AND status NOT IN ('completed', 'failed', 'cancelled')
+ LIMIT 1`,
agentID,
).Scan(&taskID); err == nil && taskID != "" {
return taskID
diff --git a/server/cmd/server/task_token_terminal_task_integration_test.go b/server/cmd/server/task_token_terminal_task_integration_test.go
new file mode 100644
index 0000000000..61630aa166
--- /dev/null
+++ b/server/cmd/server/task_token_terminal_task_integration_test.go
@@ -0,0 +1,122 @@
+package main
+
+import (
+ "context"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/auth"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestTaskTokenRejectedAfterOfflineSweepFailsTask is the GitHub #11378
+// regression. The offline-runtime sweeper fails a running task without
+// deleting its mat_ token, so the token row outlives the task. Auth must
+// refuse it anyway: a token authenticates only while its task is live.
+func TestTaskTokenRejectedAfterOfflineSweepFailsTask(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+
+ issueID, agentID, taskID := setupSweeperTestFixture(t, "running")
+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+ token := mintAgentTaskToken(t, agentID, taskID, testUserID)
+
+ getIssue := func(t *testing.T) int {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, testServer.URL+"/api/issues/"+issueID, nil)
+ if err != nil {
+ t.Fatalf("create request: %v", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatalf("perform request: %v", err)
+ }
+ resp.Body.Close()
+ return resp.StatusCode
+ }
+
+ if got := getIssue(t); got != http.StatusOK {
+ t.Fatalf("running task: status = %d, want 200", got)
+ }
+
+ setAgentRuntimeOffline(t, agentID, defaultRuntimeReconnectGrace+time.Hour)
+ failed, err := db.New(testPool).FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{
+ ReconnectGraceSecs: defaultRuntimeReconnectGrace.Seconds(),
+ MaxPerTick: offlineTaskFailBatchSize,
+ })
+ if err != nil {
+ t.Fatalf("FailTasksForOfflineRuntimes: %v", err)
+ }
+ swept := false
+ for _, task := range failed {
+ if task.ID.Bytes == parseUUIDBytes(taskID) {
+ swept = true
+ }
+ }
+ if !swept {
+ t.Fatal("sweeper did not fail the task")
+ }
+
+ // The precondition the bug needs: the sweep left the token row in place.
+ var rows int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM task_token WHERE token_hash = $1`, auth.HashToken(token),
+ ).Scan(&rows); err != nil {
+ t.Fatalf("count task tokens: %v", err)
+ }
+ if rows != 1 {
+ t.Fatalf("task_token rows after sweep = %d, want 1 (test no longer covers the undeleted-token case)", rows)
+ }
+
+ if got := getIssue(t); got != http.StatusUnauthorized {
+ t.Fatalf("failed task: status = %d, want 401", got)
+ }
+}
+
+// TestTaskTokenLiveOnlyWhileTaskIsLive pins the status rule in
+// GetTaskTokenByHash: every live status authenticates, every terminal one
+// does not, whatever path put the task there.
+func TestTaskTokenLiveOnlyWhileTaskIsLive(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+
+ issueID, agentID, taskID := setupSweeperTestFixture(t, "running")
+ t.Cleanup(func() { cleanupSweeperFixture(t, issueID, agentID) })
+ token := mintAgentTaskToken(t, agentID, taskID, testUserID)
+ queries := db.New(testPool)
+
+ for _, tc := range []struct {
+ status string
+ live bool
+ }{
+ {"queued", true},
+ {"dispatched", true},
+ {"running", true},
+ {"waiting_local_directory", true},
+ {"deferred", true},
+ {"completed", false},
+ {"failed", false},
+ {"cancelled", false},
+ } {
+ t.Run(tc.status, func(t *testing.T) {
+ if _, err := testPool.Exec(ctx,
+ `UPDATE agent_task_queue SET status = $2 WHERE id = $1`, taskID, tc.status,
+ ); err != nil {
+ t.Fatalf("set task status: %v", err)
+ }
+ _, err := queries.GetTaskTokenByHash(ctx, auth.HashToken(token))
+ if tc.live && err != nil {
+ t.Fatalf("live task: GetTaskTokenByHash error = %v, want the token", err)
+ }
+ if !tc.live && err == nil {
+ t.Fatal("terminal task: GetTaskTokenByHash returned the token, want no row")
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/inbox_access_test.go b/server/internal/handler/inbox_access_test.go
index 396695882c..094f8d96aa 100644
--- a/server/internal/handler/inbox_access_test.go
+++ b/server/internal/handler/inbox_access_test.go
@@ -150,9 +150,10 @@ func TestListInboxTaskCredentialAccess(t *testing.T) {
{"self-triggered", testUserID, "running", "", http.StatusOK},
{"another human", other, "running", "", http.StatusForbidden},
{"unattributed despite accountable owner", nil, "running", "", http.StatusForbidden},
- {"completed task with lingering token", testUserID, "completed", "", http.StatusForbidden},
- {"failed task with lingering token", testUserID, "failed", "", http.StatusForbidden},
- {"cancelled task with lingering token", testUserID, "cancelled", "", http.StatusForbidden},
+ // Auth itself refuses a token whose task has ended (GitHub #11378).
+ {"completed task with lingering token", testUserID, "completed", "", http.StatusUnauthorized},
+ {"failed task with lingering token", testUserID, "failed", "", http.StatusUnauthorized},
+ {"cancelled task with lingering token", testUserID, "cancelled", "", http.StatusUnauthorized},
{"runtime ownership changed", testUserID, "running", "owner", http.StatusForbidden},
{"missing runtime owner", testUserID, "running", "no-owner", http.StatusForbidden},
{"runtime in another workspace", testUserID, "running", "workspace", http.StatusForbidden},
diff --git a/server/internal/handler/issue_reaction_test.go b/server/internal/handler/issue_reaction_test.go
index ed79a4077d..06fafb8688 100644
--- a/server/internal/handler/issue_reaction_test.go
+++ b/server/internal/handler/issue_reaction_test.go
@@ -49,7 +49,7 @@ func TestAddIssueReactionQueuedBehindSameReactionReturnsIt(t *testing.T) {
"emoji": "👍",
}), "id", issueID))
}()
- waitForBackendBlockedBy(t, firstPID, done)
+ waitForIssueReactionBackendBlockedBy(t, firstPID, done)
if err := first.Commit(ctx); err != nil {
t.Fatalf("commit first: %v", err)
@@ -71,7 +71,7 @@ func TestAddIssueReactionQueuedBehindSameReactionReturnsIt(t *testing.T) {
}
}
-func waitForBackendBlockedBy(t *testing.T, holderPID int, done <-chan struct{}) {
+func waitForIssueReactionBackendBlockedBy(t *testing.T, holderPID int, done <-chan struct{}) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
diff --git a/server/internal/handler/quick_action_task_access_test.go b/server/internal/handler/quick_action_task_access_test.go
index 8393fa923b..3f832122f9 100644
--- a/server/internal/handler/quick_action_task_access_test.go
+++ b/server/internal/handler/quick_action_task_access_test.go
@@ -83,7 +83,6 @@ func TestQuickActionTaskTokenPrivateAccess(t *testing.T) {
{"runtime owner started the run", testUserID, "running", true},
{"another member started the run", other, "running", false},
{"no human started the run", nil, "running", false},
- {"finished run with a lingering token", testUserID, "completed", false},
} {
t.Run(tc.name, func(t *testing.T) {
runtimeID := dbfx.Runtime(t, "Quick action runtime")
@@ -130,6 +129,27 @@ func TestQuickActionTaskTokenPrivateAccess(t *testing.T) {
})
}
+ // A finished run's token is refused at auth (GitHub #11378), so it reaches
+ // neither public nor private actions and posts nothing.
+ t.Run("finished run with a lingering token", func(t *testing.T) {
+ runtimeID := dbfx.Runtime(t, "Quick action runtime")
+ agentID := dbfx.Agent(t, "Quick action agent", runtimeID)
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID, "issue_id": issueID, "status": "completed",
+ "originator_user_id": testUserID, "accountable_user_id": testUserID,
+ })
+ token := inboxTaskCredential(t, taskID, agentID, testWorkspaceID, testUserID)
+
+ testutil.Call(t, serve((*Handler).ListQuickActions), request(token, http.MethodGet, "/api/quick-actions")).
+ Want(http.StatusUnauthorized)
+ render(t, token, publicID).Want(http.StatusUnauthorized)
+ before := secretComments(t)
+ run(t, token, privateID).Want(http.StatusUnauthorized)
+ if got := secretComments(t); got != before {
+ t.Fatalf("refused run still posted the private prompt: %d comments, want %d", got, before)
+ }
+ })
+
// A human credential still reaches the creator's own private action.
t.Run("human session", func(t *testing.T) {
var resp ListQuickActionsResponse
diff --git a/server/pkg/db/generated/task_token.sql.go b/server/pkg/db/generated/task_token.sql.go
index f05c5e1901..c19fd2a2e5 100644
--- a/server/pkg/db/generated/task_token.sql.go
+++ b/server/pkg/db/generated/task_token.sql.go
@@ -70,10 +70,18 @@ func (q *Queries) DeleteTaskTokensByTask(ctx context.Context, taskID pgtype.UUID
}
const getTaskTokenByHash = `-- name: GetTaskTokenByHash :one
-SELECT id, token_hash, task_id, agent_id, workspace_id, user_id, expires_at, created_at FROM task_token
-WHERE token_hash = $1 AND expires_at > now()
+SELECT tt.id, tt.token_hash, tt.task_id, tt.agent_id, tt.workspace_id, tt.user_id, tt.expires_at, tt.created_at FROM task_token tt
+JOIN agent_task_queue q ON q.id = tt.task_id
+WHERE tt.token_hash = $1
+ AND tt.expires_at > now()
+ AND q.status NOT IN ('completed', 'failed', 'cancelled')
`
+// A token authenticates only while its task is live. Terminal task rows never
+// return to a live status (retries are new rows), so a token whose task is
+// completed, failed or cancelled is dead even when no path deleted it: the
+// bulk failure sweeps (runtime offline, stale tasks, daemon recovery) never
+// delete it, and the per-task deletes are best-effort (GitHub #11378).
func (q *Queries) GetTaskTokenByHash(ctx context.Context, tokenHash string) (TaskToken, error) {
row := q.db.QueryRow(ctx, getTaskTokenByHash, tokenHash)
var i TaskToken
diff --git a/server/pkg/db/queries/task_token.sql b/server/pkg/db/queries/task_token.sql
index fe98438e71..004096a746 100644
--- a/server/pkg/db/queries/task_token.sql
+++ b/server/pkg/db/queries/task_token.sql
@@ -4,8 +4,16 @@ VALUES ($1, $2, $3, $4, $5, $6, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid(
RETURNING *;
-- name: GetTaskTokenByHash :one
-SELECT * FROM task_token
-WHERE token_hash = $1 AND expires_at > now();
+-- A token authenticates only while its task is live. Terminal task rows never
+-- return to a live status (retries are new rows), so a token whose task is
+-- completed, failed or cancelled is dead even when no path deleted it: the
+-- bulk failure sweeps (runtime offline, stale tasks, daemon recovery) never
+-- delete it, and the per-task deletes are best-effort (GitHub #11378).
+SELECT tt.* FROM task_token tt
+JOIN agent_task_queue q ON q.id = tt.task_id
+WHERE tt.token_hash = $1
+ AND tt.expires_at > now()
+ AND q.status NOT IN ('completed', 'failed', 'cancelled');
-- name: DeleteTaskTokensByTask :exec
DELETE FROM task_token WHERE task_id = $1;