Files
PaperClipAI/server/src/__tests__/plugin-access-authorization-host-services.test.ts
T
DottaandPaperclip 6ffe9df842 fix(auth): clarify protected-agent assignment blocks (#10893)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task assignment policies control which agents can receive work.
> - Protected-agent policy flags currently stop assignment.
> - The existing error says that the assignment requires approval.
> - Paperclip has no approval workflow for this policy.
> - This pull request models the policy as a hard block and gives the
operator an action that exists.
> - The benefit is accurate API guidance without weakening the existing
fail-closed behavior.

## Linked Issues or Issue Description

Refs #6386

**What happened?**

A protected-agent assignment denial said that approval was required. No
approval record or approval action existed for this policy, so the
message sent agents and operators to a dead end.

**Expected behavior**

The authorization result must state that protected-agent policy blocks
assignment. It must tell a company administrator to remove the block
before retrying.

**Steps to reproduce**

1. Set `authorizationPolicy.protectedAgent.requiresApproval` to `true`
on a target agent.
2. Give another agent the `tasks:assign` permission.
3. Preview or attempt assignment to the protected agent.
4. Observe that the old response promises an approval step that does not
exist.

**Paperclip version or commit**

`c54936e2e9` on `master`.

**Deployment mode**

Built from source. The behavior is in the core authorization service and
is not deployment-specific.

**Agent adapter(s) involved**

Not adapter-specific.

## What Changed

- Added canonical `protectedAgent.blockAssignment` and
`protectedAgent.blockReason` policy fields.
- Kept the legacy approval-named flags as fail-closed compatibility
aliases.
- Changed denial copy to name the hard block and the administrator
action.
- Added authorization and plugin-host regression coverage for canonical
and legacy policy data.
- Updated the V1 implementation contract with the protected-assignment
rule.

## Verification

- `pnpm exec vitest run
server/src/__tests__/authorization-service.test.ts
server/src/__tests__/plugin-access-authorization-host-services.test.ts`
— 2 files passed, 61 tests passed.
- `pnpm --filter @paperclipai/shared typecheck` — passed.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/server build` — passed.
- `pnpm check:token-gates` — all gates clean.
- `git diff --check public-gh/master...HEAD` — passed.

The repository-wide local wrappers exceeded the execution host resource
limit before they printed a final summary. The PR check loop will use
GitHub CI as the complete test and build authority.

## Risks

- Low: assignment remains fail-closed. The change corrects the policy
name and denial guidance.
- Low: legacy fields remain supported, so existing plugin-owned policy
data does not change behavior.
- Low: the new policy schemas allow unknown keys for forward
compatibility, as the existing authorization policy schema already does.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex, exact model ID `gpt-5`, tool-enabled coding agent with
reasoning, shell, Git, and GitHub CLI access. The runtime does not
expose the context-window size.

## 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>
2026-08-05 10:09:17 -05:00

325 lines
10 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog,
agents,
companies,
companyMemberships,
createDb,
invites,
principalPermissionGrants,
} from "@paperclipai/db";
import { buildHostServices } from "../services/plugin-host-services.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
const pluginId = "plugin-record-id";
function createEventBusStub() {
return {
forPlugin() {
return {
emit: vi.fn(),
subscribe: vi.fn(),
clear: vi.fn(),
};
},
} as any;
}
async function createCompany(db: ReturnType<typeof createDb>, prefix: string) {
return db
.insert(companies)
.values({
name: `${prefix} ${randomUUID()}`,
issuePrefix: `${prefix}${randomUUID().slice(0, 6).toUpperCase()}`,
})
.returning()
.then((rows) => rows[0]!);
}
describeEmbeddedPostgres("plugin access and authorization host services", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plugin-access-authz-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(principalPermissionGrants);
await db.delete(invites);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
it("rejects grant writes for principals outside the requested company", async () => {
const targetCompany = await createCompany(db, "PAX");
const otherCompany = await createCompany(db, "PAY");
const otherAgent = await db
.insert(agents)
.values({
companyId: otherCompany.id,
name: "Other agent",
role: "engineer",
adapterType: "process",
adapterConfig: {},
permissions: {},
})
.returning()
.then((rows) => rows[0]!);
const services = buildHostServices(db, pluginId, "permissions-extension", createEventBusStub());
await expect(
services.authorization.setGrants({
companyId: targetCompany.id,
principalType: "agent",
principalId: otherAgent.id,
grants: [{ permissionKey: "tasks:assign" }],
}),
).rejects.toThrow("Agent not found");
const rows = await db.select().from(principalPermissionGrants);
expect(rows).toEqual([]);
services.dispose();
});
it("redacts invite token hashes and sensitive defaults from plugin invite reads", async () => {
const company = await createCompany(db, "PAZ");
const services = buildHostServices(db, pluginId, "permissions-extension", createEventBusStub());
const created = await services.access.createInvite({
companyId: company.id,
allowedJoinTypes: "human",
defaultsPayload: {
human: { role: "operator", apiKey: "secret-value" },
secret: "top-secret",
},
});
expect(created.token).toMatch(/^pcp_invite_/);
expect("tokenHash" in created).toBe(false);
expect(created.defaultsPayload).toMatchObject({
human: { role: "operator", apiKey: "***REDACTED***" },
secret: "***REDACTED***",
});
const listed = await services.access.listInvites({ companyId: company.id });
expect(listed.invites).toHaveLength(1);
expect("token" in listed.invites[0]!).toBe(false);
expect("tokenHash" in listed.invites[0]!).toBe(false);
services.dispose();
});
it("filters authorization audit entries by allow or deny decision details", async () => {
const company = await createCompany(db, "PAU");
const services = buildHostServices(db, pluginId, "permissions-extension", createEventBusStub());
await db.insert(activityLog).values([
{
companyId: company.id,
actorType: "agent",
actorId: "agent-1",
action: "authorization.assignment_preview",
entityType: "issue",
entityId: "issue-1",
details: { decision: "allow", secret: "do-not-leak" },
createdAt: new Date("2026-01-02T00:00:00Z"),
},
{
companyId: company.id,
actorType: "agent",
actorId: "agent-1",
action: "authorization.assignment_preview",
entityType: "issue",
entityId: "issue-2",
details: { reason: "deny_scope" },
createdAt: new Date("2026-01-03T00:00:00Z"),
},
]);
const [allowed, denied] = await Promise.all([
services.authorization.searchAudit({
companyId: company.id,
action: "authorization.assignment_preview",
decision: "allow",
limit: 1,
}),
services.authorization.searchAudit({
companyId: company.id,
action: "authorization.assignment_preview",
decision: "deny",
}),
]);
expect(allowed).toHaveLength(1);
expect(allowed[0]!.entityId).toBe("issue-1");
expect(allowed[0]!.details).toMatchObject({ decision: "allow", secret: "***REDACTED***" });
expect(denied).toHaveLength(1);
expect(denied[0]!.entityId).toBe("issue-2");
services.dispose();
});
it("uses persisted agent policy for plugin assignment preview and explanation", async () => {
const company = await createCompany(db, "PAP");
const [actorAgent, targetAgent] = await db
.insert(agents)
.values([
{
companyId: company.id,
name: "Actor agent",
role: "engineer",
adapterType: "process",
adapterConfig: {},
permissions: {},
},
{
companyId: company.id,
name: "Protected target",
role: "engineer",
adapterType: "process",
adapterConfig: {},
permissions: {},
},
])
.returning();
await db.insert(companyMemberships).values({
companyId: company.id,
principalType: "agent",
principalId: actorAgent!.id,
status: "active",
membershipRole: "member",
});
const services = buildHostServices(db, pluginId, "permissions-extension", createEventBusStub());
const updatedPolicy = await services.authorization.updatePolicy({
companyId: company.id,
resourceType: "agent",
resourceId: targetAgent!.id,
policy: {
assignmentPolicy: {
mode: "protected",
},
protectedAgent: {
blockAssignment: true,
blockReason: "Protected assignment",
},
managedBy: "permissions-extension",
},
});
const input = {
companyId: company.id,
actor: {
type: "agent" as const,
agentId: actorAgent!.id,
companyId: company.id,
source: "agent_key" as const,
},
target: { assigneeAgentId: targetAgent!.id },
};
const [policy, preview, explanation] = await Promise.all([
Promise.resolve(updatedPolicy),
services.authorization.previewAssignment(input),
services.authorization.explainAssignment(input),
]);
expect(policy.policy).toMatchObject({
protectedAgent: { blockAssignment: true },
});
expect(preview).toMatchObject({
allowed: false,
reason: "deny_policy_restricted",
});
expect(preview.explanation).toContain("assignment is blocked");
expect(preview.explanation).toContain("company administrator");
expect(preview.explanation).not.toContain("approval");
expect(explanation).toMatchObject(preview);
const injectedBoardPreview = await services.authorization.previewAssignment({
companyId: company.id,
actor: {
type: "board",
userId: "operator",
companyIds: [company.id],
source: "local_implicit",
isInstanceAdmin: true,
} as any,
target: { assigneeAgentId: targetAgent!.id },
});
expect(injectedBoardPreview).toMatchObject({
allowed: false,
reason: "deny_policy_restricted",
});
services.dispose();
});
it("sanitizes plugin authorization policy updates and records audit activity", async () => {
const company = await createCompany(db, "PAS");
const targetAgent = await db
.insert(agents)
.values({
companyId: company.id,
name: "Policy target",
role: "engineer",
adapterType: "process",
adapterConfig: {},
permissions: {},
})
.returning()
.then((rows) => rows[0]!);
const services = buildHostServices(db, pluginId, "permissions-extension", createEventBusStub());
const updatedPolicy = await services.authorization.updatePolicy({
companyId: company.id,
resourceType: "agent",
resourceId: targetAgent.id,
policy: {
assignmentPolicy: { mode: "protected" },
apiKey: "sk-test-secret",
nested: {
authorization: "Bearer should-not-persist",
safeLabel: "kept",
},
},
});
expect(updatedPolicy.policy).toMatchObject({
assignmentPolicy: { mode: "protected" },
apiKey: "***REDACTED***",
nested: {
authorization: "***REDACTED***",
safeLabel: "kept",
},
});
const rows = await db.select().from(activityLog);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
companyId: company.id,
actorType: "plugin",
actorId: pluginId,
action: "authorization.policy_updated_by_plugin",
entityType: "agent",
entityId: targetAgent.id,
});
expect(rows[0]!.details).toMatchObject({
hasPolicy: true,
sourcePluginId: pluginId,
sourcePluginKey: "permissions-extension",
});
expect(JSON.stringify(rows[0]!.details)).not.toContain("sk-test-secret");
expect(JSON.stringify(rows[0]!.details)).not.toContain("should-not-persist");
services.dispose();
});
});