Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(security): add workspace ownership checks to daemon API routes (#684)
Jiayuan Zhang82bbce98fd76
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 498f53a3d2..3c11dc0972 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -92,9 +92,9 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Router.Post("/auth/verify-code", h.VerifyCode)r.Post("/auth/google", h.GoogleLogin)- // Daemon API routes (all require a valid token)+ // Daemon API routes (require daemon token or valid user token)r.Route("/api/daemon", func(r chi.Router) {- r.Use(middleware.Auth(queries))+ r.Use(middleware.DaemonAuth(queries))r.Post("/register", h.DaemonRegister)r.Post("/deregister", h.DaemonDeregister)diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex f1a4c1be25..58b5ba600b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -10,11 +10,104 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/middleware"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/redact")+// ---------------------------------------------------------------------------+// Daemon workspace ownership helpers+// ---------------------------------------------------------------------------++// requireDaemonWorkspaceAccess verifies the caller has access to the given workspace.+// For daemon tokens (mdt_), compares the token's workspace ID directly.+// For PAT/JWT fallback, verifies user membership in the workspace.+func (h *Handler) requireDaemonWorkspaceAccess(w http.ResponseWriter, r *http.Request, workspaceID string) bool {+ if workspaceID == "" {+ writeError(w, http.StatusNotFound, "not found")+ return false+ }++ // Daemon token: workspace must match.+ if daemonWsID := middleware.DaemonWorkspaceIDFromContext(r.Context()); daemonWsID != "" {+ if daemonWsID != workspaceID {+ writeError(w, http.StatusNotFound, "not found")+ return false+ }+ return true+ }++ // PAT/JWT fallback: verify user is a member of the workspace.+ _, ok := h.requireWorkspaceMember(w, r, workspaceID, "not found")+ return ok+}++// requireDaemonRuntimeAccess looks up a runtime and verifies the caller owns its workspace.+func (h *Handler) requireDaemonRuntimeAccess(w http.ResponseWriter, r *http.Request, runtimeID string) (db.AgentRuntime, bool) {+ rt, err := h.Queries.GetAgentRuntime(r.Context(), parseUUID(runtimeID))+ if err != nil {+ writeError(w, http.StatusNotFound, "runtime not found")+ return db.AgentRuntime{}, false+ }+ if !h.requireDaemonWorkspaceAccess(w, r, uuidToString(rt.WorkspaceID)) {+ return db.AgentRuntime{}, false+ }+ return rt, true+}++// requireDaemonTaskAccess looks up a task and verifies the caller owns its workspace.+func (h *Handler) requireDaemonTaskAccess(w http.ResponseWriter, r *http.Request, taskID string) (db.AgentTaskQueue, bool) {+ task, err := h.Queries.GetAgentTask(r.Context(), parseUUID(taskID))+ if err != nil {+ writeError(w, http.StatusNotFound, "task not found")+ return db.AgentTaskQueue{}, false+ }++ wsID := h.resolveTaskWorkspaceID(r, task)+ if wsID == "" {+ writeError(w, http.StatusNotFound, "task not found")+ return db.AgentTaskQueue{}, false+ }++ if !h.requireDaemonWorkspaceAccess(w, r, wsID) {+ return db.AgentTaskQueue{}, false+ }+ return task, true+}++// verifyDaemonWorkspaceAccess checks workspace access without writing an HTTP error.+// Used in loops where individual items may be skipped silently.+func (h *Handler) verifyDaemonWorkspaceAccess(r *http.Request, workspaceID string) bool {+ if workspaceID == "" {+ return false+ }+ if daemonWsID := middleware.DaemonWorkspaceIDFromContext(r.Context()); daemonWsID != "" {+ return daemonWsID == workspaceID+ }+ userID := requestUserID(r)+ if userID == "" {+ return false+ }+ _, err := h.getWorkspaceMember(r.Context(), userID, workspaceID)+ return err == nil+}++// resolveTaskWorkspaceID derives the workspace ID from a task's issue or chat session.+func (h *Handler) resolveTaskWorkspaceID(r *http.Request, task db.AgentTaskQueue) string {+ if task.IssueID.Valid {+ if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {+ return uuidToString(issue.WorkspaceID)+ }+ }+ if task.ChatSessionID.Valid {+ if cs, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID); err == nil {+ return uuidToString(cs.WorkspaceID)+ }+ }+ return ""+}+// ---------------------------------------------------------------------------// Daemon Registration & Heartbeat// ---------------------------------------------------------------------------@@ -56,10 +149,23 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {return}- // Verify the caller is a member of the target workspace.- member, ok := h.requireWorkspaceMember(w, r, req.WorkspaceID, "workspace not found")- if !ok {- return+ // 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+ 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.+ } else {+ member, ok := h.requireWorkspaceMember(w, r, req.WorkspaceID, "workspace not found")+ if !ok {+ return+ }+ ownerID = member.UserID}ws, err := h.Queries.GetWorkspace(r.Context(), parseUUID(req.WorkspaceID))@@ -105,7 +211,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {Status: status,DeviceInfo: deviceInfo,Metadata: metadata,- OwnerID: member.UserID,+ OwnerID: ownerID,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())@@ -151,19 +257,25 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {affectedWorkspaces := make(map[string]bool)for _, rid := range req.RuntimeIDs {- // Look up the runtime to find its workspace.+ // Look up the runtime and verify ownership.rt, err := h.Queries.GetAgentRuntime(r.Context(), parseUUID(rid))if err != nil {slog.Warn("deregister: runtime not found", "runtime_id", rid, "error", err)continue}+ wsID := uuidToString(rt.WorkspaceID)+ if !h.verifyDaemonWorkspaceAccess(r, wsID) {+ slog.Warn("deregister: workspace mismatch", "runtime_id", rid)+ continue+ }+if err := h.Queries.SetAgentRuntimeOffline(r.Context(), parseUUID(rid)); err != nil {slog.Warn("deregister: failed to set offline", "runtime_id", rid, "error", err)continue}- affectedWorkspaces[uuidToString(rt.WorkspaceID)] = true+ affectedWorkspaces[wsID] = true}// Notify frontend clients so they re-fetch runtime list.@@ -193,6 +305,11 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {return}+ // Verify the caller owns this runtime's workspace.+ if _, ok := h.requireDaemonRuntimeAccess(w, r, req.RuntimeID); !ok {+ return+ }+_, err := h.Queries.UpdateAgentRuntimeHeartbeat(r.Context(), parseUUID(req.RuntimeID))if err != nil {writeError(w, http.StatusInternalServerError, "heartbeat failed")@@ -224,6 +341,11 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")+ // Verify the caller owns this runtime's workspace.+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {+ return+ }+task, err := h.TaskService.ClaimTaskForRuntime(r.Context(), parseUUID(runtimeID))if err != nil {writeError(w, http.StatusInternalServerError, "failed to claim task: "+err.Error())@@ -312,6 +434,11 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {func (h *Handler) ListPendingTasksByRuntime(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")+ // Verify the caller owns this runtime's workspace.+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {+ return+ }+tasks, err := h.Queries.ListPendingTasksByRuntime(r.Context(), parseUUID(runtimeID))if err != nil {writeError(w, http.StatusInternalServerError, "failed to list pending tasks")@@ -334,6 +461,11 @@ func (h *Handler) ListPendingTasksByRuntime(w http.ResponseWriter, r *http.Requefunc (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")+ // Verify the caller owns this task's workspace.+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ return+ }+task, err := h.TaskService.StartTask(r.Context(), parseUUID(taskID))if err != nil {slog.Warn("start task failed", "task_id", taskID, "error", err)@@ -361,10 +493,14 @@ func (h *Handler) ReportTaskProgress(w http.ResponseWriter, r *http.Request) {return}- // Look up task to get workspace ID via the associated issue.+ // Verify ownership and resolve workspace ID.+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ if !ok {+ return+ }+workspaceID := ""- task, err := h.Queries.GetAgentTask(r.Context(), parseUUID(taskID))- if err == nil {+ if task.IssueID.Valid {if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {workspaceID = uuidToString(issue.WorkspaceID)}@@ -385,6 +521,11 @@ type TaskCompleteRequest struct {func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")+ // Verify the caller owns this task's workspace.+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ return+ }+var req TaskCompleteRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -417,6 +558,11 @@ type TaskUsagePayload struct {func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")+ // Verify the caller owns this task's workspace.+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ return+ }+var req struct {Usage []TaskUsagePayload `json:"usage"`}@@ -446,11 +592,13 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {// Used by the daemon to check whether a task was cancelled mid-execution.func (h *Handler) GetTaskStatus(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")- task, err := h.Queries.GetAgentTask(r.Context(), parseUUID(taskID))- if err != nil {- writeError(w, http.StatusNotFound, "task not found")++ // Verify the caller owns this task's workspace.+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ if !ok {return}+writeJSON(w, http.StatusOK, map[string]string{"status": task.Status})}@@ -462,6 +610,11 @@ type TaskFailRequest struct {func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")+ // Verify the caller owns this task's workspace.+ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ return+ }+var req TaskFailRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -510,9 +663,9 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {return}- task, err := h.Queries.GetAgentTask(r.Context(), parseUUID(taskID))- if err != nil {- writeError(w, http.StatusNotFound, "task not found")+ // Verify the caller owns this task's workspace.+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ if !ok {return}@@ -569,13 +722,16 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {func (h *Handler) ListTaskMessages(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")- task, err := h.Queries.GetAgentTask(r.Context(), parseUUID(taskID))- if err != nil {- writeError(w, http.StatusNotFound, "task not found")+ // Verify the caller owns this task's workspace.+ task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ if !ok {return}- var messages []db.TaskMessage+ var (+ messages []db.TaskMessage+ err error+ )if sinceStr := r.URL.Query().Get("since"); sinceStr != "" {sinceSeq, parseErr := strconv.Atoi(sinceStr)if parseErr != nil {diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.gonew file mode 100644index 0000000000..eb700a99f9--- /dev/null+++ b/server/internal/handler/daemon_test.go@@ -0,0 +1,182 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/go-chi/chi/v5"+ "github.com/multica-ai/multica/server/internal/middleware"+)++// newDaemonTokenRequest creates an HTTP request with daemon token context set+// (simulating DaemonAuth middleware for mdt_ tokens).+func newDaemonTokenRequest(method, path string, body any, workspaceID, daemonID string) *http.Request {+ var buf bytes.Buffer+ if body != nil {+ json.NewEncoder(&buf).Encode(body)+ }+ req := httptest.NewRequest(method, path, &buf)+ req.Header.Set("Content-Type", "application/json")+ // No X-User-ID — daemon tokens don't set it.+ ctx := middleware.WithDaemonContext(req.Context(), workspaceID, daemonID)+ return req.WithContext(ctx)+}++func TestDaemonRegister_WithDaemonToken(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": "test-daemon-mdt",+ "device_name": "test-device",+ "runtimes": []map[string]any{+ {"name": "test-runtime", "type": "claude", "version": "1.0.0", "status": "online"},+ },+ }, testWorkspaceID, "test-daemon-mdt")++ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("DaemonRegister with daemon token: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp map[string]any+ json.NewDecoder(w.Body).Decode(&resp)+ runtimes, ok := resp["runtimes"].([]any)+ if !ok || len(runtimes) == 0 {+ t.Fatalf("DaemonRegister: expected runtimes in response, got %v", resp)+ }++ // Clean up: deregister the runtime.+ rt := runtimes[0].(map[string]any)+ runtimeID := rt["id"].(string)+ testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)+}++func TestDaemonRegister_WithDaemonToken_WorkspaceMismatch(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ w := httptest.NewRecorder()+ // Daemon token is for a different workspace than the request body.+ req := newDaemonTokenRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": "test-daemon-mdt",+ "device_name": "test-device",+ "runtimes": []map[string]any{+ {"name": "test-runtime", "type": "claude", "version": "1.0.0", "status": "online"},+ },+ }, "00000000-0000-0000-0000-000000000000", "test-daemon-mdt")++ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("DaemonRegister with mismatched workspace: expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestDaemonHeartbeat_WithDaemonToken_CrossWorkspace(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ // First, register a runtime using PAT (existing flow).+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/daemon/register", map[string]any{+ "workspace_id": testWorkspaceID,+ "daemon_id": "test-daemon-heartbeat",+ "device_name": "test-device",+ "runtimes": []map[string]any{+ {"name": "test-runtime-hb", "type": "claude", "version": "1.0.0", "status": "online"},+ },+ })+ testHandler.DaemonRegister(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("Setup: DaemonRegister failed: %d: %s", w.Code, w.Body.String())+ }+ var regResp map[string]any+ json.NewDecoder(w.Body).Decode(®Resp)+ runtimes := regResp["runtimes"].([]any)+ runtimeID := runtimes[0].(map[string]any)["id"].(string)+ defer testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)++ // Try heartbeat with a daemon token from a DIFFERENT workspace — should fail.+ w = httptest.NewRecorder()+ req = newDaemonTokenRequest("POST", "/api/daemon/heartbeat", map[string]any{+ "runtime_id": runtimeID,+ }, "00000000-0000-0000-0000-000000000000", "attacker-daemon")++ testHandler.DaemonHeartbeat(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("DaemonHeartbeat with cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestGetTaskStatus_WithDaemonToken_CrossWorkspace(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ // Create a task in the test workspace.+ var issueID, taskID string+ err := testPool.QueryRow(context.Background(), `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type)+ VALUES ($1, 'daemon-auth-test-issue', 'todo', 'medium', $2, 'member')+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID)+ if err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ defer testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)++ // Get an agent and runtime from the test workspace.+ var agentID, runtimeID string+ err = testPool.QueryRow(context.Background(), `+ SELECT a.id, a.runtime_id FROM agent a WHERE a.workspace_id = $1 LIMIT 1+ `, testWorkspaceID).Scan(&agentID, &runtimeID)+ if err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }++ err = testPool.QueryRow(context.Background(), `+ INSERT INTO agent_task_queue (agent_id, issue_id, status, runtime_id)+ VALUES ($1, $2, 'queued', $3)+ RETURNING id+ `, agentID, issueID, runtimeID).Scan(&taskID)+ if err != nil {+ t.Fatalf("setup: create task: %v", err)+ }+ defer testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)++ // Try GetTaskStatus with a daemon token from a DIFFERENT workspace — should fail.+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("GET", "/api/daemon/tasks/"+taskID+"/status", nil,+ "00000000-0000-0000-0000-000000000000", "attacker-daemon")+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("taskId", taskID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))++ testHandler.GetTaskStatus(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("GetTaskStatus with cross-workspace token: expected 404, got %d: %s", w.Code, w.Body.String())+ }++ // Same request with the CORRECT workspace should succeed.+ w = httptest.NewRecorder()+ req = newDaemonTokenRequest("GET", "/api/daemon/tasks/"+taskID+"/status", nil,+ testWorkspaceID, "legit-daemon")+ req = req.WithContext(context.WithValue(+ middleware.WithDaemonContext(req.Context(), testWorkspaceID, "legit-daemon"),+ chi.RouteCtxKey, rctx))++ testHandler.GetTaskStatus(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetTaskStatus with correct workspace token: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 90b9d84293..62bff77c6a 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -80,7 +80,7 @@ type RuntimeUsageResponse struct {CacheWriteTokens int64 `json:"cache_write_tokens"`}-// ReportRuntimeUsage receives usage data from the daemon (unauthenticated daemon route).+// ReportRuntimeUsage receives usage data from the daemon.func (h *Handler) ReportRuntimeUsage(w http.ResponseWriter, r *http.Request) {runtimeID := chi.URLParam(r, "runtimeId")if runtimeID == "" {@@ -88,6 +88,11 @@ func (h *Handler) ReportRuntimeUsage(w http.ResponseWriter, r *http.Request) {return}+ // Verify the caller owns this runtime's workspace.+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {+ return+ }+var req struct {Entries []RuntimeUsageEntry `json:"entries"`}diff --git a/server/internal/handler/runtime_ping.go b/server/internal/handler/runtime_ping.goindex c23c468345..68fca89008 100644--- a/server/internal/handler/runtime_ping.go+++ b/server/internal/handler/runtime_ping.go@@ -177,6 +177,13 @@ func (h *Handler) GetPing(w http.ResponseWriter, r *http.Request) {// ReportPingResult receives the ping result from the daemon.func (h *Handler) ReportPingResult(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")++ // Verify the caller owns this runtime's workspace.+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {+ return+ }+pingID := chi.URLParam(r, "pingId")var req struct {diff --git a/server/internal/handler/runtime_update.go b/server/internal/handler/runtime_update.goindex f7430544e3..d1f4dd8e5a 100644--- a/server/internal/handler/runtime_update.go+++ b/server/internal/handler/runtime_update.go@@ -191,6 +191,13 @@ func (h *Handler) GetUpdate(w http.ResponseWriter, r *http.Request) {// ReportUpdateResult receives the update result from the daemon.func (h *Handler) ReportUpdateResult(w http.ResponseWriter, r *http.Request) {+ runtimeID := chi.URLParam(r, "runtimeId")++ // Verify the caller owns this runtime's workspace.+ if _, ok := h.requireDaemonRuntimeAccess(w, r, runtimeID); !ok {+ return+ }+updateID := chi.URLParam(r, "updateId")var req struct {diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.goindex d91282cfef..a534a20f8d 100644--- a/server/internal/middleware/daemon_auth.go+++ b/server/internal/middleware/daemon_auth.go@@ -31,6 +31,14 @@ func DaemonIDFromContext(ctx context.Context) string {return id}+// WithDaemonContext returns a new context with the daemon workspace ID and daemon ID set.+// This is used by tests to simulate daemon token authentication.+func WithDaemonContext(ctx context.Context, workspaceID, daemonID string) context.Context {+ ctx = context.WithValue(ctx, ctxKeyDaemonWorkspaceID, workspaceID)+ ctx = context.WithValue(ctx, ctxKeyDaemonID, daemonID)+ return ctx+}+// DaemonAuth validates daemon auth tokens (mdt_ prefix) or falls back to// JWT/PAT validation for backward compatibility with daemons that// authenticate via user tokens.