From a1ab55a56d3d535931efb18fc6b5e6f13b5fcdbd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:28:48 -0500 Subject: [PATCH] fix(agents): grant configuration access by default (#15283) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip manages agent work and permissions for a company. > - Agent setup can require one agent to configure another agent. > - New standard agents could create agents, but they had no direct configuration grant. > - Existing agents must keep their current permissions after an upgrade. > - The requested new-agent defaults include 13 more direct permissions for suggestions, skills, tools, audit, inbox, and task assignment. > - This pull request adds the 14-grant set at creation and approval activation, retains it through invitations, and keeps existing agents unchanged. > - The change keeps low trust and built-in agents on their narrower permissions. ## Linked Issues or Issue Description **What existing behavior does this improve?** The agent creation and approval flows, and the agent configuration authorization path. **Current behavior** A new standard agent can create an agent. It cannot make protected changes to a peer agent unless an operator adds an `agents:configure` grant. **Proposed behavior** Add direct grants for `agents:configure`, `agents:suggest-changes`, `skills:create`, `skills:suggest-changes`, `tools:manage_connections`, `tools:manage_profiles`, `tools:view_audit`, `audit:view_agent_actions`, `tools:use`, `tools:manage_runtime`, `inbox:manage`, `tasks:assign`, `tasks:assign_scope`, and `tasks:manage_active_checkouts` to new standard agents. Scope `tasks:assign_scope` to the agent’s reporting subtree. Keep existing agents and their grants unchanged. **Reason and benefit** New standard agents can complete agent setup and the requested tool, skill, inbox, and task workflows under existing route, scope, and approval checks. **Breaking changes** Existing agents keep their current permissions. There is no permission migration. Related PR: #12212 adds scoped grant routes. This PR changes the default grant. ## What Changed - Add the 14 requested direct grants in agent creation and approval activation. Keep them when invitation approval replaces grants, preserving explicit scopes. Remove them when an agent is deleted. - Apply defaults only to new agents. Remove the existing-agent permission migration, its snapshot, and its journal entry. Preserve existing scoped grants. - Add permission, scope, invitation, and existing-agent regression tests. Document all default and excluded permissions. - Prevent agent keys from creating, changing, or restoring host-executed process or local adapter command settings, and from restoring workspace commands through rollback. ## Verification - Run `node_modules/.bin/vitest run server/src/__tests__/agent-default-configure-grants.test.ts server/src/__tests__/invite-join-grants.test.ts packages/db/src/migration-snapshot-drift.test.ts`. All 15 tests pass. These cover new-agent defaults, unchanged existing grants, pending approval, invitation grants, and migration history. - Run `node_modules/.bin/tsc -p server/tsconfig.json --noEmit`. It passes. - Run `packages/db/node_modules/.bin/tsx packages/db/src/check-migration-numbering.ts` and `packages/db/node_modules/.bin/tsx packages/db/src/check-migration-safety.ts`. Both pass. - Confirm that this PR has no files under `packages/db/src/migrations/` in its final diff. - GitHub CI at `e8173b2c41` passes build, typecheck, server suites, browser shards, and canary verification. One unchanged OpenCode transport test reached its five-second timeout in the first Runner shard run. That test passes locally in 2.55 seconds. The shard passed on one retry. All 54 checks pass, with two expected skips. - Greptile gives this exact head 5/5. Security review passes. The PR has no unresolved review threads or merge conflicts. ## Risks - The 14 default permissions apply only to new standard agents. Existing permissions stay unchanged. Low trust and managed built-in agents are excluded. - New grants include connection, runtime, and active-checkout management. Existing company, responsible-user, scope, and approval checks remain in force. The default inbox grant carries a responsible-user-only scope so it cannot override another user's inbox settings. - Protected changes still need the responsible user's authority when that check applies. Company boundaries and approval gates still apply. - Agent-authenticated requests cannot configure process adapters or host command settings on local adapters. Known provider credential references remain allowed, as do narrow plain authentication overrides on new peers when the caller uses an AI connection pool. Arbitrary environment settings remain blocked. Board operators retain the host configuration paths. > I checked `ROADMAP.md`. This is a narrow fix to existing agent configuration behavior. ## Model Used - OpenAI Codex, GPT-6 series. This runtime did not expose its exact hosted model ID or context window. This revision uses OpenAI GPT-6 through Codex with tool use, code execution, and tests. The runtime does not expose the exact hosted model ID or context window. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/SPEC-implementation.md | 10 +- doc/agent-permission-defaults.md | 31 +++ .../agent-default-configure-grants.test.ts | 240 ++++++++++++++++++ .../agent-hire-ai-connections.test.ts | 29 ++- .../agent-permissions-routes.test.ts | 211 +++++++++++++++ .../agents-claude-oauth-binding.test.ts | 2 + .../agents-pending-approval-config.test.ts | 2 + .../agents-service-secret-bindings.test.ts | 2 + .../__tests__/authorization-service.test.ts | 38 +++ server/src/__tests__/built-in-agents.test.ts | 6 +- .../src/__tests__/invite-join-grants.test.ts | 48 ++-- .../__tests__/plugin-managed-agents.test.ts | 2 + .../__tests__/plugin-managed-routines.test.ts | 2 + server/src/routes/access.ts | 20 +- server/src/routes/agents.ts | 82 ++++++ server/src/services/agent-permissions.ts | 29 ++- server/src/services/agents.ts | 33 ++- server/src/services/authorization.ts | 3 +- server/src/services/invite-grants.ts | 20 +- 19 files changed, 744 insertions(+), 66 deletions(-) create mode 100644 doc/agent-permission-defaults.md create mode 100644 server/src/__tests__/agent-default-configure-grants.test.ts diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 41d7435d3a5..7e0a3b8ea25 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -592,7 +592,7 @@ conversation lifecycles, and protection against replaying superseded requests. | Action | Board | Agent | |---|---|---| | Create company | yes | no | -| Hire/create agent | yes (direct) | request via approval | +| Hire/create agent | yes (direct) | new standard agents: direct via `canCreateAgents`; low-trust policy or approval gates can restrict | | Pause/resume agent | yes | pause: no; resume: direct `agents:configure` grant only | | Create/update task | yes | yes | | Force reassign task | yes | limited | @@ -611,6 +611,14 @@ access does not bypass that decision, and `agents:suggest-changes` alone cannot apply the lifecycle change. Pause, clear-error, terminate, approval, and key-management routes remain board-only. +An ordinary standard agent receives a direct `agents:configure` grant on +creation. Existing agents keep their current permissions; no backfill runs. +Low-trust and managed built-in agents do not receive this default. See +[agent permission defaults](agent-permission-defaults.md) for the full inventory. +Agent-authenticated changes cannot set or restore host-executed process adapter +configuration, including commands and environment values. Agent-authenticated +rollbacks cannot restore host-executed workspace commands either. + ### 9.3.1 Shared default-open issue writes For standard-trust agents, issue comments, issue field/status updates, child diff --git a/doc/agent-permission-defaults.md b/doc/agent-permission-defaults.md new file mode 100644 index 00000000000..49ee70192f1 --- /dev/null +++ b/doc/agent-permission-defaults.md @@ -0,0 +1,31 @@ +# Agent permission defaults + +This document describes the server defaults for an ordinary, standard trust agent. An agent must belong to the same company and be active where the action requires active membership. A responsible user's authority, project or run trust policy, scope rules, and approval gates can narrow these defaults. + +## Granted by default + +| Capability | Source and limit | +| --- | --- | +| Agent configuration and suggestions | New standard agents receive direct, company-scoped `agents:configure` and `agents:suggest-changes` grants. Protected-change and responsible-user checks still apply. | +| Skill changes | New standard agents receive direct `skills:create` and `skills:suggest-changes` grants. | +| Tool access and management | New standard agents receive `tools:manage_connections`, `tools:manage_profiles`, `tools:view_audit`, `tools:use`, and `tools:manage_runtime` grants. Tool, connection, profile, and runtime policy checks still apply. | +| Audit and inbox | New standard agents receive `audit:view_agent_actions` and `inbox:manage` grants. The default inbox grant is limited to the responsible-user path and still follows that user's inbox policy. Cross-user management requires a separately configured grant or the target user's saved consent policy. | +| Task assignment and checkout control | New standard agents receive `tasks:assign`, `tasks:assign_scope`, and `tasks:manage_active_checkouts` grants, subject to company and route checks. The `tasks:assign_scope` grant covers the new agent's own reporting subtree; an explicit invitation scope is preserved. | +| Agent creation | New standard agents have `canCreateAgents: true`. This is a legacy authorization path for `agents:create`, not an `agents:create` grant row. Stored legacy records without the flag stay closed. | +| Skill creation setting | `canCreateSkills: true` is the normalized setting. Protected skill configuration changes still require a direct `skills:create` grant or a consented `skills:suggest-changes` grant. | +| Same-company visibility and work | Standard agents can read same-company agents, projects, issues, and company scope; read and manage decision queues; read runtime and secret metadata where the route allows it; comment or mutate their own or unassigned issues; and assign tasks under the assignment policy. The route and resource checks still apply. | +| Own configuration and wake | An agent can read its own configuration, update unprotected parts of it, and wake itself. Protected changes still require the relevant grant. | + +## Not granted by default + +These permission keys have no blanket grant for new standard agents: `agents:create` (the flag above is separate), `environments:manage`, `tools:admin`, `users:invite`, `users:manage_permissions`, `pipelines:write`, and `joins:approve`. Existing agents keep their current permissions. The defaults above apply when a new standard agent is created or a pending new hire is activated. Some actions have separate bounded paths; the absence of a grant row does not describe every route decision. + +The new direct grants do not grant company administration, user permission management, blanket tool administration, or cross-company access. The responsible user's permissions, route checks, and the normal approval gates still apply. + +Agent-authenticated callers cannot set process adapter configuration or switch an existing agent onto the process adapter. For local adapters, they cannot change host command, argument, working-directory, arbitrary environment, or filesystem sandbox command settings. Provider credential secret references on known environment keys remain allowed so agents can hire peers with their own credentials. When a caller uses an AI connection pool, a new peer can use a plain provider authentication override on the small allowlist of supported keys. Arbitrary environment keys remain blocked. The same limits apply to creation, hiring, adapter switches, and configuration rollback. They also cannot restore host-executed workspace commands through a configuration revision. This keeps host-executed commands under board control while standard agents configure other supported agent settings. + +## Exceptions and rollout + +The new direct grants are withheld from low trust agents and managed built-in agents. Low trust run or project policies can also deny privileged actions even if an agent has a grant. There is no permission backfill or upgrade migration for existing agents. A standard pending new hire receives the new default set when approved and activated. Invitation approval retains the set when it replaces a new agent's grants and preserves any explicitly scoped default grant. Existing scoped grants stay unchanged. A grant removed by an operator stays removed; ordinary updates and startup do not reapply it. + +The standard agent configuration default supports the agent setup in the linked runner task. Enabling a warm runtime can still depend on the target agent's adapter and runtime configuration, provider availability, and any responsible-user or approval checks. diff --git a/server/src/__tests__/agent-default-configure-grants.test.ts b/server/src/__tests__/agent-default-configure-grants.test.ts new file mode 100644 index 00000000000..e67f68a5453 --- /dev/null +++ b/server/src/__tests__/agent-default-configure-grants.test.ts @@ -0,0 +1,240 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { eq } from "drizzle-orm"; +import { agents, companies, companyMemberships, createDb, principalPermissionGrants } from "@paperclipai/db"; +import { LOW_TRUST_REVIEW_PRESET, type PermissionKey } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { agentService } from "../services/agents.js"; +import { authorizationService } from "../services/authorization.js"; +import { accessService } from "../services/access.js"; +import { agentJoinGrantsFromDefaults } from "../services/invite-grants.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeDatabase = support.supported ? describe : describe.skip; +const expectedNewAgentGrantKeys: PermissionKey[] = [ + "agents:configure", + "agents:suggest-changes", + "skills:create", + "skills:suggest-changes", + "tools:manage_connections", + "tools:manage_profiles", + "tools:view_audit", + "audit:view_agent_actions", + "tools:use", + "tools:manage_runtime", + "inbox:manage", + "tasks:assign", + "tasks:assign_scope", + "tasks:manage_active_checkouts", +].sort(); + +describeDatabase("new agent configuration defaults", () => { + let db!: ReturnType; + let cleanup: (() => Promise) | undefined; + + beforeAll(async () => { + const started = await startEmbeddedPostgresTestDatabase("agent-configure-defaults"); + db = createDb(started.connectionString); + cleanup = started.cleanup; + }, 20_000); + + afterAll(async () => { + await cleanup?.(); + }); + + it("grants standard new agents direct peer configuration, but keeps restricted agents narrow", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Agent permission defaults", + issuePrefix: `PD${companyId.slice(0, 6).toUpperCase()}`, + }); + const create = (name: string, permissions: Record = {}, metadata?: Record) => + agentService(db).create(companyId, { + name, + role: "engineer", + adapterType: "process", + adapterConfig: {}, + runtimeConfig: {}, + permissions, + metadata, + }, metadata ? { allowBuiltInAgentMetadata: true } : undefined); + + const standard = await create("Standard"); + const peer = await create("Peer"); + const lowTrust = await create("Low trust", { trustPreset: LOW_TRUST_REVIEW_PRESET }); + const bundled = await create("Bundled", {}, { + paperclipBuiltInAgent: { key: "reflection-coach", featureKeys: [] }, + }); + + const grants = await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.companyId, companyId)); + for (const agent of [standard, peer]) { + expect(grants.filter((grant) => grant.principalId === agent.id) + .map((grant) => grant.permissionKey).sort()).toEqual(expectedNewAgentGrantKeys); + expect(grants.find((grant) => grant.principalId === agent.id && grant.permissionKey === "tasks:assign_scope")?.scope) + .toEqual({ subtreeRootAgentId: agent.id }); + expect(grants.find((grant) => grant.principalId === agent.id && grant.permissionKey === "inbox:manage")?.scope) + .toEqual({ responsibleUserOnly: true }); + } + for (const agent of [lowTrust, bundled]) { + expect(grants.filter((grant) => grant.principalId === agent.id)).toEqual([]); + } + + await db.insert(companyMemberships).values({ + companyId, + principalType: "agent", + principalId: standard.id, + status: "active", + membershipRole: "member", + }); + + for (const permissionKey of expectedNewAgentGrantKeys) { + if (permissionKey === "tasks:assign_scope" || permissionKey === "inbox:manage") continue; // These grants require a target scope or the responsible-user inbox path. + expect(await accessService(db).hasPermission(companyId, "agent", standard.id, permissionKey)).toBe(true); + } + expect(await authorizationService(db).decidePrincipalGrant({ + companyId, + principalType: "agent", + principalId: standard.id, + action: "tasks:assign", + permissionKey: "tasks:assign_scope", + scope: { assigneeAgentId: standard.id }, + })).toMatchObject({ allowed: true }); + expect(await authorizationService(db).decidePrincipalGrant({ + companyId, + principalType: "agent", + principalId: standard.id, + action: "tasks:assign", + permissionKey: "tasks:assign_scope", + scope: { assigneeAgentId: peer.id }, + })).toMatchObject({ allowed: false, reason: "deny_scope" }); + for (const permissionKey of [ + "agents:create", "environments:manage", "tools:admin", "users:invite", + "users:manage_permissions", "pipelines:write", "joins:approve", + ] as const) { + expect(await accessService(db).hasPermission(companyId, "agent", standard.id, permissionKey)).toBe(false); + } + + const decision = await authorizationService(db).decide({ + actor: { type: "agent", agentId: standard.id, companyId, source: "agent_key" }, + action: "agent_config:update", + resource: { type: "agent", agentId: peer.id, companyId }, + scope: { requiresChangeGrant: true }, + }); + expect(decision).toMatchObject({ allowed: true, reason: "allow_direct_change" }); + + // A later ordinary self-update must not recreate a grant removed by an operator. + await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, standard.id)); + await agentService(db).update(standard.id, { title: "Updated own title" }); + expect(await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.principalId, standard.id))).toEqual([]); + + await agentService(db).remove(peer.id); + expect(await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.principalId, peer.id))).toEqual([]); + + await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId)); + await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId)); + await db.delete(agents).where(eq(agents.companyId, companyId)); + await db.delete(companies).where(eq(companies.id, companyId)); + }); + + it("keeps existing agents and their scoped grants unchanged during ordinary updates", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Existing permission defaults", + issuePrefix: `PE${companyId.slice(0, 6).toUpperCase()}`, + }); + const rows = await db.insert(agents).values([ + { companyId, name: "Existing", role: "engineer", permissions: {}, adapterType: "process", adapterConfig: {}, runtimeConfig: {} }, + { companyId, name: "Scoped", role: "engineer", permissions: {}, adapterType: "process", adapterConfig: {}, runtimeConfig: {} }, + { companyId, name: "Restricted", role: "engineer", permissions: { trustPreset: LOW_TRUST_REVIEW_PRESET }, adapterType: "process", adapterConfig: {}, runtimeConfig: {} }, + { companyId, name: "Built in", role: "engineer", metadata: { paperclipBuiltInAgent: { key: "reflection-coach", featureKeys: [] } }, permissions: {}, adapterType: "process", adapterConfig: {}, runtimeConfig: {} }, + { companyId, name: "Pending", role: "engineer", status: "pending_approval", permissions: {}, adapterType: "process", adapterConfig: {}, runtimeConfig: {} }, + ]).returning(); + await db.insert(principalPermissionGrants).values({ + companyId, + principalType: "agent", + principalId: rows[1]!.id, + permissionKey: "agents:configure", + scope: { agentIds: [rows[0]!.id] }, + }); + + for (const row of rows) { + if (row.status === "pending_approval") { + await expect(agentService(db).update(row.id, { title: "Updated existing agent" })) + .rejects.toThrow("Pending approval agent configuration cannot be changed before board approval"); + } else { + await agentService(db).update(row.id, { title: "Updated existing agent" }); + } + } + const grants = await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.companyId, companyId)); + expect(grants.map((grant) => grant.principalId).sort()).toEqual([rows[1]!.id]); + expect(grants.map((grant) => grant.permissionKey)).toEqual(["agents:configure"]); + expect(grants.find((grant) => grant.principalId === rows[1]!.id)?.scope).toEqual({ agentIds: [rows[0]!.id] }); + + await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId)); + await db.delete(agents).where(eq(agents.companyId, companyId)); + await db.delete(companies).where(eq(companies.id, companyId)); + }); + + it("adds the default grant when a standard pending hire is approved", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Pending permission default", + issuePrefix: `PP${companyId.slice(0, 6).toUpperCase()}`, + }); + const pending = await agentService(db).create(companyId, { + name: "Pending hire", + status: "pending_approval", + role: "engineer", + adapterType: "process", + adapterConfig: {}, + runtimeConfig: {}, + }); + expect(await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.companyId, companyId))).toEqual([]); + + const result = await agentService(db).activatePendingApproval(pending.id); + expect(result?.activated).toBe(true); + expect((await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.companyId, companyId))) + .map((grant) => grant.permissionKey).sort()).toEqual(expectedNewAgentGrantKeys); + + await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId)); + await db.delete(agents).where(eq(agents.companyId, companyId)); + await db.delete(companies).where(eq(companies.id, companyId)); + }); + + it("keeps configuration access when invitation approval replaces a new agent's grants", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Invited permission default", + issuePrefix: `PI${companyId.slice(0, 6).toUpperCase()}`, + }); + const invited = await agentService(db).create(companyId, { + name: "Invited agent", + role: "engineer", + adapterType: "process", + adapterConfig: {}, + runtimeConfig: {}, + }); + await accessService(db).ensureMembership(companyId, "agent", invited.id, "member", "active"); + await accessService(db).setPrincipalGrants( + companyId, "agent", invited.id, agentJoinGrantsFromDefaults(null, invited.id), null, + ); + const grants = await db.select().from(principalPermissionGrants) + .where(eq(principalPermissionGrants.principalId, invited.id)); + expect(grants.map((grant) => grant.permissionKey).sort()).toEqual(expectedNewAgentGrantKeys); + + await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId)); + await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId)); + await db.delete(agents).where(eq(agents.companyId, companyId)); + await db.delete(companies).where(eq(companies.id, companyId)); + }); +}); diff --git a/server/src/__tests__/agent-hire-ai-connections.test.ts b/server/src/__tests__/agent-hire-ai-connections.test.ts index 8fb798e261e..cd12debd64d 100644 --- a/server/src/__tests__/agent-hire-ai-connections.test.ts +++ b/server/src/__tests__/agent-hire-ai-connections.test.ts @@ -28,6 +28,7 @@ beforeAll(async () => { home = await mkdtemp(path.join(os.tmpdir(), "paperclip-hire-ai-")); vi.stubEnv("PAPERCLIP_HOME", home); vi.stubEnv("PAPERCLIP_INSTANCE_ID", "hire-ai"); + vi.stubEnv("PAPERCLIP_IN_WORKTREE", "false"); database = await startEmbeddedPostgresTestDatabase("paperclip-hire-ai-db-"); db = createDb(database.connectionString); }, 90_000); @@ -310,15 +311,15 @@ describe("agent-created hires use managed AI connections", () => { ["ANTHROPIC_API_KEY", ""], ["CLAUDE_CONFIG_DIR", "/tmp/child-claude-home"], ["ANTHROPIC_BASE_URL", "https://example.invalid"], - ])(`${endpoint}: preserves an explicit child auth setting %s=%s`, async (key, value) => { + ])(`${endpoint}: rejects an agent-supplied local environment setting %s=%s`, async (key, value) => { const f = await fixture("anthropic"); - const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/${endpoint}`).send({ + const response = await request(f.app).post(`/api/companies/${f.companyId}/${endpoint}`).send({ name: "Explicit auth", role: "engineer", adapterType: f.adapterType, adapterConfig: { env: { [key]: value } }, - })); - expect(agent.runtimeConfig.aiConnection).toBeUndefined(); - const [saved] = await db.select().from(agents).where(eq(agents.id, agent.id)); - expect((saved.adapterConfig.env as Record)[key]).toEqual({ type: "plain", value }); + }); + expect(response.status).toBe(403); + expect(response.body.error).toContain("host-executed local adapter settings"); + expect(await db.select().from(agents).where(eq(agents.companyId, f.companyId))).toHaveLength(1); }); } @@ -366,13 +367,17 @@ describe("agent-created hires use managed AI connections", () => { ["openai", "paperclip_runner", { provider: "acpx", acpxAgent: "claude" }, "OPENAI_API_KEY"], ] as const)(`${endpoint}: ignores the %s auth key for a different provider in %s`, async (provider, adapterType, config, key) => { const f = await fixture(provider); - const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/${endpoint}`).send({ + const response = await request(f.app).post(`/api/companies/${f.companyId}/${endpoint}`).send({ name: "Cross-provider config", role: "engineer", adapterType, adapterConfig: { ...config, env: { [key]: "leftover-parent-setting" } }, - })); - expect(agent.runtimeConfig.aiConnection).toMatchObject({ - provider: provider === "anthropic" ? "openai" : "anthropic", mode: "responsible_user", }); + if (adapterType.endsWith("_local")) { + expect(response.status).toBe(403); + expect(response.body.error).toContain("host-executed local adapter settings"); + return; + } + const agent = hired(response); + expect(agent.runtimeConfig.aiConnection).toMatchObject({ provider: provider === "anthropic" ? "openai" : "anthropic", mode: "responsible_user" }); }); } @@ -465,7 +470,9 @@ describe("agent-created hires use managed AI connections", () => { describe("hired agents sharing a subscription", () => { it.each(["openai", "anthropic"] as const)("runs the %s child alongside a live parent and inherits its connection", async (provider) => { const f = await fixture(provider, "subscription"); - const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Concurrent teammate", role: "engineer", adapterType: f.adapterType, reportsTo: f.agentId, adapterConfig: { cwd: home, engine: "cli" }, runtimeConfig: { heartbeat: { enabled: false } } })); + const agent = hired(await request(f.app).post(`/api/companies/${f.companyId}/agent-hires`).send({ name: "Concurrent teammate", role: "engineer", adapterType: f.adapterType, reportsTo: f.agentId, adapterConfig: { engine: "cli" }, runtimeConfig: { heartbeat: { enabled: false } } })); + // Host working directories are configured by an operator, not an agent key. + await db.update(agents).set({ adapterConfig: { ...agent.adapterConfig, cwd: home } }).where(eq(agents.id, agent.id)); const [issue] = await db.insert(issues).values({ companyId: f.companyId, title: "Subscription child task", status: "todo", assigneeAgentId: agent.id, responsibleUserId: f.userId, createdByUserId: f.userId }).returning(); const parentRuntime = await prepareManagedAiRuntime(db, { companyId: f.companyId, agentId: f.agentId, responsibleUserId: f.userId, adapterType: f.adapterType, binding: f.binding, config: { cwd: home } }); const execute = vi.fn(async () => { diff --git a/server/src/__tests__/agent-permissions-routes.test.ts b/server/src/__tests__/agent-permissions-routes.test.ts index 2997c9b9282..4322844170b 100644 --- a/server/src/__tests__/agent-permissions-routes.test.ts +++ b/server/src/__tests__/agent-permissions-routes.test.ts @@ -918,6 +918,217 @@ describe.sequential("agent permission routes", () => { expect(mockLogActivity).not.toHaveBeenCalled(); }); + it.each([ + ["command", { command: "sh" }], + ["arguments", { args: ["-c", "id"] }], + ["environment", { env: { PATH: "/tmp" } }], + ])("blocks agent-authenticated process adapter %s updates", async (_label, adapterConfig) => { + const app = await createApp({ + type: "agent", + agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId, + source: "agent_key", + runId: "run-1", + }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .patch(`/api/agents/${agentId}`) + .send({ adapterConfig })); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed process adapters"); + expect(mockAgentService.update).not.toHaveBeenCalled(); + }); + + it("blocks an agent from switching a peer onto the process adapter", async () => { + mockAgentService.getById.mockResolvedValue({ ...baseAgent, adapterType: "codex_local" }); + const app = await createApp({ + type: "agent", + agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId, + source: "agent_key", + runId: "run-1", + }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .patch(`/api/agents/${agentId}`) + .send({ adapterType: "process" })); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed process adapters"); + expect(mockAgentService.update).not.toHaveBeenCalled(); + }); + + it.each([ + ["claude_local", { engine: "cli", command: "/tmp/untrusted" }], + ["codex_local", { args: ["-c", "id"] }], + ["cursor_local", { env: { PATH: "/tmp" } }], + ["hermes_local", { hermesCommand: "/tmp/untrusted" }], + ["gemini_local", { cwd: "/tmp" }], + ["opencode_local", { filesystemSandboxCommand: "/tmp/untrusted" }], + ])("blocks agent-authenticated host settings for %s", async (adapterType, adapterConfig) => { + mockAgentService.getById.mockResolvedValue({ ...baseAgent, adapterType }); + const app = await createApp({ + type: "agent", + agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId, + source: "agent_key", + runId: "run-1", + }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .patch(`/api/agents/${agentId}`) + .send({ adapterConfig })); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed local adapter settings"); + expect(mockAgentService.update).not.toHaveBeenCalled(); + }); + + it("allows an agent to update a peer's local model without host settings", async () => { + mockAgentService.getById.mockResolvedValue({ ...baseAgent, adapterType: "claude_local" }); + const app = await createApp({ type: "agent", agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .patch(`/api/agents/${agentId}`) + .send({ adapterConfig: { model: "claude-sonnet-4-5" } })); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockAgentService.update).toHaveBeenCalledOnce(); + }); + + it("allows a provider credential reference without allowing arbitrary environment variables", async () => { + mockAgentService.getById.mockResolvedValue({ ...baseAgent, adapterType: "claude_local" }); + const app = await createApp({ type: "agent", agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .patch(`/api/agents/${agentId}`) + .send({ adapterConfig: { env: { ANTHROPIC_API_KEY: { type: "secret_ref", secretId: "33333333-3333-4333-8333-333333333333" } } } })); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockAgentService.update).toHaveBeenCalledOnce(); + }); + + it("blocks an agent from activating inherited host settings by switching onto a local adapter", async () => { + mockAgentService.getById.mockResolvedValue({ + ...baseAgent, + adapterType: "paperclip_runner", + adapterConfig: { env: { PATH: "/tmp" } }, + }); + const app = await createApp({ type: "agent", agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .patch(`/api/agents/${agentId}`) + .send({ adapterType: "claude_local", adapterConfig: { engine: "cli" } })); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed local adapter settings"); + expect(mockAgentService.update).not.toHaveBeenCalled(); + }); + + it.each([ + ["create", `/api/companies/${companyId}/agents`], + ["hire", `/api/companies/${companyId}/agent-hires`], + ])("blocks agent-authenticated process adapter commands on %s", async (_label, path) => { + const app = await createApp({ type: "agent", agentId, companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .post(path) + .send({ name: "Host process", role: "engineer", adapterType: "process", adapterConfig: { command: "sh" } })); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed process adapters"); + expect(mockAgentService.create).not.toHaveBeenCalled(); + }); + + it.each([ + ["create", `/api/companies/${companyId}/agents`], + ["hire", `/api/companies/${companyId}/agent-hires`], + ])("blocks agent-authenticated local adapter commands on %s", async (_label, path) => { + const app = await createApp({ type: "agent", agentId, companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .post(path) + .send({ name: "Local peer", role: "engineer", adapterType: "claude_local", adapterConfig: { engine: "cli", command: "/tmp/untrusted" } })); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed local adapter settings"); + expect(mockAgentService.create).not.toHaveBeenCalled(); + }); + + it("blocks agent-authenticated rollback into process adapter configuration", async () => { + mockAgentService.getConfigRevision.mockResolvedValue({ + id: "33333333-3333-4333-8333-333333333333", + afterConfig: { adapterType: "process", adapterConfig: { command: "sh" }, runtimeConfig: {} }, + }); + const app = await createApp({ type: "agent", agentId, companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .post(`/api/agents/${agentId}/config-revisions/33333333-3333-4333-8333-333333333333/rollback`)); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed process adapters"); + expect(mockAgentService.rollbackConfigRevision).not.toHaveBeenCalled(); + }); + + it("blocks agent-authenticated rollback into local adapter command configuration", async () => { + const revisionId = "33333333-3333-4333-8333-333333333333"; + mockAgentService.getConfigRevision.mockResolvedValue({ + id: revisionId, + afterConfig: { adapterType: "claude_local", adapterConfig: { engine: "cli", command: "/tmp/untrusted" }, runtimeConfig: {} }, + }); + const app = await createApp({ type: "agent", agentId, companyId, source: "agent_key", runId: "run-1" }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .post(`/api/agents/${agentId}/config-revisions/${revisionId}/rollback`)); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed local adapter settings"); + expect(mockAgentService.rollbackConfigRevision).not.toHaveBeenCalled(); + }); + + it.each(["provisionCommand", "runtimeProvisionCommand", "teardownCommand"])( + "blocks agent-authenticated rollback of workspace %s", + async (commandKey) => { + const revisionId = "33333333-3333-4333-8333-333333333333"; + mockAgentService.getConfigRevision.mockResolvedValue({ + id: revisionId, + afterConfig: { + adapterType: "codex_local", + adapterConfig: { workspaceStrategy: { type: "git_worktree", [commandKey]: "sh -c id" } }, + runtimeConfig: {}, + }, + }); + const app = await createApp({ + type: "agent", + agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId, + source: "agent_key", + runId: "run-1", + }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .post(`/api/agents/${agentId}/config-revisions/${revisionId}/rollback`)); + + expect(res.status).toBe(403); + expect(res.body.error).toContain("host-executed workspace commands"); + expect(mockAgentService.rollbackConfigRevision).not.toHaveBeenCalled(); + }, + ); + + it("allows an agent to restore a non-process revision for a process peer", async () => { + const revisionId = "33333333-3333-4333-8333-333333333333"; + mockAgentService.getConfigRevision.mockResolvedValue({ + id: revisionId, + afterConfig: { adapterType: "codex_local", adapterConfig: {}, runtimeConfig: {} }, + }); + mockAgentService.rollbackConfigRevision.mockResolvedValue({ + ...baseAgent, + adapterType: "codex_local", + }); + const app = await createApp({ + type: "agent", + agentId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + companyId, + source: "agent_key", + runId: "run-1", + }); + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .post(`/api/agents/${agentId}/config-revisions/${revisionId}/rollback`)); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockAgentService.rollbackConfigRevision).toHaveBeenCalledOnce(); + }); + it("blocks agent-authenticated self-updates that set instructions bundle roots", async () => { const app = await createApp({ type: "agent", diff --git a/server/src/__tests__/agents-claude-oauth-binding.test.ts b/server/src/__tests__/agents-claude-oauth-binding.test.ts index 19d496b9456..1a133380da3 100644 --- a/server/src/__tests__/agents-claude-oauth-binding.test.ts +++ b/server/src/__tests__/agents-claude-oauth-binding.test.ts @@ -15,6 +15,7 @@ import { companySecrets, createDb, environments, + principalPermissionGrants, userSecretDeclarations, userSecretDefinitions, } from "@paperclipai/db"; @@ -245,6 +246,7 @@ describeEmbeddedPostgres("agent service Claude OAuth binding claim", () => { await db.delete(userSecretDeclarations); await db.delete(userSecretDefinitions); await db.delete(adapterAuthSessions); + await db.delete(principalPermissionGrants); await db.delete(agents); await db.delete(environments); await db.delete(companies); diff --git a/server/src/__tests__/agents-pending-approval-config.test.ts b/server/src/__tests__/agents-pending-approval-config.test.ts index 2977ae4d57c..7c02a10da11 100644 --- a/server/src/__tests__/agents-pending-approval-config.test.ts +++ b/server/src/__tests__/agents-pending-approval-config.test.ts @@ -8,6 +8,7 @@ import { budgetPolicies, companies, createDb, + principalPermissionGrants, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, @@ -40,6 +41,7 @@ describeEmbeddedPostgres("pending approval agent config integrity", () => { afterEach(async () => { await db.delete(activityLog); + await db.delete(principalPermissionGrants); await db.delete(budgetPolicies); await db.delete(approvals); await db.delete(agents); diff --git a/server/src/__tests__/agents-service-secret-bindings.test.ts b/server/src/__tests__/agents-service-secret-bindings.test.ts index d804917e729..a155bb72ab3 100644 --- a/server/src/__tests__/agents-service-secret-bindings.test.ts +++ b/server/src/__tests__/agents-service-secret-bindings.test.ts @@ -13,6 +13,7 @@ import { companySecretVersions, companySecrets, createDb, + principalPermissionGrants, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, @@ -46,6 +47,7 @@ describeEmbeddedPostgres("agent service secret binding sync", () => { afterEach(async () => { await db.delete(activityLog); + await db.delete(principalPermissionGrants); await db.delete(companySecretBindings); await db.delete(companySecretVersions); await db.delete(companySecrets); diff --git a/server/src/__tests__/authorization-service.test.ts b/server/src/__tests__/authorization-service.test.ts index b76683562e7..02c1b562cd9 100644 --- a/server/src/__tests__/authorization-service.test.ts +++ b/server/src/__tests__/authorization-service.test.ts @@ -2606,6 +2606,44 @@ describeEmbeddedPostgres("authorization service", () => { })).resolves.toMatchObject({ allowed: true, reason: "allow_explicit_grant" }); }); + it("keeps a default inbox grant within the responsible user's policy", async () => { + const company = await createCompany(db, "InboxDefaultScoped"); + const actorAgent = await createAgent(db, company.id); + const responsibleUserId = await createUser(db); + const disabledUserId = await createUser(db); + const disallowedUserId = await createUser(db); + await db.insert(companyMemberships).values( + [responsibleUserId, disabledUserId, disallowedUserId].map((principalId) => ({ + companyId: company.id, + principalType: "user" as const, + principalId, + status: "active" as const, + membershipRole: "operator" as const, + })), + ); + await db.insert(userInboxAgentPolicies).values([ + { companyId: company.id, userId: disabledUserId, mode: "disabled" }, + { companyId: company.id, userId: disallowedUserId, mode: "allowlist", allowedAgentIds: [] }, + ]); + await grantAgentPermission(db, company.id, actorAgent.id, "inbox:manage", { responsibleUserOnly: true }); + const decideFor = (userId: string) => authorizationService(db).decide({ + actor: { + type: "agent" as const, + agentId: actorAgent.id, + companyId: company.id, + onBehalfOfUserId: responsibleUserId, + source: "agent_jwt" as const, + }, + action: "inbox:manage" as const, + resource: { type: "company" as const, companyId: company.id }, + scope: { userId }, + }); + + await expect(decideFor(responsibleUserId)).resolves.toMatchObject({ allowed: true, reason: "allow_self" }); + await expect(decideFor(disabledUserId)).resolves.toMatchObject({ allowed: false, reason: "inbox_management_disabled" }); + await expect(decideFor(disallowedUserId)).resolves.toMatchObject({ allowed: false, reason: "inbox_agent_not_allowed" }); + }); + it("enforces user-scoped cross-user inbox grants", async () => { const company = await createCompany(db, "InboxCrossUserScoped"); const actorAgent = await createAgent(db, company.id); diff --git a/server/src/__tests__/built-in-agents.test.ts b/server/src/__tests__/built-in-agents.test.ts index 69de71c730c..7a90b5b5ecd 100644 --- a/server/src/__tests__/built-in-agents.test.ts +++ b/server/src/__tests__/built-in-agents.test.ts @@ -611,9 +611,9 @@ describeEmbeddedPostgres("built-in agents", () => { expect(result.defaultGrantsEnsured).toBeGreaterThanOrEqual(4); const rootGrantKeys = await permissionKeysForAgent(root.id); - expect(rootGrantKeys).toEqual(expect.arrayContaining(["agents:configure", "skills:create"])); - expect(rootGrantKeys).not.toContain("agents:suggest-changes"); - expect(rootGrantKeys).not.toContain("skills:suggest-changes"); + expect(rootGrantKeys).toEqual(expect.arrayContaining([ + "agents:configure", "agents:suggest-changes", "skills:create", "skills:suggest-changes", + ])); const state = await builtInAgentService(db).get(companyId, "reflection-coach"); expect(state).toMatchObject({ diff --git a/server/src/__tests__/invite-join-grants.test.ts b/server/src/__tests__/invite-join-grants.test.ts index 427fef0fa63..9c10d2d6367 100644 --- a/server/src/__tests__/invite-join-grants.test.ts +++ b/server/src/__tests__/invite-join-grants.test.ts @@ -8,18 +8,20 @@ import { normalizeHumanRole, resolveHumanInviteRole, } from "../services/company-member-roles.js"; +import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "../services/agent-permissions.js"; + +const invitedAgentId = "agent-1"; +const defaultAgentGrants = NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({ + permissionKey, + scope: newStandardAgentGrantScope(permissionKey, invitedAgentId), +})); describe("agentJoinGrantsFromDefaults", () => { - it("adds tasks:assign when invite defaults do not specify agent grants", () => { - expect(agentJoinGrantsFromDefaults(null)).toEqual([ - { - permissionKey: "tasks:assign", - scope: null, - }, - ]); + it("adds all new-agent grants when invite defaults do not specify grants", () => { + expect(agentJoinGrantsFromDefaults(null, invitedAgentId)).toEqual(defaultAgentGrants); }); - it("preserves invite agent grants and appends tasks:assign", () => { + it("preserves invite agent grants and appends the missing defaults", () => { expect( agentJoinGrantsFromDefaults({ agent: { @@ -30,17 +32,8 @@ describe("agentJoinGrantsFromDefaults", () => { }, ], }, - }), - ).toEqual([ - { - permissionKey: "agents:create", - scope: null, - }, - { - permissionKey: "tasks:assign", - scope: null, - }, - ]); + }, invitedAgentId), + ).toEqual([{ permissionKey: "agents:create", scope: null }, ...defaultAgentGrants]); }); it("does not duplicate tasks:assign when invite defaults already include it", () => { @@ -54,12 +47,19 @@ describe("agentJoinGrantsFromDefaults", () => { }, ], }, - }), + }, invitedAgentId), ).toEqual([ - { - permissionKey: "tasks:assign", - scope: { projectId: "project-1" }, - }, + { permissionKey: "tasks:assign", scope: { projectId: "project-1" } }, + ...defaultAgentGrants.filter((grant) => grant.permissionKey !== "tasks:assign"), + ]); + }); + + it("preserves an explicit scoped agent configuration grant", () => { + expect(agentJoinGrantsFromDefaults({ + agent: { grants: [{ permissionKey: "agents:configure", scope: { agentIds: ["agent-1"] } }] }, + }, invitedAgentId)).toEqual([ + { permissionKey: "agents:configure", scope: { agentIds: ["agent-1"] } }, + ...defaultAgentGrants.filter((grant) => grant.permissionKey !== "agents:configure"), ]); }); }); diff --git a/server/src/__tests__/plugin-managed-agents.test.ts b/server/src/__tests__/plugin-managed-agents.test.ts index 0b06a551266..30a4725f470 100644 --- a/server/src/__tests__/plugin-managed-agents.test.ts +++ b/server/src/__tests__/plugin-managed-agents.test.ts @@ -17,6 +17,7 @@ import { pluginCompanySettings, pluginManagedResources, plugins, + principalPermissionGrants, } from "@paperclipai/db"; import type { PaperclipPluginManifestV1 } from "@paperclipai/shared"; import { @@ -106,6 +107,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => { await db.delete(pluginManagedResources); await db.delete(pluginCompanySettings); await db.delete(approvals); + await db.delete(principalPermissionGrants); await db.delete(agents); await db.delete(plugins); await db.delete(companies); diff --git a/server/src/__tests__/plugin-managed-routines.test.ts b/server/src/__tests__/plugin-managed-routines.test.ts index 25a02531c2e..e5c0a4d0f32 100644 --- a/server/src/__tests__/plugin-managed-routines.test.ts +++ b/server/src/__tests__/plugin-managed-routines.test.ts @@ -12,6 +12,7 @@ import { issues, pluginManagedResources, plugins, + principalPermissionGrants, projects, routineDocuments, routineRuns, @@ -121,6 +122,7 @@ describeEmbeddedPostgres("plugin-managed routines", () => { await db.delete(agentConfigRevisions); await db.delete(activityLog); await db.delete(pluginManagedResources); + await db.delete(principalPermissionGrants); await db.delete(agents); await db.delete(projects); await db.delete(plugins); diff --git a/server/src/routes/access.ts b/server/src/routes/access.ts index d35c4586d7b..3aaa1df32e2 100644 --- a/server/src/routes/access.ts +++ b/server/src/routes/access.ts @@ -93,7 +93,7 @@ import { normalizeHumanRole, resolveHumanInviteRole, } from "../services/company-member-roles.js"; -import { humanJoinGrantsFromDefaults } from "../services/invite-grants.js"; +import { agentJoinGrantsFromDefaults as standardAgentJoinGrantsFromDefaults, humanJoinGrantsFromDefaults } from "../services/invite-grants.js"; import { collapseDuplicatePendingHumanJoinRequests, findReusableHumanJoinRequest, @@ -2246,22 +2246,13 @@ function grantsFromDefaults( } export function agentJoinGrantsFromDefaults( - defaultsPayload: Record | null | undefined + defaultsPayload: Record | null | undefined, + agentId: string, ): Array<{ permissionKey: (typeof PERMISSION_KEYS)[number]; scope: Record | null; }> { - const grants = grantsFromDefaults(defaultsPayload, "agent"); - if (grants.some((grant) => grant.permissionKey === "tasks:assign")) { - return grants; - } - return [ - ...grants, - { - permissionKey: "tasks:assign", - scope: null - } - ]; + return standardAgentJoinGrantsFromDefaults(defaultsPayload, agentId); } type JoinRequestManagerCandidate = { @@ -4297,7 +4288,8 @@ export function accessRoutes( "active" ); const grants = agentJoinGrantsFromDefaults( - invite.defaultsPayload as Record | null + invite.defaultsPayload as Record | null, + created.id, ); await access.setPrincipalGrants( companyId, diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 6e4ce96fd2b..0f7e74bbee2 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -2914,6 +2914,69 @@ export function agentRoutes( ); } + function assertNoAgentProcessAdapterMutation(req: Request, adapterType: string, mutatesConfiguration: boolean) { + if (req.actor.type !== "agent" || adapterType !== "process" || !mutatesConfiguration) return; + throw forbidden("Agent keys cannot configure host-executed process adapters."); + } + + const LOCAL_ADAPTER_HOST_COMMAND_KEYS = [ + "command", + "hermesCommand", + "args", + "extraArgs", + "cwd", + "env", + "filesystemSandboxCommand", + ] as const; + + const LOCAL_ADAPTER_CREDENTIAL_ENV_KEYS: Record = { + ...INHERITABLE_AGENT_CREDENTIAL_ENV_KEYS, + gemini_local: ["GEMINI_API_KEY", "GOOGLE_API_KEY"], + kimi_local: ["KIMI_MODEL_API_KEY"], + opencode_local: ["PAPERCLIP_OPENCODE_PROVIDERS", "OPENCODE_AUTH_JSON"], + }; + const POOL_AUTH_OVERRIDE_ENV_KEYS = [ + "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "PAPERCLIP_OPENCODE_PROVIDERS", "OPENCODE_AUTH_JSON", + ] as const; + + async function callerUsesAiConnectionPool(req: Request, companyId: string): Promise { + if (req.actor.type !== "agent" || !req.actor.agentId) return false; + const caller = await svc.getById(req.actor.agentId); + if (!caller || caller.companyId !== companyId) return false; + return asRecord(asRecord(caller.runtimeConfig)?.aiConnection)?.mode === "router"; + } + + function containsOnlyLocalAdapterCredentialRefs( + adapterType: string, + env: unknown, + allowPlainCredentials: boolean, + ): boolean { + const envRecord = asRecord(env); + if (!envRecord) return false; + const allowedKeys = LOCAL_ADAPTER_CREDENTIAL_ENV_KEYS[adapterType] ?? []; + return Object.entries(envRecord).every(([key, value]) => + (allowedKeys.includes(key) && isInheritableCredentialReference(value)) || + (allowPlainCredentials && POOL_AUTH_OVERRIDE_ENV_KEYS.includes(key as typeof POOL_AUTH_OVERRIDE_ENV_KEYS[number]) && asEnvBindingString(value) !== null), + ); + } + + function assertNoAgentLocalAdapterHostCommandMutation( + req: Request, + adapterType: string, + adapterConfig: Record, + allowPlainCredentials = false, + ) { + if (req.actor.type !== "agent" || !adapterType.endsWith("_local")) return; + const changedKeys = LOCAL_ADAPTER_HOST_COMMAND_KEYS.filter((key) => + adapterConfig[key] !== undefined && + (key !== "env" || !containsOnlyLocalAdapterCredentialRefs(adapterType, adapterConfig.env, allowPlainCredentials)), + ); + if (changedKeys.length === 0) return; + throw forbidden( + `Agent keys cannot configure host-executed local adapter settings (${changedKeys.join(", ")}).`, + ); + } + function summarizeAgentUpdateDetails(patch: Record) { const changedTopLevelKeys = Object.keys(patch).sort(); const details: Record = { changedTopLevelKeys }; @@ -4419,6 +4482,13 @@ export function agentRoutes( await assertSelectableAdapterType(rollbackAdapterType); } const rollbackAdapterConfig = asRecord(rollbackConfig.adapterConfig) ?? {}; + assertNoAgentAdapterConfigMutation(req, rollbackAdapterConfig); + assertNoAgentLocalAdapterHostCommandMutation(req, rollbackAdapterType, rollbackAdapterConfig); + assertNoAgentProcessAdapterMutation( + req, + rollbackAdapterType, + true, + ); assertExternalInstructionsAdmin(req, existing); assertExternalInstructionsAdmin(req, { ...existing, @@ -4581,6 +4651,8 @@ export function agentRoutes( rawHireAdapterConfig, ); assertNoAgentAdapterConfigMutation(req, rawHireAdapterConfig); + assertNoAgentLocalAdapterHostCommandMutation(req, hireInput.adapterType, rawHireAdapterConfig, await callerUsesAiConnectionPool(req, companyId)); + assertNoAgentProcessAdapterMutation(req, hireInput.adapterType, Object.keys(rawHireAdapterConfig).length > 0); const hiredAgentId = randomUUID(); const authInheritance = await applyHiringAgentAuthInheritance( req, @@ -4890,6 +4962,8 @@ export function agentRoutes( rawCreateAdapterConfig, ); assertNoAgentAdapterConfigMutation(req, rawCreateAdapterConfig); + assertNoAgentLocalAdapterHostCommandMutation(req, createInput.adapterType, rawCreateAdapterConfig, await callerUsesAiConnectionPool(req, companyId)); + assertNoAgentProcessAdapterMutation(req, createInput.adapterType, Object.keys(rawCreateAdapterConfig).length > 0); const agentId = randomUUID(); const requestedAdapterConfig = applyCodexLocalKeyIsolation( companyId, @@ -5528,6 +5602,7 @@ export function agentRoutes( const touchesAdapterConfiguration = hasOwn(patchData, "adapterType") || hasOwn(patchData, "adapterConfig"); + assertNoAgentProcessAdapterMutation(req, requestedAdapterType, touchesAdapterConfiguration); if (touchesAdapterConfiguration) { assertExternalInstructionsAdmin(req, existing); const existingAdapterConfig = asRecord(existing.adapterConfig) ?? {}; @@ -5575,6 +5650,13 @@ export function agentRoutes( if (requestedAdapterType === "paperclip_runner") { rawEffectiveAdapterConfig = normalizePaperclipRunnerAdapterConfig(requestedAdapterType, rawEffectiveAdapterConfig); } + if (changingAdapterType || requestedAdapterConfig) { + assertNoAgentLocalAdapterHostCommandMutation( + req, + requestedAdapterType, + changingAdapterType ? rawEffectiveAdapterConfig : (requestedAdapterConfig ?? {}), + ); + } const existingRunnerProvider = existing.adapterType === "paperclip_runner" ? existingAdapterConfig.provider diff --git a/server/src/services/agent-permissions.ts b/server/src/services/agent-permissions.ts index e628a62ec52..24f9bc29d05 100644 --- a/server/src/services/agent-permissions.ts +++ b/server/src/services/agent-permissions.ts @@ -1,4 +1,31 @@ -import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared"; +import { LOW_TRUST_REVIEW_PRESET, type PermissionKey } from "@paperclipai/shared"; + +/** Direct grants for newly activated standard agents. Existing agents are not backfilled. */ +export const NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS = [ + "agents:configure", + "agents:suggest-changes", + "skills:create", + "skills:suggest-changes", + "tools:manage_connections", + "tools:manage_profiles", + "tools:view_audit", + "audit:view_agent_actions", + "tools:use", + "tools:manage_runtime", + "inbox:manage", + "tasks:assign", + "tasks:assign_scope", + "tasks:manage_active_checkouts", +] as const satisfies readonly PermissionKey[]; + +export function newStandardAgentGrantScope( + permissionKey: PermissionKey, + agentId: string, +): Record | null { + if (permissionKey === "tasks:assign_scope") return { subtreeRootAgentId: agentId }; + if (permissionKey === "inbox:manage") return { responsibleUserOnly: true }; + return null; +} export type NormalizedAgentPermissions = Record & { canCreateAgents: boolean; diff --git a/server/src/services/agents.ts b/server/src/services/agents.ts index 3640a90d4e7..13450be91f0 100644 --- a/server/src/services/agents.ts +++ b/server/src/services/agents.ts @@ -17,6 +17,7 @@ import { issueExecutionDecisions, issues, issueComments, + principalPermissionGrants, } from "@paperclipai/db"; import { AGENT_DEFAULT_MAX_CONCURRENT_RUNS, @@ -38,8 +39,8 @@ import { syncAgentAdapterEnvBindings, } from "./agent-secret-bindings.js"; import { logActivity } from "./activity-log.js"; +import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope, normalizeAgentPermissions, permissionsImplyLowTrust } from "./agent-permissions.js"; import { recordAgentStatusEvent, recordResourceCreationEvent } from "./resource-lifecycle-events.js"; -import { normalizeAgentPermissions } from "./agent-permissions.js"; import { REDACTED_EVENT_VALUE, sanitizeRecord } from "../redaction.js"; import { assertClaudeOAuthBindingInvariant, @@ -944,6 +945,20 @@ export function agentService(db: Db) { }) .returning() .then((rows) => rows[0]); + // New standard agents receive the standard direct grants at activation. + // Low-trust and bundled agents keep their explicit, narrower grants. + if (created.status !== "pending_approval" && !permissionsImplyLowTrust(normalizedPermissions) && + !readBuiltInAgentMarker(created.metadata)) { + await tx.insert(principalPermissionGrants).values( + NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({ + companyId, + principalType: "agent" as const, + principalId: created.id, + permissionKey, + scope: newStandardAgentGrantScope(permissionKey, created.id), + })), + ).onConflictDoNothing(); + } if (options?.aiConnectionInstall) { const install = options.aiConnectionInstall; const connectionIds = [...new Set([install.connectionId, ...(install.memberConnectionIds ?? [])])]; @@ -1084,6 +1099,11 @@ export function agentService(db: Db) { await tx.delete(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, id)); await tx.delete(agentApiKeys).where(eq(agentApiKeys.agentId, id)); await tx.delete(agentRuntimeState).where(eq(agentRuntimeState.agentId, id)); + await tx.delete(principalPermissionGrants).where(and( + eq(principalPermissionGrants.companyId, existing.companyId), + eq(principalPermissionGrants.principalType, "agent"), + eq(principalPermissionGrants.principalId, id), + )); const deleted = await tx .delete(agents) .where(eq(agents.id, id)) @@ -1151,6 +1171,17 @@ export function agentService(db: Db) { }); } await syncAgentSecretBindings(updated, txDb, existing.adapterConfig); + if (!permissionsImplyLowTrust(updated.permissions) && !readBuiltInAgentMarker(updated.metadata)) { + await tx.insert(principalPermissionGrants).values( + NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({ + companyId: updated.companyId, + principalType: "agent" as const, + principalId: updated.id, + permissionKey, + scope: newStandardAgentGrantScope(permissionKey, updated.id), + })), + ).onConflictDoNothing(); + } await recordResourceCreationEvent(txDb, existing.companyId, "agent", updated.id); const agent = await agentService(txDb).getById(updated.id); if (!agent) { diff --git a/server/src/services/authorization.ts b/server/src/services/authorization.ts index d16e9f30dc6..e3edf7a99fb 100644 --- a/server/src/services/authorization.ts +++ b/server/src/services/authorization.ts @@ -2060,7 +2060,8 @@ export function authorizationService(db: Db | DbTransaction) { // implicit default-open policy remains responsible-user-only so an // absent row never becomes a company-wide cross-user grant. const grant = await findGrant(companyId, "agent", actorAgentId, "inbox:manage"); - if (grant && (await scopeAllows(db, companyId, grant.scope, { userId: targetUserId }))) { + if (grant && grant.scope?.responsibleUserOnly !== true && + (await scopeAllows(db, companyId, grant.scope, { userId: targetUserId }))) { return allow({ action: input.action, reason: "allow_explicit_grant", diff --git a/server/src/services/invite-grants.ts b/server/src/services/invite-grants.ts index 32c9aa42fe1..b2141e09305 100644 --- a/server/src/services/invite-grants.ts +++ b/server/src/services/invite-grants.ts @@ -1,5 +1,6 @@ import { PERMISSION_KEYS } from "@paperclipai/shared"; import type { HumanCompanyMembershipRole } from "@paperclipai/shared"; +import { NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS, newStandardAgentGrantScope } from "./agent-permissions.js"; import { grantsForHumanRole } from "./company-member-roles.js"; export function grantsFromDefaults( @@ -38,22 +39,21 @@ export function grantsFromDefaults( } export function agentJoinGrantsFromDefaults( - defaultsPayload: Record | null | undefined + defaultsPayload: Record | null | undefined, + agentId: string, ): Array<{ permissionKey: (typeof PERMISSION_KEYS)[number]; scope: Record | null; }> { const grants = grantsFromDefaults(defaultsPayload, "agent"); - if (grants.some((grant) => grant.permissionKey === "tasks:assign")) { - return grants; + // Invitation approval replaces the whole grant set after agent creation. + // Retain new-agent defaults, but never widen an explicitly scoped grant. + for (const permissionKey of NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS) { + if (!grants.some((grant) => grant.permissionKey === permissionKey)) { + grants.push({ permissionKey, scope: newStandardAgentGrantScope(permissionKey, agentId) }); + } } - return [ - ...grants, - { - permissionKey: "tasks:assign", - scope: null, - }, - ]; + return grants; } export function humanJoinGrantsFromDefaults(