Skip to content

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

Go

MUL-8198: fix(daemon): keep pre-588 Remote MCP tokens working for their issuing owner (#9469)

Multica Eve4dc39434ef1b
diff --git a/server/internal/handler/daemon_token_legacy_owner_test.go b/server/internal/handler/daemon_token_legacy_owner_test.go
new file mode 100644
index 0000000000..b1ae34d296
--- /dev/null
+++ b/server/internal/handler/daemon_token_legacy_owner_test.go
@@ -0,0 +1,161 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// MUL-8198: Remote MCP daemon tokens minted before migration 588 have no
+// owner_id. Through v0.6.5 FinalizeTaskClaim inserted them in the same
+// transaction as the task's task_token, so DaemonAuth recovers the issuing
+// owner from that task_token. These tests pin that a running pre-upgrade task
+// keeps working, and that every case without a single provable owner, or
+// whose runtime changed hands, is still refused.
+
+type legacyTokenFixture struct {
+ daemonID string
+ runtimeID string
+ taskID string
+}
+
+func newLegacyTokenFixture(t *testing.T, label string) legacyTokenFixture {
+ t.Helper()
+ ctx := context.Background()
+ suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
+ f := legacyTokenFixture{daemonID: "legacy-" + label + "-" + suffix}
+ f.runtimeID = dbfx.Runtime(t, label+" legacy runtime", testutil.Cols{
+ "daemon_id": f.daemonID,
+ "provider": "claude",
+ })
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, f.runtimeID, label+" legacy agent")
+ f.taskID = dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": f.runtimeID,
+ "issue_id": issueID,
+ "status": "running",
+ "started_at": testutil.Raw("now()"),
+ })
+ return f
+}
+
+// mintLegacyClaimTokens reproduces a v0.6.5 claim: one transaction inserts a
+// task_token per (taskID, userID) pair and an unbound daemon token. It
+// returns the raw daemon token.
+func mintLegacyClaimTokens(t *testing.T, daemonID string, taskTokens ...[2]string) string {
+ t.Helper()
+ ctx := context.Background()
+ raw, err := auth.GenerateDaemonToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ tx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback(ctx)
+ for _, tt := range taskTokens {
+ if _, err := tx.Exec(ctx, `
+ INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)
+ SELECT $1, q.id, q.agent_id, $2, $3, now() + interval '1 hour'
+ FROM agent_task_queue q WHERE q.id = $4`,
+ "legacy-tt-"+uuid.NewString(), testWorkspaceID, tt[1], tt[0]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var tokenID string
+ if err := tx.QueryRow(ctx, `
+ INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at)
+ VALUES ($1, $2, $3, now() + interval '24 hours') RETURNING id`,
+ auth.HashToken(raw), testWorkspaceID, daemonID).Scan(&tokenID); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id = $1`, tokenID)
+ })
+ return raw
+}
+
+func legacyTaskStatus(t *testing.T, raw, taskID string) int {
+ t.Helper()
+ req := withURLParams(httptest.NewRequest("GET", "/api/daemon/tasks/"+taskID+"/status", nil), "taskId", taskID)
+ req.Header.Set("Authorization", "Bearer "+raw)
+ w := httptest.NewRecorder()
+ middleware.DaemonAuth(testHandler.Queries, nil, nil, nil)(http.HandlerFunc(testHandler.GetTaskStatus)).ServeHTTP(w, req)
+ return w.Code
+}
+
+func TestLegacyDaemonToken_RunningTaskKeepsAccess(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newLegacyTokenFixture(t, "ok")
+ raw := mintLegacyClaimTokens(t, f.daemonID, [2]string{f.taskID, testUserID})
+ if code := legacyTaskStatus(t, raw, f.taskID); code != http.StatusOK {
+ t.Fatalf("legacy token on its own running task = %d, want 200", code)
+ }
+}
+
+func TestLegacyDaemonToken_RefusedWithoutSingleProvableOwner(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ t.Run("no matching task_token", func(t *testing.T) {
+ f := newLegacyTokenFixture(t, "none")
+ raw := mintLegacyClaimTokens(t, f.daemonID)
+ if code := legacyTaskStatus(t, raw, f.taskID); code != http.StatusNotFound {
+ t.Fatalf("got %d, want 404", code)
+ }
+ })
+
+ t.Run("task finished and task_token deleted", func(t *testing.T) {
+ f := newLegacyTokenFixture(t, "done")
+ raw := mintLegacyClaimTokens(t, f.daemonID, [2]string{f.taskID, testUserID})
+ dbfx.Exec(t, `DELETE FROM task_token WHERE task_id = $1`, f.taskID)
+ if code := legacyTaskStatus(t, raw, f.taskID); code != http.StatusNotFound {
+ t.Fatalf("got %d, want 404", code)
+ }
+ })
+
+ t.Run("runtime owner changed", func(t *testing.T) {
+ f := newLegacyTokenFixture(t, "moved")
+ raw := mintLegacyClaimTokens(t, f.daemonID, [2]string{f.taskID, testUserID})
+ other := dbfx.User(t, "legacy new owner", "legacy-owner-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, other, "member")
+ dbfx.Exec(t, `UPDATE agent_runtime SET owner_id = $1 WHERE id = $2`, other, f.runtimeID)
+ if code := legacyTaskStatus(t, raw, f.taskID); code != http.StatusNotFound {
+ t.Fatalf("got %d, want 404", code)
+ }
+ })
+
+ t.Run("ambiguous owners at the same timestamp", func(t *testing.T) {
+ f := newLegacyTokenFixture(t, "ambig")
+ g := newLegacyTokenFixture(t, "ambig2")
+ dbfx.Exec(t, `UPDATE agent_runtime SET daemon_id = $1, provider = 'codex' WHERE id = $2`, f.daemonID, g.runtimeID)
+ other := dbfx.User(t, "legacy other", "legacy-other-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, other, "member")
+ raw := mintLegacyClaimTokens(t, f.daemonID,
+ [2]string{f.taskID, testUserID}, [2]string{g.taskID, other})
+ if code := legacyTaskStatus(t, raw, f.taskID); code != http.StatusNotFound {
+ t.Fatalf("got %d, want 404", code)
+ }
+ })
+
+ t.Run("task_token on another daemon", func(t *testing.T) {
+ f := newLegacyTokenFixture(t, "otherd")
+ raw := mintLegacyClaimTokens(t, "unrelated-"+f.daemonID, [2]string{f.taskID, testUserID})
+ if code := legacyTaskStatus(t, raw, f.taskID); code != http.StatusNotFound {
+ t.Fatalf("got %d, want 404", code)
+ }
+ })
+}
diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.go
index 868102f76d..c27dead48a 100644
--- a/server/internal/middleware/daemon_auth.go
+++ b/server/internal/middleware/daemon_auth.go
@@ -179,8 +179,22 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.
WorkspaceID: uuidToString(dt.WorkspaceID),
DaemonID: dt.DaemonID,
}
+ cacheable := true
if dt.OwnerID.Valid {
identity.OwnerID = uuidToString(dt.OwnerID)
+ } else if !strings.HasPrefix(dt.DaemonID, "qoder-managed-") {
+ // Pre-588 Remote MCP token: recover its issuing owner
+ // from the task_token minted in the same claim
+ // transaction. Unresolvable tokens stay unbound and are
+ // refused by the runtime binding check, as before.
+ owner, err := legacyDaemonTokenOwner(r.Context(), queries, dt)
+ if err != nil {
+ // Fail closed for this request, but don't cache the
+ // unbound identity on a transient DB error.
+ slog.Warn("daemon_auth: legacy daemon token owner lookup failed", "path", r.URL.Path, "error", err)
+ cacheable = false
+ }
+ identity.OwnerID = owner
}
// daemon_token.expires_at is NOT NULL; pgtype Valid is true
// in normal operation, but defend against zero just in case.
@@ -188,7 +202,9 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.
if dt.ExpiresAt.Valid {
expiresAt = dt.ExpiresAt.Time
}
- daemonCache.Set(r.Context(), hash, identity, auth.TTLForExpiry(time.Now(), expiresAt))
+ if cacheable {
+ daemonCache.Set(r.Context(), hash, identity, auth.TTLForExpiry(time.Now(), expiresAt))
+ }
ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, identity.WorkspaceID)
ctx = context.WithValue(ctx, ctxKeyDaemonID, identity.DaemonID)
@@ -322,3 +338,36 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.
})
}
}
+
+// legacyDaemonTokenOwner recovers the issuing runtime owner of a daemon token
+// minted before migration 588 added daemon_token.owner_id (MUL-8198).
+//
+// Through v0.6.5 the only daemon tokens were per-task Remote MCP credentials,
+// inserted by FinalizeTaskClaim in the same transaction as the task's
+// task_token. Both rows therefore share created_at, and task_token.user_id is
+// the runtime owner that claim was authorized for. The owner is returned only
+// when exactly one live task_token on a runtime of the token's daemon
+// matches; anything else returns "" so the token stays unbound and is refused
+// by the runtime binding check. The result goes through the same owner
+// comparison as a token bound at mint time, so a daemon_id re-registered by
+// another member is still out of reach.
+//
+// Compatibility shim for tokens issued before the 0.7.0 upgrade; those expire
+// within 24h, so it can be removed one release later.
+func legacyDaemonTokenOwner(ctx context.Context, queries *db.Queries, dt db.DaemonToken) (string, error) {
+ if !dt.CreatedAt.Valid {
+ return "", nil
+ }
+ owners, err := queries.ListLegacyDaemonTokenOwners(ctx, db.ListLegacyDaemonTokenOwnersParams{
+ WorkspaceID: dt.WorkspaceID,
+ CreatedAt: dt.CreatedAt,
+ DaemonID: dt.DaemonID,
+ })
+ if err != nil {
+ return "", err
+ }
+ if len(owners) != 1 || !owners[0].Valid {
+ return "", nil
+ }
+ return uuidToString(owners[0]), nil
+}
diff --git a/server/pkg/db/generated/daemon_token.sql.go b/server/pkg/db/generated/daemon_token.sql.go
index 4aa041f19f..2b2fa7b6c8 100644
--- a/server/pkg/db/generated/daemon_token.sql.go
+++ b/server/pkg/db/generated/daemon_token.sql.go
@@ -116,3 +116,50 @@ func (q *Queries) GetDaemonTokenByHash(ctx context.Context, tokenHash string) (D
)
return i, err
}
+
+const listLegacyDaemonTokenOwners = `-- name: ListLegacyDaemonTokenOwners :many
+SELECT DISTINCT tt.user_id
+FROM task_token tt
+JOIN agent_task_queue q ON q.id = tt.task_id
+JOIN agent_runtime r ON r.id = q.runtime_id
+WHERE tt.workspace_id = $1
+ AND tt.created_at = $2
+ AND tt.expires_at > now()
+ AND r.workspace_id = $1
+ AND r.daemon_id = $3::text
+LIMIT 2
+`
+
+type ListLegacyDaemonTokenOwnersParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ DaemonID string `json:"daemon_id"`
+}
+
+// Compatibility for Remote MCP daemon tokens minted before migration 588
+// (owner_id NULL). Up to v0.6.5 FinalizeTaskClaim inserted that token and the
+// task's task_token in one transaction, so both rows carry the same
+// created_at (now() is the transaction start). task_token.user_id is the
+// runtime owner the claim was authorized for, i.e. the token's issuing owner.
+// The task must still be live (task_token not deleted/expired) and bound to a
+// runtime of the token's daemon. Callers accept the result only when exactly
+// one owner matches; LIMIT 2 is enough to detect ambiguity.
+func (q *Queries) ListLegacyDaemonTokenOwners(ctx context.Context, arg ListLegacyDaemonTokenOwnersParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listLegacyDaemonTokenOwners, arg.WorkspaceID, arg.CreatedAt, arg.DaemonID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var user_id pgtype.UUID
+ if err := rows.Scan(&user_id); err != nil {
+ return nil, err
+ }
+ items = append(items, user_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
diff --git a/server/pkg/db/queries/daemon_token.sql b/server/pkg/db/queries/daemon_token.sql
index 427ff1a71c..277cdc7713 100644
--- a/server/pkg/db/queries/daemon_token.sql
+++ b/server/pkg/db/queries/daemon_token.sql
@@ -25,3 +25,23 @@ RETURNING token_hash;
-- name: DeleteExpiredDaemonTokens :exec
DELETE FROM daemon_token
WHERE expires_at <= now();
+
+-- name: ListLegacyDaemonTokenOwners :many
+-- Compatibility for Remote MCP daemon tokens minted before migration 588
+-- (owner_id NULL). Up to v0.6.5 FinalizeTaskClaim inserted that token and the
+-- task's task_token in one transaction, so both rows carry the same
+-- created_at (now() is the transaction start). task_token.user_id is the
+-- runtime owner the claim was authorized for, i.e. the token's issuing owner.
+-- The task must still be live (task_token not deleted/expired) and bound to a
+-- runtime of the token's daemon. Callers accept the result only when exactly
+-- one owner matches; LIMIT 2 is enough to detect ambiguity.
+SELECT DISTINCT tt.user_id
+FROM task_token tt
+JOIN agent_task_queue q ON q.id = tt.task_id
+JOIN agent_runtime r ON r.id = q.runtime_id
+WHERE tt.workspace_id = @workspace_id
+ AND tt.created_at = @created_at
+ AND tt.expires_at > now()
+ AND r.workspace_id = @workspace_id
+ AND r.daemon_id = @daemon_id::text
+LIMIT 2;