fix(agents): grant configuration access by default (#15283)

## 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 <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-06 05:28:48 -05:00
1 parent f858207161
commit a1ab55a56d
19 files changed
+744 -66

No files matched your search

@@ -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<typeof createDb>;
let cleanup: (() => Promise<void>) | 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<string, unknown> = {}, metadata?: Record<string, unknown>) =>
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));
});
});
@@ -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<string, unknown>)[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 () => {
@@ -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",
@@ -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);
@@ -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);
@@ -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);
@@ -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);
+3 -3
View File
@@ -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({
+24 -24
View File
@@ -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"),
]);
});
});
@@ -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);
@@ -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);
+6 -14
View File
@@ -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<string, unknown> | null | undefined
defaultsPayload: Record<string, unknown> | null | undefined,
agentId: string,
): Array<{
permissionKey: (typeof PERMISSION_KEYS)[number];
scope: Record<string, unknown> | 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<string, unknown> | null
invite.defaultsPayload as Record<string, unknown> | null,
created.id,
);
await access.setPrincipalGrants(
companyId,
+82
View File
@@ -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<string, readonly string[]> = {
...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<boolean> {
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<string, unknown>,
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<string, unknown>) {
const changedTopLevelKeys = Object.keys(patch).sort();
const details: Record<string, unknown> = { 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
+28 -1
View File
@@ -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<string, unknown> | null {
if (permissionKey === "tasks:assign_scope") return { subtreeRootAgentId: agentId };
if (permissionKey === "inbox:manage") return { responsibleUserOnly: true };
return null;
}
export type NormalizedAgentPermissions = Record<string, unknown> & {
canCreateAgents: boolean;
+32 -1
View File
@@ -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) {
+2 -1
View File
@@ -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",
+10 -10
View File
@@ -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<string, unknown> | null | undefined
defaultsPayload: Record<string, unknown> | null | undefined,
agentId: string,
): Array<{
permissionKey: (typeof PERMISSION_KEYS)[number];
scope: Record<string, unknown> | 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(