Skip to content

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

Go

fix(agents): thread permission_mode/invocation_targets through the template create path (MUL-4010) (#4897)

Multica Eved90ee9fa3553
diff --git a/server/internal/handler/agent_permission.go b/server/internal/handler/agent_permission.go
index c775e1cd23..a202ac6041 100644
--- a/server/internal/handler/agent_permission.go
+++ b/server/internal/handler/agent_permission.go
@@ -189,11 +189,21 @@ func parsePermissionInput(workspaceID pgtype.UUID, permissionMode *string, targe
// replaceInvocationTargets rewrites an agent's invocation allow-list wholesale:
// clear then re-insert. Called inside create/update after the agent row exists.
func (h *Handler) replaceInvocationTargets(ctx context.Context, agentID pgtype.UUID, createdBy pgtype.UUID, targets []targetSpec) error {
- if err := h.Queries.DeleteAgentInvocationTargets(ctx, agentID); err != nil {
+ return replaceInvocationTargetsWithQueries(ctx, h.Queries, agentID, createdBy, targets)
+}
+
+// replaceInvocationTargetsWithQueries is the tx-friendly variant: callers that
+// hold a `qtx := h.Queries.WithTx(tx)` can pass it here so the invocation
+// target rows are written inside the same transaction as the agent row (the
+// template create path in agent_template.go depends on this — a fresh agent
+// row must not observe a state where the row exists but its targets are
+// missing).
+func replaceInvocationTargetsWithQueries(ctx context.Context, q *db.Queries, agentID pgtype.UUID, createdBy pgtype.UUID, targets []targetSpec) error {
+ if err := q.DeleteAgentInvocationTargets(ctx, agentID); err != nil {
return err
}
for _, t := range targets {
- if err := h.Queries.CreateAgentInvocationTarget(ctx, db.CreateAgentInvocationTargetParams{
+ if err := q.CreateAgentInvocationTarget(ctx, db.CreateAgentInvocationTargetParams{
AgentID: agentID,
TargetType: t.targetType,
TargetID: t.targetID,
diff --git a/server/internal/handler/agent_template.go b/server/internal/handler/agent_template.go
index 5976f31f6f..a57c8372ae 100644
--- a/server/internal/handler/agent_template.go
+++ b/server/internal/handler/agent_template.go
@@ -124,6 +124,17 @@ type CreateAgentFromTemplateRequest struct {
Model string `json:"model,omitempty"`
Visibility string `json:"visibility,omitempty"`
MaxConcurrentTasks int32 `json:"max_concurrent_tasks,omitempty"`
+ // PermissionMode + InvocationTargets are the invocation-permission inputs
+ // (MUL-3963). When permission_mode is present it is authoritative and
+ // Visibility is ignored; when absent, legacy Visibility is mapped through
+ // parsePermissionInput ("workspace" -> public_to + workspace target;
+ // "private" or "" -> private). Persisting these fields keeps template
+ // creates aligned with the manual CreateAgent path — without them the
+ // template row lands as `permission_mode='private'` (the SQL default) and
+ // canInvokeAgent silently locks out every non-owner, even if the caller
+ // asked for a workspace-shared agent.
+ PermissionMode *string `json:"permission_mode,omitempty"`
+ InvocationTargets []AgentInvocationTargetDTO `json:"invocation_targets,omitempty"`
// Optional overrides — let the picker UI customise the template before
// creation without forcing a second round-trip to the detail page.
// When nil/empty, the template's own values are used.
@@ -156,7 +167,8 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
}
var req CreateAgentFromTemplateRequest
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ rawFields, err := decodeJSONBodyWithRawFields(r.Body, &req)
+ if err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
@@ -211,6 +223,20 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
return
}
+ // Resolve invocation permission (MUL-3963) — mirrors CreateAgent so the
+ // two entry points can't drift. permission_mode is authoritative when
+ // present; otherwise legacy visibility is mapped through the same helper
+ // ("workspace" -> public_to + workspace target; "private" -> private).
+ // On create the caller is always the owner, so any submitted targets are
+ // accepted unconditionally.
+ _, hasTargets := rawFields["invocation_targets"]
+ legacyVis := req.Visibility
+ perm, _, permErr := parsePermissionInput(wsUUID, req.PermissionMode, req.InvocationTargets, req.PermissionMode != nil, hasTargets, &legacyVis)
+ if permErr != nil {
+ writeError(w, http.StatusBadRequest, permErr.Error())
+ return
+ }
+
slog.Info("agent-template create: request received",
append(logger.RequestAttrs(r),
"template_slug", tmpl.Slug,
@@ -440,7 +466,8 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
RuntimeMode: runtime.RuntimeMode,
RuntimeConfig: rc,
RuntimeID: runtime.ID,
- Visibility: req.Visibility,
+ Visibility: perm.legacyVisibility(),
+ PermissionMode: perm.mode,
MaxConcurrentTasks: req.MaxConcurrentTasks,
OwnerID: creatorUUID,
CustomEnv: ce,
@@ -491,6 +518,23 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
}
}
+ // Persist the invocation allow-list (MUL-3963) inside the same tx as the
+ // agent row so the agent is never visible to callers in a state where the
+ // row exists but its targets are missing. Without this the freshly created
+ // row would default to `permission_mode=private` + zero targets — meaning
+ // canInvokeAgent silently locks out every non-owner even when the caller
+ // asked for a workspace-shared agent (the manual CreateAgent path already
+ // did this; the template path was diverging until MUL-4010).
+ if err := replaceInvocationTargetsWithQueries(r.Context(), qtx, agent.ID, creatorUUID, perm.targets); err != nil {
+ slog.Error("agent-template create: persist invocation targets failed",
+ append(logger.RequestAttrs(r),
+ "agent_id", uuidToString(agent.ID),
+ "error", err,
+ )...)
+ writeError(w, http.StatusInternalServerError, "failed to persist invocation targets: "+err.Error())
+ return
+ }
+
// Attach user-supplied extra skills (selected in the create dialog
// alongside the template). AddAgentSkill uses ON CONFLICT DO NOTHING,
// so duplicates with template-imported skills are harmless.
@@ -551,6 +595,15 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Request
writeError(w, http.StatusInternalServerError, "failed to load agent skills")
return
}
+ // Reflect the invocation-permission state we just persisted (MUL-4010).
+ // Without this the response would still show empty invocation_targets and
+ // derive Visibility from permission_mode alone — so a client that just
+ // asked for `visibility="workspace"` would round-trip to a legacy
+ // "private" and re-render the wrong access badge.
+ if err := h.enrichAgentResponseWithTargets(r.Context(), &resp, agent.ID); err != nil {
+ slog.Warn("agent-template create: load invocation targets for response failed",
+ append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)
+ }
actorType, actorID := h.resolveActor(r, ownerID, workspaceID)
h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": resp})
diff --git a/server/internal/handler/agent_template_permission_test.go b/server/internal/handler/agent_template_permission_test.go
new file mode 100644
index 0000000000..4f4d100515
--- /dev/null
+++ b/server/internal/handler/agent_template_permission_test.go
@@ -0,0 +1,174 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// TestCreateAgentFromTemplate_LegacyVisibilityMapsToPermission is the
+// MUL-4010 regression: the template create path used to persist
+// permission_mode='private' (the SQL default) regardless of the incoming
+// legacy `visibility="workspace"` value, so an agent that the caller asked
+// to be workspace-shared silently became owner-only in canInvokeAgent.
+//
+// After the fix, parsePermissionInput runs on the template path too:
+// - visibility "workspace" -> permission_mode public_to + workspace target
+// - visibility "private" -> permission_mode private + no targets
+func TestCreateAgentFromTemplate_LegacyVisibilityMapsToPermission(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := handlerTestRuntimeID(t)
+
+ // commit-message ships with zero external skills so this test never
+ // touches the network fetch path. Any zero-skill template would do.
+ const templateSlug = "commit-message"
+ if _, ok := agentTemplates.Get(templateSlug); !ok {
+ t.Fatalf("expected template %q to be loaded", templateSlug)
+ }
+
+ create := func(name, visibility string) CreateAgentFromTemplateResponse {
+ w := httptest.NewRecorder()
+ testHandler.CreateAgentFromTemplate(w, newRequest("POST", "/api/agents/from-template?workspace_id="+testWorkspaceID, map[string]any{
+ "template_slug": templateSlug,
+ "name": name,
+ "runtime_id": runtimeID,
+ "visibility": visibility,
+ }))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("create %q (visibility=%s): expected 201, got %d: %s", name, visibility, w.Code, w.Body.String())
+ }
+ var resp CreateAgentFromTemplateResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.Agent.ID)
+ })
+ return resp
+ }
+
+ ws := create("template-legacy-workspace", "workspace")
+ if ws.Agent.PermissionMode != "public_to" {
+ t.Errorf("workspace-template agent permission_mode = %q, want public_to", ws.Agent.PermissionMode)
+ }
+ if ws.Agent.Visibility != "workspace" {
+ t.Errorf("workspace-template agent derived visibility = %q, want workspace", ws.Agent.Visibility)
+ }
+ foundWorkspaceTarget := false
+ for _, tgt := range ws.Agent.InvocationTargets {
+ if tgt.TargetType == "workspace" {
+ foundWorkspaceTarget = true
+ }
+ }
+ if !foundWorkspaceTarget {
+ t.Errorf("workspace-template agent invocation_targets = %+v, want a workspace target", ws.Agent.InvocationTargets)
+ }
+ // Additional DB-level check: canInvokeAgent's persisted inputs — the row's
+ // permission_mode column AND at least one invocation-target row — must
+ // both be present. A response that reflected the intent but a row that
+ // didn't would still deny non-owner invokes at runtime.
+ var mode string
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT permission_mode FROM agent WHERE id = $1`, ws.Agent.ID).Scan(&mode); err != nil {
+ t.Fatalf("load persisted permission_mode: %v", err)
+ }
+ if mode != "public_to" {
+ t.Errorf("persisted permission_mode = %q, want public_to", mode)
+ }
+ var targetCount int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT COUNT(*) FROM agent_invocation_target WHERE agent_id = $1 AND target_type = 'workspace'`,
+ ws.Agent.ID,
+ ).Scan(&targetCount); err != nil {
+ t.Fatalf("load persisted workspace targets: %v", err)
+ }
+ if targetCount != 1 {
+ t.Errorf("persisted workspace target rows = %d, want 1", targetCount)
+ }
+
+ priv := create("template-legacy-private", "private")
+ if priv.Agent.PermissionMode != "private" {
+ t.Errorf("private-template agent permission_mode = %q, want private", priv.Agent.PermissionMode)
+ }
+ if priv.Agent.Visibility != "private" {
+ t.Errorf("private-template agent derived visibility = %q, want private", priv.Agent.Visibility)
+ }
+ if len(priv.Agent.InvocationTargets) != 0 {
+ t.Errorf("private-template agent invocation_targets = %+v, want none", priv.Agent.InvocationTargets)
+ }
+}
+
+// TestCreateAgentFromTemplate_PublicToWithMemberTarget verifies that when
+// the new-Web-shape (permission_mode + invocation_targets) arrives on the
+// template path, it is honoured — a member allow-list is persisted verbatim
+// instead of being silently dropped and replaced with the SQL default.
+func TestCreateAgentFromTemplate_PublicToWithMemberTarget(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+ runtimeID := handlerTestRuntimeID(t)
+
+ const templateSlug = "commit-message"
+ if _, ok := agentTemplates.Get(templateSlug); !ok {
+ t.Fatalf("expected template %q to be loaded", templateSlug)
+ }
+
+ // Fresh member to grant invocation access to.
+ targetUserID := createPermissionTestMember(t, "[email protected]")
+
+ w := httptest.NewRecorder()
+ testHandler.CreateAgentFromTemplate(w, newRequest("POST", "/api/agents/from-template?workspace_id="+testWorkspaceID, map[string]any{
+ "template_slug": templateSlug,
+ "name": "template-public-to-member",
+ "runtime_id": runtimeID,
+ "permission_mode": "public_to",
+ "invocation_targets": []map[string]any{
+ {"target_type": "member", "target_id": targetUserID},
+ },
+ }))
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp CreateAgentFromTemplateResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, resp.Agent.ID)
+ })
+
+ if resp.Agent.PermissionMode != "public_to" {
+ t.Errorf("permission_mode = %q, want public_to", resp.Agent.PermissionMode)
+ }
+ // public_to limited to a specific member -> derived legacy visibility
+ // collapses to "private" (only workspace-target public_to derives to
+ // "workspace"); the real audience is the member allow-list below.
+ if resp.Agent.Visibility != "private" {
+ t.Errorf("derived legacy visibility = %q, want private (member-only public_to)", resp.Agent.Visibility)
+ }
+ sawMember := false
+ for _, tgt := range resp.Agent.InvocationTargets {
+ if tgt.TargetType == "member" && tgt.TargetID != nil && *tgt.TargetID == targetUserID {
+ sawMember = true
+ }
+ }
+ if !sawMember {
+ t.Errorf("invocation_targets = %+v, want a member target for %s", resp.Agent.InvocationTargets, targetUserID)
+ }
+
+ // DB-level check: the member row is persisted, not just echoed back.
+ var persisted int
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT COUNT(*) FROM agent_invocation_target WHERE agent_id = $1 AND target_type = 'member' AND target_id = $2`,
+ resp.Agent.ID, targetUserID,
+ ).Scan(&persisted); err != nil {
+ t.Fatalf("load persisted member target: %v", err)
+ }
+ if persisted != 1 {
+ t.Errorf("persisted member target rows = %d, want 1", persisted)
+ }
+}