Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agents): remove custom_env from agent resources, add audited env endpoint (MUL-2600) (#3209)
Bohan Jiang13f74e651a57
diff --git a/apps/docs/content/docs/agents-create.mdx b/apps/docs/content/docs/agents-create.mdxindex 2d4a7af5c5..2c2ae35635 100644--- a/apps/docs/content/docs/agents-create.mdx+++ b/apps/docs/content/docs/agents-create.mdx@@ -64,9 +64,9 @@ ANTHROPIC_BASE_URL = https://my-proxy.example.comSystem-critical variables cannot be overridden: `PATH`, `HOME`, `USER`, `SHELL`, `TERM`, `CODEX_HOME`, and any key starting with `MULTICA_*` are silently ignored by the daemon (with a warn log — no error).<Callout type="warning">-**Values in `custom_env` are stored in plaintext in Multica's server database.** Non-creators and non-workspace-admins can't see the values (the API returns `****`), but they're still visible in database backups and DB audits.+**Values in `custom_env` are stored in plaintext in Multica's server database.** Agent list/get responses no longer carry env values at all — only an opaque count. Reading values requires a workspace owner or admin to hit the dedicated, audited `GET /api/agents/{id}/env` endpoint (CLI: `multica agent env get <id>`). Agents running tasks can NOT use their host's owner credentials to reveal env on other agents — the endpoint denies agent-actor sessions.-**Don't put high-value secrets in `custom_env`** (production database passwords, root-level tokens, etc.). Use **dedicated, limited-scope credentials** for agents (read-only API keys, single-scope PATs), and rotate them regularly.+**Don't put high-value secrets in `custom_env`** (production database passwords, root-level tokens, etc.). Use **dedicated, limited-scope credentials** for agents (read-only API keys, single-scope PATs), and rotate them regularly. Database backups and DB audits remain a meaningful exposure surface.</Callout>## Custom CLI arguments (custom_args)@@ -96,7 +96,7 @@ Arguments are passed as-is, not through a shell (no injection risk), but whetherNew agents default to `private`.-**Private does not mean hidden** — every member sees a private agent's name and description in the list, they just can't see sensitive config fields (the values in `custom_env` and MCP config are masked). Full meaning in [Agents → Who can assign an agent](/agents#who-can-assign-an-agent).+**Private does not mean hidden** — every member sees a private agent's name and description in the list, they just can't read sensitive config (env values never appear in agent list/get responses; MCP config is masked for non-owners). Full meaning in [Agents → Who can assign an agent](/agents#who-can-assign-an-agent).## Concurrency limitdiff --git a/apps/docs/content/docs/agents-create.zh.mdx b/apps/docs/content/docs/agents-create.zh.mdxindex 57eb645c7e..25a8e55f7f 100644--- a/apps/docs/content/docs/agents-create.zh.mdx+++ b/apps/docs/content/docs/agents-create.zh.mdx@@ -64,7 +64,7 @@ ANTHROPIC_BASE_URL = https://my-proxy.example.com系统关键变量不能被覆盖:`PATH`、`HOME`、`USER`、`SHELL`、`TERM`、`CODEX_HOME`,以及任何 `MULTICA_*` 开头的 key 都会被守护进程静默忽略(日志里有 warn,不会报错)。<Callout type="warning">-**`custom_env` 的值在 Multica 服务器的数据库里是明文存储的。** 非智能体创建者 / 非 workspace admin 看不到值(API 返回 `****`),但数据库备份、DB 审计里仍然能看到。+**`custom_env` 的值在 Multica 服务器的数据库里是明文存储的。** agent list/get 接口不再返回任何 env 值——只返回键的数量。读取真实值需要 workspace owner / admin 调用专用且会审计的 `GET /api/agents/{id}/env`(CLI: `multica agent env get <id>`)。正在执行任务的智能体即便宿主是 owner,也无法借此读取其它智能体的 env——这个接口拒绝 agent-actor 会话。数据库备份、DB 审计里仍然能看到真实值。**不要把高价值 secret 放进 `custom_env`**(生产数据库密码、root 级 token 等)。给智能体用**独立的、有限权限的凭证**(只读 API key、单 scope 的 PAT),定期轮换。</Callout>@@ -96,7 +96,7 @@ claude --model <model> --max-turns 100 --append-system-prompt "always respond in新建默认 `private`。-**私有不等于隐藏**——列表里所有成员都能看到私有智能体的名字和描述,只是看不到敏感配置字段(`custom_env`、MCP 配置的值被打码)。完整含义见 [智能体 → 谁能把智能体分配出去](/agents#谁能把智能体分配出去)。+**私有不等于隐藏**——列表里所有成员都能看到私有智能体的名字和描述,只是看不到敏感配置(env 值从不会出现在 agent list/get 响应里;MCP 配置对非 owner 会被打码)。完整含义见 [智能体 → 谁能把智能体分配出去](/agents#谁能把智能体分配出去)。## 并发上限diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.tsindex b74b3e7fe4..b6c77cb86b 100644--- a/apps/mobile/data/schemas.ts+++ b/apps/mobile/data/schemas.ts@@ -558,9 +558,13 @@ export const AgentSchema: z.ZodType<Agent> = z.object({Agent["runtime_mode"]>,runtime_config: z.record(z.string(), z.unknown()).default({}),- custom_env: z.record(z.string(), z.string()).default({}),custom_args: z.array(z.string()).default([]),- custom_env_redacted: z.boolean().default(true),+ // MUL-2600: agent resource shape no longer carries custom_env or+ // custom_env_redacted. Mobile keeps only the coarse metadata that+ // mirrors web's expectations. Real env values are reachable via the+ // dedicated /env endpoint and we don't expose env editing on mobile.+ has_custom_env: z.boolean().optional(),+ custom_env_key_count: z.number().optional(),visibility: z.string().catch("workspace") as unknown as z.ZodType<Agent["visibility"]>,diff --git a/apps/web/test/helpers.tsx b/apps/web/test/helpers.tsxindex 2a5d9c0689..2a4cb3c236 100644--- a/apps/web/test/helpers.tsx+++ b/apps/web/test/helpers.tsx@@ -62,9 +62,7 @@ export const mockAgents: Agent[] = [status: "idle",runtime_mode: "cloud",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "workspace",max_concurrent_tasks: 3,model: "",diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.tsindex bb546cfd09..4d41761907 100644--- a/packages/core/agents/derive-presence.test.ts+++ b/packages/core/agents/derive-presence.test.ts@@ -19,9 +19,7 @@ function makeAgent(overrides: Partial<Agent> = {}): Agent {avatar_url: null,runtime_mode: "local",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "workspace",status: "idle",max_concurrent_tasks: 6,diff --git a/packages/core/agents/use-agent-activity.test.ts b/packages/core/agents/use-agent-activity.test.tsindex b50174bc53..02a1cc2d12 100644--- a/packages/core/agents/use-agent-activity.test.ts+++ b/packages/core/agents/use-agent-activity.test.ts@@ -38,9 +38,7 @@ const fullHistoryAgent: Agent = {avatar_url: null,runtime_mode: "cloud",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "workspace",status: "idle",max_concurrent_tasks: 1,diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 1cd6e29718..8924c783cc 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -18,6 +18,8 @@ import type {CreateAgentFromTemplateRequest,CreateAgentFromTemplateResponse,UpdateAgentRequest,+ AgentEnvResponse,+ UpdateAgentEnvRequest,AgentTask,AgentActivityBucket,AgentRunCount,@@ -756,6 +758,31 @@ export class ApiClient {return this.fetch(`/api/agents/${id}/archive`, { method: "POST" });}+ /**+ * Returns the plaintext `custom_env` map for an agent. Owner/admin+ * only; calls from agent-actor sessions get a 403. Every successful+ * call writes an `agent_env_revealed` activity_log row server-side.+ * MUL-2600.+ */+ async getAgentEnv(id: string): Promise<AgentEnvResponse> {+ return this.fetch(`/api/agents/${id}/env`);+ }++ /**+ * Replaces an agent's `custom_env` wholesale. Values equal to+ * `"****"` are preserved server-side (the **** guard) so a partial+ * UI edit doesn't overwrite real secrets with the masked+ * placeholder. Owner/admin only; agent actors get a 403. Every+ * successful call writes an `agent_env_updated` activity_log row.+ * MUL-2600.+ */+ async updateAgentEnv(id: string, data: UpdateAgentEnvRequest): Promise<AgentEnvResponse> {+ return this.fetch(`/api/agents/${id}/env`, {+ method: "PUT",+ body: JSON.stringify(data),+ });+ }+async restoreAgent(id: string): Promise<Agent> {return this.fetch(`/api/agents/${id}/restore`, { method: "POST" });}diff --git a/packages/core/permissions/rules.test.ts b/packages/core/permissions/rules.test.tsindex b23a174c07..c6e8d3c8f9 100644--- a/packages/core/permissions/rules.test.ts+++ b/packages/core/permissions/rules.test.ts@@ -28,9 +28,7 @@ function makeAgent(overrides: Partial<Agent> = {}): Agent {avatar_url: null,runtime_mode: "local",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "workspace",status: "idle",max_concurrent_tasks: 1,diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex c8d636195d..61a7d880d2 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -123,10 +123,24 @@ export interface Agent {avatar_url: string | null;runtime_mode: AgentRuntimeMode;runtime_config: Record<string, unknown>;- custom_env: Record<string, string>;custom_args: string[];- custom_env_redacted: boolean;- custom_env_redacted_reason?: 'policy' | 'role';+ /**+ * Coarse metadata signalling whether the agent has any custom env+ * vars configured, without exposing the keys or values. Reads of+ * the real map go through the dedicated `GET /api/agents/{id}/env`+ * endpoint (owner/admin only, audited). MUL-2600.+ *+ * Optional in the type so older backends (pre-MUL-2600) that omit+ * the field don't crash the renderer; downstream code should treat+ * `undefined` as "unknown — assume no env" rather than "definitely+ * has env".+ */+ has_custom_env?: boolean;+ /**+ * Number of keys in the agent's custom_env map. Always present+ * alongside `has_custom_env`. Treat `undefined` as zero. MUL-2600.+ */+ custom_env_key_count?: number;visibility: AgentVisibility;status: AgentStatus;max_concurrent_tasks: number;@@ -259,7 +273,15 @@ export interface UpdateAgentRequest {avatar_url?: string;runtime_id?: string;runtime_config?: Record<string, unknown>;- custom_env?: Record<string, string>;+ /**+ * NOTE: `custom_env` is intentionally NOT updatable through this+ * request shape. Env edits flow through `client.updateAgentEnv` /+ * `PUT /api/agents/{id}/env` — that path is owner/admin only,+ * denies agent actors, and writes a persistent audit row. The+ * server REJECTS any `PUT /api/agents/{id}` body that includes+ * `custom_env` with a 400; do not put the field in this payload.+ * MUL-2600.+ */custom_args?: string[];visibility?: AgentVisibility;status?: AgentStatus;@@ -276,6 +298,28 @@ export interface UpdateAgentRequest {thinking_level?: string;}+/**+ * Wire shape for the dedicated env-management endpoints+ * (`GET /api/agents/{id}/env` and `PUT /api/agents/{id}/env`). Kept+ * deliberately separate from `Agent` so generic agent reads cannot+ * accidentally surface env values. MUL-2600.+ */+export interface AgentEnvResponse {+ agent_id: string;+ custom_env: Record<string, string>;+}++/**+ * Body for `PUT /api/agents/{id}/env`. Values equal to `"****"` are+ * treated by the server as "preserve the existing value for this key"+ * — a defence-in-depth guard so a UI that round-trips a masked map+ * cannot accidentally clobber real secrets. Submit only the keys+ * touched in the form; omitted keys are removed by the server.+ */+export interface UpdateAgentEnvRequest {+ custom_env: Record<string, string>;+}+// Skills/**diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 53d7eb9d28..5d09cb2d81 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -18,6 +18,8 @@ export type {CreateAgentFromTemplateResponse,CreateAgentFromTemplateFailure,UpdateAgentRequest,+ AgentEnvResponse,+ UpdateAgentEnvRequest,Skill,SkillSummary,AgentSkillSummary,diff --git a/packages/views/agents/components/agent-live-peek-card.test.tsx b/packages/views/agents/components/agent-live-peek-card.test.tsxindex 2472d8f301..3d820f61e7 100644--- a/packages/views/agents/components/agent-live-peek-card.test.tsx+++ b/packages/views/agents/components/agent-live-peek-card.test.tsx@@ -107,9 +107,7 @@ function makeAgent(overrides: Record<string, unknown> = {}) {avatar_url: null,runtime_mode: "local" as const,runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "private" as const,status: "idle" as const,max_concurrent_tasks: 1,diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsxindex 3b65a25ab4..611a27b24e 100644--- a/packages/views/agents/components/agent-overview-pane.tsx+++ b/packages/views/agents/components/agent-overview-pane.tsx@@ -171,8 +171,6 @@ export function AgentOverviewPane({<TabContent><EnvTabagent={agent}- readOnly={agent.custom_env_redacted}- onSave={(updates) => onUpdate(agent.id, updates)}onDirtyChange={setActiveDirty}/></TabContent>diff --git a/packages/views/agents/components/create-agent-dialog.test.tsx b/packages/views/agents/components/create-agent-dialog.test.tsxindex 1b6f68d25f..4117049063 100644--- a/packages/views/agents/components/create-agent-dialog.test.tsx+++ b/packages/views/agents/components/create-agent-dialog.test.tsx@@ -105,9 +105,7 @@ function makeTemplate(runtimeId: string): Agent {avatar_url: null,runtime_mode: "local",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "private",status: "idle",max_concurrent_tasks: 1,diff --git a/packages/views/agents/components/create-agent-dialog.tsx b/packages/views/agents/components/create-agent-dialog.tsxindex 9a15f880d1..0b636993c4 100644--- a/packages/views/agents/components/create-agent-dialog.tsx+++ b/packages/views/agents/components/create-agent-dialog.tsx@@ -165,17 +165,15 @@ export function CreateAgentDialog({};if (template) {// Duplicate path: forward the hidden config fields the source- // agent had so the clone is functional out of the box (env / args- // / concurrency). Skills now flow through the dialog form, so we- // don't blindly carry template.skills here anymore — the form's- // selectedSkillIds is the source of truth.+ // agent had so the clone is functional out of the box (args /+ // concurrency). Skills flow through the dialog form. As of+ // MUL-2600 the agent resource shape no longer carries+ // custom_env values, so duplication cannot copy env at all —+ // the user has to re-set env on the clone via the env tab+ // (which now goes through the audited `/env` endpoint). The+ // dialog's create call still accepts custom_env at create+ // time, but the source values aren't available here.if (template.custom_args.length) data.custom_args = template.custom_args;- if (- !template.custom_env_redacted &&- Object.keys(template.custom_env).length > 0- ) {- data.custom_env = template.custom_env;- }if (template.max_concurrent_tasks) {data.max_concurrent_tasks = template.max_concurrent_tasks;}diff --git a/packages/views/agents/components/tabs/env-tab.tsx b/packages/views/agents/components/tabs/env-tab.tsxindex 54820f5b0a..7639332143 100644--- a/packages/views/agents/components/tabs/env-tab.tsx+++ b/packages/views/agents/components/tabs/env-tab.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useCallback, useEffect, useState } from "react";import {Eye,EyeOff,@@ -10,12 +10,19 @@ import {Save,Trash2,} from "lucide-react";+import { api } from "@multica/core/api";import type { Agent } from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";import { Input } from "@multica/ui/components/ui/input";import { toast } from "sonner";import { useT } from "../../../i18n";+// Env values never reach this component until the user clicks+// "Reveal & edit" — the agent resource feed no longer carries+// custom_env at all after MUL-2600. Until then we display only the+// configured-key count from `agent.custom_env_key_count`, which is+// safe because it's not the values themselves.+let nextEnvId = 0;interface EnvEntry {@@ -47,39 +54,68 @@ function entriesToEnvMap(entries: EnvEntry[]): Record<string, string> {export function EnvTab({agent,- readOnly = false,- onSave,onDirtyChange,+ onSaved,}: {agent: Agent;- readOnly?: boolean;- onSave: (updates: Partial<Agent>) => Promise<void>;onDirtyChange?: (dirty: boolean) => void;+ // Notifier so the parent page can refresh its agent cache after a+ // successful PUT — the parent owns the `Agent` object the rest of+ // the page reads (name, has_custom_env, etc.). Optional so call+ // sites without invalidation logic stay simple.+ onSaved?: () => void;}) {const { t } = useT("agents");- const [envEntries, setEnvEntries] = useState<EnvEntry[]>(- envMapToEntries(agent.custom_env ?? {}),- );++ // revealed === null means "haven't fetched yet"; revealed === [] is+ // a legitimate empty map after a successful reveal. We do NOT+ // pre-populate from `agent` here because the agent resource shape+ // no longer carries values — only the dedicated `/env` endpoint+ // does, and that endpoint writes an audit row per call so we never+ // fetch implicitly on mount.+ const [revealed, setRevealed] = useState<EnvEntry[] | null>(null);+ const [originalMap, setOriginalMap] = useState<Record<string, string>>({});+ const [revealing, setRevealing] = useState(false);const [saving, setSaving] = useState(false);- const currentEnvMap = entriesToEnvMap(envEntries);- const originalEnvMap = agent.custom_env ?? {};+ const keyCount = agent.custom_env_key_count ?? 0;++ const currentEnvMap = revealed ? entriesToEnvMap(revealed) : originalMap;const dirty =- JSON.stringify(currentEnvMap) !== JSON.stringify(originalEnvMap);+ revealed !== null &&+ JSON.stringify(currentEnvMap) !== JSON.stringify(originalMap);useEffect(() => {onDirtyChange?.(dirty);}, [dirty, onDirtyChange]);+ const handleReveal = useCallback(async () => {+ setRevealing(true);+ try {+ const resp = await api.getAgentEnv(agent.id);+ const env = resp.custom_env ?? {};+ setOriginalMap(env);+ setRevealed(envMapToEntries(env));+ } catch (err) {+ toast.error(+ err instanceof Error && err.message+ ? err.message+ : t(($) => $.tab_body.env.reveal_failed_toast),+ );+ } finally {+ setRevealing(false);+ }+ }, [agent.id, t]);+const addEnvEntry = () => {- setEnvEntries([- ...envEntries,+ setRevealed((prev) => [+ ...(prev ?? []),{ id: nextEnvId++, key: "", value: "", visible: true },]);};const removeEnvEntry = (index: number) => {- setEnvEntries(envEntries.filter((_, i) => i !== index));+ setRevealed((prev) => (prev ?? []).filter((_, i) => i !== index));};const updateEnvEntry = (@@ -87,23 +123,24 @@ export function EnvTab({field: "key" | "value",val: string,) => {- setEnvEntries(- envEntries.map((entry, i) =>+ setRevealed((prev) =>+ (prev ?? []).map((entry, i) =>i === index ? { ...entry, [field]: val } : entry,),);};const toggleEnvVisibility = (index: number) => {- setEnvEntries(- envEntries.map((entry, i) =>+ setRevealed((prev) =>+ (prev ?? []).map((entry, i) =>i === index ? { ...entry, visible: !entry.visible } : entry,),);};const handleSave = async () => {- const keys = envEntries.filter((e) => e.key.trim()).map((e) => e.key.trim());+ if (revealed === null) return;+ const keys = revealed.filter((e) => e.key.trim()).map((e) => e.key.trim());const uniqueKeys = new Set(keys);if (uniqueKeys.size < keys.length) {toast.error(t(($) => $.tab_body.env.duplicate_keys_toast));@@ -112,8 +149,14 @@ export function EnvTab({setSaving(true);try {- await onSave({ custom_env: currentEnvMap });+ const resp = await api.updateAgentEnv(agent.id, {+ custom_env: currentEnvMap,+ });+ const env = resp.custom_env ?? {};+ setOriginalMap(env);+ setRevealed(envMapToEntries(env));toast.success(t(($) => $.tab_body.env.saved_toast));+ onSaved?.();} catch (err) {toast.error(err instanceof Error && err.message@@ -125,42 +168,49 @@ export function EnvTab({}};- if (readOnly) {+ // Pre-reveal state: show count + Reveal button. We never auto-fetch+ // on mount so a member just navigating between tabs doesn't trigger+ // an audit-log entry; the reveal must be intentional.+ if (revealed === null) {return (<div className="space-y-4">- <p className="text-xs text-muted-foreground">- {t(($) => $.tab_body.env.intro_readonly)}- </p>- {envEntries.length > 0 ? (- <div className="space-y-2">- {envEntries.map((entry) => (- <div key={entry.id} className="flex items-center gap-2">- <Input- value={entry.key}- readOnly- className="w-[40%] bg-muted font-mono text-xs"- />- <div className="relative flex-1">- <Input- type="password"- value="****"- readOnly- className="bg-muted pr-8 font-mono text-xs"- />- <Lock className="absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />- </div>- </div>- ))}+ <div className="flex items-start justify-between gap-3">+ <div className="space-y-1">+ <p className="flex items-center gap-2 text-sm font-medium">+ <Lock className="h-3.5 w-3.5 text-muted-foreground" />+ {keyCount > 0+ ? t(($) => $.tab_body.env.not_revealed_title, {+ count: keyCount,+ })+ : t(($) => $.tab_body.env.not_revealed_empty)}+ </p>+ <p className="text-xs text-muted-foreground">+ {t(($) => $.tab_body.env.not_revealed_hint)}+ </p></div>- ) : (- <p className="text-xs italic text-muted-foreground">- {t(($) => $.tab_body.env.empty_readonly)}- </p>- )}+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={revealing}+ onClick={handleReveal}+ className="shrink-0"+ >+ {revealing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Eye className="h-3.5 w-3.5" />+ )}+ {revealing+ ? t(($) => $.tab_body.env.revealing)+ : t(($) => $.tab_body.env.reveal_action)}+ </Button>+ </div></div>);}+ // Editable state — only entered after a successful reveal.return (<div className="space-y-4"><div className="flex items-start justify-between gap-3">@@ -187,9 +237,9 @@ export function EnvTab({</Button></div>- {envEntries.length > 0 && (+ {revealed.length > 0 ? (<div className="space-y-2">- {envEntries.map((entry, index) => (+ {revealed.map((entry, index) => (<div key={entry.id} className="flex items-center gap-2"><Inputvalue={entry.key}@@ -232,6 +282,10 @@ export function EnvTab({</div>))}</div>+ ) : (+ <p className="text-xs italic text-muted-foreground">+ {t(($) => $.tab_body.env.empty_editable)}+ </p>)}<div className="flex items-center justify-end gap-3">diff --git a/packages/views/agents/components/tabs/skills-tab.test.tsx b/packages/views/agents/components/tabs/skills-tab.test.tsxindex 7874b2062b..7e3eda8997 100644--- a/packages/views/agents/components/tabs/skills-tab.test.tsx+++ b/packages/views/agents/components/tabs/skills-tab.test.tsx@@ -42,9 +42,7 @@ const agent: Agent = {avatar_url: null,runtime_mode: "local",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "workspace",status: "idle",max_concurrent_tasks: 1,diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsxindex ec0b6065a5..a7e0af1f12 100644--- a/packages/views/issues/components/issues-page.test.tsx+++ b/packages/views/issues/components/issues-page.test.tsx@@ -531,7 +531,10 @@ describe("IssuesPage (shared)", () => {renderWithQuery(<IssuesPage />);- await screen.findByText("Test User");+ // "Test User" renders both as the assignee group header and on the+ // assignee chip of each card grouped under that header, so a unique+ // match is not guaranteed.+ await screen.findAllByText("Test User");expect(screen.getAllByText("Agent One").length).toBeGreaterThanOrEqual(1);expect(screen.getAllByText("Squad One").length).toBeGreaterThanOrEqual(1);expect(screen.getByText("No assignee")).toBeInTheDocument();diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex a307771438..8587b3edbb 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -263,7 +263,7 @@"placeholder": "Define this agent's role, expertise, and working style.\n\n# Example\nYou are a frontend engineer specializing in React and TypeScript.\n\n## Working Style\n- Write small, focused PRs — one commit per logical change\n- Prefer composition over inheritance\n- Always add unit tests for new components\n\n## Constraints\n- Do not modify shared/ types without explicit approval\n- Follow the existing component patterns in features/"},"env": {- "intro_readonly": "Injected into the agent process at launch. Values are hidden — only the agent owner or workspace admin can view and edit them.",+ "intro_readonly": "Injected into the agent process at launch. Only workspace owners and admins can read or edit values; every reveal and edit is recorded in the workspace audit log.","empty_readonly": "No environment variables configured.","intro_prefix": "Injected into the agent process at launch (e.g. ","intro_separator": ", ",@@ -275,7 +275,15 @@"remove_aria": "Remove variable","duplicate_keys_toast": "Duplicate environment variable keys","saved_toast": "Environment variables saved",- "save_failed_toast": "Failed to save environment variables"+ "save_failed_toast": "Failed to save environment variables",+ "not_revealed_title_one": "{{count}} variable configured",+ "not_revealed_title_other": "{{count}} variables configured",+ "not_revealed_empty": "No environment variables configured.",+ "not_revealed_hint": "Values stay masked until you reveal them. Every reveal and edit is recorded in the workspace audit log.",+ "reveal_action": "Reveal & edit",+ "revealing": "Revealing…",+ "reveal_failed_toast": "Failed to load env values",+ "empty_editable": "No environment variables configured. Add one to inject it into the agent at launch."},"custom_args": {"intro": "Additional CLI arguments appended to the agent command at launch. Multi-token flags can share one row — they'll be split on whitespace before being passed to the CLI.",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex fc643283c2..4b94e5a059 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -258,7 +258,7 @@"placeholder": "定义这个智能体的角色、专长和工作风格。\n\n# 示例\n你是一名专注 React 和 TypeScript 的前端工程师。\n\n## 工作风格\n- 写小而聚焦的 PR —— 每个逻辑变更一个 commit\n- 优先组合而不是继承\n- 新组件总是配单元测试\n\n## 约束\n- 未经明确批准不要修改 shared/ 下的 type\n- 遵循 features/ 中现有的组件模式"},"env": {- "intro_readonly": "在智能体进程启动时注入。值已隐藏 —— 只有智能体所有者或工作区管理员可以查看和编辑。",+ "intro_readonly": "在智能体进程启动时注入。只有工作区所有者 / 管理员可以查看或编辑值;每次解锁和编辑都会写入工作区审计日志。","empty_readonly": "尚未配置环境变量。","intro_prefix": "在智能体进程启动时注入(例如 ","intro_separator": "、",@@ -270,7 +270,14 @@"remove_aria": "移除变量","duplicate_keys_toast": "环境变量 key 重复","saved_toast": "已保存环境变量",- "save_failed_toast": "保存环境变量失败"+ "save_failed_toast": "保存环境变量失败",+ "not_revealed_title_other": "已配置 {{count}} 个变量",+ "not_revealed_empty": "尚未配置环境变量。",+ "not_revealed_hint": "在解锁前所有值保持隐藏。每次解锁与编辑都会写入工作区审计日志。",+ "reveal_action": "解锁并编辑",+ "revealing": "正在解锁…",+ "reveal_failed_toast": "加载环境变量值失败",+ "empty_editable": "尚未配置环境变量。新增一条即可在智能体启动时注入。"},"custom_args": {"intro": "在智能体命令启动时追加的额外 CLI 参数。多 token 的参数可以共用一行 —— 在传给 CLI 前会按空白拆分。",diff --git a/packages/views/modals/create-squad.test.tsx b/packages/views/modals/create-squad.test.tsxindex a0eacb0e0d..233b7b5942 100644--- a/packages/views/modals/create-squad.test.tsx+++ b/packages/views/modals/create-squad.test.tsx@@ -202,9 +202,7 @@ function makeAgent(overrides: Partial<Agent> & { id: string; name: string; owneravatar_url: null,runtime_mode: "local",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "private",status: "idle",max_concurrent_tasks: 1,diff --git a/packages/views/runtimes/components/runtime-list.test.ts b/packages/views/runtimes/components/runtime-list.test.tsindex 546e396483..5dd2344290 100644--- a/packages/views/runtimes/components/runtime-list.test.ts+++ b/packages/views/runtimes/components/runtime-list.test.ts@@ -13,9 +13,7 @@ function makeAgent(overrides: Partial<Agent> = {}): Agent {avatar_url: null,runtime_mode: "local",runtime_config: {},- custom_env: {},custom_args: [],- custom_env_redacted: false,visibility: "private",status: "idle",max_concurrent_tasks: 1,diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 56a1371fd8..3eb9c5559d 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -83,6 +83,31 @@ var agentSkillsCmd = &cobra.Command{Short: "Manage agent skill assignments",}+// Agent env subcommands. Live behind a dedicated `agent env` group because+// they're the ONLY post-creation path for reading or writing+// custom_env values — `multica agent list / get / update` no longer+// expose env on the wire. Each call hits the audited+// `/api/agents/{id}/env` endpoint. See MUL-2600.++var agentEnvCmd = &cobra.Command{+ Use: "env",+ Short: "Read and update an agent's custom environment variables (audited)",+}++var agentEnvGetCmd = &cobra.Command{+ Use: "get <agent-id>",+ Short: "Print an agent's custom_env as a JSON map (workspace owner/admin only; every call is recorded)",+ Args: exactArgs(1),+ RunE: runAgentEnvGet,+}++var agentEnvSetCmd = &cobra.Command{+ Use: "set <agent-id>",+ Short: "Replace an agent's custom_env (workspace owner/admin only; values equal to **** preserve the existing entry)",+ Args: exactArgs(1),+ RunE: runAgentEnvSet,+}+var agentSkillsListCmd = &cobra.Command{Use: "list <agent-id>",Short: "List skills assigned to an agent",@@ -107,10 +132,14 @@ func init() {agentCmd.AddCommand(agentTasksCmd)agentCmd.AddCommand(agentAvatarCmd)agentCmd.AddCommand(agentSkillsCmd)+ agentCmd.AddCommand(agentEnvCmd)agentSkillsCmd.AddCommand(agentSkillsListCmd)agentSkillsCmd.AddCommand(agentSkillsSetCmd)+ agentEnvCmd.AddCommand(agentEnvGetCmd)+ agentEnvCmd.AddCommand(agentEnvSetCmd)+// agent listagentListCmd.Flags().String("output", "table", "Output format: table or json")agentListCmd.Flags().Bool("include-archived", false, "Include archived agents")@@ -147,9 +176,9 @@ func init() {agentUpdateCmd.Flags().String("runtime-config", "", "New runtime config as JSON string")agentUpdateCmd.Flags().String("model", "", "New model identifier. Pass an empty string to clear and fall back to the runtime default.")agentUpdateCmd.Flags().String("custom-args", "", "New custom CLI arguments as JSON array. For model selection prefer --model; some providers (codex app-server, openclaw) reject --model in custom_args.")- agentUpdateCmd.Flags().String("custom-env", "", "New custom environment variables as JSON object, e.g. '{\"KEY\":\"value\"}'. Treated as secret material — never logged by the CLI, but values passed on the command line are visible to shell history and 'ps'; prefer --custom-env-stdin or --custom-env-file for real secrets. Pass '{}' to clear the map; omit the flag to leave it unchanged.")- agentUpdateCmd.Flags().Bool("custom-env-stdin", false, "Read the new --custom-env JSON object from stdin. Keeps secrets out of shell history and 'ps'. Mutually exclusive with --custom-env and --custom-env-file.")- agentUpdateCmd.Flags().String("custom-env-file", "", "Read the new --custom-env JSON object from a file path (suggested mode: 0600). Mutually exclusive with --custom-env and --custom-env-stdin.")+ // custom_env is intentionally NOT part of `agent update`. Use+ // `multica agent env set <id>` — that path is owner/admin-only,+ // denies agent actors, and writes a persisted audit trail.agentUpdateCmd.Flags().String("visibility", "", "New visibility: private or workspace")agentUpdateCmd.Flags().String("status", "", "New status")agentUpdateCmd.Flags().Int32("max-concurrent-tasks", 0, "New max concurrent tasks")@@ -174,6 +203,17 @@ func init() {// agent skills setagentSkillsSetCmd.Flags().StringSlice("skill-ids", nil, "Skill IDs to assign (comma-separated)")agentSkillsSetCmd.Flags().String("output", "json", "Output format: table or json")++ // agent env get+ agentEnvGetCmd.Flags().String("output", "json", "Output format: json or table")++ // agent env set. Same three secret-safe input channels as `agent+ // create` so scripts can keep secrets out of shell history. Mutual+ // exclusion + empty-input handling is enforced by resolveCustomEnv.+ agentEnvSetCmd.Flags().String("custom-env", "", "Replacement custom_env as a JSON object, e.g. '{\"KEY\":\"value\"}'. Values equal to '****' preserve the existing entry. Treated as secret material — values passed on the command line are visible to shell history and 'ps'; prefer --custom-env-stdin or --custom-env-file for real secrets. Pass '{}' to clear all keys.")+ agentEnvSetCmd.Flags().Bool("custom-env-stdin", false, "Read the replacement custom_env JSON object from stdin. Keeps secrets out of shell history and 'ps'. Mutually exclusive with --custom-env and --custom-env-file.")+ agentEnvSetCmd.Flags().String("custom-env-file", "", "Read the replacement custom_env JSON object from a file path (suggested mode: 0600). Mutually exclusive with --custom-env and --custom-env-stdin.")+ agentEnvSetCmd.Flags().String("output", "json", "Output format: json or table")}// resolveProfile returns the --profile flag value (empty string means default profile).@@ -526,11 +566,6 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {}body["custom_args"] = ca}- if ce, ok, err := resolveCustomEnv(cmd); err != nil {- return err- } else if ok {- body["custom_env"] = ce- }if cmd.Flags().Changed("model") {v, _ := cmd.Flags().GetString("model")body["model"] = v@@ -549,7 +584,7 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {}if len(body) == 0 {- return fmt.Errorf("no fields to update; use --name, --description, --instructions, --runtime-id, --runtime-config, --model, --custom-args, --custom-env (or --custom-env-stdin, --custom-env-file), --visibility, --status, or --max-concurrent-tasks")+ return fmt.Errorf("no fields to update; use --name, --description, --instructions, --runtime-id, --runtime-config, --model, --custom-args, --visibility, --status, or --max-concurrent-tasks (env vars now live behind `multica agent env set <id>`)")}ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)@@ -806,6 +841,83 @@ func runAgentSkillsSet(cmd *cobra.Command, args []string) error {return nil}+// ---------------------------------------------------------------------------+// Agent env subcommands+// ---------------------------------------------------------------------------++// runAgentEnvGet fetches the plaintext custom_env for a single agent+// via the audited `/env` endpoint. The CLI prints raw JSON in JSON+// mode and a key/value table otherwise; we never truncate or mask+// values here — the security gate is on the server, not the printer.+func runAgentEnvGet(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ var resp map[string]any+ if err := client.GetJSON(ctx, "/api/agents/"+args[0]+"/env", &resp); err != nil {+ return fmt.Errorf("get agent env: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, resp)+ }++ headers := []string{"KEY", "VALUE"}+ env, _ := resp["custom_env"].(map[string]any)+ rows := make([][]string, 0, len(env))+ for k, v := range env {+ rows = append(rows, []string{k, fmt.Sprintf("%v", v)})+ }+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+}++// runAgentEnvSet replaces an agent's custom_env wholesale via the+// audited `/env` endpoint. The three secret-safe input channels+// (--custom-env, --custom-env-stdin, --custom-env-file) are required+// — at least one must be supplied — and the server treats any value+// equal to "****" as "preserve the existing entry" (see the **** guard+// in the handler).+func runAgentEnvSet(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ce, ok, err := resolveCustomEnv(cmd)+ if err != nil {+ return err+ }+ if !ok {+ return fmt.Errorf("specify the new env via --custom-env, --custom-env-stdin, or --custom-env-file (pass '{}' to clear)")+ }++ body := map[string]any{"custom_env": ce}++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ var result map[string]any+ if err := client.PutJSON(ctx, "/api/agents/"+args[0]+"/env", body, &result); err != nil {+ return fmt.Errorf("update agent env: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "json" {+ return cli.PrintJSON(os.Stdout, result)+ }++ env, _ := result["custom_env"].(map[string]any)+ fmt.Printf("Env updated for agent %s (%d keys)\n", args[0], len(env))+ return nil+}+// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.goindex f92c00c484..3f14c204fd 100644--- a/server/cmd/multica/cmd_agent_test.go+++ b/server/cmd/multica/cmd_agent_test.go@@ -17,12 +17,15 @@ import ("github.com/multica-ai/multica/server/internal/cli")-// freshAgentUpdateCmd returns a standalone cobra.Command with the three-// --custom-env* flags registered identically to agentUpdateCmd, so tests-// can mutate flag state without leaking across subtests (the package-level-// agentUpdateCmd has no Reset).-func freshAgentUpdateCmd() *cobra.Command {- c := &cobra.Command{Use: "update"}+// freshAgentEnvSetCmd returns a standalone cobra.Command with the three+// --custom-env* flags registered identically to agentEnvSetCmd, so+// resolveCustomEnv-shaped tests can mutate flag state without leaking+// across subtests. After MUL-2600 the same three flags are registered+// on `agent create` and `agent env set` (NOT on `agent update`), but+// the parser they drive is shared, so a single fresh-command helper+// covers both call sites.+func freshAgentEnvSetCmd() *cobra.Command {+ c := &cobra.Command{Use: "set"}c.Flags().String("custom-env", "", "")c.Flags().Bool("custom-env-stdin", false, "")c.Flags().String("custom-env-file", "", "")@@ -105,10 +108,10 @@ func TestResolveWorkspaceID_AgentContextSkipsConfig(t *testing.T) {})}-// TestParseCustomEnv covers the --custom-env flag parser used by both-// `agent create` and `agent update`. The flag accepts a JSON object of-// string keys and values; the only clear signal is the explicit "{}"-// (server treats a non-nil empty map on update as a clear). Empty or+// TestParseCustomEnv covers the --custom-env flag parser used by+// `agent create` and `agent env set`. The flag accepts a JSON object+// of string keys and values; the only clear signal is the explicit+// "{}" (server treats a non-nil empty map as a clear). Empty or// whitespace-only input must error — that path nearly always means an// upstream failure rather than a deliberate clear, especially via the// stdin/file channels.@@ -186,12 +189,12 @@ func TestParseCustomEnv(t *testing.T) {}}-// TestAgentUpdateNoFieldsErrorMentionsAllCustomEnvFlags actually invokes-// runAgentUpdate with no flags set and asserts the resulting "no fields"-// error mentions all three --custom-env channels by name. This guards-// against the discoverability regression we'd see if a future edit-// dropped one of the flag names from the hint.-func TestAgentUpdateNoFieldsErrorMentionsAllCustomEnvFlags(t *testing.T) {+// TestAgentUpdateNoFieldsErrorPointsAtEnvCommand invokes runAgentUpdate+// with no flags set and asserts the resulting "no fields" error+// directs the user toward the new env subcommand. After MUL-2600 the+// --custom-env* flags are gone from `agent update`; the hint must+// surface their replacement so users discover the new audited path.+func TestAgentUpdateNoFieldsErrorPointsAtEnvCommand(t *testing.T) {t.Setenv("HOME", t.TempDir())t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")t.Setenv("MULTICA_WORKSPACE_ID", "test-ws")@@ -199,10 +202,6 @@ func TestAgentUpdateNoFieldsErrorMentionsAllCustomEnvFlags(t *testing.T) {t.Setenv("MULTICA_AGENT_ID", "")t.Setenv("MULTICA_TASK_ID", "")- // Build a fresh command with the same flag surface as agentUpdateCmd- // but without the package-level state, so cmd.Flags().Changed(...)- // returns false for every field and runAgentUpdate falls into the- // "no fields to update" branch.cmd := &cobra.Command{Use: "update"}cmd.Flags().String("name", "", "")cmd.Flags().String("description", "", "")@@ -211,9 +210,6 @@ func TestAgentUpdateNoFieldsErrorMentionsAllCustomEnvFlags(t *testing.T) {cmd.Flags().String("runtime-config", "", "")cmd.Flags().String("model", "", "")cmd.Flags().String("custom-args", "", "")- cmd.Flags().String("custom-env", "", "")- cmd.Flags().Bool("custom-env-stdin", false, "")- cmd.Flags().String("custom-env-file", "", "")cmd.Flags().String("visibility", "", "")cmd.Flags().String("status", "", "")cmd.Flags().Int32("max-concurrent-tasks", 0, "")@@ -225,11 +221,19 @@ func TestAgentUpdateNoFieldsErrorMentionsAllCustomEnvFlags(t *testing.T) {t.Fatal("runAgentUpdate with no flags: expected 'no fields' error, got nil")}msg := err.Error()- // "--custom-env (" matches the bare flag specifically, not its -stdin /- // -file siblings, so we can prove all three names are present.- for _, want := range []string{"--custom-env (", "--custom-env-stdin", "--custom-env-file"} {- if !strings.Contains(msg, want) {- t.Fatalf("no-fields error must mention %q; got: %q", want, msg)+ if !strings.Contains(msg, "multica agent env set") {+ t.Fatalf("no-fields error must direct users to `multica agent env set`; got: %q", msg)+ }+}++// TestAgentUpdateDoesNotExposeCustomEnvFlags is the inverse guarantee+// for the above test: if someone re-adds the --custom-env* flags to+// `agent update`, this fails loudly. The /env path is the only+// audited surface and we don't want a silent regression.+func TestAgentUpdateDoesNotExposeCustomEnvFlags(t *testing.T) {+ for _, flag := range []string{"custom-env", "custom-env-stdin", "custom-env-file"} {+ if agentUpdateCmd.Flag(flag) != nil {+ t.Errorf("agent update must NOT expose --%s after MUL-2600; use `multica agent env set` instead", flag)}}}@@ -274,18 +278,19 @@ func TestParseCustomArgsErrorSanitization(t *testing.T) {}}-// TestAgentCreateAndUpdateExposeSecretSafeFlags guarantees the+// TestAgentCreateAndEnvSetExposeSecretSafeFlags guarantees the// --custom-env-stdin and --custom-env-file alternatives stay wired-// up on both commands. They exist specifically so callers can keep+// up on both commands that accept env input (`agent create` and the+// new `agent env set`). They exist specifically so callers can keep// secret material out of shell history / 'ps'; regressing either// surface reopens the foot-gun.-func TestAgentCreateAndUpdateExposeSecretSafeFlags(t *testing.T) {+func TestAgentCreateAndEnvSetExposeSecretSafeFlags(t *testing.T) {for _, flag := range []string{"custom-env-stdin", "custom-env-file"} {if agentCreateCmd.Flag(flag) == nil {t.Fatalf("agent create must expose --%s", flag)}- if agentUpdateCmd.Flag(flag) == nil {- t.Fatalf("agent update must expose --%s", flag)+ if agentEnvSetCmd.Flag(flag) == nil {+ t.Fatalf("agent env set must expose --%s", flag)}}// The --custom-env help text must warn users that argv is visible@@ -295,7 +300,7 @@ func TestAgentCreateAndUpdateExposeSecretSafeFlags(t *testing.T) {usage string}{{"agent create", agentCreateCmd.Flag("custom-env").Usage},- {"agent update", agentUpdateCmd.Flag("custom-env").Usage},+ {"agent env set", agentEnvSetCmd.Flag("custom-env").Usage},} {low := strings.ToLower(c.usage)if !strings.Contains(low, "shell history") || !strings.Contains(low, "'ps'") {@@ -308,7 +313,7 @@ func TestAgentCreateAndUpdateExposeSecretSafeFlags(t *testing.T) {// flag, stdin, file, mutual exclusion, and the "not supplied" path.func TestResolveCustomEnv(t *testing.T) {t.Run("not supplied", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()got, ok, err := resolveCustomEnv(cmd)if err != nil || ok || got != nil {t.Fatalf("unset flags: got=%v ok=%v err=%v", got, ok, err)@@ -316,7 +321,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("inline flag", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()if err := cmd.Flags().Set("custom-env", `{"A":"1"}`); err != nil {t.Fatal(err)}@@ -330,7 +335,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("stdin", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()if err := cmd.Flags().Set("custom-env-stdin", "true"); err != nil {t.Fatal(err)}@@ -350,7 +355,7 @@ func TestResolveCustomEnv(t *testing.T) {if err := os.WriteFile(path, []byte(`{"C":"3"}`), 0o600); err != nil {t.Fatal(err)}- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()if err := cmd.Flags().Set("custom-env-file", path); err != nil {t.Fatal(err)}@@ -364,7 +369,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("mutually exclusive: inline + stdin", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env", `{"A":"1"}`)_ = cmd.Flags().Set("custom-env-stdin", "true")_, _, err := resolveCustomEnv(cmd)@@ -379,7 +384,7 @@ func TestResolveCustomEnv(t *testing.T) {if err := os.WriteFile(path, []byte(`{}`), 0o600); err != nil {t.Fatal(err)}- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env", `{}`)_ = cmd.Flags().Set("custom-env-file", path)_, _, err := resolveCustomEnv(cmd)@@ -394,7 +399,7 @@ func TestResolveCustomEnv(t *testing.T) {if err := os.WriteFile(path, []byte(`{}`), 0o600); err != nil {t.Fatal(err)}- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-stdin", "true")_ = cmd.Flags().Set("custom-env-file", path)_, _, err := resolveCustomEnv(cmd)@@ -404,7 +409,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("file: missing path surfaces filesystem error", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-file", filepath.Join(t.TempDir(), "does-not-exist.json"))_, _, err := resolveCustomEnv(cmd)if err == nil || !strings.Contains(err.Error(), "--custom-env-file") {@@ -417,7 +422,7 @@ func TestResolveCustomEnv(t *testing.T) {// The resolver must reject it with a channel-specific error so the// secret map is never silently wiped.t.Run("stdin: empty input errors", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-stdin", "true")cmd.SetIn(bytes.NewBufferString(""))_, _, err := resolveCustomEnv(cmd)@@ -427,7 +432,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("stdin: whitespace-only input errors", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-stdin", "true")cmd.SetIn(bytes.NewBufferString(" \n\t "))_, _, err := resolveCustomEnv(cmd)@@ -437,7 +442,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("stdin: explicit {} still clears", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-stdin", "true")cmd.SetIn(bytes.NewBufferString("{}"))got, ok, err := resolveCustomEnv(cmd)@@ -455,7 +460,7 @@ func TestResolveCustomEnv(t *testing.T) {if err := os.WriteFile(path, nil, 0o600); err != nil {t.Fatal(err)}- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-file", path)_, _, err := resolveCustomEnv(cmd)if err == nil || !strings.Contains(err.Error(), "--custom-env-file") || !strings.Contains(err.Error(), "{}") {@@ -464,7 +469,7 @@ func TestResolveCustomEnv(t *testing.T) {})t.Run("file: empty path errors instead of being silently swallowed", func(t *testing.T) {- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()// Mark the flag as Changed with an empty value — previously this// was swallowed by the && filePath != "" guard._ = cmd.Flags().Set("custom-env-file", "")@@ -483,7 +488,7 @@ func TestResolveCustomEnv(t *testing.T) {if err := os.WriteFile(path, []byte("{}"), 0o600); err != nil {t.Fatal(err)}- cmd := freshAgentUpdateCmd()+ cmd := freshAgentEnvSetCmd()_ = cmd.Flags().Set("custom-env-file", path)got, ok, err := resolveCustomEnv(cmd)if err != nil || !ok {@@ -752,7 +757,6 @@ func TestAgentAvatarUpdateFailure(t *testing.T) {}}-// TestAgentAvatarMissingFileFlag rejects when --file is not provided.func TestAgentAvatarMissingFileFlag(t *testing.T) {t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")@@ -889,13 +893,13 @@ func TestAgentGetTableIncludesAvatarURL(t *testing.T) {t.Errorf("unexpected path: %s", r.URL.Path)}json.NewEncoder(w).Encode(map[string]any{- "id": "agent-123",- "name": "TestAgent",- "status": "active",+ "id": "agent-123",+ "name": "TestAgent",+ "status": "active","runtime_mode": "cloud",- "visibility": "workspace",- "avatar_url": "https://cdn.example.com/avatar.png",- "description": "A test agent",+ "visibility": "workspace",+ "avatar_url": "https://cdn.example.com/avatar.png",+ "description": "A test agent",})}))defer srv.Close()diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 0f996878f6..7503ee4b34 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -537,6 +537,12 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/tasks", h.ListAgentTasks)r.Get("/skills", h.ListAgentSkills)r.Put("/skills", h.SetAgentSkills)+ // Dedicated env-management endpoint. Owner/admin only;+ // agent actors are denied. Every reveal / write is+ // audited to activity_log. See MUL-2600 and+ // internal/handler/agent_env.go.+ r.Get("/env", h.GetAgentEnv)+ r.Put("/env", h.UpdateAgentEnv)})})diff --git a/server/internal/auth/jwt.go b/server/internal/auth/jwt.goindex f300ed707e..9f02bc7f6b 100644--- a/server/internal/auth/jwt.go+++ b/server/internal/auth/jwt.go@@ -46,6 +46,19 @@ func GenerateDaemonToken() (string, error) {return "mdt_" + hex.EncodeToString(b), nil}+// GenerateAgentTaskToken creates a new task-scoped agent auth token:+// "mat_" + 40 random hex chars. The token is single-purpose — bound to a+// specific (agent_id, task_id) pair on the server side — and is what the+// daemon injects into the agent process in place of its own owner PAT.+// See MUL-2600.+func GenerateAgentTaskToken() (string, error) {+ b := make([]byte, 20)+ if _, err := rand.Read(b); err != nil {+ return "", fmt.Errorf("generate agent task token: %w", err)+ }+ return "mat_" + hex.EncodeToString(b), nil+}+// HashToken returns the hex-encoded SHA-256 hash of a token string.func HashToken(token string) string {h := sha256.Sum256([]byte(token))diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 2b7a5c80dc..0d8db5e63a 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2333,8 +2333,22 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// MULTICA_TASK_SLOT is allocated from the daemon-wide concurrency pool, not// per-agent. When one daemon hosts multiple agents, slots index shared// daemon-level resources such as GPUs.+ // MULTICA_TOKEN is the credential the agent process will use to call the+ // Multica API. Prefer the task-scoped token the server minted at claim+ // time — that token is bound to (agent, task) and the auth middleware+ // rejects it on owner-only endpoints (e.g. `/api/agents/{id}/env`), so+ // the agent cannot use it to read another agent's secrets. Falls back+ // to the daemon's own credential only when the server returned no+ // auth_token (older server, or cloud / system runtime with no owner) —+ // in that legacy mode lateral-movement protection relies on the+ // runtime not handing the daemon a workspace-owner PAT in the first+ // place. See MUL-2600.+ agentToken := task.AuthToken+ if agentToken == "" {+ agentToken = d.client.Token()+ }agentEnv := map[string]string{- "MULTICA_TOKEN": d.client.Token(),+ "MULTICA_TOKEN": agentToken,"MULTICA_SERVER_URL": d.cfg.ServerBaseURL,"MULTICA_DAEMON_PORT": fmt.Sprintf("%d", d.cfg.HealthPort),"MULTICA_WORKSPACE_ID": task.WorkspaceID,diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex cea346c4b0..897576dc71 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -75,6 +75,12 @@ type Task struct {// when description is empty so the agent doesn't see a useless heading.RequestingUserName string `json:"requesting_user_name,omitempty"`RequestingUserProfileDescription string `json:"requesting_user_profile_description,omitempty"`+ // AuthToken is the task-scoped credential the server mints at claim time.+ // The daemon injects it into the spawned agent as MULTICA_TOKEN so the+ // agent never sees the daemon's own (often workspace-owner) credential.+ // Empty when the server-side runtime has no owning user — the daemon+ // then falls back to its own token. See MUL-2600.+ AuthToken string `json:"auth_token,omitempty"`}// ChatAttachmentMeta is the structured attachment metadata the daemondiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 03dad78da5..9b7f96a1b3 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -28,25 +28,31 @@ import (const maxAgentDescriptionLength = 255type AgentResponse struct {- ID string `json:"id"`- WorkspaceID string `json:"workspace_id"`- RuntimeID string `json:"runtime_id"`- Name string `json:"name"`- Description string `json:"description"`- Instructions string `json:"instructions"`- AvatarURL *string `json:"avatar_url"`- RuntimeMode string `json:"runtime_mode"`- RuntimeConfig any `json:"runtime_config"`- CustomEnv map[string]string `json:"custom_env"`- CustomArgs []string `json:"custom_args"`- McpConfig json.RawMessage `json:"mcp_config"`- CustomEnvRedacted bool `json:"custom_env_redacted"`- CustomEnvRedactedReason string `json:"custom_env_redacted_reason,omitempty"`- McpConfigRedacted bool `json:"mcp_config_redacted"`- Visibility string `json:"visibility"`- Status string `json:"status"`- MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`- Model string `json:"model"`+ ID string `json:"id"`+ WorkspaceID string `json:"workspace_id"`+ RuntimeID string `json:"runtime_id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Instructions string `json:"instructions"`+ AvatarURL *string `json:"avatar_url"`+ RuntimeMode string `json:"runtime_mode"`+ RuntimeConfig any `json:"runtime_config"`+ CustomArgs []string `json:"custom_args"`+ McpConfig json.RawMessage `json:"mcp_config"`+ // custom_env is intentionally NOT serialized on agent resources. The+ // agent_list/get/create/update/archive/restore responses and WS events+ // only expose coarse metadata (has_custom_env, custom_env_key_count) so+ // the UI can show "N variables configured" without dragging secrets+ // across the API surface. Reading values requires the dedicated, audited+ // `GET /api/agents/{id}/env` endpoint; writing requires `PUT` to the+ // same path. agent-actor tokens are denied there. See MUL-2600.+ HasCustomEnv bool `json:"has_custom_env"`+ CustomEnvKeyCount int `json:"custom_env_key_count"`+ McpConfigRedacted bool `json:"mcp_config_redacted"`+ Visibility string `json:"visibility"`+ Status string `json:"status"`+ MaxConcurrentTasks int32 `json:"max_concurrent_tasks"`+ Model string `json:"model"`// ThinkingLevel is the runtime-native reasoning/effort token persisted// for this agent (empty = use runtime default). The picker is per-runtime// per-model; the API never normalizes across providers. See MUL-2339.@@ -68,14 +74,18 @@ func agentToResponse(a db.Agent) AgentResponse {rc = map[string]any{}}- var customEnv map[string]string+ // Compute env metadata WITHOUT exposing the values. We unmarshal here+ // only to count keys; the map never reaches the response. A coarse+ // has_custom_env / key_count is what the UI gets — to read the values+ // the caller must hit GET /api/agents/{id}/env (owner/admin only,+ // audited).+ envKeyCount := 0if a.CustomEnv != nil {+ var customEnv map[string]stringif err := json.Unmarshal(a.CustomEnv, &customEnv); err != nil {slog.Warn("failed to unmarshal agent custom_env", "agent_id", uuidToString(a.ID), "error", err)}- }- if customEnv == nil {- customEnv = map[string]string{}+ envKeyCount = len(customEnv)}var customArgs []string@@ -103,9 +113,10 @@ func agentToResponse(a db.Agent) AgentResponse {AvatarURL: textToPtr(a.AvatarUrl),RuntimeMode: a.RuntimeMode,RuntimeConfig: rc,- CustomEnv: customEnv,CustomArgs: customArgs,McpConfig: mcpConfig,+ HasCustomEnv: envKeyCount > 0,+ CustomEnvKeyCount: envKeyCount,Visibility: a.Visibility,Status: a.Status,MaxConcurrentTasks: a.MaxConcurrentTasks,@@ -199,6 +210,15 @@ type AgentTaskResponse struct {RequestingUserName string `json:"requesting_user_name,omitempty"`RequestingUserProfileDescription string `json:"requesting_user_profile_description,omitempty"`Kind string `json:"kind"` // discriminator: "comment" | "autopilot" | "chat" | "quick_create" | "direct" — used by the activity row to label tasks that have no linked issue+ // AuthToken is the task-scoped `mat_` token the daemon must inject as+ // MULTICA_TOKEN in the agent process environment. The server binds it to+ // this (agent_id, task_id) pair at claim time and treats any request+ // authenticated with it as actor=agent, regardless of headers — so the+ // agent process cannot use it to read another agent's secrets via the+ // env-management endpoint. Empty when the runtime has no owning user+ // (cloud / system runtimes that pre-date per-task tokens); in that case+ // the daemon falls back to its own credential. See MUL-2600.+ AuthToken string `json:"auth_token,omitempty"`}// ChatAttachmentMeta is the structured attachment metadata embedded in@@ -327,15 +347,18 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {})}- // Check workspace-level always-redact setting.- var alwaysRedact bool+ // mcp_config still uses the workspace-level always-redact setting and+ // the per-row owner/admin gate — secrets in MCP server configs follow+ // the same exposure rules as custom_env used to. custom_env itself is+ // never serialized on agent resources anymore (MUL-2600); see the+ // AgentResponse comment.ws, err := h.Queries.GetWorkspace(r.Context(), parseUUID(workspaceID))if err != nil {slog.Warn("GetWorkspace failed for redact check", "workspace_id", workspaceID, "error", err)writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})return}- alwaysRedact = workspaceAlwaysRedactEnv(ws.Settings)+ alwaysRedact := workspaceAlwaysRedactSecrets(ws.Settings)// Resolve the request actor once. Agents bypass the private-agent gate// to preserve A2A collaboration; members must be in allowed_principals@@ -352,16 +375,13 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {if skills, ok := skillMap[resp.ID]; ok {resp.Skills = skills}- // Redact sensitive fields for users who are not the agent owner or workspace owner/admin,- // or unconditionally when the workspace opts into always_redact_env.- if alwaysRedact {- redactEnv(&resp)- redactMcpConfig(&resp)- resp.CustomEnvRedactedReason = "policy"- } else if !canViewAgentEnv(a, userID, member.Role) {- redactEnv(&resp)+ // Agent actors NEVER see mcp_config secrets, even when their host's+ // PAT would normally satisfy the owner/admin role gate. Otherwise an+ // agent running under an owner's daemon could read other agents'+ // MCP configs (which routinely embed third-party API tokens) — the+ // same lateral-movement vector MUL-2600 closed for custom_env.+ if actorType == "agent" || alwaysRedact || !canViewAgentSecrets(a, userID, member.Role) {redactMcpConfig(&resp)- resp.CustomEnvRedactedReason = "role"}visible = append(visible, resp)}@@ -406,26 +426,22 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {}}- // Redact sensitive fields for users who are not the agent owner or workspace owner/admin,- // or unconditionally when the workspace opts into always_redact_env.+ // mcp_config redaction (custom_env was removed from this response shape+ // in MUL-2600; secrets are now fetched via GET /api/agents/{id}/env).userID := requestUserID(r)- var alwaysRedact boolws, err := h.Queries.GetWorkspace(r.Context(), agent.WorkspaceID)if err != nil {slog.Warn("GetWorkspace failed for redact check", "workspace_id", uuidToString(agent.WorkspaceID), "error", err)writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})return}- alwaysRedact = workspaceAlwaysRedactEnv(ws.Settings)- if alwaysRedact {- redactEnv(&resp)+ alwaysRedact := workspaceAlwaysRedactSecrets(ws.Settings)+ // Agent actors NEVER see mcp_config (see ListAgents for the rationale).+ if actorType == "agent" || alwaysRedact {redactMcpConfig(&resp)- resp.CustomEnvRedactedReason = "policy"} else if member, ok := ctxMember(r.Context()); ok {- if !canViewAgentEnv(agent, userID, member.Role) {- redactEnv(&resp)+ if !canViewAgentSecrets(agent, userID, member.Role) {redactMcpConfig(&resp)- resp.CustomEnvRedactedReason = "role"}}@@ -614,7 +630,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {resp := agentToResponse(created)actorType, actorID := h.resolveActor(r, ownerID, workspaceID)- h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": resp})+ h.publish(protocol.EventAgentCreated, workspaceID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})h.Analytics.Capture(analytics.AgentCreated(ownerID,@@ -626,23 +642,32 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {isFirstAgent,))+ redactAgentResponseForActor(&resp, actorType)writeJSON(w, http.StatusCreated, resp)}type UpdateAgentRequest struct {- Name *string `json:"name"`- Description *string `json:"description"`- Instructions *string `json:"instructions"`- AvatarURL *string `json:"avatar_url"`- RuntimeID *string `json:"runtime_id"`- RuntimeConfig any `json:"runtime_config"`- CustomEnv *map[string]string `json:"custom_env"`- CustomArgs *[]string `json:"custom_args"`- McpConfig *json.RawMessage `json:"mcp_config"`- Visibility *string `json:"visibility"`- Status *string `json:"status"`- MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`- Model *string `json:"model"`+ Name *string `json:"name"`+ Description *string `json:"description"`+ Instructions *string `json:"instructions"`+ AvatarURL *string `json:"avatar_url"`+ RuntimeID *string `json:"runtime_id"`+ RuntimeConfig any `json:"runtime_config"`+ // custom_env is intentionally NOT updatable through this endpoint.+ // Use `PUT /api/agents/{id}/env` for env changes — that path is+ // owner/admin-only, denies agent actors, and writes a persisted+ // audit log entry. A `PUT /api/agents/{id}` body that carries+ // `custom_env` is rejected with 400 in the handler below so a+ // caller never believes they rotated a secret when the value is+ // actually unchanged, and so a client that round-tripped a+ // previously-returned masked map cannot silently overwrite real+ // secret values with literal `****`. See MUL-2600.+ CustomArgs *[]string `json:"custom_args"`+ McpConfig *json.RawMessage `json:"mcp_config"`+ Visibility *string `json:"visibility"`+ Status *string `json:"status"`+ MaxConcurrentTasks *int32 `json:"max_concurrent_tasks"`+ Model *string `json:"model"`// ThinkingLevel is treated as a tri-state per-MUL-2339:// - field omitted → no change (leave existing value alone)// - field present with "" → explicit clear (use runtime default)@@ -652,12 +677,17 @@ type UpdateAgentRequest struct {ThinkingLevel *string `json:"thinking_level"`}-// workspaceAlwaysRedactEnv checks whether the workspace has opted into-// unconditional redaction of custom_env and mcp_config on read responses,-// regardless of the caller's role. This is useful for single-tenant-// self-hosts or security-conscious teams that never want plaintext secrets-// returned from the API.-func workspaceAlwaysRedactEnv(settings []byte) bool {+// workspaceAlwaysRedactSecrets reports whether the workspace has opted+// into unconditional redaction of secret-bearing fields (currently+// `mcp_config`) on read responses, regardless of the caller's role.+//+// The legacy JSON key is still `always_redact_env` for backwards-+// compatibility with workspaces that flipped the setting before MUL-2600+// shipped. The setting no longer affects `custom_env` because that field+// is never serialized on agent resources anymore — secrets there are+// fetched exclusively through `GET /api/agents/{id}/env` with audit+// logging — so the flag now only governs `mcp_config` exposure.+func workspaceAlwaysRedactSecrets(settings []byte) bool {if len(settings) == 0 {return false}@@ -670,26 +700,32 @@ func workspaceAlwaysRedactEnv(settings []byte) bool {return s.AlwaysRedactEnv}-// canViewAgentEnv checks whether the requesting user is allowed to see the-// agent's custom environment variables. Only the agent owner or workspace-// owner/admin may view them; for everyone else the field is redacted.-func canViewAgentEnv(agent db.Agent, userID string, memberRole string) bool {+// canViewAgentSecrets checks whether the requesting user is allowed to+// see the agent's secret-bearing fields (currently `mcp_config`). Only+// the agent owner or workspace owner/admin qualify; for everyone else+// the response is redacted. `custom_env` is no longer part of an agent+// resource response (see MUL-2600), so this predicate is shared only by+// the remaining mcp_config redaction path.+func canViewAgentSecrets(agent db.Agent, userID string, memberRole string) bool {if roleAllowed(memberRole, "owner", "admin") {return true}return uuidToString(agent.OwnerID) == userID}-// redactEnv masks custom_env values in the response when the caller is not-// authorised to view them. Keys are preserved so members can see which-// variables are configured; values are replaced with "****".-func redactEnv(resp *AgentResponse) {- masked := make(map[string]string, len(resp.CustomEnv))- for k := range resp.CustomEnv {- masked[k] = "****"- }- resp.CustomEnv = masked- resp.CustomEnvRedacted = true+// broadcastAgentResponse strips secret-bearing fields from an+// AgentResponse before it goes onto the WebSocket bus. Mutation+// handlers call this when fanning out create/update/archive/restore+// events: subscribers (which include agent processes that have+// authenticated with their own task tokens) must not learn another+// agent's mcp_config via a WS push that bypassed the read-path+// redaction in ListAgents / GetAgent. The caller still receives the+// canonical form in the HTTP response; only the broadcast copy is+// redacted.+func broadcastAgentResponse(resp AgentResponse) AgentResponse {+ out := resp+ redactMcpConfig(&out)+ return out}// redactMcpConfig removes the mcp_config value from the response when the caller is not@@ -702,6 +738,19 @@ func redactMcpConfig(resp *AgentResponse) {}}+// redactAgentResponseForActor strips secret-bearing fields from an agent+// resource HTTP response when the request actor is an agent. Read+// handlers already gate on actorType — mutation handlers+// (create/update/archive/restore) must apply the same rule, otherwise+// an agent with a host owner/admin token can do an unrelated mutation+// (e.g. flip max_concurrent_tasks) on a target agent and harvest the+// target's mcp_config from the mutation response. MUL-2600.+func redactAgentResponseForActor(resp *AgentResponse, actorType string) {+ if actorType == "agent" {+ redactMcpConfig(resp)+ }+}+// canManageAgent checks whether the current user can update or archive an agent.// Only the agent owner or workspace owner/admin can manage any agent,// regardless of whether it is public or private.@@ -737,6 +786,18 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {return}+ // Hard-reject any attempt to write custom_env through the generic+ // update endpoint. Silently dropping the field (which is what an+ // `omitempty` field would do) was the pre-PR behaviour and led to+ // users believing they had rotated a secret when the value was+ // actually unchanged. env values move only through `PUT+ // /api/agents/{id}/env` — that endpoint is owner/admin-only, denies+ // agent actors, and writes a queryable audit row.+ if _, ok := rawFields["custom_env"]; ok {+ writeError(w, http.StatusBadRequest, "custom_env is no longer accepted on this endpoint; use PUT /api/agents/{id}/env (or `multica agent env set`)")+ return+ }+params := db.UpdateAgentParams{ID: existing.ID,}@@ -760,10 +821,6 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {rc, _ := json.Marshal(req.RuntimeConfig)params.RuntimeConfig = rc}- if req.CustomEnv != nil {- ce, _ := json.Marshal(*req.CustomEnv)- params.CustomEnv = ce- }if req.CustomArgs != nil {ca, _ := json.Marshal(*req.CustomArgs)params.CustomArgs = ca@@ -905,7 +962,8 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {slog.Info("agent updated", append(logger.RequestAttrs(r), "agent_id", id, "workspace_id", uuidToString(updated.WorkspaceID))...)userID := requestUserID(r)actorType, actorID := h.resolveActor(r, userID, uuidToString(updated.WorkspaceID))- h.publish(protocol.EventAgentStatus, uuidToString(updated.WorkspaceID), actorType, actorID, map[string]any{"agent": resp})+ h.publish(protocol.EventAgentStatus, uuidToString(updated.WorkspaceID), actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})+ redactAgentResponseForActor(&resp, actorType)writeJSON(w, http.StatusOK, resp)}@@ -963,7 +1021,8 @@ func (h *Handler) ArchiveAgent(w http.ResponseWriter, r *http.Request) {slog.Info("agent archived", append(logger.RequestAttrs(r), "agent_id", id, "workspace_id", wsID)...)resp := agentToResponse(archived)actorType, actorID := h.resolveActor(r, userID, wsID)- h.publish(protocol.EventAgentArchived, wsID, actorType, actorID, map[string]any{"agent": resp})+ h.publish(protocol.EventAgentArchived, wsID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})+ redactAgentResponseForActor(&resp, actorType)writeJSON(w, http.StatusOK, resp)}@@ -993,7 +1052,8 @@ func (h *Handler) RestoreAgent(w http.ResponseWriter, r *http.Request) {resp := agentToResponse(restored)userID := requestUserID(r)actorType, actorID := h.resolveActor(r, userID, wsID)- h.publish(protocol.EventAgentRestored, wsID, actorType, actorID, map[string]any{"agent": resp})+ h.publish(protocol.EventAgentRestored, wsID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(resp)})+ redactAgentResponseForActor(&resp, actorType)writeJSON(w, http.StatusOK, resp)}diff --git a/server/internal/handler/agent_env.go b/server/internal/handler/agent_env.gonew file mode 100644index 0000000000..86fe369564--- /dev/null+++ b/server/internal/handler/agent_env.go@@ -0,0 +1,332 @@+package handler++import (+ "encoding/json"+ "log/slog"+ "net/http"+ "sort"++ "github.com/go-chi/chi/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/logger"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// envSentinel is the masked marker the UI / clients see in place of a+// real value. A PUT body carrying it for a given key means "do not+// overwrite the existing value for that key" — a defense-in-depth+// guard so a client that round-trips a partially-revealed map cannot+// silently destroy real secrets by saving the masked placeholder.+const envSentinel = "****"++// agentEnvActivityRevealed and agentEnvActivityUpdated are the+// activity_log `action` constants for the two env-management+// endpoints. Stored on rows where `issue_id IS NULL` (env access is not+// tied to any issue). Owners can later query them — a queryable audit+// UI is out of scope for this PR, but the rows are written now so the+// data is captured from day one. Workspace activity history will+// eventually surface them; for now they're forensic-only.+const (+ agentEnvActivityRevealed = "agent_env_revealed"+ agentEnvActivityUpdated = "agent_env_updated"+)++// AgentEnvResponse is the wire shape for the dedicated env-management+// endpoint. Kept distinct from `AgentResponse` so secrets cannot leak+// back into the generic agent resource by accident — a future+// refactor that adds a field to AgentResponse cannot accidentally+// pull env values along.+type AgentEnvResponse struct {+ AgentID string `json:"agent_id"`+ CustomEnv map[string]string `json:"custom_env"`+}++// UpdateAgentEnvRequest is the wire shape for `PUT+// /api/agents/{id}/env`. Only `custom_env` is accepted — fewer+// surfaces, less to misuse.+type UpdateAgentEnvRequest struct {+ CustomEnv map[string]string `json:"custom_env"`+}++// authorizeAgentEnv enforces the per-request auth contract for the env+// endpoints:+//+// 1. The actor MUST resolve to a member (human). Any request authored+// by an agent token — even one whose backing member is a workspace+// owner — is rejected. This is the key fix for the+// impersonation/lateral-movement risk that motivated MUL-2600: an+// agent running in the workspace cannot use its host's owner+// credentials to reveal another agent's secrets.+// 2. The member must be a workspace owner or admin.+//+// Returns the loaded agent and the authenticated member on success.+// All non-2xx branches write their own response and return ok=false.+func (h *Handler) authorizeAgentEnv(w http.ResponseWriter, r *http.Request) (db.Agent, db.Member, bool) {+ agentID := chi.URLParam(r, "id")+ agent, ok := h.loadAgentForUser(w, r, agentID)+ if !ok {+ return db.Agent{}, db.Member{}, false+ }++ workspaceID := uuidToString(agent.WorkspaceID)+ userID := requestUserID(r)++ // Reject agent actors before anything else. resolveActor returns+ // "agent" iff both X-Agent-ID and a valid X-Task-ID are present and+ // the task belongs to that agent — so this guard is precise and+ // cannot be tricked by a member-supplied header.+ actorType, _ := h.resolveActor(r, userID, workspaceID)+ if actorType == "agent" {+ writeError(w, http.StatusForbidden, "agents may not access env management endpoints")+ return db.Agent{}, db.Member{}, false+ }++ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "agent not found", "owner", "admin")+ if !ok {+ return db.Agent{}, db.Member{}, false+ }++ return agent, member, true+}++// GetAgentEnv returns the plaintext custom_env map for a single agent+// after gating through authorizeAgentEnv. Every successful read writes+// an `agent_env_revealed` row to activity_log (keys only, never+// values) so workspace owners have a trail of who saw which keys.+//+// Audit semantics are fail-closed: if we cannot persist the audit row+// we MUST NOT serve the plaintext. A reveal we cannot record is+// indistinguishable from an unaudited reveal, which would silently+// break the MUL-2600 promise of "every reveal leaves a queryable+// trail". Operators who hit a 500 here see the audit-log outage and+// can fix it; the alternative — quietly handing out secrets — is+// invisible.+func (h *Handler) GetAgentEnv(w http.ResponseWriter, r *http.Request) {+ agent, member, ok := h.authorizeAgentEnv(w, r)+ if !ok {+ return+ }++ customEnv := unmarshalCustomEnv(agent)++ revealedKeys := sortedKeys(customEnv)+ details, _ := json.Marshal(map[string]any{+ "agent_id": uuidToString(agent.ID),+ "agent_name": agent.Name,+ "revealed_keys": revealedKeys,+ "key_count": len(revealedKeys),+ })+ if _, err := h.Queries.CreateActivity(r.Context(), db.CreateActivityParams{+ WorkspaceID: agent.WorkspaceID,+ IssueID: pgtype.UUID{}, // env access is not tied to an issue+ ActorType: pgtype.Text{String: "member", Valid: true},+ ActorID: parseUUID(uuidToString(member.UserID)),+ Action: agentEnvActivityRevealed,+ Details: details,+ }); err != nil {+ slog.Error("agent_env_revealed audit write failed; refusing to serve plaintext",+ append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)+ writeError(w, http.StatusInternalServerError, "audit log write failed; refusing to serve env without a recorded reveal")+ return+ }++ writeJSON(w, http.StatusOK, AgentEnvResponse{+ AgentID: uuidToString(agent.ID),+ CustomEnv: customEnv,+ })+}++// UpdateAgentEnv replaces an agent's custom_env wholesale. The **** marker is+// honoured per-key: any value equal to envSentinel is treated as+// "keep the existing value for that key", protecting against the+// scenario where a UI fetches the env, exposes some values but leaves+// others masked, and then naively PUTs the whole map back. A+// straightforward write would have stored literal `****` in place of+// the real secret. Audit log captures the symmetric difference between+// old and new keys but never values.+//+// Persist + audit run inside one DB transaction so they commit+// together or roll back together. An audit-write outage cannot leave+// an unaudited env mutation on disk, and a persist failure does not+// leave a phantom audit row claiming a change that never happened.+func (h *Handler) UpdateAgentEnv(w http.ResponseWriter, r *http.Request) {+ agent, member, ok := h.authorizeAgentEnv(w, r)+ if !ok {+ return+ }++ var req UpdateAgentEnvRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if req.CustomEnv == nil {+ req.CustomEnv = map[string]string{}+ }++ existing := unmarshalCustomEnv(agent)+ merged, audit := mergeAgentEnv(existing, req.CustomEnv)++ envBytes, err := json.Marshal(merged)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to encode env")+ return+ }++ tx, err := h.TxStarter.Begin(r.Context())+ if err != nil {+ slog.Error("agent_env update: begin tx failed",+ append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to update env")+ return+ }+ defer tx.Rollback(r.Context())+ qtx := h.Queries.WithTx(tx)++ updated, err := qtx.UpdateAgentCustomEnv(r.Context(), db.UpdateAgentCustomEnvParams{+ ID: agent.ID,+ CustomEnv: envBytes,+ })+ if err != nil {+ slog.Warn("update agent custom_env failed",+ append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to update env")+ return+ }++ auditDetails := map[string]any{+ "agent_id": uuidToString(agent.ID),+ "agent_name": agent.Name,+ "added_keys": audit.added,+ "removed_keys": audit.removed,+ "changed_keys": audit.changed,+ "preserved_keys": audit.preserved,+ }+ details, _ := json.Marshal(auditDetails)+ if _, err := qtx.CreateActivity(r.Context(), db.CreateActivityParams{+ WorkspaceID: agent.WorkspaceID,+ IssueID: pgtype.UUID{},+ ActorType: pgtype.Text{String: "member", Valid: true},+ ActorID: parseUUID(uuidToString(member.UserID)),+ Action: agentEnvActivityUpdated,+ Details: details,+ }); err != nil {+ slog.Error("agent_env_updated audit write failed; rolling back update",+ append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)+ writeError(w, http.StatusInternalServerError, "audit log write failed; env update rolled back")+ return+ }++ if err := tx.Commit(r.Context()); err != nil {+ slog.Error("agent_env update: tx commit failed",+ append(logger.RequestAttrs(r), "error", err, "agent_id", uuidToString(agent.ID))...)+ writeError(w, http.StatusInternalServerError, "failed to update env")+ return+ }++ // Broadcast an agent:status update so connected clients refresh the+ // "N variables configured" indicator. Payload is the redacted+ // AgentResponse — no env values are sent.+ resp := agentToResponse(updated)+ workspaceID := uuidToString(updated.WorkspaceID)+ h.publish(protocol.EventAgentStatus, workspaceID, "member", uuidToString(member.UserID), map[string]any{"agent": broadcastAgentResponse(resp)})++ writeJSON(w, http.StatusOK, AgentEnvResponse{+ AgentID: uuidToString(updated.ID),+ CustomEnv: merged,+ })+}++// envAudit summarises the diff between an agent's existing env and the+// new one, broken down so an auditor can reconstruct exactly which+// keys an operation touched without leaking values. All slices are+// sorted to keep the activity row content deterministic for tests and+// downstream tooling.+type envAudit struct {+ added []string+ removed []string+ changed []string+ preserved []string+}++// mergeAgentEnv applies the **** sentinel rule and returns both the+// final map to persist and an audit summary of which keys changed.+// Behaviour:+// - request key present, value == "****", key exists in `existing`+// → keep the existing value, append to preserved+// - request key present, value == "****", key NOT in `existing`+// → drop the key (literal "****" is never a valid stored value)+// - request key present, value != "****", key already in existing+// with same value → no-op (not counted)+// - request key present, value != "****", different from existing+// → write new value, append to changed+// - request key present, value != "****", key NOT in existing+// → write new value, append to added+// - key in existing but absent from request → removed+func mergeAgentEnv(existing, request map[string]string) (map[string]string, envAudit) {+ merged := make(map[string]string, len(request))+ audit := envAudit{}++ for k, v := range request {+ if v == envSentinel {+ if old, ok := existing[k]; ok {+ merged[k] = old+ audit.preserved = append(audit.preserved, k)+ }+ // else: drop. We never persist a literal "****".+ continue+ }+ if old, ok := existing[k]; ok {+ if old == v {+ merged[k] = v+ continue+ }+ merged[k] = v+ audit.changed = append(audit.changed, k)+ continue+ }+ merged[k] = v+ audit.added = append(audit.added, k)+ }++ for k := range existing {+ if _, ok := request[k]; !ok {+ audit.removed = append(audit.removed, k)+ }+ }++ sort.Strings(audit.added)+ sort.Strings(audit.removed)+ sort.Strings(audit.changed)+ sort.Strings(audit.preserved)+ return merged, audit+}++// unmarshalCustomEnv decodes an agent's stored custom_env bytea into a+// map, returning an empty (never nil) map so callers can iterate+// safely.+func unmarshalCustomEnv(a db.Agent) map[string]string {+ out := map[string]string{}+ if len(a.CustomEnv) == 0 {+ return out+ }+ if err := json.Unmarshal(a.CustomEnv, &out); err != nil {+ slog.Warn("failed to unmarshal agent custom_env", "agent_id", uuidToString(a.ID), "error", err)+ return map[string]string{}+ }+ if out == nil {+ return map[string]string{}+ }+ return out+}++func sortedKeys(m map[string]string) []string {+ keys := make([]string, 0, len(m))+ for k := range m {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ return keys+}diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.goindex f3ba8f8d95..20141c6771 100644--- a/server/internal/handler/agent_test.go+++ b/server/internal/handler/agent_test.go@@ -1,10 +1,14 @@package handlerimport (+ "bytes""context""encoding/json"+ "fmt""net/http""net/http/httptest"+ "reflect"+ "strings""testing")@@ -186,7 +190,7 @@ func TestCreateAgent_RejectsDuplicateName(t *testing.T) {}}-func TestWorkspaceAlwaysRedactEnv(t *testing.T) {+func TestWorkspaceAlwaysRedactSecrets(t *testing.T) {tests := []struct {name stringsettings []byte@@ -202,33 +206,37 @@ func TestWorkspaceAlwaysRedactEnv(t *testing.T) {}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- if got := workspaceAlwaysRedactEnv(tt.settings); got != tt.want {- t.Errorf("workspaceAlwaysRedactEnv(%q) = %v, want %v", tt.settings, got, tt.want)+ if got := workspaceAlwaysRedactSecrets(tt.settings); got != tt.want {+ t.Errorf("workspaceAlwaysRedactSecrets(%q) = %v, want %v", tt.settings, got, tt.want)}})}}-func resetWorkspaceSettings(t *testing.T, workspaceID string) {+// rawJSONResponse decodes the raw map so we can assert the literal+// JSON shape — `custom_env` MUST be absent from the wire output, not+// merely empty, otherwise a future caller decoding into a wider struct+// could still see masked or partial values.+func rawJSONResponse(t *testing.T, body []byte) map[string]any {t.Helper()- if _, err := testPool.Exec(context.Background(), "UPDATE workspace SET settings = '{}'::jsonb WHERE id = $1", workspaceID); err != nil {- t.Logf("warning: failed to reset workspace settings: %v", err)+ var out map[string]any+ if err := json.Unmarshal(body, &out); err != nil {+ t.Fatalf("failed to decode response: %v", err)}+ return out}-func TestGetAgent_AlwaysRedactEnv_OwnerSeesRedacted(t *testing.T) {+// TestGetAgent_ResponseHasNoCustomEnv guards the core invariant from+// MUL-2600: the generic agent resource response NEVER carries the+// custom_env field, even for the agent's owner. Only the dedicated+// env endpoint exposes secret values.+func TestGetAgent_ResponseHasNoCustomEnv(t *testing.T) {if testHandler == nil {t.Skip("database not available")}ctx := context.Background()- // Enable always_redact_env on workspace.- if _, err := testPool.Exec(ctx, `UPDATE workspace SET settings = '{"always_redact_env": true}' WHERE id = $1`, testWorkspaceID); err != nil {- t.Fatalf("failed to set workspace settings: %v", err)- }- t.Cleanup(func() { resetWorkspaceSettings(t, testWorkspaceID) })-- agentID := createHandlerTestAgent(t, "redact-get-test-agent", nil)+ agentID := createHandlerTestAgent(t, "noenv-get-agent", nil)if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"SECRET_KEY": "super-secret"}' WHERE id = $1`, agentID); err != nil {t.Fatalf("failed to set custom_env: %v", err)}@@ -242,108 +250,549 @@ func TestGetAgent_AlwaysRedactEnv_OwnerSeesRedacted(t *testing.T) {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}- var resp AgentResponse- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("failed to decode response: %v", err)+ raw := rawJSONResponse(t, w.Body.Bytes())+ if _, ok := raw["custom_env"]; ok {+ t.Errorf("custom_env field must not appear in agent response, got %v", raw["custom_env"])+ }+ if _, ok := raw["custom_env_redacted"]; ok {+ t.Errorf("custom_env_redacted field must not appear in agent response (use has_custom_env)")}- if !resp.CustomEnvRedacted {- t.Error("expected custom_env_redacted to be true")+ if got, _ := raw["has_custom_env"].(bool); !got {+ t.Errorf("has_custom_env expected true, got %v", raw["has_custom_env"])}- if resp.CustomEnvRedactedReason != "policy" {- t.Errorf("expected custom_env_redacted_reason to be 'policy', got %q", resp.CustomEnvRedactedReason)+ if got, _ := raw["custom_env_key_count"].(float64); got != 1 {+ t.Errorf("custom_env_key_count expected 1, got %v", raw["custom_env_key_count"])+ }++ // Sanity-check the typed shape too — the struct must not have+ // rehydrated the masked map.+ var typed AgentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &typed); err != nil {+ t.Fatalf("typed decode failed: %v", err)}- if resp.CustomEnv["SECRET_KEY"] != "****" {- t.Errorf("expected SECRET_KEY to be redacted, got %q", resp.CustomEnv["SECRET_KEY"])+ if typed.HasCustomEnv != true {+ t.Errorf("typed.HasCustomEnv expected true")+ }+ if typed.CustomEnvKeyCount != 1 {+ t.Errorf("typed.CustomEnvKeyCount expected 1, got %d", typed.CustomEnvKeyCount)}}-func TestListAgents_AlwaysRedactEnv_OwnerSeesRedacted(t *testing.T) {+// TestListAgents_ResponseHasNoCustomEnv mirrors the GetAgent guard for+// the list endpoint. Same invariant: no custom_env field on the wire,+// only coarse metadata.+func TestListAgents_ResponseHasNoCustomEnv(t *testing.T) {if testHandler == nil {t.Skip("database not available")}ctx := context.Background()- if _, err := testPool.Exec(ctx, `UPDATE workspace SET settings = '{"always_redact_env": true}' WHERE id = $1`, testWorkspaceID); err != nil {- t.Fatalf("failed to set workspace settings: %v", err)- }- t.Cleanup(func() { resetWorkspaceSettings(t, testWorkspaceID) })-- agentName := "redact-list-test-agent"+ agentName := "noenv-list-agent"agentID := createHandlerTestAgent(t, agentName, nil)- if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"SECRET_KEY": "super-secret"}' WHERE id = $1`, agentID); err != nil {+ if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"SECRET_KEY": "super-secret", "OTHER": "y"}' WHERE id = $1`, agentID); err != nil {t.Fatalf("failed to set custom_env: %v", err)}req := newRequest("GET", "/agents", nil)w := httptest.NewRecorder()testHandler.ListAgents(w, req)-if w.Code != http.StatusOK {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}- var agents []AgentResponse- if err := json.Unmarshal(w.Body.Bytes(), &agents); err != nil {+ var rawAgents []map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &rawAgents); err != nil {t.Fatalf("failed to decode response: %v", err)}- var found *AgentResponse- for i := range agents {- if agents[i].Name == agentName {- found = &agents[i]+ var found map[string]any+ for _, a := range rawAgents {+ if name, _ := a["name"].(string); name == agentName {+ found = abreak}}if found == nil {t.Fatal("agent not found in list response")}- if !found.CustomEnvRedacted {- t.Error("expected custom_env_redacted to be true")+ if _, ok := found["custom_env"]; ok {+ t.Errorf("custom_env must not appear in list response")}- if found.CustomEnvRedactedReason != "policy" {- t.Errorf("expected custom_env_redacted_reason to be 'policy', got %q", found.CustomEnvRedactedReason)+ if got, _ := found["custom_env_key_count"].(float64); got != 2 {+ t.Errorf("custom_env_key_count expected 2, got %v", found["custom_env_key_count"])}- if found.CustomEnv["SECRET_KEY"] != "****" {- t.Errorf("expected SECRET_KEY to be redacted, got %q", found.CustomEnv["SECRET_KEY"])+ if got, _ := found["has_custom_env"].(bool); !got {+ t.Errorf("has_custom_env expected true")}}-func TestGetAgent_DefaultNoRedactForOwner(t *testing.T) {+// TestGetAgentEnv_OwnerSucceedsAndAudits exercises the happy path: an+// agent owner reveals env, and the response carries the plaintext map.+// The activity_log row is checked at the end so the audit trail is+// proven to land in the same transaction window.+func TestGetAgentEnv_OwnerSucceedsAndAudits(t *testing.T) {if testHandler == nil {t.Skip("database not available")}ctx := context.Background()- // Ensure workspace has no always_redact_env policy (guards against test-order leakage).- if _, err := testPool.Exec(ctx, `UPDATE workspace SET settings = '{}'::jsonb WHERE id = $1`, testWorkspaceID); err != nil {- t.Fatalf("failed to clear workspace settings: %v", err)+ agentID := createHandlerTestAgent(t, "env-reveal-owner-agent", nil)+ if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"KEY_ONE": "v1", "KEY_TWO": "v2"}' WHERE id = $1`, agentID); err != nil {+ t.Fatalf("failed to set custom_env: %v", err)}- agentID := createHandlerTestAgent(t, "no-redact-get-test-agent", nil)- if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"SECRET_KEY": "super-secret"}' WHERE id = $1`, agentID); err != nil {+ req := newRequest("GET", "/api/agents/"+agentID+"/env", nil)+ req = withURLParam(req, "id", agentID)+ w := httptest.NewRecorder()+ testHandler.GetAgentEnv(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("GetAgentEnv: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp AgentEnvResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.AgentID != agentID {+ t.Errorf("agent_id mismatch: got %q", resp.AgentID)+ }+ expected := map[string]string{"KEY_ONE": "v1", "KEY_TWO": "v2"}+ if !reflect.DeepEqual(resp.CustomEnv, expected) {+ t.Errorf("CustomEnv mismatch: got %v, want %v", resp.CustomEnv, expected)+ }++ // Audit row must exist; keys but not values must be recorded.+ var revealedKeysJSON string+ if err := testPool.QueryRow(ctx, `+ SELECT details::text FROM activity_log+ WHERE workspace_id = $1 AND action = 'agent_env_revealed'+ AND details->>'agent_id' = $2+ ORDER BY created_at DESC LIMIT 1+ `, testWorkspaceID, agentID).Scan(&revealedKeysJSON); err != nil {+ t.Fatalf("no agent_env_revealed activity row found: %v", err)+ }+ if !strings.Contains(revealedKeysJSON, `"KEY_ONE"`) || !strings.Contains(revealedKeysJSON, `"KEY_TWO"`) {+ t.Errorf("expected revealed_keys to contain KEY_ONE and KEY_TWO, got: %s", revealedKeysJSON)+ }+ if strings.Contains(revealedKeysJSON, `"v1"`) || strings.Contains(revealedKeysJSON, `"v2"`) {+ t.Errorf("activity details must NOT contain env values, got: %s", revealedKeysJSON)+ }+}++// TestAgentEnv_AgentActorRejected proves the security-critical actor+// guard: even when the underlying user is a workspace owner, a request+// arriving from inside a running agent task is denied 403. This is+// the lateral-movement fix — an agent running with its owner's token+// cannot reveal a sibling agent's secrets.+func TestAgentEnv_AgentActorRejected(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ targetID := createHandlerTestAgent(t, "env-target-agent", nil)+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET custom_env = '{"K":"v"}' WHERE id = $1`, targetID); err != nil {t.Fatalf("failed to set custom_env: %v", err)}- req := newRequest("GET", "/agents/"+agentID, nil)+ // Spin up a separate agent + task that authorises the X-Agent-ID /+ // X-Task-ID header pair resolveActor checks. The owning member of+ // the host agent is the same testUserID (workspace owner), which is+ // the exact lateral-movement shape we want to block.+ hostAgentID := createHandlerTestAgent(t, "env-host-agent", nil)+ hostTaskID := createHandlerTestTaskForAgent(t, hostAgentID)++ cases := []struct {+ name string+ fn func(http.ResponseWriter, *http.Request)+ body any+ }{+ {"reveal", testHandler.GetAgentEnv, nil},+ {"update", testHandler.UpdateAgentEnv, map[string]any{"custom_env": map[string]string{"K": "v2"}}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ method := http.MethodGet+ if tc.body != nil {+ method = http.MethodPut+ }+ req := newRequest(method, "/api/agents/"+targetID+"/env", tc.body)+ req = withURLParam(req, "id", targetID)+ req.Header.Set("X-Agent-ID", hostAgentID)+ req.Header.Set("X-Task-ID", hostTaskID)+ w := httptest.NewRecorder()+ tc.fn(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403 from agent actor, got %d: %s", w.Code, w.Body.String())+ }+ })+ }+}++// TestAgentEnv_TaskTokenActorSource locks in the post-MUL-2600 attack+// model: an agent process that strips its identifying headers+// (X-Agent-ID / X-Task-ID) but is still authenticated by an `mat_`+// task token MUST be recognized as actor=agent and rejected on the+// env endpoint. The auth middleware sets X-Actor-Source=task_token+// from the token row; resolveActor honors that header before the+// header-pair fallback. Without this guard the lateral-movement fix+// would only block "honest" CLIs that voluntarily set both headers.+func TestAgentEnv_TaskTokenActorSource(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ targetID := createHandlerTestAgent(t, "env-tt-target-agent", nil)+ if _, err := testPool.Exec(context.Background(), `UPDATE agent SET custom_env = '{"K":"v"}' WHERE id = $1`, targetID); err != nil {+ t.Fatalf("failed to set custom_env: %v", err)+ }++ req := newRequest(http.MethodGet, "/api/agents/"+targetID+"/env", nil)+ req = withURLParam(req, "id", targetID)+ // Simulate the auth middleware's post-mat_-resolution state: the+ // only header touching actor identity is X-Actor-Source. The agent+ // process stripped X-Agent-ID and X-Task-ID, hoping to fall back+ // to the member auth path — the server-set X-Actor-Source must+ // short-circuit that escape.+ req.Header.Set("X-Actor-Source", "task_token")+ req.Header.Del("X-Agent-ID")+ req.Header.Del("X-Task-ID")+ w := httptest.NewRecorder()+ testHandler.GetAgentEnv(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403 when X-Actor-Source=task_token, got %d: %s", w.Code, w.Body.String())+ }+}++// TestUpdateAgentEnv_PreservesSentinelValues verifies the **** guard.+// A naive write would clobber real secrets with the masked+// placeholder; we want any key whose value comes in as **** to keep+// its stored value.+func TestUpdateAgentEnv_PreservesSentinelValues(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID := createHandlerTestAgent(t, "env-sentinel-agent", nil)+ if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"KEEP_ME":"real-secret","ALSO":"another-secret"}' WHERE id = $1`, agentID); err != nil {+ t.Fatalf("failed to seed custom_env: %v", err)+ }++ // Client sends one key with a real new value, one with **** (should+ // be preserved), and one new key that isn't in the existing map but+ // arrives as **** (must be dropped, never written as literal).+ body := map[string]any{+ "custom_env": map[string]string{+ "KEEP_ME": "****",+ "ALSO": "rotated",+ "PHANTOM": "****",+ "BRAND_NEW": "fresh",+ },+ }+ req := newRequest(http.MethodPut, "/api/agents/"+agentID+"/env", body)req = withURLParam(req, "id", agentID)w := httptest.NewRecorder()- testHandler.GetAgent(w, req)+ testHandler.UpdateAgentEnv(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgentEnv: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ // Refetch from DB so we don't rely on the response body alone.+ var stored string+ if err := testPool.QueryRow(ctx, `SELECT custom_env::text FROM agent WHERE id = $1`, agentID).Scan(&stored); err != nil {+ t.Fatalf("failed to read back custom_env: %v", err)+ }+ var got map[string]string+ if err := json.Unmarshal([]byte(stored), &got); err != nil {+ t.Fatalf("failed to decode stored custom_env: %v", err)+ }+ want := map[string]string{+ "KEEP_ME": "real-secret", // **** must preserve the existing value+ "ALSO": "rotated", // explicit overwrite+ "BRAND_NEW": "fresh", // new addition+ // PHANTOM is intentionally absent — **** for a non-existent key+ // is dropped, never persisted as literal `****`.+ }+ if !reflect.DeepEqual(got, want) {+ t.Errorf("stored custom_env mismatch:\n got: %v\n want: %v", got, want)+ }++ // Audit row should reflect the diff. We decode the jsonb back into a+ // typed map and compare semantically — postgres serializes jsonb with+ // canonicalised whitespace (`"added_keys": ["BRAND_NEW"]`), so a raw+ // substring match on the dense form silently fails on real database+ // output.+ var details string+ if err := testPool.QueryRow(ctx, `+ SELECT details::text FROM activity_log+ WHERE workspace_id = $1 AND action = 'agent_env_updated' AND details->>'agent_id' = $2+ ORDER BY created_at DESC LIMIT 1+ `, testWorkspaceID, agentID).Scan(&details); err != nil {+ t.Fatalf("expected agent_env_updated activity row: %v", err)+ }+ var auditFields struct {+ AddedKeys []string `json:"added_keys"`+ ChangedKeys []string `json:"changed_keys"`+ PreservedKeys []string `json:"preserved_keys"`+ }+ if err := json.Unmarshal([]byte(details), &auditFields); err != nil {+ t.Fatalf("failed to decode audit details: %v (raw=%s)", err, details)+ }+ if !reflect.DeepEqual(auditFields.AddedKeys, []string{"BRAND_NEW"}) {+ t.Errorf("added_keys: got %v, want [BRAND_NEW]; raw=%s", auditFields.AddedKeys, details)+ }+ if !reflect.DeepEqual(auditFields.ChangedKeys, []string{"ALSO"}) {+ t.Errorf("changed_keys: got %v, want [ALSO]; raw=%s", auditFields.ChangedKeys, details)+ }+ if !reflect.DeepEqual(auditFields.PreservedKeys, []string{"KEEP_ME"}) {+ t.Errorf("preserved_keys: got %v, want [KEEP_ME]; raw=%s", auditFields.PreservedKeys, details)+ }+ // Audit must never contain values.+ for _, leak := range []string{"real-secret", "another-secret", "rotated", "fresh"} {+ if strings.Contains(details, leak) {+ t.Errorf("audit details leaked value %q: %s", leak, details)+ }+ }+}++func TestUpdateAgent_RejectsCustomEnvInBody(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID := createHandlerTestAgent(t, "update-no-env-agent", nil)+ if _, err := testPool.Exec(ctx, `UPDATE agent SET custom_env = '{"PRE":"existing"}' WHERE id = $1`, agentID); err != nil {+ t.Fatalf("failed to seed custom_env: %v", err)+ }++ // Sending custom_env via the generic PUT /api/agents/{id} must fail+ // loudly with a 400 — see the comment on the rejection in agent.go.+ // Silently dropping the field used to make scripted clients believe+ // they had rotated a secret when nothing actually happened.+ body := map[string]any{+ "description": "still updating description",+ "custom_env": map[string]string{"INJECTED": "should-not-stick"},+ }+ req := newRequest(http.MethodPut, "/api/agents/"+agentID, body)+ req = withURLParam(req, "id", agentID)+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("UpdateAgent: expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "custom_env") || !strings.Contains(w.Body.String(), "/env") {+ t.Errorf("error body should mention custom_env and the env endpoint; got %s", w.Body.String())+ }++ // The stored env must be untouched by the rejected request.+ var stored string+ if err := testPool.QueryRow(ctx, `SELECT custom_env::text FROM agent WHERE id = $1`, agentID).Scan(&stored); err != nil {+ t.Fatalf("failed to read custom_env: %v", err)+ }+ if !strings.Contains(stored, `"PRE": "existing"`) && !strings.Contains(stored, `"PRE":"existing"`) {+ t.Errorf("UpdateAgent must NOT touch custom_env; got %q", stored)+ }+ if strings.Contains(stored, "INJECTED") {+ t.Errorf("UpdateAgent should have rejected custom_env in body; got %q", stored)+ }+}++// TestMergeAgentEnv_PureFunction exercises the diff/sentinel logic+// without the DB round-trip — keeps the contract front-and-centre in+// case someone refactors the handler later.+func TestMergeAgentEnv_PureFunction(t *testing.T) {+ cases := []struct {+ name string+ existing map[string]string+ request map[string]string+ want map[string]string+ audit envAudit+ }{+ {+ name: "preserve sentinel",+ existing: map[string]string{"A": "real"},+ request: map[string]string{"A": "****"},+ want: map[string]string{"A": "real"},+ audit: envAudit{preserved: []string{"A"}},+ },+ {+ name: "drop sentinel for missing key",+ existing: map[string]string{},+ request: map[string]string{"A": "****"},+ want: map[string]string{},+ audit: envAudit{},+ },+ {+ name: "add new key",+ existing: map[string]string{},+ request: map[string]string{"B": "v"},+ want: map[string]string{"B": "v"},+ audit: envAudit{added: []string{"B"}},+ },+ {+ name: "change existing value",+ existing: map[string]string{"B": "old"},+ request: map[string]string{"B": "new"},+ want: map[string]string{"B": "new"},+ audit: envAudit{changed: []string{"B"}},+ },+ {+ name: "remove key absent from request",+ existing: map[string]string{"B": "v"},+ request: map[string]string{},+ want: map[string]string{},+ audit: envAudit{removed: []string{"B"}},+ },+ {+ name: "noop when value unchanged",+ existing: map[string]string{"B": "same"},+ request: map[string]string{"B": "same"},+ want: map[string]string{"B": "same"},+ audit: envAudit{},+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, audit := mergeAgentEnv(tc.existing, tc.request)+ if !reflect.DeepEqual(got, tc.want) {+ t.Errorf("merged map: got %v, want %v", got, tc.want)+ }+ if !reflect.DeepEqual(audit, tc.audit) {+ t.Errorf("audit: got %+v, want %+v", audit, tc.audit)+ }+ })+ }+}++// Compile-time guard: AgentResponse must NOT carry the legacy env+// fields. Reintroducing them is a security regression — this test+// fails to compile rather than fails at runtime so reviewers see the+// breakage in the diff. Kept as a runtime test because the package+// boundary makes a struct-tag introspection cheap and obvious.+func TestAgentResponseShape_HasNoLegacyEnvFields(t *testing.T) {+ typ := reflect.TypeOf(AgentResponse{})+ for i := 0; i < typ.NumField(); i++ {+ f := typ.Field(i)+ tag := strings.Split(f.Tag.Get("json"), ",")[0]+ switch tag {+ case "custom_env", "custom_env_redacted", "custom_env_redacted_reason":+ t.Errorf("AgentResponse must not carry %q field (MUL-2600)", tag)+ }+ }+}++// TestUpdateAgent_RedactsMcpConfigForAgentActor closes the second leg+// of MUL-2600 review #2: an agent process with a task token (or with+// the X-Actor-Source server marker) must not be able to scrape another+// agent's mcp_config via an unrelated mutation response. Even when the+// host PAT would otherwise satisfy canManageAgent, the response body+// must come back with mcp_config redacted.+func TestUpdateAgent_RedactsMcpConfigForAgentActor(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ // The target agent has a populated mcp_config that historically would+ // be leaked back via the UpdateAgent / ArchiveAgent / RestoreAgent+ // HTTP response.+ target := createHandlerTestAgent(t, "mut-mcp-target", []byte(`{"server":"secret-config"}`))++ // A second agent acts as the "calling" agent process whose task+ // token authenticated the request. It is registered in the same+ // workspace so resolveActor recognises X-Agent-ID as valid.+ caller := createHandlerTestAgent(t, "mut-mcp-caller", nil)+ taskID := insertHandlerTestTask(t, caller)+ desc := "trivial mutation that should NOT leak target mcp_config"+ req := newRequest(http.MethodPut, "/api/agents/"+target, map[string]any{+ "description": desc,+ })+ req = withURLParam(req, "id", target)+ // Simulate a task-token-authenticated agent request. The auth+ // middleware would normally set these; we mimic both the modern+ // path (X-Actor-Source) and the legacy header pair so the test is+ // resilient to either resolveActor branch.+ req.Header.Set("X-Actor-Source", "task_token")+ req.Header.Set("X-Agent-ID", caller)+ req.Header.Set("X-Task-ID", taskID)+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, req)if w.Code != http.StatusOK {- t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())}var resp AgentResponse- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {- t.Fatalf("failed to decode response: %v", err)+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ // The response contract keeps `mcp_config` always-present so clients+ // can distinguish "no config" vs "redacted" via the companion flag.+ // `json.RawMessage` of a JSON null decodes to the literal bytes+ // `null`, not Go nil — so check for "no secret-bearing content"+ // rather than `!= nil`.+ if len(resp.McpConfig) > 0 && !bytes.Equal(bytes.TrimSpace(resp.McpConfig), []byte("null")) {+ t.Errorf("UpdateAgent response leaked mcp_config to agent actor: %s", string(resp.McpConfig))+ }+ if !resp.McpConfigRedacted {+ t.Errorf("UpdateAgent response should set mcp_config_redacted=true for agent actor")+ }+}++// TestUpdateAgent_KeepsMcpConfigForMemberActor is the matching positive+// test — a normal member request (owner/admin) still receives the full+// mcp_config in the mutation response, so the redaction does not+// accidentally regress the legitimate Web admin flow.+func TestUpdateAgent_KeepsMcpConfigForMemberActor(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")}- if resp.CustomEnvRedacted {- t.Error("expected custom_env_redacted to be false")++ target := createHandlerTestAgent(t, "mut-mcp-member", []byte(`{"server":"member-visible"}`))++ req := newRequest(http.MethodPut, "/api/agents/"+target, map[string]any{+ "description": "owner-visible mutation",+ })+ req = withURLParam(req, "id", target)+ w := httptest.NewRecorder()+ testHandler.UpdateAgent(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgent: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var resp AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)}- if resp.CustomEnvRedactedReason != "" {- t.Errorf("expected custom_env_redacted_reason to be empty, got %q", resp.CustomEnvRedactedReason)+ if resp.McpConfig == nil {+ t.Errorf("UpdateAgent response should keep mcp_config for member actor; got nil")}- if resp.CustomEnv["SECRET_KEY"] != "super-secret" {- t.Errorf("expected SECRET_KEY to be visible, got %q", resp.CustomEnv["SECRET_KEY"])+ if resp.McpConfigRedacted {+ t.Errorf("UpdateAgent response should NOT mark mcp_config redacted for member actor")}}++// insertHandlerTestTask creates an in_progress task for the given+// agent so resolveActor's GetAgentTask lookup succeeds without+// dragging the full TaskService into the test.+func insertHandlerTestTask(t *testing.T, agentID string) string {+ t.Helper()+ ctx := context.Background()+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority)+ VALUES ($1, $2, 'running', 0)+ RETURNING id+ `, agentID, handlerTestRuntimeID(t)).Scan(&taskID); err != nil {+ t.Fatalf("insert test task: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ })+ return taskID+}++// Defence-in-depth: spot-check that the package compiles a small+// fmt.Sprintf so accidental imports stay tidy.+var _ = fmt.Sprintfdiff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex b9d3b8b4d0..6883ff1bcd 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -17,6 +17,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"+ "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/service"@@ -1527,6 +1528,44 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {)}+ // Mint a task-scoped `mat_` token bound to (agent, task, workspace,+ // owner). The daemon will inject this as MULTICA_TOKEN into the agent+ // process instead of its own credential, so any API call the agent+ // makes — even one that strips X-Agent-ID / X-Task-ID headers — is+ // recognized server-side as actor=agent, closing the lateral-movement+ // path on owner-only endpoints (e.g. `/api/agents/{id}/env`). MUL-2600.+ //+ // Skip silently when the runtime has no owning user (cloud / system+ // runtimes installed before this PR) — the response carries no+ // `auth_token`, and the daemon falls back to its existing credential.+ // Token expires after the queue/runtime upper bound (24h) so it survives+ // long-running tasks but cannot outlive a forgotten one.+ if runtime.OwnerID.Valid {+ tokenStr, terr := auth.GenerateAgentTaskToken()+ if terr != nil {+ outcome = "error_token"+ slog.Error("task claim: failed to generate agent task token",+ "task_id", uuidToString(task.ID), "error", terr)+ writeError(w, http.StatusInternalServerError, "failed to mint task token")+ return+ }+ if _, terr := h.Queries.CreateTaskToken(r.Context(), db.CreateTaskTokenParams{+ TokenHash: auth.HashToken(tokenStr),+ TaskID: task.ID,+ AgentID: task.AgentID,+ WorkspaceID: parseUUID(resp.WorkspaceID),+ UserID: runtime.OwnerID,+ ExpiresAt: pgtype.Timestamptz{Time: time.Now().Add(24 * time.Hour), Valid: true},+ }); terr != nil {+ outcome = "error_token"+ slog.Error("task claim: failed to persist agent task token",+ "task_id", uuidToString(task.ID), "error", terr)+ writeError(w, http.StatusInternalServerError, "failed to persist task token")+ return+ }+ resp.AuthToken = tokenStr+ }+slog.Info("task claimed by runtime", "task_id", uuidToString(task.ID), "runtime_id", runtimeID, "agent_id", uuidToString(task.AgentID), "prior_session", resp.PriorSessionID)writeJSON(w, http.StatusOK, map[string]any{"task": resp})}@@ -1643,6 +1682,16 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {h.emitIssueExecutedOnFirstCompletion(r, task)+ // Best-effort revoke of any agent task token minted at claim time.+ // The token would naturally expire at the 24h watermark and is also+ // cascaded on agent_task deletion, but eagerly deleting it on+ // completion shrinks the window where a compromised agent process+ // can keep making API calls after its task finishes. Failure here is+ // non-fatal; the expiry / cascade are the durable guards.+ if err := h.Queries.DeleteTaskTokensByTask(r.Context(), task.ID); err != nil {+ slog.Warn("complete task: failed to revoke task tokens", "task_id", uuidToString(task.ID), "error", err)+ }+slog.Info("task completed", "task_id", taskID, "agent_id", uuidToString(task.AgentID))writeJSON(w, http.StatusOK, taskToResponse(*task))}@@ -1776,6 +1825,13 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {return}+ // Best-effort revoke of the mat_ task token minted at claim. Same+ // rationale as CompleteTask — eager deletion shrinks the post-+ // terminal window. The 24h expiry / cascade are the durable guards.+ if err := h.Queries.DeleteTaskTokensByTask(r.Context(), task.ID); err != nil {+ slog.Warn("fail task: failed to revoke task tokens", "task_id", uuidToString(task.ID), "error", err)+ }+slog.Info("task failed", "task_id", taskID, "agent_id", uuidToString(task.AgentID), "task_error", req.Error, "failure_reason", req.FailureReason)writeJSON(w, http.StatusOK, taskToResponse(*task))}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 5727a34f0c..d6a40baee1 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -274,20 +274,31 @@ func requestUserID(r *http.Request) string {}// resolveActor determines whether the request is from an agent or a human member.-// To claim "agent" identity the request MUST carry both X-Agent-ID and a valid-// X-Task-ID, and the task must belong to the claimed agent. Otherwise we fall-// back to "member" using the user ID from the session.+//+// First-class signal: X-Actor-Source set to "task_token" means the request+// authenticated via an `mat_` task-scoped token. The auth middleware sets+// that header (and stripped any client-supplied value first), so it is+// authoritative — the bound (agent_id, task_id) cannot be forged or+// stripped by the agent process. This is the path MUL-2600 relies on to+// reject agent-process traffic on owner-only endpoints.+//+// Fallback signal (legacy CLI / member-token paths): the request MUST+// carry both X-Agent-ID and a valid X-Task-ID, and the task must belong+// to the claimed agent. Otherwise we fall back to "member".//// X-Agent-ID alone is not trusted: any workspace member can guess or observe// an agent's UUID, and a member-supplied X-Agent-ID would otherwise let that// member impersonate the agent and bypass the private-agent gate (#2359-// review). The daemon always pairs the two headers — X-Agent-ID names the-// agent claiming the request, X-Task-ID names the in-flight task that-// authorizes it — so requiring both has no effect on legitimate agent-// callers but closes the impersonation path.+// review). The daemon always pairs the two headers, so requiring both has+// no effect on legitimate agent callers but closes the impersonation path.//// Returns ("agent", agentID) on success, ("member", userID) otherwise.func (h *Handler) resolveActor(r *http.Request, userID, workspaceID string) (actorType, actorID string) {+ if r.Header.Get("X-Actor-Source") == "task_token" {+ // Server-set header — auth middleware also forced X-Agent-ID+ // from the token row. Trust it directly without re-querying.+ return "agent", r.Header.Get("X-Agent-ID")+ }agentID := r.Header.Get("X-Agent-ID")if agentID == "" {return "member", userIDdiff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.goindex 8eeced0cbe..38146c3486 100644--- a/server/internal/middleware/auth.go+++ b/server/internal/middleware/auth.go@@ -30,6 +30,15 @@ func uuidToString(u pgtype.UUID) string { return util.UUIDToString(u) }func Auth(queries *db.Queries, patCache *auth.PATCache) func(http.Handler) http.Handler {return func(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // X-Actor-Source is server-set only — any value supplied by+ // the client is untrusted and discarded before the auth+ // branches run. Only the mat_ branch below re-sets it. This+ // is what prevents a client from sending a normal mul_ PAT+ // plus a forged `X-Actor-Source: member` (or anything else)+ // to convince a downstream handler that its request came+ // from a non-task-token path.+ r.Header.Del("X-Actor-Source")+tokenString, fromCookie := extractToken(r)if tokenString == "" {slog.Debug("auth: no token found", "path", r.URL.Path)@@ -44,6 +53,42 @@ func Auth(queries *db.Queries, patCache *auth.PATCache) func(http.Handler) http.return}+ // Agent task token: "mat_" prefix. Minted by the server at+ // task-claim time and injected by the daemon into the agent+ // process. Authoritative for actor identity — the bound+ // (user_id, agent_id, task_id, workspace_id) triple is+ // written into request headers here, OVERRIDING whatever the+ // client sent, so a downstream actor-resolver cannot be+ // tricked by a client that strips or forges X-Agent-ID /+ // X-Task-ID. Owner-only endpoints (e.g. agent env+ // management) reject requests authenticated this way; see+ // `actorSourceFromRequest`. MUL-2600.+ if strings.HasPrefix(tokenString, "mat_") {+ if queries == nil {+ http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)+ return+ }+ hash := auth.HashToken(tokenString)+ tt, err := queries.GetTaskTokenByHash(r.Context(), hash)+ if err != nil {+ slog.Warn("auth: invalid task token", "path", r.URL.Path, "error", err)+ http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)+ return+ }+ r.Header.Set("X-User-ID", uuidToString(tt.UserID))+ r.Header.Set("X-Agent-ID", uuidToString(tt.AgentID))+ r.Header.Set("X-Task-ID", uuidToString(tt.TaskID))+ r.Header.Set("X-Workspace-ID", uuidToString(tt.WorkspaceID))+ // X-Actor-Source flags the auth path so resolveActor and+ // any owner-only handler can deny without re-querying the+ // token table. The value "task_token" is the only signal+ // this header is allowed to carry — strip anything else a+ // client tried to send.+ r.Header.Set("X-Actor-Source", "task_token")+ next.ServeHTTP(w, r)+ return+ }+// PAT: tokens starting with "mul_"if strings.HasPrefix(tokenString, "mul_") {hash := auth.HashToken(tokenString)diff --git a/server/internal/middleware/auth_test.go b/server/internal/middleware/auth_test.goindex bc4abfc6fd..a755f666de 100644--- a/server/internal/middleware/auth_test.go+++ b/server/internal/middleware/auth_test.go@@ -228,6 +228,39 @@ func TestAuth_InvalidPAT(t *testing.T) {}}+// TestAuth_StripsClientSuppliedActorSource enforces the invariant that+// X-Actor-Source is a server-only header: any value the client sends+// must be discarded before downstream code sees it. Without this+// guarantee a client carrying a normal mul_ PAT could supply a forged+// `X-Actor-Source: task_token` (or any other value) to fool a handler+// into treating the request differently — exactly the kind of trust+// boundary MUL-2600 introduces.+func TestAuth_StripsClientSuppliedActorSource(t *testing.T) {+ var gotActorSource string+ mw := Auth(nil, nil)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ gotActorSource = r.Header.Get("X-Actor-Source")+ w.WriteHeader(http.StatusOK)+ }))++ token := generateToken(validClaims(), auth.JWTSecret())+ req := httptest.NewRequest("GET", "/api/me", nil)+ req.Header.Set("Authorization", "Bearer "+token)+ // Client tries to forge the actor-source header. The middleware must+ // discard it before the JWT branch runs (which doesn't set it again+ // for human sessions).+ req.Header.Set("X-Actor-Source", "task_token")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotActorSource != "" {+ t.Fatalf("X-Actor-Source must be cleared on non-task-token paths, got %q", gotActorSource)+ }+}+// TestAuth_PATCacheHit pins the optimization: when the PAT cache already// holds an entry for this token, the middleware MUST NOT call into queries// — it short-circuits before the DB lookup and the last_used_at update.diff --git a/server/internal/middleware/workspace.go b/server/internal/middleware/workspace.goindex a30eaf8121..f663d2b3c0 100644--- a/server/internal/middleware/workspace.go+++ b/server/internal/middleware/workspace.go@@ -52,11 +52,13 @@ var errWorkspaceNotFound = errors.New("workspace not found")// themselves.//// Priority:-// 1. middleware-injected context (fast path for middleware-protected routes)-// 2. X-Workspace-Slug header → GetWorkspaceBySlug → UUID (post-refactor frontend)-// 3. ?workspace_slug query → GetWorkspaceBySlug → UUID-// 4. X-Workspace-ID header (CLI/daemon compat)-// 5. ?workspace_id query (CLI/daemon compat)+// 1. task-token binding (X-Actor-Source == "task_token") — authoritative,+// server-set, cannot be re-negotiated by the client (MUL-2600)+// 2. middleware-injected context (fast path for middleware-protected routes)+// 3. X-Workspace-Slug header → GetWorkspaceBySlug → UUID (post-refactor frontend)+// 4. ?workspace_slug query → GetWorkspaceBySlug → UUID+// 5. X-Workspace-ID header (CLI/daemon compat)+// 6. ?workspace_id query (CLI/daemon compat)//// Returns "" when no identifier was provided OR a slug was provided but// doesn't resolve to any workspace. Callers that need to distinguish "no@@ -64,6 +66,15 @@ var errWorkspaceNotFound = errors.New("workspace not found")// internal resolver instead — this helper collapses both cases to "" for// simpler handler-level checks.func ResolveWorkspaceIDFromRequest(r *http.Request, queries *db.Queries) string {+ // A mat_ task token is bound to exactly one workspace by the token+ // row. Auth middleware writes that workspace into X-Workspace-ID+ // after stripping any client-supplied X-Actor-Source. Any other+ // workspace identifier on the request (slug header/query, ID+ // query, URL param) is the agent trying to widen its blast+ // radius — ignore it.+ if r.Header.Get("X-Actor-Source") == "task_token" {+ return r.Header.Get("X-Workspace-ID")+ }if id := WorkspaceIDFromContext(r.Context()); id != "" {return id}@@ -92,12 +103,26 @@ type workspaceResolver func(r *http.Request) (string, error)// resolveWorkspaceUUID builds a resolver that accepts slug-first identification.//// Priority:-// 1. X-Workspace-Slug header / ?workspace_slug query → GetWorkspaceBySlug → UUID-// 2. X-Workspace-ID header / ?workspace_id query → UUID directly (CLI/daemon compat)+// 1. task-token binding (X-Actor-Source == "task_token") — authoritative,+// server-set; the agent cannot widen its workspace scope by passing a+// different slug/id (MUL-2600)+// 2. X-Workspace-Slug header / ?workspace_slug query → GetWorkspaceBySlug → UUID+// 3. X-Workspace-ID header / ?workspace_id query → UUID directly (CLI/daemon compat)//// TODO: cache slug→UUID lookup (slug is immutable, safe to cache with short TTL)func resolveWorkspaceUUID(queries *db.Queries) workspaceResolver {return func(r *http.Request) (string, error) {+ // Task-token-authenticated requests must operate on the+ // token's bound workspace. The auth middleware wrote that ID+ // into X-Workspace-ID; nothing the agent can put on the wire+ // (slug header/query, id query, URL param) can override it.+ if r.Header.Get("X-Actor-Source") == "task_token" {+ id := r.Header.Get("X-Workspace-ID")+ if id == "" {+ return "", errWorkspaceNotFound+ }+ return id, nil+ }// Slug path (preferred — frontend sends this after the URL refactor)if slug := r.URL.Query().Get("workspace_slug"); slug != "" {ws, err := queries.GetWorkspaceBySlug(r.Context(), slug)@@ -180,6 +205,20 @@ func buildMiddleware(queries *db.Queries, resolve workspaceResolver, roles []strreturn}+ // Final task-token binding check: even when the workspace+ // was resolved from a chi URL parameter+ // (RequireWorkspaceMemberFromURL), the agent must not be+ // allowed to operate on a workspace other than the one+ // stamped into its task token. This is the catch-all+ // behind resolveWorkspaceUUID's earlier check. MUL-2600.+ if r.Header.Get("X-Actor-Source") == "task_token" {+ bound := r.Header.Get("X-Workspace-ID")+ if bound == "" || workspaceID != bound {+ writeError(w, http.StatusForbidden, "task token is bound to a different workspace")+ return+ }+ }+userID := r.Header.Get("X-User-ID")if userID == "" {writeError(w, http.StatusUnauthorized, "user not authenticated")diff --git a/server/internal/middleware/workspace_test.go b/server/internal/middleware/workspace_test.goindex a23c3b4a2b..5f25b2f855 100644--- a/server/internal/middleware/workspace_test.go+++ b/server/internal/middleware/workspace_test.go@@ -146,6 +146,28 @@ func TestResolveWorkspaceIDFromRequest(t *testing.T) {},wantEmpty: true,},+ {+ // MUL-2600: a mat_ task token authenticates the request and+ // the auth middleware writes the token-bound workspace into+ // X-Workspace-ID along with X-Actor-Source=task_token. Any+ // other workspace identifier the agent puts on the wire — a+ // slug pointing at a sibling workspace, a different+ // workspace_id — must be ignored. Otherwise an agent could+ // route owner-token traffic at any workspace its host is+ // also a member of.+ name: "task_token actor: client-supplied slug/id cannot override token-bound workspace",+ setup: func(r *http.Request) {+ r.Header.Set("X-Actor-Source", "task_token")+ r.Header.Set("X-Workspace-ID", uuidA)+ // All of these should be ignored under task_token.+ r.Header.Set("X-Workspace-Slug", testResolverSlug)+ q := r.URL.Query()+ q.Set("workspace_slug", testResolverSlug)+ q.Set("workspace_id", uuidB)+ r.URL.RawQuery = q.Encode()+ },+ want: uuidA,+ },}for _, tc := range cases {diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex b163fafb08..f1417f5946 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -171,6 +171,16 @@ func (s *TaskService) captureTaskCancelled(ctx context.Context, task db.AgentTass.taskAnalyticsContext(ctx, task),taskDurationMS(task),))+ // Revoke any mat_ task tokens minted for this task. Cancellation is+ // a terminal transition, so the running agent process no longer+ // needs to call back; eagerly deleting the token closes the+ // window where a compromised process could keep authenticating+ // against the API until the 24h expiry. Failure is non-fatal — the+ // expiry / FK cascade are the durable guards. MUL-2600.+ if err := s.Queries.DeleteTaskTokensByTask(ctx, task.ID); err != nil {+ slog.Warn("cancel task: failed to revoke task tokens",+ "task_id", util.UUIDToString(task.ID), "error", err)+ }}func (s *TaskService) captureTaskEvent(ctx context.Context, event analytics.Event) {diff --git a/server/migrations/108_task_token.down.sql b/server/migrations/108_task_token.down.sqlnew file mode 100644index 0000000000..e94b346a94--- /dev/null+++ b/server/migrations/108_task_token.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS task_token;diff --git a/server/migrations/108_task_token.up.sql b/server/migrations/108_task_token.up.sqlnew file mode 100644index 0000000000..e058416e16--- /dev/null+++ b/server/migrations/108_task_token.up.sql@@ -0,0 +1,30 @@+-- task_token replaces the historical practice of injecting the daemon+-- owner's MULTICA_TOKEN (a workspace owner/admin PAT) into the agent+-- process. That practice gave the agent full owner privileges via+-- whatever credential the daemon happened to be using, which made+-- agent-resource secrets reachable from the agent (MUL-2600).+--+-- The daemon now mints a short-lived task-scoped token at task-claim+-- time and injects THAT into the agent. The server treats `mat_`+-- tokens as authoritative for actor identity (agent + task), so a+-- request from the agent process is recognised as actor=agent+-- regardless of whether the agent strips or forges X-Agent-ID /+-- X-Task-ID headers. Owner-only endpoints (`/api/agents/{id}/env`,+-- env-management CLI) consequently 403 on agent traffic.+CREATE TABLE task_token (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ token_hash TEXT NOT NULL,+ -- Bound triple: the only identity the agent can ever claim from+ -- this token. user_id is the daemon owner (kept so member-shaped+ -- read access still resolves correctly when the agent does+ -- legitimate reads), agent_id and task_id are server-derived.+ task_id UUID NOT NULL REFERENCES agent_task_queue(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL REFERENCES agent(id) ON DELETE CASCADE,+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,+ user_id UUID NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,+ expires_at TIMESTAMPTZ NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE UNIQUE INDEX idx_task_token_hash ON task_token(token_hash);+CREATE INDEX idx_task_token_task ON task_token(task_id);diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 004868b0b8..44848558fe 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -2292,6 +2292,53 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentreturn i, err}+const updateAgentCustomEnv = `-- name: UpdateAgentCustomEnv :one+UPDATE agent+SET custom_env = $2, updated_at = now()+WHERE id = $1+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level+`++type UpdateAgentCustomEnvParams struct {+ ID pgtype.UUID `json:"id"`+ CustomEnv []byte `json:"custom_env"`+}++// Replaces an agent's custom_env map wholesale. Used by the dedicated+// env-management endpoint (POST/PUT /api/agents/{id}/env), which is the+// only post-creation write path for env. UpdateAgent has been stripped+// of custom_env handling so all env mutations flow through here and the+// handler's audit-log + **** sentinel guard.+func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCustomEnvParams) (Agent, error) {+ row := q.db.QueryRow(ctx, updateAgentCustomEnv, arg.ID, arg.CustomEnv)+ var i Agent+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.Name,+ &i.AvatarUrl,+ &i.RuntimeMode,+ &i.RuntimeConfig,+ &i.Visibility,+ &i.Status,+ &i.MaxConcurrentTasks,+ &i.OwnerID,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.Description,+ &i.RuntimeID,+ &i.Instructions,+ &i.ArchivedAt,+ &i.ArchivedBy,+ &i.CustomEnv,+ &i.CustomArgs,+ &i.McpConfig,+ &i.Model,+ &i.ThinkingLevel,+ )+ return i, err+}+const updateAgentStatus = `-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1diff --git a/server/pkg/db/generated/contact_sales.sql.go b/server/pkg/db/generated/contact_sales.sql.goindex e73a1ef98b..2dc9001fc0 100644--- a/server/pkg/db/generated/contact_sales.sql.go+++ b/server/pkg/db/generated/contact_sales.sql.go@@ -1,6 +1,6 @@// Code generated by sqlc. DO NOT EDIT.// versions:-// sqlc v1.30.0+// sqlc v1.31.1// source: contact_sales.sqlpackage dbdiff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex c78177312f..34a152698a 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -525,6 +525,17 @@ type TaskMessage struct {CreatedAt pgtype.Timestamptz `json:"created_at"`}+type TaskToken struct {+ ID pgtype.UUID `json:"id"`+ TokenHash string `json:"token_hash"`+ TaskID pgtype.UUID `json:"task_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+}+type TaskUsage struct {ID pgtype.UUID `json:"id"`TaskID pgtype.UUID `json:"task_id"`diff --git a/server/pkg/db/generated/task_token.sql.go b/server/pkg/db/generated/task_token.sql.gonew file mode 100644index 0000000000..abd7e0cabc--- /dev/null+++ b/server/pkg/db/generated/task_token.sql.go@@ -0,0 +1,89 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: task_token.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const createTaskToken = `-- name: CreateTaskToken :one+INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)+VALUES ($1, $2, $3, $4, $5, $6)+RETURNING id, token_hash, task_id, agent_id, workspace_id, user_id, expires_at, created_at+`++type CreateTaskTokenParams struct {+ TokenHash string `json:"token_hash"`+ TaskID pgtype.UUID `json:"task_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ UserID pgtype.UUID `json:"user_id"`+ ExpiresAt pgtype.Timestamptz `json:"expires_at"`+}++func (q *Queries) CreateTaskToken(ctx context.Context, arg CreateTaskTokenParams) (TaskToken, error) {+ row := q.db.QueryRow(ctx, createTaskToken,+ arg.TokenHash,+ arg.TaskID,+ arg.AgentID,+ arg.WorkspaceID,+ arg.UserID,+ arg.ExpiresAt,+ )+ var i TaskToken+ err := row.Scan(+ &i.ID,+ &i.TokenHash,+ &i.TaskID,+ &i.AgentID,+ &i.WorkspaceID,+ &i.UserID,+ &i.ExpiresAt,+ &i.CreatedAt,+ )+ return i, err+}++const deleteExpiredTaskTokens = `-- name: DeleteExpiredTaskTokens :exec+DELETE FROM task_token WHERE expires_at <= now()+`++func (q *Queries) DeleteExpiredTaskTokens(ctx context.Context) error {+ _, err := q.db.Exec(ctx, deleteExpiredTaskTokens)+ return err+}++const deleteTaskTokensByTask = `-- name: DeleteTaskTokensByTask :exec+DELETE FROM task_token WHERE task_id = $1+`++func (q *Queries) DeleteTaskTokensByTask(ctx context.Context, taskID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteTaskTokensByTask, taskID)+ return err+}++const getTaskTokenByHash = `-- name: GetTaskTokenByHash :one+SELECT id, token_hash, task_id, agent_id, workspace_id, user_id, expires_at, created_at FROM task_token+WHERE token_hash = $1 AND expires_at > now()+`++func (q *Queries) GetTaskTokenByHash(ctx context.Context, tokenHash string) (TaskToken, error) {+ row := q.db.QueryRow(ctx, getTaskTokenByHash, tokenHash)+ var i TaskToken+ err := row.Scan(+ &i.ID,+ &i.TokenHash,+ &i.TaskID,+ &i.AgentID,+ &i.WorkspaceID,+ &i.UserID,+ &i.ExpiresAt,+ &i.CreatedAt,+ )+ return i, err+}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 81ee1fe79a..1a8d014065 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -58,6 +58,17 @@ UPDATE agent SET mcp_config = NULL, updated_at = now()WHERE id = $1RETURNING *;+-- name: UpdateAgentCustomEnv :one+-- Replaces an agent's custom_env map wholesale. Used by the dedicated+-- env-management endpoint (POST/PUT /api/agents/{id}/env), which is the+-- only post-creation write path for env. UpdateAgent has been stripped+-- of custom_env handling so all env mutations flow through here and the+-- handler's audit-log + **** sentinel guard.+UPDATE agent+SET custom_env = $2, updated_at = now()+WHERE id = $1+RETURNING *;+-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1diff --git a/server/pkg/db/queries/task_token.sql b/server/pkg/db/queries/task_token.sqlnew file mode 100644index 0000000000..f9eea21459--- /dev/null+++ b/server/pkg/db/queries/task_token.sql@@ -0,0 +1,14 @@+-- name: CreateTaskToken :one+INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)+VALUES ($1, $2, $3, $4, $5, $6)+RETURNING *;++-- name: GetTaskTokenByHash :one+SELECT * FROM task_token+WHERE token_hash = $1 AND expires_at > now();++-- name: DeleteTaskTokensByTask :exec+DELETE FROM task_token WHERE task_id = $1;++-- name: DeleteExpiredTaskTokens :exec+DELETE FROM task_token WHERE expires_at <= now();