Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agents): allow agent owners to manage their own agent's env (MUL-5438) (#6080)
Bohan Jiangcc5ee169f061
diff --git a/apps/docs/content/docs/agents-create.ja.mdx b/apps/docs/content/docs/agents-create.ja.mdxindex e8eaf01eb7..863188f7d5 100644--- a/apps/docs/content/docs/agents-create.ja.mdx+++ b/apps/docs/content/docs/agents-create.ja.mdx@@ -64,7 +64,7 @@ ANTHROPIC_BASE_URL = https://my-proxy.example.comシステムにとって重要な変数は上書きできません。`PATH`、`HOME`、`USER`、`SHELL`、`TERM`、`CODEX_HOME`、そして `MULTICA_*` で始まるすべてのキーは、デーモンが静かに無視します(警告ログは残しますが、エラーは発生しません)。<Callout type="warning">-**`custom_env` の値は Multica サーバーのデータベースに平文で保存されます。** エージェントの list/get レスポンスには環境変数の値がまったく含まれなくなり、不透明な個数だけが返されます。実際の値を読み取るには、ワークスペースの owner または admin が、専用で監査される `GET /api/agents/{id}/env` エンドポイント(CLI: `multica agent env get <id>`)を呼び出す必要があります。タスクを実行中のエージェントは、ホストの owner 資格情報を使って他のエージェントの環境変数を明らかにすることはできません。このエンドポイントはエージェントアクターのセッションを拒否します。+**`custom_env` の値は Multica サーバーのデータベースに平文で保存されます。** エージェントの list/get レスポンスには環境変数の値がまったく含まれなくなり、不透明な個数だけが返されます。実際の値を読み取るには、そのエージェント自身の owner、またはワークスペースの owner / admin が、専用で監査される `GET /api/agents/{id}/env` エンドポイント(CLI: `multica agent env get <id>`)を呼び出す必要があります。タスクを実行中のエージェントは、ホストの owner 資格情報を使って他のエージェントの環境変数を明らかにすることはできません。同じ人物が owner のエージェントであっても同様です。このエンドポイントはエージェントアクターのセッションを拒否します。**価値の高いシークレットは `custom_env` に入れないでください**(本番データベースのパスワード、root レベルのトークンなど)。エージェントには**権限範囲が限定された専用の資格情報**(読み取り専用 API キー、単一スコープの PAT)を使用し、定期的にローテーションしてください。データベースのバックアップと DB 監査は、依然として意味のある露出面として残ります。</Callout>diff --git a/apps/docs/content/docs/agents-create.ko.mdx b/apps/docs/content/docs/agents-create.ko.mdxindex fe524c73da..6ac299d5b4 100644--- a/apps/docs/content/docs/agents-create.ko.mdx+++ b/apps/docs/content/docs/agents-create.ko.mdx@@ -64,7 +64,7 @@ ANTHROPIC_BASE_URL = https://my-proxy.example.com시스템에 핵심적인 변수는 재정의할 수 없습니다. `PATH`, `HOME`, `USER`, `SHELL`, `TERM`, `CODEX_HOME`, 그리고 `MULTICA_*`로 시작하는 모든 키는 데몬이 조용히 무시합니다(경고 로그는 남기지만 오류는 발생하지 않습니다).<Callout type="warning">-**`custom_env`의 값은 Multica 서버 데이터베이스에 평문으로 저장됩니다.** 에이전트 list/get 응답은 더 이상 환경 변수 값을 전혀 포함하지 않으며, 불투명한 개수만 반환합니다. 실제 값을 읽으려면 워크스페이스 owner 또는 admin이 전용으로 감사되는 `GET /api/agents/{id}/env` 엔드포인트(CLI: `multica agent env get <id>`)를 호출해야 합니다. 작업을 실행 중인 에이전트는 호스트의 owner 자격 증명을 이용해 다른 에이전트의 환경 변수를 드러낼 수 없습니다. 이 엔드포인트는 에이전트 액터 세션을 거부합니다.+**`custom_env`의 값은 Multica 서버 데이터베이스에 평문으로 저장됩니다.** 에이전트 list/get 응답은 더 이상 환경 변수 값을 전혀 포함하지 않으며, 불투명한 개수만 반환합니다. 실제 값을 읽으려면 해당 에이전트 자신의 owner 또는 워크스페이스 owner / admin이 전용으로 감사되는 `GET /api/agents/{id}/env` 엔드포인트(CLI: `multica agent env get <id>`)를 호출해야 합니다. 작업을 실행 중인 에이전트는 호스트의 owner 자격 증명을 이용해 다른 에이전트의 환경 변수를 드러낼 수 없으며, 같은 사람이 owner인 에이전트라도 마찬가지입니다. 이 엔드포인트는 에이전트 액터 세션을 거부합니다.**가치가 높은 secret은 `custom_env`에 넣지 마세요**(운영 데이터베이스 비밀번호, root 수준 토큰 등). 에이전트에는 **권한 범위가 제한된 전용 자격 증명**(읽기 전용 API 키, 단일 스코프 PAT)을 사용하고 정기적으로 교체하세요. 데이터베이스 백업과 DB 감사는 여전히 의미 있는 노출 표면으로 남아 있습니다.</Callout>diff --git a/apps/docs/content/docs/agents-create.mdx b/apps/docs/content/docs/agents-create.mdxindex 900176aff2..f272a46f25 100644--- a/apps/docs/content/docs/agents-create.mdx+++ b/apps/docs/content/docs/agents-create.mdx@@ -64,7 +64,7 @@ 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.** 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.+**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 the agent's own owner — or a workspace owner/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, not even on an agent the same human owns — 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. Database backups and DB audits remain a meaningful exposure surface.</Callout>diff --git a/apps/docs/content/docs/agents-create.zh.mdx b/apps/docs/content/docs/agents-create.zh.mdxindex c6d9b6d603..0a1fcf0de2 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 服务器的数据库里是明文存储的。** agent list/get 接口不再返回任何 env 值——只返回键的数量。读取真实值需要 workspace owner / admin 调用专用且会审计的 `GET /api/agents/{id}/env`(CLI: `multica agent env get <id>`)。正在执行任务的智能体即便宿主是 owner,也无法借此读取其它智能体的 env——这个接口拒绝 agent-actor 会话。数据库备份、DB 审计里仍然能看到真实值。+**`custom_env` 的值在 Multica 服务器的数据库里是明文存储的。** agent list/get 接口不再返回任何 env 值——只返回键的数量。读取真实值需要该智能体自己的 owner、或 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>diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 0c82c8142b..1a2e42722d 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1169,10 +1169,10 @@ export class ApiClient {}/**- * 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.+ * Returns the plaintext `custom_env` map for an agent. Admits the+ * agent's owner or a workspace owner/admin (MUL-5438); 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`);@@ -1182,9 +1182,9 @@ export class ApiClient {* 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.+ * placeholder. Admits the agent's owner or a workspace owner/admin+ * (MUL-5438); 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`, {diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 6fe333b160..bc67bece6b 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -384,7 +384,7 @@ export interface Agent {* 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.+ * endpoint (agent owner or workspace owner/admin, 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@@ -649,8 +649,9 @@ export interface UpdateAgentRequest {/*** 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+ * `PUT /api/agents/{id}/env` — that path admits the agent owner or a+ * workspace owner/admin, 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.diff --git a/packages/views/agents/components/agent-overview-pane.test.tsx b/packages/views/agents/components/agent-overview-pane.test.tsxindex d3cf69574e..4d96ce756d 100644--- a/packages/views/agents/components/agent-overview-pane.test.tsx+++ b/packages/views/agents/components/agent-overview-pane.test.tsx@@ -122,7 +122,10 @@ function makeRuntime(provider: string): AgentRuntime {};}-function renderPane(runtimes: AgentRuntime[]) {+function renderPane(+ runtimes: AgentRuntime[],+ { canEdit = true }: { canEdit?: boolean } = {},+) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});@@ -145,7 +148,7 @@ function renderPane(runtimes: AgentRuntime[]) {runtimes={runtimes}members={[]}onUpdate={vi.fn().mockResolvedValue(undefined)}- canEdit+ canEdit={canEdit}/></QueryClientProvider></NavigationProvider>@@ -241,3 +244,24 @@ describe("AgentOverviewPane Settings navigation", () => {expect(screen.getByRole("tab", { name: /^Access$/i })).toBeInTheDocument();});});++describe("AgentOverviewPane Environment tab visibility", () => {+ it("shows the Environment tab to someone who can manage the agent", () => {+ renderPane([makeRuntime("claude")]);+ openSettings();+ expect(+ screen.getByRole("tab", { name: /^Environment$/i }),+ ).toBeInTheDocument();+ });++ it("hides the Environment tab from users who cannot manage the agent", () => {+ // The env endpoints admit the agent owner or a workspace owner/admin+ // (MUL-5438) — the rule `canEdit` already encodes. Anyone else who opens+ // the tab hits a guaranteed 403 on "Reveal & edit".+ renderPane([makeRuntime("claude")], { canEdit: false });+ openSettings();+ expect(+ screen.queryByRole("tab", { name: /^Environment$/i }),+ ).not.toBeInTheDocument();+ });+});diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsxindex 096c46a571..dad3fa20b5 100644--- a/packages/views/agents/components/agent-overview-pane.tsx+++ b/packages/views/agents/components/agent-overview-pane.tsx@@ -201,10 +201,17 @@ export function AgentOverviewPane({const visibleSettingsTabs = useMemo(() =>- SETTINGS_TABS.filter(- (tab) => tab.id !== "runtime_config" || runtime?.provider === "openclaw",- ),- [runtime?.provider],+ SETTINGS_TABS.filter((tab) => {+ // Env is the only settings tab backed by a secret-bearing endpoint.+ // GET/PUT /api/agents/{id}/env admits the agent owner or a workspace+ // owner/admin (MUL-5438) — the same rule `canEdit` encodes — so+ // showing the tab to anyone else guarantees a 403 on "Reveal & edit".+ // The server stays the boundary; this only removes a dead entry point.+ if (tab.id === "env") return canEdit;+ if (tab.id === "runtime_config") return runtime?.provider === "openclaw";+ return true;+ }),+ [canEdit, runtime?.provider],);const visibleViews = useMemo(diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 802585b558..c3e7095ca7 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -97,14 +97,14 @@ var agentEnvCmd = &cobra.Command{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)",+ Short: "Print an agent's custom_env as a JSON map (agent owner or workspace owner/admin; 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)",+ Short: "Replace an agent's custom_env (agent owner or workspace owner/admin; values equal to **** preserve the existing entry)",Args: exactArgs(1),RunE: runAgentEnvSet,}@@ -190,8 +190,9 @@ func init() {agentUpdateCmd.Flags().String("service-tier", "", "New Codex execution service tier from the selected model's runtime catalog. Pass an empty string to clear and inherit local Codex configuration.")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.")// 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.+ // `multica agent env set <id>` — that path admits the agent owner or a+ // workspace owner/admin, denies agent actors, and writes a persisted+ // audit trail.//// mcp_config, unlike custom_env, IS updatable here: it is persisted// through the generic UpdateAgent endpoint (there is no dedicateddiff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 11d5a95989..857d7af5c3 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1269,9 +1269,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Put("/skills/{skillId}/enabled", h.SetAgentSkillEnabled)r.Put("/runtime-skills/enabled", h.SetAgentRuntimeSkillEnabled)r.Delete("/skills/{skillId}", h.RemoveAgentSkill)- // Dedicated env-management endpoint. Owner/admin only;- // agent actors are denied. Every reveal / write is- // audited to activity_log. See MUL-2600 and+ // Dedicated env-management endpoint. Admits the agent+ // owner or a workspace owner/admin; agent actors are+ // denied. Every reveal / write is audited to+ // activity_log. See MUL-2600, MUL-5438 and// internal/handler/agent_env.go.r.Get("/env", h.GetAgentEnv)r.Put("/env", h.UpdateAgentEnv)diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 366d2e2f83..cb90c5969c 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -120,8 +120,8 @@ func agentToResponse(a db.Agent) AgentResponse {// 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).+ // the caller must hit GET /api/agents/{id}/env (agent owner or+ // workspace owner/admin, audited).envKeyCount := 0if a.CustomEnv != nil {var customEnv map[string]string@@ -1289,9 +1289,10 @@ type UpdateAgentRequest struct {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+ // Use `PUT /api/agents/{id}/env` for env changes — that path admits+ // the agent owner or a workspace owner/admin, 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@@ -1527,8 +1528,9 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {// `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.+ // /api/agents/{id}/env` — that endpoint admits the agent owner or a+ // workspace owner/admin, 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`)")returndiff --git a/server/internal/handler/agent_env.go b/server/internal/handler/agent_env.goindex 37baccc771..90cc6f5300 100644--- a/server/internal/handler/agent_env.go+++ b/server/internal/handler/agent_env.go@@ -55,11 +55,21 @@ type UpdateAgentEnvRequest struct {//// 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.+// owner, or the very human who owns the target agent — 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/admin, or the agent's own+// human owner (MUL-5438).+//+// Rule 2 used to be workspace-role-only, which made env the single+// endpoint in the agent permission model that ignored agent ownership:+// canManageAgent already lets the owner update/archive/restore, and+// canViewAgentSecrets already lets the owner read mcp_config. The+// asymmetry was worst on create — POST /api/agents accepts custom_env+// from any member — so a member could write secrets into their own+// agent and then never read or rotate them.//// Returns the loaded agent and the authenticated member on success.// All non-2xx branches write their own response and return ok=false.@@ -83,14 +93,38 @@ func (h *Handler) authorizeAgentEnv(w http.ResponseWriter, r *http.Request) (db.return db.Agent{}, db.Member{}, false}- member, ok := h.requireWorkspaceRole(w, r, workspaceID, "agent not found", "owner", "admin")+ member, ok := h.requireWorkspaceRole(w, r, workspaceID, "agent not found", "owner", "admin", "member")if !ok {return db.Agent{}, db.Member{}, false}+ if !canManageAgentEnv(agent, member) {+ writeError(w, http.StatusForbidden, "only the agent owner or a workspace owner/admin can manage this agent's env")+ return db.Agent{}, db.Member{}, false+ }return agent, member, true}+// canManageAgentEnv is the pure half of the env authorization rule:+// a workspace owner/admin, or the human who owns the agent. Mirrors+// canManageAgent (update/archive) so a member who can manage an agent+// can also rotate its secrets.+//+// The owner comparison deliberately runs against member.UserID rather+// than requestUserID(r). agent.owner_id is nullable (migration 001) and+// uuidToString renders a NULL UUID as "", so comparing against a raw+// header — which can also be empty — would make every NULL-owner agent+// readable by anyone. member.UserID only exists after the membership+// lookup succeeded, and the empty-owner guard below closes the case+// from the other side as well.+func canManageAgentEnv(agent db.Agent, member db.Member) bool {+ if roleAllowed(member.Role, "owner", "admin") {+ return true+ }+ ownerID := uuidToString(agent.OwnerID)+ return ownerID != "" && ownerID == uuidToString(member.UserID)+}+// 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, neverdiff --git a/server/internal/handler/agent_env_permission_test.go b/server/internal/handler/agent_env_permission_test.gonew file mode 100644index 0000000000..e2aed78bcd--- /dev/null+++ b/server/internal/handler/agent_env_permission_test.go@@ -0,0 +1,256 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestCanManageAgentEnv_Pure exercises the predicate behind the env+// endpoints without a database. Ownership must count for a plain member+// (MUL-5438), workspace owner/admin must keep working, and a NULL+// agent.owner_id must never match anyone: the column is nullable and+// uuidToString renders a NULL UUID as "".+func TestCanManageAgentEnv_Pure(t *testing.T) {+ ownerUserID := "11111111-1111-1111-1111-111111111111"+ otherUserID := "22222222-2222-2222-2222-222222222222"++ owned := db.Agent{OwnerID: util.MustParseUUID(ownerUserID)}+ orphaned := db.Agent{} // owner_id IS NULL++ cases := []struct {+ name string+ agent db.Agent+ userID string+ role string+ want bool+ }{+ {"workspace owner, not agent owner", owned, otherUserID, "owner", true},+ {"workspace admin, not agent owner", owned, otherUserID, "admin", true},+ {"agent owner with member role", owned, ownerUserID, "member", true},+ {"agent owner with admin role", owned, ownerUserID, "admin", true},+ {"plain member, not agent owner", owned, otherUserID, "member", false},+ {"plain member with no role string", owned, otherUserID, "", false},+ {"null owner_id, plain member", orphaned, otherUserID, "member", false},+ {"null owner_id, workspace admin", orphaned, otherUserID, "admin", true},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ member := db.Member{UserID: util.MustParseUUID(tc.userID), Role: tc.role}+ if got := canManageAgentEnv(tc.agent, member); got != tc.want {+ t.Fatalf("canManageAgentEnv(owner=%q, user=%s, role=%s) = %v; want %v",+ uuidToString(tc.agent.OwnerID), tc.userID, tc.role, got, tc.want)+ }+ })+ }+}++// agentEnvOwnerFixture creates a plain (role=member) workspace member and+// an agent owned by that member, seeded with a known custom_env map. This+// is the shape a member creating their own agent produces: POST+// /api/agents stores the caller as owner_id and accepts custom_env from+// any member.+func agentEnvOwnerFixture(t *testing.T, agentName, email string) (agentID, ownerUserID string) {+ t.Helper()++ ownerUserID = createPermissionTestMember(t, email)+ agentID = createHandlerTestAgent(t, agentName, nil)+ if _, err := testPool.Exec(context.Background(), `+ UPDATE agent SET owner_id = $1, custom_env = '{"API_KEY":"secret-value"}' WHERE id = $2+ `, ownerUserID, agentID); err != nil {+ t.Fatalf("assign agent owner: %v", err)+ }+ return agentID, ownerUserID+}++// TestAgentEnv_AgentOwnerMemberCanRevealAndUpdate is the MUL-5438 fix:+// the human who owns an agent can reveal and rotate its env even with a+// plain `member` workspace role. The audit assertions come along because+// the reveal/update trail must keep naming the real human operator and+// must still never carry values.+func TestAgentEnv_AgentOwnerMemberCanRevealAndUpdate(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID, ownerUserID := agentEnvOwnerFixture(t, "env-owner-member-agent", "[email protected]")++ req := withURLParam(newRequestAs(ownerUserID, http.MethodGet, "/api/agents/"+agentID+"/env", nil), "id", agentID)+ w := httptest.NewRecorder()+ testHandler.GetAgentEnv(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetAgentEnv as agent owner: 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 reveal response: %v", err)+ }+ if resp.CustomEnv["API_KEY"] != "secret-value" {+ t.Fatalf("expected plaintext API_KEY, got %v", resp.CustomEnv)+ }++ body := map[string]any{"custom_env": map[string]string{"API_KEY": "rotated-value"}}+ req = withURLParam(newRequestAs(ownerUserID, http.MethodPut, "/api/agents/"+agentID+"/env", body), "id", agentID)+ w = httptest.NewRecorder()+ testHandler.UpdateAgentEnv(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateAgentEnv as agent owner: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var stored string+ if err := testPool.QueryRow(ctx, `SELECT custom_env::text FROM agent WHERE id = $1`, agentID).Scan(&stored); err != nil {+ t.Fatalf("read back custom_env: %v", err)+ }+ var got map[string]string+ if err := json.Unmarshal([]byte(stored), &got); err != nil {+ t.Fatalf("decode stored custom_env: %v", err)+ }+ if got["API_KEY"] != "rotated-value" {+ t.Errorf("expected the rotated value on disk, got %v", got)+ }++ // Audit must attribute the acting human — the member, not the+ // workspace owner — and must never carry the value itself.+ var actorID, details string+ if err := testPool.QueryRow(ctx, `+ SELECT actor_id::text, 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(&actorID, &details); err != nil {+ t.Fatalf("expected agent_env_updated activity row: %v", err)+ }+ if actorID != ownerUserID {+ t.Errorf("audit actor_id = %s; want the acting agent owner %s", actorID, ownerUserID)+ }+ if strings.Contains(details, "secret-value") || strings.Contains(details, "rotated-value") {+ t.Errorf("activity details must NOT contain env values, got: %s", details)+ }+}++// TestAgentEnv_UnrelatedMemberForbidden keeps the blast radius of+// MUL-5438 at exactly one agent: ownership, not membership, is what+// opens the endpoint. A member who owns some other agent still gets 403+// on this one.+func TestAgentEnv_UnrelatedMemberForbidden(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ agentID, _ := agentEnvOwnerFixture(t, "env-unrelated-target-agent", "[email protected]")+ strangerID := createPermissionTestMember(t, "[email protected]")++ 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{"API_KEY": "stolen"}}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ method := http.MethodGet+ if tc.body != nil {+ method = http.MethodPut+ }+ req := withURLParam(newRequestAs(strangerID, method, "/api/agents/"+agentID+"/env", tc.body), "id", agentID)+ w := httptest.NewRecorder()+ tc.fn(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("expected 403 for an unrelated member, got %d: %s", w.Code, w.Body.String())+ }+ })+ }++ // The rejected PUT must not have touched the stored map.+ var stored string+ if err := testPool.QueryRow(context.Background(), `SELECT custom_env::text FROM agent WHERE id = $1`, agentID).Scan(&stored); err != nil {+ t.Fatalf("read back custom_env: %v", err)+ }+ if !strings.Contains(stored, "secret-value") {+ t.Errorf("forbidden update must leave custom_env untouched, got: %s", stored)+ }+}++// TestAgentEnv_WorkspaceRolesUnchanged pins the pre-existing behavior the+// fix must not regress: workspace owner and admin keep full access to any+// agent's env, including agents they do not own.+func TestAgentEnv_WorkspaceRolesUnchanged(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID, _ := agentEnvOwnerFixture(t, "env-role-check-agent", "[email protected]")++ adminID := createPermissionTestMember(t, "[email protected]")+ if _, err := testPool.Exec(ctx, `+ UPDATE member SET role = 'admin' WHERE workspace_id = $1 AND user_id = $2+ `, testWorkspaceID, adminID); err != nil {+ t.Fatalf("promote member to admin: %v", err)+ }++ // testUserID is the workspace owner and does NOT own this agent.+ for _, actorID := range []string{testUserID, adminID} {+ req := withURLParam(newRequestAs(actorID, http.MethodGet, "/api/agents/"+agentID+"/env", nil), "id", agentID)+ w := httptest.NewRecorder()+ testHandler.GetAgentEnv(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetAgentEnv as %s: expected 200, got %d: %s", actorID, w.Code, w.Body.String())+ }+ }+}++// TestAgentEnv_AgentActorRejectedForOwnedAgent is the boundary MUL-5438+// must not widen. TestAgentEnv_AgentActorRejected already covers an agent+// backed by a workspace owner; this covers the new shape the fix creates —+// an agent whose backing human is the target agent's own owner. The actor+// check runs before the ownership check precisely so this stays a 403.+func TestAgentEnv_AgentActorRejectedForOwnedAgent(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ targetID, ownerUserID := agentEnvOwnerFixture(t, "env-actor-target-agent", "[email protected]")++ // The calling agent runs on behalf of the same human who owns the+ // target agent, so the owner check alone would let it through.+ hostAgentID := createHandlerTestAgent(t, "env-actor-host-agent", nil)+ if _, err := testPool.Exec(ctx, `UPDATE agent SET owner_id = $1 WHERE id = $2`, ownerUserID, hostAgentID); err != nil {+ t.Fatalf("assign host agent owner: %v", err)+ }+ 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{"API_KEY": "exfiltrated"}}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ method := http.MethodGet+ if tc.body != nil {+ method = http.MethodPut+ }+ req := withURLParam(newRequestAs(ownerUserID, method, "/api/agents/"+targetID+"/env", tc.body), "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 an agent actor, got %d: %s", w.Code, w.Body.String())+ }+ })+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex dc61b885db..99c0b33f0b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2590,7 +2590,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {// 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`). Runtime+ // path on human-only endpoints (e.g. `/api/agents/{id}/env`). Runtime// owner is required because task tokens are still bound to an owning user;// without one, fail the claim explicitly instead of letting the daemon// fall back to a member/owner credential. MUL-3292.diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.goindex d4407388ba..a0ab05c9a0 100644--- a/server/internal/middleware/auth.go+++ b/server/internal/middleware/auth.go@@ -67,7 +67,7 @@ func Auth(queries *db.Queries, patCache *auth.PATCache, cloudPAT *auth.CloudPATV// 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+ // X-Task-ID. Human-only endpoints (e.g. agent env// management) reject requests authenticated this way; see// `actorSourceFromRequest`. MUL-2600.if strings.HasPrefix(tokenString, "mat_") {diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.mdindex beb3a936de..4842f9c3ae 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md@@ -20,7 +20,7 @@ These commands read state and have no side effects:```bashmultica agent get <agent-id> --output json # full persisted agent recordmultica agent skills list <agent-id> --output json # current skill bindings-multica agent env get <agent-id> --output json # plaintext env (owner/admin only, agents denied)+multica agent env get <agent-id> --output json # plaintext env (agent owner or ws owner/admin; agents denied)````agent get` returns the persisted agent including `runtime_id`, `model`,@@ -189,14 +189,15 @@ Read-side facts (these are the wrong assumptions to avoid):list/get/create/update` and WS events return only `has_custom_env` (bool) and`custom_env_key_count` (int).- Reading plaintext values requires the dedicated `GET /api/agents/{id}/env`- endpoint (`multica agent env get`). It is gated to workspace **owner/admin**- members, and **agent actors are denied** regardless of the backing member's- role — a running agent cannot read another agent's secrets.+ endpoint (`multica agent env get`). It is gated to the **agent's own human+ owner** or a workspace **owner/admin**, and **agent actors are denied**+ regardless of the backing member's role — a running agent cannot read another+ agent's secrets, not even one its own human owns.- Writing values after creation does NOT go through `agent update`. The genericupdate handler rejects any `custom_env` field with a 400 ("use PUT/api/agents/{id}/env"). Plaintext env writes are handled by- `PUT /api/agents/{id}/env` (`multica agent env set`), which is owner/admin-only- and writes an audit row.+ `PUT /api/agents/{id}/env` (`multica agent env set`), which carries the same+ gate and writes an audit row.### mcp_configdiff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.mdindex db810a954b..5dab553366 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md@@ -105,9 +105,10 @@ only.| Contract | Line | Behavior ||---|---|---|-| `authorizeAgentEnv` gate | 66 | loads agent, then applies the two checks below |-| Agent actors denied | 80–84 | `if actorType == "agent"` → 403 "agents may not access env management endpoints" (MUL-2600 impersonation guard) |-| Owner/admin only | 86 | `requireWorkspaceRole(..., "owner", "admin")` |+| `authorizeAgentEnv` gate | 76 | loads agent, then applies the two checks below |+| Agent actors denied | 90–94 | `if actorType == "agent"` → 403 "agents may not access env management endpoints" (MUL-2600 impersonation guard); runs FIRST, so an agent is denied even when its backing human owns the target agent |+| Agent owner or ws owner/admin | 96–103 | `requireWorkspaceRole(..., "owner", "admin", "member")` then `canManageAgentEnv` → 403 otherwise (MUL-5438) |+| `canManageAgentEnv` predicate | 120 | workspace owner/admin, or `agent.owner_id == member.user_id`; a NULL `owner_id` never matches |## Routes — `server/cmd/server/router.go`