Skip to content

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

Go

MUL-8154 fix(daemon): enforce runtime ownership on daemon routes (#9423)

Multica Eve13eb4bda9349
diff --git a/server/internal/auth/daemon_token_cache.go b/server/internal/auth/daemon_token_cache.go
index c79eca728a..00b3ff4060 100644
--- a/server/internal/auth/daemon_token_cache.go
+++ b/server/internal/auth/daemon_token_cache.go
@@ -13,7 +13,10 @@ import (
// daemonTokenCachePrefix namespaces daemon-token cache keys separately
// from PAT (mul:auth:pat:*) so the two key spaces can't collide and an
// invalidation on one kind of token doesn't accidentally hit the other.
-const daemonTokenCachePrefix = "mul:auth:daemon:"
+//
+// v2 (MUL-8154) added OwnerID; entries written before it are never read, so a
+// pre-upgrade entry cannot authorize a token without its owner binding.
+const daemonTokenCachePrefix = "mul:auth:daemon:v2:"
// DaemonTokenIdentity is what DaemonAuth needs from the cached lookup —
// the workspace_id and daemon_id that the middleware injects into the
@@ -22,6 +25,9 @@ const daemonTokenCachePrefix = "mul:auth:daemon:"
type DaemonTokenIdentity struct {
WorkspaceID string `json:"w"`
DaemonID string `json:"d"`
+ // OwnerID is the runtime owner the token was issued for ("" for
+ // Qoder-managed tokens). MUL-8154.
+ OwnerID string `json:"o,omitempty"`
}
// DaemonTokenCache caches resolved daemon-token (mdt_) lookups in Redis.
diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.go
index 2ce80ccad0..53a696d5a1 100644
--- a/server/internal/daemonws/hub.go
+++ b/server/internal/daemonws/hub.go
@@ -22,7 +22,16 @@ const (
// ClientIdentity captures the already-authenticated daemon connection scope.
type ClientIdentity struct {
DaemonID string
- UserID string
+ // DaemonTokenHash is the hash of the mdt_ token that authenticated the
+ // connection (empty for user credentials). RPCs replay requests without
+ // an Authorization header, so credential-specific checks such as Qoder
+ // revocation re-validate this hash on every call (MUL-8154).
+ DaemonTokenHash string
+ // DaemonTokenOwnerID is the runtime owner that token is bound to (empty
+ // for Qoder-managed tokens and user credentials), replayed into every RPC
+ // so the per-runtime owner binding holds over WS as well (MUL-8154).
+ DaemonTokenOwnerID string
+ UserID string
// WorkspaceID is the legacy single-workspace scope used by older callers
// and daemon-token auth. New code should populate WorkspaceIDs from the
// runtime rows authorized for this connection.
diff --git a/server/internal/handler/chat_channel_debounce_boundary_test.go b/server/internal/handler/chat_channel_debounce_boundary_test.go
index d0ba2980b2..2c60fdc37a 100644
--- a/server/internal/handler/chat_channel_debounce_boundary_test.go
+++ b/server/internal/handler/chat_channel_debounce_boundary_test.go
@@ -55,8 +55,7 @@ type claimResult struct {
func claimTaskRaw(t *testing.T, runtimeID, daemonID string) claimResult {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
- testWorkspaceID, daemonID)
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("runtimeId", runtimeID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/chat_project_context_test.go b/server/internal/handler/chat_project_context_test.go
index 47011b5307..13054a787e 100644
--- a/server/internal/handler/chat_project_context_test.go
+++ b/server/internal/handler/chat_project_context_test.go
@@ -327,12 +327,10 @@ func TestClaimTaskByRuntime_ChatProjectContext(t *testing.T) {
})
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(
+ req := newOwnerDaemonRequest(
http.MethodPost,
"/api/daemon/runtimes/"+runtimeID+"/claim",
nil,
- testWorkspaceID,
- "chat-project-context-test",
)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
diff --git a/server/internal/handler/claim_project_context_test.go b/server/internal/handler/claim_project_context_test.go
index 207188afd0..6d6e6e5638 100644
--- a/server/internal/handler/claim_project_context_test.go
+++ b/server/internal/handler/claim_project_context_test.go
@@ -125,8 +125,7 @@ func TestClaimTask_IssueProjectInForeignWorkspace_DegradesToWorkspaceRepos(t *te
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
- testWorkspaceID, "test-claim-foreign-issue-project")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -257,8 +256,7 @@ func TestClaimTask_ProjectResourceFromForeignWorkspace_IsFilteredOut(t *testing.
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
- testWorkspaceID, "test-claim-foreign-resource")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -322,8 +320,7 @@ func TestClaimTask_AutopilotRunOnlyForeignWorkspace_CancelsTask(t *testing.T) {
"autopilot_run_id": foreignRunID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+localRuntimeID+"/claim", nil,
- testWorkspaceID, "test-claim-foreign-autopilot")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+localRuntimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", localRuntimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)
if !strings.Contains(w.Text(), "task workspace isolation check failed") {
diff --git a/server/internal/handler/comment_reconcile_test.go b/server/internal/handler/comment_reconcile_test.go
index 0a6de2c0be..9c1433e14e 100644
--- a/server/internal/handler/comment_reconcile_test.go
+++ b/server/internal/handler/comment_reconcile_test.go
@@ -18,9 +18,9 @@ import (
func completeTaskViaHandler(t *testing.T, taskID, output string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{"output": output},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/comment_steer_test.go b/server/internal/handler/comment_steer_test.go
index 1e6ea10634..1597de2048 100644
--- a/server/internal/handler/comment_steer_test.go
+++ b/server/internal/handler/comment_steer_test.go
@@ -43,8 +43,8 @@ func runningSteerableTask(t *testing.T, f supplementFixture, name string) (agent
func completeTaskViaDaemon(t *testing.T, taskID string) {
t.Helper()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/complete",
- map[string]any{"output": "done"}, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/complete",
+ map[string]any{"output": "done"})
testutil.Call(t, testHandler.CompleteTask, withURLParam(req, "taskId", taskID)).Want(http.StatusOK)
}
diff --git a/server/internal/handler/comment_worker_handoff_test.go b/server/internal/handler/comment_worker_handoff_test.go
index ec60baaf4e..e8d5a78b5a 100644
--- a/server/internal/handler/comment_worker_handoff_test.go
+++ b/server/internal/handler/comment_worker_handoff_test.go
@@ -18,7 +18,7 @@ import (
func claimWorkerReplyRun(t *testing.T, runtimeID string) *AgentTaskResponse {
t.Helper()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "worker-reply-handoff")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityCoalescedCommentsV1)
var response struct {
@@ -30,7 +30,7 @@ func claimWorkerReplyRun(t *testing.T, runtimeID string) *AgentTaskResponse {
func completeWorkerReplyRun(t *testing.T, taskID string) {
t.Helper()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/complete", map[string]any{"output": "Processed the inputs delivered to this run"}, testWorkspaceID, "worker-reply-handoff")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/complete", map[string]any{"output": "Processed the inputs delivered to this run"})
req = withURLParam(req, "taskId", taskID)
testutil.Call(t, testHandler.CompleteTask, req).Want(http.StatusOK)
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 2234e216f7..48938d6f9f 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -93,7 +93,74 @@ func (h *Handler) requireDaemonWorkspaceAccess(w http.ResponseWriter, r *http.Re
return ok
}
-// requireDaemonRuntimeAccess looks up a runtime and verifies the caller owns its workspace.
+// daemonRuntimeBindingAllowed is the runtime-level half of daemon
+// authorization (MUL-8154). Workspace access alone is not enough: every
+// member of a workspace can reach /api/daemon/* with their own PAT/JWT, and
+// without this check could claim another member's tasks (receiving the
+// agent's custom_env, MCP config and a task token minted for the runtime
+// owner) or write results into them.
+//
+// - Daemon token (mdt_): the token is bound to one daemon, so the runtime
+// must carry that exact, non-empty daemon_id. A runtime with no daemon_id
+// is never reachable through a daemon token — those tokens are also minted
+// per task for Remote MCP, so "same workspace" is far too wide. A daemon_id
+// can be re-registered by another member once its runtimes are deleted,
+// so the token must also be bound to the runtime's current owner;
+// unbound tokens are accepted only for Qoder-managed daemons, whose
+// tokens are governed by their cloud_agent_connection instead.
+// - User credential (PAT / JWT / mcn_): the caller must be the runtime's
+// owner. A NULL owner fails closed; ownerless rows are only reachable by
+// a daemon token for their own daemon.
+//
+// Callers must have already passed requireDaemonWorkspaceAccess (or its
+// non-writing sibling) — this does not re-check membership or workspace.
+func daemonRuntimeBindingAllowed(r *http.Request, daemonID pgtype.Text, ownerID pgtype.UUID) bool {
+ ctx := r.Context()
+ if middleware.DaemonWorkspaceIDFromContext(ctx) != "" {
+ tokenDaemonID := middleware.DaemonIDFromContext(ctx)
+ if tokenDaemonID == "" || !daemonID.Valid ||
+ strings.TrimSpace(daemonID.String) == "" || daemonID.String != tokenDaemonID {
+ return false
+ }
+ if isQoderManagedDaemonID(tokenDaemonID) {
+ return true
+ }
+ tokenOwnerID := middleware.DaemonTokenOwnerIDFromContext(ctx)
+ return tokenOwnerID != "" && ownerID.Valid && uuidToString(ownerID) == tokenOwnerID
+ }
+ userID := requestUserID(r)
+ return userID != "" && ownerID.Valid && uuidToString(ownerID) == userID
+}
+
+// isQoderManagedDaemonID reports the reserved daemon_id namespace of the
+// server-run Qoder bridge.
+func isQoderManagedDaemonID(daemonID string) bool {
+ return strings.HasPrefix(daemonID, "qoder-managed-")
+}
+
+// requireDaemonRuntimeAuthorized combines workspace access with the runtime
+// binding check and writes the error itself. A binding refusal is reported
+// as 404 so a non-owner cannot probe for other members' runtime ids.
+func (h *Handler) requireDaemonRuntimeAuthorized(w http.ResponseWriter, r *http.Request, workspaceID string, daemonID pgtype.Text, ownerID pgtype.UUID, notFoundMsg string) bool {
+ if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {
+ return false
+ }
+ if !daemonRuntimeBindingAllowed(r, daemonID, ownerID) {
+ writeError(w, http.StatusNotFound, notFoundMsg)
+ return false
+ }
+ return true
+}
+
+// verifyDaemonRuntimeAuthorized is the non-writing sibling used by batch
+// loops that skip unauthorized runtimes instead of failing the request.
+func (h *Handler) verifyDaemonRuntimeAuthorized(r *http.Request, rt db.AgentRuntime) bool {
+ return h.verifyDaemonWorkspaceAccess(r, uuidToString(rt.WorkspaceID)) &&
+ daemonRuntimeBindingAllowed(r, rt.DaemonID, rt.OwnerID)
+}
+
+// requireDaemonRuntimeAccess looks up a runtime and verifies the caller may
+// act as its daemon: workspace access plus daemonRuntimeBindingAllowed.
//
// Only pgx.ErrNoRows is treated as a real "runtime gone" 404 — the daemon uses
// that response to drop the stale runtime from its in-memory map and re-register,
@@ -114,13 +181,14 @@ func (h *Handler) requireDaemonRuntimeAccess(w http.ResponseWriter, r *http.Requ
writeError(w, http.StatusInternalServerError, "failed to load runtime")
return db.AgentRuntime{}, false
}
- if !h.requireDaemonWorkspaceAccess(w, r, uuidToString(rt.WorkspaceID)) {
+ if !h.requireDaemonRuntimeAuthorized(w, r, uuidToString(rt.WorkspaceID), rt.DaemonID, rt.OwnerID, "runtime not found") {
return db.AgentRuntime{}, false
}
return rt, true
}
-// requireDaemonTaskAccess looks up a task and verifies the caller owns its workspace.
+// requireDaemonTaskAccess looks up a task and verifies the caller may act as
+// the daemon of the runtime the task is bound to.
func (h *Handler) requireDaemonTaskAccess(w http.ResponseWriter, r *http.Request, taskID string) (db.AgentTaskQueue, bool) {
task, _, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)
return task, ok
@@ -133,6 +201,14 @@ func (h *Handler) requireDaemonTaskAccess(w http.ResponseWriter, r *http.Request
// ResolveTaskWorkspaceID lookup. The two helpers share their entire
// implementation; the simpler one is preserved for ergonomic call sites
// that genuinely don't need workspace_id.
+//
+// Authorization is runtime-level (MUL-8154): the task must be bound to a
+// runtime in the task's own workspace, and the caller must pass
+// daemonRuntimeBindingAllowed for that runtime. A task with no runtime
+// (runtime deleted; the task was unbound and kept as history) has no
+// provable executor, so it is reported as not found — these routes write
+// results, messages and credentials, and "any workspace member" must not be
+// a fallback for them.
func (h *Handler) requireDaemonTaskAccessWithWorkspace(w http.ResponseWriter, r *http.Request, taskID string) (db.AgentTaskQueue, string, bool) {
taskUUID, ok := parseUUIDOrBadRequest(w, taskID, "task_id")
if !ok {
@@ -172,6 +248,24 @@ func (h *Handler) requireDaemonTaskAccessWithWorkspace(w http.ResponseWriter, r
if !h.requireDaemonWorkspaceAccess(w, r, wsID) {
return db.AgentTaskQueue{}, "", false
}
+ if !task.RuntimeID.Valid {
+ writeError(w, http.StatusNotFound, "task not found")
+ return db.AgentTaskQueue{}, "", false
+ }
+ rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, task.RuntimeID)
+ if err != nil {
+ if isNotFound(err) {
+ writeError(w, http.StatusNotFound, "task not found")
+ return db.AgentTaskQueue{}, "", false
+ }
+ slog.Warn("get task runtime failed", "task_id", taskID, "error", err)
+ writeError(w, http.StatusInternalServerError, "failed to load task")
+ return db.AgentTaskQueue{}, "", false
+ }
+ if uuidToString(rt.WorkspaceID) != wsID || !daemonRuntimeBindingAllowed(r, rt.DaemonID, rt.OwnerID) {
+ writeError(w, http.StatusNotFound, "task not found")
+ return db.AgentTaskQueue{}, "", false
+ }
return task, wsID, true
}
@@ -182,7 +276,16 @@ func (h *Handler) verifyDaemonWorkspaceAccess(r *http.Request, workspaceID strin
return false
}
if daemonWsID := middleware.DaemonWorkspaceIDFromContext(r.Context()); daemonWsID != "" {
- return daemonWsID == workspaceID
+ if daemonWsID != workspaceID {
+ return false
+ }
+ // Same revocation rule as requireDaemonWorkspaceAccess; an
+ // unavailable check skips the item rather than allowing it.
+ if daemonID := middleware.DaemonIDFromContext(r.Context()); strings.HasPrefix(daemonID, "qoder-managed-") {
+ allowed, err := h.qoderCredentialAllowed(r, workspaceID, daemonID)
+ return err == nil && allowed
+ }
+ return true
}
userID := requestUserID(r)
if userID == "" {
@@ -319,11 +422,11 @@ func normalizeProvider(s string) string {
// existing rows keep whatever they already have. A lookup/update error is
// non-fatal — registration must still succeed — so the input row is returned
// unchanged on any failure.
-func (h *Handler) inheritMachineCustomName(ctx context.Context, rt db.AgentRuntime, inserted bool) db.AgentRuntime {
+func (h *Handler) inheritMachineCustomName(ctx context.Context, q *db.Queries, rt db.AgentRuntime, inserted bool) db.AgentRuntime {
if !inserted || rt.CustomName.Valid || !rt.DaemonID.Valid {
return rt
}
- names, err := h.Queries.ListDaemonCustomNames(ctx, db.ListDaemonCustomNamesParams{
+ names, err := q.ListDaemonCustomNames(ctx, db.ListDaemonCustomNamesParams{
WorkspaceID: rt.WorkspaceID,
DaemonID: rt.DaemonID,
ExcludeID: rt.ID,
@@ -335,7 +438,7 @@ func (h *Handler) inheritMachineCustomName(ctx context.Context, rt db.AgentRunti
if !ok {
return rt
}
- updated, err := h.Queries.UpdateAgentRuntimeCustomName(ctx, db.UpdateAgentRuntimeCustomNameParams{
+ updated, err := q.UpdateAgentRuntimeCustomName(ctx, db.UpdateAgentRuntimeCustomNameParams{
CustomName: pgtype.Text{String: shared, Valid: true},
ID: rt.ID,
})
@@ -352,22 +455,19 @@ var errRuntimeProfileDisabled = errors.New("runtime profile is disabled")
// commits; DeleteRuntimeProfile takes a conflicting UPDATE lock before it
// enumerates runtime rows. This closes the stale-read window where deletion
// could miss an instance inserted by a concurrently registering daemon.
+//
+// It runs on the caller's registration transaction (MUL-8154), so the profile
+// lock is held until the whole registration commits.
func (h *Handler) upsertRuntimeWithProfile(
ctx context.Context,
+ qtx *db.Queries,
workspaceID, profileID pgtype.UUID,
build func(db.RuntimeProfile) db.UpsertAgentRuntimeWithProfileParams,
) (db.UpsertAgentRuntimeWithProfileRow, db.RuntimeProfile, error) {
var row db.UpsertAgentRuntimeWithProfileRow
var profile db.RuntimeProfile
- tx, err := h.TxStarter.Begin(ctx)
- if err != nil {
- return row, profile, fmt.Errorf("begin profile runtime registration: %w", err)
- }
- defer tx.Rollback(ctx)
- qtx := h.Queries.WithTx(tx)
-
- profile, err = qtx.LockRuntimeProfileForRegistration(ctx, db.LockRuntimeProfileForRegistrationParams{
+ profile, err := qtx.LockRuntimeProfileForRegistration(ctx, db.LockRuntimeProfileForRegistrationParams{
ID: profileID,
WorkspaceID: workspaceID,
})
@@ -380,11 +480,15 @@ func (h *Handler) upsertRuntimeWithProfile(
row, err = qtx.UpsertAgentRuntimeWithProfile(ctx, build(profile))
if err != nil {
+ // The profile lookup above already turned "unknown profile" into
+ // ErrNoRows; here ErrNoRows can only mean the ownership fence
+ // refused the conflict update, which must not be reported as an
+ // unknown profile.
+ if errors.Is(err, pgx.ErrNoRows) {
+ return row, profile, errRuntimeOwnedByAnotherUser
+ }
return row, profile, fmt.Errorf("upsert profile runtime: %w", err)
}
- if err := tx.Commit(ctx); err != nil {
- return row, profile, fmt.Errorf("commit profile runtime registration: %w", err)
- }
return row, profile, nil
}
@@ -415,6 +519,33 @@ func sharedDaemonCustomName(names []pgtype.Text) (string, bool) {
return first, true
}
+// beginDaemonRegistration opens the transaction a registration's ownership
+// pre-check and every runtime write run in, after taking a transaction-scoped
+// advisory lock on (workspace_id, daemon_id). Registrations of the same daemon
+// therefore run one at a time and each pre-check sees what the previous one
+// committed (MUL-8154 review). Everything under the lock runs on this one
+// connection, so a queue of waiting registrations cannot starve the holder of
+// pool connections.
+func (h *Handler) beginDaemonRegistration(ctx context.Context, workspaceID, daemonID string) (pgx.Tx, error) {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("begin registration: %w", err)
+ }
+ if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 8154))`, workspaceID+"/"+daemonID); err != nil {
+ _ = tx.Rollback(context.Background())
+ return nil, fmt.Errorf("acquire registration lock: %w", err)
+ }
+ return tx, nil
+}
+
+// errRuntimeOwnedByAnotherUser reports that a user-credential registration
+// hit a runtime row (same workspace + daemon_id) that the caller does not own.
+// MUL-8154: re-registering a row used to rewrite owner_id to the caller, so
+// any member could take over another member's runtime.
+var errRuntimeOwnedByAnotherUser = errors.New("runtime is registered to another user")
+
+const runtimeOwnedByAnotherUserMessage = "this daemon's runtimes are registered to another user; remove them from the workspace or sign the daemon in as their owner"
+
func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
var req DaemonRegisterRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -459,6 +590,34 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "daemon identity mismatch")
return
}
+ // Qoder-managed daemon tokens are exempt from the owner binding below,
+ // so the exemption is granted only after the token is proven to belong to
+ // a live cloud_agent_connection — unconditionally, not just when the body
+ // declares a qoder_cloud runtime (MUL-8154 review round 4). Pre-upgrade
+ // tokens under this prefix were issued for ordinary runtimes and carry no
+ // such binding. The bridge only ever registers one built-in qoder_cloud
+ // runtime, so anything else under this namespace is refused too.
+ if tokenDaemonID := middleware.DaemonIDFromContext(r.Context()); tokenDaemonID != "" && isQoderManagedDaemonID(tokenDaemonID) {
+ allowed, err := h.qoderCredentialAllowed(r, req.WorkspaceID, req.DaemonID)
+ if err != nil {
+ writeError(w, http.StatusServiceUnavailable, "runtime authorization unavailable")
+ return
+ }
+ if !allowed {
+ writeError(w, http.StatusForbidden, "managed runtime credential required")
+ return
+ }
+ if len(req.FailedProfiles) > 0 {
+ writeError(w, http.StatusForbidden, "managed runtime registration must be a single qoder_cloud runtime")
+ return
+ }
+ for _, rt := range req.Runtimes {
+ if normalizeProvider(rt.Type) != "qoder_cloud" || strings.TrimSpace(rt.ProfileID) != "" {
+ writeError(w, http.StatusForbidden, "managed runtime registration must be a single qoder_cloud runtime")
+ return
+ }
+ }
+ }
for _, rt := range req.Runtimes {
if normalizeProvider(rt.Type) != "qoder_cloud" {
continue
@@ -482,22 +641,50 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
}
// Verify workspace access and resolve owner.
- // Daemon tokens (mdt_) prove workspace access directly; OwnerID will be zero
- // (the SQL COALESCE preserves any existing owner on upsert).
- // PAT/JWT tokens require a membership check and set OwnerID from the member.
- var ownerID pgtype.UUID
+ // - User credential (PAT/JWT): membership check; the member is the owner.
+ // - Non-Qoder daemon token: the owner the token is bound to (MUL-8154).
+ // The same pre-check and SQL fence apply, so a token issued for one
+ // owner cannot rewrite a runtime another member re-registered under
+ // this daemon_id. Unbound tokens (pre-588) are refused.
+ // - Qoder-managed daemon token: ownerID stays zero (COALESCE keeps the
+ // existing owner); the credential was checked against its
+ // cloud_agent_connection above.
+ // mergeOwnerID is set only for user credentials: daemon tokens never
+ // trigger legacy merges.
+ var ownerID, mergeOwnerID pgtype.UUID
if daemonWsID := middleware.DaemonWorkspaceIDFromContext(r.Context()); daemonWsID != "" {
if daemonWsID != req.WorkspaceID {
writeError(w, http.StatusNotFound, "workspace not found")
return
}
- // ownerID stays zero — COALESCE keeps the existing owner on upsert.
+ if !isQoderManagedDaemonID(req.DaemonID) {
+ tokenOwner := middleware.DaemonTokenOwnerIDFromContext(r.Context())
+ if tokenOwner == "" {
+ writeError(w, http.StatusForbidden, "daemon credential is not bound to a runtime owner")
+ return
+ }
+ ownerUUID, err := util.ParseUUID(tokenOwner)
+ if err != nil {
+ writeError(w, http.StatusForbidden, "daemon credential is not bound to a runtime owner")
+ return
+ }
+ ownerID = ownerUUID
+ }
} else {
member, ok := h.requireWorkspaceMember(w, r, req.WorkspaceID, "workspace not found")
if !ok {
return
}
ownerID = member.UserID
+ mergeOwnerID = member.UserID
+
+ // The Qoder-managed namespace is reserved for the server's bridge
+ // and its daemon token, which is not owner-bound; a member must not
+ // be able to own a runtime that token would reach (MUL-8154).
+ if isQoderManagedDaemonID(req.DaemonID) {
+ writeError(w, http.StatusForbidden, "reserved daemon_id")
+ return
+ }
}
ws, err := h.Queries.GetWorkspace(r.Context(), wsUUID)
@@ -506,6 +693,51 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
return
}
+ // One transaction for the ownership pre-check and every runtime write,
+ // serialized per (workspace, daemon_id) for both auth paths (MUL-8154
+ // review). The pre-check and the per-provider / per-profile upserts hit
+ // different conflict keys, so without this two members registering
+ // different providers of the same daemon could both read "no rows" and
+ // both insert — one daemon, two owners, and a daemon token minted for
+ // either runtime would then reach the other's. A failure anywhere rolls
+ // the whole registration back. Legacy merges, analytics and the
+ // register event run only after commit.
+ tx, err := h.beginDaemonRegistration(r.Context(), req.WorkspaceID, req.DaemonID)
+ if err != nil {
+ slog.Warn("register: begin registration failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusServiceUnavailable, "failed to register runtime")
+ return
+ }
+ defer tx.Rollback(context.Background())
+ qtx := h.Queries.WithTx(tx)
+ var afterCommit []func()
+
+ if ownerID.Valid {
+ // Ownership pre-check: every row this daemon_id already holds in
+ // the workspace must belong to the caller — including ownerless
+ // rows, which ordinary registration must not silently claim. The
+ // upserts keep the same fence in SQL (required_owner_id) as
+ // defense in depth.
+ existing, err := qtx.ListRuntimeOwnersByDaemon(r.Context(), db.ListRuntimeOwnersByDaemonParams{
+ WorkspaceID: wsUUID,
+ DaemonID: strToText(req.DaemonID),
+ })
+ if err != nil {
+ slog.Warn("register: runtime owner pre-check failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to register runtime")
+ return
+ }
+ for _, row := range existing {
+ if !row.OwnerID.Valid || row.OwnerID != ownerID {
+ slog.Warn("register: refused runtime owned by another user",
+ "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,
+ "runtime_id", uuidToString(row.ID))
+ writeError(w, http.StatusForbidden, runtimeOwnedByAnotherUserMessage)
+ return
+ }
+ }
+ }
+
resp := make([]AgentRuntimeResponse, 0, len(req.Runtimes))
for _, runtime := range req.Runtimes {
provider := normalizeProvider(runtime.Type)
@@ -554,6 +786,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
// the provider used for task routing cannot drift from the profile.
prow, profile, err := h.upsertRuntimeWithProfile(
r.Context(),
+ qtx,
wsUUID,
profileUUID,
func(profile db.RuntimeProfile) db.UpsertAgentRuntimeWithProfileParams {
@@ -568,9 +801,16 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
Metadata: metadata,
OwnerID: ownerID,
ProfileID: profileUUID,
+ // Ownership fence: zero (no fence) on the daemon-token
+ // path, the caller on the user-credential path.
+ RequiredOwnerID: ownerID,
}
},
)
+ if errors.Is(err, errRuntimeOwnedByAnotherUser) {
+ writeError(w, http.StatusForbidden, runtimeOwnedByAnotherUserMessage)
+ return
+ }
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusBadRequest, "unknown runtime profile: "+runtime.ProfileID)
return
@@ -615,7 +855,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
ProfileID: prow.ProfileID,
}
} else {
- row, err := h.Queries.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{
+ row, err := qtx.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{
WorkspaceID: wsUUID,
DaemonID: strToText(req.DaemonID),
Name: name,
@@ -625,7 +865,14 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
DeviceInfo: deviceInfo,
Metadata: metadata,
OwnerID: ownerID,
+ // See the profile branch: the SQL fence that backs the
+ // pre-check against a concurrent registration.
+ RequiredOwnerID: ownerID,
})
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusForbidden, runtimeOwnedByAnotherUserMessage)
+ return
+ }
if err != nil {
obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeFailed(
uuidToString(ownerID),
@@ -665,30 +912,33 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
// A brand-new runtime on an already-named machine inherits the machine's
// shared custom name so the machine title stays stable as providers come
// and go (MUL-4217). Shared with the failed-profile path below.
- registered = h.inheritMachineCustomName(r.Context(), registered, inserted)
+ registered = h.inheritMachineCustomName(r.Context(), qtx, registered, inserted)
// Inserted is false for normal daemon reconnects/upserts, so
// runtime_ready is a first-ready-per-runtime-row signal.
if inserted {
- obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeRegistered(
- uuidToString(ownerID),
- req.WorkspaceID,
- uuidToString(registered.ID),
- req.DaemonID,
- provider,
- runtime.Version,
- req.CLIVersion,
- ))
- if registered.Status == "online" {
- obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeReady(
+ registered, provider, runtime := registered, provider, runtime
+ afterCommit = append(afterCommit, func() {
+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeRegistered(
uuidToString(ownerID),
req.WorkspaceID,
uuidToString(registered.ID),
req.DaemonID,
provider,
- 0,
+ runtime.Version,
+ req.CLIVersion,
))
- }
+ if registered.Status == "online" {
+ obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.RuntimeReady(
+ uuidToString(ownerID),
+ req.WorkspaceID,
+ uuidToString(registered.ID),
+ req.DaemonID,
+ provider,
+ 0,
+ ))
+ }
+ })
}
// Seamless migration from the previous hostname-derived identity. The
@@ -702,8 +952,13 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
// ancestor to merge, and mergeLegacyRuntimes scopes by provider alone
// (no profile_id), which could otherwise fold a built-in row into a
// custom one of the same provider.
+ // Merges lock both runtime rows in their own transaction, so they
+ // must run after this registration commits the new row.
if !isCustom {
- h.mergeLegacyRuntimes(r, registered, provider, req.LegacyDaemonIDs)
+ registered, provider := registered, provider
+ afterCommit = append(afterCommit, func() {
+ h.mergeLegacyRuntimes(r, registered, provider, req.LegacyDaemonIDs, mergeOwnerID)
+ })
}
resp = append(resp, runtimeToResponse(registered))
@@ -722,8 +977,18 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
reason = "custom runtime command could not be resolved"
}
commandName := strings.TrimSpace(failed.CommandName)
+ // Best effort, as before: a savepoint keeps one failed record from
+ // aborting the registration transaction.
+ sp, err := tx.Begin(r.Context())
+ if err != nil {
+ slog.Warn("failed to record runtime profile registration failure",
+ "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,
+ "profile_id", profileID, "error", err)
+ continue
+ }
prow, _, err := h.upsertRuntimeWithProfile(
r.Context(),
+ h.Queries.WithTx(sp),
wsUUID,
profileUUID,
func(profile db.RuntimeProfile) db.UpsertAgentRuntimeWithProfileParams {
@@ -751,20 +1016,28 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
"command_name": resolvedCommandName,
})
return db.UpsertAgentRuntimeWithProfileParams{
- WorkspaceID: wsUUID,
- DaemonID: strToText(req.DaemonID),
- Name: name,
- RuntimeMode: "local",
- Provider: agent.ProfileRuntimeType(profile.RuntimeType, profile.ProtocolFamily),
- Status: "offline",
- DeviceInfo: strings.TrimSpace(req.DeviceName),
- Metadata: metadata,
- OwnerID: ownerID,
- ProfileID: profileUUID,
+ WorkspaceID: wsUUID,
+ DaemonID: strToText(req.DaemonID),
+ Name: name,
+ RuntimeMode: "local",
+ Provider: agent.ProfileRuntimeType(profile.RuntimeType, profile.ProtocolFamily),
+ Status: "offline",
+ DeviceInfo: strings.TrimSpace(req.DeviceName),
+ Metadata: metadata,
+ OwnerID: ownerID,
+ ProfileID: profileUUID,
+ RequiredOwnerID: ownerID,
}
},
)
if err != nil {
+ _ = sp.Rollback(r.Context())
+ slog.Warn("failed to record runtime profile registration failure",
+ "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,
+ "profile_id", profileID, "error", err)
+ continue
+ }
+ if err := sp.Commit(r.Context()); err != nil {
slog.Warn("failed to record runtime profile registration failure",
"workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID,
"profile_id", profileID, "error", err)
@@ -772,7 +1045,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
}
// Keep the failed-profile row consistent with the machine's name so it
// doesn't drag the machine title back to the hostname (MUL-4217).
- h.inheritMachineCustomName(r.Context(), db.AgentRuntime{
+ h.inheritMachineCustomName(r.Context(), qtx, db.AgentRuntime{
ID: prow.ID,
WorkspaceID: prow.WorkspaceID,
DaemonID: prow.DaemonID,
@@ -780,6 +1053,15 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
}, prow.Inserted)
}
+ if err := tx.Commit(r.Context()); err != nil {
+ slog.Warn("register: commit failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to register runtime")
+ return
+ }
+ for _, fn := range afterCommit {
+ fn()
+ }
+
slog.Info("daemon registered", "workspace_id", req.WorkspaceID, "daemon_id", req.DaemonID, "runtimes_count", len(resp))
h.publish(protocol.EventDaemonRegister, req.WorkspaceID, "system", "", map[string]any{
@@ -814,7 +1096,23 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
// precisely when case-duplicate rows exist — which is the bug we're fixing.
// We also dedupe across legacy ids so overlapping candidates (e.g. `foo` and
// `foo.local` both resolving to the same stored row) don't double-process.
-func (h *Handler) mergeLegacyRuntimes(r *http.Request, registered db.AgentRuntime, provider string, legacyIDs []string) {
+//
+// Authorization (MUL-8154): legacy_daemon_ids are client-supplied, so they are
+// a lookup hint, never proof of ownership. callerOwnerID is the user the
+// registration was authenticated as; the merge only proceeds when it is set
+// and owns both rows (re-verified on the locked rows inside the merge
+// transaction). A daemon-token registration passes a zero callerOwnerID and so
+// never merges: its token proves only its own daemon_id, and legacy rows
+// predate daemon tokens anyway.
+func (h *Handler) mergeLegacyRuntimes(r *http.Request, registered db.AgentRuntime, provider string, legacyIDs []string, callerOwnerID pgtype.UUID) {
+ if len(legacyIDs) == 0 {
+ return
+ }
+ if !callerOwnerID.Valid {
+ slog.Warn("legacy runtime merge skipped: registration has no user identity",
+ "new_runtime_id", uuidToString(registered.ID))
+ return
+ }
newID := uuidToString(registered.ID)
merged := make(map[string]struct{})
@@ -843,7 +1141,7 @@ func (h *Handler) mergeLegacyRuntimes(r *http.Request, registered db.AgentRuntim
}
merged[oldID] = struct{}{}
- if err := h.mergeLegacyRuntime(r.Context(), registered.ID, old.ID, legacyID, provider); err != nil {
+ if err := h.mergeLegacyRuntime(r.Context(), registered.ID, old.ID, legacyID, provider, callerOwnerID); err != nil {
slog.Warn("legacy runtime merge failed",
"legacy_daemon_id", legacyID, "old_runtime_id", oldID, "new_runtime_id", newID, "error", err)
}
@@ -858,6 +1156,11 @@ func (h *Handler) mergeLegacyRuntimes(r *http.Request, registered db.AgentRuntim
// the teardown rolled back.
var errRuntimeMergeFenced = errors.New("runtime merge refused by the task-write fence")
+// errRuntimeMergeUnauthorized reports that the locked rows failed the
+// ownership check: different workspaces, or either side not owned by the
+// registering user. Nothing is moved or deleted.
+var errRuntimeMergeUnauthorized = errors.New("runtime merge refused: caller does not own both runtimes")
+
// mergeLegacyRuntime folds one legacy runtime row into the freshly registered one,
// as a single transaction.
//
@@ -886,7 +1189,7 @@ var errRuntimeMergeFenced = errors.New("runtime merge refused by the task-write
// Holding the fence lock from the first statement to COMMIT closes both: the
// teardown cannot start deleting the target until this merge finishes, and any
// failure rolls the whole merge back to its starting state.
-func (h *Handler) mergeLegacyRuntime(ctx context.Context, newRuntimeID, oldRuntimeID pgtype.UUID, legacyID, provider string) error {
+func (h *Handler) mergeLegacyRuntime(ctx context.Context, newRuntimeID, oldRuntimeID pgtype.UUID, legacyID, provider string, callerOwnerID pgtype.UUID) error {
tx, err := h.TxStarter.Begin(ctx)
if err != nil {
return fmt.Errorf("begin merge tx: %w", err)
@@ -913,6 +1216,16 @@ func (h *Handler) mergeLegacyRuntime(ctx context.Context, newRuntimeID, oldRunti
// inside the reassignment would refuse anyway.
return errRuntimeMergeFenced
}
+ // Ownership, checked on the rows we now hold FOR UPDATE so a concurrent
+ // owner change cannot slip in between check and move (MUL-8154).
+ if !callerOwnerID.Valid || len(locked) != 2 || locked[0].WorkspaceID != locked[1].WorkspaceID {
+ return errRuntimeMergeUnauthorized
+ }
+ for _, row := range locked {
+ if !row.OwnerID.Valid || row.OwnerID != callerOwnerID {
+ return errRuntimeMergeUnauthorized
+ }
+ }
reassignment, err := qtx.ReassignTasksToRuntime(ctx, db.ReassignTasksToRuntimeParams{
NewRuntimeID: newRuntimeID,
@@ -1045,8 +1358,8 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {
}
wsID := uuidToString(rt.WorkspaceID)
- if !h.verifyDaemonWorkspaceAccess(r, wsID) {
- slog.Warn("deregister: workspace mismatch", "runtime_id", rid)
+ if !h.verifyDaemonRuntimeAuthorized(r, rt) {
+ slog.Warn("deregister: runtime not authorized for caller", "runtime_id", rid)
continue
}
@@ -1203,7 +1516,7 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
return
}
wsCheckStart := time.Now()
- wsOK := h.requireDaemonWorkspaceAccess(w, r, uuidToString(rt.WorkspaceID))
+ wsOK := h.requireDaemonRuntimeAuthorized(w, r, uuidToString(rt.WorkspaceID), rt.DaemonID, rt.OwnerID, "runtime not found")
workspaceCheckMs = time.Since(wsCheckStart).Milliseconds()
if !wsOK {
outcome = "workspace_denied"
@@ -1865,7 +2178,11 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {
if !ok {
continue
}
- if !h.verifyDaemonWorkspaceAccess(r, uuidToString(rt.WorkspaceID)) {
+ // Workspace access plus runtime ownership / daemon binding
+ // (MUL-8154). For user credentials the body daemon_id is
+ // caller-chosen, so the daemon_id check below is not an
+ // authorization boundary on its own.
+ if !h.verifyDaemonRuntimeAuthorized(r, rt) {
continue
}
// Group-ownership check (mirrors the WS path, daemon_ws.go): a runtime
@@ -2355,6 +2672,9 @@ func remoteMCPDaemonTokenForClaim(resp AgentTaskResponse, runtime db.AgentRuntim
WorkspaceID: runtime.WorkspaceID,
DaemonID: runtime.DaemonID.String,
ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},
+ // Owner binding (MUL-8154). FinalizeTaskClaim re-binds it to the
+ // locked runtime owner inside the claim transaction.
+ OwnerID: runtime.OwnerID,
}}, nil
}
@@ -5073,9 +5393,21 @@ func (h *Handler) GetTaskStatus(w http.ResponseWriter, r *http.Request) {
return
}
+ // Runtime-level authorization (MUL-8154) from the same row: a bound task
+ // is visible only to its runtime's daemon (owner / matching daemon token).
+ // An unbound task — its runtime was deleted and the task kept as history —
+ // exposes only its status, so workspace access stays sufficient there:
+ // the daemon still needs a terminal answer to stop polling.
if !h.requireDaemonWorkspaceAccess(w, r, uuidToString(task.WorkspaceID)) {
return
}
+ if task.RuntimeID.Valid {
+ if uuidToString(task.RuntimeWorkspaceID) != uuidToString(task.WorkspaceID) ||
+ !daemonRuntimeBindingAllowed(r, task.RuntimeDaemonID, task.RuntimeOwnerID) {
+ writeError(w, http.StatusNotFound, "task not found")
+ return
+ }
+ }
writeJSON(w, http.StatusOK, map[string]string{"status": task.Status})
}
diff --git a/server/internal/handler/daemon_batch_claim_deadline_test.go b/server/internal/handler/daemon_batch_claim_deadline_test.go
index 8fed75ade2..bfbfc478b2 100644
--- a/server/internal/handler/daemon_batch_claim_deadline_test.go
+++ b/server/internal/handler/daemon_batch_claim_deadline_test.go
@@ -15,7 +15,6 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/daemonws"
- "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -77,7 +76,7 @@ func TestClaimTasksByRuntime_PartialSuccessFitsClientDeadlines(t *testing.T) {
return status, response, err
})
identity := daemonws.ClientIdentity{
- DaemonID: batchClaimTestDaemonID, UserID: testUserID,
+ UserID: testUserID, // user-credential connection: no daemon id
WorkspaceID: testWorkspaceID, WorkspaceIDs: []string{testWorkspaceID},
RuntimeIDs: []string{runtimeID}, Capabilities: protocol.DaemonCapabilityClaimPollHintsV1,
}
@@ -88,7 +87,7 @@ func TestClaimTasksByRuntime_PartialSuccessFitsClientDeadlines(t *testing.T) {
}
defer close(completed)
r.Header.Set("X-Client-Capabilities", identity.Capabilities)
- h.ClaimTasksByRuntime(w, r.WithContext(middleware.WithDaemonContext(r.Context(), testWorkspaceID, batchClaimTestDaemonID)))
+ h.ClaimTasksByRuntime(w, asRuntimeOwner(r))
}))
defer server.Close()
body, err := json.Marshal(map[string]any{
diff --git a/server/internal/handler/daemon_batch_claim_notifications_test.go b/server/internal/handler/daemon_batch_claim_notifications_test.go
index 29efad8b62..ba7caf9912 100644
--- a/server/internal/handler/daemon_batch_claim_notifications_test.go
+++ b/server/internal/handler/daemon_batch_claim_notifications_test.go
@@ -19,7 +19,6 @@ import (
"github.com/jackc/pgx/v5"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/events"
- "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/realtime"
"github.com/multica-ai/multica/server/internal/service"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -120,7 +119,7 @@ func TestClaimTasksByRuntime_HTTPFollowupDoesNotWaitForRecovery(t *testing.T) {
firstCompleted := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wrapped := chimw.NewWrapResponseWriter(chimw.NewWrapResponseWriter(w, r.ProtoMajor), r.ProtoMajor)
- r = r.WithContext(middleware.WithDaemonContext(r.Context(), testWorkspaceID, batchClaimTestDaemonID))
+ r = asRuntimeOwner(r)
if requests.Add(1) == 1 {
defer close(firstCompleted)
firstHandler.ClaimTasksByRuntime(wrapped, r)
@@ -243,7 +242,7 @@ func TestClaimTasksByRuntime_ResponsePrecedesRecoveryNotifications(t *testing.T)
return status, response, err
})
identity := daemonws.ClientIdentity{
- DaemonID: batchClaimTestDaemonID, UserID: testUserID,
+ UserID: testUserID, // user-credential connection: no daemon id
WorkspaceID: testWorkspaceID, WorkspaceIDs: []string{testWorkspaceID},
RuntimeIDs: []string{runtimeID}, Capabilities: protocol.DaemonCapabilityClaimPollHintsV1,
}
@@ -255,7 +254,7 @@ func TestClaimTasksByRuntime_ResponsePrecedesRecoveryNotifications(t *testing.T)
defer close(completed)
// The production logger and metrics both wrap the HTTP writer.
wrapped := chimw.NewWrapResponseWriter(chimw.NewWrapResponseWriter(w, r.ProtoMajor), r.ProtoMajor)
- h.ClaimTasksByRuntime(wrapped, r.WithContext(middleware.WithDaemonContext(r.Context(), testWorkspaceID, batchClaimTestDaemonID)))
+ h.ClaimTasksByRuntime(wrapped, asRuntimeOwner(r))
}))
defer server.Close()
defer releaseEvent() // Release a blocked event before server shutdown on failure.
diff --git a/server/internal/handler/daemon_batch_claim_recovery_test.go b/server/internal/handler/daemon_batch_claim_recovery_test.go
index 50af86b1d1..71e5f68d74 100644
--- a/server/internal/handler/daemon_batch_claim_recovery_test.go
+++ b/server/internal/handler/daemon_batch_claim_recovery_test.go
@@ -49,7 +49,7 @@ func TestClaimTasksByRuntime_DeadlineRecoveryOverWebSocket(t *testing.T) {
h.TaskService = service.NewTaskService(testHandler.Queries, testPool, testHandler.TaskService.Hub, testHandler.TaskService.Bus, hub)
hub.SetRPCHandler(h.DaemonRPCHandler)
identity := daemonws.ClientIdentity{
- DaemonID: batchClaimTestDaemonID, UserID: testUserID,
+ UserID: testUserID, // user-credential connection: no daemon id
WorkspaceID: testWorkspaceID, WorkspaceIDs: []string{testWorkspaceID},
RuntimeIDs: []string{runtimeID}, Capabilities: protocol.DaemonCapabilityClaimPollHintsV1,
}
diff --git a/server/internal/handler/daemon_batch_claim_test.go b/server/internal/handler/daemon_batch_claim_test.go
index 78de75c7ac..8f4fdc4fb4 100644
--- a/server/internal/handler/daemon_batch_claim_test.go
+++ b/server/internal/handler/daemon_batch_claim_test.go
@@ -56,8 +56,15 @@ func postBatchClaimWithCapabilities(t *testing.T, workspaceID string, runtimeIDs
}
func batchClaimRequest(workspaceID string, runtimeIDs []string, maxTasks int, capabilities string) *http.Request {
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/claim",
- map[string]any{"daemon_id": batchClaimTestDaemonID, "runtime_ids": runtimeIDs, "max_tasks": maxTasks}, workspaceID, batchClaimTestDaemonID)
+ body := map[string]any{"daemon_id": batchClaimTestDaemonID, "runtime_ids": runtimeIDs, "max_tasks": maxTasks}
+ // Own workspace: authenticate as the fixture runtimes' owner, as a real
+ // daemon does. Any other workspace stays a daemon-token scoping probe.
+ var req *http.Request
+ if workspaceID == testWorkspaceID {
+ req = newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/claim", body)
+ } else {
+ req = newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/claim", body, workspaceID, batchClaimTestDaemonID)
+ }
if capabilities != "" {
req.Header.Set("X-Client-Capabilities", capabilities)
}
@@ -69,6 +76,13 @@ func batchClaimRequest(workspaceID string, runtimeIDs []string, maxTasks int, ca
// consistency check passes on the happy path.
const batchClaimTestDaemonID = "batch-claim-review"
+// asRuntimeOwner authenticates r as the fixture runtimes' owner (testUserID)
+// with no daemon-token context — the user-credential daemon path.
+func asRuntimeOwner(r *http.Request) *http.Request {
+ r.Header.Set("X-User-ID", testUserID)
+ return r
+}
+
func TestClaimTasksByRuntime_ClaimPollHintSchedulesNextDeferredTask(t *testing.T) {
if testHandler == nil || testPool == nil {
t.Skip("database not available")
@@ -288,8 +302,8 @@ func TestClaimTasksByRuntime_CancelsTaskWhenRuntimeOwnerMissing(t *testing.T) {
var rtNull 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, owner_id)
- VALUES ($1, NULL, 'Ownerless RT', 'cloud', 'handler_test_runtime', 'online', 'x', '{}'::jsonb, now(), 'private', NULL)
- RETURNING id`, testWorkspaceID).Scan(&rtNull); err != nil {
+ VALUES ($1, $2, 'Ownerless RT', 'cloud', 'handler_test_runtime', 'online', 'x', '{}'::jsonb, now(), 'private', NULL)
+ RETURNING id`, testWorkspaceID, batchClaimTestDaemonID).Scan(&rtNull); err != nil {
t.Fatalf("ownerless runtime: %v", err)
}
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE id = $1`, rtNull) })
@@ -297,23 +311,32 @@ func TestClaimTasksByRuntime_CancelsTaskWhenRuntimeOwnerMissing(t *testing.T) {
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, rtNull, "Ownerless agent")
taskID := seedQueuedIssueTask(t, ctx, agentID, rtNull, issueID)
- w := postBatchClaim(t, testWorkspaceID, []string{rtNull}, 1)
- if w.Code != http.StatusOK {
- t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ // MUL-8154: a user credential never reaches an ownerless runtime — the
+ // batch skips it without touching the task.
+ userW := postBatchClaim(t, testWorkspaceID, []string{rtNull}, 1)
+ if userW.Code != http.StatusOK || strings.Contains(userW.Body.String(), taskID) {
+ t.Fatalf("user-credential batch claim reached the ownerless runtime: %d %s", userW.Code, userW.Body.String())
}
- var resp batchClaimResponse
- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
- t.Fatalf("decode: %v", err)
+ var untouched string
+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&untouched); err != nil || untouched != "queued" {
+ t.Fatalf("task status after refused user claim = %q (%v), want queued", untouched, err)
}
- if len(resp.Tasks) != 0 {
- t.Fatalf("claimed %d tasks from owner-less runtime, want 0: %s", len(resp.Tasks), w.Body.String())
+
+ // Daemon tokens are owner-bound as well (MUL-8154): this daemon's own
+ // token cannot reach the ownerless runtime either.
+ w := httptest.NewRecorder()
+ testHandler.ClaimTasksByRuntime(w, newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/claim",
+ map[string]any{"daemon_id": batchClaimTestDaemonID, "runtime_ids": []string{rtNull}, "max_tasks": 1},
+ testWorkspaceID, batchClaimTestDaemonID))
+ if w.Code != http.StatusOK || strings.Contains(w.Body.String(), taskID) {
+ t.Fatalf("daemon-token batch claim reached the ownerless runtime: %d %s", w.Code, 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 = %s, want cancelled (owner missing)", status)
+ if status != "queued" {
+ t.Fatalf("task status = %s, want untouched (queued)", status)
}
}
diff --git a/server/internal/handler/daemon_claim_attachment_batch_test.go b/server/internal/handler/daemon_claim_attachment_batch_test.go
index 9b8d5bb206..07e6051219 100644
--- a/server/internal/handler/daemon_claim_attachment_batch_test.go
+++ b/server/internal/handler/daemon_claim_attachment_batch_test.go
@@ -72,7 +72,7 @@ func seedMessageAttachment(t *testing.T, sessionID, messageID, filename, created
// returns the response recorder wrapper asserting the wanted status.
func claimForRuntimeExpecting(t *testing.T, h *Handler, runtimeID, daemonID string, want int) *testutil.Response {
t.Helper()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, daemonID)
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
return testutil.Call(t, h.ClaimTaskByRuntime, req).Want(want)
}
diff --git a/server/internal/handler/daemon_claim_cancelled_session_test.go b/server/internal/handler/daemon_claim_cancelled_session_test.go
index 5b5dfa5c24..8f1587e2bb 100644
--- a/server/internal/handler/daemon_claim_cancelled_session_test.go
+++ b/server/internal/handler/daemon_claim_cancelled_session_test.go
@@ -912,8 +912,8 @@ func pinTaskSessionViaAPI(t *testing.T, taskID, daemonID, sessionID, workDir str
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/session",
- map[string]any{"session_id": sessionID, "work_dir": workDir}, testWorkspaceID, daemonID)
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+taskID+"/session",
+ map[string]any{"session_id": sessionID, "work_dir": workDir})
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/daemon_claim_channel_type_test.go b/server/internal/handler/daemon_claim_channel_type_test.go
index 0bf755f775..9694849b36 100644
--- a/server/internal/handler/daemon_claim_channel_type_test.go
+++ b/server/internal/handler/daemon_claim_channel_type_test.go
@@ -102,8 +102,7 @@ type claimedChatChannel struct {
func claimChatChannelFields(t *testing.T, runtimeID string) claimedChatChannel {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "claim-channel-type")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
diff --git a/server/internal/handler/daemon_claim_continuity_gap_test.go b/server/internal/handler/daemon_claim_continuity_gap_test.go
index 3eec67df83..1ac0e248d9 100644
--- a/server/internal/handler/daemon_claim_continuity_gap_test.go
+++ b/server/internal/handler/daemon_claim_continuity_gap_test.go
@@ -21,7 +21,7 @@ type claimContinuityGapProbe struct {
func claimOneTaskForRuntime(t *testing.T, runtimeID, daemonID string) claimContinuityGapProbe {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, daemonID)
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
if w.Code != http.StatusOK {
diff --git a/server/internal/handler/daemon_claim_issue_status_test.go b/server/internal/handler/daemon_claim_issue_status_test.go
index 98da61a00d..fd516ee25c 100644
--- a/server/internal/handler/daemon_claim_issue_status_test.go
+++ b/server/internal/handler/daemon_claim_issue_status_test.go
@@ -43,8 +43,7 @@ func TestClaimTaskByRuntime_PopulatesIssueStatusCatalog(t *testing.T) {
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Issue status catalog claim agent")
taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "issue-status-catalog-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -107,8 +106,7 @@ func TestClaimTaskByRuntime_IssueStatusCatalogAbsentWithoutCustoms(t *testing.T)
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Issue status catalog empty claim agent")
taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "issue-status-catalog-empty-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -142,7 +140,7 @@ func TestClaimTaskByRuntime_IssueStatusCatalogCap(t *testing.T) {
runtimeID := createClaimReclaimRuntime(t, ctx, "Capped catalog runtime")
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Capped catalog agent")
taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "capped-catalog-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
var resp struct {
Task *struct {
diff --git a/server/internal/handler/daemon_claim_workspace_mcp_test.go b/server/internal/handler/daemon_claim_workspace_mcp_test.go
index 5b8e331360..246b5e23ee 100644
--- a/server/internal/handler/daemon_claim_workspace_mcp_test.go
+++ b/server/internal/handler/daemon_claim_workspace_mcp_test.go
@@ -14,7 +14,7 @@ func claimAgentMcpConfigForTest(t *testing.T, runtimeID string) json.RawMessage
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "ws-mcp-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
if w.Code != http.StatusOK {
diff --git a/server/internal/handler/daemon_comment_delivery_test.go b/server/internal/handler/daemon_comment_delivery_test.go
index 6b7b10c153..1a5282c9fa 100644
--- a/server/internal/handler/daemon_comment_delivery_test.go
+++ b/server/internal/handler/daemon_comment_delivery_test.go
@@ -220,8 +220,7 @@ func makeCommentDeliverySingleThread(t *testing.T, fixture commentDeliveryFixtur
func claimCommentDeliveryFixture(t *testing.T, fixture commentDeliveryFixture, capabilities string) AgentTaskResponse {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "comment-delivery-matrix")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil)
if capabilities != "" {
req.Header.Set("X-Client-Capabilities", capabilities)
}
@@ -365,8 +364,7 @@ func testClaimRepairsDeletedTrigger(t *testing.T, deleteTriggerSQL string) {
}
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "stale-comment-plan-repair")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil)
req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityCoalescedCommentsV1)
req = withURLParam(req, "runtimeId", fixture.runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
@@ -933,8 +931,7 @@ func TestClaimTaskByRuntime_FinalizationFailureRequeuesImmediately(t *testing.T)
defer func() { testHandler.TaskService.TxStarter = originalTxStarter }()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "comment-delivery-finalize-failure")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+fixture.runtimeID+"/tasks/claim", nil)
req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityCoalescedCommentsV1)
req = withURLParam(req, "runtimeId", fixture.runtimeID)
failingHandler.ClaimTaskByRuntime(w, req)
diff --git a/server/internal/handler/daemon_comment_workspace_scope_test.go b/server/internal/handler/daemon_comment_workspace_scope_test.go
index b92e0187f2..0afe4954dc 100644
--- a/server/internal/handler/daemon_comment_workspace_scope_test.go
+++ b/server/internal/handler/daemon_comment_workspace_scope_test.go
@@ -58,8 +58,7 @@ func enqueueIssueTaskWithTrigger(t *testing.T, ctx context.Context, agentID, iss
func claimTriggerFieldsForTest(t *testing.T, runtimeID string) (taskID, triggerContent, triggerSummary, raw string) {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "comment-workspace-scope")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
if w.Code != http.StatusOK {
diff --git a/server/internal/handler/daemon_context_exhausted_test.go b/server/internal/handler/daemon_context_exhausted_test.go
index c583375105..c4d25f86c6 100644
--- a/server/internal/handler/daemon_context_exhausted_test.go
+++ b/server/internal/handler/daemon_context_exhausted_test.go
@@ -66,7 +66,7 @@ func TestCompleteTask_ContextExhaustionFromOlderDaemonIsRecordedAsFailed(t *test
// Exactly what an older daemon posts: a successful completion whose output
// is the provider's notice, carrying the saturated session id.
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{
"output": "Prompt is too long · the request is ~274931 tokens (limit 200000) but this conversation is only ~1597 tokens — " +
"the rest is system prompt, tool definitions, and attachment content. A single-exchange conversation cannot be " +
@@ -74,7 +74,7 @@ func TestCompleteTask_ContextExhaustionFromOlderDaemonIsRecordedAsFailed(t *test
"session_id": "sess-saturated-6402",
"work_dir": "/tmp/gh6402",
},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -189,9 +189,9 @@ func TestCompleteTask_RealAnswerStillCompletes(t *testing.T) {
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{"output": tc.output, "session_id": "sess-healthy"},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/daemon_issue_snapshot_test.go b/server/internal/handler/daemon_issue_snapshot_test.go
index 646f1b1766..632935dd60 100644
--- a/server/internal/handler/daemon_issue_snapshot_test.go
+++ b/server/internal/handler/daemon_issue_snapshot_test.go
@@ -198,7 +198,7 @@ func TestClaimTaskByRuntime_RecordsItsOwnIssueSnapshot(t *testing.T) {
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "issue-snapshot-write")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
diff --git a/server/internal/handler/daemon_legacy_skill_redirect_test.go b/server/internal/handler/daemon_legacy_skill_redirect_test.go
index f0511021f0..2a78e22ab1 100644
--- a/server/internal/handler/daemon_legacy_skill_redirect_test.go
+++ b/server/internal/handler/daemon_legacy_skill_redirect_test.go
@@ -71,7 +71,7 @@ func TestClaimTaskByRuntime_LegacySkillRedirectFollowsTheCapability(t *testing.T
ctx := context.Background()
runtimeID, _, _ := seedSkillLoadFixture(t, ctx, tc.fixture)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, tc.fixture+"-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
if tc.capabilities != "" {
req.Header.Set("X-Client-Capabilities", tc.capabilities)
}
diff --git a/server/internal/handler/daemon_rpc.go b/server/internal/handler/daemon_rpc.go
index 9a88332ba5..c73fcd6da6 100644
--- a/server/internal/handler/daemon_rpc.go
+++ b/server/internal/handler/daemon_rpc.go
@@ -64,6 +64,10 @@ func (h *Handler) rpcClaimTasks(ctx context.Context, identity daemonws.ClientIde
// workspaces).
if identity.DaemonID != "" {
reqCtx = middleware.WithDaemonContext(reqCtx, identity.PrimaryWorkspaceID(), identity.DaemonID)
+ // Carry the connection's credential so per-call revocation checks
+ // (Qoder) validate the real token instead of an empty header.
+ reqCtx = middleware.WithDaemonTokenHash(reqCtx, identity.DaemonTokenHash)
+ reqCtx = middleware.WithDaemonTokenOwnerID(reqCtx, identity.DaemonTokenOwnerID)
}
req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, "/api/daemon/tasks/claim", bytes.NewReader(body))
if err != nil {
diff --git a/server/internal/handler/daemon_rpc_test.go b/server/internal/handler/daemon_rpc_test.go
index 3d92a37e65..11c6012933 100644
--- a/server/internal/handler/daemon_rpc_test.go
+++ b/server/internal/handler/daemon_rpc_test.go
@@ -22,7 +22,7 @@ func TestDaemonRPCHandler_TasksClaim(t *testing.T) {
taskID := seedQueuedIssueTask(t, ctx, a, rt, i)
identity := daemonws.ClientIdentity{
- DaemonID: "ws-daemon",
+ // User-credential connection (the runtime owner): no daemon id.
UserID: testUserID,
WorkspaceID: testWorkspaceID,
WorkspaceIDs: []string{testWorkspaceID},
diff --git a/server/internal/handler/daemon_runtime_access_test.go b/server/internal/handler/daemon_runtime_access_test.go
index b86cde3116..1a08a70a94 100644
--- a/server/internal/handler/daemon_runtime_access_test.go
+++ b/server/internal/handler/daemon_runtime_access_test.go
@@ -28,8 +28,7 @@ func TestClaimTaskByRuntime_OwnerlessAgentOnPrivateRuntimeFailsExplicitly(t *tes
dbfx.Exec(t, `UPDATE agent SET owner_id = NULL WHERE id = $1`, agentID)
taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "ownerless-agent-claim")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
@@ -65,8 +64,7 @@ func TestClaimTaskByRuntime_SettlesPrivateOwnerMismatch(t *testing.T) {
dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE id = $2`, foreignOwnerID, agentID)
taskID := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "mismatch-issue-claim")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
@@ -97,8 +95,7 @@ func TestClaimTaskByRuntime_SettlesPrivateOwnerMismatchChatFailure(t *testing.T)
sessionID := createHandlerTestChatSession(t, agentID)
taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "chat_session_id": sessionID, "issue_id": nil})
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "mismatch-chat-claim")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
@@ -183,8 +180,7 @@ func TestBuildClaimedTaskResponseRejectsAgentOwnerChangedAfterClaim(t *testing.T
if err != nil {
t.Fatalf("load runtime: %v", err)
}
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "claim-then-owner-change")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
_, _, _, _, _, failure := testHandler.buildClaimedTaskResponse(
req, task, runtime, runtimeID, testWorkspaceID,
)
@@ -238,8 +234,7 @@ func TestBuildClaimedTaskResponseRejectsAgentReboundAfterClaim(t *testing.T) {
if err != nil {
t.Fatalf("load old runtime: %v", err)
}
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+oldRuntimeID+"/tasks/claim", nil,
- testWorkspaceID, "claim-then-rebind")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+oldRuntimeID+"/tasks/claim", nil)
_, _, _, _, _, failure := testHandler.buildClaimedTaskResponse(
req, task, runtime, oldRuntimeID, testWorkspaceID,
)
@@ -368,8 +363,7 @@ func TestClaimTaskByRuntime_RuntimeOwnerChangedAfterClaimNeverDelivered(t *testi
}
dbfx.Exec(t, `UPDATE agent_runtime SET owner_id = $1 WHERE id = $2`, newOwnerID, runtimeID)
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "delivery-gate-owner-change")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
resp, deliveredCommentIDs, _, _, settledFailure, finalizeErr := testHandler.finalizeClaimDeliveryForTestWithRuntime(
req, task, runtimeSnapshot, runtimeID, testWorkspaceID,
)
@@ -409,9 +403,10 @@ func TestClaimTaskByRuntime_RuntimeOwnerChangedAfterClaimNeverDelivered(t *testi
}
// And the full HTTP claim surface stays an empty successful poll.
+ // The previous owner's credential no longer reaches this runtime
+ // (MUL-8154), so the post-settle poll comes from the new owner.
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, func() *http.Request {
- r := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "delivery-gate-poll")
+ r := newRequestAs(newOwnerID, http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
return testutil.WithURLParams(r, "runtimeId", runtimeID)
}()).Want(http.StatusOK)
if strings.TrimSpace(w.Body.String()) != `{"task":null}` {
@@ -457,8 +452,7 @@ func TestFinalizeClaimDelivery_UsesCurrentRuntimeOwnerForTaskToken(t *testing.T)
dbfx.Exec(t, `UPDATE "user" SET profile_description = $1 WHERE id = $2`, currentProfile, newOwnerID)
dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public', owner_id = $1 WHERE id = $2`, newOwnerID, runtimeID)
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "public-delivery-owner-change")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
resp, _, _, _, failure, finalizeErr := testHandler.finalizeClaimDeliveryForTestWithRuntime(
req, task, runtimeSnapshot, runtimeID, testWorkspaceID,
)
@@ -516,8 +510,7 @@ func TestFinalizeClaimDelivery_CurrentRuntimeOwnerMissingNeverMintsToken(t *test
}
dbfx.Exec(t, `UPDATE agent_runtime SET visibility = 'public', owner_id = NULL WHERE id = $1`, runtimeID)
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "ownerless-delivery")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
resp, _, _, _, failure, finalizeErr := testHandler.finalizeClaimDeliveryForTestWithRuntime(
req, task, runtimeSnapshot, runtimeID, testWorkspaceID,
)
@@ -618,8 +611,7 @@ func TestFinalizeClaimDelivery_SettlementFailureIsUnsettled(t *testing.T) {
injectRuntimeOwnerFlipAfterClaim(t, ctx, taskID, runtimeID, foreignOwnerID)
injectFailTaskSettlementFailure(t, ctx, taskID)
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "settlement-failure")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)
if strings.TrimSpace(w.Text()) == `{"task":null}` {
diff --git a/server/internal/handler/daemon_runtime_ownership_review_test.go b/server/internal/handler/daemon_runtime_ownership_review_test.go
new file mode 100644
index 0000000000..4dbc4c4174
--- /dev/null
+++ b/server/internal/handler/daemon_runtime_ownership_review_test.go
@@ -0,0 +1,519 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/daemonws"
+ "github.com/multica-ai/multica/server/internal/middleware"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/remotemcp"
+)
+
+// Regression tests for the PR #9423 review (MUL-8154), derived from the
+// reviewer's reproduction probes.
+
+// registrationPrecheckBarrier delays every registration's owner pre-check
+// until a second one has also read (or the window closes). Before the
+// registration lock both reads saw an empty daemon and both inserted; with
+// the lock the second read cannot start until the first registration is done,
+// so the barrier just times out and lets each proceed in turn.
+type registrationPrecheckBarrier struct {
+ arrivals atomic.Int32
+ release chan struct{}
+ once sync.Once
+ window time.Duration
+}
+
+// barrierTxStarter wraps the handler's TxStarter so every transaction it
+// opens routes Query through the barrier.
+type barrierTxStarter struct {
+ inner txStarter
+ barrier *registrationPrecheckBarrier
+}
+
+func (s barrierTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.inner.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return barrierTx{Tx: tx, barrier: s.barrier}, nil
+}
+
+type barrierTx struct {
+ pgx.Tx
+ barrier *registrationPrecheckBarrier
+}
+
+func (t barrierTx) Query(ctx context.Context, query string, args ...any) (pgx.Rows, error) {
+ rows, err := t.Tx.Query(ctx, query, args...)
+ if err != nil {
+ return rows, err
+ }
+ t.barrier.wait(query)
+ return rows, nil
+}
+
+func (d *registrationPrecheckBarrier) wait(query string) {
+ if !strings.Contains(query, "name: ListRuntimeOwnersByDaemon") {
+ return
+ }
+ if d.arrivals.Add(1) == 2 {
+ d.once.Do(func() { close(d.release) })
+ }
+ select {
+ case <-d.release:
+ case <-time.After(d.window):
+ }
+}
+
+func TestDaemonRegister_ConcurrentDifferentProvidersAndProfilesHaveOneOwner(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ profileID := insertRuntimeProfileFixture(t, ctx, "Race profile "+uuid.NewString()[:8], "pi", "race-wrapper")
+
+ cases := []struct {
+ name string
+ runtimes [2]map[string]any
+ }{
+ {"providers", [2]map[string]any{
+ {"name": "claude", "type": "claude", "status": "online"},
+ {"name": "codex", "type": "codex", "status": "online"},
+ }},
+ {"provider and profile", [2]map[string]any{
+ {"name": "claude", "type": "claude", "status": "online"},
+ {"name": "race profile", "type": "pi", "profile_id": profileID, "status": "online"},
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ second := dbfx.User(t, "race second owner", "race-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, second, "member")
+ daemonID := "race-" + uuid.NewString()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID)
+ })
+
+ // The pre-check runs on the registration transaction, so the
+ // barrier is injected at the TxStarter level, not h.Queries.
+ h := *testHandler
+ h.TxStarter = barrierTxStarter{
+ inner: testHandler.TxStarter,
+ barrier: &registrationPrecheckBarrier{release: make(chan struct{}), window: 500 * time.Millisecond},
+ }
+ users := []string{testUserID, second}
+ codes := make([]int, 2)
+ var wg sync.WaitGroup
+ for i := range users {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ w := httptest.NewRecorder()
+ h.DaemonRegister(w, newRequestAs(users[i], "POST", "/api/daemon/register", map[string]any{
+ "workspace_id": testWorkspaceID, "daemon_id": daemonID,
+ "runtimes": []map[string]any{tc.runtimes[i]},
+ }))
+ codes[i] = w.Code
+ }(i)
+ }
+ wg.Wait()
+
+ var owners, rows int
+ dbfx.QueryRow(t, `SELECT count(DISTINCT owner_id), count(*) FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`,
+ testWorkspaceID, daemonID).Scan(&owners, &rows)
+ if owners != 1 || rows != 1 {
+ t.Fatalf("daemon has %d owners across %d rows after concurrent registration (statuses %v), want exactly one", owners, rows, codes)
+ }
+ ok, forbidden := 0, 0
+ for _, c := range codes {
+ switch c {
+ case http.StatusOK:
+ ok++
+ case http.StatusForbidden:
+ forbidden++
+ }
+ }
+ if ok != 1 || forbidden != 1 {
+ t.Fatalf("statuses = %v, want one 200 and one 403", codes)
+ }
+ })
+ }
+}
+
+// TestDaemonRPC_QoderClaimRevalidatesConnectionCredential: a WS RPC replays
+// the claim without an Authorization header, so the Qoder revocation check
+// must use the connection's credential — accepting it while valid and
+// refusing it once revoked.
+func TestDaemonRPC_QoderClaimRevalidatesConnectionCredential(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ daemonID := "qoder-managed-" + testWorkspaceID
+ raw, err := auth.GenerateDaemonToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, err := testHandler.Queries.CreateDaemonToken(ctx, db.CreateDaemonTokenParams{
+ TokenHash: auth.HashToken(raw), WorkspaceID: parseUUID(testWorkspaceID), DaemonID: daemonID,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id = $1`, token.ID) })
+ dbfx.Exec(t, `INSERT INTO cloud_agent_connection (workspace_id, provider, owner_id, token_id, config_encrypted, enabled)
+ VALUES ($1, 'qoder_cloud', $2, $3, 'test-only', true)`, testWorkspaceID, testUserID, token.ID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM cloud_agent_connection WHERE workspace_id = $1 AND provider = 'qoder_cloud'`, testWorkspaceID)
+ })
+ runtimeID := dbfx.Runtime(t, "qoder ws runtime", testutil.Cols{"daemon_id": daemonID, "provider": "qoder_cloud"})
+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "qoder ws agent")
+
+ // Handshake through the real DaemonAuth middleware, as production does.
+ var (
+ identity daemonws.ClientIdentity
+ ok bool
+ )
+ handshake := httptest.NewRequest(http.MethodGet, "/api/daemon/ws", nil)
+ handshake.Header.Set("Authorization", "Bearer "+raw)
+ hw := httptest.NewRecorder()
+ middleware.DaemonAuth(testHandler.Queries, nil, nil, nil)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ identity, ok = testHandler.buildDaemonWebSocketIdentity(w, r, []string{runtimeID}, "")
+ })).ServeHTTP(hw, handshake)
+ if !ok {
+ t.Fatalf("valid Qoder handshake refused: %d %s", hw.Code, hw.Body.String())
+ }
+ if identity.DaemonTokenHash == "" {
+ t.Fatal("WS identity did not capture the authenticating token")
+ }
+
+ claim := func(t *testing.T) []AgentTaskResponse {
+ t.Helper()
+ body, _ := json.Marshal(map[string]any{"daemon_id": daemonID, "runtime_ids": []string{runtimeID}, "max_tasks": 1})
+ status, respBody, err := testHandler.DaemonRPCHandler(ctx, identity, "tasks.claim", body)
+ if err != nil || status != http.StatusOK {
+ t.Fatalf("rpc claim: status=%d err=%v body=%s", status, err, respBody)
+ }
+ var resp struct {
+ Tasks []AgentTaskResponse `json:"tasks"`
+ }
+ if err := json.Unmarshal(respBody, &resp); err != nil {
+ t.Fatal(err)
+ }
+ return resp.Tasks
+ }
+
+ first := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+ if tasks := claim(t); len(tasks) != 1 || tasks[0].ID != first {
+ t.Fatalf("valid credential: claimed %+v, want task %s", tasks, first)
+ }
+
+ // Revoke the connection: the same open WS must stop claiming.
+ dbfx.Exec(t, `UPDATE cloud_agent_connection SET enabled = false WHERE workspace_id = $1 AND provider = 'qoder_cloud'`, testWorkspaceID)
+ dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, first)
+ second := seedQueuedIssueTask(t, ctx, agentID, runtimeID, issueID)
+ if tasks := claim(t); len(tasks) != 0 {
+ t.Fatalf("revoked credential still claimed %+v", tasks)
+ }
+ if got := taskStatusOf(t, second); got != "queued" {
+ t.Fatalf("task status after revoked claim = %q, want queued", got)
+ }
+}
+
+// TestDaemonToken_OldOwnersCredentialCannotReachReplacementOwner covers the
+// daemon_id reuse lifecycle from the second #9423 review: after A's runtimes
+// are deleted and B registers the same daemon_id, A's Remote MCP daemon token
+// must not reach B's runtime over HTTP, a new WS handshake, or an already
+// open WS connection.
+func TestDaemonToken_OldOwnersCredentialCannotReachReplacementOwner(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ daemonID := "reused-" + uuid.NewString()
+ oldID := dbfx.Runtime(t, "reuse old runtime", testutil.Cols{"daemon_id": daemonID, "provider": "claude"})
+ old, err := testHandler.Queries.GetAgentRuntime(ctx, parseUUID(oldID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, params, err := remoteMCPDaemonTokenForClaim(AgentTaskResponse{
+ RemoteMCPConnections: []remotemcp.Connection{{ContributionKey: "reuse"}},
+ }, old)
+ if err != nil || len(params) != 1 {
+ t.Fatalf("mint: %v", err)
+ }
+ if uuidToString(params[0].OwnerID) != testUserID {
+ t.Fatalf("Remote MCP token owner = %q, want the runtime owner", uuidToString(params[0].OwnerID))
+ }
+ token, err := testHandler.Queries.CreateDaemonToken(ctx, params[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id = $1`, token.ID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID)
+ })
+ authed := func(h http.HandlerFunc, req *http.Request) *httptest.ResponseRecorder {
+ req.Header.Del("X-User-ID")
+ req.Header.Set("Authorization", "Bearer "+raw)
+ w := httptest.NewRecorder()
+ middleware.DaemonAuth(testHandler.Queries, nil, nil, nil)(h).ServeHTTP(w, req)
+ return w
+ }
+ heartbeat := func(runtimeID string) int {
+ return authed(testHandler.DaemonHeartbeat, newRequest("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": runtimeID})).Code
+ }
+ if code := heartbeat(oldID); code != http.StatusOK {
+ t.Fatalf("positive control: owner's token heartbeat = %d", code)
+ }
+ // A WS connection the old owner opened before the hand-over.
+ var openIdentity daemonws.ClientIdentity
+ authed(func(w http.ResponseWriter, r *http.Request) {
+ var ok bool
+ if openIdentity, ok = testHandler.buildDaemonWebSocketIdentity(w, r, []string{oldID}, ""); !ok {
+ t.Fatalf("positive control: owner's WS handshake refused: %d", w.(*httptest.ResponseRecorder).Code)
+ }
+ }, httptest.NewRequest(http.MethodGet, "/api/daemon/ws", nil))
+
+ // A deletes the last runtime; B registers the same daemon_id.
+ testutil.Call(t, testHandler.DeleteAgentRuntime,
+ withURLParams(newRequestAs(testUserID, "DELETE", "/api/runtimes/"+oldID, nil), "runtimeId", oldID)).Want(http.StatusOK)
+ second := dbfx.User(t, "replacement owner", "replacement-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, second, "member")
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(second, daemonID)).Want(http.StatusOK)
+ var newID string
+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2 AND owner_id = $3`,
+ testWorkspaceID, daemonID, second).Scan(&newID)
+ agentID := testutil.New(testPool, testWorkspaceID, second).Agent(t, "replacement agent", newID)
+ issueID := dbfx.Issue(t, "replacement task")
+ taskID := seedQueuedIssueTask(t, ctx, agentID, newID, issueID)
+
+ if code := heartbeat(newID); code != http.StatusNotFound {
+ t.Fatalf("old token heartbeat on the replacement runtime = %d, want 404", code)
+ }
+ w := authed(testHandler.ClaimTaskByRuntime,
+ withURLParams(newRequest("POST", "/api/daemon/runtimes/"+newID+"/tasks/claim", nil), "runtimeId", newID))
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("old token claim on the replacement runtime = %d %s, want 404", w.Code, w.Body.String())
+ }
+ authed(func(w http.ResponseWriter, r *http.Request) {
+ if _, ok := testHandler.buildDaemonWebSocketIdentity(w, r, []string{newID}, ""); ok {
+ t.Fatal("old token opened a WS onto the replacement runtime")
+ }
+ }, httptest.NewRequest(http.MethodGet, "/api/daemon/ws", nil))
+ body, _ := json.Marshal(map[string]any{"daemon_id": daemonID, "runtime_ids": []string{newID}, "max_tasks": 1})
+ status, respBody, err := testHandler.DaemonRPCHandler(ctx, openIdentity, "tasks.claim", body)
+ if err != nil || status != http.StatusOK || strings.Contains(string(respBody), taskID) {
+ t.Fatalf("already-open WS claimed on the replacement runtime: status=%d err=%v body=%s", status, err, respBody)
+ }
+ if got := taskStatusOf(t, taskID); got != "queued" {
+ t.Fatalf("replacement owner's task status = %q, want queued", got)
+ }
+ var tokens int
+ dbfx.QueryRow(t, `SELECT count(*) FROM task_token WHERE task_id = $1`, taskID).Scan(&tokens)
+ if tokens != 0 {
+ t.Fatalf("%d task tokens minted for the replacement owner's task", tokens)
+ }
+}
+
+func TestDaemonRegister_RefusesReservedQoderDaemonIDForUsers(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ daemonID := "qoder-managed-" + testWorkspaceID
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(testUserID, daemonID)).Want(http.StatusForbidden)
+ var n int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID).Scan(&n)
+ if n != 0 {
+ t.Fatalf("%d runtimes registered under the reserved Qoder daemon_id", n)
+ }
+}
+
+// Third #9423 review: daemon-token registration must apply the token's owner
+// binding, and tokens without a recorded issuing owner (pre-migration 588)
+// must be refused everywhere rather than re-bound to whoever owns the
+// daemon now.
+func TestDaemonToken_ReplacedOwnerAndUnboundTokensCannotRegisterOrAct(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ for _, tc := range []struct {
+ name string
+ unbound bool
+ }{{"bound to previous owner", false}, {"unbound legacy token", true}} {
+ t.Run(tc.name, func(t *testing.T) {
+ daemonID := "reuse-reg-" + uuid.NewString()
+ oldID := dbfx.Runtime(t, "reuse-reg old", testutil.Cols{"daemon_id": daemonID, "provider": "claude"})
+ old, err := testHandler.Queries.GetAgentRuntime(ctx, parseUUID(oldID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, params, err := remoteMCPDaemonTokenForClaim(AgentTaskResponse{
+ RemoteMCPConnections: []remotemcp.Connection{{ContributionKey: "reuse-reg"}},
+ }, old)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if tc.unbound {
+ params[0].OwnerID = pgtype.UUID{}
+ }
+ token, err := testHandler.Queries.CreateDaemonToken(ctx, params[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id = $1`, token.ID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID)
+ })
+ call := func(h http.HandlerFunc, req *http.Request) int {
+ req.Header.Del("X-User-ID")
+ req.Header.Set("Authorization", "Bearer "+raw)
+ w := httptest.NewRecorder()
+ middleware.DaemonAuth(testHandler.Queries, nil, nil, nil)(h).ServeHTTP(w, req)
+ return w.Code
+ }
+ register := func() int {
+ return call(testHandler.DaemonRegister, newRequest("POST", "/api/daemon/register", map[string]any{
+ "workspace_id": testWorkspaceID, "daemon_id": daemonID,
+ "runtimes": []map[string]any{{"type": "claude", "name": "written by old token", "status": "offline"}},
+ }))
+ }
+ if tc.unbound {
+ // Refused even while the issuing owner still owns the daemon.
+ if code := call(testHandler.DaemonHeartbeat, newRequest("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": oldID})); code != http.StatusNotFound {
+ t.Fatalf("unbound token heartbeat = %d, want 404", code)
+ }
+ if code := register(); code != http.StatusForbidden {
+ t.Fatalf("unbound token register = %d, want 403", code)
+ }
+ } else if code := register(); code != http.StatusOK {
+ t.Fatalf("positive control: bound token re-registers its owner's daemon = %d", code)
+ }
+
+ testutil.Call(t, testHandler.DeleteAgentRuntime,
+ withURLParams(newRequestAs(testUserID, "DELETE", "/api/runtimes/"+oldID, nil), "runtimeId", oldID)).Want(http.StatusOK)
+ second := dbfx.User(t, "reuse-reg replacement", "reuse-reg-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, second, "member")
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(second, daemonID)).Want(http.StatusOK)
+ var newID string
+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID).Scan(&newID)
+
+ if code := register(); code != http.StatusForbidden {
+ t.Fatalf("old token register over the replacement owner = %d, want 403", code)
+ }
+ rt, err := testHandler.Queries.GetAgentRuntime(ctx, parseUUID(newID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rt.Status != "online" || rt.Name == "written by old token" || uuidToString(rt.OwnerID) != second {
+ t.Fatalf("replacement runtime mutated: status=%s name=%q owner=%s", rt.Status, rt.Name, uuidToString(rt.OwnerID))
+ }
+ if code := call(testHandler.DaemonHeartbeat, newRequest("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": newID})); code != http.StatusNotFound {
+ t.Fatalf("old token heartbeat on the replacement runtime = %d, want 404", code)
+ }
+ })
+ }
+}
+
+// Fourth #9423 review: a qoder-managed-* daemon token gets the owner-binding
+// exemption only with a live cloud_agent_connection, whatever runtime type
+// the body declares. Pre-upgrade tokens under that prefix were issued for
+// ordinary runtimes and have no connection.
+func TestDaemonRegister_QoderPrefixNeedsLiveConnectionForEveryShape(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ daemonID := "qoder-managed-" + testWorkspaceID
+ victim := dbfx.User(t, "qoder prefix victim", "qoder-prefix-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, testWorkspaceID, victim, "member")
+ runtimeID := dbfx.Runtime(t, "qoder prefix victim runtime", testutil.Cols{
+ "daemon_id": daemonID, "provider": "claude", "owner_id": victim,
+ })
+ raw, err := auth.GenerateDaemonToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ token, err := testHandler.Queries.CreateDaemonToken(ctx, db.CreateDaemonTokenParams{
+ TokenHash: auth.HashToken(raw), WorkspaceID: parseUUID(testWorkspaceID), DaemonID: daemonID,
+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(time.Hour), Valid: true},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM daemon_token WHERE id = $1`, token.ID) })
+ profileID := insertRuntimeProfileFixture(t, ctx, "Qoder prefix profile "+uuid.NewString()[:8], "pi", "qp-wrapper")
+
+ register := func(body map[string]any) int {
+ body["workspace_id"] = testWorkspaceID
+ body["daemon_id"] = daemonID
+ req := httptest.NewRequest(http.MethodPost, "/api/daemon/register", strings.NewReader(mustJSON(t, body)))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+raw)
+ w := httptest.NewRecorder()
+ middleware.DaemonAuth(testHandler.Queries, nil, nil, nil)(http.HandlerFunc(testHandler.DaemonRegister)).ServeHTTP(w, req)
+ return w.Code
+ }
+ for name, body := range map[string]map[string]any{
+ "built-in claude": {"runtimes": []map[string]any{{"type": "claude", "name": "written via prefix", "status": "offline"}}},
+ "custom profile": {"runtimes": []map[string]any{{"type": "pi", "profile_id": profileID, "name": "written via prefix", "status": "offline"}}},
+ "failed profiles": {"failed_profiles": []map[string]any{{"profile_id": profileID, "reason": "x"}}},
+ "qoder_cloud": {"runtimes": []map[string]any{{"type": "qoder_cloud", "runtime_mode": "cloud", "name": "written via prefix", "status": "online"}}},
+ } {
+ if code := register(body); code != http.StatusForbidden {
+ t.Errorf("%s: register with an unconnected qoder-prefix token = %d, want 403", name, code)
+ }
+ }
+ rt, err := testHandler.Queries.GetAgentRuntime(ctx, parseUUID(runtimeID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rt.Status != "online" || rt.Name == "written via prefix" || uuidToString(rt.OwnerID) != victim {
+ t.Fatalf("victim runtime mutated: status=%s name=%q owner=%s", rt.Status, rt.Name, uuidToString(rt.OwnerID))
+ }
+ var n int
+ dbfx.QueryRow(t, `SELECT count(*) FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID).Scan(&n)
+ if n != 1 {
+ t.Fatalf("%d runtimes under the qoder prefix, want only the victim's", n)
+ }
+
+ // With a live connection the bridge's own registration shape works, and
+ // it still cannot register anything other than its qoder_cloud runtime.
+ dbfx.Exec(t, `INSERT INTO cloud_agent_connection (workspace_id, provider, owner_id, token_id, config_encrypted, enabled)
+ VALUES ($1, 'qoder_cloud', $2, $3, 'test-only', true)`, testWorkspaceID, testUserID, token.ID)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM cloud_agent_connection WHERE workspace_id = $1 AND provider = 'qoder_cloud'`, testWorkspaceID)
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2 AND provider = 'qoder_cloud'`, testWorkspaceID, daemonID)
+ })
+ if code := register(map[string]any{"runtimes": []map[string]any{{"type": "claude", "name": "written via prefix", "status": "offline"}}}); code != http.StatusForbidden {
+ t.Fatalf("connected qoder token registering a claude runtime = %d, want 403", code)
+ }
+ if code := register(map[string]any{"runtimes": []map[string]any{{"type": "qoder_cloud", "runtime_mode": "cloud", "name": "QCA", "status": "online"}}}); code != http.StatusOK {
+ t.Fatalf("connected qoder token registering its qoder_cloud runtime = %d, want 200", code)
+ }
+}
+
+func mustJSON(t *testing.T, v any) string {
+ t.Helper()
+ b, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
diff --git a/server/internal/handler/daemon_runtime_ownership_test.go b/server/internal/handler/daemon_runtime_ownership_test.go
new file mode 100644
index 0000000000..ab03d1b630
--- /dev/null
+++ b/server/internal/handler/daemon_runtime_ownership_test.go
@@ -0,0 +1,441 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// MUL-8154: /api/daemon/* accepts any workspace member's PAT/JWT. These tests
+// pin that workspace membership alone no longer lets a member act as another
+// member's daemon, that registration cannot take a runtime over, that legacy
+// merges need ownership of both rows, that daemon tokens are bound to their
+// own daemon, and that tasks without a runtime are not writable.
+
+type ownershipFixture struct {
+ victimRuntime string
+ victimDaemon string
+ agentID string
+ issueID string
+ queuedTask string
+ runningTask string
+ attackerID string
+}
+
+func newOwnershipFixture(t *testing.T, label string) ownershipFixture {
+ t.Helper()
+ ctx := context.Background()
+ suffix := strings.ReplaceAll(uuid.NewString(), "-", "")[:12]
+ f := ownershipFixture{victimDaemon: "victim-" + label + "-" + suffix}
+ // Victim = testUserID, who owns every handler fixture runtime.
+ f.victimRuntime = dbfx.Runtime(t, label+" victim runtime", testutil.Cols{
+ "daemon_id": f.victimDaemon,
+ "provider": "claude",
+ })
+ f.agentID, f.issueID = createClaimReclaimAgentAndIssue(t, ctx, f.victimRuntime, label+" victim agent")
+ f.queuedTask = seedQueuedIssueTask(t, ctx, f.agentID, f.victimRuntime, f.issueID)
+ // A second agent holds the running task so the first agent's
+ // concurrency slot stays free for the owner's positive-control claim.
+ runningAgent := dbfx.Agent(t, label+" victim running agent", f.victimRuntime)
+ f.runningTask = dbfx.Task(t, runningAgent, testutil.Cols{
+ "runtime_id": f.victimRuntime,
+ "issue_id": f.issueID,
+ "status": "running",
+ "started_at": testutil.Raw("now()"),
+ })
+ f.attackerID = dbfx.User(t, label+" attacker", label+"-attacker-"+suffix+"@example.com")
+ dbfx.Member(t, testWorkspaceID, f.attackerID, "member")
+ return f
+}
+
+func taskStatusOf(t *testing.T, taskID string) string {
+ t.Helper()
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)
+ return status
+}
+
+func runtimeOwnerOf(t *testing.T, runtimeID string) pgtype.UUID {
+ t.Helper()
+ var owner pgtype.UUID
+ dbfx.QueryRow(t, `SELECT owner_id FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&owner)
+ return owner
+}
+
+func TestDaemonRuntimeOwnership_MemberCannotActOnAnotherMembersRuntime(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newOwnershipFixture(t, "crossowner")
+ as := func(method, path string, body any, params ...string) *http.Request {
+ req := newRequestAs(f.attackerID, method, path, body)
+ if len(params) > 0 {
+ req = withURLParams(req, params...)
+ }
+ return req
+ }
+
+ t.Run("single claim", func(t *testing.T) {
+ testutil.Call(t, testHandler.ClaimTaskByRuntime,
+ as("POST", "/api/daemon/runtimes/"+f.victimRuntime+"/tasks/claim", nil, "runtimeId", f.victimRuntime)).
+ Want(http.StatusNotFound)
+ })
+ t.Run("batch claim with the victim's daemon_id", func(t *testing.T) {
+ w := testutil.Call(t, testHandler.ClaimTasksByRuntime, as("POST", "/api/daemon/tasks/claim", map[string]any{
+ "daemon_id": f.victimDaemon, "runtime_ids": []string{f.victimRuntime}, "max_tasks": 5,
+ })).Want(http.StatusOK)
+ if strings.Contains(w.Body.String(), f.queuedTask) {
+ t.Fatalf("attacker claimed the victim's task: %s", w.Body.String())
+ }
+ })
+ if got := taskStatusOf(t, f.queuedTask); got != "queued" {
+ t.Fatalf("victim's queued task status = %q after refused claims, want queued", got)
+ }
+
+ t.Run("heartbeat", func(t *testing.T) {
+ testutil.Call(t, testHandler.DaemonHeartbeat,
+ as("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": f.victimRuntime})).
+ Want(http.StatusNotFound)
+ })
+ t.Run("deregister is a no-op", func(t *testing.T) {
+ testutil.Call(t, testHandler.DaemonDeregister,
+ as("POST", "/api/daemon/deregister", map[string]any{"runtime_ids": []string{f.victimRuntime}})).
+ Want(http.StatusOK)
+ var status string
+ dbfx.QueryRow(t, `SELECT status FROM agent_runtime WHERE id = $1`, f.victimRuntime).Scan(&status)
+ if status != "online" {
+ t.Fatalf("victim runtime status = %q, want online", status)
+ }
+ })
+ t.Run("websocket handshake", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ if _, ok := testHandler.buildDaemonWebSocketIdentity(w, as("GET", "/api/daemon/ws", nil), []string{f.victimRuntime}, f.attackerID); ok {
+ t.Fatal("attacker's websocket was authorized for the victim's runtime")
+ }
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("ws status = %d, want 404", w.Code)
+ }
+ })
+
+ taskPath := "/api/daemon/tasks/" + f.runningTask
+ for _, tc := range []struct {
+ name string
+ handler http.HandlerFunc
+ method string
+ suffix string
+ body any
+ }{
+ {"complete", testHandler.CompleteTask, "POST", "/complete", map[string]any{"output": "hijacked"}},
+ {"fail", testHandler.FailTask, "POST", "/fail", map[string]any{"error": "hijacked"}},
+ {"report messages", testHandler.ReportTaskMessages, "POST", "/messages", map[string]any{
+ "messages": []any{map[string]any{"seq": 1, "type": "text", "content": "forged"}},
+ }},
+ {"list messages", testHandler.ListTaskMessages, "GET", "/messages", nil},
+ {"status", testHandler.GetTaskStatus, "GET", "/status", nil},
+ {"gc check", testHandler.GetTaskGCCheck, "GET", "/gc-check", nil},
+ } {
+ t.Run("task "+tc.name, func(t *testing.T) {
+ testutil.Call(t, tc.handler, as(tc.method, taskPath+tc.suffix, tc.body, "taskId", f.runningTask)).
+ Want(http.StatusNotFound)
+ })
+ }
+ if got := taskStatusOf(t, f.runningTask); got != "running" {
+ t.Fatalf("victim's running task status = %q after refused writes, want running", got)
+ }
+ var messages int
+ dbfx.QueryRow(t, `SELECT count(*) FROM task_message WHERE task_id = $1`, f.runningTask).Scan(&messages)
+ if messages != 0 {
+ t.Fatalf("attacker wrote %d messages into the victim's task", messages)
+ }
+
+ // The owner's own credential is unaffected — and this positive control
+ // proves the refused claims above were refused by authorization, not by
+ // an unclaimable fixture.
+ t.Run("owner batch claim", func(t *testing.T) {
+ w := testutil.Call(t, testHandler.ClaimTasksByRuntime, newOwnerDaemonRequest("POST", "/api/daemon/tasks/claim", map[string]any{
+ "daemon_id": f.victimDaemon, "runtime_ids": []string{f.victimRuntime}, "max_tasks": 5,
+ })).Want(http.StatusOK)
+ if !strings.Contains(w.Body.String(), f.queuedTask) {
+ t.Fatalf("owner could not claim their own task: %s", w.Body.String())
+ }
+ })
+ // The owner's own credential is unaffected.
+ t.Run("owner heartbeat", func(t *testing.T) {
+ testutil.Call(t, testHandler.DaemonHeartbeat,
+ newOwnerDaemonRequest("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": f.victimRuntime})).
+ Want(http.StatusOK)
+ })
+ t.Run("owner task status", func(t *testing.T) {
+ testutil.Call(t, testHandler.GetTaskStatus,
+ withURLParams(newOwnerDaemonRequest("GET", taskPath+"/status", nil), "taskId", f.runningTask)).
+ Want(http.StatusOK)
+ })
+}
+
+func registerAs(userID, daemonID string, legacyIDs ...string) *http.Request {
+ body := map[string]any{
+ "workspace_id": testWorkspaceID,
+ "daemon_id": daemonID,
+ "device_name": "ownership-test",
+ "runtimes": []map[string]any{{"name": "claude", "type": "claude", "version": "test", "status": "online"}},
+ }
+ if len(legacyIDs) > 0 {
+ body["legacy_daemon_ids"] = legacyIDs
+ }
+ return newRequestAs(userID, "POST", "/api/daemon/register", body)
+}
+
+func TestDaemonRegister_RefusesTakeoverOfAnotherMembersRuntime(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newOwnershipFixture(t, "regtakeover")
+
+ w := testutil.Call(t, testHandler.DaemonRegister, registerAs(f.attackerID, f.victimDaemon)).Want(http.StatusForbidden)
+ if strings.Contains(w.Body.String(), f.victimRuntime) {
+ t.Fatalf("refused registration leaked the runtime: %s", w.Body.String())
+ }
+ if owner := runtimeOwnerOf(t, f.victimRuntime); uuidToString(owner) != testUserID {
+ t.Fatalf("runtime owner = %s after refused takeover, want the victim", uuidToString(owner))
+ }
+
+ // An ownerless row must not be claimable by ordinary registration either.
+ ownerlessDaemon := "ownerless-" + uuid.NewString()
+ ownerless := dbfx.Runtime(t, "ownerless runtime", testutil.Cols{
+ "daemon_id": ownerlessDaemon, "provider": "claude", "runtime_mode": "local", "owner_id": nil,
+ })
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(f.attackerID, ownerlessDaemon)).Want(http.StatusForbidden)
+ if owner := runtimeOwnerOf(t, ownerless); owner.Valid {
+ t.Fatalf("ownerless runtime was claimed by %s", uuidToString(owner))
+ }
+
+ // The owner re-registers normally.
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(testUserID, f.victimDaemon)).Want(http.StatusOK)
+}
+
+// TestUpsertAgentRuntime_OwnerFence pins the SQL-level fence that backs the
+// handler pre-check against a concurrent registration.
+func TestUpsertAgentRuntime_OwnerFence(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newOwnershipFixture(t, "sqlfence")
+ ctx := context.Background()
+ params := func(owner, required pgtype.UUID) db.UpsertAgentRuntimeParams {
+ return db.UpsertAgentRuntimeParams{
+ WorkspaceID: parseUUID(testWorkspaceID), DaemonID: strToText(f.victimDaemon),
+ Name: "claude", RuntimeMode: "local", Provider: "claude", Status: "online",
+ Metadata: []byte(`{}`), OwnerID: owner, RequiredOwnerID: required,
+ }
+ }
+ attacker := parseUUID(f.attackerID)
+ if _, err := testHandler.Queries.UpsertAgentRuntime(ctx, params(attacker, attacker)); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("fenced upsert err = %v, want pgx.ErrNoRows", err)
+ }
+ if owner := runtimeOwnerOf(t, f.victimRuntime); uuidToString(owner) != testUserID {
+ t.Fatalf("owner changed to %s through the fenced upsert", uuidToString(owner))
+ }
+ victim := parseUUID(testUserID)
+ if _, err := testHandler.Queries.UpsertAgentRuntime(ctx, params(victim, victim)); err != nil {
+ t.Fatalf("owner upsert: %v", err)
+ }
+ // Daemon-token path: no fence, no owner — the existing owner is kept.
+ row, err := testHandler.Queries.UpsertAgentRuntime(ctx, params(pgtype.UUID{}, pgtype.UUID{}))
+ if err != nil {
+ t.Fatalf("daemon-token upsert: %v", err)
+ }
+ if uuidToString(row.OwnerID) != testUserID {
+ t.Fatalf("daemon-token upsert owner = %s, want kept", uuidToString(row.OwnerID))
+ }
+}
+
+// TestDaemonRegister_ConcurrentRegistrationsHaveOneOwner races two members
+// registering the same fresh daemon_id: exactly one becomes the owner and
+// every request from the other is refused.
+func TestDaemonRegister_ConcurrentRegistrationsHaveOneOwner(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newOwnershipFixture(t, "regrace")
+ daemonID := "race-" + uuid.NewString()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID)
+ })
+
+ users := []string{testUserID, f.attackerID}
+ codes := make(map[string][]int)
+ var mu sync.Mutex
+ var wg sync.WaitGroup
+ for i := 0; i < 12; i++ {
+ user := users[i%2]
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ w := httptest.NewRecorder()
+ testHandler.DaemonRegister(w, registerAs(user, daemonID))
+ mu.Lock()
+ codes[user] = append(codes[user], w.Code)
+ mu.Unlock()
+ }()
+ }
+ wg.Wait()
+
+ var owner pgtype.UUID
+ dbfx.QueryRow(t, `SELECT owner_id FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, daemonID).Scan(&owner)
+ winner := uuidToString(owner)
+ if winner != testUserID && winner != f.attackerID {
+ t.Fatalf("runtime owner = %q, want one of the two registrants", winner)
+ }
+ for user, got := range codes {
+ want := http.StatusForbidden
+ if user == winner {
+ want = http.StatusOK
+ }
+ for _, code := range got {
+ if code != want {
+ t.Fatalf("user %s got %v, want all %d (winner %s)", user, got, want, winner)
+ }
+ }
+ }
+}
+
+func TestDaemonRegister_LegacyMergeRequiresOwnershipOfBothRows(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newOwnershipFixture(t, "legacymerge")
+ attackerDaemon := "attacker-" + uuid.NewString()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, attackerDaemon)
+ })
+
+ // The attacker's own registration succeeds, but naming the victim's
+ // daemon as a legacy id must not move or delete anything.
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(f.attackerID, attackerDaemon, f.victimDaemon)).Want(http.StatusOK)
+ if !rowExists(t, "agent_runtime", f.victimRuntime) {
+ t.Fatal("the victim's runtime was deleted by the attacker's legacy merge")
+ }
+ var agentRuntime, taskRuntime string
+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent WHERE id = $1`, f.agentID).Scan(&agentRuntime)
+ dbfx.QueryRow(t, `SELECT runtime_id FROM agent_task_queue WHERE id = $1`, f.queuedTask).Scan(&taskRuntime)
+ if agentRuntime != f.victimRuntime || taskRuntime != f.victimRuntime {
+ t.Fatalf("agent/task moved to %s/%s, want both still on %s", agentRuntime, taskRuntime, f.victimRuntime)
+ }
+
+ // The locked-row check refuses directly too.
+ var attackerRuntime string
+ dbfx.QueryRow(t, `SELECT id FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, attackerDaemon).Scan(&attackerRuntime)
+ err := testHandler.mergeLegacyRuntime(context.Background(), parseUUID(attackerRuntime), parseUUID(f.victimRuntime),
+ f.victimDaemon, "claude", parseUUID(f.attackerID))
+ if !errors.Is(err, errRuntimeMergeUnauthorized) {
+ t.Fatalf("mergeLegacyRuntime = %v, want errRuntimeMergeUnauthorized", err)
+ }
+
+ // The owner migrating their own machine still merges.
+ ownerDaemon := "owner-new-" + uuid.NewString()
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE workspace_id = $1 AND daemon_id = $2`, testWorkspaceID, ownerDaemon)
+ })
+ testutil.Call(t, testHandler.DaemonRegister, registerAs(testUserID, ownerDaemon, f.victimDaemon)).Want(http.StatusOK)
+ if rowExists(t, "agent_runtime", f.victimRuntime) {
+ t.Fatal("the owner's legacy runtime survived the owner's own merge")
+ }
+}
+
+func TestDaemonToken_BoundToItsOwnDaemon(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ f := newOwnershipFixture(t, "mdtbind")
+ peer := func(method, path string, body any, params ...string) *http.Request {
+ req := newDaemonTokenRequest(method, path, body, testWorkspaceID, "peer-daemon-"+f.victimDaemon)
+ if len(params) > 0 {
+ req = withURLParams(req, params...)
+ }
+ return req
+ }
+
+ testutil.Call(t, testHandler.ClaimTaskByRuntime,
+ peer("POST", "/api/daemon/runtimes/"+f.victimRuntime+"/tasks/claim", nil, "runtimeId", f.victimRuntime)).
+ Want(http.StatusNotFound)
+ testutil.Call(t, testHandler.GetTaskStatus,
+ peer("GET", "/api/daemon/tasks/"+f.runningTask+"/status", nil, "taskId", f.runningTask)).
+ Want(http.StatusNotFound)
+ testutil.Call(t, testHandler.CompleteTask,
+ peer("POST", "/api/daemon/tasks/"+f.runningTask+"/complete", map[string]any{"output": "x"}, "taskId", f.runningTask)).
+ Want(http.StatusNotFound)
+ w := httptest.NewRecorder()
+ if _, ok := testHandler.buildDaemonWebSocketIdentity(w, peer("GET", "/api/daemon/ws", nil), []string{f.victimRuntime}, ""); ok {
+ t.Fatal("peer daemon token authorized a websocket for another daemon's runtime")
+ }
+ if got := taskStatusOf(t, f.queuedTask); got != "queued" {
+ t.Fatalf("queued task status = %q, want queued", got)
+ }
+
+ // A runtime with no daemon_id is never reachable by a daemon token.
+ unpinned := dbfx.Runtime(t, "mdtbind unpinned runtime")
+ testutil.Call(t, testHandler.DaemonHeartbeat,
+ peer("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": unpinned})).
+ Want(http.StatusNotFound)
+
+ // The matching daemon token works.
+ testutil.Call(t, testHandler.DaemonHeartbeat,
+ newDaemonTokenRequest("POST", "/api/daemon/heartbeat", map[string]any{"runtime_id": f.victimRuntime}, testWorkspaceID, f.victimDaemon)).
+ Want(http.StatusOK)
+}
+
+func TestDaemonTaskRoutes_UnboundTaskIsNotWritable(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := dbfx.Runtime(t, "unbound task runtime")
+ agentID := dbfx.Agent(t, "unbound task agent", runtimeID)
+ issueID := dbfx.Issue(t, "unbound task issue")
+ // The shape a deleted runtime leaves behind: terminal history, no runtime.
+ taskID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": nil, "issue_id": issueID, "status": "completed",
+ "started_at": testutil.Raw("now() - interval '1 minute'"), "completed_at": testutil.Raw("now()"),
+ })
+ path := "/api/daemon/tasks/" + taskID
+
+ for _, tc := range []struct {
+ name string
+ handler http.HandlerFunc
+ method string
+ suffix string
+ body any
+ }{
+ {"complete", testHandler.CompleteTask, "POST", "/complete", map[string]any{"output": "x"}},
+ {"report messages", testHandler.ReportTaskMessages, "POST", "/messages", map[string]any{
+ "messages": []any{map[string]any{"seq": 1, "type": "text", "content": "forged"}},
+ }},
+ {"list messages", testHandler.ListTaskMessages, "GET", "/messages", nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ testutil.Call(t, tc.handler, withURLParams(newOwnerDaemonRequest(tc.method, path+tc.suffix, tc.body), "taskId", taskID)).
+ Want(http.StatusNotFound)
+ })
+ }
+ if got := taskStatusOf(t, taskID); got != "completed" {
+ t.Fatalf("unbound task status = %q, want untouched", got)
+ }
+ var messages int
+ dbfx.QueryRow(t, `SELECT count(*) FROM task_message WHERE task_id = $1`, taskID).Scan(&messages)
+ if messages != 0 {
+ t.Fatalf("%d messages written into an unbound task", messages)
+ }
+
+ // Status stays readable so a daemon can still see a terminal answer.
+ testutil.Call(t, testHandler.GetTaskStatus, withURLParams(newOwnerDaemonRequest("GET", path+"/status", nil), "taskId", taskID)).
+ Want(http.StatusOK)
+}
diff --git a/server/internal/handler/daemon_skill_load_failure_test.go b/server/internal/handler/daemon_skill_load_failure_test.go
index e82c0bf926..bfd504d679 100644
--- a/server/internal/handler/daemon_skill_load_failure_test.go
+++ b/server/internal/handler/daemon_skill_load_failure_test.go
@@ -117,7 +117,7 @@ func TestClaimTaskByRuntime_SkillReadFailurePreservesTask(t *testing.T) {
failing := newSkillFileReadFailureHandler(t)
runtimeID, taskID, _ := seedSkillLoadFixture(t, ctx, tc.fixture)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "skill-read-fail-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
if tc.capability != "" {
req.Header.Set("X-Client-Capabilities", tc.capability)
}
@@ -161,12 +161,12 @@ func TestResolveTaskSkillBundles_SkillReadFailureReturns500(t *testing.T) {
// The same request succeeds on the healthy handler, so the 500 below is
// the injected read failure and not a malformed fixture.
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", body, testWorkspaceID, "skill-read-fail-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", body)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusOK)
failing := newSkillFileReadFailureHandler(t)
- req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", body, testWorkspaceID, "skill-read-fail-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", body)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
testutil.Call(t, failing.ResolveTaskSkillBundles, req).Want(http.StatusInternalServerError)
}
diff --git a/server/internal/handler/daemon_skill_resolve_scope_test.go b/server/internal/handler/daemon_skill_resolve_scope_test.go
index e1fb820df9..a0d2fcc995 100644
--- a/server/internal/handler/daemon_skill_resolve_scope_test.go
+++ b/server/internal/handler/daemon_skill_resolve_scope_test.go
@@ -143,9 +143,9 @@ func resolveScopeFixture(t *testing.T, ctx context.Context, name string, skillNa
func resolveBundles(t *testing.T, h *Handler, runtimeID, taskID string, refs ...resolveSkillBundleRef) *testutil.Response {
t.Helper()
- req := newDaemonTokenRequest("POST",
+ req := newOwnerDaemonRequest("POST",
"/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve",
- resolveSkillBundlesRequest{Skills: refs}, testWorkspaceID, "resolve-scope-daemon")
+ resolveSkillBundlesRequest{Skills: refs})
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
return testutil.Call(t, h.ResolveTaskSkillBundles, req)
}
diff --git a/server/internal/handler/daemon_start_claim_test.go b/server/internal/handler/daemon_start_claim_test.go
index 4e31365ac1..d3ed2bd646 100644
--- a/server/internal/handler/daemon_start_claim_test.go
+++ b/server/internal/handler/daemon_start_claim_test.go
@@ -31,9 +31,9 @@ func startClaimFixture(t *testing.T, status string) (string, string, time.Time)
}
func startClaimRequest(taskID, runtimeID string, generation time.Time) *http.Request {
- return withURLParam(newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]string{
+ return withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]string{
"runtime_id": runtimeID, "dispatched_at": generation.Format(time.RFC3339Nano),
- }, testWorkspaceID, "start-claim-test"), "taskId", taskID)
+ }), "taskId", taskID)
}
func TestStartClaimLostResponseAndOwnership(t *testing.T) {
@@ -171,11 +171,11 @@ func TestStartClaimInvalidBodiesAndLegacy(t *testing.T) {
map[string]string{"runtime_id": "invalid", "dispatched_at": generation.Format(time.RFC3339Nano)},
map[string]string{"runtime_id": runtimeID, "dispatched_at": generation.Add(time.Nanosecond).Format(time.RFC3339Nano)},
} {
- req := withURLParam(newDaemonTokenRequest("POST", "/start", body, testWorkspaceID, "legacy-test"), "taskId", id)
+ req := withURLParam(newOwnerDaemonRequest("POST", "/start", body), "taskId", id)
testutil.Call(t, testHandler.StartTask, req).Want(http.StatusBadRequest)
}
for _, code := range []int{http.StatusOK, http.StatusBadRequest} {
- req := withURLParam(newDaemonTokenRequest("POST", "/start", nil, testWorkspaceID, "legacy-test"), "taskId", id)
+ req := withURLParam(newOwnerDaemonRequest("POST", "/start", nil), "taskId", id)
testutil.Call(t, testHandler.StartTask, req).Want(code)
}
}
@@ -190,7 +190,7 @@ func TestStartClaimWirePrecision(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- req := newDaemonTokenRequest("POST", "/claim", nil, testWorkspaceID, "claim-wire-test")
+ req := newOwnerDaemonRequest("POST", "/claim", nil)
// Exercise non-UTC database timestamp locations even on a UTC CI runner.
for _, zone := range []*time.Location{time.UTC, time.FixedZone("UTC+08", 8*60*60), time.FixedZone("UTC-07", -7*60*60)} {
t.Run(zone.String(), func(t *testing.T) {
diff --git a/server/internal/handler/daemon_task_lookup_test.go b/server/internal/handler/daemon_task_lookup_test.go
index 27a0248f28..76eb02968d 100644
--- a/server/internal/handler/daemon_task_lookup_test.go
+++ b/server/internal/handler/daemon_task_lookup_test.go
@@ -61,7 +61,7 @@ func TestGetTaskStatus_DoesNotResolveSourceWorkspace(t *testing.T) {
})
fault := &lookupFaultPool{DBTX: testPool, query: tc.query}
h := &Handler{Queries: db.New(fault), TaskService: &service.TaskService{Queries: db.New(fault)}}
- req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil, testWorkspaceID, "test-daemon")
+ req := newOwnerDaemonRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil)
req = withURLParam(req, "taskId", taskID)
var response map[string]string
@@ -84,7 +84,7 @@ func TestGetTaskStatus_TaskRowPresenceContract(t *testing.T) {
t.Run("task row missing", func(t *testing.T) {
missing := uuid.NewString()
- req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+missing+"/status", nil, testWorkspaceID, "test-daemon")
+ req := newOwnerDaemonRequest(http.MethodGet, "/api/daemon/tasks/"+missing+"/status", nil)
req = withURLParam(req, "taskId", missing)
w := testutil.Call(t, testHandler.GetTaskStatus, req).Want(http.StatusNotFound)
if !strings.Contains(w.Body.String(), "task not found") {
@@ -105,7 +105,7 @@ func TestGetTaskStatus_TaskRowPresenceContract(t *testing.T) {
})
dbfx.Exec(t, "DELETE FROM chat_session WHERE id = $1", chatID)
- req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil, testWorkspaceID, "test-daemon")
+ req := newOwnerDaemonRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil)
req = withURLParam(req, "taskId", taskID)
var response map[string]string
testutil.Call(t, testHandler.GetTaskStatus, req).Want(http.StatusOK).JSON(&response)
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index b4fca3ff65..d2b06d892e 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -83,6 +83,16 @@ func setHandlerTestWorkspaceRepos(t *testing.T, repos []map[string]string) {
// newDaemonTokenRequest creates an HTTP request with daemon token context set
// (simulating DaemonAuth middleware for mdt_ tokens).
+// newOwnerDaemonRequest builds a daemon-route request authenticated the way a
+// real daemon is: with the runtime owner's user credential (PAT/JWT), i.e.
+// X-User-ID = testUserID and no daemon-token context. Every dbfx / handler
+// fixture runtime is owned by testUserID. Use newDaemonTokenRequest only for
+// tests about daemon-token (mdt_) semantics, which since MUL-8154 require the
+// target runtime's daemon_id to match the token.
+func newOwnerDaemonRequest(method, path string, body any) *http.Request {
+ return newRequest(method, path, body)
+}
+
func newDaemonTokenRequest(method, path string, body any, workspaceID, daemonID string) *http.Request {
var buf bytes.Buffer
if body != nil {
@@ -92,6 +102,9 @@ func newDaemonTokenRequest(method, path string, body any, workspaceID, daemonID
req.Header.Set("Content-Type", "application/json")
// No X-User-ID — daemon tokens don't set it.
ctx := middleware.WithDaemonContext(req.Context(), workspaceID, daemonID)
+ // Production daemon tokens are bound to the runtime owner they were
+ // issued for (MUL-8154); fixture runtimes are owned by testUserID.
+ ctx = middleware.WithDaemonTokenOwnerID(ctx, testUserID)
return req.WithContext(ctx)
}
@@ -215,8 +228,7 @@ func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {
}, string) {
t.Helper()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "claim-reclaim-review")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -235,8 +247,7 @@ func claimTaskByRuntimeForTest(t *testing.T, runtimeID string) (*struct {
func claimChatIntroForTest(t *testing.T, runtimeID string) (string, bool, string) {
t.Helper()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "chat-intro-review")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -438,13 +449,11 @@ func TestExtendTaskPrepareLease(t *testing.T) {
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Extend prepare lease agent")
taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+otherRuntimeID+"/tasks/"+taskID+"/prepare-lease", nil,
- testWorkspaceID, "extend-prepare-lease")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+otherRuntimeID+"/tasks/"+taskID+"/prepare-lease", nil)
req = withURLParams(req, "runtimeId", otherRuntimeID, "taskId", taskID)
testutil.Call(t, testHandler.ExtendTaskPrepareLease, req).Want(http.StatusNotFound)
- req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/prepare-lease", nil,
- testWorkspaceID, "extend-prepare-lease")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/prepare-lease", nil)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
testutil.Call(t, testHandler.ExtendTaskPrepareLease, req).Want(http.StatusOK)
@@ -542,7 +551,7 @@ func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "skill-refs-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilitySkillBundlesV1)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -569,7 +578,7 @@ func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {
}
staleHashBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source, Hash: "sha256:stale"}}}
- req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", staleHashBody, testWorkspaceID, "skill-refs-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", staleHashBody)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusOK)
var staleHashResp struct {
@@ -581,12 +590,12 @@ func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {
}
invalidRefBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source}}}
- req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", invalidRefBody, testWorkspaceID, "skill-refs-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", invalidRefBody)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusBadRequest)
resolveBody := resolveSkillBundlesRequest{Skills: []resolveSkillBundleRef{{ID: ref.ID, Source: ref.Source, Hash: ref.Hash}}}
- req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody, testWorkspaceID, "skill-refs-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusOK)
var resolveResp struct {
@@ -598,7 +607,7 @@ func TestClaimTaskByRuntime_SkillBundleRefsAndResolve(t *testing.T) {
}
dbfx.Exec(t, `UPDATE agent_task_queue SET status = 'running', started_at = now() WHERE id = $1`, taskID)
- req = newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody, testWorkspaceID, "skill-refs-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/"+taskID+"/skill-bundles/resolve", resolveBody)
req = withURLParams(req, "runtimeId", runtimeID, "taskId", taskID)
w = testutil.Call(t, testHandler.ResolveTaskSkillBundles, req).Want(http.StatusConflict)
}
@@ -634,8 +643,7 @@ func TestClaimTaskByRuntime_PopulatesWorkspaceContext(t *testing.T) {
dbfx.QueryRow(t, `SELECT slug, issue_prefix FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&workspaceSlug, &issuePrefix)
dbfx.QueryRow(t, `SELECT number FROM issue WHERE id = $1`, issueID).Scan(&issueNumber)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "workspace-context-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -691,8 +699,7 @@ func TestClaimTaskByRuntime_WorkspaceContextEmptyWhenUnset(t *testing.T) {
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Workspace context empty claim agent")
taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "workspace-context-empty-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -719,7 +726,7 @@ func TestClaimTaskByRuntime_MissingRuntimeOwnerCancelsAndRejects(t *testing.T) {
ctx := context.Background()
runtimeID := dbfx.Insert(t, "agent_runtime", testutil.Cols{
"workspace_id": testWorkspaceID,
- "daemon_id": nil,
+ "daemon_id": "missing-owner-daemon",
"name": "Missing owner claim runtime",
"runtime_mode": "cloud",
"provider": "handler_test_runtime",
@@ -733,18 +740,23 @@ func TestClaimTaskByRuntime_MissingRuntimeOwnerCancelsAndRejects(t *testing.T) {
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Missing owner claim agent")
taskID := createDispatchedClaimFixtureTask(t, ctx, agentID, runtimeID, issueID, "120 seconds", false)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "missing-owner-claim")
+ // MUL-8154: an ownerless runtime is never reachable by a user
+ // credential, so nobody can claim it by PAT and nothing is touched.
+ userReq := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
+ userReq = withURLParam(userReq, "runtimeId", runtimeID)
+ testutil.Call(t, testHandler.ClaimTaskByRuntime, userReq).Want(http.StatusNotFound)
+
+ // Daemon tokens are owner-bound too, so even this daemon's own token
+ // cannot reach an ownerless runtime; the claim-path missing-owner
+ // defense stays covered by TestFinalizeClaimDelivery_*OwnerMissing*.
+ req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "missing-owner-daemon")
req = withURLParam(req, "runtimeId", runtimeID)
- w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusInternalServerError)
- 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())
- }
+ testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusNotFound)
var status string
dbfx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status)
- if status != "cancelled" {
- t.Fatalf("task status = %q, want cancelled", status)
+ if status != "dispatched" {
+ t.Fatalf("task status = %q, want untouched (dispatched)", status)
}
}
@@ -786,7 +798,7 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {
ctx := context.Background()
profileID := insertRuntimeProfileFixture(t, ctx, "Missing Custom Codex", "codex", "missing-codex")
- req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{
+ req := newOwnerDaemonRequest("POST", "/api/daemon/register", map[string]any{
"workspace_id": testWorkspaceID,
"daemon_id": "test-daemon-profile-failure",
"device_name": "test-device",
@@ -797,7 +809,7 @@ func TestDaemonRegister_RecordsRuntimeProfileRegistrationFailure(t *testing.T) {
"reason": "command not found on PATH: missing-codex",
},
},
- }, testWorkspaceID, "test-daemon-profile-failure")
+ })
req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityLocalWorktreeV1)
testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)
t.Cleanup(func() {
@@ -971,9 +983,9 @@ func TestDaemonHeartbeat_HTTPRuntimeGoneReturns404(t *testing.T) {
}
missingRuntime := uuid.New().String()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
"runtime_id": missingRuntime,
- }, testWorkspaceID, "test-daemon")
+ })
w := testutil.Call(t, testHandler.DaemonHeartbeat, req).Want(http.StatusNotFound)
if !strings.Contains(strings.ToLower(w.Body.String()), "runtime not found") {
t.Fatalf("expected 'runtime not found' body, got %s", w.Body.String())
@@ -1006,9 +1018,9 @@ func TestDaemonHeartbeat_SlowProbeDoesNotWedge(t *testing.T) {
})
w := httptest.NewRecorder()
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
"runtime_id": runtimeID,
- }, testWorkspaceID, "runtime-local-skills-daemon")
+ })
start := time.Now()
testHandler.DaemonHeartbeat(w, req)
@@ -1045,9 +1057,9 @@ func TestDaemonHeartbeat_EmptyQueueSkipsPopPending(t *testing.T) {
testHandler.LocalSkillImportStore = origImport
})
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
"runtime_id": runtimeID,
- }, testWorkspaceID, "runtime-local-skills-daemon")
+ })
testutil.Call(t, testHandler.DaemonHeartbeat, req).Want(http.StatusOK)
if listSpy.popCalls != 0 {
t.Fatalf("expected 0 PopPending calls on empty list queue, got %d", listSpy.popCalls)
@@ -1083,6 +1095,9 @@ func TestGetTaskStatus_WithDaemonToken_CrossWorkspace(t *testing.T) {
t.Fatalf("setup: get agent: %v", err)
}
+ // Since MUL-8154 a daemon token reaches only runtimes carrying its own
+ // daemon_id, so bind the task to a runtime of "legit-daemon".
+ runtimeID = dbfx.Runtime(t, "daemon-auth-status runtime", testutil.Cols{"daemon_id": "legit-daemon"})
err = testPool.QueryRow(context.Background(), `
INSERT INTO agent_task_queue (agent_id, issue_id, status, runtime_id)
VALUES ($1, $2, 'queued', $3)
@@ -1594,7 +1609,7 @@ func TestGetDaemonWorkspaceRepos_CACerts(t *testing.T) {
t.Cleanup(func() { testHandler.cfg.GitExtraCACerts = prev })
call := func() map[string]any {
- req := newDaemonTokenRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil, testWorkspaceID, "test-daemon-mdt")
+ req := newOwnerDaemonRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil)
req = withURLParam(req, "workspaceId", testWorkspaceID)
var resp map[string]any
testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusOK).JSON(&resp)
@@ -1623,14 +1638,14 @@ func TestDaemonRegister_CACerts(t *testing.T) {
const pemCerts = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"
testHandler.cfg.GitExtraCACerts = []byte(pemCerts)
- req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{
+ req := newOwnerDaemonRequest("POST", "/api/daemon/register", map[string]any{
"workspace_id": testWorkspaceID,
"daemon_id": "test-daemon-ca",
"device_name": "test-device",
"runtimes": []map[string]any{
{"name": "test-runtime-ca", "type": "claude", "version": "1.0.0", "status": "online"},
},
- }, testWorkspaceID, "test-daemon-ca")
+ })
var resp map[string]any
testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK).JSON(&resp)
t.Cleanup(func() {
@@ -1654,7 +1669,7 @@ func TestGetDaemonWorkspaceRepos_VersionIgnoresOrderAndDescription(t *testing.T)
getReposVersion := func() string {
t.Helper()
- req := newDaemonTokenRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil, testWorkspaceID, "test-daemon-mdt")
+ req := newOwnerDaemonRequest("GET", "/api/daemon/workspaces/"+testWorkspaceID+"/repos", nil)
req = withURLParam(req, "workspaceId", testWorkspaceID)
w := testutil.Call(t, testHandler.GetDaemonWorkspaceRepos, req).Want(http.StatusOK)
var resp struct {
@@ -2069,10 +2084,10 @@ func TestStartTask_AutopilotRunOnlyTask_ResolvesWorkspace(t *testing.T) {
// Same-workspace daemon token must succeed — this is the bug in #1224.
w = httptest.NewRecorder()
- req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]any{
+ req = newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/start", map[string]any{
"capabilities": []string{protocol.DaemonCapabilityTaskSupplementV1},
},
- testWorkspaceID, "legit-daemon")
+ )
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
testHandler.StartTask(w, req)
@@ -2137,7 +2152,7 @@ func TestClaimTask_ProjectGithubReposOverrideWorkspaceRepos(t *testing.T) {
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-project-repos")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -2203,7 +2218,7 @@ func TestClaimTask_ProjectDescriptionInjected(t *testing.T) {
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-project-desc")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -2292,7 +2307,7 @@ func TestClaimTask_ProjectWithoutRepos_FallsBackToWorkspaceRepos(t *testing.T) {
"issue_id": issueID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-fallback")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
@@ -2372,8 +2387,7 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceAndProjectContext(t *testi
defer testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
- testWorkspaceID, "test-daemon-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("runtimeId", runtimeID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -2493,8 +2507,7 @@ func TestClaimTaskByRuntime_TaskWorkspaceMismatch_CancelsAndRejects(t *testing.T
})
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+localRuntimeID+"/claim", nil,
- testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+localRuntimeID+"/claim", nil)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("runtimeId", localRuntimeID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -2558,9 +2571,9 @@ func TestCompleteTask_CommentTriggered_SynthesizesCommentWhenAgentSilent(t *test
)
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{"output": agentFinalOutput},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -2643,9 +2656,9 @@ func TestCompleteTask_CommentTriggered_SkipsSynthesisWhenAgentAlreadyCommented(t
`, issueID, testWorkspaceID, agentID, triggerCommentID)
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{"output": "final terminal text that must NOT become a comment"},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -2691,9 +2704,9 @@ func TestCompleteTask_CommentTriggered_SuppressesTrivialDoneOutput(t *testing.T)
})
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{"output": "Done."},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -2736,9 +2749,9 @@ func TestCompleteTask_AssignmentTriggered_DoesNotSuppressTrivialDoneOutput(t *te
})
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/complete",
map[string]any{"output": "Done."},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -2806,8 +2819,7 @@ func claimTaskForRuntimeGuardWithCapabilities(t *testing.T, runtimeID, daemonID,
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
- testWorkspaceID, daemonID)
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
if capabilities != "" {
req.Header.Set("X-Client-Capabilities", capabilities)
}
@@ -3874,8 +3886,7 @@ func TestGetChatSessionGCCheck(t *testing.T) {
w := testutil.Call(t, testHandler.GetChatSessionGCCheck, req).Want(http.StatusNotFound)
// Same-workspace daemon token sees the live row.
- req = newDaemonTokenRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil,
- testWorkspaceID, "legit-daemon")
+ req = newOwnerDaemonRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil)
req = withURLParam(req, "sessionId", sessionID)
w = testutil.Call(t, testHandler.GetChatSessionGCCheck, req).Want(http.StatusOK)
var resp struct {
@@ -3893,8 +3904,7 @@ func TestGetChatSessionGCCheck(t *testing.T) {
// Hard-deleted session: 404 — exactly what the daemon needs to reclaim
// the workdir on the next GC pass after a user runs DeleteChatSession.
dbfx.Exec(t, `DELETE FROM chat_session WHERE id = $1`, sessionID)
- req = newDaemonTokenRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil,
- testWorkspaceID, "legit-daemon")
+ req = newOwnerDaemonRequest("GET", "/api/daemon/chat-sessions/"+sessionID+"/gc-check", nil)
req = withURLParam(req, "sessionId", sessionID)
w = testutil.Call(t, testHandler.GetChatSessionGCCheck, req).Want(http.StatusNotFound)
}
@@ -3935,8 +3945,7 @@ func TestGetAutopilotRunGCCheck(t *testing.T) {
w := testutil.Call(t, testHandler.GetAutopilotRunGCCheck, req).Want(http.StatusNotFound)
// Same-workspace probe.
- req = newDaemonTokenRequest("GET", "/api/daemon/autopilot-runs/"+runID+"/gc-check", nil,
- testWorkspaceID, "legit-daemon")
+ req = newOwnerDaemonRequest("GET", "/api/daemon/autopilot-runs/"+runID+"/gc-check", nil)
req = withURLParam(req, "runId", runID)
w = testutil.Call(t, testHandler.GetAutopilotRunGCCheck, req).Want(http.StatusOK)
var resp struct {
@@ -3990,8 +3999,7 @@ func TestGetTaskGCCheck(t *testing.T) {
w := testutil.Call(t, testHandler.GetTaskGCCheck, req).Want(http.StatusNotFound)
// Same-workspace probe — terminal task returns its status.
- req = newDaemonTokenRequest("GET", "/api/daemon/tasks/"+taskID+"/gc-check", nil,
- testWorkspaceID, "legit-daemon")
+ req = newOwnerDaemonRequest("GET", "/api/daemon/tasks/"+taskID+"/gc-check", nil)
req = withURLParam(req, "taskId", taskID)
w = testutil.Call(t, testHandler.GetTaskGCCheck, req).Want(http.StatusOK)
var resp struct {
@@ -4271,7 +4279,7 @@ type claimCommentTaskResp struct {
func claimCommentTask(t *testing.T, runtimeID, daemonID string) claimCommentTaskResp {
t.Helper()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, daemonID)
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
var resp claimCommentTaskResp
@@ -4403,7 +4411,7 @@ func TestClaimTaskByRuntime_CommentTaskPopulatesInitiator(t *testing.T) {
taskID, _ := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)
dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $2, accountable_user_id = $2, originator_source = 'direct_human' WHERE id = $1`, taskID, testUserID)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "comment-initiator-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
w := testutil.Call(t, testHandler.ClaimTaskByRuntime, req).Want(http.StatusOK)
var resp struct {
@@ -4450,7 +4458,7 @@ func TestClaimTaskByRuntime_AssignmentHydratesOriginator(t *testing.T) {
"accountable_user_id": testUserID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "assignment-originator-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
var resp struct {
Task *AgentTaskResponse `json:"task"`
@@ -4502,7 +4510,7 @@ func TestClaimTaskByRuntime_DelegatedRunHydratesOriginator(t *testing.T) {
"delegated_from_task_id": sourceTaskID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+targetRuntimeID+"/tasks/claim", nil, testWorkspaceID, "delegated-originator-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+targetRuntimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", targetRuntimeID)
var resp struct {
Task *AgentTaskResponse `json:"task"`
@@ -4552,7 +4560,7 @@ func TestClaimTaskByRuntime_CommentAuthorDiffersFromOriginator(t *testing.T) {
"accountable_user_id": testUserID,
})
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "rerun-originator-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
var resp struct {
Task *AgentTaskResponse `json:"task"`
@@ -4581,7 +4589,7 @@ func TestClaimTaskByRuntime_CommentWithoutOriginatorOmitsOnBehalfOf(t *testing.T
agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Unattributed comment agent")
taskID, _ := createCommentTriggeredClaimTask(t, ctx, agentID, runtimeID, issueID, nil)
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil, testWorkspaceID, "unattributed-comment-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
var resp struct {
Task *AgentTaskResponse `json:"task"`
@@ -4712,8 +4720,7 @@ func TestAckTaskCancelled(t *testing.T) {
}
// Same-workspace token settles the deferred finalize.
- req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,
- testWorkspaceID, "legit-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil)
req = withURLParam(req, "taskId", taskID)
testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusOK)
dbfx.QueryRow(t, `
@@ -4731,8 +4738,7 @@ func TestAckTaskCancelled(t *testing.T) {
}
// Idempotent: a second ack is a no-op (no duplicate Stopped.).
- req = newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil,
- testWorkspaceID, "legit-daemon")
+ req = newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/cancel-ack", nil)
req = withURLParam(req, "taskId", taskID)
testutil.Call(t, testHandler.AckTaskCancelled, req).Want(http.StatusOK)
dbfx.QueryRow(t, `
@@ -4789,8 +4795,8 @@ func TestIssueGCChecksReportWireStatusNotRawCustomStatus(t *testing.T) {
type wire struct{ status, category string }
t.Run("batch endpoint", func(t *testing.T) {
- req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
- map[string]any{"issue_ids": []string{doneID, openID}}, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
+ map[string]any{"issue_ids": []string{doneID, openID}})
req = withURLParam(req, "workspaceId", testWorkspaceID)
var resp struct {
@@ -4831,7 +4837,7 @@ func TestIssueGCChecksReportWireStatusNotRawCustomStatus(t *testing.T) {
{"nonterminal custom status", openID, wire{issuestatus.InProgress, issuestatus.CategoryStarted}},
} {
t.Run(tc.name, func(t *testing.T) {
- req := newDaemonTokenRequest("GET", "/api/daemon/issues/"+tc.issueID+"/gc-check", nil, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("GET", "/api/daemon/issues/"+tc.issueID+"/gc-check", nil)
req = withURLParam(req, "issueId", tc.issueID)
var resp struct {
@@ -4877,8 +4883,8 @@ func TestBatchIssueGCCheckReadsCatalogOnceForManyCustomStatuses(t *testing.T) {
}
counter := withCountingCatalog(t)
- req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
- map[string]any{"issue_ids": ids}, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
+ map[string]any{"issue_ids": ids})
req = withURLParam(req, "workspaceId", testWorkspaceID)
var resp struct {
@@ -4929,8 +4935,8 @@ func TestBatchIssueGCCheckReadsNoCatalogForBuiltInStatuses(t *testing.T) {
}
counter := withCountingCatalog(t)
- req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
- map[string]any{"issue_ids": ids}, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
+ map[string]any{"issue_ids": ids})
req = withURLParam(req, "workspaceId", testWorkspaceID)
testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusOK)
@@ -4949,10 +4955,10 @@ func TestDaemonRegister_ProfileUsesStoredRuntimeIdentity(t *testing.T) {
if _, err := testPool.Exec(ctx, `UPDATE runtime_profile SET runtime_type = 'omp' WHERE id = $1`, profileID); err != nil {
t.Fatal(err)
}
- req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{
+ req := newOwnerDaemonRequest("POST", "/api/daemon/register", map[string]any{
"workspace_id": testWorkspaceID, "daemon_id": "test-omp-profile", "device_name": "test-device",
"runtimes": []map[string]any{{"name": "Custom OMP", "type": "pi", "profile_id": profileID, "status": "online"}},
- }, testWorkspaceID, "test-omp-profile")
+ })
testutil.Call(t, testHandler.DaemonRegister, req).Want(http.StatusOK)
t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_runtime WHERE profile_id = $1`, profileID) })
var provider string
diff --git a/server/internal/handler/daemon_ws.go b/server/internal/handler/daemon_ws.go
index dd450f59b4..60b27842d7 100644
--- a/server/internal/handler/daemon_ws.go
+++ b/server/internal/handler/daemon_ws.go
@@ -5,6 +5,7 @@ import (
"net/http"
"strings"
+ "github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/daemonws"
"github.com/multica-ai/multica/server/internal/middleware"
)
@@ -35,12 +36,14 @@ func (h *Handler) DaemonWebSocket(w http.ResponseWriter, r *http.Request) {
// this fixed scope without re-reading agent_runtime every 15 seconds.
func (h *Handler) buildDaemonWebSocketIdentity(w http.ResponseWriter, r *http.Request, runtimeIDs []string, userID string) (daemonws.ClientIdentity, bool) {
identity := daemonws.ClientIdentity{
- DaemonID: middleware.DaemonIDFromContext(r.Context()),
- UserID: userID,
- RuntimeIDs: runtimeIDs,
- RuntimeLeases: make(map[string]*daemonws.RuntimeLease, len(runtimeIDs)),
- ClientVersion: r.Header.Get("X-Client-Version"),
- Capabilities: r.Header.Get("X-Client-Capabilities"),
+ DaemonID: middleware.DaemonIDFromContext(r.Context()),
+ DaemonTokenHash: daemonTokenHashForRequest(r),
+ DaemonTokenOwnerID: middleware.DaemonTokenOwnerIDFromContext(r.Context()),
+ UserID: userID,
+ RuntimeIDs: runtimeIDs,
+ RuntimeLeases: make(map[string]*daemonws.RuntimeLease, len(runtimeIDs)),
+ ClientVersion: r.Header.Get("X-Client-Version"),
+ Capabilities: r.Header.Get("X-Client-Capabilities"),
}
if len(runtimeIDs) == 0 {
return identity, true
@@ -70,12 +73,12 @@ func (h *Handler) buildDaemonWebSocketIdentity(w http.ResponseWriter, r *http.Re
return daemonws.ClientIdentity{}, false
}
rt := rows[index]
- if identity.DaemonID != "" && rt.DaemonID.Valid && rt.DaemonID.String != identity.DaemonID {
- writeError(w, http.StatusNotFound, "runtime not found")
- return daemonws.ClientIdentity{}, false
- }
+ // Same runtime-level rule as the HTTP daemon routes (MUL-8154): a
+ // daemon token must match the runtime's daemon_id, a user credential
+ // must own the runtime. The leases seeded below authorize every later
+ // WS heartbeat for this runtime, so this is the only check they get.
workspaceID := uuidToString(rt.WorkspaceID)
- if !h.requireDaemonWorkspaceAccess(w, r, workspaceID) {
+ if !h.requireDaemonRuntimeAuthorized(w, r, workspaceID, rt.DaemonID, rt.OwnerID, "runtime not found") {
return daemonws.ClientIdentity{}, false
}
if workspaceID != "" {
@@ -101,6 +104,24 @@ func (h *Handler) buildDaemonWebSocketIdentity(w http.ResponseWriter, r *http.Re
return identity, true
}
+// daemonTokenHashForRequest returns the hash of the mdt_ token behind a
+// daemon-token request: the one DaemonAuth recorded, or — for a request that
+// carries a daemon context without passing DaemonAuth — the Authorization
+// header's. Empty for user credentials.
+func daemonTokenHashForRequest(r *http.Request) string {
+ if middleware.DaemonWorkspaceIDFromContext(r.Context()) == "" {
+ return ""
+ }
+ if hash := middleware.DaemonTokenHashFromContext(r.Context()); hash != "" {
+ return hash
+ }
+ raw := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ if !strings.HasPrefix(raw, "mdt_") {
+ return ""
+ }
+ return auth.HashToken(raw)
+}
+
func parseRuntimeIDs(r *http.Request) []string {
seen := map[string]struct{}{}
var out []string
diff --git a/server/internal/handler/daemon_ws_test.go b/server/internal/handler/daemon_ws_test.go
index cfd221096d..8626d5e6ee 100644
--- a/server/internal/handler/daemon_ws_test.go
+++ b/server/internal/handler/daemon_ws_test.go
@@ -83,7 +83,7 @@ func TestBuildDaemonWebSocketIdentityFailsClosedForMissingRuntime(t *testing.T)
if testHandler == nil {
t.Skip("database not available")
}
- req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/ws", nil, testWorkspaceID, "lease-daemon")
+ req := newOwnerDaemonRequest(http.MethodGet, "/api/daemon/ws", nil)
w := httptest.NewRecorder()
if _, ok := testHandler.buildDaemonWebSocketIdentity(w, req, []string{uuid.NewString()}, ""); ok {
diff --git a/server/internal/handler/issue_status_compatibility_test.go b/server/internal/handler/issue_status_compatibility_test.go
index b82a637c8b..1f600b56ff 100644
--- a/server/internal/handler/issue_status_compatibility_test.go
+++ b/server/internal/handler/issue_status_compatibility_test.go
@@ -193,13 +193,13 @@ func TestStatusCompatibilityGCAfterContract(t *testing.T) {
}
}
var single result
- req := withURLParam(newDaemonTokenRequest("GET", "/api/daemon/issues/"+id+"/gc-check", nil, testWorkspaceID, "compat-daemon"), "issueId", id)
+ req := withURLParam(newOwnerDaemonRequest("GET", "/api/daemon/issues/"+id+"/gc-check", nil), "issueId", id)
testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusOK).JSON(&single)
check(single)
var batch struct {
Issues []result `json:"issues"`
}
- req = withURLParam(newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{"issue_ids": []string{id}}, testWorkspaceID, "compat-daemon"), "workspaceId", testWorkspaceID)
+ req = withURLParam(newOwnerDaemonRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{"issue_ids": []string{id}}), "workspaceId", testWorkspaceID)
testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusOK).JSON(&batch)
if len(batch.Issues) != 1 {
t.Fatalf("GC results=%d", len(batch.Issues))
diff --git a/server/internal/handler/issue_wakeup_join_test.go b/server/internal/handler/issue_wakeup_join_test.go
index 81d5bff670..d00f200d7f 100644
--- a/server/internal/handler/issue_wakeup_join_test.go
+++ b/server/internal/handler/issue_wakeup_join_test.go
@@ -82,7 +82,7 @@ func claimRun(t *testing.T, taskID string, rendersJoined bool) string {
if err != nil {
t.Fatal(err)
}
- req := newDaemonTokenRequest("POST", "/claim", nil, testWorkspaceID, "joined-wakeups-test")
+ req := newOwnerDaemonRequest("POST", "/claim", nil)
if rendersJoined {
req.Header.Set("X-Client-Capabilities", protocol.DaemonCapabilityJoinedWakeupsV1)
}
diff --git a/server/internal/handler/qoder_connection.go b/server/internal/handler/qoder_connection.go
index d915fa5eb5..1b93c8b897 100644
--- a/server/internal/handler/qoder_connection.go
+++ b/server/internal/handler/qoder_connection.go
@@ -18,6 +18,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/auth"
+ "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/qoderruntime"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -590,8 +591,19 @@ func (h *Handler) qoderReady(ctx context.Context, ws string, revision int64, run
}
func (h *Handler) qoderCredentialAllowed(r *http.Request, ws, daemonID string) (bool, error) {
+ // Prefer the hash DaemonAuth recorded for the authenticating token: a WS
+ // RPC replays the request in-process without an Authorization header
+ // (MUL-8154). Fall back to the header for callers outside DaemonAuth.
+ tokenHash := middleware.DaemonTokenHashFromContext(r.Context())
+ if tokenHash == "" {
+ raw := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
+ if raw == "" {
+ return false, nil
+ }
+ tokenHash = auth.HashToken(raw)
+ }
var allowed bool
- err := h.DB.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection c JOIN daemon_token d ON d.id=c.token_id JOIN member m ON m.workspace_id=c.workspace_id AND m.user_id=c.owner_id WHERE c.provider='qoder_cloud' AND c.workspace_id=$1 AND c.enabled AND d.daemon_id=$2 AND d.token_hash=$3 AND d.expires_at>now() AND m.role IN ('owner','admin'))`, ws, daemonID, auth.HashToken(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))).Scan(&allowed)
+ err := h.DB.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM cloud_agent_connection c JOIN daemon_token d ON d.id=c.token_id JOIN member m ON m.workspace_id=c.workspace_id AND m.user_id=c.owner_id WHERE c.provider='qoder_cloud' AND c.workspace_id=$1 AND c.enabled AND d.daemon_id=$2 AND d.token_hash=$3 AND d.expires_at>now() AND m.role IN ('owner','admin'))`, ws, daemonID, tokenHash).Scan(&allowed)
return allowed, err
}
diff --git a/server/internal/handler/runtime_custom_name_test.go b/server/internal/handler/runtime_custom_name_test.go
index 32377f3845..195d2933da 100644
--- a/server/internal/handler/runtime_custom_name_test.go
+++ b/server/internal/handler/runtime_custom_name_test.go
@@ -130,14 +130,14 @@ func TestUpdateAgentRuntime_CustomNameMachineFanout(t *testing.T) {
func registerRuntimeOnDaemon(t *testing.T, daemonID, provider string) map[string]any {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{
+ req := newOwnerDaemonRequest("POST", "/api/daemon/register", map[string]any{
"workspace_id": testWorkspaceID,
"daemon_id": daemonID,
"device_name": "host",
"runtimes": []map[string]any{
{"name": provider + " (host)", "type": provider, "version": "1.0.0", "status": "online"},
},
- }, testWorkspaceID, daemonID)
+ })
testHandler.DaemonRegister(w, req)
if w.Code != http.StatusOK {
t.Fatalf("register %s: expected 200, got %d: %s", provider, w.Code, w.Body.String())
diff --git a/server/internal/handler/runtime_local_skills_overwrite_test.go b/server/internal/handler/runtime_local_skills_overwrite_test.go
index bf467e207e..f1b44f9618 100644
--- a/server/internal/handler/runtime_local_skills_overwrite_test.go
+++ b/server/internal/handler/runtime_local_skills_overwrite_test.go
@@ -133,7 +133,7 @@ func reportLocalSkillImport(t *testing.T, runtimeID, requestID string, body map[
w := httptest.NewRecorder()
req := withURLParams(
- newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+requestID+"/result", body, testWorkspaceID, "overwrite-test-daemon"),
+ newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+requestID+"/result", body),
"runtimeId", runtimeID,
"requestId", requestID,
)
diff --git a/server/internal/handler/runtime_local_skills_test.go b/server/internal/handler/runtime_local_skills_test.go
index d4b574b48c..5acc4119b2 100644
--- a/server/internal/handler/runtime_local_skills_test.go
+++ b/server/internal/handler/runtime_local_skills_test.go
@@ -495,9 +495,9 @@ func TestRuntimeLocalSkillImportFlow_EndToEnd(t *testing.T) {
}
w = httptest.NewRecorder()
- heartbeatReq := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
+ heartbeatReq := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
"runtime_id": runtimeID,
- }, testWorkspaceID, "runtime-local-skills-daemon")
+ })
testHandler.DaemonHeartbeat(w, heartbeatReq)
if w.Code != http.StatusOK {
t.Fatalf("DaemonHeartbeat: expected 200, got %d: %s", w.Code, w.Body.String())
@@ -526,7 +526,7 @@ func TestRuntimeLocalSkillImportFlow_EndToEnd(t *testing.T) {
w = httptest.NewRecorder()
reportReq := withURLParams(
- newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{
+ newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{
"status": "completed",
"skill": map[string]any{
"name": "Original Review Helper",
@@ -541,7 +541,7 @@ func TestRuntimeLocalSkillImportFlow_EndToEnd(t *testing.T) {
},
},
},
- }, testWorkspaceID, "runtime-local-skills-daemon"),
+ }),
"runtimeId", runtimeID,
"requestId", importReq.ID,
)
@@ -619,10 +619,10 @@ func TestBatchImportViaHeartbeat(t *testing.T) {
// Single heartbeat should return all 5 via the plural field.
w := httptest.NewRecorder()
- heartbeatReq := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
+ heartbeatReq := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
"runtime_id": runtimeID,
"supports_batch_import": true,
- }, testWorkspaceID, "runtime-local-skills-daemon")
+ })
testHandler.DaemonHeartbeat(w, heartbeatReq)
if w.Code != http.StatusOK {
t.Fatalf("DaemonHeartbeat: expected 200, got %d: %s", w.Code, w.Body.String())
@@ -668,10 +668,10 @@ func TestBatchImportViaHeartbeat(t *testing.T) {
// Second heartbeat should return nothing (all were claimed).
w = httptest.NewRecorder()
- heartbeatReq2 := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
+ heartbeatReq2 := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat", map[string]any{
"runtime_id": runtimeID,
"supports_batch_import": true,
- }, testWorkspaceID, "runtime-local-skills-daemon")
+ })
testHandler.DaemonHeartbeat(w, heartbeatReq2)
if w.Code != http.StatusOK {
t.Fatalf("DaemonHeartbeat: expected 200, got %d: %s", w.Code, w.Body.String())
@@ -722,7 +722,7 @@ func TestReportLocalSkillImportResult_IgnoresTimedOutRequests(t *testing.T) {
w := httptest.NewRecorder()
reportReq := withURLParams(
- newDaemonTokenRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{
+ newOwnerDaemonRequest(http.MethodPost, "/api/daemon/runtimes/"+runtimeID+"/local-skills/import/"+importReq.ID+"/result", map[string]any{
"status": "completed",
"skill": map[string]any{
"name": "Original Review Helper",
@@ -731,7 +731,7 @@ func TestReportLocalSkillImportResult_IgnoresTimedOutRequests(t *testing.T) {
"source_path": "~/.claude/skills/review-helper",
"provider": "claude",
},
- }, testWorkspaceID, "runtime-local-skills-daemon"),
+ }),
"runtimeId", runtimeID,
"requestId", importReq.ID,
)
diff --git a/server/internal/handler/runtime_lookup_metrics_test.go b/server/internal/handler/runtime_lookup_metrics_test.go
index b63132c6ec..7b91af9191 100644
--- a/server/internal/handler/runtime_lookup_metrics_test.go
+++ b/server/internal/handler/runtime_lookup_metrics_test.go
@@ -47,8 +47,8 @@ func TestAgentRuntimeLookupWSHotPathIsZeroRead(t *testing.T) {
}
}
- httpBeat := newDaemonTokenRequest(http.MethodPost, "/api/daemon/heartbeat",
- map[string]any{"runtime_id": runtimeID}, testWorkspaceID, "lookup-source-daemon")
+ httpBeat := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/heartbeat",
+ map[string]any{"runtime_id": runtimeID})
testutil.Call(t, h.DaemonHeartbeat, httpBeat).Want(http.StatusOK)
// A model poll for a runtime that no longer exists: the read-access gate
diff --git a/server/internal/handler/runtime_model_catalog_fallback_test.go b/server/internal/handler/runtime_model_catalog_fallback_test.go
index 90e5f38a2b..a62e0c3ff0 100644
--- a/server/internal/handler/runtime_model_catalog_fallback_test.go
+++ b/server/internal/handler/runtime_model_catalog_fallback_test.go
@@ -16,10 +16,10 @@ import (
// mis-wired cache branch in production code.
func reportModelList(t *testing.T, requestID string, body map[string]any) *httptest.ResponseRecorder {
t.Helper()
- req := newDaemonTokenRequest(
+ req := newOwnerDaemonRequest(
http.MethodPost,
"/api/daemon/runtimes/"+testRuntimeID+"/models/"+requestID+"/result",
- body, testWorkspaceID, "daemon-mul5549",
+ body,
)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("runtimeId", testRuntimeID)
diff --git a/server/internal/handler/squad_briefing_claim_test.go b/server/internal/handler/squad_briefing_claim_test.go
index 289917361b..69479b7273 100644
--- a/server/internal/handler/squad_briefing_claim_test.go
+++ b/server/internal/handler/squad_briefing_claim_test.go
@@ -18,8 +18,7 @@ func claimAgentInstructionsForTest(t *testing.T, runtimeID string) (taskID strin
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil,
- testWorkspaceID, "squad-briefing-claim")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/tasks/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
diff --git a/server/internal/handler/squad_briefing_test.go b/server/internal/handler/squad_briefing_test.go
index 7341cedfb1..357a8bdcc0 100644
--- a/server/internal/handler/squad_briefing_test.go
+++ b/server/internal/handler/squad_briefing_test.go
@@ -371,7 +371,7 @@ func claimAndDecodeAgent(t *testing.T, runtimeID string) *TaskAgentData {
t.Fatalf("refresh runtime heartbeat: %v", err)
}
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil, testWorkspaceID, "test-claim-squad-briefing")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil)
req = withURLParam(req, "runtimeId", runtimeID)
testHandler.ClaimTaskByRuntime(w, req)
if w.Code != http.StatusOK {
diff --git a/server/internal/handler/squad_no_action_test.go b/server/internal/handler/squad_no_action_test.go
index f91afef76b..0b2901a2c7 100644
--- a/server/internal/handler/squad_no_action_test.go
+++ b/server/internal/handler/squad_no_action_test.go
@@ -79,9 +79,9 @@ func completeRunningTask(t *testing.T, fx runningSquadLeaderTaskFixture, output
t.Helper()
w := httptest.NewRecorder()
- r := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+fx.TaskID+"/complete",
+ r := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+fx.TaskID+"/complete",
map[string]any{"output": output},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", fx.TaskID)
r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/task_message_batch_test.go b/server/internal/handler/task_message_batch_test.go
index 32aced2fc7..d5050c08dc 100644
--- a/server/internal/handler/task_message_batch_test.go
+++ b/server/internal/handler/task_message_batch_test.go
@@ -11,7 +11,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
- "github.com/multica-ai/multica/server/internal/middleware"
"github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -44,8 +43,9 @@ func batchMessagesRequest(t *testing.T, taskID string, messages []any) *http.Req
req := testutil.JSONRequest(http.MethodPost,
"/api/daemon/tasks/"+taskID+"/messages", map[string]any{"messages": messages})
req = testutil.WithURLParams(req, "taskId", taskID)
- return req.WithContext(middleware.WithDaemonContext(
- req.Context(), testWorkspaceID, "batch-messages-daemon"))
+ // The fixture runtime's owner, as a real daemon authenticates.
+ req.Header.Set("X-User-ID", testUserID)
+ return req
}
// TestReportTaskMessagesPersistsWholeBatch covers the multi-message shape of the
diff --git a/server/internal/handler/task_message_call_id_test.go b/server/internal/handler/task_message_call_id_test.go
index e70d18a62b..0cc1f6addb 100644
--- a/server/internal/handler/task_message_call_id_test.go
+++ b/server/internal/handler/task_message_call_id_test.go
@@ -76,8 +76,9 @@ func TestTaskMessageCallIDLiveAndHistory(t *testing.T) {
t.Run(reader.name+suffix, func(t *testing.T) {
req := testutil.JSONRequest(http.MethodGet, "/api/tasks/"+taskID+"/messages"+suffix, nil)
req = testutil.WithURLParams(req, "taskId", taskID)
- ctx := middleware.WithDaemonContext(req.Context(), testWorkspaceID, "call-id-daemon")
- ctx = middleware.SetMemberContext(ctx, testWorkspaceID, db.Member{})
+ // Both readers authenticate as the fixture runtime's owner.
+ req.Header.Set("X-User-ID", testUserID)
+ ctx := middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{})
var history []map[string]any
testutil.Call(t, reader.handler, req.WithContext(ctx)).Want(http.StatusOK).JSON(&history)
want := live
diff --git a/server/internal/handler/task_payload_nul_test.go b/server/internal/handler/task_payload_nul_test.go
index d3f2c06716..2c061496a7 100644
--- a/server/internal/handler/task_payload_nul_test.go
+++ b/server/internal/handler/task_payload_nul_test.go
@@ -63,7 +63,7 @@ func seedNULTask(t *testing.T, label string) (agentID, taskID string) {
// a chi URL param, the way the router does in production.
func daemonTaskRequest(t *testing.T, path, taskID string, body any) *http.Request {
t.Helper()
- req := newDaemonTokenRequest("POST", path, body, testWorkspaceID, "nul-regression-daemon")
+ req := newOwnerDaemonRequest("POST", path, body)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/task_supplement_test.go b/server/internal/handler/task_supplement_test.go
index f27cf0c34f..80a18a1240 100644
--- a/server/internal/handler/task_supplement_test.go
+++ b/server/internal/handler/task_supplement_test.go
@@ -70,10 +70,10 @@ func TestTaskSupplementClaimStartReplay(t *testing.T) {
generation := time.Date(2026, 9, 23, 0, 0, 0, 0, time.UTC)
dbfx.Exec(t, `UPDATE agent_task_queue SET dispatched_at=$2 WHERE id=$1`, f.taskID, generation)
for range 2 {
- req := withURLParam(newDaemonTokenRequest(http.MethodPost, "/start", map[string]any{
+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, "/start", map[string]any{
"runtime_id": f.runtimeID, "dispatched_at": generation.Format(time.RFC3339Nano),
"capabilities": []string{protocol.DaemonCapabilityTaskSupplementV1},
- }, testWorkspaceID, "start-claim-test"), "taskId", f.taskID)
+ }), "taskId", f.taskID)
var started AgentTaskResponse
testutil.Call(t, testHandler.StartTask, req).Want(http.StatusOK).JSON(&started)
if started.SupplementCapability != protocol.DaemonCapabilityTaskSupplementV1 {
@@ -101,7 +101,7 @@ func TestTaskSupplementLateDeliveryAndDeletion(t *testing.T) {
t.Fatalf("complete task: status %d: %s", w.Code, w.Body.String())
}
for _, c := range []CommentResponse{sent, pending} {
- req := withURLParams(newDaemonTokenRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}, testWorkspaceID, "legit-daemon"), "taskId", f.taskID, "commentId", c.ID)
+ req := withURLParams(newOwnerDaemonRequest(http.MethodPost, "/ack", map[string]any{"delivered": true}), "taskId", f.taskID, "commentId", c.ID)
want := http.StatusOK
if c.ID == pending.ID {
want = http.StatusConflict
@@ -264,8 +264,8 @@ func TestTaskSupplementCompletionDoesNotReplayBoundComments(t *testing.T) {
// Drive the real completion handler: a direct SQL status update skips
// the reconciliation that previously replayed the supplement.
- req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/"+fixture.taskID+"/complete",
- map[string]any{"output": "done"}, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest(http.MethodPost, "/api/daemon/tasks/"+fixture.taskID+"/complete",
+ map[string]any{"output": "done"})
testutil.Call(t, testHandler.CompleteTask, withURLParam(req, "taskId", fixture.taskID)).Want(http.StatusOK)
if status == "pending" || status == "delivering" {
receipt, err := testHandler.Queries.GetTaskSupplementForRun(t.Context(), db.GetTaskSupplementForRunParams{
diff --git a/server/internal/handler/task_terminal_wakeup_test.go b/server/internal/handler/task_terminal_wakeup_test.go
index f550798d83..30d3e8be67 100644
--- a/server/internal/handler/task_terminal_wakeup_test.go
+++ b/server/internal/handler/task_terminal_wakeup_test.go
@@ -20,9 +20,9 @@ func (r *terminalWakeupRecorder) NotifyTaskAvailable(runtimeID, taskID string) {
func failTaskViaHandler(t *testing.T, taskID string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/fail",
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/fail",
map[string]any{"error": "agent failed", "failure_reason": "agent_error"},
- testWorkspaceID, "legit-daemon")
+ )
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/handler/workspace_delete_fence_test.go b/server/internal/handler/workspace_delete_fence_test.go
index 7bbf9b628e..ee43dcc2bb 100644
--- a/server/internal/handler/workspace_delete_fence_test.go
+++ b/server/internal/handler/workspace_delete_fence_test.go
@@ -360,7 +360,7 @@ func TestMergeLegacyRuntime_KeepsOldRuntimeWhenFenceRefuses(t *testing.T) {
// the target's workspace was torn down a moment ago.
vanishedTarget := parseUUID("00000000-0000-0000-0000-0000000000fe")
- err := h.mergeLegacyRuntime(ctx, vanishedTarget, parseUUID(f.victimRuntime), "legacy-daemon", "delete-test")
+ err := h.mergeLegacyRuntime(ctx, vanishedTarget, parseUUID(f.victimRuntime), "legacy-daemon", "delete-test", parseUUID(testUserID))
if !errors.Is(err, errRuntimeMergeFenced) {
t.Fatalf("mergeLegacyRuntime = %v, want errRuntimeMergeFenced", err)
}
@@ -394,7 +394,7 @@ RETURNING id
t.Fatalf("create merge target: %v", err)
}
if err := h.mergeLegacyRuntime(ctx, parseUUID(freshRuntime), parseUUID(f.victimRuntime),
- "legacy-daemon", "delete-test"); err != nil {
+ "legacy-daemon", "delete-test", parseUUID(testUserID)); err != nil {
t.Fatalf("merge onto a live runtime: %v", err)
}
if rowExists(t, "agent_runtime", f.victimRuntime) {
@@ -464,7 +464,7 @@ FOR EACH ROW EXECUTE FUNCTION mul5999_fail_agent_move()
})
err := testHandler.mergeLegacyRuntime(ctx, parseUUID(target), parseUUID(f.victimRuntime),
- "legacy-daemon", "delete-test")
+ "legacy-daemon", "delete-test", parseUUID(testUserID))
if err == nil {
t.Fatal("merge reported success even though the agent reassignment failed")
}
@@ -509,7 +509,7 @@ FOR EACH ROW EXECUTE FUNCTION mul5999_fail_agent_move()
t.Fatalf("drop injection trigger: %v", err)
}
if err := testHandler.mergeLegacyRuntime(ctx, parseUUID(target), parseUUID(f.victimRuntime),
- "legacy-daemon", "delete-test"); err != nil {
+ "legacy-daemon", "delete-test", parseUUID(testUserID)); err != nil {
t.Fatalf("merge after removing the injection: %v", err)
}
if rowExists(t, "agent_runtime", f.victimRuntime) {
diff --git a/server/internal/handler/worktree_claim_gate_test.go b/server/internal/handler/worktree_claim_gate_test.go
index c2a11db2e0..eb8d1864a2 100644
--- a/server/internal/handler/worktree_claim_gate_test.go
+++ b/server/internal/handler/worktree_claim_gate_test.go
@@ -167,8 +167,8 @@ func TestWorktreeDeliveryMetadataRoundTripsThroughBothTerminalPaths(t *testing.T
post := func(t *testing.T, taskID, endpoint string, body map[string]any, call func(http.ResponseWriter, *http.Request)) {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/"+endpoint,
- body, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/"+endpoint,
+ body)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -279,8 +279,8 @@ func TestWorktreeDeliveryMetadataSurvivesEveryTerminalPath(t *testing.T) {
post := func(t *testing.T, taskID, endpoint string, body map[string]any, call func(http.ResponseWriter, *http.Request)) {
t.Helper()
w := httptest.NewRecorder()
- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/"+endpoint,
- body, testWorkspaceID, "legit-daemon")
+ req := newOwnerDaemonRequest("POST", "/api/daemon/tasks/"+taskID+"/"+endpoint,
+ body)
rctx := chi.NewRouteContext()
rctx.URLParams.Add("taskId", taskID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.go
index 0455c08888..868102f76d 100644
--- a/server/internal/middleware/daemon_auth.go
+++ b/server/internal/middleware/daemon_auth.go
@@ -20,6 +20,8 @@ const (
ctxKeyDaemonWorkspaceID daemonContextKey = iota
ctxKeyDaemonID
ctxKeyDaemonAuthPath
+ ctxKeyDaemonTokenHash
+ ctxKeyDaemonTokenOwnerID
)
// Daemon auth path labels exposed via context for slow-log attribution.
@@ -52,6 +54,43 @@ func DaemonAuthPathFromContext(ctx context.Context) string {
// WithDaemonContext returns a new context with the daemon workspace ID and daemon ID set.
// This is used by tests to simulate daemon token authentication.
+// DaemonTokenHashFromContext returns the hash of the mdt_ token that
+// authenticated the request, or "" for any other auth path. Checks that must
+// re-validate the exact credential (e.g. Qoder revocation) read it from here
+// rather than the Authorization header, so they also work for requests that
+// are replayed in-process from a WebSocket connection (MUL-8154).
+func DaemonTokenHashFromContext(ctx context.Context) string {
+ h, _ := ctx.Value(ctxKeyDaemonTokenHash).(string)
+ return h
+}
+
+// DaemonTokenOwnerIDFromContext returns the runtime owner the authenticating
+// mdt_ token is bound to, or "" when it is unbound (Qoder-managed) or the
+// request did not use a daemon token (MUL-8154).
+func DaemonTokenOwnerIDFromContext(ctx context.Context) string {
+ id, _ := ctx.Value(ctxKeyDaemonTokenOwnerID).(string)
+ return id
+}
+
+// WithDaemonTokenOwnerID attaches the token's owner binding; the WS RPC
+// bridge uses it to replay a connection's credential in-process.
+func WithDaemonTokenOwnerID(ctx context.Context, ownerID string) context.Context {
+ if ownerID == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, ctxKeyDaemonTokenOwnerID, ownerID)
+}
+
+// WithDaemonTokenHash attaches the authenticating mdt_ token hash. The WS
+// RPC bridge uses it to carry the connection's credential into the
+// synthetic request it hands to the HTTP handler.
+func WithDaemonTokenHash(ctx context.Context, tokenHash string) context.Context {
+ if tokenHash == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, ctxKeyDaemonTokenHash, tokenHash)
+}
+
func WithDaemonContext(ctx context.Context, workspaceID, daemonID string) context.Context {
ctx = context.WithValue(ctx, ctxKeyDaemonWorkspaceID, workspaceID)
ctx = context.WithValue(ctx, ctxKeyDaemonID, daemonID)
@@ -119,6 +158,8 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.
ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, id.WorkspaceID)
ctx = context.WithValue(ctx, ctxKeyDaemonID, id.DaemonID)
ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)
+ ctx = context.WithValue(ctx, ctxKeyDaemonTokenHash, hash)
+ ctx = WithDaemonTokenOwnerID(ctx, id.OwnerID)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
@@ -138,6 +179,9 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.
WorkspaceID: uuidToString(dt.WorkspaceID),
DaemonID: dt.DaemonID,
}
+ if dt.OwnerID.Valid {
+ identity.OwnerID = uuidToString(dt.OwnerID)
+ }
// daemon_token.expires_at is NOT NULL; pgtype Valid is true
// in normal operation, but defend against zero just in case.
var expiresAt time.Time
@@ -149,6 +193,8 @@ func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.
ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, identity.WorkspaceID)
ctx = context.WithValue(ctx, ctxKeyDaemonID, identity.DaemonID)
ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)
+ ctx = context.WithValue(ctx, ctxKeyDaemonTokenHash, hash)
+ ctx = WithDaemonTokenOwnerID(ctx, identity.OwnerID)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 97b76a8cc9..f55ab83416 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3842,7 +3842,16 @@ func (s *TaskService) FinalizeTaskClaim(
if err := qtx.DeleteExpiredDaemonTokens(ctx); err != nil {
return fmt.Errorf("delete expired daemon tokens: %w", err)
}
- if _, err := qtx.CreateDaemonToken(ctx, daemonTokens[0]); err != nil {
+ // Bind the credential to the same owner the task token was just
+ // minted for (the locked runtime owner, set by authorize), so it
+ // can never reach a runtime another member later registers under
+ // this daemon_id (MUL-8154).
+ daemonToken := daemonTokens[0]
+ daemonToken.OwnerID = token.UserID
+ if !daemonToken.OwnerID.Valid {
+ return fmt.Errorf("create remote MCP daemon token: runtime owner required")
+ }
+ if _, err := qtx.CreateDaemonToken(ctx, daemonToken); err != nil {
return fmt.Errorf("create remote MCP daemon token: %w", err)
}
}
diff --git a/server/migrations/588_daemon_token_owner.down.sql b/server/migrations/588_daemon_token_owner.down.sql
new file mode 100644
index 0000000000..ff14f9ad98
--- /dev/null
+++ b/server/migrations/588_daemon_token_owner.down.sql
@@ -0,0 +1 @@
+ALTER TABLE daemon_token DROP COLUMN IF EXISTS owner_id;
diff --git a/server/migrations/588_daemon_token_owner.up.sql b/server/migrations/588_daemon_token_owner.up.sql
new file mode 100644
index 0000000000..2f6e8b1517
--- /dev/null
+++ b/server/migrations/588_daemon_token_owner.up.sql
@@ -0,0 +1,14 @@
+-- MUL-8154: bind daemon tokens to the runtime owner they were issued for.
+-- A daemon_id can be re-registered by another member after its runtimes are
+-- deleted; a token bound only to (workspace_id, daemon_id) would then reach
+-- the new owner's runtimes. Daemon routes require owner_id to match the
+-- runtime's owner for every non-Qoder-managed token.
+--
+-- No backfill: the issuing owner of a pre-existing token cannot be recovered
+-- (the daemon's current owner may be a later re-registrant), so existing
+-- non-Qoder tokens stay NULL and are refused. They are short-lived Remote MCP
+-- credentials (24h) that are re-issued on the next claim. Qoder-managed
+-- tokens are governed by cloud_agent_connection and stay NULL by design.
+-- Plain column, no foreign key (repository rule): a token whose owner is
+-- deleted simply never matches a runtime owner again.
+ALTER TABLE daemon_token ADD COLUMN IF NOT EXISTS owner_id UUID;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 03ae31691a..ac898986b0 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -4251,24 +4251,42 @@ func (q *Queries) GetAgentTaskInWorkspace(ctx context.Context, arg GetAgentTaskI
}
const getAgentTaskStatus = `-- name: GetAgentTaskStatus :one
-SELECT atq.status, a.workspace_id
+SELECT atq.status, a.workspace_id, atq.runtime_id,
+ rt.workspace_id AS runtime_workspace_id,
+ rt.daemon_id AS runtime_daemon_id,
+ rt.owner_id AS runtime_owner_id
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
+LEFT JOIN agent_runtime rt ON rt.id = atq.runtime_id
WHERE atq.id = $1
`
type GetAgentTaskStatusRow struct {
- Status string `json:"status"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Status string `json:"status"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ RuntimeWorkspaceID pgtype.UUID `json:"runtime_workspace_id"`
+ RuntimeDaemonID pgtype.Text `json:"runtime_daemon_id"`
+ RuntimeOwnerID pgtype.UUID `json:"runtime_owner_id"`
}
// Hot-path status polling needs only the task status and the owning agent's
// workspace for authorization. Keep this independent of optional source links
// (issue, chat session, autopilot run) so it needs no source-entity lookup.
+// The bound runtime's workspace / daemon / owner ride along (LEFT JOIN: a
+// terminal task outlives a deleted runtime) so the daemon route can enforce
+// runtime ownership without a second round trip (MUL-8154).
func (q *Queries) GetAgentTaskStatus(ctx context.Context, id pgtype.UUID) (GetAgentTaskStatusRow, error) {
row := q.db.QueryRow(ctx, getAgentTaskStatus, id)
var i GetAgentTaskStatusRow
- err := row.Scan(&i.Status, &i.WorkspaceID)
+ err := row.Scan(
+ &i.Status,
+ &i.WorkspaceID,
+ &i.RuntimeID,
+ &i.RuntimeWorkspaceID,
+ &i.RuntimeDaemonID,
+ &i.RuntimeOwnerID,
+ )
return i, err
}
diff --git a/server/pkg/db/generated/daemon_token.sql.go b/server/pkg/db/generated/daemon_token.sql.go
index 9bd2503f4f..4aa041f19f 100644
--- a/server/pkg/db/generated/daemon_token.sql.go
+++ b/server/pkg/db/generated/daemon_token.sql.go
@@ -12,9 +12,9 @@ import (
)
const createDaemonToken = `-- name: CreateDaemonToken :one
-INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at)
-VALUES ($1, $2, $3, $4)
-RETURNING id, token_hash, workspace_id, daemon_id, expires_at, created_at
+INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at, owner_id)
+VALUES ($1, $2, $3, $4, $5)
+RETURNING id, token_hash, workspace_id, daemon_id, expires_at, created_at, owner_id
`
type CreateDaemonTokenParams struct {
@@ -22,14 +22,18 @@ type CreateDaemonTokenParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
DaemonID string `json:"daemon_id"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
+ OwnerID pgtype.UUID `json:"owner_id"`
}
+// owner_id binds the token to the runtime owner it was issued for (MUL-8154);
+// NULL only for Qoder-managed tokens.
func (q *Queries) CreateDaemonToken(ctx context.Context, arg CreateDaemonTokenParams) (DaemonToken, error) {
row := q.db.QueryRow(ctx, createDaemonToken,
arg.TokenHash,
arg.WorkspaceID,
arg.DaemonID,
arg.ExpiresAt,
+ arg.OwnerID,
)
var i DaemonToken
err := row.Scan(
@@ -39,6 +43,7 @@ func (q *Queries) CreateDaemonToken(ctx context.Context, arg CreateDaemonTokenPa
&i.DaemonID,
&i.ExpiresAt,
&i.CreatedAt,
+ &i.OwnerID,
)
return i, err
}
@@ -93,7 +98,7 @@ func (q *Queries) DeleteExpiredDaemonTokens(ctx context.Context) error {
}
const getDaemonTokenByHash = `-- name: GetDaemonTokenByHash :one
-SELECT id, token_hash, workspace_id, daemon_id, expires_at, created_at FROM daemon_token
+SELECT id, token_hash, workspace_id, daemon_id, expires_at, created_at, owner_id FROM daemon_token
WHERE token_hash = $1 AND expires_at > now()
`
@@ -107,6 +112,7 @@ func (q *Queries) GetDaemonTokenByHash(ctx context.Context, tokenHash string) (D
&i.DaemonID,
&i.ExpiresAt,
&i.CreatedAt,
+ &i.OwnerID,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index c56adb8151..aa8f3362f0 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -668,6 +668,7 @@ type DaemonToken struct {
DaemonID string `json:"daemon_id"`
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ OwnerID pgtype.UUID `json:"owner_id"`
}
type DingtalkBotIdentity struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 02f60629d2..9d2b063321 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -603,7 +603,7 @@ func (q *Queries) GetAgentRuntimeForWorkspace(ctx context.Context, arg GetAgentR
}
const getAgentRuntimeHeartbeatLeases = `-- name: GetAgentRuntimeHeartbeatLeases :many
-SELECT id, workspace_id, daemon_id, status, last_seen_at
+SELECT id, workspace_id, daemon_id, owner_id, status, last_seen_at
FROM agent_runtime
WHERE id = ANY($1::uuid[])
`
@@ -612,6 +612,7 @@ type GetAgentRuntimeHeartbeatLeasesRow struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
DaemonID pgtype.Text `json:"daemon_id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
Status string `json:"status"`
LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
}
@@ -620,6 +621,9 @@ type GetAgentRuntimeHeartbeatLeasesRow struct {
// WebSocket authenticates its whole runtime set in one round trip and then
// keeps these immutable ownership fields plus liveness state in its connection
// lease, avoiding a GetAgentRuntime call on every heartbeat.
+//
+// owner_id is carried so the WS handshake can enforce runtime ownership for
+// user-credential connections (MUL-8154) with the same single round trip.
func (q *Queries) GetAgentRuntimeHeartbeatLeases(ctx context.Context, ids []pgtype.UUID) ([]GetAgentRuntimeHeartbeatLeasesRow, error) {
rows, err := q.db.Query(ctx, getAgentRuntimeHeartbeatLeases, ids)
if err != nil {
@@ -633,6 +637,7 @@ func (q *Queries) GetAgentRuntimeHeartbeatLeases(ctx context.Context, ids []pgty
&i.ID,
&i.WorkspaceID,
&i.DaemonID,
+ &i.OwnerID,
&i.Status,
&i.LastSeenAt,
); err != nil {
@@ -1084,6 +1089,44 @@ func (q *Queries) ListNonOwnerActiveTasksByRuntimeForUpdate(ctx context.Context,
return items, nil
}
+const listRuntimeOwnersByDaemon = `-- name: ListRuntimeOwnersByDaemon :many
+SELECT id, owner_id FROM agent_runtime
+WHERE workspace_id = $1 AND daemon_id = $2
+`
+
+type ListRuntimeOwnersByDaemonParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+}
+
+type ListRuntimeOwnersByDaemonRow struct {
+ ID pgtype.UUID `json:"id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+}
+
+// Registration pre-check (MUL-8154): every runtime row a daemon_id already
+// holds in a workspace, with its owner. A user-credential registration is
+// refused before any write when any of them belongs to someone else.
+func (q *Queries) ListRuntimeOwnersByDaemon(ctx context.Context, arg ListRuntimeOwnersByDaemonParams) ([]ListRuntimeOwnersByDaemonRow, error) {
+ rows, err := q.db.Query(ctx, listRuntimeOwnersByDaemon, arg.WorkspaceID, arg.DaemonID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListRuntimeOwnersByDaemonRow{}
+ for rows.Next() {
+ var i ListRuntimeOwnersByDaemonRow
+ if err := rows.Scan(&i.ID, &i.OwnerID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listStaleOfflineRuntimeGCCandidates = `-- name: ListStaleOfflineRuntimeGCCandidates :many
SELECT id FROM agent_runtime
WHERE status = 'offline'
@@ -1306,12 +1349,18 @@ func (q *Queries) LockRuntimeRevocationChatSessions(ctx context.Context, arg Loc
}
const lockRuntimesForMerge = `-- name: LockRuntimesForMerge :many
-SELECT id FROM agent_runtime
+SELECT id, workspace_id, owner_id FROM agent_runtime
WHERE id = ANY($1::uuid[])
ORDER BY id
FOR UPDATE
`
+type LockRuntimesForMergeRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+}
+
// Step 2: the runtime rows themselves, FOR UPDATE, in id order.
//
// FOR UPDATE is the point. A task write's fence takes FOR KEY SHARE on the runtime
@@ -1328,19 +1377,21 @@ FOR UPDATE
//
// Returns the ids it actually locked: a caller that asked for two and got fewer
// knows a runtime disappeared before it got there and must abandon the merge.
-func (q *Queries) LockRuntimesForMerge(ctx context.Context, runtimeIds []pgtype.UUID) ([]pgtype.UUID, error) {
+// workspace_id and owner_id come back with the lock so the merge can verify,
+// against the locked rows, that the caller owns both sides (MUL-8154).
+func (q *Queries) LockRuntimesForMerge(ctx context.Context, runtimeIds []pgtype.UUID) ([]LockRuntimesForMergeRow, error) {
rows, err := q.db.Query(ctx, lockRuntimesForMerge, runtimeIds)
if err != nil {
return nil, err
}
defer rows.Close()
- items := []pgtype.UUID{}
+ items := []LockRuntimesForMergeRow{}
for rows.Next() {
- var id pgtype.UUID
- if err := rows.Scan(&id); err != nil {
+ var i LockRuntimesForMergeRow
+ if err := rows.Scan(&i.ID, &i.WorkspaceID, &i.OwnerID); err != nil {
return nil, err
}
- items = append(items, id)
+ items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
@@ -2028,7 +2079,10 @@ INSERT INTO agent_runtime (
metadata,
owner_id,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
+) VALUES (
+ $1, $2, $3, $4, $5, $6,
+ $7, $8, $9, now()
+)
ON CONFLICT (workspace_id, daemon_id, provider) WHERE profile_id IS NULL
DO UPDATE SET
name = EXCLUDED.name,
@@ -2039,19 +2093,22 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
+WHERE $10::uuid IS NULL
+ OR agent_runtime.owner_id = $10::uuid
RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- DaemonID pgtype.Text `json:"daemon_id"`
- Name string `json:"name"`
- RuntimeMode string `json:"runtime_mode"`
- Provider string `json:"provider"`
- Status string `json:"status"`
- DeviceInfo string `json:"device_info"`
- Metadata []byte `json:"metadata"`
- OwnerID pgtype.UUID `json:"owner_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode"`
+ Provider string `json:"provider"`
+ Status string `json:"status"`
+ DeviceInfo string `json:"device_info"`
+ Metadata []byte `json:"metadata"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ RequiredOwnerID pgtype.UUID `json:"required_owner_id"`
}
type UpsertAgentRuntimeRow struct {
@@ -2078,6 +2135,14 @@ type UpsertAgentRuntimeRow struct {
// (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
// that updated an existing row (false). Analytics reads this to fire
// runtime_registered/runtime_ready only on first-time registration.
+//
+// Ownership fence (MUL-8154): when required_owner_id is set (user-credential
+// registration), the conflict branch only updates a row already owned by that
+// user. A row owned by someone else - or by nobody - is left untouched and the
+// statement returns no row, so a workspace member cannot take over another
+// member's runtime by re-registering its (daemon_id, provider). Daemon-token
+// registration passes NULL here and NULL owner_id, which keeps the existing
+// owner via the COALESCE below.
// Built-in runtimes carry no profile_id. The arbiter is the partial unique
// index from migration 121 (WHERE profile_id IS NULL); the predicate must be
// spelled out so Postgres selects that partial index, not the custom-runtime
@@ -2093,6 +2158,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
arg.DeviceInfo,
arg.Metadata,
arg.OwnerID,
+ arg.RequiredOwnerID,
)
var i UpsertAgentRuntimeRow
err := row.Scan(
@@ -2131,7 +2197,10 @@ INSERT INTO agent_runtime (
owner_id,
profile_id,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
+) VALUES (
+ $1, $2, $3, $4, $5, $6,
+ $7, $8, $9, $10, now()
+)
ON CONFLICT (workspace_id, daemon_id, profile_id) WHERE profile_id IS NOT NULL
DO UPDATE SET
name = EXCLUDED.name,
@@ -2143,20 +2212,23 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
+WHERE $11::uuid IS NULL
+ OR agent_runtime.owner_id = $11::uuid
RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeWithProfileParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- DaemonID pgtype.Text `json:"daemon_id"`
- Name string `json:"name"`
- RuntimeMode string `json:"runtime_mode"`
- Provider string `json:"provider"`
- Status string `json:"status"`
- DeviceInfo string `json:"device_info"`
- Metadata []byte `json:"metadata"`
- OwnerID pgtype.UUID `json:"owner_id"`
- ProfileID pgtype.UUID `json:"profile_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode"`
+ Provider string `json:"provider"`
+ Status string `json:"status"`
+ DeviceInfo string `json:"device_info"`
+ Metadata []byte `json:"metadata"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ ProfileID pgtype.UUID `json:"profile_id"`
+ RequiredOwnerID pgtype.UUID `json:"required_owner_id"`
}
type UpsertAgentRuntimeWithProfileRow struct {
@@ -2186,7 +2258,8 @@ type UpsertAgentRuntimeWithProfileRow struct {
// single daemon can host the built-in provider AND any number of custom
// profiles of the same protocol family. provider carries the base runtime
// identity so ResolveBackend applies its descriptor; profile_id preserves
-// custom-profile provenance. (xmax = 0) AS inserted mirrors UpsertAgentRuntime.
+// custom-profile provenance. (xmax = 0) AS inserted mirrors UpsertAgentRuntime,
+// and the required_owner_id fence matches it too.
func (q *Queries) UpsertAgentRuntimeWithProfile(ctx context.Context, arg UpsertAgentRuntimeWithProfileParams) (UpsertAgentRuntimeWithProfileRow, error) {
row := q.db.QueryRow(ctx, upsertAgentRuntimeWithProfile,
arg.WorkspaceID,
@@ -2199,6 +2272,7 @@ func (q *Queries) UpsertAgentRuntimeWithProfile(ctx context.Context, arg UpsertA
arg.Metadata,
arg.OwnerID,
arg.ProfileID,
+ arg.RequiredOwnerID,
)
var i UpsertAgentRuntimeWithProfileRow
err := row.Scan(
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index ceef11884d..b9001a75c0 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -685,9 +685,16 @@ WHERE id = $1;
-- Hot-path status polling needs only the task status and the owning agent's
-- workspace for authorization. Keep this independent of optional source links
-- (issue, chat session, autopilot run) so it needs no source-entity lookup.
-SELECT atq.status, a.workspace_id
+-- The bound runtime's workspace / daemon / owner ride along (LEFT JOIN: a
+-- terminal task outlives a deleted runtime) so the daemon route can enforce
+-- runtime ownership without a second round trip (MUL-8154).
+SELECT atq.status, a.workspace_id, atq.runtime_id,
+ rt.workspace_id AS runtime_workspace_id,
+ rt.daemon_id AS runtime_daemon_id,
+ rt.owner_id AS runtime_owner_id
FROM agent_task_queue atq
JOIN agent a ON a.id = atq.agent_id
+LEFT JOIN agent_runtime rt ON rt.id = atq.runtime_id
WHERE atq.id = $1;
-- name: GetAgentTaskForDelegatedFailureUpdate :one
diff --git a/server/pkg/db/queries/daemon_token.sql b/server/pkg/db/queries/daemon_token.sql
index ec4a139b5b..427ff1a71c 100644
--- a/server/pkg/db/queries/daemon_token.sql
+++ b/server/pkg/db/queries/daemon_token.sql
@@ -1,6 +1,8 @@
-- name: CreateDaemonToken :one
-INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at)
-VALUES ($1, $2, $3, $4)
+-- owner_id binds the token to the runtime owner it was issued for (MUL-8154);
+-- NULL only for Qoder-managed tokens.
+INSERT INTO daemon_token (token_hash, workspace_id, daemon_id, expires_at, owner_id)
+VALUES (@token_hash, @workspace_id, @daemon_id, @expires_at, sqlc.narg('owner_id'))
RETURNING *;
-- name: GetDaemonTokenByHash :one
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 46c7528b71..ccedc13f39 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -35,7 +35,10 @@ WHERE id = ANY(@ids::uuid[]);
-- WebSocket authenticates its whole runtime set in one round trip and then
-- keeps these immutable ownership fields plus liveness state in its connection
-- lease, avoiding a GetAgentRuntime call on every heartbeat.
-SELECT id, workspace_id, daemon_id, status, last_seen_at
+--
+-- owner_id is carried so the WS handshake can enforce runtime ownership for
+-- user-credential connections (MUL-8154) with the same single round trip.
+SELECT id, workspace_id, daemon_id, owner_id, status, last_seen_at
FROM agent_runtime
WHERE id = ANY(@ids::uuid[]);
@@ -64,6 +67,14 @@ WHERE id = $1 AND workspace_id = $2;
-- (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
-- that updated an existing row (false). Analytics reads this to fire
-- runtime_registered/runtime_ready only on first-time registration.
+--
+-- Ownership fence (MUL-8154): when required_owner_id is set (user-credential
+-- registration), the conflict branch only updates a row already owned by that
+-- user. A row owned by someone else - or by nobody - is left untouched and the
+-- statement returns no row, so a workspace member cannot take over another
+-- member's runtime by re-registering its (daemon_id, provider). Daemon-token
+-- registration passes NULL here and NULL owner_id, which keeps the existing
+-- owner via the COALESCE below.
INSERT INTO agent_runtime (
workspace_id,
daemon_id,
@@ -75,7 +86,10 @@ INSERT INTO agent_runtime (
metadata,
owner_id,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
+) VALUES (
+ @workspace_id, @daemon_id, @name, @runtime_mode, @provider, @status,
+ @device_info, @metadata, @owner_id, now()
+)
-- Built-in runtimes carry no profile_id. The arbiter is the partial unique
-- index from migration 121 (WHERE profile_id IS NULL); the predicate must be
-- spelled out so Postgres selects that partial index, not the custom-runtime
@@ -90,6 +104,8 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
+WHERE sqlc.narg('required_owner_id')::uuid IS NULL
+ OR agent_runtime.owner_id = sqlc.narg('required_owner_id')::uuid
RETURNING *, (xmax = 0) AS inserted;
-- name: UpsertAgentRuntimeWithProfile :one
@@ -99,7 +115,8 @@ RETURNING *, (xmax = 0) AS inserted;
-- single daemon can host the built-in provider AND any number of custom
-- profiles of the same protocol family. provider carries the base runtime
-- identity so ResolveBackend applies its descriptor; profile_id preserves
--- custom-profile provenance. (xmax = 0) AS inserted mirrors UpsertAgentRuntime.
+-- custom-profile provenance. (xmax = 0) AS inserted mirrors UpsertAgentRuntime,
+-- and the required_owner_id fence matches it too.
INSERT INTO agent_runtime (
workspace_id,
daemon_id,
@@ -112,7 +129,10 @@ INSERT INTO agent_runtime (
owner_id,
profile_id,
last_seen_at
-) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, now())
+) VALUES (
+ @workspace_id, @daemon_id, @name, @runtime_mode, @provider, @status,
+ @device_info, @metadata, @owner_id, @profile_id, now()
+)
ON CONFLICT (workspace_id, daemon_id, profile_id) WHERE profile_id IS NOT NULL
DO UPDATE SET
name = EXCLUDED.name,
@@ -124,6 +144,8 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
+WHERE sqlc.narg('required_owner_id')::uuid IS NULL
+ OR agent_runtime.owner_id = sqlc.narg('required_owner_id')::uuid
RETURNING *, (xmax = 0) AS inserted;
-- name: UpdateAgentRuntimeVisibility :one
@@ -539,7 +561,9 @@ FOR KEY SHARE;
--
-- Returns the ids it actually locked: a caller that asked for two and got fewer
-- knows a runtime disappeared before it got there and must abandon the merge.
-SELECT id FROM agent_runtime
+-- workspace_id and owner_id come back with the lock so the merge can verify,
+-- against the locked rows, that the caller owns both sides (MUL-8154).
+SELECT id, workspace_id, owner_id FROM agent_runtime
WHERE id = ANY(@runtime_ids::uuid[])
ORDER BY id
FOR UPDATE;
@@ -632,3 +656,10 @@ SELECT EXISTS (
-- Final fail-closed assertion after UnbindTasksFromRuntime. A non-zero result
-- aborts the transaction instead of relying on the legacy ON DELETE CASCADE.
SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1;
+
+-- name: ListRuntimeOwnersByDaemon :many
+-- Registration pre-check (MUL-8154): every runtime row a daemon_id already
+-- holds in a workspace, with its owner. A user-credential registration is
+-- refused before any write when any of them belongs to someone else.
+SELECT id, owner_id FROM agent_runtime
+WHERE workspace_id = @workspace_id AND daemon_id = @daemon_id;